FHEM is mainly used for home automation, but it is suitable for other tasks
too, where notification, timers and logging plays an important role.
It supports different hardware devices to interface with certain protocols
(e.g. FHZ1000PC to interface FS20 and HMS, CM11 to access X10), and logical
devices like FS20 or FHT to digest the messages for a certain device type using
this protocol.
FHEM is modular. The different devices are represented through modules which
implement certain functions (e.g. define, get, set). Even seemingly integral
parts of FHEM like triggers (notify) and timers (at) are implemented this way, giving the possibility to
replace/extend this functionality.
FHEM is controlled through readable / ascii commands, which are specified in
files (e.g. the configuration file), or issued over a TCP/IP connection, either
directly in a telnet session, with a fhem.pl in client mode or from one of the
web frontends.
When starting the server you have to specify a configuration file:
perl fhem.pl fhem.cfg
A reasonable minimal configuration file looks like:
attr global logfile log/fhem.log
attr global modpath .
attr global statefile log/fhem.save
define telnetPort telnet 7072 global
define WEB FHEMWEB 8083 global
Note: the last two lines are optional and assume you wish to use the
builtin telnet and WEB interface.
The web interface can be reached at
http://<fhemhost>:8083
TCP/IP communication with FHEM can either happen in a "session" (via
telnet) or single client command (via fhem.pl). Example:
If a OS-user called fhem exists, and FHEM is started as root, FHEM will
automatically change to to this user via setuid.
If FHEM is started with the -d option (perl fhem.pl -d fhem.cfg), then the
verbose level is set to 5 and the logfile is redirected to the STDOUT.
The environment variable FHEM_GLOBALATTR is evaluated: it consists of space
separated name=value pairs, where name is a global attribute. Values from this
source override values set in the configuration file.
There are three types of commands: "FHEM" commands (described in this
document), shell commands (they must be enclosed in double quotes ") and perl
expressions (enclosed in curly brackets {}). shell commands or perl expressions
are needed for complex at or notify
arguments, but can also issued as a "normal" command.
E.g. the following three commands all do the same when issued from a telnet
prompt:
set lamp off
"fhem.pl 7072 "set lamp off""
{fhem("set lamp off")}
Shell commands will be executed in the background, perl expressions and
FHEM commands will be executed in the main "thread". In order to make perl
expressions easier to write, some special functions and variables are
available. See the section Perl special for a description.
To trigger FHEM commands from a shell script (this is the "other way round"),
use the client form of fhem.pl (described above).
Multiple FHEM commands are separated by semicolon (;). In order to use semicolon
in perl code or shell programs, they have to be escaped by the double semicolon
(;;). See the Notes section of the notify
chapter on command parameters and escape rules.
E.g. the following first command switches Lamp1 off at 07:00 and Lamp2
immediately (at the point of definition), the second one switches both lamps
off at 07:00.
define lampoff at 07:00 set Lamp1 off; set Lamp2 off
define lampoff at 07:00 set Lamp1 off;; set Lamp2 off
For every further indirection you need to double the semicolons:, e.g. to
switch on every day 2 devices at 7:00 for 10 minutes you have to write:
define onAt at 07:00 set Lamp1 on;;set Lamp2 on;; define offAt at +00:10 set Lamp1 off;;;;set Lamp2 off
Don't dispair, the previous example can also be written as
define onAt at 07:00 set Lamp1,Lamp2 on-for-timer 600
Commands can be either typed in plain, or read from a file (e.g. the
configuration file at startup). The commands are either executed directly, or
later if they are arguments to the at and notify FHEM commands.
A line ending with \ will be concatenated with the next one, so long lines
(e.g. multiple perl commands) can be split in multiple lines. Some web fronteds
(e.g. webpgm2) make editing of multiline commands transparent for you (i.e. there is no need for \) .
Note: mixing command types (FHEM/shell/perl) on one line is not supported, even
if it might work in some cases.
a single device name. This is the most common case.
a list of devices, separated by comma (,)
a regular expression
a NAME=VALUE pair, where NAME can be an internal value like TYPE, a
Reading-Name or an attribute. VALUE is a regexp. To negate the
comparison, use NAME!=VALUE. To restrict the search, use i: as prefix
for internal values, r: for readings and a: for attributes.
See the example below.
Case sensitivity is being ignored using ~ or !~.
if the spec is followed by the expression :FILTER=NAME=VALUE, then the
values found in the first round are filtered by the second expression.
Examples:
set lamp1 on set lamp1,lamp2,lamp3 on set lamp.* on set room=kitchen off set room=kitchen:FILTER=STATE=on off set room=kitchen:FILTER=STATE!=off off list disabled= list room~office list TYPE=FS20 STATE list i:TYPE=FS20 STATE
Notes:
the spec may not contain space characters.
if there is a device which exactly corresponds to the spec, then
no special processing is done.
first the spec is separated by comma, then the regular expression and
filter operations are executed.
the returned list can contain the same device more than once, so
"set lamp3,lamp3 on" switches lamp3 twice.
for more complex structuring demands see the
structure device.
All devices have attributes. These can be set by means of the attr command, displayed with the displayattr command, and deleted by the deleteattr command.
There are global attributes that are used by all devices and local attributes
that apply to individual device classes only.
Some devices (like FHEMWEB) automatically define new
global attributes on the first definition of a device of such type.
You can use the command
attr global userattr
<attributelist>
for the global device to
declare new global attributes and
attr <devicespec> userattr
<attributelist>
for individual devices according to devspec to declare new local attributes.
<attributelist> is a space-separated list which contains the
names of the additional attributes. See the documentation of the attr command for examples.
Be careful not to overwrite additional global attributes previously defined by
yourself or a device. Use the attr global userattr
<attributelist> as early in your configuration as possible.
Device specific attributes
Device specific attributes are documented in the corresponding device section.
Global attributes used by all devices
alias
Used by FHEMWEB to display a device with another name e.g. when using
special characters/spaces not accepted by device definition.
comment
Add an arbitrary comment.
eventMap
Replace event names and set arguments. The value of this attribute
consists of a list of space separated values, each value is a colon
separated pair. The first part specifies the "old" value, the second
the new/desired value. If the first character is slash(/) or comma(,)
then split not by space but by this character, enabling to embed spaces.
You can specify a widgetOverride after an additional colon (e.g.
on-for-timer:OnFor:texField), the default widget is :noArg to avoid
extra input fields in cmdList.
Examples:
attr store eventMap on:open off:closed
attr store eventMap /on-for-timer 10:open/off:closed/
set store open
The explicit variant of this attribute has the following syntax:
attr store eventMap { dev=>{'on'=>'open'}, usr=>{'open'=>'on'} }
attr store eventMap { dev=>{'^on(-for-timer)?(.*)'=>'open$2'},
usr=>{'^open(.*)'=>'on$1'},
fw=>{'^open(.*)'=>'open'} }
This variant must be used, if the mapping is not symmetrical, the first
part (dev) representing the device to user mapping, i.e. if the device
reports on 100 or on-for-timer 100, the user will see open 100. The
second part (usr) is the other direction, if the user specified open
10, the device will receive on 10. On both occasions the key will be
first compared directly with the text, and if it is not equal, then it
will be tried to match it as a regexp. When using regexps in the usr
part with wildcards, the fw part must be filled with the exact same
keys to enable a correct display in the FHEMWEB set dropdown list in
the detail view.
genericDisplayType
used by some frontends (but not FHEMWEB) to offer a default image or
appropriate commands for this device. Currently the following values
are supported: switch,outlet,light,blind,speaker,thermostat
group
Group devices. Recognized by web-pgm2 (module FHEMWEB), it makes
devices in the same group appear in the same box).
This is used to further group
devices together. A device can appear in more than one group, in this
case the groups have to be specified comma-separated.
If this attribute is not set then the device type is used as the
grouping attribute.
overrideNotifydev
if set (the argument is a devspec), the optimization for notifications
is using this value instead of the module-set NOTIFYDEV internal.
Use it only, if you know it better than the module maintainer.
In order to be available, the global or the device userattr must be set
first, to include it.
room
Filter/group devices in frontends. A device can appear in more than one
room, in this case the rooms have to be specified comma-separated.
Devices in the room hidden will not appear in the web output, or set
the FHEMWEB attribute hiddenroom to
selectively disable rooms for certain FHEMWEB instances.
The -> string is considered as a structure separator for rooms, e.g.
"1st. floor->Master bedroom".
suppressReading
Used to eliminate unwanted readings. The value is a regular expression,
with ^ and $ added. Only necessary in exceptional cases.
showtime
Used in the webfrontend pgm2 to show the time of last activity
instead of the state in the summary view. Useful e.g. for FS20 PIRI
devices.
verbose
Set the verbosity level. Possible values:
0 - server start/stop
1 - error messages or unknown packets
2 - major events/alarms.
3 - commands sent out will be logged.
4 - you'll see whats received by the different devices.
5 - debugging.
The value for the global device is a default for
other devices without own verbose attribute set.
readingFnAttributes
The following global attributes are honored by the modules that make use of the
standardized readings updating mechanism in fhem.pl. Check the module's
attribute list if you want to know if a device supports these attributes.
stateFormat
Modifies the STATE of the device, shown by the list command or in the room
overview in FHEMWEB. If not set, its value is taken from the state reading.
If set, then every word in the argument is replaced by the value of the
reading if such a reading for the current device exists. If the value of
this attribute is enclosed in {}, then it is evaluated. This attribute is
evaluated each time a reading is updated.
The "set magic" described here is also applied.
Note: some FHEM modules are setting STATE directly (against the guidelines),
in this case the attribute may not work as expected.
event-on-update-reading
If not set, every update of any reading creates an event, which e.g. is
handled by notify or FileLog.
The attribute takes a comma-separated list of readings. You may use regular
expressions in that list. If set, only updates of the listed readings
create events.
event-on-change-reading
The attribute takes a comma-separated list of readings. You may use regular
expressions in that list. If set, only changes of the listed readings
create events. In other words, if a reading listed here is updated with the
new value identical to the old value, no event is created. If an optional [:threshold]
is given after a reading name events are only generated if the change is >= threshold.
The precedence of event-on-update-reading and event-on-change-reading is as
follows:
If both attributes are not set, any update of any reading of the device
creates an event.
If any of the attributes is set, no events occur for updates or changes
of readings not listed in any of the attributes.
If a reading is listed in event-on-update-reading, an update of the
reading creates an event no matter whether the reading is also listed
in event-on-change-reading.
timestamp-on-change-reading
The attribute takes a comma-separated list of readings. You may use regular
expressions in that list. If set, the listed readings will not be changed
(or created) if event-on-change-reading is also set and it would not create
an event for this reading.
event-aggregator
The primary uses of this attribute are to calculate (time-weighted) averages of
readings over time periods and to throttle the update rate of readings and thus
the amount of data written to the logs.
This attribute takes a comma-separated list of reading:interval:method:function:holdTime
quintuples. You may use regular expressions for reading. If set, updates for the
listed readings are ignored and associated events are suppressed for a black-out period of at
least interval seconds (downsampling). After the black-out period has expired, the reading is
updated with a value that is calculated from the values and timestamps of the previously ignored
updates within the black-out period as follows:
function
description
v
the last value encountered
v0
the first value encountered
min
the smallest value encountered
max
the largest value encountered
mean
the arithmetic mean of all values
sd
the standard deviation from the mean
median
the median of all values (requires holdTime and method none)
integral
the arithmetic sum (if not time-weighted) or integral area (if time-weighted) of all values
n
number of samples
t
timestamp of the last value
t0
timestamp of the first value
If method is none, then that's all there is. If method
is const or linear, the time-weighted series of values is taken into
account instead. The weight is the timespan between two subsequent updates.
With the const method, the value is the value of the reading at the beginning of
the timespan; with the linear method, the value is the arithmetic average of
the values at the beginning and the end of the timespan.
Rollovers of black-out periods are handled as one would expect it.
One would typically use the linear method with the mean function for
quantities continuously varying over time like electric power consumption, temperature or speed.
For cumulative quantities like energy consumed, rain fallen or distance covered,
the none method with the v function is used. The constant
method is for discrete quantities that stay constant until the corresponding reading is updated,
e.g. counters, switches and the like.
If the holdTime in seconds is defined, the samples will be kept in memory allowing
the calculation of floating statistics instead of blocked statistics. With holdTime
defined the interval can be kept undefined so that the readings update rate is unchanged
or it can be set to a value less then holdTime for downsampling as described above
with a full history of the readings in memory. Note that the historic samples are not persistent
and will be lost when restarting FHEM.
The event aggregator only takes into consideration those updates that remain after preprocessing
according to the event-on-update-reading and event-on-change-reading
directives. Besides which, any update of a reading that occurs within a timespan from the preceding
update that is smaller than the resolution of FHEM's time granularity is ditched.
When more than one function should be calculated for the same reading, the original reading must be
multiplied (e.g. by using a notify) before applying the event-aggregator to the derived readings.
event-min-interval
This attribute takes a comma-separated list of reading:minInterval pairs.
You may use regular expressions for reading. Events will only be
generated, if at least minInterval seconds elapsed since the last reading
of the matched type. If event-on-change-reading is also specified, they are
combined with OR: if one of them is true, the event is generated.
oldreadings
This attribute takes a comma-separated list of readings. You may use
regular expressions in that list. For each reading in the list FHEM will
internaly store the previous value if the readings value changes. To access
the storead value use the OldReadings.* functions.
If the previous value is always to be stored (even if it didn't changed),
then set the last value of the comma-separated list to oldreadingsAlways.
userReadings
A comma-separated list of definitions of user-defined readings. Each
definition has the form:
After a single or bulk readings update, the user-defined readings are set
by evaluating the perl code { <perl code>
} for all definitions and setting the value of the respective
user-defined reading <reading> to the result. If
<trigger> is given, then all processing for this specific user
reading is only done if one of the just updated "reading: value"
combinations matches <trigger>, which is treated as a regexp.
Examples:
none: the same as it would not have been given at all.
difference: the reading is set to the difference between the current
and the previously evaluated value.
differential: the reading is set to the difference between the
current and the previously evaluated value divided by the time in
seconds between the current and the previous evaluation. Granularity
of time is one second. No value is calculated if the time past is
below one second. Useful to calculate rates.
integral: reverse function of differential. The result is incremented
by the product of the time difference between the last two readings
and the avarage of the last two readings.
result += (time - timeold) * (oldval + value) / 2
offset: if the current evaluated value is smaler than the previously
evaluated value the reading is incremented by the previous value.
the reading can then be used as an offset correct for a counter that
is reset for example due to a power loss.
monotonic: if the difference between the current and the previously
evaluated value is positive the reading is incremented by this difference.
this allows to derive a monotonic growing counter from an original counter
even if the original will be rest by a power loss
Example:
attr myPowerMeter userReadings power
differential { ReadingsVal("myPowerMeter","counters.A",0)/1250.0;; }
Notes:
user readings with modifiers difference and differential store the
calculated values internally. The user reading is set earliest at the
second evaluation. Beware of stale values when changing
definitions!
the name of the defined Readings consists of alphanumeric characters
with underscore (_) and the minus (-) sign.
Common attributes
The following local attributes are used by a wider range of devices:
IODev
Set the IO or physical device which should be used for sending signals
for this "logical" device. An example for the physical device is an FHZ
or a CUL. Note: Upon startup FHEM assigns each logical device
(FS20/HMS/KS300/etc) the last physical device which can receive data
for this type of device. The attribute IODev needs to be used only if
you attached more than one physical device capable of receiving signals
for this logical device.
disable
Disables the corresponding device. Note: it can be toggled by issuing the following command:
attr <device> disable toggle
disabledForIntervals HH:MM-HH:MM HH:MM-HH:MM ...
Space separated list of HH:MM or D@HH:MM tupels. If the current time is
between the two time specifications, the current device is disabled.
Instead of HH:MM you can also specify HH or HH:MM:SS. D is the day of
the week, with 0 indicating Sunday and 3 indicating Wednesday.
Specifying the day for the "from" part does _not_ specify it for the
"to" part, i.e. 1@00-24 will disable from monday to the end of the
week, but not on sunday (as 1@00 is greater than any time on sunday).
To specify an interval spawning midnight, you have to specify two
intervals, e.g.:
23:00-24:00 00:00-01:00
If parts of the attribute value are enclosed in {}, they are evaluated:
Set an attribute for a device defined by define.
The value is optional, and is set to 1 if missing.
You can define your own attributes too to use them
in other applications.
Use "attr <name> ?" to get a list of possible attributes.
See the Device specification section for details on
<devspec>.
After setting the attribute, the global event "ATTR" will be generated.
If the option -a is specified, append the given value to the currently
existing value. Note: if the value does not start with a comma (,), then a
space will be added automatically to the old value before appending the
new.
With the -r option one can remove a part of an attribute value.
With the -silent option the command is not recorded in the "save -?" list.
Define a device. You need devices if you want to manipulate them (e.g.
set on/off), and the logfile is also more readable if it contains e.g.
"lamp off" instead of "Device 5673, Button 00, Code 00 (off)".
After definition, the global event "DEFINED" will be generated, see the
notify section for details.
Each device takes different additional arguments at definition, see the
corresponding device section for details.
Options:
-temporary
Add the TEMPORARY flag to the definition, which will prevent saving the
device to fhem.cfg.
-ignoreErr
Reduce the number of errors displayed when a certain FHEM-module cannot
be loaded. Used by fhem.cfg.demo, as using the RSS example requires the
installation of several uncommon perl modules.
-silent
Do no enter the command in the "save ?" list.
Define a device or modify it, if it already exists. E.g. to switch off a lamp
10 Minutes after the last message from the motion detector, you may use
define mdNtfy notify motionDetector defmod mdOff at +00:10 set lamp off
Using define here for the mdOff will generate an error if the motion detector
triggers within the 10 minutes after the first event, as the mdOff at
definition still exists.
For the options see the define documentation.
Delete something created with the define command.
See the Device specification section for details on
<devspec>.
After deletion, the global event "DELETED" will be generated, see the notify
section for details.
Examples:
Delete either a single attribute (see the attr command)
or all attributes for a device (if no <attrname> is defined).
See the Device specification section for details on
<devspec>.
<attrname> is in fact a regexp, complemented with ^ and $ as usual, so
a range of attributes can be deleted with one command.
After deleting the attribute, the global event "DELETEATTR" will be generated.
Examples:
Delete the reading <readingname>
for a device. <readingname> is a perl regular expression that must
match the whole name of the reading. Use with greatest care! FHEM might
crash if you delete vital readings of a device.
See the Device specification section for details on
<devspec>.
Display either the value of a single attribute (see the attr command)
or all attributes for a device (if no <attrname> is defined).
See the Device specification section for details on
<devspec>.
If more then one device is specified, then the device name will also included
in the output.
Examples:
fhem> di WEB
menuEntries AlarmOn,/fhem?cmd=set%20alarm%20on
room Misc.
fhem> di WEB room
Misc.
Monitor events via a telnet client. This command is the telnet equivalent of
the FHEMWEB Event monitor, but can also be used by other programs/modules to
receive a notification. Options:
on
switch the inform mechanism on
onWithState
show the additional state event too
off
switch the inform mechanism off (both events and logs, see below)
raw
show only raw events from physical devices
timer
prepend a timestamp to each event
log
show messages written by the FHEM Log interface
list [devspec] [value ...]
or list {-r|-R} devspec
Output a list of all definitions, all notify settings and all at
entries. This is one of the few commands which return a string in a
normal case.
See the Device specification section for details on
<devspec>.
If <value> is specified, then output this property (internal, reading
or attribute) for all devices from the devspec. <value> can be
restricted with prefix i: for internals, r: for readings and a: for
attributes.
Example:
fhem> list
Type list <name> for detailed info.
Internal:
global (Internal)
FHZ:
FHZ (fhtbuf: 23)
FS20:
Btn4 (on-old-for-timer)
Roll1 (on)
Stehlampe (off)
FHT:
fl (measured-temp: 21.1 (Celsius))
KS300:
out1 (T: 2.9 H: 74 W: 2.2 R: 8.2 IR: no)
at:
at_rollup (Next: 07:00:00)
notify:
ntfy_btn4 (active)
FileLog:
avglog (active)
If specifying name, then a detailed status for name
will be displayed, e.g.:
fhem> list fl
Internals:
CODE 5102
DEF 5102
NAME fl
NR 15
STATE measured-temp: 21.1 (Celsius)
TYPE FHT
IODev FHZ
Attributes:
room Heizung
Readings:
2006-11-02 09:45:56 actuator 19%
[...]
With the -r (raw) option output the device definition in a format suitable
for inclusion in fhem.cfg and fhem.state. -R returns the definition of the
device itself, together with the definition of probably associated devices.
Note: the algorithm to select associated devices is known to be imperfect.
Used to modify some definitions. Useful for changing some at or notify definitions. If specifying
one argument to an at type definition, only the time part will be changed. In
case of a notify type definition, only the regex part will be changed. All
other values (state, attributes, etc) will remain intact.
After modify, the global event "MODIFIED" will be generated.
With the -silent option the command is not recorded in the "save -?" list.
Example:
define lampon at 19:00 set lamp on modify lampon *19:00 modify lampon 19:00 set lamp on-for-timer 16
Rename a device from the <oldname> to <newname>, together with
its attributes. The global event RENAMED will be generated, see the notify
section for details.
Re-read the active configuration file, or the optionally specified file.
The sequence: the statefile will be saved first,
then all devices will be deleted, then the currently active config file (or
the specified file) will be read and at last the statefile will be
reloaded.
Upon completion it triggers the global:REREADCFG event. All existing
connections up to the one issuing the rereadcfg will be closed.
Save first the statefile, then the
configfile information. If a parameter is specified,
it will be used instead the global configfile attribute.
Notes:
save only writes out definitions and attributes, but no (set/get)
commands which were previously part of the config file. If you need such
commands after the initialization (e.g. FHTcode), you
should trigger them via notify, when receiving the
INITIALIZED event.
save tries to preserve comments (lines starting with #) and include
structures, but it won't work correctly if some of these files are not
writeable.
before overwriting the files, the old version will be saved, see the restoreDirs global attribute for details.
Set parameters of a device / send signals to a device. You can
get a list of possible parameters by
set <name> ?
See the Device specification section for details on
<devspec>. The set command returns only a value on error.
Each device has different set parameters, see the corresponding device
section for details.
From featurelevel 5.7 on the set and setreading command replaces:
[device:name] with the reading, internal or attribute of the device, if
both device and the reading, internal or attribute exists.
You can use the r:, i: or a: prefix to restrict the search to one
type, analogue to the devspec filtering.
The suffix :d retrieves the first number
The suffix :i retrieves the integer part of the first number.
The suffix :r<n> retrieves the first number and rounds it to
<n> decimal places. If <n> is missing, then rounds it to
one decimal place.
The suffix :t returns the timestamp (works only for readings)
The suffix :sec returns the number of seconds since the reading was
set.
Example:
set Lamp blink [blinkDummy:number] [r:blinkDummy:duration:d]
[device:name:d] same as above, but only the number is retrieved
[device:name:sec] same as above, but only the number is retrieved
{(perlExpression)} with the result of perlExpression.
The $DEV variable is additionally available, designating the set device
name.
These replacements are also known as "set magic".
Some modules support a common list of set extensions, and point in
their documentation to this section. If the module itself implements one of
the following commands, then the module-implementation takes precedence.
on-for-timer <seconds>
Issue the on command for the device, and after <seconds> the off
command. For issuing the off command an internal timer will be
scheduled, which is deleted upon a restart. To delete this internal
timer without restart specify 0 as argument.
off-for-timer <seconds>
see on-for-timer above.
on-till <timedet>
Issue the on command for the device, and create an at definition with
<timedet> (in the form HH:MM[:SS]) to set it off. This definition
is visible, and its name is deviceName+"_till". To cancel the scheduled
off, delete the at definition. Note: on-till is not active, if the
specified time is after the current time, in order to make things like
define morningLight at *06:00 set Lamp on-till {sunrise()}
easy.
on-till-overnight <timedet>
Like on-till, but wont compare the current time with the timespec, so
following will work:
define nightLight at *{sunset()} set Lamp on-till-overnight 01:00
off-till <timedet>
see on-till above.
off-till-overnight <timedet>
see on-till-overnight above.
blink <number> <blink-period>
set the device on for <blink-period> then off for
<blink-period> and repeat this <number> times.
To stop blinking specify "0 0" as argument.
intervals <from1>-<till1> <from2>-<till2>...
set the device on for the specified intervals, which are all timespecs
in the form HH:MM[:SS]. The intervals are space separated.
toggle
Issue the off command, if the current STATE is on, else the on command.
dim XX is also interpreted as on, if XX is not 0.
Examples:
set switch on-for-timer 12.5
set switch on-till {sunset()}
set switch blink 3 1
set switch intervals 08:00-12:00 13:00-18:00
attrTemplate
with this command a set of predefined attributes may be set at once. The
template files containing the entries are in FHEM/lib/AttrTemplate
directory. Template entries can be module specific, and may require further
parameters to be specified.
Add a default attribute. Each device defined from now on will receive
this attribute. If no attrname is specified, then the default attribute
list will be deleted.
Example to set the attribute "room kitchen" and "loglevel 4" to
each of the lamps:
Set the reading <reading> for the device <name> to
<value> without sending out commands to the device, but triggering
events and eventMap/stateFormat transformations as usual. See the set
command documentation for replacement description.
If the timespec is omitted (default) the current time will be used.
Examples:
setreading lamp state on
Note: setreading won't generate an event for device X, if it is called from a
notify for device X. Use "sleep 0.1; setreading X Y Z" in this case.
Set the STATE entry for the device specified by <devspec>,
which is used for displaying the device state in different frontends.
No signals will be sent to the device, no events will be generated, and no
eventMap or stateFormat translation will be done either.
This command is also used in the statefile.
See the Device specification section for details on
<devspec>.
Examples:
setstate lamp on
Note: this command is also used to store the readings in the statefile, in
this case the timestamp will preceed the value. As a side-effect there is no
way to save a state correctly if it starts with a timestamp in the YYYY-MM-DD
HH:MM:SS form.
show a temporary room with devices from <devspec>. The command ist only
available through FHEMWEB. See the Device
specification section for details on <devspec>.
Shut down the server (after saving the state information
). It triggers the global:SHUTDOWN event. If the optional restart
parameter is specified, FHEM tries to restart itself. exitValue may be
important for start scripts.
sleep followed by another command is comparable to a nameless at or notify, it executes the
following commands after waiting for the specified time or an event matching
<regex>. The delay can be given
in seconds, with millisecond accuracy, as you can specify decimal places,
as a timespec (HH:MM or HH:MM:SS or {perlfunc})
or as a regex (devicename or devicename:event)
A sleep with an <id> will replace a sleep with the same <id>
and can be canceled by cancel.
When called in a notify/at/etc, then nonempty return values of the following
commands are logged to the global logfile with loglevel 2. If quiet is
specified, then skip this logging.
Example:
define n3 notify btn3.* set lamp on;;sleep 1.5;;set lamp off
define a3 at +*00:05 set Windsensor 1w_measure;; sleep 2 quiet;; get
Windsensor 1w_temp
Note: a sleep not followed by any command will block FHEM, is deprecated, and
it issues a WARNING in the FHEM log.
The global device is used to set different global attributes. It will be
automatically defined, it cannot be deleted or renamed and has no set or get
parameters
Define
N/A
Set
N/A
Get
N/A
Internals
init_errors
contains configuration errors and security issues collected at FHEM
startup.
Attributes
altitude
Specifies the mean sea level in meters. Default is 0.
archivesort
archivesort may be set to the (default) alphanum or timestamp, and
specifies how the last files are computed for the nrarchive attribute.
autoload_undefined_devices
If set, automatically load the corresponding module when a message
of this type is received. This is used by the
autocreate device, to automatically create a FHEM device upon
receiving a corresponding message.
autosave
enable some modules to automatically trigger save after a configuration
change, e.g. after a new device was created. Default is 1 (true), you
can deactivate this feature by setting the value to 0. Configration
errors at startup automatically deactivate this value.
backupcmd
You could pass the backup to your own command / script by using this attribute.
If this attribute is specified, then it will be started as a shell command and
passes a space separated list of files / directories as one
argument to the command, like e.g.:
Note: Your command / script has to return the string "backup done" or
everything else to report errors, to work properly with update!
This Attribute is used by the backup command.
Example:
attr global backupcmd /usr/local/bin/myBackupScript.sh
backupdir
A folder to store the compressed backup file.
This Attribute is used by the backup command.
Example:
attr global backupdir /Volumes/BigHD
backupsymlink
If this attribute is set to everything else as "no", the archive
command tar will support symlinks in your backup. Otherwise, if this
attribute is set to "no" symlinks are ignored by tar.
This Attribute is used by the backup command.
Example:
attr global backupsymlink yes
blockingCallMax
Limit the number of parallel running processes started by the
BlockingCall FHEM helper routine. Useful on limited hardware, default
is 32. If the limit is reached, further calls are delayed.
configfile
Contains the name of the FHEM configuration file. If save is called without argument, then the output will
be written to this file.
commandref
If set to "full", then a full commandref will be generated after each
update. If set to modular (default since FHEM 6.1), there is only a
short description at the beginning, and the module documentation is
loaded from FHEM dynamically.
disableFeatures
comma separated list of values. Currently following values are
recognized:
attrTemplate: to avoid loading the AttrTemplates (which currently
consumes about 1MB of memory and needs some seconds to load on a
slow hardware)
securityCheck: to avoid checking if each Server port is secured
by password. May make sense to avoid warnings, if you know it
better.
dnsHostsFile
If dnsServer is set, check the contents of the file specified as
argument. To use the system hosts file, set it to /etc/hosts on
Linux/Unix/OSX and C:\windows\system32\drivers\etc\hosts on Windows.
Note: only IPv4 is supported.
dnsServer
Contains the IP address of the DNS Server. If some of the modules or
user code calls the HttpUtils_NonblockingGet function, and this
attribute is set, then FHEM specific nonblocking code will be used to
resolve the given address. If this attribute is not set, the blocking
OS implementation (inet_aton and gethostbyname) will be used.
encoding
Set the internal encoding used for storing strings.
Possible values: bytestream (default) and unicode.
Notes:
Since not all modules were checked, if they work correctly with
the internal unicode encoding, this feature is experimental.
Changing the attribute value triggers a save and a shutdown restart
featurelevel
Enable/disable old or new features, based on FHEM version.
E.g. the $value hash for notify is only set for featurelevel up to 5.6,
as it is deprecated, use the Value() function instead.
holiday2we
If this attribute is set, then the $we variable
will be true, if it is either saturday/sunday, or the value of the holiday variable referenced by this attribute is
not none. If it is a comma separated list, then it is true, if one
of the referenced entities is not none.
Example:
attr global holiday2we he
Note: if one of the elements in the list is named weekEnd, then the
check for saturday/sunday is skipped If the name is noWeekEnd, and
its Value is not none, than $we is 0.
httpcompress
the HttpUtils module is used by a lot of FHEM modules, and enables
compression by default. Set httpcompress to 0 to disable this feature.
ignoreRegexp
Do not log messages matching the value into the FHEM log. Note: the
usual ^ and $ will be appended to the regexp, like in notify or
FileLog.
keyFileName
FHEM modules store passwords and unique IDs in the file
FHEM/FhemUtils/uniqueID. In order to start multiple FHEM instances from
the same directory, you may set this attribute, whose value will
appended to FHEM/FhemUtils/
latitude
Used e.g. by SUNRISE_EL to calculate sunset/sunrise.
Default is Frankfurt am Main, Germany (50.112).
longitude
Used e.g. by SUNRISE_EL to calculate sunset/sunrise.
Default is Frankfurt am Main, Germany (8.686).
logdir
If set, the %L attribute in the logfile attribute (or in the FileLog
modules file definition) is replaced wth the value of the attribute.
Note: changing the value won't result in moving the files and may cause
other problems.
logfile
Specify the logfile to write. You can use "-" for
stdout, in this case the server won't background itself.
The logfile name can also take wildcards for easier logfile rotation,
see the FileLog section. Just apply the
archivecmd / archivedir / nrarchive attributes to the
global device as you would do for a FileLog device.
You can access the current name of the logfile with
{ $currlogfile }.
maxChangeLog
FHEM stores the structural change history which is displayed by
"save ?" or in FHEMWEB by clicking on the red question mark.
By default this list is limited to 10 entries, this attribute changes
the limit.
The length of each stored line is limited to 40 characters. This value
can be changed with the (optional, space separated) second number.
Example: attr global myxChangeLog 20 200
maxShutdownDelay
Some modules need some time at shutdown to finish the cleanup, but FHEM
restricts the delay to 10 seconds. Use this attribute to modify the
maximum delay.
modpath
Specify the path to the modules directory FHEM. The path
does not contain the directory FHEM. Upon setting the
attribute, the directory will be scanned for filenames of the form
NN_<NAME>.pm, and make them available for device definition under
<NAME>. If the first device of type <NAME> is defined, the
module will be loaded, and its function with the name
<NAME>_Initialize will be called. Exception to this rule are
modules with NN=99, these are considered to be utility modules
containing only perl helper functions, they are loaded at startup (i.e.
modpath attribute definition time).
motd
Message Of The Day. Displayed on the homescreen of the FHEMWEB package,
or directly after the telnet logon, before displaying the fhem> prompt.
In addition, the content of the internal value init_errors will be
displayed. To avoid displaying messages set its value to none.
mseclog
If set, the timestamp in the logfile will contain a millisecond part.
nofork
If set and the logfile is not "-", do not try to background. Needed on
some Fritzbox installations, and it will be set automatically for
Windows.
perlSyntaxCheck
by setting the global attribute perlSyntaxCheck, a syntax check
will be executed upon definition or modification, if the command is
perl and FHEM is already started.
pidfilename
Write the process id of the perl process to the specified file. The
server runs as a daemon, and some distributions would like to check by
the pid if we are still running. The file will be deleted upon
shutdown.
proxy
IP:PORT of the proxy server to be used by HttpUtils.
proxyAuth
Base64 encoded username:password
proxyExclude
regexp for hosts to exclude when using a proxy
restoreDirs
update saves each file before overwriting it with the new version from
the Web. For this purpose update creates a directory restoreDir/update
in the global modpath directory, then a subdirectory with the current
date, where the old version of the currently replaced file is stored.
The default value of this attribute is 3, meaning that 3 old versions
(i.e. date-directories) are kept, and the older ones are deleted.
fhem.cfg and fhem.state will be also copied with this method before
executing save into restoreDir/save/YYYY-MM-DD. To restore the files,
you can use the restore FHEM command.
If the attribute is set to 0, the feature is deactivated.
statefile
Set the filename where the state and certain at
information will be saved before shutdown. If it is not specified, then
no information will be saved.
useInet6
try to use IPv6 in HttpUtils for communication. If the server does not
have an IPv6 address, fall back to IPv4. Note: IO::Socket::INET6 is
required.
userattr
A space separated list which contains the names of additional
attributes for all devices. Without specifying them you will not be
able to set them (in order to prevent typos).
userattr can also specified for other devices, in this case
these additional attribute names are only valid for this device.
dupTimeout
Define the timeout for which 2 identical events from two different
receiver are considered a duplicate. Default is 0.5 seconds.
showInternalValues
Show data used for internal computations. If the name of an internal
value, reading or attribute starts with dot (.), then it is normally
hidden, and will only be visible, if this attribute is set to 1.
The attribute is checked by the list command, by the FHEMWEB room
overview and by xmllist.
sslVersion
Specifies the accepted cryptography algorithms by all modules using the
TcpServices helper module. The current default TLSv12:!SSLv3 is thought
to be more secure than the previously used SSLv23:!SSLv3:!SSLv2, but it
causes problems with some not updated web services.
stacktrace
if set (to 1), dump a stacktrace to the log for each "PERL WARNING".
restartDelay
set the delay for shutdown restart, default is 2 (seconds).
Events:
INITIALIZED after initialization is finished.
REREADCFG after the configuration is reread.
SAVE before the configuration is saved.
SHUTDOWN before FHEM is shut down.
DEFINED <devname> after a device is defined.
DELETED <devname> after a device was deleted.
RENAMED <old> <new> after a device was renamed.
UNDEFINED <defspec> upon reception of a message for an
undefined device.
MODIFIED <defspec> after a device modification.
UPDATE after an update is completed.
CANNOT_FORKif BlockingCall encounters this problem.
Defines an Allnet 4027 device (Box with 8 relays) connected to an ALL4000 via its ip address. The status of the device is also pooled (delay interval), because someone else is able to change the state via the webinterface of the device.
Examples:
define lamp1 ALL4027 192.168.8.200 0 7 60
Set
set <name> <value>
where value is one of:
off
on
on-for-timer <Seconds>
toggle
Examples:
set poolpump on
Notes:
Toggle is special implemented. List name returns "on" or "off" even after a toggle command
AMAD - Automagic Android DeviceAMADCommBridge - Communication bridge for all AMAD devices
This module is the central point for the successful integration of Android devices in FHEM. It also provides a link level between AMAD supported devices and FHEM. All communication between AMAD Android and FHEM runs through this interface.
Therefore, the initial setup of an AMAD device is also performed exactly via this module instance.
In order to successfully establish an Android device in FHEM, an AMADCommBridge device must be created in the first step.
Define
define <name> AMADCommBridge
Example:
define AMADBridge AMADCommBridge
This statement creates a new AMADCommBridge device named AMADBridge.
The APP Automagic or Tasker can be used on the Android device.
For Autoremote:
In the following, only the Flowset has to be installed on the Android device and the Flow 'First Run Assistant' run. (Simply press the Homebutton)
The wizard then guides you through the setup of your AMAD device and ensures that at the end of the installation process the Android device is created as an AMAD device in FHEM.
For Tasker:
When using Tasker, the Tasker-project must be loaded onto the Android device and imported into Tasker via the import function.
For the initial setup on the Android device there is an Tasker input mask (Scene), in which the required parameters (device name, device IP, bridgeport etc.)
can be entered, these fields are filled (if possible) automatically, but can also be adjusted manually.
To do this, run the "AMAD" task.
For quick access, a Tasker shortcut can also be created on the home screen for this task.
Information on the individual settings can be obtained by touching the respective text field.
If all entries are complete, the AMAD Device can be created via the button "create Device".
For control commands from FHEM to Tasker, the APP "Autoremote" or "Tasker Network Event Server (TNES)" is additionally required.
Readings
JSON_ERROR - JSON Error message reported by Perl
JSON_ERROR_STRING - The string that caused the JSON error message
receiveFhemCommand - is set the fhemControlMode attribute to trigger, the reading is set as soon as an FHEM command is sent. A notification can then be triggered.
If set instead of trigger setControl as value for fhemControlMode, the reading is not executed but the set command executed immediately.
receiveVoiceCommand - The speech control is activated by AMAD (set DEVICE activateVoiceInput), the last recognized voice command is written into this reading.
receiveVoiceDevice - Name of the device from where the last recognized voice command was sent
state - state of the Bridge, open, closed
Attributes
allowFrom - Regexp the allowed IP addresses or hostnames. If this attribute is set, only connections from these addresses are accepted.
Attention: If allowfrom is not set, and no kind allowed instance is defined, and the remote has a non-local address, then the connection is rejected. The following addresses are considered local:
IPV4: 127/8, 10/8, 192.168/16, 172.16/10, 169.254/16
IPV6: ::1, fe80/10
debugJSON - If set to 1, JSON error messages are written in readings. See JSON_ERROR * under Readings
fhemControlMode - Controls the permissible type of control of FHEM devices. You can control the bridge in two ways FHEM devices. Either by direct FHEM command from a flow, or as a voice command by means of voice control (set DEVICE activateVoiceInput)
trigger - If the value trigger is set, all FHEM set commands sent to the bridge are written to the reading receiveFhemCommand and can be executed using notify. Voice control is possible; readings receiveVoice * are set. On the Android device several voice commands can be linked by means of "and". Example: turn on the light scene in the evening and turn on the TV
setControl - All set commands sent via the flow are automatically executed. The triggering of a reading is not necessary. The control by means of language behaves like the value trigger
thirdPartControl - Behaves as triggered, but in the case of voice control, a series of voice commands by means of "and" is not possible. Used for voice control via modules of other module authors ((z.B. 39_TEERKO.pm)
If you have problems with the wizard, an Android device can also be applied manually, you will find in the Commandref to the AMADDevice module.
AMAD - Automagic Android Device
This module integrates Android devices into FHEM and displays several settings using the Android app "Automagic" or "Tasker".
Automagic is comparable to the "Tasker" app for automating tasks and configuration settings. But Automagic is more user-friendly. The "Automagic Premium" app currently costs EUR 2.90.
Any information retrievable by Automagic/Tasker can be displayed in FHEM by this module. Just define your own Automagic-"flow" or Tasker-"task" and send the data to the AMADCommBridge. One even can control several actions on Android devices.
To be able to make use of all these functions the Automagic/Tasker app and additional flows/Tasker-project need to be installed on the Android device. The flows/Tasker-project can be retrieved from the FHEM directory, the app can be bought in Google Play Store.
How to use AMADDevice?
first, make sure that the AMADCommBridge in FHEM was defined
Using Automagic
install the "Automagic Premium" app from the PlayStore
install the flowset 74_AMADDeviceautomagicFlowset$VERSION.xml file from the $INSTALLFHEM/FHEM/lib/ directory on the Android device
activate the "installation assistant" Flow in Automagic. If one now sends Automagic into the background, e.g. Homebutton, the assistant starts and creates automatically a FHEM device for the android device
Using Tasker
install the "Tasker" app from the PlayStore
install the Tasker-project 74_AMADtaskerset_$VERSION.prj.xml file from the $INSTALLFHEM/FHEM/lib/ directory on the Android device
run the "AMAD" task in Tasker and make your initial setup, by pressing the "create Device" button it will automatically create the device in FHEM
In this case, an AMADDevice is created by hand. The AMAD_ID, here 123456, must also be entered exactly as a global variable in Automagic/Tasker.
Readings
airplanemode - on/off, state of the aeroplane mode
androidVersion - currently installed version of Android
automagicState - state of the Automagic or Tasker App (prerequisite Android >4.3). In case you have Android >4.3 and the reading says "not supported", you need to enable Automagic/Tasker inside Android / Settings / Sound & notification / Notification access
batteryHealth - the health of the battery (1=unknown, 2=good, 3=overheat, 4=dead, 5=over voltage, 6=unspecified failure, 7=cold) (Automagic only)
powerPercent - state of battery in %
batterytemperature - the temperature of the battery (Automagic only)
bluetooth - on/off, bluetooth state
checkActiveTask - state of an app (needs to be defined beforehand). 0=not active or not active in foreground, 1=active in foreground, see note below (Automagic only)
connectedBTdevices - list of all devices connected via bluetooth (Automagic only)
connectedBTdevicesMAC - list of MAC addresses of all devices connected via bluetooth (Automagic only)
currentMusicAlbum - currently playing album of mediaplayer (Automagic only)
currentMusicApp - currently playing player app (Amazon Music, Google Play Music, Google Play Video, Spotify, YouTube, TuneIn Player, Aldi Life Music) (Automagic only)
currentMusicArtist - currently playing artist of mediaplayer (Automagic only)
currentMusicIcon - cover of currently play album Not yet fully implemented (Automagic only)
currentMusicState - state of currently/last used mediaplayer (Automagic only)
currentMusicTrack - currently playing song title of mediaplayer (Automagic only)
daydream - on/off, daydream currently active
deviceState - state of Android devices. unknown, online, offline.
doNotDisturb - state of do not Disturb Mode
dockingState - undocked/docked, Android device in docking station
flow_SetCommands - active/inactive, state of SetCommands flow
flow_informations - active/inactive, state of Informations flow
flowsetVersionAtDevice - currently installed version of the flowsets on the Android device
incomingCallerName - Callername from last Call
incomingCallerNumber - Callernumber from last Call
incomingWhatsAppMessage - last WhatsApp message
incomingTelegramMessage - last telegram message
incomingSmsMessage - last SMS message
intentRadioName - name of the most-recent streamed intent radio
intentRadioState - state of intent radio player
keyguardSet - 0/1 keyguard set, 0=no 1=yes, does not indicate whether it is currently active
lastSetCommandError - last error message of a set command
lastSetCommandState - last state of a set command, command send successful/command send unsuccessful
lastStatusRequestError - last error message of a statusRequest command
lastStatusRequestState - ast state of a statusRequest command, command send successful/command send unsuccessful
nextAlarmDay - currently set day of alarm
nextAlarmState - alert/done, current state of "Clock" stock-app
nextAlarmTime - currently set time of alarm
nfc - state of nfc service on/off
nfcLastTagID - nfc_id of last scan nfc Tag / In order for the ID to be recognized correctly, the trigger NFC TagIDs must be processed in Flow NFC Tag Support and the TagId's Commase-separated must be entered. (Automagic only)
powerPlugged - 0=no/1,2=yes, power supply connected
screen - on locked,unlocked/off locked,unlocked, state of display
screenBrightness - 0-255, level of screen-brightness
screenOrientationMode - auto/manual, mode for screen orientation
state - current state of AMAD device
userFlowState - current state of a Flow, established under setUserFlowState Attribut (Automagic only)
volume - media volume setting
volumeNotification - notification volume setting
wiredHeadsetPlugged - 0/1 headset plugged out or in
Prerequisite for using the reading checkActivTask the package name of the application to be checked needs to be defined in the attribute checkActiveTask. Example: attr Nexus10Wohnzimmer
checkActiveTask com.android.chrome für den Chrome Browser.
Set
activateVoiceInput - start voice input on Android device
bluetooth - on/off, switch bluetooth on/off
clearNotificationBar - All/Automagic, deletes all or only Automagic/Tasker notifications in status bar
closeCall - hang up a running call
currentFlowsetUpdate - start flowset/Tasker-project update on Android device
installFlowSource - install a Automagic flow on device, XML file must be stored in /tmp/ with extension xml. Example:set TabletWohnzimmer installFlowSource WlanUebwerwachen.xml (Automagic only)
doNotDisturb - sets the do not Disturb Mode, always Disturb, never Disturb, alarmClockOnly alarm Clock only, onlyImportant only important Disturbs
mediaPlay - play command to media App
mediaStop - stop command to media App
mediaNext - skip Forward command to media App
mediaBack - skip Backward to media App
nextAlarmTime - sets the alarm time. Only valid for the next 24 hours.
notifySndFile - plays a media-file which by default needs to be stored in the folder "/storage/emulated/0/Notifications/" of the Android device. You may use the attribute setNotifySndFilePath for defining a different folder.
openCall - initial a call and hang up after optional time / set DEVICE openCall 0176354 10 call this number and hang up after 10s
screenMsg - display message on screen of Android device
sendintent - send intent string Example: set $AMADDEVICE sendIntent org.smblott.intentradio.PLAY url http://stream.klassikradio.de/live/mp3-192/stream.klassikradio.de/play.m3u name Klassikradio, first parameter contains the action, second parameter contains the extra. At most two extras can be used.
sendSMS - Sends an SMS to a specific phone number. Bsp.: sendSMS Dies ist ein Test|555487263
startDaydream - start Daydream
statusRequest - Get a new status report of Android device. Not all readings can be updated using a statusRequest as some readings are only updated if the value of the reading changes.
timer - set a countdown timer in the "Clock" stock app. Only minutes are allowed as parameter.
ttsMsg - send a message which will be played as voice message (to change laguage temporary set first character &en; or &de;)
userFlowState - set Flow/Tasker-profile active or inactive,set Nexus7Wohnzimmer Badezimmer:inactive vorheizen or set Nexus7Wohnzimmer Badezimmer vorheizen,Nachtlicht Steven:inactive
userFlowRun - executes the specified flow/task
vibrate - vibrate Android device
volume - set media volume. Works on internal speaker or, if connected, bluetooth speaker or speaker connected via stereo jack
volumeNotification - set notifications volume
Set (depending on attribute values)
changetoBtDevice - switch to another bluetooth device. Attribute setBluetoothDevice needs to be set. See note below! (Automagic only)
nfc - activate or deactivate the nfc Modul on/off. attribute root
openApp - start an app. attribute setOpenApp
openURL - opens a URLS in the standard browser as long as no other browser is set by the attribute setOpenUrlBrowser.Example: attr Tablet setOpenUrlBrowser de.ozerov.fully|de.ozerov.fully.MainActivity, first parameter: package name, second parameter: Class Name
screen - on/off/lock/unlock, switch screen on/off or lock/unlock screen. In Automagic "Preferences" the "Device admin functions" need to be enabled, otherwise "Screen off" does not work. attribute setScreenOnForTimer changes the time the display remains switched on! (Tasker supports only "on/off" command)
screenFullscreen - on/off, activates/deactivates full screen mode. attribute setFullscreen
screenLock - Locks screen with request for PIN. attribute setScreenlockPIN - enter PIN here. Only use numbers, 4-16 numbers required. (Automagic only)
system - issue system command (only with rooted Android devices). reboot,shutdown,airplanemodeON (can only be switched ON) attribute root, in Automagic "Preferences" "Root functions" need to be enabled.
takePicture - take a camera picture Attribut setTakePictureResolution
takeScreenshot - take a Screenshot picture Attribut setTakeScreenshotResolution
Attribut
setAPSSID - set WLAN AccesPoint SSID('s) to prevent WLAN sleeps (Automagic only), more than one ssid can comma seperate
setNotifySndFilePath - set systempath to notifyfile (default /storage/emulated/0/Notifications/
setTtsMsgSpeed - set speaking speed for TTS (For Automagic: Value between 0.5 - 4.0, 0.5 Step, default: 1.0)(For Tasker: Value between 1 - 10, 1 Step, default: 5)
setTtsMsgLang - set speaking language for TTS, de or en (default is de)
setTtsMsgVol - is set, change automatically the media audio end set it back
set setTakePictureResolution - set the camera resolution for takePicture action (800x600,1024x768,1280x720,1600x1200,1920x1080)
setTakePictureCamera - which camera do you use (Back,Front).
To be able to use "openApp" the corresponding attribute "setOpenApp" needs to contain the app package name.
To be able to switch between bluetooth devices the attribute "setBluetoothDevice" needs to contain (a list of) bluetooth devices defined as follows: attr <DEVICE> BTdeviceName1|MAC,BTDeviceName2|MAC No spaces are allowed in any BTdeviceName. Defining MAC please make sure to use the character : (colon) after each second digit/character.
Example: attr Nexus10Wohnzimmer setBluetoothDevice Logitech_BT_Adapter|AB:12:CD:34:EF:32,Anker_A3565|GH:56:IJ:78:KL:76
state
initialized - shown after initial define.
active - device is active.
disabled - device is disabled by the attribute "disable".
AirUnit implements a FHEM device to control Danfoss AirUnits (a1,a2,w1,w2). Tested only with w2 (Feb 2021).
With this module it is possible to control the most useful functions of your ventilation system.
possible Readings
units of values
Abluft_Grundstufe_Einstellung
percent
Abluft_Luefterdrehzahl
rpm
Abluft_Stufe
step
Abluft_Temperatur
degree
Aussenluft_Temperatur
degree
Bypass_aktiviert
on/off
Bypass_Dauer
hour
Feuerstaette_aktiviert
on/off
Fortluft_Temperatur
degree
Luefterstufe_manuell
step
Luftfeuchtigkeit
percent
Model
name
Modus
mode of operation
Nachtkuehlung_aktiviert
on/off
Raumluft_Temperatur_AirDail
degree
Seriennummer
number
Stosslueftung_aktiviert
on/off
Stosslueftung_Dauer
hour
Zuluft_Grundstufe_Einstellung
percent
Zuluft_Luefterdrehzahl
rpm
Zuluft_Stufe
step
Zuluft_Temperatur
degree
automatische_Stosslueftung
on/off
automatischer_Bypass
on/off
verbl.Batterielebensdauer_AirDial
percent
verbl.verbl.Filterlebensdaue
percent
Arbeitsstunden
hour
Define
define <name> AirUnit <IP-address[:Port]> [poll-interval]
If the poll interval is omitted, it is set to 300 (seconds). Smallest possible value is 30.
Usually, the port needs not to be defined.
Example: define myAirUnit AirUnit 192.168.0.12 600
Set
set <name> <option> <value>
You can set different values to any of the following options.
Options:
Modus
You can choose between "Bedarfsmodus", for automatic mode "Programm", you can define a programm in your AirDail-Controller and choose one. "Manuell", you can set the steps for the fans manually (only in manual mode). Bypass and Boost are in automatic mode. "Aus", the system is off for 24 hours, after this time, the system starts in automatic mode with fanstep 1.
Luefterstufe
You can set the steps for the fans manually. (only in manual mode)
Stosslueftung
You can activate/deactive the Boost-Option of your ventilation system. You can configure this mode in your AirDail-Controller, the standard fanstep 10 for 3 hours.
It is useful if you need more Air e.g. in case of cooking or a party with more people.
Stosslueftung_Dauer
You can set the hours for the duration of Boost-Option manually.
Bypass
You can activate/deactive the Bypass-Option of you ventilations systems. Its a cooling function, the heat exchanger will be deactivated.
You can configure this mode in your AirDail-Controller, the standard time is 3 hours. You can't activte it, if the outdoor temperature is under 5°C.
This option is not available for w1-unit.
Bypass_Dauer
You can set the hours for the duration of Bypass-Option manually.
Nachtkuehlung
You can activate/deactive the nightcooling option of you ventilations systems. You can configure this in your AirDail-Controller. This option is not available for w1-unit.
automatische_Stosslueftung
You can activate/deactive the automatic Boost-Option of you ventilations systems. Its automaticly activated, if the humidity increase very strong, then it runs for 30min.
automatischer_Bypass
You can activate/deactive the automatic Bypass-Option of you ventilations systems. Its automaticly activated, if the outdoor temperature and room temperature are higher then the configured values.
You can configure this mode in your AirDail-Controller.
Intervall
You can setup the refresh intervall of your readings. Minimum 30 seconds.
Feuerstaette
You can activate/deactive the Fireplace-Option.
Get
set <name> <option> <value>
You can set different values to any of the following options.
Options:
update
You can refresh all values manually.
Attributes
attr <name> <attribute> <value>
Attributes:
disable 0|1
When you set disable to "1", the connection and the refresh intervall will be disabled. (takes a while)
This feature gives you the possibility to use an external connection (e.g. the Danfoss-Windows-Tool) without deletion of the device.
additional information
PC-Tool
You can donwload the Danfoss-Windows-Tool HERE.
You can start this tool with 3 different options: enduser, service or installer.
You need only to change the "HRVPCTool.exe.config" in the installation directory.
set <name> locked set <name> unlocked sets the lockstate of the alarm module to locked (i.e., alarm setups
may not be changed) resp. unlocked (i.e., alarm setups may be changed>)
set <name> save|restore Manually save/restore the arm states to/from the external file AlarmFILE (save done automatically at each state modification, restore at FHEM start)
Get
get <name> version Display the version of the module
For each of the 8 alarm levels, several attributes
hold the alarm setup. They should not be changed by hand, but through the web
interface to avoid confusion: level<level>cond, level<level>start, level<level>end, level<level>autocan,
level<level>msg, level<level>onact,
level<level>offact
The module allows to control an Android device by using the Android Debug Bridge (ADB).
Before one can define an Android device, an AndroidDBHost I/O device must exist.
Dependencies: 89_AndroidDBHost
Define
define <name> AndroidDB <NameOrIP>[<Port>]
The parameter NameOrIP is the hostname or the IP address of the Android device.
The parameter Port specifies the TCP port to be used for the device connection.
The default port is 5555.
Set
set <Name> createRemote <Layout>
Create a remote control device for the Android device. Create a notify device for
the remote control to send button events to the AndroidDB device.
br/>
set <Name> exportPresets <Filename>
Export the currently loaded presets to file. This file can be modified and assigned
again by using attribute 'preset'.
set <name> reboot
Reboot the device.
set <name> remoteControl <MacroName>
Send key codes associated with 'MacroName' to the Android device. Either attribute
'macros' or 'preset' must be set to make this command available. Macro names defined
in attribute 'macros' are overwriting macros with the same name in a preset selected
by attribute 'preset'.
set <name> rollHorz <DeltaX>
Scroll display horizontally. Not supported on all types of Android devices.
set <name> rollVert <DeltaY>
Scroll display vertically. Not supported on all types of Android devices.
set <name> sendKey [longpress] <KeyCode> [...]
Send a key code to the Android device. If option 'longpress' is specified, only one
KeyCode is allowed.
set <name> sendNumKeys <Number>
Send digits of Number to the Android device. Number must be in range 0-9999.
set <name> sendText <Text>
Send Text to the Android device.
set <name> shell <Command> [<Arguments>]
Execute shell command on Android device.
set <name> tap <X> <Y>
Simulate a tap on a touchscreen (only available an devices having a touchscreen).
Get
set <Name> keyPreset <PresetName>
List key preset definition.
br/>
set <Name> cmdPreset <PresetName>
List command preset definition.
br/>
Attributes
connect 0|1
If set to 1, a connection to the Android device will be established during
FHEM start. Note: Set this attribute for one Android device only!
createReadings <command-expression>
Create readings for shell command-expression. Output must contain lines in format key=value.
Example: attr myDev createReadings dumpsys
macros <MacroDef>[;...]
Define a list of keycode macros to be sent to an Android device with 'remoteControl'
command or define shortcuts for remote commands.
A 'MacroDef' is using the following syntax:
MacroName:KeyCode[,...]
or
MacroName:Command
Parameter Command is a adb command.
Example, define a command 'set listpackages':
attr myDev macros listpackages:shell pm list packages -f
Several macro definitions can be specified by seperating them using a semicolon.
preset <PresetName>
Select a preset of keycode macros.
presetFile <Filename>
Load a set of macros from a preset defintion file.
If the same macro name is defined in the selected
preset and in attribute 'macros', the definition in the 'macros' attribute overwrites
the definition in the preset.
A preset defintion file is using the following format:
The parameter 'host' is the hostname of the system, where the ADB server is running. Default is 'localhost'.
Parameter 'adb' can be used to specify the path to the adb command (must include 'adb' or 'adb.exe'). Note: The adb command must be executable by the account under which FHEM is running.
Set
set <name> command <Command> [<Args>]
Execute ADB command.
AptToDate - Retrieves apt information about Debian update state state
With this module it is possible to read the apt update information from a Debian System.
It's required to insert "fhem ALL=NOPASSWD: /usr/bin/apt-get" via "visudo".
Define
define <name> AptToDate <HOST>
Example:
define fhemServer AptToDate localhost
This statement creates a AptToDate Device with the name fhemServer and the Host localhost.
After the device has been created the Modul is fetch all information about update state. This will need a moment.
Readings
state - update status about the server
os-release_ - all information from /etc/os-release
repoSync - status about last repository sync.
toUpgrade - status about last upgrade
updatesAvailable - number of available updates
Set
repoSync - fetch information about update state
toUpgrade - to run update process. this will take a moment
Get
showUpgradeList - list about available updates
showUpdatedList - list about updated packages, from old version to new version
showWarningList - list of all last warnings
showErrorList - list of all last errors
Attributes
disable - disables the device
upgradeListReading - add Upgrade List Reading as JSON
distupgrade - change upgrade prozess to dist-upgrade
disabledForIntervals - disable device for interval time (13:00-18:30 or 13:00-18:30 22:00-23:00)
This modul fetch Air Quality data from http://aqicn.org.
Define
define <name> Aqicn token=<TOKEN-KEY>
Example:
define aqicnMaster Aqicn token=12345678
This statement creates the Aqicn Master Device.
After the device has been created, you can search Aqicn Station by city name and create automatically the station device.
Readings
APL - Air Pollution Level
AQI - Air Quality Index (AQI) of the dominant pollutant in city. Values are converted from µg/m³ to AQI level using US EPA standards. For more detailed information: https://en.wikipedia.org/wiki/Air_quality_index and https://www.airnow.gov/index.cfm?action=aqi_brochure.index.
CO-AQI - AQI of CO (carbon monoxide). An AQI of 100 for carbon monoxide corresponds to a level of 9 parts per million (averaged over 8 hours).
NO2-AQI - AQI of NO2 (nitrogen dioxide). See also https://www.airnow.gov/index.cfm?action=pubs.aqiguidenox
PM10-AQI - AQI of PM10 (respirable particulate matter). For particles up to 10 micrometers in diameter: An AQI of 100 corresponds to 150 micrograms per cubic meter (averaged over 24 hours).
PM2.5-AQI - AQI of PM2.5 (fine particulate matter). For particles up to 2.5 micrometers in diameter: An AQI of 100 corresponds to 35 micrograms per cubic meter (averaged over 24 hours).
O3-AQI - AQI of O3 (ozone). An AQI of 100 for ozone corresponds to an ozone level of 0.075 parts per million (averaged over 8 hours). See also https://www.airnow.gov/index.cfm?action=pubs.aqiguideozone
SO2-AQI - AQI of SO2 (sulfur dioxide). An AQI of 100 for sulfur dioxide corresponds to a level of 75 parts per billion (averaged over one hour).
temperature - Temperature in degrees Celsius
pressure - Atmospheric pressure in hectopascals (hPa)
humidity - Relative humidity in percent
state- Current AQI and air pollution level
status - condition of the data
pubDate- Local time of publishing the data
pubUnixTime - Unix time stamp of local time but converted wrongly, if local time is e.g. 1300 GMT+1, the time stamp shows 1300 UTC.
pubTimezone - Time zone of the city (UTC)
windspeed - Wind speed in kilometer per hour
windDirection - Wind direction
dominatPoll - Dominant pollutant in city
dewpoint - Dew in degrees Celsius
healthImplications - Information about Health Implications
htmlStyle - can be used to format the STATE and FHEMWEB (Example: stateFormate htmlStyle
get
stationSearchByCity - search station by city name and open the result in seperate popup window
update - fetch new data every x times
Attribute
interval - interval in seconds for automatically fetch data (default 3600)
This module implements an Interface to an Arduino, ESP8266 or ESP32 based counter for pulses on any input pin of an Arduino Uno, Nano, Jeenode,
NodeMCU, Wemos D1, TTGO T-Display or similar device.
The device connects to Fhem either through USB / serial or via Wifi / TCP if an ESP board is used.
ArduCounter does not only count pulses but also measure pulse lenghts and the time between pulses so it can filter noise / bounces
and gives better power/flow (Watts or liters/second) readings than systems that just count in fixed time intervals.
The number of pulses per kWh or liter is defineable and counters continue even when Fhem or the device restarts
so you don't need additional user readings to make such calculations
The typical use case is an S0-Interface on an energy meter or water meter, but also reflection light barriers
to monitor old ferraris counters or analog water meters are supported
Counters are configured with attributes that define which GPIO pins should count pulses and in which intervals the board should report the current counts.
The sketch that works with this module uses pin change interrupts so it can efficiently count pulses on all available input pins.
The module has been tested with 14 inputs of an Arduino Uno counting in parallel and pulses as short as 3 milliseconds.
The module creates readings for pulse counts, consumption and optionally also a pin history with pulse lengths and gaps of the last pulses.
If an ESP8266 or ESP32 is used, the device can be flashed and configured over Wifi (it opens its own temporary Hotspot / SSID for configuration
so you can set which existing SSID to connect to and which password to use). For TTGO T-Display boards (ESP32 with TFT display)
the local display on the device itself can also display Wifi status and current consumption.
Prerequisites
This module requires an Arduino Uno, Nano, Jeenode, NodeMCU, Wemos D1, TTGO T-Display or similar device based on an Atmel 328p, ESP8266 or ESP32
running the ArduCounter sketch provided with this module
In order to flash an arduino board with the corresponding ArduCounter firmware from within Fhem, avrdude needs to be installed.
To flash ESP32 or ESP8266 boards form within Fhem, Python and the scripts esptool.py / espota.py need to be installed.
For old ferraris counters a reflection light barrier which in the simpest case can consist of a photo transistor (connected to an anlalog input of the Arduino / ESP)
and an led or a laser module (connected to a digital output), both with a resistor in line are needed.
To drive a laser module with 5V, another transistor is typically needed to switch 5V from a 3.3V GPIO output.
Define
define <name> ArduCounter <device>
or define <name> ArduCounter <ip:port>
<device> specifies the serial port to communicate with the Arduino.
<ip:port> specifies the ip address and tcp port to communicate with an esp8266 / ESP32 where port is typically 80.
The name of the serial device depends on your distribution and serial adapter.
You can also specify a baudrate for serial connections if the device name contains the @ character, e.g.: /dev/ttyUSB0@115200
The default baudrate of the ArduCounter firmware is 115200 since sketch version 4 and used to be 38400 since sketch version 1.4
The latest version of this module will however try different baudrates automatically if communication with the counting device seems not possible.
Example:
define AC ArduCounter /dev/ttyUSB2@115200
define AC ArduCounter 192.168.1.134:80
Configuration of ArduCounter digital counters
Specify the pins where impulses should be counted e.g. as attr AC pinX falling pullup min 25
The X in pinX can be an Arduino / ESP GPIO pin number with or without the letter D e.g. pin4, pinD5, pin6, pinD7 ...
After the pin you can use the keywords falling or rising to define if a logical one / 5V (rising) or a logical zero / 0V (falling) should be treated as pulse.
The optional keyword pullup activates the pullup resistor for the given Pin.
The last argument is also optional but recommended and specifies a minimal pulse length in milliseconds.
An energy meter with S0 interface is typically connected to GND and an input pin like D4.
The S0 pulse then pulls the input down to 0V.
Since the minimal pulse lenght of an S0 interface is specified to be 30ms, the typical configuration for an s0 interface is attr AC pinX falling pullup min 25
Specifying a minimal pulse length is recommended since it filters bouncing of reed contacts or other noise.
The keyword min before 25 is optional.
Example:
define AC ArduCounter /dev/ttyUSB2
attr AC pulsesPerUnit 1000
attr AC interval 60 300
attr AC pinD4 falling pullup min 5
attr AC pinD5 falling pullup min 25
attr AC pinD6 rising
This defines a counter that is connected to Fhem via serial line ttyUSB2 with three counters connected to the GPIO pins D4, D5 and D5.
D4 and D5 have their pullup resistors activated and the impulses draw the pins to zero.
For D4 and D5 the board measures the time in milliseconds between the falling edge and the rising edge.
If this time is longer than the specified 5 (or 25 for pin D5) milliseconds then the impulse is counted.
If the time is shorter then this impulse is regarded as noise and added to a separate reject counter.
For pin D6 the board uses a default minimal length of 2ms and counts every time when the signal changes from 1 (rising pulse) back to 0.
Configuration of ArduCounter analog counters
This module and the corresponding ArduCounter sketch can be used to read water meters or old analog ferraris energy counters.
Therefore a reflection light barrier needs to be connected to the board. This might simply consist of an infra red photo transistor
(connected to an analog input) and an infra red led (connected to a digital output), both with a resistor in line.
The idea comes from Martin Kompf (https://www.kompf.de/tech/emeir.html) and has been adopted for ArduCounter to support
old ferraris energy counters or water meters.
The configuration is then similar to the one for digital counters:
define WaterMeter ArduCounter 192.168.1.110:80
attr ACF pinA0 rising pullup min 4 analog out 27 threshold 120,220
attr ACF interval 5,60,2,15,10,3
attr ACF pulsesPerUnit 35
attr ACF stateFormat {sprintf("%.3f l/min", ReadingsVal($name,"powerA0",0))}
In this case an analog GPIO pin is used as input and the normal configuration parameters are followed by the keyword
analog out or simply out, the gpio number of a GPIO output that connects a light source and the thresholds
that decide when an analog input value is regarded as "low" or "high".
In the example an ESP32 is used via Wifi connection. GPIO pin A0 is used as analog input and is connected to a photo transistor that senses the intensity of light.
GPIO 27 is used as LED output and switched on/off in a high frequency. On GPIO A0 the reflected light is measured
and the difference in a measurement between when the LED is off and when the LED is on is compared to the thresholds defined in the pinA0-attribute.
When the measured light difference is above 220, then a pulse starts (since rising is specified).
When the measured difference is below 120 then the pulse ends.
The attribute interval has the following meaning in the above example:
The device reports the current counts and the time difference beween the first and the last pulse if at least 2 pulses have been counted
and if they are more than 15 milliseconds apart form each other. If not, then the device continues counting.
If after 60 seconds these conditions are stil not met, then the device will report the current count anyways and use the current time as the end of the interval.
The last two numbers of the interval attribute define that the device will read the analog input 3 times and then work with the average.
Between each analog measurement series there will be a delay of 10 milliseconds.
The attribute pulsesPerUnit 35 defines that 35 pulses correspond to one unit (e.g. liter) and the reading calcCounterA0
is increased by the reported raw counts divided by 35.
To find out the right analog thresholds you can set the attribute enableHistory to 1 which will ask the firmware of your counting board
to report the average difference measurements before they are compared to a threshold.
The ArduCounter module will count how often each value is reported and you can then query these analog level counts with get levels.
After a few measuremets the result of get levels might look like this:
This shows the measured values together with the frequency how often the individual value has been measured.
It is obvious that most measurements result in values between 120 and 135, very few values are betweem 96 and 115
and another peak is around the value 95.
It means that in the example of a ferraris energy counter, when the red mark of the ferraris disc is under the sensor,
the value is around 95 and while when the blank disc is under the sensor, the value is typically between 120 and 135.
So a good upper threshold would be 120 and a good lower threshold would be for example 96.
Set-Commands
raw
send the value to the board so you can directly talk to the sketch using its commands.
This is not needed for normal operation but might be useful sometimes for debugging
flash [<file>]
flashes the ArduCounter firmware from the subdirectory FHEM/firmware onto the device.
Normally you can just specify set myDevice flash. The parameter <file> is optional and allows specifying an alternative firmware file.
The attribute flashCommand can be used to override which command is executed.
If the attribute flashCommand is not specified then the module selects an appropriate command depending on the board type
(set with the attribute board) and depending on the connection (serial or Wifi).
For an arduino NANO for example the module would execute avrdude (which has to be installed of course)
and flash the connected arduino with the updated hex file
(by default it looks for ArduCounter.hex in the FHEM/firmware subdirectory).
For an Arduino UNO for example the default is avrdude -p atmega328P -c arduino -P [PORT] -D -U flash:w:[HEXFILE] 2>[LOGFILE]
For an Arduino Nano based counter -b 57600 is added.
For an ESP32 connected via Wifi, the module would call espota.py which will upload the firmware over the air.
If the attribute flashCommand is not specified for an ESP32 based board connected via serial line, then the module uses the command
esptool.py --chip esp32 --port [PORT] --baud 460800 --before default_reset --after hard_reset write_flash -z
--flash_mode dio --flash_freq 40m --flash_size detect
0x1000 FHEM/firmware/ArduCounter_ESP32_bootloader_dio_40m.bin
0x8000 FHEM/firmware/ArduCounter_ESP32_partitions.bin
0xe000 FHEM/firmware/ArduCounter_ESP32_boot_app0.bin
0x10000 FHEM/firmware/ArduCounter_ESP32_firmware.bin >[LOGFILE] 2>&1
for example which flashes the whole ESP32 with all the partitions.
For over the air flashing it would use
espota.py -i[IP] -p [NETPORT] -f [BINFILE] 2>[LOGFILE].
Of course esptool.py or espota.py as well as python would need to be installed on the system.
resetWifi
reset Wifi settings of the counting device so the Wifi Manager will come up after the next reset to select a wireless network and enter the Wifi passphrase.
reset
sends a command to the device which causes a hardware reset or reinitialize and reset of the internal counters of the board.
The module then reopens the counting device and resends the attribute configuration / definition of the pins.
saveConfig
stores the current interval, analog threshold and pin configuration in the EEPROM of the counter device so it will automatically be retrieved after a reset.
enable
sets the attribute disable to 0
disable
sets the attribute disable to 1
reconnect
closes the tcp connection to an ESP based counter board that is conected via TCP/IP and reopen the connection
clearLevels
clears the statistics for analog levels. This is only relevant if you use the board to read via a reflective light barrier
and you want to set the thresholds according to the statistics.
clearCounters <pin>
resets all the counter readings for the specified pin to 0
counter <pin>, <value>
set the calcCounter reading for the specified pin to the given value
clearHistory
deletes all the cached pin history entries
Get-Commands
info
send a command to the Arduino board to get current counts.
This is not needed for normal operation but might be useful sometimes for debugging
levels
show the count for the measured levels if an analog pin is used to measure e.g. the red mark of a ferraris counter disc. This is useful for setting the thresholds for analog measurements.
history <pin>
shows details regarding all the level changes that the counter device (Arduino or ESP) has detected and how they were used (counted or rejected)
If get history is issued with a pin name (e.g. get history D5) then only the history entries concerning D5 will be shown.
This information is sent from the device to Fhem if the attribute enableHistory is set to 1.
The maximum number of lines that the Arducounter module stores in a ring buffer is defined by the attribute maxHist and defaults to 1000.
pin[AD]?[0-9]+<rising|falling> [<pullup>] [min] <min length> [[analog] out <out pin> [threshold] <min, max>]
Define a GPIO pin of the Arduino or ESP board as input. This attribute expects for digital inputs either
rising or falling, followed by an optional pullup and the optional keyword min
and an optional number as minimal length of pulses and gaps between pulses.
The counter device will track rising and falling edges of each impulse and measure the length of a pulse in milliseconds.
The minimal length specified here is the minimal duration of a pulse and a pause before a pulse. If one is too small,
the pulse is not counted but added to a separate reject counter.
Example:
attr MyCounter pinD4 falling pullup 25
For analog inputs with connected reflective light barries, you have to add analog out
and the GPIO pin number of the pin where the light source (LED or laser) is connected, the keyword threshold
followed by the lower and upper threshold separated by a komma.
Example:
attr MyCounter pinA0 rising pullup min 3 analog out 27 threshold 120,220
interval <normal> <max> [<min> <min count> [<analog interval> <analog samples>]]
Defines the parameters that affect the way counting and reporting works.
This Attribute expects at least two and a maximum of six numbers as value.
The first is the normal interval, the second the maximal interval, the third is a minimal interval and the fourth is a minimal pulse count.
The last two numbers are only needed for counting with reflective light barriers. They specify the delay between the measurements
and the number of samples for each measurement.
In the usual operation mode (when the normal interval is smaller than the maximum interval),
the Arduino board just counts and remembers the time between the first impulse and the last impulse for each pin.
After the normal interval is elapsed the Arduino board reports the count and time for those pins where impulses were encountered.
This means that even though the normal interval might be 10 seconds, the reported time difference can be
something different because it observed impulses as starting and ending point.
The Power (e.g. for energy meters) is then calculated based of the counted impulses and the time between the first and the last impulse.
For the next interval, the starting time will be the time of the last impulse in the previous reporting period
and the time difference will be taken up to the last impulse before the reporting interval has elapsed.
The second, third and fourth numbers (maximum, minimal interval and minimal count) exist for the special case
when the pulse frequency is very low and the reporting time is comparatively short.
For example if the normal interval (first number) is 60 seconds and the device counts only one impulse in 90 seconds,
the the calculated power reading will jump up and down and will give ugly numbers.
By adjusting the other numbers of this attribute this can be avoided.
In case in the normal interval the observed impulses are encountered in a time difference that is smaller than the third number (minimal interval)
or if the number of impulses counted is smaller than the fourth number (minimal count) then the reporting is delayed until the maximum interval has elapsed
or the above conditions have changed after another normal interval.
This way the counter will report a higher number of pulses counted and a larger time difference back to fhem.
Example:
attr myCounter interval 60 600 5 2
If this is seems too complicated and you prefer a simple and constant reporting interval, then you can set the normal interval and the mximum interval to the same number.
This changes the operation mode of the counter to just count during this normal and maximum interval and report the count.
In this case the reported time difference is always the reporting interval and not the measured time between the real impulses.
For analog sampling the last two numbers define the delay in milliseconds between analog measurements and the number of samples that will be taken as one mesurement.
board
specify the type of the board used for ArduCounter like NANO, UNO, ESP32, ESP8266 or T-Display
Example:
attr myCounter board NANO
pulsesPerUnit <number>
specify the number of pulses that the meter is giving out per unit that sould be displayed (e.g. per kWh energy consumed).
For many S0 counters this is 1000, for old ferraris counters this is 75 (rounds per kWh).
This attribute used to be called pulsesPerKWh and this name still works but the new name should be used preferably since the old one could be removed in future versions.
Example:
attr myCounter pulsesPerUnit 75
readingPulsesPerUnit[AD]?[0-9]+ <number>
is the same as pulsesPerUnit but specified per GPIO pin individually in case you have multiple counters with different settings at the same time
This attribute used to be called readingPulsesPerKWh[AD]?[0-9]+ and this name still works but the new name should be used preferably
since the old one could be removed in future versions.
readingFlowUnitTime[AD]?[0-9]+ <time>
specified the time period in seconds which is used as the basis for calculating the current flow or power for the given pin.
If the counter e.g. counts liters and you want to see the flow in liters per minute, then you have to set this attribute to 60.
If you count kWh and you want to see the current power in kW, then specify 3600 (one hour).
Since this attribute is just used for multiplying the consumption per second, you can also use it to get watts
instead of kW by using 3600000 instead of 3600.
flowUnitTime <time>
like readingFlowUnitTimeXX but applies to all pins that have no explicit readingFlowUnitTimeXX attribute.
readingStartTime[AD]?[0-9]+ [0|1]
Allow the reading time stamp to be set to the beginning of measuring intervals.
This is a hack where the timestamp of readings is artificially set to a past time and may have side effects
so avoid it unless you fully understand how Fhem works with readings and their time.
verboseReadings[AD]?[0-9]+ [0|1]
create the additional readings lastMsg and pinHistory for each pin
if verboseReafings is set to 1 for the specified pin.
If set to -1 then the internal counter, the long counter and interpolated long counter readings will be hidden.
Example:
attr myCounter verboseReadingsD4 1
enableHistory [0|1]
tells the counting device to record the individual time of each change at each GPIO pin and send it to Fhem.
This information is cached on the Fhem side and can be viewed with the command get history
The optput of get history will look like this:
Seq 12627 2020-03-22 20:39:54 Pin D5 0.080 seconds at 0 -> pulse counted
Seq 12628 2020-03-22 20:39:55 Pin D5 1.697 seconds at 1 -> gap
Seq 12629 2020-03-22 20:39:56 Pin D5 0.080 seconds at 0 -> pulse counted
Seq 12630 2020-03-22 20:39:56 Pin D5 1.694 seconds at 1 -> gap
Seq 12631 2020-03-22 20:39:58 Pin D5 0.081 seconds at 0 -> pulse counted
Seq 12632 2020-03-22 20:39:58 Pin D5 1.693 seconds at 1 -> gap
Seq 12633 2020-03-22 20:40:00 Pin D5 0.081 seconds at 0 -> pulse counted
Seq 12634 2020-03-22 20:40:00 Pin D5 1.696 seconds at 1 -> gap
Seq 12635 2020-03-22 20:40:02 Pin D5 0.081 seconds at 0 -> pulse counted
Seq 12636 2020-03-22 20:40:02 Pin D5 1.699 seconds at 1 -> gap
Seq 12637 2020-03-22 20:40:03 Pin D5 0.079 seconds at 0 -> pulse counted
Seq 12638 2020-03-22 20:40:03 Pin D5 1.700 seconds at 1 -> gap
Seq 12639 2020-03-22 20:40:05 Pin D5 0.080 seconds at 0 -> pulse counted
Seq 12642 2020-03-22 20:40:05 Pin D5 1.699 seconds at 1 -> gap
Seq 12643 2020-03-22 20:40:07 Pin D5 0.080 seconds at 0 -> pulse counted
Seq 12644 2020-03-22 20:40:07 Pin D5 1.698 seconds at 1 -> gap
enableSerialEcho [0|1]
tells the counting device to show diagnostic data over the serial line when connected via TCP
enablePinDebug [0|1]
tells the counting device to show every level change of the defined input pins over the serial line or via TCP
enableAnalogDebug [0|1]
tells the counting device to show every analog measurement of the defined analog input pins over the serial line or via TCP
enableDevTime [0|1]
tells the counting device to show its internal millis timer so a drift between the devices time and fhem time can be calculated and logged
maxHist <max entries>
specifies how many pin history lines hould be buffered for "get history".
This attribute defaults to 1000.
analogThresholds
this Attribute is outdated. Please specify the analog thresholds for reflective light barrier input with the attribute "pin..."
flashCommand <new shell command>
overrides the default command to flash the firmware via Wifi (OTA) or serial line. It is recommended to not define this attribute.
Example:
[PORT] is automatically replaced with the serial port for this device as it is specified in the define command. [HEXFILE] or [BINFILE] are synonyms and are both automatically replaced with the firmware file appropriate for the device.
For ESP32 boards [HEXFILE] would be replaced by ArduCounter-8266.bin for example. [LOGFILE] is automatically replaced ArduCounterFlash.log in the fhem log subdirectory. [NETPORT] is automatically replaced by the tcp port number used for OTA flashing.
For ESP32 this usually is 3232 and for 8266 Bords it is 8266.
keepAliveDelay <delay>
defines an interval in which the module sends keepalive messages to a counter device that is conected via tcp.
This attribute is ignored if the device is connected via serial port.
If the device doesn't reply within a defined timeout then the module closes and tries to reopen the connection.
The module tells the device when to expect the next keepalive message and the device will also close the tcp connection if it doesn't see a keepalive message within the delay multiplied by 3
The delay defaults to 10 seconds.
Example:
attr myCounter keepAliveDelay 30
keepAliveTimeout <seconds>
defines the timeout when wainting for a keealive reply (see keepAliveDelay)
The timeout defaults to 2 seconds.
Example:
attr myCounter keepAliveTimeout 3
keepAliveRetries <max number of retries>
defines how often sending a keepalive is retried before the connection is closed and reopened.
It defaults to 2.
Example:
attr myCounter keepAliveRetries 3
nextOpenDelay <delay>
defines the time in seconds that the module waits before retrying to open a disconnected tcp connection.
This defaults to 60 seconds.
Example:
attr myCounter nextOpenDelay 20
openTimeout <timeout>
defines the timeout in seconds after which tcp open gives up trying to establish a connection to the counter device.
This timeout defaults to 3 seconds.
Example:
attr myCounter openTimeout 5
silentReconnect [0|1]
if set to 1, then it will set the loglevel for "disconnected" and "reappeared" messages to 4 instead of 3
Example:
disable [0|1]
if set to 1 then the module is disabled and closes the connection to a counter device.
factor
Define a multiplicator for calculating the power from the impulse count and the time between the first and the last impulse.
This attribute is outdated and unintuitive so you should avoid it.
Instead you should specify the attribute pulsesPerUnit or readingPulsesPerUnit[0-9]+ (where [0-9]+ stands for the pin number).
readingFactor[AD]?[0-9]+
Override the factor attribute for this individual pin.
Just like the attribute factor, this is a rather cumbersome way to specify the pulses per kWh.
Instead it is advised to use the attribute pulsesPerUnit or readingPulsesPerUnit[0-9]+ (where [0-9]+ stands for the pin number).
runTime[AD]?[0-9]+
if this attribute is set for a pin, then a new reading will be created which accumulates the run time for this pin while consumption is greater than 0.
This allows e.g. to check if a water meter shows water consumption for a time longer than X without stop.
runTimeIgnore[AD]?[0-9]+
this allows to ignore consumption for the run time attribute while a certain other device is switched on.
devVerbose
this attribute is outdated and has been replaced with the attributes
enableHistory, enableSerialEcho, enablePinDebug, enableAnalogDebug, enableDevTime
configDelay
specify the time to wait for the board to report its configuration before Fhem sends the commands to reconfigure the board
helloSendDelay
specify the time to wait for the board to report its type before Fhem sends the commands to ask for it
helloWaitTime
specify the time to wait for the board to report its type when Fhem has asked for it before a timeout occurs
Readings / Events
The module creates at least the following readings and events for each defined pin:
calcCounter.*
This is recommended reading for counting units based on the pulses and the attribute pulsesPerUnit. It is similar to interpolated long count
which keeps on counting up after fhem restarts but this counter will take the pulses per Unit attribute into the calculation und thus does not
count pulses but real Units (kWh, liters or some other unit that is applicable)
The name of this reading can be changed with the attribute readingNameCalcCount[AD]?[0-9]+ where [AD]?[0-9]+ stands for the pin description e.g. D4.
Another reading with the same name but ending in _i (e.g. calcCounterD4_i) will show how many kWh (or other units) of the above value is interpolated.
pin.* e.g. pinD4
the current internal count at this pin (internal to the Arduino / ESP device, starts at 0 when the device restarts).
The name of this reading can be changed with the attribute readingNameCount[AD]?[0-9]+ where [AD]?[0-9]+ stands for the pin description e.g. D4
long.* e.g. longD5
long count which keeps on counting up after fhem restarts whereas the pin.* count is only a temporary internal count that starts at 0 when the arduino board starts.
The name of this reading can be changed with the attribute readingNameLongCount[AD]?[0-9]+ where [AD]?[0-9]+ stands for the pin description e.g. D4
interpolatedLong.*
like long.* but when the Arduino restarts the potentially missed pulses are interpolated based on the pulse rate before the restart and after the restart.
The name of this reading can be changed with the attribute readingNameInterpolatedCount[AD]?[0-9]+ where [AD]?[0-9]+ stands for the pin description e.g. D4
reject.*
counts rejected pulses that are shorter than the specified minimal pulse length.
power.*
the current calculated power / flow at this pin.
The name of this reading can be changed with the attribute readingNamePower[AD]?[0-9]+ where [AD]?[0-9]+ stands for the pin description e.g. D4.
This reading depends on the attributes pulsesPerUnit as well as readingFlowUnitTime or flowUnitTime for calculation
pinHistory.*
shows detailed information of the last pulses. This is only available when a minimal pulse length is specified for this pin. Also the total number of impulses recorded here is limited to 20 for all pins together. The output looks like -36/7:0C, -29/7:1G, -22/8:0C, -14/7:1G, -7/7:0C, 0/7:1G
The first number is the relative time in milliseconds when the input level changed, followed by the length in milliseconds, the level and the internal action.
-36/7:0C for example means that 36 milliseconds before the reporting started, the input changed to 0V, stayed there for 7 milliseconds and this was counted.
countDiff.*
delta of the current count to the last reported one. This is used together with timeDiff.* to calculate the power consumption.
timeDiff.*
time difference between the first pulse in the current observation interval and the last one. Used togehter with countDiff to calculate the power consumption.
seq.*
internal sequence number of the last report from the board to Fhem.
runTime.*
this reading will only be created when the attribute runTime[AD]?[0-9]+ is set for a given pin.
It contains the time in seconds that the consumption / flow observed at the specified pin has not ben zero.
If a water meter which outputs 10 impulses per liter on its digital output is for example connected to GPIO pin D6,
then if the attribute runTimeD6 is set to 1, the reading runTimeD6 will show for how many seconds the water has been flowing without a stop longer than the
observation interval specifie in the interval-attribute. This is helpful when you want to create alerts in case someone forgot to close a water tap.
Arlo security cams are connected to the Arlo Cloud via base stations. The base stations and cameras can be controlled with a REST API.
Events (like movement and state changes) are delivery by server-sent events (SSE).
Define
define Arlo_Cloud Arlo ACCOUNT <hans.mustermann@xyz.de> <myArloPassword> <myEmailPassword> <myEmailUsername>
Please replace hans.mustermann@xyz.de by the e-mail address you have registered at Arlo and myArloPassword by the password used there.
For the 2 factor authentication you also have to set the password of the email account. The email server which receives the Arlo mails has to be set
with attr Arlo_Cloud mailServer imap.gmx.net, where imap.gmx.net has to be replaced by the IMAP server of your mail provider. Only IMAP with encryption is supported.
You can skip the parameter myEmailUsername if the username matches the email address.
After you have successfully created the account definition, you can call set Arlo_Cloud autocreate.
Now the base station(s) and cameras which are assigned to the Arlo account will be created in FHEM. All new devices are created in the room Arlo.
In the background there is a permanent SSE connection to the Arlo server. If you temporary don't use Arlo in FHEM, you can stop this SSE connection by setting
the attribute "disable" at the Arlo_Cloud device to 1.
Set
autocreate (subtype ACCOUNT)
Reads all devices which are assigned to the Arlo account and creates FHEM devices, if the devices don't exist in FHEM.
reconnect (subtype ACCOUNT)
Connect or reconnect to the Arlo server. First FHEM logs in, then a SSE connection is established. This method is only used if the connection
to the Arlo server was interrupted.
readModes (subtype ACCOUNT)
Reads the modes of the base stations (iincl. custom modes). Is called automatically, normally you don't have to call this manually.
updateReadings (subtype ACCOUNT)
The data of all base stations and cameras are retrieved from the Arlo cloud. This is done every hour automatically, if you don't set the
attribute disable=1 at the Cloud device. The interval can be changed by setting the attribute updateInterval (in seconds, e.g. 600 for 10 minutes, 7200 for 2 hours).
arm (subtype BASESTATION, BRIDGE, ARLOQ and BABYCAM)
Activates the motion detection.
disarm (subtype BASESTATION, BRIDGE, ARLOQ and BABYCAM)
Deactivates the motion detection.
mode (subtype BASESTATION and BRIDGE)
Set a custom mode (parameter: name of the mode).
siren (subtype BASESTATION)
Activates or deactivates the siren of the base station (attention: the siren is loud!).
subscribe (subtype BASESTATION, ARLOQ and BABYCAM)
Subscribe base station for the SSE connection. Normally you don't have to do this manually, this is done automatically after login.
unsubscribe (subtype BASESTATION, ARLOQ and BABYCAM)
Unsubscribe base station for the current SSE connection.
brightness (subtype CAMERA, ARLOQ and BABYCAM)
Adjust brightness of the camera (possible values: -2 to +2).
on (Subtype CAMERA)
Switch on camera (deactivate privacy mode).
off (subtype CAMERA)
Switch off camera (activate privacy mode).
snapshot (subtype CAMERA, ARLOQ and BABYCAM)
Take a snapshot. The snapshot url is written to the reading snapshotUrl. This command only works if the camera has the state on.
startRecording (subtype CAMERA, ARLOQ and BABYCAM)
Start recording. This command only works if the camera has the state on.
stopRecording (subtype CAMERA, ARLOQ and BABYCAM)
Stops an active recording. The recording url is stored in the reading lastVideoUrl, a frame of the recording in lastVideoImageUrl and a thumbnail of the recording in lastVideoThumbnailUrl.
nightlight (Subtype BABYCAM)
Switch nightlight on or off.
nightlight-brightness (Subtype BABYCAM)
Set brightness of nightlight.
nightlight-color (Subtype BABYCAM)
Set color of nightlight.
If this attribute is set at the cloud device (subtype ACCOUNT), the files which are stored at the Arlo Cloud (videos / images) will also be downloaded to the given directory.
If you want to access these files via FHEM http you have to use a subdirectory of /opt/fhem/www.
Attention: the fhem user has to have write access to the directory.
downloadLink
If the attribute downloadDir is set and the files will be downloaded from Arlo Cloud, you can set this attribute to create a correct URL to the last video, last snapshot and so on.
A correct value is like http://hostname:8083/fhem/subdirectory-of-www
disable
Subtype ACCOUNT: Deactivates the SSE connection to Arlo Cloud.
Subtype BASESTATION: Deactivates the periodic update of the readings from Arlo Cloud.
expiryTime
Subtype ACCOUNT: If all base stations have the status "disarmed" the connection to the cloud will be closed after this time. A new connection will be established if needed.
Unit is seconds, default 600 (10 minutes). If you set the value to 0 the connection will not be closed.
mailServer
Subtype ACCOUNT: Name of the IMAP mail server which receives the Arlo 2FA code mail. The passwort for the mail server has to be set in the define of Arlo_Cloud device.
videoDownloadFix
Subtype ACCOUNT: Set this attribute to 1 if videos are not downloaded automatically. Normally the server sents a notification when there is a new video available but sometimes
this doesn't work. Default is 0.
pingInterval
Subtype ACCOUNT: Set the interval in seconds for the heartbeat-ping. Without a heartbeat-ping the session in Arlo Cloud would expire and FHEM wouldn't receive any more events.
Default is 90.
updateInterval
Subtype ACCOUNT: Set the interval in seconds how often the readings of base statations and cameras will be updated. Default is 3600 = 1 hour.
ssePollingInterval
Subtype ACCOUNT: Set the interval in seconds how often the SSE events are checked. Default is 2 seconds.
FHEM module with a collection of various routines for astronomical data
Define
define <name> Astro [global] Defines the Astro device (only one is needed per FHEM installation).
Optional parameter 'global' will mark this device for global configuration options, see SUNRISE_EL compatibility mode below for details.
Readings with prefix Sun refer to the sun, with prefix Moon refer to the moon.
The suffixes for these readings are:
Age = angle (in degrees) of body along its track
Az,Alt = azimuth and altitude angle (in degrees) of body above horizon
Dec,Ra = declination (in degrees) and right ascension (in HH:MM) of body position
HrsVisible,HrsInvisible = Hours of visiblity and invisiblity of the body
Lat,Lon = latitude and longituds (in degrees) of body position
Diameter = virtual diameter (in arc minutes) of body
Distance,DistanceObserver = distance (in km) of body to center of earth or to observer
PhaseN,PhaseS = Numerical and string value for phase of body
Sign,SignN = Circadian sign for body along its track
Rise,Transit,Set = times (in HH:MM) for rise and set as well as for highest position of body
Readings with prefix Obs refer to the observer.
In addition to some of the suffixes gives above, the following may occur:
Date,Dayofyear = date
JD = Julian date
Time,Timezone,TimezoneS = obvious meaning
IsDST = 1 if running on daylight savings time, 0 otherwise
GMST,LMST = Greenwich and Local Mean Sidereal Time (in HH:MM)
An SVG image of the current moon phase may be obtained under the link
<ip address of fhem>/fhem/Astro_moonwidget?name='<device name>'.
Optional web parameters are [&size='<width>x<height>'][&mooncolor=<color>][&moonshadow=<color>]
Notes:
Calculations are only valid between the years 1900 and 2100
Attention: Timezone is taken from the local Perl settings, NOT automatically defined for a location
This module uses the global attribute language to determine its output data
(default: EN=english). For German output, set attr global language DE.
If a local attribute on the device was set for language it will take precedence.
The time zone is determined automatically from the local settings of the
operating system. If geocordinates from a different time zone are used, the results are
not corrected automatically.
Some definitions determining the observer position are used
from the global device, i.e.
attr global longitude <value> attr global latitude <value> attr global altitude <value> (in m above sea level)
These definitions are only used when there are no corresponding local attribute settings on the device.
It is not necessary to define an Astro device to use the data provided by this module.
To use its data in any other module, you just need to put LoadModule("Astro");
at the start of your own code, and then may call, for example, the function
to acquire the sunrise on Christmas Eve 2019. The hash reference may also be undefined or an existing device name of any type. Note that device attributes of the respective device will be respected as long as their name matches those mentioned for an Astro device.
attribute=value pairs may be added in text format to enforce
settings like language that would otherwise be defined by a real device.
You may also add parameters to customize your request:
Functions that can replace those from SUNRISE_EL are available under the same name and adding a as a prefix in front of it (for example, use asunrise() instead of sunrise()). A single Astro device can act as a global configuration device for such functions if it was created using the global define parameter. If you don't want to create any Astro device at all, you may put LoadModule("Astro"); into your 99_myUtils.pm to only load the SUNRISE_EL replacement functions.
Set
set <name> update trigger to recompute values immediately.
Get
Attention: Get-calls are NOT written into the readings of the device. Readings change only through periodic updates.
get <name> json [<reading>,[<reading>]] [-1|yesterday|+1|tomorrow] get <name> json [<reading>,[<reading>]] MM-DD [-1|yesterday|+1|tomorrow] get <name> json [<reading>,[<reading>]] YYYY-MM-DD [-1|yesterday|+1|tomorrow] get <name> json [<reading>,[<reading>]] HH:MM[:SS] [-1|yesterday|+1|tomorrow] get <name> json [<reading>,[<reading>]] YYYY-MM-DD HH:MM[:SS] [-1|yesterday|+1|tomorrow] returns the complete set of an individual reading of astronomical data either for the current time, or for a day and time given in the argument. yesterday, tomorrow or any other integer number may be given at the end to get data relative to the given day and time.
Formatted values as described below may be generated in a subtree text by adding text=1 to the request.
get <name> text [<reading>,[<reading>]] [-1|yesterday|+1|tomorrow] get <name> text [<reading>,[<reading>]] MM-DD [-1|yesterday|+1|tomorrow] get <name> text [<reading>,[<reading>]] YYYY-MM-DD [-1|yesterday|+1|tomorrow] get <name> text [<reading>,[<reading>]] HH:MM[:SS] [-1|yesterday|+1|tomorrow] get <name> text [<reading>,[<reading>]] YYYY-MM-DD HH:MM[:SS] [-1|yesterday|+1|tomorrow] returns the complete set of an individual reading of astronomical data either for the current time, or for a day and time given in the argument. yesterday, tomorrow or any other integer number may be given at the end to get data relative to the given day and time.
The return value may be formatted and/or labeled by adding one or more of the following key=value pairs to the request:
unit=1 = Will add a unit to numerical values. Depending on attribute lc_numeric, the decimal separator will be in regional format as well.
long=1 = A describtive label will be added to the value.
long=2 = Same as long=1 but the label will be separated from the value by a colon.
long=3 = Same as long=2 but Sun or Moon will be added as a prefix.
long=4 = Same as long=3 but the separator will be used to separate Sun/Moon instead.
get <name> version Display the version of the module
Attributes
<interval> Update interval in seconds. The default is 3600 seconds, a value of 0 disables the periodic update.
<language> A language may be set to overwrite global attribute settings.
<lc_numeric> Set regional settings to format numerical values in textual output. If not set, it will generate the locale based on the attribute language (if set).
<lc_time> Set regional settings to format time related values in textual output. If not set, it will generate the locale based on the attribute language (if set).
<recomputeAt> Enforce recomputing values at specific event times, independant from update interval. This attribute contains a list of one or many of the following values:
MoonRise,MoonSet,MoonTransit = for moon rise, set, and transit
NewDay = for 00:00:00 hours of the next calendar day
SunRise,SunSet,SunTransit = for sun rise, set, and transit
*TwilightEvening,*TwilightMorning = for the respective twilight stage begin
<timezone> A timezone may be set to overwrite global and system settings. Format may depend on your local system implementation but is likely in the format similar to Europe/Berlin.
Some definitions determining the observer position:
attr <name> longitude <value> attr <name> latitude <value> attr <name> altitude <value> (in m above sea level) attr <name> horizon <value> custom horizon angle in degrees, default 0. Different values for morning/evening may be set as <morning>:<evening>
These definitions take precedence over global attribute settings.
<disable> When set, this will completely disable any device update.
multiple paramters can be set at once separated by :
Examples: set LC on : transitiontime 100 set bulb on : pct 100 : color 4000
Get
rgb
RGB
devStateIcon
returns html code that can be used to create an icon that represents the device color in the room overview.
Attributes
color-icon
1 -> use lamp color as icon color and 100% shape as icon shape
2 -> use lamp color scaled to full brightness as icon color and dim state as icon shape
transitiontime
default transitiontime for all set commands if not specified directly in the set.
delayedUpdate
1 -> the update of the device status after a set command will be delayed for 1 second. usefull if multiple devices will be switched.
devStateIcon
will be initialized to {(Aurora_devStateIcon($name),"toggle")} to show device color as default in room overview.
webCmd
will be initialized to a device specific value
AutoShuttersControl (ASC) provides a complete automation for shutters with comprehensive
configuration options, e.g. open or close shutters depending on the sunrise or sunset,
by outdoor brightness or randomly for simulate presence.
So that ASC can drive the blinds on the basis of the astronomical times, it is very important to
correctly set the location (latitude, longitude) in the device "global".
After telling ASC which shutters should be controlled, several in-depth configuration options
are provided. With these and in combination with a resident presence state, complex scenarios are possible:
For example, shutters could be opened if a resident awakes from sleep and the sun is already rosen. Or if a
closed window with shutters down is tilted, the shutters could be half opened for ventilation.
Many more is possible.
Define
define <name> AutoShuttersControl
Usage:
define myASControl AutoShuttersControl
This creates an new AutoShuttersControl device, called myASControl.
Now was the new global attribute ASC added to the FHEM installation.
Each shutter that is to be controlled by AutoShuttersControl must now have the attribute ASC set to 1 or 2.
The value 1 is to be used with devices whose state is given as position (i.e. ROLLO or Siro, shutters
openend is 0, shutters closed is 100), 2 with devices whose state is given as percent closed (i.e. HomeMatic,
shutters opened is 100, closed is 0).
After setting the attributes to all devices who should be controlled, the automatic scan at the main device
can be started for example with set myASControl scanForShutters
Readings
Within the ASC device:
..._nextAstroTimeEvent - Next astro event: sunrise, sunset or fixed time
..._PosValue - current position
..._lastPosValue - shutters last position
..._lastDelayPosValue - last specified order, will be executed with the next matching
event
partyMode on|off - is working mode set to part?y
ascEnable on|off - are the associated shutters control by ASC completely?
controlShading on|off - are the associated shutters controlled for shading by ASC?
hardLockOut on|off - switch for preventing a global hard lock out
room_... - list of every found shutter for every room: room_Sleeping: Patio
selfDefense - state of the self defense mode
state - state of the ASC device: active, enabled, disabled or other state information
sunriseTimeWeHoliday on|off - state of the weekend and holiday support
userAttrList - ASC sets some user defined attributes (userattr)
for the shutter devices. This readings shows the current state of the given user attributes to the
shutter devices.
Within the shutter devices:
ASC_Enable on|off - shutter is controlled by ASC or not
ASC_Time_DriveUp - if the astro mode is used, the next sunrise is shown.
If the brightness or time mode is used, the value from ASC_Time_Up_Late is shown.
ASC_Time_DriveDown - if the astro mode is used, the next sunset is shown.
If the brightness or time mode is used, the value from ASC_TASC_Time_Down_Late is
shown.
ASC_ShuttersLastDrive - initiator for the last action
Set
advDriveDown - execute all moves delayed by ASC_Adv on.
ascEnable on|off - enable or disable the global control by ASC
controlShading on|off - enable or disable the global shading control by ASC
createNewNotifyDev - re-creates the internal structure for NOTIFYDEV. Is only present if
the
ASC_Expert attribute is set to 1.
hardLockOut on|off -
hardLockOut - on/off - Aktiviert den hardwareseitigen Aussperrschutz für die Rollläden, bei denen das Attributs ASC_LockOut entsprechend auf hard gesetzt ist. Mehr Informationen in der Beschreibung bei den Attributen für die Rollladengeräten.
partyMode on|off - controls the global party mode for shutters. Every shutters whose
ASC_Partymode attribute is set to on, is not longer controlled by ASC. The last saved
working command send to the device, i.e. by a event, created by a window or presence event, will be executed
once the party mode is disabled.
renewTimer - resets the sunrise and sunset timers for selected shutter
device and creates new internal FHEM timers.
renewAllTimer - resets the sunrise and sunset timers for all shutter
device and creates new internal FHEM timers.
scanForShutters - scans the whole FHEM installation for (new) devices whose ASC
attribute is set (to 1 or 2, see above).
selfDefense on|off - controls the self defense function. This function listens for
example on a residents device. If this device is set to absent and a window is still open, ASC will close
the shutter for a rudimentary burglary protection.
shutterASCenableToggle on|off - controls if the ASC controls are shown at a associated
shutter device.
sunriseTimeWeHoliday on|off - controls the weekend and holiday support. If enabled, the
ASC_Time_Up_WE_Holiday attribute is considered.
wiggle - wiggles a device for a given value (default 5%, controlled by
ASC_WiggleValue) up or down and back after a minute. Useful as a deterrence in combination with
alarm system.
Get
showNotifyDevsInformations - shows the generated NOTIFYDEV structure. Useful for
debugging and only shown if the ASC_expert attribute is set to 1.
Attributes
At the global ASC device:
ASC_autoAstroModeEvening - REAL, CIVIL, NAUTIC, ASTRONOMIC or HORIZON
ASC_autoAstroModeEveningHorizon - Height above the horizon. Is only considered
if the ASC_autoAstroModeEvening attribute is set to HORIZON. Defaults to 0.
ASC_autoAstroModeMorning - REAL, CIVIL, NAUTIC, ASTRONOMIC or HORIZON
ASC_autoAstroModeMorningHorizon - Height above the horizon. Is only considered
if the ASC_autoAstroModeMorning attribute is set to HORIZON. Defaults to 0.
ASC_autoShuttersControlComfort - on|off -
Controls the comfort functions: If a three state sensor, like the HmIP-SRH window handle
sensor, is installed, ASC will open the window if the sensor signals open position. The
ASC_ComfortOpen_Pos attribute has to be set for the shutter to on, defaults to off.
ASC_autoShuttersControlEvening - on|off - Enables the automatic control by ASC
at the evenings.
ASC_autoShuttersControlMorning - on|off - Enables the automatic control by ASC
at the mornings.
ASC_blockAscDrivesAfterManual 0|1 - If set to 1, ASC will not
automatically control a shutter if there was an manual control to the shutter. To be considered, the
ASC_ShuttersLastDrive reading has to contain the value manual and the shutter is in
an unknown (i.e. not otherwise configured in ASC) position.
ASC_brightnessDriveUpDown - VALUE-MORNING:VALUE-EVENING - Drive the shutters by
brightness. VALUE-MORNING sets the brightness threshold for the morning. If the value is
reached in the morning, the shutter will go up. Vice versa in the evening. This is a global setting
and can be overwritte per device with the ASC_BrightnessSensor attribute (see below).
ASC_debug -
Extendend logging for debugging purposes
ASC_expert - Switches the export mode on. Currently, if set to 1, get
and set will contain additional functions regarding the NOTIFYDEFs.
ASC_freezeTemp - Temperature threshold for the freeze protection. The freeze protection
prevents the shutter to be operated by ASC. Last operating order will be kept.
ASC_advStartDate - Begin of Advent Season, selected FirstAdvent or DeadSunday.
ASC_advEndDate - End of Advent Season, selected CandlemasDay 6. January or EpiphanyDay 2. February.
ASC_rainSensor DEVICENAME[:READINGNAME] MAXTRIGGER[:HYSTERESE] [CLOSEDPOS] - Contains
settings for the rain protection. DEVICNAME specifies a rain sensor, the optional
READINGNAME the name of the reading at the DEVICENAME. The READINGNAME
should contain the values rain and dry or a numeral rain amount. MAXTRIGGER
sets the threshold for the amount of rain for when the shutter is driven to CLOSEDPOS as soon
the threshold is reached. HYSTERESE sets a hysteresis for MAXTRIGGER.
ASC_residentsDev DEVICENAME[:READINGNAME] - DEVICENAME points to a device
for presence, e.g. of type RESIDENTS. READINGNAME points to a reading at
DEVICENAME which contains a presence state, e.g. rgr_Residents:state. The target
should contain values alike the RESIDENTS family.
ASC_shuttersDriveDelay - Maximum random drive delay in seconds for calculating
the operating time. 0 equals to no delay.
ASC_TempSensor DEVICENAME[:READINGNAME] - DEVICENAME points to a device
with a temperature, READINGNAME to a reading located at the DEVICENAME, for example
OUTDOOR_TEMP:measured-temp. READINGNAME defaults to temperature.
ASC_twilightDevice - points to a DEVICENAME containing values regarding
the sun position. Supports currently devices of type Twilight or Astro.
ASC_windSensor DEVICENAME[:READINGNAME] - DEVICENAME points to a device
containing a wind speed. Reads from the wind reading, if not otherwise specified by
READINGNAME.
At shutter devices, controlled by ASC:
ASC - 0|1|2
0 - don't create attributes for ASC at the first scan and don't be controlled
by ASC
1 - inverse or venetian type blind mode. Shutter is open equals to 0, shutter is closed equals
to 100, is controlled by position values.
2 - HomeMatic mode. Shutter is open equals to 100, shutter is closed equals to 0, is
controlled by pct values.
hard / am / pm - freeze protection will be active (everytime,
ante meridiem or post meridiem).
off - freeze protection is disabled, default value
ASC_Antifreeze_Pos - Position to be operated if the shutter should be closed,
but ASC_Antifreeze is not set to off. (Default: dependent on attributASC 85/15).
ASC_AutoAstroModeEvening - Can be set to REAL, CIVIL,
NAUTIC, ASTRONOMIC or HORIZON. Defaults to none of those.
ASC_AutoAstroModeEveningHorizon - If this value is reached by the sun, a sunset is
presumed. Is used if ASC_autoAstroModeEvening is set to HORIZON. Defaults to none.
ASC_AutoAstroModeMorning - Can be set to REAL, CIVIL,
NAUTIC, ASTRONOMIC or HORIZON. Defaults to none of those.
ASC_AutoAstroModeMorningHorizon - If this value is reached by the sun, a sunrise is
presumed. Is used if ASC_AutoAstroModeMorning is set to HORIZON. Defaults to none.
ASC_Shutter_IdleDetection - indicates the Reading which gives information about the running status of the roller blind, as well as secondly the value in the Reading which says that the roller blind does not run.
ASC_BlockingTime_afterManual - Time in which operations by ASC are blocked
after the last manual operation in seconds. Defaults to 1200 (20 minutes).
ASC_BlockingTime_beforDayOpen - Time in which no closing operation is made by
ASC after opening at the morning in seconds. Defaults to 3600 (one hour).
ASC_BlockingTime_beforNightClose - Time in which no closing operation is made by
ASC before closing at the evening in seconds. Defaults to 3600 (one hour).
ASC_BrightnessSensor - DEVICE[:READING] MORNING-VALUE:EVENING-VALUE -
Drive this shutter by brightness. MORNING-VALUE sets the brightness threshold for the morning.
If the value is reached in the morning, the shutter will go up. Vice versa in the evening, specified by
EVENING-VALUE. Gets the brightness from DEVICE, reads by default from the
brightness reading, unless READING is specified. Defaults to none.
ASC_Closed_Pos - The closed position value from 0 to 100 percent in increments of 10.
(Default: dependent on attributASC 100/0).
ASC_ComfortOpen_Pos - The comfort opening position, ranging
from 0 to 100 percent in increments of 10. (Default: dependent on attributASC 20/80).
ASC_Down - astro|time|brightness|roommate - Drive the shutter depending on this setting:
astro - drive down at sunset
time - drive at ASC_Time_Down_Early
brightness - drive between ASC_Time_Down_Early and ASC_Time_Down_Late,
depending on the settings of ASC_BrightnessSensor (see above).
roommate - no drive by time or brightness, roommate trigger only
Defaults to astro.
ASC_DriveUpMaxDuration - Drive up duration of the shutter plus 5 seconds. Defaults
to 60 seconds if not set.
ASC_Drive_Delay - maximum value for a random delay (in seconds) to add to the calculated drive times. (needs also ASC_Drive_DelayStart to be set!)
ASC_Drive_DelayStart - delay in seconds to add to each calculated drive time.
ASC_LockOut soft|hard|off - Configures the lock out protection for the current
shutter. Values are:
soft - works if the global lock out protection lockOut soft is set and a sensor
specified by ASC_WindowRec is set. If the sensor is set to open, the shutter will not
be closed. Affects only commands issued by ASC.
hard - see soft, but ASC tries also to block manual issued commands by a switch.
off - lock out protection is disabled. Default.
ASC_LockOut_Cmd inhibit|blocked|protection - Configures the lock out command for
ASC_LockOut if hard is chosen as a value. Defaults to none.
ASC_Mode_Down always|home|absent|off - When will a shutter be driven down:
always - ASC will drive always. Default value.
off - don't drive
home / absent - considers a residents status set by ASC_residentsDev. If no
resident is configured and this attribute is set to absent, ASC will not
operate the shutter.
ASC_Mode_Up always|home|absent|off - When will a shutter be driven up:
always - ASC will drive always. Default value.
off - don't drive
home / absent - considers a residents status set by ASC_residentsDev. If no
resident is configured and this attribute is set to absent, ASC will not
operate the shutter.
ASC_Open_Pos - The opening position value from 0 to 100 percent in increments of 10.
(Default: dependent on attributASC 0/100).
ASC_Sleep_Pos - The opening position value from 0 to 100 percent in increments of 10.
(Default: dependent on attributASC 75/25).
ASC_Partymode on|off - Party mode. If configured to on, driving orders for the
shutter by ASC will be queued if partyMode is set to on at the
global ASC device. Will execute the driving orders after partyMode is disabled.
Defaults to off.
ASC_Pos_Reading - Points to the reading name, which contains the current
position for the shutter in percent. Will be used for set at devices of unknown kind.
ASC_PrivacyDownValue_beforeNightClose - How many seconds is the privacy mode activated
before the shutter is closed in the evening. For Brightness, in addition to the time value,
the Brightness value must also be specified. 1800:300 means 30 min before night close or above a brightness
value of 300. -1 is the default
value.
ASC_PrivacyDown_Pos -
Position in percent for privacy mode, defaults to 50.
ASC_PrivacyUpValue_beforeDayOpen - How many seconds is the privacy mode activated
before the shutter is open in the morning. For Brightness, in addition to the time value,
the Brightness value must also be specified. 1800:600 means 30 min before day open or above a brightness
value of 600. -1 is the default
value.
ASC_PrivacyUp_Pos -
Position in percent for privacy mode, defaults to 50.
ASC_ExternalTrigger - DEVICE:READING VALUEACTIVE:VALUEINACTIVE POSACTIVE:[POSINACTIVE VALUEACTIVE2:POSACTIVE2], example: setting to "WohnzimmerTV:state on:off 66:100" will cause a "state:on" event to drive the shutter to position 66. "state:off" event will set it to position 100. If no POSINACTIVE is set, LastStatus position will be used as target position.
ASC_WindProtection on|off - Shutter is protected by the wind protection. Defaults
to off.
ASC_RainProtection on|off - Shutter is protected by the rain protection. Defaults
to off.
ASC_Roommate_Device - Comma separated list of ROOMMATE devices, representing
the inhabitants of the room to which the shutter belongs. Especially useful for bedrooms. Defaults
to none.
ASC_Roommate_Reading - Specifies a reading name to ASC_Roommate_Device.
Defaults to state.
ASC_Adv - on/off If on, from 1. advent to 6. January all closing commands will be delayed until set ASCDEVICE advDriveDown is issued.
ASC_Self_Defense_Mode - absent/gone/off - which Residents status Self Defense should become
active without the window being open. (default: gone) off exclude from self defense
ASC_Self_Defense_AbsentDelay - time in seconds to wait after Residents went gone. (default: 300)
ASC_ShuttersPlace window|terrace - If set to terrace, and the
residents device is set to gone, and selfDefense is activated, the shutter will
be closed. If set to window, will not. Defaults to window.
ASC_Time_Down_Early - Will not drive before time is ASC_Time_Down_Early
or later, even the sunset occurs earlier. To be set in military time. Defaults to 16:00.
ASC_Time_Down_Late - Will not drive after time is ASC_Time_Down_Late
or earlier, even the sunset occurs later. To be set in military time. Defaults to 22:00.
ASC_Time_Up_Early - Will not drive before time is ASC_Time_Up_Early
or earlier, even the sunrise occurs earlier. To be set in military time. Defaults to 05:00.
ASC_Time_Up_Late - Will not drive after time is ASC_Time_Up_Late
or earlier, even the sunrise occurs later. To be set in military time. Defaults to 08:30.
ASC_Time_Up_WE_Holiday - Will not drive before time is ASC_Time_Up_WE_Holiday
on weekends and holidays (holiday2we is considered). Defaults to 08:00. Warning!
If ASC_Up set to brightness, the time for ASC_Time_Up_WE_Holiday
must be earlier then ASC_Time_Up_Late.
ASC_Up astro|time|brightness|roommate - Drive the shutter depending on this setting:
astro - drive up at sunrise
time - drive at ASC_Time_Up_Early
brightness - drive between ASC_Time_Up_Early and ASC_Time_Up_Late,
depending on the settings of ASC_BrightnessSensor (see above).
roommate - no drive by time or brightness, roommate trigger only
Defaults to astro.
ASC_Ventilate_Pos - The opening position value for ventilation
from 0 to 100 percent in increments of 10. (Default: dependent on attributASC 70/30).
ASC_Ventilate_Window_Open on|off - Drive to ventilation position as window is opened
or tilted, even when the current shutter position is lower than the ASC_Ventilate_Pos.
Defaults to on.
ASC_WiggleValue - How many percent should the shutter be driven if a wiggle drive
is operated. Defaults to 5.
ASC_WindParameters THRESHOLD-ON[:THRESHOLD-OFF] [DRIVEPOSITION] -
Threshold for when the shutter is driven to the wind protection position. Optional
THRESHOLD-OFF sets the complementary value when the wind protection is disabled. Disabled
if THRESHOLD-ON is set to -1. Defaults to 50:20 ASC_Closed_Pos.
ASC_WindowRec - WINDOWREC:[READING], Points to the window contact device, associated with the shutter.
Defaults to none. Reading is optional
ASC_WindowRec_subType - Model type of the used ASC_WindowRec:
twostate - optical or magnetical sensors with two states: opened or closed
threestate - sensors with three states: opened, tilted, closed
Defaults to twostate.
ASC_SlatPosCmd_SlatDevice - If your shutter is "venetian blind" type (with turnable slats, lamellas or similar), this is the place to set additional command and/or device info to control the slat level. Examples: attr ROLLO ASC_SlatPosCmd_SlatDevice slatPct or attr ROLLO ASC_SlatPosCmd_SlatDevice dim:ROLLOSLATDEVICE. Providing a device name for the slat device is only needed in case it's different to the shutter itself. If attribute is set, additional positioning values for the respective slat levels can be set in attributes ASC_Open_Pos, ASC_Closed_Pos, ASC_Ventilate_Pos, ASC_ComfortOpen_Pos, ASC_Shading_Pos and ASC_Sleep_Pos.
ASC_CommandTemplate - FHEM or Perl command (Perl in braces as usual needs escaping semicolons etc.).
This optional attribute will override the internally determined command to drive this shutter. Setting it, is only recommended in some rare and special cases,, in most cases there's no need to set this attribute!
The parameters $name (name of the shutter device), $pos (target position for the respective drive command), $slatPos (target position for the (turnable) lammellas in venetion blinds) and $cause (internal label for the cause of the driving command) will be replaced by the appropirate values. You may have to take care to avoid unneeded driving commands.
Examples:
attr ROLLO ASC_CommandTemplate set $name $pos - Address the position command directly to the main switch of the device
attr ROLLO ASC_CommandTemplate set $name pct $pos - Address the setter pct for positioning commands
attr ROLLO ASC_CommandTemplate set $name datapoint 4.LEVEL_2 $slatPos 4.LEVEL $pos - combined positioning command, e.g. appropriate for HM-IP-venetian blind type actors
attr ROLLO ASC_CommandTemplate { fhem("set $name ".($pos+1024)).";set $name 0")} - positioning command with Perl calculation and additional "execute" command, e.g. for an SPS type blind
attr ROLLO ASC_CommandTemplate { myPerlFn("$name",$pos,$slatPos,"$cause")} - call own Perl function (e.g. from 99_myUtils.pm)
ASC_WindowRec_PosAfterDayClosed - open,lastManual / auf welche Position soll das Rollo nach dem schließen am Tag fahren. Open Position oder letzte gespeicherte manuelle Position (default: open)
Shading
Shading is only available if the following prerequests are met:
The controlShading reading is set to on, and there is a device
of type Astro or Twilight configured to ASC_twilightDevice, and ASC_TempSensor
is set.
ASC_BrightnessSensor is configured to any shutter device.
All other attributes are optional and the default value for them is used, if they are not
otherwise configured. Please review the settings carefully, especially the values for
StateChange_Cloudy and StateChange_Sunny.
The following attributes are available:
ASC_Shading_InOutAzimuth - Azimuth value from which shading is to be used when shading is exceeded and shading when undershooting is required.
Defaults to 95:265.
ASC_Shading_MinMax_Elevation - Shading starts as min point of sun elevation is
reached and end as max point of sun elevation is reached, depending also on other sensor values. Defaults to 25.0:100.0.
ASC_Shading_Min_OutsideTemperature - Shading starts at this outdoor temperature,
depending also on other sensor values. Defaults to 18.0.
ASC_Shading_Mode absent|always|off|home - see ASC_Mode_Down above,
but for shading. Defaults to off.
ASC_Shading_Pos - Shading position in percent. (Default: dependent on attribute ASC 85/15)
ASC_Shading_StateChange_Cloudy - Shading ends at this
outdoor brightness, depending also on other sensor values. Defaults to 20000.
ASC_Shading_StateChange_SunnyCloudy - Shading starts/stops at this
outdoor brightness, depending also on other sensor values. An optional parameter specifies how many successive brightness reading values should be used to average the brightness value. Defaults to 35000:20000 [3].
ASC_Shading_WaitingPeriod - Waiting time in seconds before additional sensor values
to ASC_Shading_StateChange_Sunny or ASC_Shading_StateChange_Cloudy
are used for shading. Defaults to 120.
ASC_Shading_BetweenTheTime - Limit the time slots for shading functionality. Example: 09:00-13:00 11:25-15:30
AutoShuttersControl API description
It's possible to access internal data of the ASC module by calling the API function.
Data points of a shutter device, controlled by ASC
{ ascAPIget('Getter','SHUTTERS_DEVICENAME') }
Getter
Description
FreezeStatus
1 = soft, 2 = daytime, 3 = hard
NoDelay
Was the offset handling deactivated (e.g. by operations triggered by a window event)
LastDrive
Reason for the last action caused by ASC
LastPos
Last position of the shutter
LastPosTimestamp
Timestamp of the last position
LastManPos
Last position manually set of the shutter
LastManPosTimestamp
Timestamp of the last position manually set
SunsetUnixTime
Calculated sunset time in seconds since the UNIX epoche
Sunset
1 = operation in the evening was made, 0 = operation in the evening was not yet made
SunriseUnixTime
Calculated sunrise time in seconds since the UNIX epoche
Sunrise
1 = operation in the morning was made, 0 = operation in the morning was not yet made
RoommatesStatus
Current state of the room mate set for this shutter
RoommatesLastStatus
Last state of the room mate set for this shutter
ShadingStatus
Value of the current shading state. Can hold in, out, in reserved or
out reserved
ShadingStatusTimestamp
Timestamp of the last shading state
IfInShading
Is the shutter currently in shading (depends on the shading mode)
WindProtectionStatus
Current state of the wind protection. Can hold protection or unprotection
RainProtectionStatus
Current state of the rain protection. Can hold protection or unprotection
DelayCmd
Last operation order in the waiting queue. Set for example by the party mode
Status
Position of the shutter
ASCenable
Does ASC control the shutter?
PrivacyDownStatus
Is the shutter currently in privacyDown mode
outTemp
Current temperature of a configured temperature device, return -100 is no device configured
Übersicht für das Rollladen-Device mit Parameterübergabe
{ ascAPIget('Getter','ROLLODEVICENAME',VALUE) }
Getter
Erläuterung
QueryShuttersPos
Rückgabewert 1 bedeutet das die aktuelle Position des Rollos unterhalb der Valueposition ist. 0 oder nichts bedeutet oberhalb der Valueposition.
Data points of the ASC device
{ ascAPIget('Getter') }
Getter
Description
OutTemp
Current temperature of a configured temperature device, return -100 is no device configured
This module allows the communication between the Husqvarna Cloud and FHEM to control Husqvarna Automower equipped with a Connect Module (SIM).
It acts as Device for one mower. Use this Module for aditional mower registered in the API. Provide a different application key and application secret each mower
The mower path is shown in the detail view.
An arbitrary map can be used as background for the mower path.
The map has to be a raster image in webp, png or jpg format.
The property limits can be registered manually.
The mowing area limits can be registered manually.
The mowing area limits can be calculated, alternatively.
It's possible to control everything the API offers, e.g. schedule, headlight, cutting height and actions like start, pause, park etc.
Zones are definable.
Cutting height can be set for each zone differently.
All API data is stored in the device hash. Use {Dumper $defs{<name>}} in the commandline to find the data and build userReadings out of it.
Requirements
To get access to the API an application has to be created in the Husqvarna Developer Portal. The application has to be connected with the AutomowerConnect API.
During registration an application key (client_id) and an application secret (client secret) is provided. Use these for the module.
The module uses client credentials as grant type for authorization.
The module downloads third party software from external server necessary to calculate the hull of mowing area.
Define
define <device name> AutomowerConnect <application key> [<mower number>]
Example: define myMower AutomowerConnect 123456789012345678901234567890123456 First device: the default mower number is 0.
It has to be set a client_secret. It's the application secret from the Husqvarna Developer Portal. set myMower <client secret>
Hints
The available setter, attributes, Readings and and the map depend on the mower capabilities ( cutting height, headlights, position, stay out zones, work areas ).
Button
Mower Schedule
The Button opens GUI to maintain the mower schedule..
Add/change entry: fill out the schedule fields and press .
Delete entry: unselect each weekday and press .
Reset entry: fill any time field with -- and press .
Set
Park set <name> Park <number of minutes>
Parks mower in charging station for <number of minutes>
ParkUntilFurtherNotice set <name> ParkUntilFurtherNotice
Parks mower in charging station until further notice
ParkUntilNextSchedule set <name> ParkUntilNextSchedule
Parks mower in charging station and starts with next planned start
Pause set <name> Pause
Pauses mower immediately at current position
ResumeSchedule set <name> ResumeSchedule
Starts immediately if in planned intervall, otherwise with next scheduled start>
Start set <name> Start <number of minutes>
Starts immediately for <number of minutes>
dateTime set <name> dateTime <timestamp / s>
Syncronize the mower time to timestamp. The default (empty Input field) timestamp is for local time of the machine the mower is defined, see also mowerAutoSyncTime.
confirmError set <name> confirmError
Testing: Confirm current error on the mower. Will only work if current error is considered confirmable by the mower. Available for models 405X, 415X, 435X AWD and 535 AWD. Also available on all Ceora, EPOS and NERA models.
StartInWorkArea set <name> StartInWorkArea <workAreaId|name> [<number of minutes>]
Testing: Starts immediately in <workAreaId|name> for <number of minutes>.
If <number of minutes> is empty or 0 is selected in the widget the mower will continue forever.
Work area name must not include space.
chargingStationPositionToAttribute set <name> chargingStationPositionToAttribute
Sets the calculated charging station coordinates to the corresponding attributes.
client_secret set <name> client_secret <application secret>
Sets the mandatory application secret (client secret)
cuttingHeight set <name> cuttingHeight <1..9>
Sets the cutting height. NOTE: Do not use for 550 EPOS and Ceora.
resetCuttingBladeUsageTime set <name> resetCuttingBladeUsageTime
Resets the cutting blade usage time if the mower provides it.
cuttingHeightInWorkArea set <name> cuttingHeightInWorkArea <Id|name> <0..100>
Testing: Sets the cutting height for Id or zone name from 0 to 100. Zone name must not include space and contain at least one alphabetic character.
stayOutZone set <name> stayOutZone <Id|name> <enable|disable>
Testing: Enables or disables stay out zone by Id or zone name. Zone name must not include space and contain at least one alphabetic character.
getNewAccessToken set <name> getNewAccessToken
For debug purpose only.
getUpdate set <name> getUpdate
For debug purpose only.
html get <name> html
Returns the mower area image as html code. For use in uiTable, TabletUI, Floorplan, readingsGroup, weblink etc.
InternalData get <name> InternalData
Lists some device internal data
MowerData get <name> MowerData
Lists all mower data with its hash path exept positon array. The hash path can be used for generating userReadings. The trigger is e.g. device_state: connected or mower_wsEvent: <status-event|positions-event|settings-event>.
Example: created reading serialnumber with hash path $hash->{helper}{mower}{attributes}{system}{serialNumber}
StatisticsData get <name> StatisticsData
Lists statistics data with its hash path. The hash path can be used for generating userReadings. The trigger is e.g. device_state: connected or mower_wsEvent: <status-event|positions-event|settings-event>.
errorCodes get <name> errorCodes
Lists API response status codes and mower error codes
errorStack get <name> errorStack
Lists error stack and messages, see also getMessages.
Attributes
mapImagePath attr <name> mapImagePath <path to image>
Path of a raster image file for an area the mower path has to be drawn to.
If the image name implies the image size by containing a part which matches /(\d+)x(\d+)/
the corresponding attribute will be set to mapImageWidthHeight = '$1 $2'
Image name example: map740x1300.webp
mapImageWidthHeight attr <name> mapImageWidthHeight <width in pixel><separator><height in pixel>
Width and Height in pixel of a raster image file for an area image the mower path has to be drawn to. <separator> is one space character.
mapImageZoom attr <name> mapImageZoom <zoom factor>
Zoom of a raster image for an area the mower path has to be drawn to.
mapBackgroundColor attr <name> mapBackgroundColor <background-color>
The value is used as background-color.
mapDesignAttributes attr <name> mapDesignAttributes <complete list of design-attributes>
Load the list of attributes by set <name> defaultDesignAttributesToAttribute to change its values. Design attributes with changed default values are mandatory in this attribute.
Default values:
mapImageCoordinatesToRegister attr <name> mapImageCoordinatesToRegister <upper left longitude><space><upper left latitude><line feed><lower right longitude><space><lower right latitude>
Upper left and lower right coordinates to register (or to fit to earth) the image. Format: linewise longitude and latitude values separated by 1 space.
The lines are splitted by (/\s|\R$/). Use WGS84 (GPS) coordinates in decimal degree notation.
mapImageCoordinatesUTM attr <name> mapImageCoordinatesUTM <upper left longitude><space><upper left latitude><line feed><lower right longitude><space><lower right latitude>
Upper left and lower right coordinates to register (or to fit to earth) the image. Format: linewise longitude and latitude values separated by 1 space.
The lines are splitted by (/\s|\R$/). Use UTM coordinates in meter notation.
This attribute has to be set after the attribute mapImageCoordinatesToRegister. The values are used to calculate the scale factors and the attribute scaleToMeterXY is set accordingly.
showMap attr <name> showMap <1,0>
Shows Map on (1 default) or not (0).
mowerAutoSyncTime attr <name> mowerAutoSyncTime <0,1>
Synchronizes mower time if DST changes, on (1) or not (0 default).
chargingStationCoordinates attr <name> chargingStationCoordinates <longitude><separator><latitude>
Longitude and latitude of the charging station. Use WGS84 (GPS) coordinates in decimal degree notation. <separator> is one space character
chargingStationImagePosition attr <name> chargingStationImagePosition <right, bottom, left, top, center>
Position of the charging station image relative to its coordinates.
mowerCuttingWidth attr <name> mowerCuttingWidth <cutting width>
mower cutting width in meter to calculate the mowed area. default: 0.24
mowerSchedule attr <name> mowerSchedule <schedule array>
This attribute provides the possebility to edit the mower schedule in form of an JSON array. The actual schedule can be loaded with the command set <name> mowerScheduleToAttribute. The command set <name> sendScheduleFromAttributeToMower sends the schedule to the mower. The maximum of array elements is 14 and 2 each day, so every day of a week can have 2 time spans. Each array element consists of 7 day values (monday to sunday) which can be true or false, a start and duration value in minutes. Start time counts from midnight. NOTE: Do not use for 550 EPOS and Ceora. Delete the attribute after the schedule is successfully uploaded.
mowingAreaLimits attr <name> mowingAreaLimits <positions list>
List of position describing the area to mow. Format: linewise longitude and latitude values separated by 1 space. The lines are splitted by (/\s|\R$/). The position values could be taken from Google Earth KML file, but whithout the altitude values.
propertyLimits attr <name> propertyLimits <positions list>
List of position describing the property limits. Format: linewise of longitude and latitude values separated by 1 space. The lines are splitted by (/\s|\R$/).The position values could be taken from . For converting UTM32 meter to ETRS89 / WGS84 decimal degree you can use the BKG-Geodatenzentrum BKG-Geodatenzentrum.
numberOfWayPointsToDisplay attr <name> numberOfWayPointsToDisplay <number of way points>
Set the number of way points stored and displayed, default is 5000 at least 100. The way points are shifted through the dedicated stack.
weekdaysToResetWayPoints attr <name> weekdaysToResetWayPoints <any combination of weekday numbers, space or minus [0123456 -]>
A combination of weekday numbers when the way point stack will be reset. No reset for space or minus. Default 1.
scaleToMeterXY attr <name> scaleToMeterXY <scale factor longitude><seperator><scale factor latitude>
The scale factor depends from the Location on earth, so it has to be calculated for short ranges only. <seperator> is one space character.
Longitude: (LongitudeMeter_1 - LongitudeMeter_2) / (LongitudeDegree_1 - LongitudeDegree _2)
Latitude: (LatitudeMeter_1 - LatitudeMeter_2) / (LatitudeDegree_1 - LatitudeDegree _2)
mapZones attr <name> mapZones <valid perl condition to separate Zones>
These Zones are provided by the Modul and are not related to Husqvarnas work areas.
Provide the zones with conditions as JSON-String:
The waypoints are accessable by the variables $longitude und $latitude.
Zones have have to be separated by conditions in alphabetical order of their names.
The last zone is determined by the remaining waypoints.
Syntactical example:
'{
"<name_1>" : {
"condition" : "<condition to separate name_1 from other zones>",
"cuttingHeight" : "<cutting height for the first zone>"
},
"<name_2>" : {
"condition" : "<condition to separate name_2 from other zones, except name_1>",
"cuttingHeight" : "<cutting height for the second zone>"
},
"<name_3>" : {
"condition" : "<condition to separate name_3 from other zones, except name_1 and name_2>",
"cuttingHeight" : "<cutting height for the third zone>"
},
"<name_n-1>" : {
"condition" : "<condition to separate name_n-1 from other zones ,except the zones already seperated>",
"cuttingHeight" : "<cutting height for the nth-1 zone>"
},
"<name n>" : {
"condition" : "Use 'undef' because the last zone remains.",
"cuttingHeight" : "<cutting height for the nth zone>"
}
}'
Example with two Zones and virtual lines defined by latitude 52.6484600648553, 52.64839739580418 (horizontal) and longitude 9.54799477359984 (vertikal). all way points above 52.6484600648553 or all way points above 52.64839739580418 and all way points to the right of 9.54799477359984 belong to zone 01_oben. All other way points belong to zone 02_unten.
There are different cutting heightts each zone
'{
"01_oben" : {
"condition" : "$latitude > 52.6484600648553 || $longitude > 9.54799477359984 && $latitude > 52.64839739580418",
"cuttingHeight" : "7"
},
"02_unten" : {
"condition" : "undef",
"cuttingHeight" : "3"
}
}'
addPollingMinInterval attr <name> addPollingMinInterval <interval in seconds>
Set minimum intervall for additional polling triggered by status-event, default 0 (no polling). Gets periodically statistics data from mower. Make sure to be within API limits (10000 calls per month).
addPositionPolling attr <name> addPositionPolling <[1|0]>
Set position polling, default 0 (no position polling). Gets periodically position data from mower, instead from websocket. It has no effect without setting attribute addPollingMinInterval.
mowingAreaHull attr <name> mowingAreaHull <use button 'mowingAreaHullToAttribute' to fill the attribute>
Contains the calculated hull coordinates as JSON string and is set by button 'mowingAreaHullToAttribute' under the dislpayed map.
The stored hull polygon is displayed like the other limits.
Use the design attribute 'hullResolution' to change the number of fractions ℕ .
The hull polygon is calculated when the design attribut is set to 1 hullCalculate="1" and there are more than 50 Points for activity MOWING.
The calculation is done only after site reload.
The calculation of hull is stopped when the attribute ist set and starts again when attribute is deleted.
The attribute weekdaysToResetWayPoints should be set to - and also the design attribute mowingPathUseDots should be set to "1" until the hull is sufficient.
If there is a polygon in attribute, it can be changed.
The design attribute hullSubtract can be set to a natural number {ℕ}, it depicts the recursion depth in which polygon points removed from way points.
This reduces spikes in border region. hullSubtract="" removes the button 'Subtract Hull'.
mowerPanel attr <name> mowerPanel <html code>
Shows user defined html beneath the map. usefull for a panel with shortcuts
The command attribute has to contain the mower command, without set <name> command="Start 210" stands for set <name> Start 210
A directive as comment in the first line allows positioning.
<!-- ON_TOP --> shows html above map
Panel has to be enclosed by a div-tag with a mandatory HTML-attribute data-amc_panel_inroom=<"1"|"">. Panel is shown in room view, i.e. for uiTable, weblink, etc., for value "1" and hidden for value "" look at example.
Example:
<style>
.amc_panel_button {height:50px; width:150px;}
.amc_panel_div {position:relative; left:348px; top:-330px; z-index: 2; width:150px; height:1px}
</style>
<div class="amc_panel_div" data-amc_panel_inroom="1" >
<button class="amc_panel_button" command="Start 210" >Start für 3 1/2 h</button>
<button class="amc_panel_button" command="Pause" >Pause bis auf Weiteres</button>
<button class="amc_panel_button" command="ResumeSchedule" >Weiter nach Plan</button>
<button class="amc_panel_button" command="ParkUntilNextSchedule" >Parken bis nächsten Termin</button>
<button class="amc_panel_button" command="ParkUntilNextSchedule" >Parken bis auf Weiteres</button>
</div>
BDKM is a module supporting Buderus Logamatic KM gateways similar
to the km200 module. For installation of the
gateway see fhem km200 internet wiki
Compared with the km200 module the code of the BDKM module is more
compact and has some extra features. It has the ablility to
define how often a gateway ID is polled, which FHEM reading
(alias) is generated for a gateway ID and which minimum difference
to the last reading must exist to generate a new reading (see
attributes).
It determines value ranges, allowed values and writeability from
the gateway supporting FHEMWEB and readingsGroup when setting
Values (drop down value menues).
On definition of a BDKM device the gateway is connected and a full
poll collecting all IDs is done. This takes about 20 to 30
seconds. After that the module knows all IDs reported
by the gateway. To examine these IDs just type: get myBDKM INFO
These IDs can be used with the PollIds attribute to define if and
how the IDs are read during the poll cycle. All IDs can be
mapped to own short readings.
<name> :
Name of device <IP-address> :
The IP adress of your Buderus gateway <GatewayPassword> :
The gateway password as printed on case of the gateway s.th.
of the form: xxxx-xxxx-xxxx-xxxx <PrivatePassword> : The private password as
set with the buderus App <MD5-Salt> : MD5 salt for the crypt
algorithm you want to use (hex string like 867845e9.....). Have a look for km200 salt 86 ...
AES-Key can be generated here:
https://ssl-account.com/km200.andreashahn.info
Set
set <name> <ID> <value> ...
where ID is a valid writeable gateway ID (See list command,
or "get myBDKM INFO")
The set command first reads the the ID from the gateway and also
triggers a FHEM readings if necessary. After that it is checked if the
value is valid. Then the ID and value(s) are transfered to to the
gateway. After waiting (attr ReadBackDelay milliseconds) the value
is read back and checked against value to be set. If necessary again
a FHEM reading may be triggered. The read back value or an error is
returned by the command.
Examples:
set myBDKM /heatingCircuits/hc1/temporaryRoomSetpoint 22.0
or the aliased version of it (if
/heatingCircuits/hc1/temporaryRoomSetpointee is aliased to
RoomTemporaryDesiredTemp): set myBDKM RoomTemporaryDesiredTemp 22.0
special to set time of gateway to the hosts date: set myBDKM /gateway/DateTime now
aliased: set myBDKM DateTime now
Get
get <name> <ID> <[raw|json]>...
where ID is a valid gateway ID or an alias to it.
(See list command) The get command reads the the ID from the
gateway, triggeres readings if necessarry, and returns the value
or an error if s.th. went wrong. While polling is done
asychronously with a non blocking HTTP GET. The set and get
functions use a blocking HTTP GET/POST to be able to return a
value directly to the user. Normaly get and set are only used by
command line or when setting values via web interface.
With the raw option the whole original decoded data of the
ID (as read from the gateway) is returned as a string. With
the json option a perl hash reference pointing to the
JSON data is returned (take a look into the module if you want to
use that)
Examples:
get myBDKM /heatingCircuits/hc1/temporaryRoomGetpoint
or the aliased version of it (see attr below): get myBDKM RoomTemporaryDesiredTemp get myBDKM DateTime get myBDKM /gateway/instAccess
Spacial to get Infos about IDs known by the gateway and own
configurations: get myBDKM INFO
Everything matching /temp/
get myBDKM INFO temp
Everything matching /Heaven/ or /Hell/
get myBDKM INFO Heaven Hell
Everything known:
get myBDKM INFO .*
Arguments to INFO are reqular expressions
which are matched against all IDs and all aliases.
Attributes
BaseInterval
The interval time in seconds between poll cycles.
It defaults to 120 seconds. Which means that every 120 seconds a
new poll collects values of IDs which turn it is.
InterPollDelay
The delay time in milliseconds between reading of two IDs from
the gateway. It defaults to 0 (read as fast as possible).
Some gateways/heatings seem to stop answering after a while
when you are reading a lot of IDs. (verbose 2 "communication ERROR").
To avoid gateway hangups always try to read only as many IDs as
really required. If it doesn't help try to increase the
InterPollDelay value. E.g. start with 100.
ReadBackDelay
Read back delay for the set command in milliseconds. This value
defaults to 500 (0.5s). After setting a value, the gateway need
some time before the value can be read back. If this delay is
too short after writing you will get back the old value and not
the expected new one. The default should work in most cases.
HttpTimeout
Timeout for all HTTP requests in seconds (polling, set,
get). This defaults to 10s. If there is no answer from the
gateway for HttpTimeout time an error is returned. If a HTTP
request expires while polling an error log (level 2) is
generated and the request is automatically restarted after 60
seconds.
PollIds
Without this attribute FHEM readings are NOT generated
automatically!
This attribute defines how and when IDs are polled within
a base interval (set by atrribute BaseInterval).
The attribute contains list of space separated IDs and options
written as GatewayID:Modulo:Delta:Alias
Where Gateway is the real gateway ID like "/gateway/DateTime".
Modulo is the value which defines how often the GatewayID is
polled from the gateway and checked for FHEM readings update.
E.g. a value of 4 means that the ID is polled only every 4th cycle.
Delta defines the minimum difference a polled value must have to the
previous reading, before a FHEM reading with the new value is generated.
Alias defines a short name for the GatewayID under which the gateway ID
can be accessed. Also readings (Logfile entries) are generated with this
short alias if set. If not set, the original ID is used.
In detail: ID:1:0:Alias - poll every cycle, when difference >= 0 to previous reading (means always, also for strings) trigger FHEM reading to "Alias" ID:1::Alias - poll every cycle, no Delta set => trigger FHEM reading to "Alias" on value change only ID:0::Alias - update reading on startup once if reading changed (to the one prevously saved in fhem.save) ID:1:0.5:Alias - poll every cycle, when difference => 0.5 trigger a FHEM reading to "Alias" ID:15::Alias - poll every 15th cylce, update reading only if changed ID:::Alias - update reading on (get/set) only and only if value changed ID::0:Alias - update reading on (get/set) only and trigger reading always on get/set ID - without colons ":", poll every cycle, update reading allways (same as ID:1:0:)
Also some usefull defaults can be set by the special keyword RC300DEFAULTS, RC35DEFAULTS, RC30DEFAULTS.
As I don't know anything about RC35 or RC30 the later keywords are currently empty (please send me some info with "get myBDKM INFO" :-)
Definitions set by the special keywords (see the module code for it) are overwritten by definitions later set in the attribute definition
Example:
Which means: Use RC300DEFAULTS, trigger FHEM reading "Date" when date has changed on startup only. Trigger FHEM reading "/system/info" (no aliasing) always on startup, poll water temperature every cycle and trigger FHEM reading "WaterTemp" when difference to last reading was at least 0.2 degrees.
BEOK implements a connection to BEOK / Floureon / Hysen WiFi room thermostat
AES Encyrption is needed. Maybe you must first install extra Perl modules.
E.g. for Debian/Raspian :
sudo apt-get install libcrypt-cbc-perl
sudo apt-get install libcrypt-rijndael-perl
sudo apt-get install libssl-dev
sudo cpan Crypt/OpenSSL/AES.pm
Define
define <name> BEOK <ip> [mac]
Example: define Thermo BEOK 192.168.1.100
Set
desired-temp <5 - 99>
mode <auto manual>
loop <12345.67 123456.7 1234567>
12345.67 means Saturday and Sunday follow the "weekend" schedule
1234567 means every day (including Saturday and Sunday) follows the "weekday" schedule
sensor <external internal both>
both = internal control temperature, external limit temperature
time
sets time and day of week on device to FHEM time & day
lock <on off>
power-on-memory <on off>
fre <open close>
Anti-freezing function
room-temp-adj <-5 +5>
osv <5 - 99>
Limit temperature value of external sensor
svh <5 - 99>
Set upper limit temperature value
svl <5 - 99>
Set lower limit temperature value
dif <1 - 9>
difference of limit temperature value of external sensor
BOSEST is used to control a BOSE SoundTouch system (one or more SoundTouch 10, 20 30, 300 or Portable devices)
Note: The following libraries are required for this module:
libwww-perl
libmojolicious-perl
libxml-simple-perl
libnet-bonjour-perl
libev-perl
liburi-escape-xs-perl
sox
libsox-fmt-mp3
Use sudo apt-get install libwww-perl libmojolicious-perl libxml-simple-perl libnet-bonjour-perl libev-perl liburi-escape-xs-perl to install this libraries.
Please note: libmojolicious-perl must be >=5.54
Use sudo apt-get install cpanminus and sudo cpanm Mojolicious to update to the newest version.
TextToSpeach (TTS) can be configured as described in the following thread: Link
Questions and/or feedback can be posted on the FHEM forum: Link
Define
define <name> BOSEST
Example:
define bosesystem BOSEST
Defines BOSE SoundTouch system. All devices/speakers will show up after 60s under "Unsorted" in FHEM.
Set
set <name> <command> [<parameter>]
The following commands are defined for the devices/speakers (except autoAddDLNAServers is for the "main" BOSEST) :
General commands
on - power on the device
off - turn the device off
power - toggle on/off
volume [0...100] [+x|-x] - set the volume level in percentage or change volume by ±x from current level
channel 0...20 - select present to play
saveChannel 07...20 - save current channel to channel 07 to 20
play - start to play
pause - pause the playback
playpause - toggle play/pause
stop - stop playback
nextTrack - play next track
prevTrack - play previous track
playTrack name|location|source[|sourceAccount] - searches per DNLA for the track title and plays it
additional information:
You can test it in the SoundTouch APP: Use the search in the APP to see if a playlist is found and played. It yes it will work with playTrack too. (german FHEM forum post)
mute on|off|toggle - control volume mute
shuffle on|off - control shuffle mode
repeat all|one|off - control repeat mode
bass 0...10 - set the bass level
recent 0...15 - set number of names in the recent list in readings
source bluetooth,bt-discover,aux mode, airplay - select a local source
addDLNAServer Name1 [Name2] [Namex] - add DLNA servers Name1 (and Name2 to Namex) to the BOSE library
removeDLNAServer Name1 [Name2] [Namex] - remove DLNA servers Name1 (and Name2 to Namex) to the BOSE library
Example: set BOSE_1234567890AB volume 25 Set volume on device with the name BOSE_1234567890AB
Timer commands:
on-for-timer 1...x - power on the device for x seconds
off-for-timer 1...x - turn the device off and power on again after x seconds
on-till hh:mm:ss - power on the device until defined time
off-till hh:mm:ss - turn the device off and power on again at defined time
on-till-overneight hh:mm:ss - power on the device until defined time on the next day
off-till-overneight hh:mm:ss - turn the device off at defined time on the next day
Example: set BOSE_1234567890AB on-till 23:00:00 Switches device with the name BOSE_1234567890AB now on and at 23:00:00 off
Multiroom commands:
createZone deviceID[,deviceID] - create multiroom zone and adds device(s) to the multiroom zone
addToZone deviceID - add device to multiroom zone
removeFromZone deviceID - remove device from multiroom zone
playEverywhere - play sound of a device on all others devices
stopPlayEverywhere - stop playing sound on all devices
Example1: set BOSE_1234567890AB playEverywhere Starts playing the sound of the device BOSE_1234567890AB on allother devices
Example2: set BOSE_1234567890AB createZone AB1234567890,12AB34567890 Defines BOSE_1234567890AB as multiroom master
and adds BOSE_AB1234567890 and BOSE_12AB34567890 to the multiroom zone
Note: A "double-tap" (<1s) on a preset button (device or remote control) will toggle playEverywhere/stopPlayEverywhere
Show clock command (only for ST20/30):
clock enable/disable - show or hide clock
Example: set BOSE_1234567890AB clock enable Show time in the ST20/30 display.
TextToSpeach commands (needs Google Translate):
speak "message" [0...100] [+x|-x] [en|de|xx] - Text to speak, optional with volume adjustment and language to use.
speakOff "message" [0...100] [+x|-x] [en|de|xx] - Text to speak, optional with volume adjustment and language to use. Device is switched off after speak.
Example: set BOSE_1234567890AB speakOff "Music is going to switch off now. Good night." 30 en Speaks message at volume 30 and then switches off device.
DNLA Server command:
autoAddDLNAServers 0|1 - 1=automatically add all DLNA servers to BOSE library. This command is only for "main" BOSEST, not for devices/speakers!
Get
n/a
Attributes
staticIPs IP-Address [,IP-Address] - Manually define the used IP address(es) (comma separated) of your BOSE devices. Should be used only, if BOSEST device detection doesn't work in your network (e.g. several subnets on server, subnet not directly connected, ...) Example: attr bosesystem staticIPs 192.168.1.52,192.168.1.53
speakChannel channel(s) - speaks channel/present name bevor starting a playback, useful for SoundTouch without display (comma separated or range: e.g. 2,3,5,6 or 1-6 ). TTS must be installed.
auto-zone on|off - automatic start multiroom zone play, if speakers are playing the same, according to "contentItemLocation"; (default: off)
ttsDirectory "directory" - set DLNA TTS directory. FHEM user needs permissions to write to that directory.
ttsLanguage en|de|xx - set default TTS language (default: en)
ttsSpeakOnError 0|1 - 0=disable to speak "not available" text
ttsVolume [0...100] [+x|-x] - set the TTS volume level in percentage or change volume by ±x from current level
Channel_07 to Channel_20 name|location|source|[sourceAccount] - define present 07 to 20 When you play something, you can find ContentItemLocationName, ContentItemLocation, etc. in the readings. These data can be used here to define the present.
This module controls Neato Botvac Connected and Vorwerk Robot Vacuums.
For issuing commands or retrieving Readings it's necessary to fetch the information from the NEATO/VORWERK Server. In this way, it can happen, that it's not possible to send commands to the Robot until the corresponding Values are fetched. This means, it can need some time until your Robot will react on your command.
After defining the Device, it's necessary to log in into your account which is linked to your email address.
If you have a password, enter it with set <name> password <password>
It is exactly the same Password as you use on the Website or inside the App.
Example: set NEATO passwort mySecretPassword
If authentication without a password is provided, you have to following the registration process.
Ask for an one-time password by set <name> requestVerification
Provide one-time password from email set <name> sendVerification <code>
Get
get <name> batteryPercent
requests the state of the battery from Robot
get <name> securityTokens
list of all tokens stored by the module. The tokens are relevant for user authentication and to get access to robot data.
get <name> statistics
display statistical data, extracted from available maps of recent cleanings
Set
set <name> findMe
plays a sound and let the LED light for easier finding of a stuck robot
set <name> dismissCurrentAlert
reset an actual Warning (e.g. dustbin full)
set <name> nextCleaningMode
Depending on Model, there are Arguments available: eco/turbo
set <name> nextCleaningModifier
The modifier is used for next spot cleaning. Depending on Model, there are Arguments available: normal/double
set <name> nextCleaningNavigationMode
The navigation mode is used for the next house cleaning. Depending on Model, there are Arguments available: normal/extraCare/deep
set <name> nextCleaningZone
Depending on Model, the ID of the zone that will be used for the next zone cleaning can be set.
set <name> nextCleaningSpotHeight
Is defined as number between 100 - 400. The unit is cm.
set <name> nextCleaningSpotWidth
Is defined as number between 100 - 400. The unit is cm.
set <name> password <password>
set the password for the NEATO/VORWERK account
set <name> pause
interrupts the cleaning
set <name> pauseToBase
stops cleaning and returns to base
set <name> reloadMaps
load last map from server into the cache of the module. no file is stored!
set <name> resume
resume cleaning after pause
set <name> requestVerification
Request one-time password for account verfication.
One-time password will be sent to the account's email address.
set <name> schedule
on and off, switch time control
set <name> sendToBase
send roboter back to base
set <name> sendVerification <code>
Use one-time password from email as code to log in into your account, see requestVerification.
set <name> setBoundariesOnFloorplan_<floor plan> <name|{JSON String}>
Set boundaries/nogo lines in the corresponding floor plan. The paramter can either be a name, which is already defined by attribute "boundaries", or alternatively a JSON string. (A comma-separated list of names is also possible.) Description of syntax
Examples: set <name> setBoundariesOnFloorplan_0 Bad set <name> setBoundariesOnFloorplan_0 Bad,Kueche set <name> setBoundariesOnFloorplan_0 {"type":"polyline","vertices":[[0.710,0.6217],[0.710,0.6923]], "name":"Bad","color":"#E54B1C","enabled":true}
set <name> setRobot
choose robot if more than one is registered at the used account
set <name> startCleaning ([house|map|zone])
start the Cleaning from the scratch. If the robot supports boundaries/nogo lines/zones, the additional parameter can be used as:
house - cleaning without a persisted map
map - cleaning with a persisted map
zone - cleaning in a specific zone, set zone with nextCleaningZone
set <name> startSpot
start spot-Cleaning from actual position.
set <name> startManual
start Manual Cleaning. This cleaning mode opens a direct websocket connection to the robot. Therefore robot and FHEM installation has to reside in the same LAN. Even though an internet connection is necessary as the initialization is triggered by a remote call. Note: If the robot does not receive any messages for 30 seconds it will exit Manual Cleaning, but it will not close the websocket connection automaticaly.
set <name> statusRequest
pull update of all readings. necessary because NEATO/VORWERK does not send updates at their own.
set <name> stop
stop cleaning and in case of manual cleaning mode close also the websocket connection
set <name> syncRobots
sync robot data with online account. Useful if one has more then one robot registered
set <name> pollingMode <on|off>
set polling on (default) or off like attribut disable.
set <name> robotSounds <on|off>
set sounds on or off.
set <name> dirtbinAlertReminderInterval <30|60|90|120|150>
set alert intervall in minutes.
set <name> filterChangeReminderInterval <1|2|3>
set alert intervall in months.
set <name> brushChangeReminderInterval <4|5|6|7|8>
set alert intervall in months.
set <name> wsCommand
Commands start or stop cleaning activities.
eco-on
eco-off
turbo-on
turbo-off
brush-on
brush-off
vacuum-on
vacuum-off
set <name> wsCombo
Combos specify a behavior on the robot.
They need to be sent with less than 1Hz frequency. If the robot doesn't receive a combo with the specified frequency it will stop moving. Also, if the robot does not receive any messages for 30 seconds it will exit Manual Cleaning.
forward - issues a continuous forward motion.
back - issues a discontinuous backward motion in ~30cm intervals as a safety measure since the robot has no sensors at the back.
arc-left - issues a 450 turn counter-clockwise while going forward.
arc-right - issues a 450 turn clockwise while going forward.
pivot-left - issues a 900 turn counter-clockwise.
pivot-right - issues a 900 turn clockwise.
stop - issues an immediate stop.
Attributes
actionInterval
time in seconds between status requests while Device is working
boundaries
Boundary entries separated by space in JSON format, e.g. {"type":"polyline","vertices":[[0.710,0.6217],[0.710,0.6923]],"name":"Bad","color":"#E54B1C","enabled":true} {"type":"polyline","vertices":[[0.7139,0.4101],[0.7135,0.4282],[0.4326,0.3322],[0.4326,0.2533],[0.3931,0.2533],[0.3931,0.3426],[0.7452,0.4637],[0.7617,0.4196]],"name":"Kueche","color":"#000000","enabled":true} Description of syntax
The value of paramter name is used as setListe for setBoundariesOnFloorplan_<floor plan>. It is also possible to save more than one boundary with the same name. The command setBoundariesOnFloorplan_<floor plan> <name> sends all boundary with the same name.
With definition of a BRAVIA device an internal task will be scheduled.
This task pulls frequently the status and other information from the TV.
The intervall can be defined in seconds by an optional parameter <poll-intervall>.
The default value is 45 seconds.
After definition of a device using this module it has to be registered as a remote control
(set register).
As long as readings are not among the usual AV readings they are clustered:
s_*
: status
ci_*
: content information
The module contains predefined layouts for remotecontrol using PNG and SVG.
Set
set <name> <option> <value>
Options:
application
List of applications.
Applications are available with models from 2013 and newer.
channel
List of all known channels. The module collects all visited channels.
Channels can be loaded automtically with models from 2013 and newer.
(number of channels, see channelsMax).
channelDown
Switches a channel back.
channelUp
Switches a channel forward.
enable
Enables the internal task to pull the status and other information from the TV.
disable
Disables the internal task to pull the status and other information from the TV.
input
List of input channels.
Imputs are available with models from 2013 and newer.
off
Switches TV to off. State of device will have been set to "set_off" for 60 seconds or until off-status is pulled from TV.
on
Switches TV to on, with models from 2013 using WOL. State of device will have been set to "set_on" for 60 seconds or until on-status is pulled from TV.
openUrl
Opens an URL on the screen.
This Feature is available on models from 2013 and newer.
pause
Pauses a playing of a recording, of an internal App, etc.
play
Starts playing of a recording, of an internal App, etc.
record
Starts recording of current content.
register
One-time registration of Fhem as remote control in the TV.
With requestFormat = "xml" registration works without parameter.
With requestFormat = "json" registration has to be executed twice.
The register option offers an additional input field:
Call with empty input. A PIN for registration has to be shown on the TV.
Insert PIN into input field and register again.
requestFormat
"xml" for xml based communication (models from 2011 and 2012)
"json" for communication with models from 2013 and newer
requestReboot
Reboots the TV immediately.
This Feature is available on models from 2013 and newer.
remoteControl
Sends command directly to TV.
statusRequest
Retrieves current status information from TV.
stop
Stops recording, playing of an internal App, etc.
text
Includes the given text into an input field on display.
toggle
Toggles power status of TV.
tvpause
Activates Timeshift mode.
upnp
Activates Upnp service used to control volume.
volume
Straight setting of volume. Upnp service has to be activated.
volumeDown
Decreases volume.
volumeUp
Increases volume.
Attributes
attr <name> <attribute> <value>
Attributes:
channelsMax
Maximum amount of channels to be displayed, default is 50.
macaddr
Enables power on of TV using Wake-On-Lan.
wolBroadcast
Broadcast address for Wake-On-Lan magic packets, default is 255.255.255.255.
The module BS allows to collect data from a brightness sensor through a
FHZ device. For details on the brightness sensor see
busware wiki.
You can have at most nine different brightness sensors in range of your
FHZ.
The state contains the brightness in % (reading brightness) and
the brightness in lux (reading lux). The flags
reading is always zero. The meaning of these readings is explained in more
detail on the above mentioned wiki page.
Define
define <name> BS <sensor#> [<RExt>]
<sensor#> is the number of sensor in the brightness
sensor address system that runs from 1 to 9.
<RExt> is the value of the resistor on your brightness
sensor in Ω (Ohm). The brightness reading in % is proportional to the resistance, the
lux reading is proportional to the resistance squared. The value is
optional. The default resistance is RExt= 50.000Ω.
This module uses the global attribute language to determine its output data
(default: EN=english). For German output set attr global language DE.
This module needs the JSON package.
Only when the chatbot functionality of RiveScript is required, the RiveScript module must be installed as well, see https://github.com/aichaos/rivescript-perl
Usage
To use this module,
call the Perl function Babble_DoIt("<name>","<sentence>"[,<parm0>,<parm1>,...]).
execute the FHEM command set <name> talk|doit <sentence>[,<parm0>,<parm1>,...].
<name> is the name of the Babble device, <parm0> <parm1> are arbitrary parameters passed to the executed command.
The module will analyze the sentence passed an isolate a device to be addressed, a place identifier,
a verb, a target and its value from the sentence passed. Attention: in case the FHEM command is used, <sentence> must not contain commas.
If a proper command has been stored with device, place, verb and target, it will be subject to substitutions and then will be executed.
In these substitutions, a string $VALUE will be replaced by the value for the target reading, a string $DEV will be replaced by the device name identified by Babble,
and strings $PARM[0|1|2...] will be replaced by the
corresponding parameters passed to the function Babble_DoIt
If no stored command ist found, the sentence is passed to the local RiveScript interpreter if present
To have a FHEM register itself as a Babble Device, it must get an attribute value babbleDevice=<name>. The name parameter must either be
unique to the Babble system, or it muts be of the form <name>_<digits>
Devices on remote FHEM installations are defined in the babbleDevices attribute, see below
set <name> locked set <name> unlocked sets the lockstate of the babble module to locked (i.e., babble setups
may not be changed) resp. unlocked (i.e., babble setups may be changed>)
set <name> save|restore Manually save/restore the babble to/from the external file babbleFILE (save done automatically at each state modification, restore at FHEM start)
an integer 1..3, indication which of the remoteFHEM functions to be called
The Babble device name may contain a *-character. If this is the case, it will be considered a regular expression, with the star replaced by (.*).
When using Babble with a natural language sentence whose device part matches this regular expression, the character group addressed by the star sequence is placed in the variable
$STAR, and used to replace this value in the command sequence.
attr <name> helpFunc <function name&rt; name of a help function which is used in case no command is found for a certain device. When this function is called, the strings $DEV, $HELP, $PARM[0|1|2...]
will be replaced by the devicename identified by Babble, the help text for this device and parameters passed to the Babble_DoIt function
attr <name> testParm(0|1|2|3) <string&rt; if a command is not really excuted, but only tested, the values of these attributes will be used to substitute the strings $PARM[0|1|2...]
in the tested command
attr <name> confirmFunc <function name&rt; name of a confirmation function which is used in case a command is exceuted. When this function is called, the strings $DEV, $HELP, $PARM[0|1|2...]
will be replaced by the devicename identified by Babble, the help text for this device and parameters passed to the Babble_DoIt function
attr <name> noChatBot 0|1 if this attribute is set to 1, a local RiveScript interpreter will be ignored even though it is present in the system
attr <name> babbleSubs :,:, ... space separated list of regular expressions and their replacements - this will be used on the initial sentence submitted to Babble
(Note: a space in the regexp must be replaced by \s).
attr <name> babbleVerbs ,...:,...: space separated list of verb groups to be identified in speech. Each group consists of comma separated verb forms (conjugations as well as variations),
followed by a ':' and then the infinitive form of the verb. Example: speak,speaks,say,says:speaking
attr <name> babbleWrites ... space separated list of write verbs to be identified in speech. Example: send add remove
This module connects remotely to a system of Blink Home Cameras
Blink Home Cameras are relatively inexpensive wire-free video home security & monitoring system
Disclaimer: Since there are no official APIs for the blink cameras, there is no guarantee for this module to continue working. Several changes over the years have caused temporary outages due to incompatibe changes done by the provider of the Blink cameras.
The blink device contains the possibility to regular poll for updates (i.e. specifically for notifications/alerts)
MOst commands that change configurations are not synchronous, but the result will be returned after polling for status information. This is automatically handled in the device and the result of the cmd is marked in the reading cmdResult with the value "SUCCESS".
Traditional Blink cameras and also the BlinkMini types should work
The blink device also contains a proxy for retrieving videos and thumbnails throug an FHEMweb extension in the form of http://<fhem>:<fhemwebport>/fhem/BlinkCamera/<name of the blink device>/...
Define
define <name> BlinkCamera <email> [ <password> ]
Defines a BlinkCamera device, which connects to the cloud servers with the given user name and password (as provided during registration / setup)
The password will be removed from the define and stored separately (so needs to be given on the initial define)
login Initiate a login to the blink servers. This is usually done automatically when needed or when the login is expired
verifyPin can be used to verify the pin send from blink via email/sms
arm or disarm All enabled cameras in the system will be armed (i.e. they will be set to a mode where alarms/videos are automatically created based on the current settings) / disarmed (set to inactive mode where no video is recorded.
camEnable <camera name or number or "all"> or camDisable <camera name or number> The specified camera will be enabled (i.e. so that it is included in the arm / disarm commands) / disabled (excluded from arm/disarm).
reset Reset the FHEM device (only used in case of something gets into an unknown or strange state)
resetUniqueID Reset the FHEM device (only used in case of something gets into an unknown or strange state). Additionally the uniqueID that is used in the device loing will be reset in this option.
videoDelete <video id> The video with the given id will be removed (both from the local filesystem and from the blink servers)
Get
get <name> <what> [<value>]
where <what> / <value> is one of
getNetworks Retrieve the networks defined in the blink account. This is needed for further operations and information request to blink. For specifying a specific network (id), the attribute network can be also set
getInfo Get information about the system from the blink servers (including cameras and state) . This is usually done automatically based on the reular interval specified in attribute pollingTimeout
getInfoCamera <camera name or number or "all"> Get the information about the specified camera from the blink system. Currently the information about the camera is just stored in raw json format in a single reading cameraConfig<camera id>
getThumbnail <camera name or number or "all"> Request a new thumbnail being taken from the specified camera in the blink system. The thumbnail is not automatically retrieved, this can be done using getInfoCamera
getVideoAlert [ <video id> ] Retrieve the video for the corresponding id (or if ommitted as specified in the reading alertID) and store the video in a local file in the directory given in the attribute proxyDir
liveview <camera name or number or "all"> Request a link to the live video stream. The live video stream access (URL) will be stored in the reading liveVideo (the associated cam id in liveCam). The link to the video is an rtsp - which can be shown in video players like VLC.
Note: Live video streaming might have a substantially negative effect on battery life
Attributes
maxRetries <0|1|2...|9> Defines the number of retries that are done in case of a failure of a command. Pauses between retries are done with an increasing delay between calls.
network <network id> This attribute is needed if your blink system contains more than one network. If not specified the first netowrk defined in the account is used
proxyDir <directory path> Specify the path where temporary files (videos, thumbnails) are stored to be access via the proxy server built into the device as an fhemweb extension
pollingTimeout <interval> Interval in which the system is checking for status updates from the blink servers (given in seconds - value 0 means no polling). This is the frequency in which new alerts can be received
imgTemplate <HTML template for reading> Give an HTML template for the image reading that shows the thumbnail of a camera. Default is a template which shows the image a link to the image and also the url as text. In the template the string #URL# will be replaced with the actual URL
imgOriginalFile <1 or 0> If set to 1 it will keep the original filename of the thumbnail when storing ti. With setting this new thumbnails will not overwrite existing ones.
NOTE: No cleanup of thumbnails is done, so over time more and more thumbnails will be stored in the proxydir.
vidTemplate <HTML template for reading> Give an HTML template for the video reading that shows the video of a notification from the camera. Default is a template which shows the video a link to the video and also the url and id as text. In the template the string #URL# will be replaced with the actual URL of the video and #ID# will be replaced by the video ID.
webname <path to fhem web> can be set if fhem is not accessible through the standard url of FHEMWeb /fhem/... (Default value is fhem).
homeScreenV3 <1 or 0> If set to 1 (default) the new version 3 of the blink API will be used. Unfortunately this includes different readings and settings
NOTE: This attribute is deprecated and not needed anymore, since the old API has been switched off by Blink (default is on = 1)
Readings
cmd <internal name of the last executed command> Used to identify the cmd that was last executed and where the result is given in cmdResult
cmdResult <error message or SUCCESS> Used to identify success or failure of a command
networks <list of networks> Lists the defined networks for the account at blink in the form networkid:networkname
networkName <name> Name of the network that is currently used to fill the readings
networkArmed <status> Network arm status (true or false)
networkStatus <ok or failure> Basic status of the current network
networkCameras <number> Lists the defined cameras in the current network in the form cameraid:cameraname
networkSyncModule <id and status> Information about the syncmodule in the current network in the form syncid:syncmodulestatus
networkCamera... Set of readings specific for each camera (identified by the cameraID in the reading name). Providing status and name of the camera / most recent thumbnail / url for the thumbnail to the proxy
networkCameraEnabled Shows the enabled (active) status of the camera (known values: 0 / 1 / "undef" - last value will be given if this value is not contained in the camerainfo
alert... Set of readings specifying the last alert (movement alert) coming from one of the devices. Especially the ID is relevant here for accessing the corresponding video secifically. Additionally the camera, time and video url are specifed here.
Broadlink implements a connection to Broadlink devices - currently tested with Broadlink RM Pro, which is able to send IR and 433MHz commands. It is also able to record this commands.
It can also control rmmini devices and sp3 or sp3s plugs.
It requires AES encryption please install on Windows: ppm install Crypt-CBC ppm install Crypt-OpenSSL-AES
This module creates a device with deadlines based on calendar-devices of the 57_Calendar.pm module. You need to install the perl-modul Date::Parse!
Please configure the attribut HideOlderThen in your CALENDAR-Device, that controls if old events from past are shown!
Define
define <Name> CALVIEW <calendarname(s) separate with ','> <next> <updateintervall in sec (default 43200)>
define myView CALVIEW Googlecalendar next
define myView CALVIEW Googlecalendar,holiday next 900
- setting the update interval is not needed normally because every calendar update triggers a caview update
Set
set <Name> update
set myView update
this will manually update all readings from the given CALENDAR Devices
Attribute
datestyle
not set - the default, disables displaying readings bdatetimeiso / edatetimeiso
ISO8601 - enables readings bdatetimeiso / edatetimeiso (start and end time of term ISO8601 formated like 2017-02-27T00:00:00)
disable
0 / not set - internal notify function enabled (default)
1 - disable the internal notify-function of CALVIEW wich is triggered when one of the given CALENDAR devices has updated
filterSummary
filterSummary <filtersouce>:<filtersummary>[,<filtersouce>:<filtersummary>]
not set - displays all terms (default .*:.*)
<filtersouce>:<filtersummary>[,<filtersouce>:<filtersummary>] - CALVIEW will display term where summary matches the <filtersouce>:<filtersummary>, several filters must be separated by comma (,)
e.g.: filterSummary Kalender_Abfall:Leichtverpackungen,Kalender_Abfall:Bioabfall
filterSummary Kalender_Abfall:Leichtverpackungen,Kalender_Feiertage:.*,Kalender_Christian:.*,Kalender_Geburtstage:.*
fulldaytext [text]
this text will be displayed in _timeshort reading for fullday terms (default ganztägig)
isbirthday
0 / not set - no age calculation (default)
1 - age calculation active. The module calculates the age with year given in description or location (see att yobfield).
maxreadings
defines the number of max term as readings
modes
here the CALENDAR modes can be selected , to be displayed in the view
oldStyledReadings
0 the default style of readings
1 readings look like "2015.06.21-00:00" with value "Start of Summer"
sourcecolor <calendername>:<colorcode>[,<calendername>:<colorcode>]
here you can define the termcolor for terms from your calendars for the calview tabletui widget, several calendar:color pairs must be separated by comma
timeshort
0 time in _timeshort readings formated 00:00:00
1 time in _timeshort readings formated 00:00
yobfield
_description - (default) year of birth will be read from term description
_location - year of birth will be read from term location
_summary - year of birth will be read from summary (uses the first sequence of 4 digits in the string)
weekdayformat
formats the name of the reading weekdayname
- de-long - (default) german, long name like Dienstag
- de-short - german, short name like Di
- en-long - english, long name like Tuesday
- en-short - english, short name like Tue
The DWD provides values ​​for the amount of rain that has fallen per day, which are based on rain radar measurements and whose values ​​have been adjusted to the amounts measured by the weather station. The spatial resolution is 1 km, which makes the data interesting for those who do not have their own rainfall measurement available.
Define
define <name> CDCOpenData [<name>:]latitude,longitude>
The parameters latitude,longitude define the location.
[<name>:] is an optional descriptive name for the location.
If the parameters are not specified, the location is determined from the global attributes latitude,longitude.
If these are not defined, the standard location 49.473067 6.3851 for Germany is used.
Example: define DWDRain CDCOpenData ....
Set
set <name> update
Starts an update of the data.
set <name> htmlBarAsStateFormat <on|off>
Defines an HTML bar to display the rain radar in the stateFormat attribute.
In order to persist the change, it must be saved by clicking on 'Save config'.
The generation function can also be used to define a weblink device.
Polling-Interval. Default is 300 (seconds). Smallest possible value is 60.
If the attribut cronTime is set, INTERVAL will be deactivated.
attr <name> verbose <0 .. 5>
If verbose is set to the value 5, all log data will be saved in its own log file.
Log file name:deviceName_debugLog.dlog
In the INTERNAL Reading DEBUGLOG there is a link <DEBUG log can be viewed here> for direct viewing of the log.
Furthermore, a FileLog device:deviceName_debugLog is created in the same room and the same group as the CDCOpenData device.
If verbose is set to less than 5, the FileLog device is deleted and the log file is retained.
If verbose is deleted, the FileLog device and the log file are deleted.
attr <name> FhemLog3Std <0 | 1>
If set, the log information will be written in standard Fhem format.
If the output to a separate log file was activated by a verbose 5, this will be ended.
The separate log file and the associated FileLog device are deleted.
If the attribute is set to 0 or deleted and the device verbose is set to 5, all log data will be written to a separate log file.
Log file name: deviceName_debugLog.dlog
In the INTERNAL Reading DEBUGLOG there is a link <DEBUG log can be viewed here> for direct viewing of the log.
attr <name> clearRadarFileLog <name of FileLog device>
If set, the FileLog of the FileLog Device will be emptied when the Regen Radar is updated.
Only makes sense for FileLogs that use the Regen Radar data for a graphic.
attr <name> RainRadarFileLog <name of FileLog device>
If set, a FileLog device will be created.
The FileLog of the FileLog Device will be emptied when the Regen Radar is updated.
Only makes sense for FileLogs that use the Regen Radar data for a graphic.
attr <name> ownRadarFileLog <0 | 1>
If set, a log file: deviceName_rainLog.log will be generated directly via the module.
The log file always only contains the current values.
Additionally, a FileLog device with the name deviceName_rainLog is created in the same room and the same group.
attr <name> cronTime <* * * * *>
CRON Expression. If set, then execution is controlled via the CRON expression.
Default is one hour.
Note: this module requires the Device::SerialPort or Win32::SerialPort module.
Define
define <name> CM11 <serial-device>
CM11 is the X10 module to interface X10 devices with the PC.
The current implementation can evaluate incoming data on the powerline of
any kind. It can send on, off, dimdown and dimup commands.
The name of the serial-device depends on your distribution. If
serial-device is none, then no device will be opened, so you can experiment
without hardware attached.
If you experience problems (for verbose 4 you get a lot of "Bad CRC message"
in the log), then try to define your device as define <name> FHZ <serial-device> strangetty
Example:
define x10if CM11 /dev/ttyUSB3
Set
set <name> reopen
Reopens the serial port.
Get
get <name> fwrev
Reads the firmware revision of the CM11 device. Returns error
if the serial connection to the device times out. Can be used for error
detection.
get <name> time
Reads the internal time of the device which is the total uptime (modulo one
year), since fhem sets the time to 0.00:00:00 if the device requests the time
to be set after being powered on. Returns error
if the serial connection to the device times out. Can be used for error
detection.
Module for measuring air quality with usb sticks based on the AppliedSensor iAQ-Engine sensor.
Products currently know to work are the VOLTCRAFT CO-20, the Sentinel Haus Institut RaumluftWächter
and the VELUX Raumluftfühler.
Probably works with all devices recognized as iAQ Stick (0x03eb:0x2013).
Notes:
Device::USB hast to be installed on the FHEM host.
It can be installed with 'cpan install Device::USB'
or on debian with 'sudo apt-get install libdevice-usb-perl''
Advanced features are only available after setting the attribute advanced.
Almost all the hidden settings from the Windows application are implemented in this mode.
Readout of values gathered in standalone mode is not possible yet.
Define
define <name> CO20 [bus:device]
Defines a CO20 device. bus:device hast to be used if more than one sensor is connected to the same host.
Examples:
define CO20 CO20
Readings
voc
CO2 equivalents in ppm
debug
debug value
pwm
pwm value
r_h
resistance of heating element in Ohm (?)
r_s
resistance of sensor element in Ohm (?)
Get
update / air_data
trigger an update
flag_data
get internal flag values
knob_data
get internal knob values
stick_data
get stick information
Set
KNOB_CO2_VOC_level_warn1
sets threshold for yellow led
KNOB_CO2_VOC_level_warn2
sets threshold for red led
KNOB_Reg_Set
internal value, affects voc reading
KNOB_Reg_P
internal pid value
KNOB_Reg_I
internal pid value
KNOB_Reg_D
internal pid value
KNOB_LogInterval
log interval for standalone mode
KNOB_ui16StartupBits
set to 0 for no automatic calibration on startup
FLAG_WARMUP
warmup time left in minutes
FLAG_BURN_IN
burn in time left in minutes
FLAG_RESET_BASELINE
reset voc baseline value
FLAG_CALIBRATE_HEATER
trigger calibration / burn in
FLAG_LOGGING
value count from external logging
Attributes
interval
the interval in seconds used to read updates [10..]. the default ist 300.
retries
number of retries on USB read/write failures [0..20]. the default is 3.
timeout
the USB connection timeout in milliseconds [250..10000]. the default is 1000.
advanced
1 -> enables most of the advanced settings and readings described here
The CUL/CUN(O) is a family of RF devices sold by busware.de.
With the opensource firmware
culfw they are capable
to receive and send different 433/868 MHz protocols (FS20/FHT/S300/EM/HMS/MAX!).
It is even possible to use these devices as range extenders/routers, see the
CUL_RFR module for details.
Some protocols (FS20, FHT and KS300) are converted by this module so that
the same logical device can be used, irrespective if the radio telegram is
received by a CUL or an FHZ device.
Other protocols (S300/EM) need their
own modules. E.g. S300 devices are processed by the CUL_WS module if the
signals are received by the CUL, similarly EMWZ/EMGZ/EMEM is handled by the
CUL_EM module.
It is possible to attach more than one device in order to get better
reception, FHEM will filter out duplicate messages.
Note: This module may require the Device::SerialPort or
Win32::SerialPort module if you attach the device via USB
and the OS sets strange default parameters for serial devices.
Define
define <name> CUL <device> <FHTID>
USB-connected devices (CUL/CUN):
<device> specifies the serial port to communicate with the CUL.
The name of the serial-device depends on your distribution, under
linux the cdc_acm kernel module is responsible, and usually a
/dev/ttyACM0 device will be created. If your distribution does not have a
cdc_acm module, you can force usbserial to handle the CUL by the
following command:
modprobe usbserial vendor=0x03eb product=0x204b
In this case the device is most probably /dev/ttyUSB0.
You can also specify a baudrate if the device name contains the @
character, e.g.: /dev/ttyACM0@38400
If the baudrate is "directio" (e.g.: /dev/ttyACM0@directio), then the
perl module Device::SerialPort is not needed, and FHEM
opens the device with simple file io. This might work if the operating
system uses sane defaults for the serial parameters, e.g. some Linux
distributions and OSX.
Network-connected devices (CUN(O)):
<device> specifies the host:port of the device, e.g.
192.168.0.244:2323
If the device is called none, then no device will be opened, so you
can experiment without hardware attached.
The FHTID is a 4 digit hex number, and it is used when the CUL talks to
FHT devices or when CUL requests data. Set it to 0000 to avoid answering
any FHT80b request by the CUL.
Set
reopen
Reopens the connection to the device and reinitializes it.
raw
Issue a CUL firmware command. See the this document
for details on CUL commands.
freq / bWidth / rAmpl / sens SlowRF mode only.
Set the CUL frequency / bandwidth / receiver-amplitude / sensitivity
Use it with care, it may destroy your hardware and it even may be
illegal to do so. Note: The parameters used for RFR transmission are
not affected.
freq sets both the reception and transmission frequency. Note:
Although the CC1101 can be set to frequencies between 315 and 915
MHz, the antenna interface and the antenna of the CUL is tuned for
exactly one frequency. Default is 868.3 MHz (or 433 MHz)
bWidth can be set to values between 58 kHz and 812 kHz. Large values
are susceptible to interference, but make possible to receive
inaccurately calibrated transmitters. It affects tranmission too.
Default is 325 kHz.
rAmpl is receiver amplification, with values between 24 and 42 dB.
Bigger values allow reception of weak signals. Default is 42.
sens is the decision boundary between the on and off values, and it
is 4, 8, 12 or 16 dB. Smaller values allow reception of less clear
signals. Default is 4 dB.
hmPairForSec HomeMatic mode only.
Set the CUL in Pairing-Mode for the given seconds. Any HM device set into
pairing mode in this time will be paired with FHEM.
hmPairSerial HomeMatic mode only.
Try to pair with the given device. The argument is a 10 character
string, usually starting with letters and ending with digits, printed on
the backside of the device. It is not necessary to put the given device
in learning mode if it is a receiver.
led
Set the CUL led off (00), on (01) or blinking (02).
ITClock
Set the IT clock for Intertechno V1 protocol. Default 250.
Get
version
returns the CUL firmware version
uptime
returns the CUL uptime (time since CUL reset)
raw
Issues a CUL firmware command, and waits for one line of data returned by
the CUL. See the CUL firmware README document for details on CUL
commands.
fhtbuf
CUL has a message buffer for the FHT. If the buffer is full, then newly
issued commands will be dropped, and an "EOB" message is issued to the
FHEM log.
fhtbuf returns the free memory in this buffer (in hex),
an empty buffer in the CUL V2 is 74 bytes, in CUL V3/CUN(O) 200 Bytes.
A message occupies 3 + 2x(number of FHT commands) bytes,
this is the second reason why sending multiple FHT commands with one
set is a good idea. The first reason is, that
these FHT commands are sent at once to the FHT.
ccconf
Read some CUL radio-chip (cc1101) registers (frequency, bandwidth, etc.),
and display them in human readable form.
cmds
Depending on the firmware installed, CULs have a different set of
possible commands. Please refer to the README of the firmware of your
CUL to interpret the response of this command. See also the raw command.
credit10ms
One may send for a duration of credit10ms*10 ms before the send limit
is reached and a LOVF is generated.
Attributes
addvaltrigger
Create triggers for additional device values. Right now these are RSSI
and RAWMSG for the CUL family and RAWMSG for the FHZ.
connectCommand
raw culfw command sent to the CUL after a (re-)connect of the USB device,
and sending the usual initialization needed for the configured rfmode.
hmId
Set the HomeMatic ID of this device. If this attribute is absent, the
ID will be F1<FHTID>. Note 1: After setting or changing this
attribute you have to relearn all your HomeMatic devices. Note 2: The
value must be a 6 digit hex number, and 000000 is not valid. FHEM
won't complain if it is not correct, but the communication won't work.
hmProtocolEvents
Generate events for HomeMatic protocol messages. These are normally
used for debugging, by activating "inform timer" in a telnet session,
or looking at the Event Monitor window in the FHEMWEB frontend.
Example:
longids
Comma separated list of device-types for CUL that should be handled
using long IDs. This additional ID allows it to differentiate some
weather sensors, if they are sending on the same channel.
Therefore a random generated id is added. If you choose to use longids,
then you'll have to define a different device after battery change.
Default is not to use long IDs.
Modules which are using this functionality are for e.g. :
14_Hideki, 41_OREGON, 14_CUL_TCM97001, 14_SD_WS07.
Examples:
# Do not use any long IDs for any devices (this is default):
attr cul longids 0
# Use long IDs for all devices:
attr cul longids 1
# Use longids for SD_WS07 devices.
# Will generate devices names like SD_WS07_TH_3 for channel 3.
attr cul longids SD_WS07
noRawReadLog
Do not log RAW read events at verbose 5, as sometimes makes this the
log unreadable (Forum #122160).
sendpool
If using more than one CUL for covering a large area, sending
different events by the different CUL's might disturb each other. This
phenomenon is also known as the Palm-Beach-Resort effect.
Putting them in a common sendpool will serialize sending the events.
E.g. if you have three CUN's, you have to specify following
attributes: attr CUN1 sendpool CUN1,CUN2,CUN3
attr CUN2 sendpool CUN1,CUN2,CUN3
attr CUN3 sendpool CUN1,CUN2,CUN3
rfmode
Configure the RF Transceiver of the CUL (the CC1101). Available
arguments are:
SlowRF
To communicate with FS20/FHT/HMS/EM1010/S300/Hoermann devices @1 kHz
datarate. This is the default.
HomeMatic
To communicate with HomeMatic type of devices @10 kHz datarate.
MAX
To communicate with MAX! type of devices @10 kHz datarate.
WMBus_S
WMBus_T
WMBus_C
To communicate with Wireless M-Bus devices like water, gas or
electrical meters. Wireless M-Bus uses three different communication
modes, S-Mode, T-Mode and C-Mode. While in this mode, no reception of other
protocols like SlowRF or HomeMatic is possible. See also the WMBUS
FHEM Module.
<code> is the code which must be set on the EM device. Valid values
are 1 through 12. 1-4 denotes EMWZ, 5-8 EMEM and 9-12 EMGZ devices.
corr1 is used to correct the current number, corr2
for the total number.
for EMWZ devices you should specify the rotation speed (R/kW)
of your watt-meter (e.g. 150) for corr1 and 12 times this value for
corr2
for EMEM devices the corr1 value is 0.01, and the corr2 value is
0.001
CostPerUnit and BasicFeePerMonth are used to compute your
daily and monthly fees. Your COST will appear in the log, generated once
daily (without the basic fee) or month (with the bassic fee included). Your
definition should look like e.g.:
Tip: You can configure your EMWZ device to show in the CUM column of the
STATE reading the current reading of your meter. For this purpose: multiply
the current reading (from the real device) with the corr1 value (RperKW),
and subtract the RAW CUM value from it. Now set the basis reading of your
EMWZ device (named emwz) to this value.
maxPeak <number>
Specifies the maximum possible peak value for the EM meter
("TOP:" value in logfile). Peak values greater than this value
are considered as EM read errors and are ignored.
For example if it's not possible to consume more than 40kW of
power set maxPeak to 40 to make the readings of the power meter
more robust.
CounterOffset
Specifies the difference between true (gas) meter value and
value reported by the EMGZ.
CounterOffset = true Value - Reading "total"
Example:
This module handles messages from the FHT80 TF "Fenster-Tür-Kontakt" (Window-Door-Contact)
which are normally only acted upon by the FHT80B. With this module,
FHT80 TFs are in a limited way (see Wiki
for detailed explanation of TF's mode of operation) usable similar to HMS100 TFK. The name
of the module was chosen as a) only CUL will spill out the datagrams and b) "TF" designates
usually temperature+humidity sensors (no clue, why ELV didn't label this one "TFK" like with
FS20 and HMS).
As said before, FHEM can receive FHT80 TF radio (868.35 MHz) messages only through an
CUL device, so this must be defined first.
With the latest build on SVN
or next official version 1.62 or higher, it is possible to send out FHT80 TF data with a CUL or simular
devices. So it can be simulate up to four window sensor with one device
(see FHEM Wiki). To setup a window sensor, you have to
add and/or change the attribute "model" to virtual. The 6 digit hex number must not equal to FHTID.
Define
define <name> CUL_FHTTK <devicecode>
<devicecode> is a six digit hex number, given to the FHT80 TF during
production, i. e. it is not changeable. (Yes, it keeps this code after changing batteries
as well.)
Examples:
define TK_TEST CUL_FHTTK 965AB0
Set
Only available, if model is set to virtual.
set <name> <value>
where value is one of:
Closed set window state to Closed
Open set window state to Open
Pair start pairing with FHT80B (activate FHT80B sync mode before) - state after pairing is Closed
ReSync resync virtual sensor with FHT80b after a reset of CUL device. In other words, perform a virtual
battery exchange to synchronize the sensor with FHT80b device again. (at the moment, only
available with prototype cul fw - see forum 55774)
Special to the "ReSync" of existing FHT80TFs after a CUL firmware reset:
After a reset or restart of a CUL device, the connection between the FHT80B and the virtual FHT80TFs is interrupted. This is equivalent to a battery change.
The contacts are still registered at the FHT80B. No new pairing is required. If multiple virtual contacts are used, it is recommended to synchronize them at large intervals!
Calling the CUL_FHTTK_ReSyncAll() function synchronizes all virtual window contacts successively with the FHT80B.
The time interval between the individual sensors is 1 hour. This is determined by the 1% rule, since per contact 480 credits are consumed within 64 seconds!
Correct device definition is the key for HM environment simple maintenance.
Background to define entities:
HM devices has a 3 byte (6 digit hex value) HMid - which is key for
addressing. Each device hosts one or more channels. HMid for a channel is
the device's HMid plus the channel number (1 byte, 2 digit) in hex.
Channels should be defined for all multi-channel devices. Channel entities
cannot be defined if the hosting device does not exist Note: FHEM
mappes channel 1 to the device if it is not defined explicitely. Therefore
it does not need to be defined for single channel devices.
Note: if a device is deleted all assotiated channels will be removed as
well. An example for a full definition of a 2 channel switch is given
below:
livingRoomSwitch is the device managing communication. This device is
defined prior to channels to be able to setup references.
LivingroomMainLight is channel 01 dealing with status of light, channel
peers and channel assotiated register. If not defined channel 01 is covered
by the device entity. LivingRoomBackLight is the second 'channel',
channel 02. Its definition is mandatory to operate this function.
Sender specials: HM threats each button of remotes, push buttons and
similar as channels. It is possible (not necessary) to define a channel per
button. If all channels are defined access to pairing informatin is
possible as well as access to channel related register. Furthermore names
make the traces better readable.
define may also be invoked by the autocreate
module, together with the necessary subType attribute.
Usually you issue a hmPairForSec and press the
corresponding button on the device to be paired, or issue a hmPairSerial set command if the device is a receiver
and you know its serial number. Autocreate will then create a fhem
device and set all necessary attributes. Without pairing the device
will not accept messages from fhem. fhem may create the device even if
the pairing is not successful. Upon a successful pairing you'll see a
CommandAccepted entry in the details section of the CUL_HM device.
If you cannot use autocreate, then you have to specify:
the <6-digit-hex-code>or HMid+ch <8-digit-hex-code>
It is the unique, hardcoded device-address and cannot be changed (no,
you cannot choose it arbitrarily like for FS20 devices). You may
detect it by inspecting the fhem log.
the subType attribute
which is one of switch dimmer blindActuator remote sensor swi
pushButton threeStateSensor motionDetector keyMatic winMatic
smokeDetector
Without these attributes fhem won't be able to decode device messages
appropriately.
Notes
If the interface is a CUL device, the rfmode
attribute of the corresponding CUL/CUN device must be set to HomeMatic.
Note: this mode is BidCos/Homematic only, you will not receive
FS20/HMS/EM/S300 messages via this device. Previously defined FS20/HMS
etc devices must be assigned to a different input device (CUL/FHZ/etc).
Currently supported device families: remote, switch, dimmer,
blindActuator, motionDetector, smokeDetector, threeStateSensor,
THSensor, winmatic. Special devices: KS550, HM-CC-TC and the KFM100.
Device messages can only be interpreted correctly if the device type is
known. fhem will extract the device type from a "pairing request"
message, even if it won't respond to it (see hmPairSerial and hmPairForSec to enable pairing).
The so called "AES-Encryption" is in reality a signing request: if it is
enabled, an actor device will only execute a received command, if a
correct answer to a request generated by the actor is received. This
means:
Reaction to commands is noticably slower, as 3 messages are sent
instead of one before the action is processed by the actor.
Every command and its final ack from the device is sent in clear,
so an outside observer will know the status of each device.
The firmware implementation is buggy: the "toggle" event is executed
before the answer for the signing request is received, at
least by some switches (HM-LC-Sw1-Pl and HM-LC-SW2-PB-FM).
The HMLAN configurator will answer signing
requests by itself, and if it is configured with the 3-byte address
of a foreign CCU which is still configurerd with the default
password, it is able to answer signing requests correctly.
AES-Encryption is useable with a HMLAN or a CUL. When using
a CUL, the perl-module Crypt::Rijndael needs to be installed.
Due to the issues above I do not recommend using Homematic
encryption at all.
Set
Note: devices which are normally send-only (remote/sensor/etc) must be set
into pairing/learning mode in order to receive the following commands.
Universal commands (available to most hm devices):
assignHmKey
Initiates a key-exchange with the device, exchanging the old AES-key of the device with the key with the highest
index defined by the attribute hmKey* in the HMLAN or VCCU. The old key is determined by the reading aesKeyNbr,
which specifies the index of the old key when the reading is divided by 2.
clear <[rssi|readings|register|msgEvents|attack|all]>
A set of variables or readings can be removed.
readings: all readings are removed. Any new reading will be added usual. Used to eliminate old data.
register: all captured register-readings in FHEM are removed. NO impact to the device.
msgEvents: all message event counter are removed. Also commandstack is cleared.
msgErrors: message-error counter are removed.
rssi: collected rssi values are cleared.
attack: information regarding an attack are removed.
trigger: all trigger readings are removed.
all: all of the above.
getConfig
Will read configuration of the physical HM device. Executed
on a channel it reads peerings and register information.
Executed on a device the command will retrieve configuration for ALL associated channels.
getRegRaw [List0|List1|List2|List3|List4|List5|List6|List7]<peerChannel>
Read registerset in raw format. Description of the registers is beyond
the scope of this documentation.
Registers are structured in so called lists each containing a set of
registers.
List0: device-level settings e.g. CUL-pairing or dimmer thermal limit
settings.
List1: per channel settings e.g. time to drive the blind up and
down.
List3: per 'link' settings - means per peer-channel. This is a lot of
data!. It controlls actions taken upon receive of a trigger from the
peer.
List4: settings for channel (button) of a remote
<PeerChannel> paired HMid+ch, i.e. 4 byte (8 digit) value like
'12345601'. It is mendatory for List 3 and 4 and can be left out for
List 0 and 1.
'all' can be used to get data of each paired link of the channel.
'selfxx' can be used to address data for internal channels (associated
with the build-in switches if any). xx is the number of the channel in
decimal.
Note1: execution depends on the entity. If List1 is requested on a
device rather then a channel the command will retrieve List1 for all
channels assotiated. List3 with peerChannel = all will get all link
for all channel if executed on a device.
Note2: for 'sender' see remote
Note3: the information retrieval may take a while - especially for
devices with a lot of channels and links. It may be necessary to
refresh the web interface manually to view the results
Note4: the direct buttons on a HM device are hidden by default.
Nevertheless those are implemented as links as well. To get access to
the 'internal links' it is necessary to issue
'set <name> regSet intKeyVisib visib'
or
'set <name> regBulk RegL_0. 2:81'
Reset it by replacing '81' with '01' example:
set mydimmer getRegRaw List1
set mydimmer getRegRaw List3 all
getSerial
Read serial number from device and write it to attribute serialNr.
inhibit [on|off]
Block / unblock all changes to the actor channel, i.e. actor state is frozen
until inhibit is set off again. Inhibit can be executed on any actor channel
but obviously not on sensors - would not make any sense.
Practically it can be used to suspend any notifies as well as peered channel action
temporarily without the need to delete them.
Examples:
# Block operation
set keymatic inhibit on
pair
Pair the device with a known serialNumber (e.g. after a device reset)
to FHEM Central unit. FHEM Central is usualy represented by CUL/CUNO,
HMLAN,...
If paired, devices will report status information to
FHEM. If not paired, the device won't respond to some requests, and
certain status information is also not reported. Paring is on device
level. Channels cannot be paired to central separate from the device.
See also getPair and
unpair.
Don't confuse pair (to a central) with peer (channel to channel) with
peerChan.
peerBulk <peerch1,peerch2,...> [set|unset]
peerBulk will add peer channels to the channel. All peers in the list will be added.
with unset option the peers in the list will be subtracted from the device's peerList.
peering sets the configuration of this link to its defaults. As peers are not
added in pairs default will be as defined for 'single' by HM for this device.
More suffisticated funktionality is provided by
peerChan.
peerBulk will not delete existing peers, just handle the given peerlist.
Other already installed peers will not be touched.
peerBulk may be used to remove peers using unset option while default ist set.
Main purpose of this command is to re-store data to a device.
It is recommended to restore register configuration utilising
regBulk subsequent.
Example:
set myChannel peerBulk 12345601,
set myChannel peerBulk self01,self02,FB_Btn_04,FB_Btn_03,
set myChannel peerBulk 12345601 unset # remove peer 123456 channel 01
regBulk <reg List>.<peer> <addr1:data1> <addr2:data2>...
This command will replace the former regRaw. It allows to set register
in raw format. Its main purpose is to restore a complete register list
to values secured before.
Values may be read by getConfig. The
resulting readings can be used directly for this command.
<reg List> is the list data should be written to. Format could be
'00', 'RegL_00', '01'...
<peer> is an optional adder in case the list requires a peer.
The peer can be given as channel name or the 4 byte (8 chars) HM
channel ID.
<addr1:data1> is the list of register to be written in hex
format.
Example:
myblind will set the max drive time up for a blind actor to 25,6sec
regSet [prep|exec] <regName> <value> <peerChannel>
For some major register a readable version is implemented supporting
register names <regName> and value conversionsing. Only a subset
of register can be supproted.
Optional parameter [prep|exec] allowes to pack the messages and therefore greatly
improve data transmission.
Usage is to send the commands with paramenter "prep". The data will be accumulated for send.
The last command must have the parameter "exec" in order to transmitt the information.
<value> is the data in human readable manner that will be written
to the register.
<peerChannel> is required if this register is defined on a per
'peerChan' base. It can be set to '0' other wise.See getRegRaw for full description
Supported register for a device can be explored using
set regSet ? 0 0
Condensed register description will be printed
using
set regSet <regname> ? 0
reset
Factory reset the device. You need to pair it again to use it with
fhem.
sign [on|off]
Activate or deactivate signing (also called AES encryption, see the note above). Warning: if the device is attached via
a CUL, you need to install the perl-module Crypt::Rijndael to be
able to switch it (or deactivate signing) from fhem.
statusRequest
Update device status. For multichannel devices it should be issued on
an per channel base
unpair
"Unpair" the device, i.e. make it available to pair with other master
devices. See pair for description.
virtual <number of buttons>
configures a defined curcuit as virtual remote controll. Then number
of button being added is 1 to 255. If the command is issued a second
time for the same entity additional buttons will be added.
Example for usage:
define vRemote CUL_HM 100000 # the selected HMid must not be in use
set vRemote virtual 20 # define 20 button remote controll
set vRemote_Btn4 peerChan 0 <actorchannel> # peers Button 4 and 5 to the given channel
set vRemote_Btn4 press
set vRemote_Btn5 press long
deviceRename <newName>
rename the device and all its channels.
fwUpdate [onlyEnterBootLoader] <filename> [<waitTime>]
update Fw of the device. User must provide the appropriate file.
waitTime can be given optionally. In case the device needs to be set to
FW update mode manually this is the time the system will wait.
"onlyEnterBootLoader" tells the device to enter the boot loader so it can be
flashed using the eq3 firmware update tool. Mainly useful for flush-mounted devices
in FHEM environments solely using HM-LAN adapters.
assignIO <IOname> <set|unset>
Add or remove an IO device to the list of available IO's.
Changes attribute IOList accordingly.
subType dependent commands:
switch
on - set level to 100%
off - set level to 0%
on-for-timer <sec> -
set the switch on for the given seconds [0-85825945]. Note:
off-for-timer like FS20 is not supported. It may to be programmed
thru channel register.
on-till <time> - set the switch on for the given end time.
set <name> on-till 20:32:10
Currently a max of 24h is supported with endtime.
pressL <peer> [<repCount>] [<repDelay>]
simulate a press of the local button or direct connected switch of the actor. <peer> allows to stimulate button-press of any peer of the actor.
i.e. if the actor is peered to any remote, virtual or io (HMLAN/CUL)
press can trigger the action defined. <repCount> number of automatic repetitions. <repDelay> timer between automatic repetitions. Example:
set actor pressL FB_Btn01 # trigger long peer FB button 01
set actor pressL FB_chn-8 # trigger long peer FB button 08
set actor pressL self01 # trigger short of internal peer 01
set actor pressL fhem02 # trigger short of FHEM channel 2
pressS <peer>
simulates a short press similar to long press
eventL <peer> <condition> [<repCount>] [<repDelay>]
simulate an event of an peer and stimulates the actor. <peer> allows to stimulate button-press of any peer of the actor.
i.e. if the actor is peered to any remote, virtual or io (HMLAN/CUL)
press can trigger the action defined. <codition> the level of the condition Example:
set actor eventL md 30 # trigger from motion detector with level 30
eventS <peer> <condition>
simulates a short event from a peer of the actor. Typically sensor do not send long events.
toggle - toggle the Actor. It will switch from any current
level to off or from off to 100%
dimmer, blindActuator
Dimmer may support virtual channels. Those are autocrated if applicable. Usually there are 2 virtual channels
in addition to the primary channel. Virtual dimmer channels are inactive by default but can be used in
in parallel to the primay channel to control light.
Virtual channels have default naming SW<channel>_V<no>. e.g. Dimmer_SW1_V1 and Dimmer_SW1_V2.
Dimmer virtual channels are completely different from FHEM virtual buttons and actors but
are part of the HM device. Documentation and capabilities for virtual channels is out of scope.
0 - 100 [on-time] [ramp-time]
set the actuator to the given value (in percent)
with a resolution of 0.5.
Optional for dimmer on-time and ramp time can be choosen, both in seconds with 0.1s granularity.
On-time is analog "on-for-timer".
Ramp-time default is 2.5s, 0 means instantanous
old - switch back to old value after a change. Dimmer only.
pct <level> [<ontime>] [<ramptime>] - set actor to a desired absolut level.
Optional ontime and ramptime could be given for dimmer.
ontime may be time in seconds. It may also be entered as end-time in format hh:mm:ss
up [changeValue] [<ontime>] [<ramptime>] dim up one step
down [changeValue] [<ontime>] [<ramptime>] dim up one step
changeValue is optional an gives the level to be changed up or down in percent. Granularity is 0.5%, default is 10%.
ontime is optional an gives the duration of the level to be kept. '0' means forever and is default.
ramptime is optional an defines the change speed to reach the new level. It is meaningful only for dimmer.
remotes, pushButton
This class of devices does not react on requests unless they are put
to learn mode. FHEM obeys this behavior by stacking all requests until
learn mode is detected. Manual interaction of the user is necessary to
activate learn mode. Whether commands are pending is reported on
device level with parameter 'protCmdPend'.
trgEventS [all|<peer>] <condition>
Issue eventS on the peer entity. If all is selected each of the peers will be triggered. See also eventS <condition>: is the condition being transmitted with the event. E.g. the brightness in case of a motion detector.
trgEventL [all|<peer>] <condition>
Issue eventL on the peer entity. If all is selected each of the peers will be triggered. a normal device will not sent event long. See also eventL <condition>: is the condition being transmitted with the event. E.g. the brightness in case of a motion detector.
trgPressS [all|<peer>]
Issue pressS on the peer entity. If all is selected each of the peers will be triggered. See also pressS
trgPressL [all|<peer>]
Issue pressL on the peer entity. If all is selected each of the peers will be triggered. See also pressL
peerIODev [IO] <btn_no> [set|unset]
The command is similar to peerChan.
While peerChan
is executed on a remote and peers any remote to any actor channel peerIODev is
executed on an actor channel and peer this to an channel of an FHEM IO device.
An IO device according to eQ3 supports up to 50 virtual buttons. Those
will be peered/unpeerd to the actor. press can be
used to stimulate the related actions as defined in the actor register.
peerSmart [<peer>]
The command is similar to peerChan
with reduced options for peer and unpeer.
peerSmart peers in single mode (see peerChan) while funktionallity should be defined
by setting register (not much difference to peerChan).
Smart register setting could be done using hmTemplate.
peerChan <btn_no> <actChan> [single|dual|reverse][set|unset] [both|actor|remote]
peerChan will establish a connection between a sender- channel and
an actuator-channel called link in HM nomenclatur. Peering must not be
confused with pairing. Pairing refers to assign a device to the central. Peering refers to virtally connect two channels.
Peering allowes direkt interaction between sender and aktor without
the necessity of a CCU
Peering a sender-channel causes the sender to expect an ack from -each-
of its peers after sending a trigger. It will give positive feedback (e.g. LED green)
only if all peers acknowledged.
Peering an aktor-channel will setup a parameter set which defines the action to be
taken once a trigger from -this- peer arrived. In other words an aktor will
- process trigger from peers only
- define the action to be taken dedicated for each peer's trigger
An actor channel will setup a default action upon peering - which is actor dependant.
It may also depend whether one or 2 buttons are peered in one command.
A swich may setup oen button for 'on' and the other for 'off' if 2 button are
peered. If only one button is peered the funktion will likely be 'toggle'.
The funtion can be modified by programming the register (aktor dependant).
Even though the command is executed on a remote or push-button it will
as well take effect on the actuator directly. Both sides' peering is
virtually independant and has different impact on sender and receiver
side.
Peering of one actuator-channel to multiple sender-channel as
well as one sender-channel to multiple Actuator-channel is
possible.
<actChan> is the actuator-channel to be peered.
<btn_no> is the sender-channel (button) to be peered. If
'single' is choosen buttons are counted from 1. For 'dual' btn_no is
the number of the Button-pair to be used. I.e. '3' in dual is the
3rd button pair correcponding to button 5 and 6 in single mode.
If the command is executed on a channel the btn_no is ignored.
It needs to be set, should be 0
[single|dual]: this mode impacts the default behavior of the
Actuator upon using this button. E.g. a dimmer can be learned to a
single button or to a button pair.
Defaults to dual.
'dual' (default) Button pairs two buttons to one actuator. With a
dimmer this means one button for dim-up and one for dim-down.
'reverse' identical to dual - but button order is reverse.
'single' uses only one button of the sender. It is useful for e.g. for
simple switch actuator to toggle on/off. Nevertheless also dimmer can
be learned to only one button.
[set|unset]: selects either enter a peering or remove it.
Defaults to set.
'set' will setup peering for the channels
'unset' will remove the peering for the channels
[actor|remote|both] limits the execution to only actor or only remote.
This gives the user the option to redo the peering on the remote
channel while the settings in the actor will not be removed.
Defaults to both.
Example:
set myRemote peerChan 2 mySwActChn single set #peer second button to an actuator channel
set myRmtBtn peerChan 0 mySwActChn single set #myRmtBtn is a button of the remote. '0' is not processed here
set myRemote peerChan 2 mySwActChn dual set #peer button 3 and 4
set myRemote peerChan 3 mySwActChn dual unset #remove peering for button 5 and 6
set myRemote peerChan 3 mySwActChn dual unset aktor #remove peering for button 5 and 6 in actor only
set myRemote peerChan 3 mySwActChn dual set remote #peer button 5 and 6 on remote only. Link settings il mySwActChn will be maintained
simulates button press for an actor from a peered sensor.
will be sent of type "long".
[long|short] defines whether long or short press shall be simulated. Defaults to short
[<peer>] define which peer's trigger shall be simulated.Defaults to self(channelNo).
[<repCount>] Valid for long press only. How long shall the button be pressed? Number of repetition of the messages is defined. Defaults to 1
[<repDelay>] Valid for long press only. defines wait time between the single messages.
virtTemp <[off -10..50]>
simulates a thermostat. If peered to a device it periodically sends the
temperature until "off" is given. See also virtHum
virtHum <[off -10..50]>
simulates the humidity part of a thermostat. If peered to a device it periodically sends
the temperature and humidity until both are "off". See also virtTemp
valvePos <[off 0..100]>
stimulates a VD
smokeDetector
Note: All these commands work right now only if you have more then one
smoekDetector, and you peered them to form a group. For issuing the
commands you have to use the master of this group, and currently you
have to guess which of the detectors is the master.
smokeDetector can be setup to teams using
peerChan. You need to peer all
team-members to the master. Don't forget to also peerChan the master
itself to the team - i.e. peer it to itself! doing that you have full
controll over the team and don't need to guess.
teamCall - execute a network test to all team members
teamCallBat - execute a network test simulate bat low
text <btn_no> [on|off] <text1> <text2>
Set the text on the display of the device. To this purpose issue
this set command first (or a number of them), and then choose from
the teach-in menu of the 4Dis the "Central" to transmit the data.
If used on a channel btn_no and on|off must not be given but only pure text.
\_ will be replaced by blank character.
Example:
set 4Dis text 1 on On Lamp
set 4Dis text 1 off Kitchen Off
set 4Dis_chn4 text Kitchen Off
Climate-Control (HM-CC-TC)
desired-temp <temp>
Set different temperatures. <temp> must be between 6 and 30
Celsius, and precision is half a degree.
tempListSat [prep|exec] HH:MM temp ... 24:00 temp
tempListSun [prep|exec] HH:MM temp ... 24:00 temp
tempListMon [prep|exec] HH:MM temp ... 24:00 temp
tempListTue [prep|exec] HH:MM temp ... 24:00 temp
tempListThu [prep|exec] HH:MM temp ... 24:00 temp
tempListWed [prep|exec] HH:MM temp ... 24:00 temp
tempListFri [prep|exec] HH:MM temp ... 24:00 temp
Specify a list of temperature intervals. Up to 24 intervals can be
specified for each week day, the resolution is 10 Minutes. The
last time spec must always be 24:00.
Example: until 6:00 temperature shall be 19, from then until 23:00 temperature shall be
22.5, thereafter until midnight, 19 degrees celsius is desired. set th tempListSat 06:00 19 23:00 22.5 24:00 19
tempListTmpl =>"[verify|restore] [[ <file> :]templateName] ...
The tempList for one or more devices can be stored in a file. User can compare the
tempList in the file with the data read from the device.
Restore will write the tempList to the device.
Default opeartion is verify.
Default file is tempList.cfg.
Default templateName is the name of the actor
Default for file and templateName can be set with attribut tempListTmpl
Example for templist file. room1 and room2 are the names of the template: entities:room1
tempListSat>08:00 16.0 15:00 18.0 21:30 19.0 24:00 14.0
tempListSun>08:00 16.0 15:00 18.0 21:30 19.0 24:00 14.0
tempListMon>07:00 16.0 16:00 18.0 21:00 19.0 24:00 14.0
tempListTue>07:00 16.0 13:00 16.0 16:00 18.0 21:00 19.0 24:00 15.0
tempListWed>07:00 16.0 16:00 18.0 21:00 19.0 24:00 14.0
tempListThu>07:00 16.0 16:00 18.0 21:00 19.0 24:00 14.0
tempListFri>07:00 16.0 13:00 16.0 16:00 18.0 21:00 19.0 24:00 14.0
entities:room2
tempListSat>08:00 14.0 15:00 18.0 21:30 19.0 24:00 14.0
tempListSun>08:00 14.0 15:00 18.0 21:30 19.0 24:00 14.0
tempListMon>07:00 14.0 16:00 18.0 21:00 19.0 24:00 14.0
tempListTue>07:00 14.0 13:00 16.0 16:00 18.0 21:00 19.0 24:00 15.0
tempListWed>07:00 14.0 16:00 18.0 21:00 19.0 24:00 14.0
tempListThu>07:00 14.0 16:00 18.0 21:00 19.0 24:00 14.0
tempListFri>07:00 14.0 13:00 16.0 16:00 18.0 21:00 19.0 24:00 14.0
Specials:
none: template will be ignored
defaultWeekplan: as default each day is set to 18.0 degree.
useful if peered to a TC controller. Implicitely teh weekplan of TC will be used.
tempTmplSet =>"[[ <file> :]templateName]
Set the attribut and apply the change to the device
tplDel =>" <template>
Delete template entry for this entity
tplSet_<peer> =>" <template>
Set a template for a peer of the entity. Possible parameter will be set to the current register value of the device - i.e. no change to the register. Parameter may be changed after assigning the template by using the tplPara command.
The command is avalilable if HMinfo is defined and a tamplate fitting the combination is available. Note that the register of the device need to be available (see getConfig command).
In case of dedicated template for long and short trigger separat commands will be available.
tplParaxxx_<peer>_<tpl>_<param> =>" <template>
A parameter of an assigned template can be modified. A command s available for each parameter of each assigned template.
partyMode <HH:MM><durationDays>
set control mode to party and device ending time. Add the time it ends
and the number of days it shall last. If it shall end next day '1'
must be entered
sysTime
set time in climate channel to system time
Climate-Control (HM-CC-RT-DN|HM-CC-RT-DN-BOM)
controlMode <auto|boost|day|night>
controlManu <temp>
controlParty <temp><startDate><startTime><endDate><endTime>
set control mode to party, define temp and timeframe.
example: set controlParty 15 03-8-13 20:30 5-8-13 11:30
sysTime
set time in climate channel to system time
desired-temp <temp>
Set different temperatures. <temp> must be between 6 and 30
Celsius, and precision is half a degree.
tempListSat [prep|exec] HH:MM temp ... 24:00 temp
tempListSun [prep|exec] HH:MM temp ... 24:00 temp
tempListMon [prep|exec] HH:MM temp ... 24:00 temp
tempListTue [prep|exec] HH:MM temp ... 24:00 temp
tempListThu [prep|exec] HH:MM temp ... 24:00 temp
tempListWed [prep|exec] HH:MM temp ... 24:00 temp
tempListFri [prep|exec] HH:MM temp ... 24:00 temp
Specify a list of temperature intervals. Up to 24 intervals can be
specified for each week day, the resolution is 10 Minutes. The
last time spec must always be 24:00.
Optional parameter [prep|exec] allowes to pack the messages and therefore greatly
improve data transmission. This is especially helpful if device is operated in wakeup mode.
Usage is to send the commands with paramenter "prep". The data will be accumulated for send.
The last command must have the parameter "exec" in order to transmitt the information.
Example: until 6:00 temperature shall be 19, from then until 23:00 temperature shall be
22.5, thereafter until midnight, 19 degrees celsius is desired. set th tempListSat 06:00 19 23:00 22.5 24:00 19
set th tempListSat prep 06:00 19 23:00 22.5 24:00 19
set th tempListSun prep 06:00 19 23:00 22.5 24:00 19
set th tempListMon prep 06:00 19 23:00 22.5 24:00 19
set th tempListTue exec 06:00 19 23:00 22.5 24:00 19
OutputUnit (HM-OU-LED16)
led [off|red|green|yellow]
switches the LED of the channel to the color. If the command is
executed on a device it will set all LEDs to the specified
color.
For Expert all LEDs can be set individual by providing a 8-digit hex number to the device.
ilum <brightness><duration>
<brightness> [0-15] of backlight.
<duration> [0-127] in sec. 0 is permanent 'on'.
OutputUnit (HM-OU-CFM-PL)
led <color>[,<color>..] [<repeat>..]
Possible colors are [redL|greenL|yellowL|redS|greenS|yellowS|pause]. A
sequence of colors can be given separating the color entries by ','.
White spaces must not be used in the list. 'S' indicates short and
'L' long ilumination. repeat defines how often the sequence shall be executed. Defaults to 1.
playTone <MP3No>[,<MP3No>..] [<repeat>] [<volume>]
Play a series of tones. List is to be entered separated by ','. White
spaces must not be used in the list. replay can be entered to repeat the last sound played once more. repeat defines how often the sequence shall be played. Defaults to 1. volume is defined between 0 and 10. 0 stops any sound currently playing. Defaults to 10 (100%).
Example:
# "hello" in display, symb bulb on, backlight, beep
set cfm_Mp3 playTone 3 # MP3 title 3 once
set cfm_Mp3 playTone 3 3 # MP3 title 3 3 times
set cfm_Mp3 playTone 3,6,8,3,4 # MP3 title list 3,6,8,3,4 once
set cfm_Mp3 playTone 3,6,8,3,4 255# MP3 title list 3,6,8,3,4 255 times
set cfm_Mp3 playTone replay # repeat last sequence
set cfm_Led led redL 4 # led red blink 3 times long
set cfm_Led led redS,redS,redS,redL,redL,redL,redS,redS,redS 255 # SOS 255 times
HM-RC-19xxx
alarm <count>
issue an alarm message to the remote
service <count>
issue an service message to the remote
symbol <symbol> [set|unset]
activate a symbol as available on the remote.
beep [off|1|2|3]
activate tone
backlight [off|on|slow|fast]
activate backlight
display <text> comma unit tone backlight <symbol(s)>
control display of the remote
<text> : up to 5 chars
comma : 'comma' activates the comma, 'no' leaves it off
[unit] : set the unit symbols.
[off|Proz|Watt|x3|C|x5|x6|x7|F|x9|x10|x11|x12|x13|x14|x15]. Currently
the x3..x15 display is not tested.
tone : activate one of the 3 tones [off|1|2|3]
backlight: activate backlight flash mode [off|on|slow|fast]
<symbol(s)> activate symbol display. Multople symbols can be
acticated at the same time, concatinating them comma separated. Don't
use spaces here. Possiblesymbols are
[bulb|switch|window|door|blind|scene|phone|bell|clock|arrowUp|arrowDown]
Example:
# "hello" in display, symb bulb on, backlight, beep
set FB1 display Hello no off 1 on bulb
# "1234,5" in display with unit 'W'. Symbols scene,phone,bell and
# clock are active. Backlight flashing fast, Beep is second tone
set FB1 display 12345 comma Watt 2 fast scene,phone,bell,clock
HM-DIS-WM55
displayWM help displayWM [long|short] <text1> <color1> <icon1> ... <text6> <color6> <icon6> displayWM [long|short] <lineX> <text> <color> <icon>
up to 6 lines can be addressed. lineX line number that shall be changed. If this is set the 3 parameter of a line can be adapted. textNo is the text to be dispalyed in line No. The text is assotiated with the text defined for the buttons.
txt<BtnNo>_<lineNo> references channel 1 to 10 and their lines 1 or 2.
Alternaly a free text of up to 12 char can be used color is one white, red, orange, yellow, green, blue icon is one off, on, open, closed, error, ok, noIcon
Example:
set disp01 displayWM short txt02_2 green noIcon txt10_1 red error txt05_2 yellow closed txt02_2 orange open
set disp01 displayWM long line3 txt02_2 green noIcon
set disp01 displayWM long line2 nc yellow noIcon
set disp01 displayWM long line6 txt02_2
set disp01 displayWM long line1 nc nc closed
HM-DIS-EP-WM55
displayEP help displayEP <text1,icon1:text2,icon2:text3,icon3> <sound> <repetition> <pause> <signal>
up to 3 lines can be addressed.
If help is given a help on the command is given. Options for all parameter will be given. textx 12 char text for the given line.
If empty the value as per reading will be transmittet - i.e. typically no change.
text0-9 will display predefined text of channels 4 to 8.
0xHH allows to display a single char in hex format. iconx Icon for this line.
If empty the value as per reading will be transmittet - i.e. typically no change. sound sound to be played repetition 0..15 pause 1..160 signal signal color to be displayed
Note: param reWriteDisplayxx
upon button press the device will overwrite the 3 middles lines. When set
attr chan param reWriteDisplayxx
the 3 lines will be rewritten to the latest value after xx seconds. xx is between 01 and 99
keyMatic
The Keymatic uses the AES signed communication. Control
of the Keymatic is possible with the HM-LAN adapter and the CUL.
To control the KeyMatic with a CUL, the perl-module Crypt::Rijndael
needs to be installed.
lock
The lock bolt moves to the locking position
unlock [sec]
The lock bolt moves to the unlocking position.
[sec]: Sets the delay in seconds after the lock automatically locked again.
0 - 65535 seconds
open [sec]
Unlocked the door so that the door can be opened.
[sec]: Sets the delay in seconds after the lock automatically locked
again. 0 - 65535 seconds
winMatic
winMatic provides 2 channels, one for the window control and a second
for the accumulator.
level <level> <relockDelay> <speed>
set the level.
<level>: range is 0 to 100%
<relockDelay>: range 0 to 65535 sec. 'ignore' can be used to igneore the value alternaly
<speed>: range is 0 to 100%
stop
stop movement
CCU_FHEM
defIgnUnknown
define unknown devices which are present in the readings.
set attr ignore and remove the readingfrom the list.
HM-SYS-SRP-PL
setup the repeater's entries. Up to 36entries can be applied.
setRepeat <entry> <sender> <receiver> <broadcast>
<entry> [1..36] entry number in repeater table. The repeater can handle up to 36 entries.
<sender> name or HMID of the sender or source which shall be repeated
<receiver> name or HMID of the receiver or destination which shall be repeated
<broadcast> [yes|no] determines whether broadcast from this ID shall be repeated
short application: setRepeat setAll 0 0 0
will rewrite the complete list to the deivce. Data will be taken from attribut repPeers.
attribut repPeers is formated:
src1:dst1:[y/n],src2:dst2:[y/n],src2:dst2:[y/n],...
Reading repPeer is formated:
Number src dst broadcast verify
number: entry sequence number
src: message source device - read from repeater
dst: message destination device - assembled from attributes
broadcast: shall broadcast be repeated for this source - read from repeater
verify: do attributes and readings match?
Debugging:
raw <data> ...
Only needed for experimentation.
send a "raw" command. The length will be computed automatically, and the
message counter will be incremented if the first two charcters are
++. Example (enable AES):
set hm1 raw ++A001F100001234560105000000001
Get
configSave <filename>
Saves the configuration of an entity into a file. Data is stored in a
format to be executed from fhem command prompt.
The file is located in the fhem home directory aside of fhem.cfg. Data
will be stored cumulative - i.e. new data will be appended to the
file. It is up to the user to avoid duplicate storage of the same
entity.
Target of the data is ONLY the HM-device information which is located
IN the HM device. Explicitely this is the peer-list and the register.
With the register also the peering is included.
The file is readable and editable by the user. Additionaly timestamps
are stored to help user to validate.
Restrictions:
Even though all data of the entity will be secured to the file FHEM
stores the data that is avalilable to FHEM at time of save!. It is up
to the user to read the data from the HM-hardware prior to execution.
See recommended flow below.
This command will not store any FHEM attributes o device definitions.
This continues to remain in fhem.cfg.
Furthermore the secured data will not automatically be reloaded to the
HM-hardware. It is up to the user to perform a restore.
As with other commands also 'configSave' is best executed on a device
rather then on a channel. If executed on a device also the assotiated
channel data will be secured.
Recommended work-order for device 'HMdev':
set HMdev clear msgEvents # clear old events to better check flow
set HMdev getConfig # read device & channel inforamtion
# wait until operation is complete
# protState should be CMDs_done
# there shall be no warnings amongst prot... variables
get configSave myActorFile
param <paramName>
returns the content of the relevant parameter for the entity.
Note: if this command is executed on a channel and 'model' is
requested the content hosting device's 'model' will be returned.
reg <addr> <list> <peerID>
returns the value of a register. The data is taken from the storage in FHEM and not
read directly outof the device.
If register content is not present please use getConfig, getReg in advance.
<addr> address in hex of the register. Registername can be used alternaly
if decoded by FHEM. "all" will return all decoded register for this entity in one list.
<list> list from which the register is taken. If rgistername is used list
is ignored and can be set to 0.
<peerID> identifies the registerbank in case of list3 and list4. It an be set to dummy if not used.
regVal <addr> <list> <peerID>
returns the value of a register. It does the same as reg but strips off units
regList
returns a list of register that are decoded by FHEM for this device.
Note that there could be more register implemented for a device.
saveConfig <file>
stores peers and register to the file.
Stored will be the data as available in fhem. It is necessary to read the information from the device prior to the save.
The command supports device-level action. I.e. if executed on a device also all related channel entities will be stored implicitely.
Storage to the file will be cumulative.
If an entity is stored multiple times to the same file data will be appended.
User can identify time of storage in the file if necessary.
Content of the file can be used to restore device configuration.
It will restore all peers and all register to the entity.
Constrains/Restrictions:
prior to rewrite data to an entity it is necessary to pair the device with FHEM.
restore will not delete any peered channels, it will just add peer channels.
list (normal|hidden);
issue list command for the fiven entity normal or including the hidden parameter
listDevice
when used with ccu it returns a list of Devices using the ccu service to assign an IO.
when used with ActionDetector user will get a comma separated list of entities being assigned to the action detector
get ActionDetector listDevice # returns all assigned entities
get ActionDetector listDevice notActive# returns entities which habe not status alive
get ActionDetector listDevice alive # returns entities with status alive
get ActionDetector listDevice unknown # returns entities with status unknown
get ActionDetector listDevice dead # returns entities with status dead
info
provides information about entities using ActionDetector
actAutoTry
actAutoTry 0_off,1_on
setting this option enables Action Detector to send a statusrequest in case of a device is going to be marked dead.
The attribut may be useful in case a device is being checked that does not send messages regularely - e.g. an ordinary switch.
actCycle <[hhh:mm]|off>
Supports 'alive' or better 'not alive' detection for devices. [hhh:mm] is the maximum silent time for the device.
Upon no message received in this period an event will be raised "<device> is dead".
If the device sends again another notification is posted "<device> is alive".
This actiondetect will be autocreated for each device with build in cyclic status report.
Controlling entity is a pseudo device "ActionDetector" with HMId "000000".
Due to performance considerations the report latency is set to 600sec (10min).
It can be controlled by the attribute "actCycle" of "ActionDetector".
Once entered to the supervision the HM device has 2 attributes:
actStatus: activity status of the device
actCycle: detection period [hhh:mm]
The overall function can be viewed checking out the "ActionDetector" entity. The status of all entities is present in the READING section.
Note: This function can be enabled for devices with non-cyclic messages as well. It is up to the user to enter a reasonable cycletime.
actStatus
readonly
This attribut is set by ActionDetector. It cannot be set manually
aesCommReq
if set IO is forced to request AES signature before sending ACK to the device.
Defautls to 0
aesKey
specifies which aes key is to be used if aesCommReq is active
autoReadReg
'0' autoReadReg will be ignored.
'1' will execute a getConfig for the device automatically after each reboot of FHEM.
'2' like '1' plus execute after power_on.
'3' includes '2' plus updates on writes to the device
'4' includes '3' plus tries to request status if it seems to be missing
'5' checks reglist and peerlist. If reading seems incomplete getConfig will be scheduled
'8_stateOnly' will only update status information but not configuration
data like register and peer
Execution will be delayed in order to prevent congestion at startup. Therefore the update
of the readings and the display will be delayed depending on the size of the database.
Recommendations and constrains upon usage:
usage on devices which only react to 'config' mode is not recommended since executen will
not start until config is triggered by the user
usage on devices which support wakeup-mode is usefull. But consider that execution is delayed
until the device "wakes up".
burstAccess
can be set for the device entity if the model allowes conditionalBurst.
The attribut will switch off burst operations (0_off) which causes less message load
on HMLAN and therefore reduces the chance of HMLAN overload.
Setting it on (1_auto) allowes shorter reaction time of the device. User does not
need to wait for the device to wake up.
Note that also the register burstRx needs to be set in the device.
expert <option1[[,option2],...]>
This attribut controls the visibility of the register readings. This attibute controls
the presentation of device parameter in readings.
Options are:
defReg : default register
allReg : all register
rawReg : raw reading
templ : template assiciation
none : no register
If expert is applied to the device it is used for assotiated channels if not overwritten by it.
communication status copied to channel reading
on: device communication status not visible in channel entities
off: device communication status commState is visiblein channel entities
firmware <FWversion>
Firmware version of the device. Should not be overwritten.
hmKey <key>
AES key to be used
hmProtocolEvents
parses and logs the device messages. This is performance consuming and may disturb the timing. Use with care.
Options:
0_off : no parsing - default
1_dump : log all messages
2_dumpFull : log with extended parsing
3_dumpTrigger : log full and include trigger events
readOnly
1: restricts commands to read od observ only.
readingOnDead
defines how readings shall be treated upon device is marked 'dead'.
The attribute is applicable for devices only. It will modify the readings upon entering dead of the device.
Upon leaving state 'dead' the selected readings will be set to 'notDead'. It is expected that useful values will be filled by the normally operating device.
Options are:
noChange: no readings will be changed upon entering 'dead' except Actvity. Other valvues will be ignored
state: set the entites 'state' readings to dead
periodValues: set periodic numeric readings of the device to '0'
periodString: set periodic string readings of the device to 'dead'
channels: if set the device's channels will be effected identical to the device entity
custom readings: customer may add a list of other readings that will be set to 'dead'
Example:
attr myDevice readingOnDead noChange,state # no dead marking - noChange has priority
attr myDevice readingOnDead state,periodValues,channels # Recommended. reading state of the device and all its channels will be set to 'dead'.
Periodic numerical readings will be set to 0 which influences graphics
attr myDevice readingOnDead state,channels # reading state of the device and all its channels will be set to 'dead'.
attr myDevice readingOnDead periodValues,channels # numeric periodic readings of device and channels will be set to '0'
attr myDevice readingOnDead state,deviceMsg,CommandAccepted # upon entering dead state,deviceMsg and CommandAccepted of the device will be set to 'dead' if available.
rssiLog
can be given to devices, denied for channels. If switched '1' each RSSI entry will be
written to a reading. User may use this to log and generate a graph of RSSI level.
Due to amount of readings and events it is NOT RECOMMENDED to switch it on by default.
IOgrp
can be given to devices and shall point to a virtual CCU.
Setting the attribut will remove attr IODev since it mutual exclusiv.
As a consequence the
VCCU will take care of the assignment to the best suitable IO. It is necessary that a
virtual VCCU is defined and all relevant IO devices are assigned to it. Upon sending the CCU will
check which IO is operational and has the best RSSI performance for this device.
Optional a prefered IO - perfIO can be given. In case this IO is operational it will be selected regardless
of rssi values.
If none is detected in the VCCU's IOList the mechanism is stopped.
Example:
levelRange <min,max>
It defines the usable dimm-range.
Can be used for e.g. LED light starting at 10% and reach maxbrightness at 40%.
levelRange will normalize the level to this range. I.e. set to 100% will physically set the
dimmer to 40%, 1% will set to 10% physically. 0% still switches physially off.
Applies to all level commands as on, up, down, toggle and pct. off and level 0 still sets to physically 0%.
LevelRage does not impact register controlled level and direct peering.
The attribut needs to be set for each virtual channel of a device.
Example:
attr myChannel levelRange 10,80
levelMap <=[:=[:...]]>
the level value valX will be replaced by keyX. Multiple values can be mapped.
modelForce
modelForce overwrites the model attribute. Doing that it converts the device and its channel to the new model.
Reason for this attribute is an eQ3 bug as some devices are delivered with wrong Module IDs.
ATTENTION: changing model id automatically starts reconfiguration of the device and its channels! channels may be deleted or incarnated
model
showes model. This is read only.
subType
showes models subType. This is read only.
serialNr
device serial number. Should not be set manually
msgRepeat
defines number of repetitions if a device doesn't answer in time.
Devices which donly support config mode no repeat ist allowed.
For devices with wakeup mode the device will wait for next wakeup. Lonng delay might be
considered in this case.
Repeat for burst devices will impact HMLAN transmission capacity.
peerIDs
will be filled automatically by getConfig and shows the direct peerings of the channel. Should not be changed by user.
rawToReadable
Used to convert raw KFM100 values to readable data, based on measured
values. E.g. fill slowly your container, while monitoring the
values reported with inform. You'll see:
10 (at 0%)
50 (at 20%)
79 (at 40%)
270 (at 100%)
Apply these values with: "attr KFM100 rawToReadable 10:0 50:20 79:40 270:100".
fhem will do a linear interpolation for values between the bounderies.
tempListTmpl
Sets the default template for a heating controller. If not given the detault template is taken from
file tempList.cfg using the enitity name as template name (e.g. ./tempLict.cfg:RT1_Clima
To avoid template usage set this attribut to 'none' or '0'.
Format is <file>:<templatename>. lt
unit
set the reported unit by the KFM100 if rawToReadable is active. E.g.
attr KFM100 unit Liter
cyclicMsgOffset
when calculating the timestamp for sending the next cyclic message (e.g. weather or valve data) then the value of this attribute
in milliseconds is added to the result. So adjusting this might fix problems for example when weather messages of virtual devices are not received reliably
param defines model specific behavior or functions. Available parameters are (model dependand):
HM-SEN-RD-O offAtPon heat channel only: force heating off after powerOn onAtRain heat channel only: force heating on while status changes to 'rain' and off when it changes to 'dry'
virtuals noOnOff virtual entity will not toggle state when trigger is received. If this parameter is
not given the entity will toggle its state between On and Off with each trigger msgReduce:<No> if channel is used for valvePos it skips every No message
in order to reduce transmit load. Numbers from 0 (no skip) up to 9 can be given.
VD will lose connection with more then 5 skips
blind levelInverse while HM considers 100% as open and 0% as closed this may not be
intuitive to all user. Ny default 100% is open and will be dislayed as 'on'. Setting this param the display will be inverted - 0% will be open and 100% is closed.
NOTE: This will apply to readings and set commands. It does not apply to any register. ponRestoreSmart upon powerup of the device the Blind will drive to expected closest endposition followed by driving to the pre-PON level ponRestoreForce upon powerup of the device the Blind will drive to level 0, then to level 100 followed by driving to the pre-PON level
switch levelInverse siehe blind above.
sensRain siren powerMeter switch dimmer rgb showTimed if timmed is running -till will be added to state.
This results eventually in state on-till which allowes better icon handling.
Generated events:
general
recentStateType:[ack|info] # cannot be used ti trigger notifies
ack indicates that some statusinfo is derived from an acknowledge
info indicates an autonomous message from the device
sabotageAttackId
Alarming configuration access to the device from a unknown source
sabotageAttack
Alarming configuration access to the device that was not issued by our system
trigDst_<name>: noConfig
A sensor triggered a Device which is not present in its peerList. Obviously the peerList is not up to date
HM-CC-TC,ROTO_ZEL-STG-RM-FWT
T: $t H: $h
battery:[low|ok]
measured-temp $t
humidity $h
actuator $vp %
desired-temp $dTemp
desired-temp-manu $dTemp #temperature if switchen to manual mode
desired-temp-cent $dTemp #temperature if switchen to central mode
windowopen-temp-%d %.1f (sensor:%s)
tempList$wd hh:mm $t hh:mm $t ...
displayMode temp-[hum|only]
displayTemp [setpoint|actual]
displayTempUnit [fahrenheit|celsius]
controlMode [auto|manual|central|party]
tempValveMode [Auto|Closed|Open|unknown]
param-change offset=$o1, value=$v1
ValveErrorPosition_for_$dname $vep %
ValveOffset_for_$dname : $of %
ValveErrorPosition $vep %
ValveOffset $of %
time-request
trig_<src> <value> #channel was triggered by <src> channel.
This event relies on complete reading of channels configuration, otherwise Data can be
incomplete or incorrect.
trigLast <channel> #last receiced trigger
HM-CC-VD,ROTO_ZEL-STG-RM-FSA
$vp %
battery:[critical|low|ok]
motorErr:[ok|blocked|loose|adjusting range too small|opening|closing|stop]
ValvePosition:$vp %
ValveErrorPosition:$vep %
ValveOffset:$of %
ValveDesired:$vp % # set by TC
operState:[errorTargetNotMet|onTarget|adjusting|changed] # operational condition
operStateErrCnt:$cnt # number of failed settings
HM-OU-LED16
color $value # hex - for device only
$value # hex - for device only
color [off|red|green|orange] # for channel
[off|red|green|orange] # for channel
remote/pushButton
battery [low|ok]
trigger [Long|Short]_$no trigger event from channel
swi
Btn$x Short
Btn$x Short (to $dest)
battery: [low|ok]
switch/dimmer/blindActuator
$val
powerOn [on|off|$val]
[unknown|motor|dim] [up|down|stop]:$val
timedOn [running|off] # on is temporary - e.g. started with on-for-timer
sensRain
$val
powerOn
level <val≥
timedOn [running|off] # on is temporary - e.g. started with on-for-timer
trigger [Long|Short]_$no trigger event from channel
smokeDetector
[off|smoke-Alarm|alive] # for team leader
[off|smoke-forward|smoke-alarm] # for team members
[normal|added|addedStrong] #HM-CC-SCD
SDteam [add|remove]_$dname
battery [low|ok]
smoke_detect [none|<src>]
teamCall:from $src
threeStateSensor
[open|tilted|closed]
[wet|damp|dry] #HM-SEC-WDS only
cover [open|closed] #HM-SEC-WDS and HM-SEC-RHS
alive yes
battery [low|ok]
contact [open|tilted|closed]
contact [wet|damp|dry] #HM-SEC-WDS only
sabotageError [on|off] #HM-SEC-SC only
The CUL_HOERMANN module registers the 868MHz Hoermann Garage-Door-Opener
signals received by the CUL. Note: As the structure of this signal is
not understood, no checksum is verified, so it is likely to receive bogus
messages.
Define
define <name> CUL_HOERMANN <10-digit-hex-code>
Set
toggle
Send a signal, which, depending on the status of the door, opens it,
closes it or stops the current movement. NOTE: needs culfw 1.67+
The CUL_IR module interprets Infrared messages received by the CUN/CUNO/CUNOv2/TuxRadio.
Those devices can receive Infrared Signals from basically any Remote controller and will transform
that information in a so called Button-Code
<IODev> is the devicename of the IR-receivung device, e.g. CUNO1.
Your definition should look like E.g.:
define IR-Dev CUL_IR CUNO1
Set
irLearnForSec
Sets the CUL_IR device in an IR-Code Learning mode for the given seconds. Any received IR-Code will
be stored as a Button attribute for this devices. The name of these attributes is dependent on the two
attributes learncount and learnprefix.
Attention: Before learning IR-Codes the CUL_IR device needs to be set in IR-Receiving mode
by modifying the irReceive attribute.
irSend
Sends out IR-commands via the connected IODev. The IR-command can be specified as buttonname according
to Button.* or as IR-Code directly. If a buttonname is specified, the
corresponding IR-Code will be sent out.
Example:
set IR-Dev irSend ButtonA001
If defining an IR-Code directly the following Code-Syntax needs to be followed:
IRCode: <PP><AAAA><CCCC><FF>
with P = Protocol; A = Address; C = Command; F = Flags
With the Flags you can modify IR-Repetition. Flags between 00-0E will produce
0-15 IR-Repetitions.
You can type the IR-Code as plain as above, or with a heading "I" as learnt for the buttons.
Example: set IR-Dev irSend 0A07070F0F02
set IR-Dev irSend I0A07070F0F00
irReceive
Configure the IR Transceiver of the <IODev> (the CUNO1). Available
arguments are:
OFF
Switching off the reception of IR signals. This is the default.
ON
Switching on the reception of IR signals. This is WITHOUT filtering repetitions. This is
not recommended as many remote controls do repeat their signals.
ON_NR
Switching on the reception of IR signals with filtering of repetitions. This is
the recommended modus operandi.
Button.*
Button.* is the wildcard for all learnt IR-Codes. IR-Codes are learnt as Button-Attributes.
The name for a learnt Button - IR-Code is compiled out of three elements:
Button<learnprefix><learncount>
When the CUL_IR device is set into learning mode it will generate a
new button-attribute for each new IR-Code received.This is done according to the following syntax:
<Button-Attribute-Name> <IR-Code>
Examples of learnt button-attributes with EMPTY <learnprefix> and <learncount> starting from 1:
Button001 I02029A000000
Button002 I02029A000001
To make sure that something happens when this IR-code is received later on one has to modify the attribute
and to add commands as attribute values.
Examples:
Button001 I02029A000000 set WZ_Lamp on
Button002 I02029A000001 set Switch on
Group.*
Group.* is the wildcard for IR-Code groups. With these attributes one can define
IR-Code parts, which may match to several Button-IR-Codes.
This is done by defining group-attributes that contain only parts of the IR-Code.
The syntax is:
<Group-Attribute-Name> <IR-Code>
Examples of a group-attribute is:
Group001 I02029A
With this all IR-Codes starting with I02029A will match the Group001.
learncount
learncount is used to store the next button-code-number that needs to be learned.
By manually modifying this attribute new button sequences can be arranged.
learnprefix
learnprefix is a string which will be added to the button-attribute-name.
A button-attribute-name is constructed by:
Button<learnprefix><learncount>
If learnprefix is empty the button-attribute-name only contains the term
"Button" and the actual number of learncount.
The CUL_MAX module interprets MAX! messages received by the CUL. It will be automatically created by autocreate, just make sure
that you set the right rfmode like attr CUL0 rfmode MAX.
Define
define <name> CUL_MAX <addr>
Defines an CUL_MAX device of type <type> and rf address <addr>. The rf address
must not be in use by any other MAX device.
Set
pairmode
Sets the CUL_MAX into pairing mode for 60 seconds where it can be paired with
other devices (Thermostats, Buttons, etc.). You also have to set the other device
into pairing mode manually. (For Thermostats, this is pressing the "Boost" button
for 3 seconds, for example).
fakeSC <device> <open>
Sends a fake ShutterContactState message <open> must be 0 or 1 for
"window closed" or "window opened". If the <device> has a non-zero groupId,
the fake ShutterContactState message affects all devices with that groupId.
Make sure you associate the target device(s) with fakeShutterContact beforehand.
fakeWT <device> <desiredTemperature> <measuredTemperature>
Sends a fake WallThermostatControl message (parameters both may have one digit
after the decimal point, for desiredTemperature it may only by 0 or 5).
If the <device> has a non-zero groupId, the fake WallThermostatControl
message affects all devices with that groupId. Make sure you associate the target
device with fakeWallThermostat beforehand.
The CUL_RFR module is used to "attach" a second CUL to your base CUL, and
use it as a repeater / range extender. RFR is shorthand for RF_ROUTER.
Transmission of the data uses the CC1101 packet capabilities with GFSK
modulation at 250kBaud after pinging the base CUL at the usual 1kBaud. After
configured, the RFR device can be used like another CUL connected directly to
FHEM.
In theory every SlowRF protocol should work, as the hook is implemented in
the culfw output routine: instead of sending the data to the USB-Interface it
is transmitted via radio to the base CUL. There are still some restrictions:
due to the ping both CULs have to be in SlowRF mode, and use the same
parameters (freq, bwidth, etc).
the logical module handling the protocol is not allowed to access the
routines of the IODev (i.e. CUL) directly.
Tested protocols are FHT, FS20, EM, HMS, S300.
Since there is no ack or a resend mechanism, it should be primarily used to
forward "unimportant" data, it was developed for forwading KS300 packets.
Before you can use this feature in fhem, you have to enable/configure RF
ROUTING in both CUL's:
First give your base CUL (which remains connected to the PC) an RFR ID
by issuing the fhem command "set MyCUL raw ui0100". With this command
the base CUL will get the ID 01, and it will not relay messages to other
CUL's (as the second number is 00).
Now replace the base CUL with the RFR CUL, and set its id by issuing
the fhem command "set MyCUL raw ui0201". Now remove this CUL and attach the
original, base CUL again. The RFR CUL got the id 02, and will relay every
message to the base CUL with id 01.
Take the RFR CUL, and attach it to an USB power supply, as seen on
the image. As the configured base id is not 00, it will activate RF
reception on boot, and will start sending messages to the base CUL.
Now you have to define this RFR cul as a fhem device:
Define
define <name> CUL_RFR <own-id> <base-id>
<own-id> is the id of the RFR CUL not connected to the PC,
<base-id> is the id of the CUL connected to the PC. Both parameters
have two characters, each representing a one byte hex number.
Example:
set MyCUL raw ui0100
# Now replace the base CUL with the RFR CUL set MyCUL raw ui0201
# Reattach the base CUL to the PC and attach the RFR CUL to a
USB power supply define MyRFR CUL_RFR 02 01
New received device packages are add in fhem category CUL_TCM97001 with autocreate.
Define
The received devices created automatically.
The ID of the defive are the first two Hex values of the package as dezimal.
Generated events:
temperature: The temperature
humidity: The humidity (if available)
battery: The battery state: low or ok (if available)
channel: The Channelnumber (if available)
trend: The temperature trend (if available)
israining: Statement rain between two measurements (if available)
rain: The rain value, a consecutive number until the battery is changed (if available)
winddir: The current wind direction
windgrad: The current wind direction in degrees
windspeed: The current wind speed
windgust: windguest
Attributes
IODev
Note: by setting this attribute you can define different sets of 8
devices in FHEM, each set belonging to a Device which is capable of receiving the signals. It is important, however,
that a device is only received by the defined IO Device, e.g. by using
different Frquencies (433MHz vs 868MHz)
disableCreateUndefDevice
this can be used to deactivate the creation of new devices
the new devices (Modell + ID, ioname, number) are saved in the device Unknown in the readings "undefModel_a" and "undefModel_b"
disableUnknownEvents
with this, the events can be deactivated for unknown messages
max-deviation-temp: (default:1, allowed values: 1,2,3,4,5,6,7,8,9,10,15,20,25,30,35,40,45,50)
Maximum permissible deviation of the measured temperature from the previous value in Kelvin.
max-diff-rain: Default:0 (deactive)
Maximum permissible deviation of the rainfall to the previous value in l/qm.
The CUL_TX module interprets TX2/TX3 type of messages received by the CUL,
see also http://www.f6fbb.org/domo/sensors/tx3_th.php.
This protocol is used by the La Crosse TX3-TH thermo/hygro sensor and other
wireless themperature sensors. Please report the manufacturer/model of other
working devices.
Define
define <name> CUL_TX <code> [corr] [minsecs]
<code> is the code of the autogenerated address of the TX device (0
to 127)
corr is a correction factor, which will be added to the value received from
the device.
minsecs are the minimum seconds between two log entries or notifications
from this device. E.g. if set to 300, logs of the same type will occure
with a minimum rate of one per 5 minutes even if the device sends a message
every minute. (Reduces the log file size and reduces the time to display
the plots)
The CUL_WS module interprets S300 type of messages received by the CUL.
Define
define <name> CUL_WS <code> [corr1...corr4]
<code> is the code which must be set on the S300 device. Valid values
are 1 through 8.
corr1..corr4 are up to 4 numerical correction factors, which will be added
to the respective value to calibrate the device. Note: rain-values will be
multiplied and not added to the correction factor.
Set
N/A
Get
N/A
Attributes
IODev
Note: by setting this attribute you can define different sets of 8
devices in FHEM, each set belonging to a CUL. It is important, however,
that a device is only received by the CUL defined, e.g. by using
different Frquencies (433MHz vs 868MHz)
strangeTempDiff DIFFVAL
If set, the module will only accept temperature values when the
difference between the reported temperature and the last recorded value
is less than DIFFVAL.
Download the firmware from a nightly SVN chekout and flash the
hardware.
Currently the CUL is supported with its versions:
CUL_V2, CUL_V2_HM, CUL_V3, CUL_V3_ZWAVE, CUL_V4.
If the fhem-device is none, than the inserted device must already be in the
flash-mode. Note:for flashing the CUL dfu-programmer has to be installed in the
path, this is already the case with the Fritz!Box 7390 image from
fhem.de
Example:
CULflash CUL CUL_V3
CULflash none CUL_V3
Note: the message "dfu-programmer: failed to release interface 0." is
normal on the FB7390.
A calendar device periodically gathers calendar events from the source calendar at the given URL or from a file.
The file must be in ICal format.
If the URL
starts with https://, the perl module IO::Socket::SSL must be installed
(use cpan -i IO::Socket::SSL).
<URL> may contain %-wildcards of the
POSIX strftime function of the underlying OS (see your strftime manual).
Common used 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)
- Wildcards in url will be evaluated on every calendar update.
- The evaluation of wildcards maybe disabled by adding literal 'noWildcards' to attribute 'quirks'.
This may be useful in url containing % without marking a wildcard.
Note for users of Google Calendar:
Wildcards must not be used in Google Calendar url!
You can literally use the private ICal URL from your Google Calendar.
If your Google Calendar URL starts with https:// and the perl module IO::Socket::SSL is
not installed on your system, you can replace it by http:// if and only if there is
no redirection to the https:// URL. Check with your browser first if unsure.
Note for users of Netxtcloud Calendar: you can use an URL of the form
https://admin:admin@demo.nextcloud.com/wid0ohgh/remote.php/dav/calendars/admin/personal/?export.
The optional parameter interval is the time between subsequent updates
in seconds. It defaults to 3600 (1 hour).
An interval = 0 will not be allowed and replaced by 3600 automatically. A corresponding log entry will be created.
Events that are more than 400 days in the past or in the future from their
time of creation are omitted. This time window can be further reduced by
the cutoffOlderThan and cutoffLaterThan attributes.
This would have the following consequence: as long as the calendar is not
re-initialized (set ... reload or restart of FHEM) and the VEVENT record is
not modified, events beyond the horizon never get created.
Thus, a forced reload should be scheduled every now and then.
Set
set <name> update
Forces the retrieval of the calendar from the URL. The next automatic retrieval is scheduled to occur interval seconds later.
set <name> reload
Same as update but all calendar events are removed first.
Get
get <name> update
Same as set <name> update
get <name> reload
Same as set <name> update
get <name> events [format:<formatSpec>] [timeFormat:<timeFormatSpec>] [filter:<filterSpecs>]
[series:next[=<max>]] [limit:<limitSpecs>]
[include:<names>]
[returnType:<returnTypeSpec>]
The swiss army knife for displaying calendar events.
Returns, line by line, information on the calendar events in the calendar <name>
according to formatting and filtering rules.
You can give none, one or several of the format,
timeFormat, filter, series and limit
parameters and it makes even sense to give the filter
parameter several times.
The format parameter determines the overall formatting of the calendar event.
The following format specifications are available:
<formatSpec>
content
default
the default format (see below)
full
same as custom="$U $M $A $T1-$T2 $S $CA $L"
text
same as custom="$T1 $S"
human
same as custom={ human($t1,$t2,$S) } - human() is a built-in function that presents the event in a terse human-readable format
custom="<formatString>"
a custom format (see below)
custom="{ <perl-code> }"
a custom format (see below)
Single quotes (') can be used instead of double quotes (") in the
custom format.
You can use the following variables in the <formatString> and in
the <perl-code>:
variable
meaning
$t1
the start time in seconds since the epoch
$T1
the start time according to the time format
$t2
the end time in seconds since the epoch
$T2
the end time according to the time format
$a
the alarm time in seconds since the epoch
$A
the alarm time according to the time format
$d
the duration in seconds
$D
the duration in human-readable form
$S
the summary
$L
the location
$CA
the categories
$CL
the classification
$DS
the description
$U
the UID
$M
the mode
\, (masked comma) in summary, location and description is replaced by a comma but \n
(indicates newline) is untouched.
If the format parameter is omitted, the custom format string
from the defaultFormat attribute is used. If this attribute
is not set, "$T1 $D $S" is used as default custom format string.
The last occurance wins if the format
parameter is given several times.
Examples: get MyCalendar events format:full get MyCalendar events format:custom="$T1-$T2 $S \@ $L" get MyCalendar events format:custom={ sprintf("%20s %8s", $S, $D) }
The timeFormat parameter determines the formatting of
start, end and alarm times.
You use the POSIX conversion specifications in the <timeFormatSpec>.
The web page strftime.net has a nice builder
for <timeFormatSpec>.
If the timeFormat parameter is omitted, the time format specification
from the defaultTimeFormat attribute is used. If this attribute
is not set, "%d.%m.%Y %H:%M" is used as default time format
specification.
Single quotes (') or double quotes (") can be
used to enclose the format specification.
The last occurance wins if the parameter is given several times.
Example: get MyCalendar events timeFormat:"%e-%b-%Y" format:full
The filter parameter restricts the calendar
events displayed to a subset. <filterSpecs> is a comma-separated
list of <filterSpec> specifications. All filters must apply for a
calendar event to be displayed. The parameter is cumulative: all separate
occurances of the parameter add to the list of filters.
<filterSpec>
description
uid=="<uid>"
UID is <uid>
same as field(uid)=="<uid>"
uid=~"<regex>"
UID matches regular expression <regex>
same as field(uid)=~"<regex>"
mode=="<mode>"
mode is <mode>
same as field(mode)=="<mode>"
mode=~"<regex>"
mode matches regular expression <regex>
same as field(mode)=~"<regex>"
field(<field>)=="<value>"
content of the field <field> is <value>
<field> is one of uid, mode, summary, location,
description, categories, classification
field(<field>)=~"<regex>"
content of the field <field> matches <regex>
<field> is one of uid, mode, summary, location,
description, categories, classification
The double quotes (") on the right hand side of a <filterSpec>
are not part of the value or regular expression. Single quotes (') can be
used instead.
Examples: get MyCalendar events filter:uid=="432dsafweq64yehdbwqhkd" get MyCalendar events filter:uid=~"^7" get MyCalendar events filter:mode=="alarm" get MyCalendar events filter:mode=~"alarm|upcoming" get MyCalendar events filter:field(summary)=~"Mama" get MyCalendar events filter:field(classification)=="PUBLIC" get MyCalendar events filter:field(summary)=~"Gelber Sack",mode=~"upcoming|start" get MyCalendar events filter:field(summary)=~"Gelber Sack" filter:mode=~"upcoming|start"
The series parameter determines the display of
recurring events. series:next limits the display to the
next calendar event out of all calendar events in the series that have
not yet ended. series:next=<max> shows at most the
<max> next calendar events in the series. This applies
per series. To limit the total amount of events displayed see the limit
parameter below.
The limit parameter limits the number of events displayed.
<limitSpecs> is a comma-separated list of <limitSpec>
specifications.
<limitSpec>
description
count=<n>
shows at most <n> events, <n> is a positive integer
from=[+|-]<timespec>
shows only events that end after
a timespan <timespec> from now; use a minus sign for events in the
past; <timespec> is described below in the Attributes section
to=[+|-]<timespec>
shows only events that start before
a timespan <timespec> from now; use a minus sign for events in the
past; <timespec> is described below in the Attributes section
when=today|tomorrow
shows events for today or tomorrow
when=<D1>
shows events for day <D1> from now, <D1>= 0 stands for today, negative values allowed
when=<D1>..<D2>
shows events for the day range from day <D1> to day <D2> from now
Examples: get MyCalendar events limit:count=10 get MyCalendar events limit:from=-2d get MyCalendar events limit:when=today get MyCalendar events limit:count=10,from=0,to=+10d
The include parameter includes events from other calendars. This is useful for
displaying events from several calendars in one combined output. <names> is
a comma-separated list of names of calendar devices. The name of the device itself as well as
any duplicates are silently ignored. Names of non-existant devices or of devices that are not
Calendar devices are ignored and an error is written to the log.
Example: get MyCalendar events include:HolidayCalendar,GarbageCollection
The returnType parameter is used to return the events in a particular type.
This is useful for Perl scripts.
<returnTypeSpec>
description
$text
a multiline string in human-readable format (default)
@texts
an array of strings in human-readable format
@events
an array of Calendar::Event hashes
get <name> find <regexp>
Returns, line by line, the UIDs of all calendar events whose summary matches the regular expression
<regexp>.
get <name> vcalendar
Returns the calendar in ICal format as retrieved from the source.
get <name> vevents
Returns a list of all VEVENT entries in the calendar with additional information for
debugging. Only properties that have been kept during processing of the source
are shown. The list of calendar events created from each VEVENT entry is shown as well
as the list of calendar events that have been omitted.
Attributes
defaultFormat <formatSpec>
Sets the default format for the get <name> events
command. The specification is explained there. You must enclose
the <formatSpec> in double quotes (") like input
in attr myCalendar defaultFormat "$T1 $D $S".
defaultTimeFormat <timeFormatSpec>
Sets the default time format for the get <name>events
command. The specification is explained there. Do not enclose
the <timeFormatSpec> in quotes.
synchronousUpdate 0|1
If this attribute is not set or if it is set to 0, the processing is done
in the background and FHEM will not block during updates.
If this attribute is set to 1, the processing of the calendar is done
in the foreground. Large calendars will block FHEM on slow systems.
Attribute value will be ignored if FHEM is running on a Windows platform.
On Windows platforms the processing will always be done synchronously
update onUrlChanged|none
If this attribute is set to onUrlChanged, the processing is done only
if url to calendar has changed since last calendar update.
If this attribute is set to none, the calendar will not be updated at all.
delay <time>
The waiting time in seconds after the initialization of FHEM or a configuration change before
actually retrieving the calendar from its source. If not set, a random time between 10 and 29
seconds is chosen. When several calendar devices are defined, staggered delays reduce
load error rates.
timeout <time>
The timeout in seconds for retrieving the calendar from its source. The default is 30.
Increase for very large calendars that take time to be assembled and retrieved from
their sources.
removevcalendar 0|1
If this attribute is set to 1, the vCalendar will be discarded after the processing to reduce the memory consumption of the module.
A retrieval via get <name> vcalendar is then no longer possible.
hideOlderThan <timespec> hideLaterThan <timespec>
These attributes limit the list of events shown by
get <name> full|debug|text|summary|location|alarm|start|end ....
The time is specified relative to the current time t. If hideOlderThan is set,
calendar events that ended before t-hideOlderThan are not shown. If hideLaterThan is
set, calendar events that will start after t+hideLaterThan are not shown.
Please note that an action triggered by a change to mode "end" cannot access the calendar event
if you set hideOlderThan to 0 because the calendar event will already be hidden at that time. Better set
hideOlderThan to 10.
<timespec> must have one of the following formats:
format
description
example
SSS
seconds
3600
SSSs
seconds
3600s
HH:MM
hours:minutes
02:30
HH:MM:SS
hours:minutes:seconds
00:01:30
D:HH:MM:SS
days:hours:minutes:seconds
122:10:00:00
DDDd
days
100d
cutoffOlderThan <timespec> cutoffLaterThan <timespec>
These attributes cut off all calendar events that end a timespan cutoffOlderThan
before or a timespan cutoffLaterThan after the last update of the calendar.
The purpose of setting this attribute is to save memory and processing time.
Such calendar events cannot be accessed at all from FHEM.
onCreateEvent <perl-code>
This attribute allows to run the Perl code <perl-code> for every
calendar event that is created. See section Plug-ins below.
SSLVerify
This attribute sets the verification mode for the peer certificate for connections secured by
SSL. Set attribute either to 0 for SSL_VERIFY_NONE (no certificate verification) or
to 1 for SSL_VERIFY_PEER (certificate verification). Disabling verification is useful
for local calendar installations (e.g. OwnCloud, NextCloud) without valid SSL certificate.
ignoreCancelled
Set to 1 to ignore events with status "CANCELLED".
Set this attribute to 1 if calanedar events of a series are returned
although they are cancelled.
hasModeReadings
Set to 1 to use the obsolete mode readings.
quirks <values>
Parameters to handle special situations. <values> is
a comma-separated list of the following keywords:
ignoreDtStamp: if present, a modified DTSTAMP attribute of a calendar event
does not signify that the calendar event was modified.
noWildcards: if present, wildcards in the calendar's
URL will not be expanded.
A calendar is a set of calendar events. The calendar events are
fetched from the source calendar at the given URL on a regular basis.
A calendar event has a summary (usually the title shown in a visual
representation of the source calendar), a start time, an end time, and zero, one or more alarm times. In case of multiple alarm times for a calendar event, only the
earliest alarm time is kept.
Recurring calendar events (series) are currently supported to an extent:
FREQ INTERVAL UNTIL COUNT are interpreted, BYMONTHDAY BYMONTH WKST
are recognized but not interpreted. BYDAY is correctly interpreted for weekly and monthly events.
The module will get it most likely wrong
if you have recurring calendar events with unrecognized or uninterpreted keywords.
Out-of-order events and events excluded from a series (EXDATE) are handled.
Calendar events are only created within ±400 days around the time of the
last update.
Calendar events are created when FHEM is started or when the respective entry in the source
calendar has changed and the calendar is updated or when the calendar is reloaded with
get <name> reload.
Only calendar events within ±400 days around the event creation time are created. Consider
reloading the calendar from time to time to avoid running out of upcoming events. You can use something like define reloadCalendar at +*240:00:00 set MyCalendar reload for that purpose.
Some dumb calendars do not use LAST-MODIFIED. This may result in modifications in the source calendar
go unnoticed. Reload the calendar if you experience this issue.
A calendar event is identified by its UID. The UID is taken from the source calendar.
All events in a series including out-of-order events habe the same UID.
All non-alphanumerical characters
are stripped off the original UID to make your life easier.
A calendar event can be in one of the following modes:
upcoming
Neither the alarm time nor the start time of the calendar event is reached.
alarm
The alarm time has passed but the start time of the calendar event is not yet reached.
start
The start time has passed but the end time of the calendar event is not yet reached.
end
The end time of the calendar event has passed.
A calendar event transitions from one mode to another immediately when the time for the change has come. This is done by waiting
for the earliest future time among all alarm, start or end times of all calendar events.
For backward compatibility, mode readings are filled when the hasModeReadings attribute is set. The remainder of
this description applies to the obsolete mode readings.
Each mode reading is a semicolon-separated list of UIDs of
calendar events that satisfy certain conditions:
calname
name of the calendar
modeAlarm
events in alarm mode
modeAlarmOrStart
events in alarm or start mode
modeAlarmed
events that have just transitioned from upcoming to alarm mode
modeChanged
events that have just changed their mode somehow
modeEnd
events in end mode
modeEnded
events that have just transitioned from start to end mode
modeStart
events in start mode
modeStarted
events that have just transitioned to start mode
modeUpcoming
events in upcoming mode
For recurring events, usually several calendar events exists with the same UID. In such a case,
the UID is only shown in the mode reading for the most interesting mode. The most
interesting mode is the first applicable of start, alarm, upcoming, end.
In particular, you will never see the UID of a series in modeEnd or modeEnded as long as the series
has not yet ended - the UID will be in one of the other mode... readings. This means that you better
do not trigger FHEM events for series based on mode... readings. See below for a recommendation.
Events
When the calendar was reloaded or updated or when an alarm, start or end time was reached, one
FHEM event is created:
triggered
When you receive this event, you can rely on the calendar's readings being in a consistent and
most recent state.
When a calendar event has changed, two FHEM events are created:
changed: UID <mode> <mode>: UID
<mode> is the current mode of the calendar event after the change. Note: there is a
colon followed by a single space in the FHEM event specification.
The recommended way of reacting on mode changes of calendar events is to get notified
on the aforementioned FHEM events and do not check for the FHEM events triggered
by a change of a mode reading.
Plug-ins
A plug-in is a piece of Perl code that modifies a calendar event on the fly. The Perl code operates on the
hash reference $e. The most important elements are as follows:
code
description
$e->{start}
the start time of the calendar event, in seconds since the epoch
$e->{end}
the end time of the calendar event, in seconds since the epoch
$e->{alarm}
the alarm time of the calendar event, in seconds since the epoch
$e->{summary}
the summary (caption, title) of the calendar event
$e->{location}
the location of the calendar event
To add or change the alarm time of a calendar event for all events with the string "Tonne" in the
summary, the following plug-in can be used:
Think about a calendar with calendar events whose summaries (subjects, titles) are the names of devices in your fhem installation.
You want the respective devices to switch on when the calendar event starts and to switch off when the calendar event ends.
define SwitchActorOn notify MyCalendar:start:.* { \
my $reading="$EVTPART0";; \
my $uid= "$EVTPART1";; \
my $actor= fhem('get MyCalendar events filter:uid=="'.$uid.'" format:custom="$S"');; \
if(defined $actor) {
fhem("set $actor on")
} \
}
define SwitchActorOff notify MyCalendar:end:.* { \
my $reading="$EVTPART0";; \
my $uid= "$EVTPART1";; \
my $actor= fhem('get MyCalendar events filter:uid=="'.$uid.'" format:custom="$S"');; \
if(defined $actor) {
fhem("set $actor off")
} \
}
You can also do some logging:
define LogActors notify MyCalendar:(start|end):.*
{ my $reading= "$EVTPART0";; my $uid= "$EVTPART1";; \
my $actor= fhem('get MyCalendar events filter:uid=="'.$uid.'" format:custom="$S"');; \
Log3 $NAME, 1, "Actor: $actor, Reading $reading" }
Inform about garbage collection
We assume the GarbageCalendar has all the dates of the
garbage collection with the type of garbage collected in the summary. The
following notify can be used to inform about the garbage collection:
define GarbageCollectionNotifier notify GarbageCalendar:alarm:.* { \
my $uid= "$EVTPART1";; \
my $summary= fhem('get MyCalendar events filter:uid=="'.$uid.'" format:custom="$S"');; \
# e.g. mail $summary to someone \
}
If the garbage calendar has no reminders, you can set these to one day
before the date of the collection:
The module provides two functions which return HTML code.
CalendarAsHtml(<name>,<options>)
returns the HTML code for a list of calendar events. <name> is the name of the
Calendar device and <options> is what you would write
after get <name> text .... This function is deprecated.
CalendarEventsAsHtml(<name>,<parameters>)
returns the HTML code for a list of calendar events. <name> is the name of the
Calendar device and <parameters> is what you would write
in get <name> events <parameters>.
sendDataAnalog Publishes analog values. Example:
set sendDataAnalog <Target-IP> <CAN-Channel> <Index>=<Value>;<Type>
set coe sendDataAnalog 192.168.1.1 3 1=22.7;1 2=18.0;1
sendDataDigital Publishes digital values. This can be 0 or 1. Example:
set sendDataDigital <Target-IP> <CAN-Channel> <Index>=<Value>
set coe sendDataDigital 192.168.1.1 3 1=1 2=0
ComfoAir provides a way to communicate with ComfoAir ventilation systems from Zehnder, especially the ComfoAir 350 (CA350).
It seems that many other ventilation systems use the same communication device and protocol,
e.g. WHR930 from StorkAir, G90-380 from Wernig and Santos 370 DC from Paul.
They are connected via serial line to the fhem computer.
This module is based on the protocol description at http://www.see-solutions.de/sonstiges/Protokollbeschreibung_ComfoAir.pdf
and copies some ideas from earlier modules for the same devices that were posted in the fhem forum from danhauck(Santos) and Joachim (WHR962).
The module can be used in two ways depending on how fhem and / or a vendor supplied remote control device
like CC Ease or CC Luxe are connected to the system. If a remote control device is connected it is strongly advised that
fhem does not send data to the ventilation system as well and only listens to the communication betweem the vendor equipment.
The RS232 interface used is not made to support more than two parties communicating and connecting fhem in parallel to a CC Ease or similar device can lead to
collisions when sending data which can corrupt the ventilation system.
If connected in parallel fhem should only passively listen and <Interval> is to be set to 0.
If no remote control device is connected to the ventilation systems then fhem has to take control and actively request data
in the interval to be defined. Otherwiese fhem will not see any data. In this case fhem can also send commands to modify settings.
Prerequisites
This module requires the Device::SerialPort or Win32::SerialPort module.
Define
define <name> ComfoAir <device> <Interval>
The module connects to the ventialation system through the given Device and either passively listens to data that is communicated
between the ventialation system and its remote control device (e.g. CC Luxe) or it actively requests data from the
ventilation system every <Interval> seconds
If <Interval> is set to 0 then no polling will be done and the module only listens to messages on the line.
Example:
define ZL ComfoAir /dev/ttyUSB1@9600 60
Configuration of the module
apart from the serial connection and the interval which both are specified in the define command there are several attributes that
can optionally be used to modify the behavior of the module.
The module internally gives names to all the protocol messages that are defined in the module and these names can be used
in attributes to define which requests are periodically sent to the ventilation device. The same nams can also be used with
set commands to manually send a request. Since all messages and readings are generically defined in a data structure in the module, it should be
quite easy to add more protocol details if needed without programming.
The names currently defined are:
if the attribute is set to 1, the corresponding data is requested every <Interval> seconds. If it is set to 0, then the data is not requested.
by default Ventilation-Levels, Temperaturen and Status-Bypass are requested if no attributes are set.
like with the attributes mentioned above, set commands can be used to send a request for data manually. The following set options are available for this:
Temp_Komfort (target temperature for comfort)
Stufe (ventilation level)
Get-Commands
All readings that are derived from the responses to protocol requests are also available as Get commands. Internally a Get command triggers the corresponding
request to the device and then interprets the data and returns the right field value. To avoid huge option lists in FHEMWEB, only the most important Get options
are visible in FHEMWEB. However this can easily be changed since all the readings and protocol messages are internally defined in the modue in a data structure
and to make a Reading visible as Get option only a little option (e.g. showget => 1 has to be added to this data structure
include a request for the data belonging to the named group when sending requests every interval seconds
hide-Bootloader-Version
hide-Firmware-Version
hide-RS232-Modus
hide-Sensordaten
hide-KonPlatine-Version
hide-Verzoegerungen
hide-Ventilation-Levels
hide-Temperaturen
hide-Betriebsstunden
hide-Status-Bypass
hide-Status-Vorheizung
prevent readings of the named group from being created even if used passively without polling and an external remote control requests this data.
please note that this attribute doesn't delete already existing readings.
queueDelay
modify the delay used when sending requests to the device from the internal queue, defaults to 1 second
queueMax
max length of the send queue, defaults to 50
timeout
set the timeout for reads, defaults to 2 seconds
alignTime
Aligns each periodic read request for the defined interval to this base time. This is typcally something like 00:00 (see the Fhem at command)
This module allows to define own readings. The readings can be defined in an attribute so that they can get changed without changing the code of the module.
To use this module you should have some perl and linux knowledge
The examples presuppose that you run FHEM on a linux machine like a Raspberry Pi or a Cubietruck.
Note: the "bullshit" definition is an example to show what happens if you define bullshit :-)
Optionally, to display the readings:
define myReadingsDisplay weblink htmlCode {CustomReadings_GetHTML('myReadings')}
attr myReadingsDisplay group Readings
attr myReadingsDisplay room 0-Test
Resulting readings:
ac_powersupply_current
0.236
2014-08-09 15:40:21
ac_powersupply_voltage
5.028
2014-08-09 15:40:21
bullshit
ERROR
2014-08-09 15:40:21
device_name
myReadings
2014-08-09 15:40:21
fhem_backup_folder_size
20M
2014-08-09 15:40:21
hdd_temperature
/dev/sda: TS128GSSD320: 47°C
2014-08-09 15:40:21
kernel
3.4.103-sun7i+
2014-08-09 15:40:21
perl_version
5.014002
2014-08-09 15:40:21
timezone
Europe/Berlin
2014-08-09 15:40:21
Define
define <name> CustomReadings
Readings
As defined
Attributes
interval
Refresh interval in seconds
readingDefinitions
The definitions are separated by a comma. A definition consists of two parts, separated by a colon.
The first part is the name of the reading and the second part the function.
The function gets evaluated and must return a result.
Example: kernel:qx(uname -r 2>&1)
Defines a reading with the name "kernel" and evaluates the linux function uname -r
Multiline output from commands, systemcall, scripts etc. can be use for more than one reading with
the keyword COMBINED as reading (which wont appear itself) while its command output
will be put line by line in the following readings defined (so they don't need a function defined
after the colon (it would be ignored)).But the lines given must match the number and order of the
following readings.
COMBINED can be used together or lets say after or even in between normal expressions if the
number of lines of the output matches exactly.
Example: COMBINED:qx(cat /proc/sys/vm/dirty_background*),dirty_bytes:,dirty_ration:
Defines two readings (dirty_bytes and dirty_ratio) which will get set by the lines of those
two files the cat command will find in the kernel proc directory.
In some cases this can give an noticeable performance boost as the readings are filled up all at once.
This module controls DENON (Marantz) A/V receivers in real-time via network connection.
Instead of IP address or hostname you may set a serial connection format for direct connectivity.
Example:
define avr DENON_AVR 192.168.0.10
# With explicit port
define avr DENON_AVR 192.168.0.10:23
# With serial connection
define avr DENON_AVR /dev/ttyUSB0@9600
Set
set <name> <command> [<parameter>]
Currently, the following commands are defined:
allZoneStereo - set allZoneStereo on/off
audioRestorer - set audioRestorer off/low/medium/high
audysseyLFC - set audysseyLFC on/off
audysseyLFCAmount - set audysseyLFCAmount (1 - 7)
autoStandby - set auto standby (off, 15,30,60 min)
bass - adjust bass level
channelVolume - adjust channel volume level for active speakers (up/down),
to reset all channel level use FactoryDefaults
Example to adjust volume level via command line: set avr channelVolume FrontLeft -1
(possible values -12 to 12)
cinemaEQ - set cinemaEQ on/off
display - controls display dim state
dynamicEQ - set dynamicEQ on/off
dynamicEQRefLevelOffset - set dynamicEQRefLevelOffset (0, 5, 10, 15)
dynamicVolume - set dynamicEQ off/light/medium/heavy
eco - controls eco state
favorite - switches between favorite (only older models)
favoriteList - select entries in favorite list (workaround for new models >= 2014),
it is recommended to use set stream in combination with module 98_DLNARenderer!
input - switches between inputs
loudness - set loudness on/off
lowFrequencyEffect - adjust LFE level (-10 to 0)
multiEQ - set multiEQ off/reference/bypassLR...
mute on,off - controls volume mute
muteT - toggle mute state
off - turns the device in standby mode
on - powers on the device
preset - switches between presets (1-3, only older models)
presetCall - switches between presets (00-35, 00-55 older models)
presetMemory - save presets (00-35, 00-55 older models, for alphanumeric mode A1-G8 set attribute "presetMode" to "alphanumeric")
quickselect - switches between quick select modes (1-5, only new models)
smartselect - switches between smart select modes (1-5, only Marantz, to activate set attribute brand to Marantz)
stream - send stream adress via module 98_DLNARenderer to reciever; the user has to create a file "Denon.streams" in folder "fhem/FHEM"
list format:
Rockantenne<>http://mp3channels.webradio.antenne.de/rockantenne
Bayern3<>http://streams.br.de/bayern3_2.m3u
JamFM<>http://www.jam.fm/streams/jam-nmr-mp3.m3u
The attribut "dlnaName" must be set to the name of the reciever in DLNARenderer module.
surroundMode - set surround mode
toggle - switch between on and off
treble - adjust treble level
trigger1 - set trigger1 on/off
trigger2 - set trigger2 on/off
tuner - switch between AM and FM
tunerPreset - switches between tuner presets (1-56)
tunerPresetMemory - save tuner presets (1-56)
usedInputs - set used inputs manually if needed (e.g. us model)
volume 0...98 - set the volume level in percentage
volumeStraight -80...18 - set the volume level in dB
volumeUp - increases the volume level
volumeDown - decreases the volume level
Get
get <name> <what>
Currently, the following commands are defined:
disconnect - disconnect AV receiver
mediaInfo - refresh current media infos
reconnect - reconnect AV receiver
remoteControl - autocreate remote ccontrol
statusRequest - refresh status
some readings - see list below
zone - autocreate zones
Generated Readings/Events:
The AV reciever sends some readings only if settings (e.g. ampAssign) have changed
or the reciever has been disconnected (power supply) for more than 5 min and connected again.
ampAssign - amplifier settings for AV receiver (5.1, 7.1, 9.1,...)
This module integrates the DFPlayerMini - FN-M16P Embedded MP3 Audio Module device into fhem.
See the datasheet of the module for technical details.
The MP3 player can be connected directly to a serial interface or via ethernet/WiFi by using a hardware with offers a transparent
serial bridge over TCP/IP like ESPEasy Ser2Net.
It is also possible to use other fhem transport devices like MYSENSORS.
The module supports all commands of the DFPlayer and offers additional convenience functions like
integration of Text2Speech for easy download of speech mp3 files
easier control of which file to play by
keeping a reference of all files the DFPlayer can play
If directly connected <devicename> specifies the serial port to communicate with the DFPlayer Mini.
The name of the serial-device depends on your distribution, under
linux the cdc_acm kernel module is responsible, and usually a
/dev/ttyACM0 or /dev/ttyUSB0 device will be created.
You can also specify a baudrate if the device name contains the @
character, e.g.: /dev/ttyACM0@9600
This is also the default baudrate and normally shouldn't be changed
as the DFPlayer uses a fixed baudrate of 9600.
If the baudrate is "directio" (e.g.: /dev/ttyACM0@directio), then the
perl module Device::SerialPort is not needed, and fhem opens the device
with simple file io. This might work if the operating system uses sane
defaults for the serial parameters, e.g. some Linux distributions and
OSX.
If connected via TCP/IP <hostname:port> specifies the IP address and port of the device that provides the transparent serial
bridge to the DFP, e.g. 192.168.2.28:23
for other types of transport none can be specified as the device. In that case the attribute sendCmd should be specified and responses
from the DFP should be given to this module with set response.
Attributes
TTSDev
The name of a Text2Speech device. This has to be defined beforehand with none as the <alsadevice> as a server device. It should be used for no other purposes
than use by this module.
requestAck
The DFPlayer can send a response to any command sent to it to acknowledge that is has received the command. As this increases the communication
overhead it can be switched off if the communication integrity is ensured by other means. If set the next command is only sent if the last one was
acknowledged by the DFPlayer. This ensures that no command is lost if the the DFPlayer is busy/sleeping.
sendCmd
A fhem command that is used to send the command data generated by this module to the DFPlayer hardware. If this is set, no other way of communication with the DFP is used.
This can be used integrate other transport devices than those supported natively.
E. g. to communicate via a MySensors device named mys_dfp with an appropriate sketch use
attr <dfp> sendCmd set mys_dfp value11 $msg
The module will then send a command to the DFP replacing $msg with the actual payload using the fhem command
set mys_dfp value11 <payload>
See set response for a way to get the response of the DFPlayer received via a different device back into this module.
uploadPath
The DFPlayer plays files from an SD card or USB stick connected to it. The mp3/wav files have to be copied to this storage device by the user.
The device expects the files with specific names and in specific folders, see the datasheet for details.
Copying the files can also be done by this module if the storage device is accessible by the computer fhem is running on.
It has to be mounted in a specific path with is specified with this attribute.
See uploadTTS, uploadTTScache and readFiles commands where this is used.
rememberMissingTTS
If set tts commands without a matching file create a special reading. See set tts and set uploadTTScache.
keepAliveInterval
Specifies the interval in seconds for sending a keep alive message to the DFP. Can be used to check if the DFP is still working and to keep connections open.
After three missing answers the status of the devices is set to disconnected.
Set the interval to 0 to disable the keep alive feature. Default is 60 seconds.
Get
All query commands supported by the DFP have a corresponding get command:
get
DFP cmd byte
parameters
comment
storage
0x3F
status
0x42
volume
0x43
equalizer
0x44
noTracksRootUsb
0x47
noTracksRootSd
0x48
currentTrackUsb
0x4B
currentTrackSd
0x4C
noTracksInFolder
0x4E
folder number
1-99
noFolders
0x4F
Set
All commands supported by the DFP have a corresponding set command:
set
DFP cmd byte
parameters
comment
next
0x01
-
prev
0x02
-
trackNum
0x03
number of track in root directory
between 1 and 3000 (uses the order in which the files where created!)
volumeUp
0x04
-
volumeDown
0x05
-
volumeStraight
0x06
volume
0-30
equalizer
0x07
name of the equalizer mode
Normal, Pop, Rock, Jazz, Classic, Bass
repeatSingle
0x08
-
storage
0x09
SD or USB
sleep
0x0A
-
not supported by DFP, DFP needs power cycle to work again
wake
0x0B
-
not supported by DFP, but probably by FN-M22P
reset
0x0C
-
play
0x0D
-
plays the current track
play
0x0F, 0x12, 0x13, 0x14
a space separated list of files to play successively
the correct DFP command is used automatically.
Files can be specified with either their reading name, reading value or folder name/track number.
See set readFiles
pause
0x0E
-
amplification
0x10
level of amplification
0-31
repeatRoot
0x11
on, off
MP3TrackNum
0x12
tracknumber
1-3000, from folder MP3
intercutAdvert
0x13
tracknumber
1-3000, from folder ADVERT
folderTrackNum
0x0F
foldernumber tracknumber
folder: 1-99, track: 1-255
folderTrackNum3000
0x14
foldernumber tracknumber
folder: 1-15, track: 1-3000
stopAdvert
0x15
-
stop
0x16
-
repeatFolder
0x17
number of folder
1-99
shuffle
0x18
-
repeatCurrentTrack
0x19
on, off
DAC
0x1A
on, off
All other set commands are not sent to the DFP but offer convenience functions:
close
raw sends a command encoded in hex directly to the DFP without any validation
reopen
readFiles reads all files from the storage medium mounted at uploadPath. If these files are accessible by the DFP (i.e. they conform to the naming convention)
a reading is created for the file. The reading name is File_<folder>/<tracknumber>. Folder can be ., MP3, ADVERT, 00 to 99.
The reading value is the filename without the tracknumber and suffix.
Example:
For the file MP3/0003SongTitle.mp3 the reading File_MP3/0003 with value SongTitle is created.
The set <dfp> play command can make use of these readings, i.e. it is possible to use either set <dfp> play File_MP3/0003,
set <dfp> play MP3/3 or set <dfp> play SongTitle to play the same track.
uploadTTS <destination path> <Text to translate to speech>
The text specified is converted to a speech mp3 file using the Text2Speech device specified with attr TTSDev. The mp3 file is then copied into the given
destination path within uploadPath.
Examples: set <dfp> 01/0001Test Dies ist ein Test set <dfp> ADVERT/0099Hinweis Achtung
uploadTTScache
upload all files from the cache directory of the TTSDev to uploadPath. Uploading starts with folder 01. After 3000 files
the next folder is used. The MD5 hash is used as the filename. When the upload is finished set readFiles is executed. The command set tts makes use of the readings created by this.
tts <text to translate to speech> TTSDev is used to calculate the MD5 hash of <text to translate to speech>. It then tries to play the file with this hash value.
If no reading for such a file exists and if the attribute rememberMissingTTS is set, a new reading Missing_MD5<md5> with <text to translate to speech> as its
value is created.
Prerequisites:
This only works if this text had been translated earlier and the resulting mp3 file was stored in the cache directory of TTSDev.
The files in the cache have to be uploaded to the storage card with set uploadTTScache.
uploadNumbers destinationFolder
creates mp3 files for all tokens required to speak arbitrary german numbers.
Example: set <dfp> uploadNumbers 99
creates the 31 mp3 files required in folder 99.
sayNumber number
translates a number into speech and plays the required tracks. Requires that uploadNumbers command was used to create the speech files.
Example:
sayNumber -34.7
is equivalent to
play minus vier und dreissig komma sieben
response 10 bytes response message from DFP encoded as hex
DLNARenderer automatically discovers all your MediaRenderer devices in your local network and allows you to fully control them.
It also supports multiroom audio for Caskeid and Bluetooth Caskeid speakers (e.g. MUNET).
Note: The followig libraries are required for this module:
SOAP::Lite
LWP::Simple
XML::Simple
XML::Parser::Lite
LWP::UserAgent
Define
define <name> DLNARenderer
Example:
define dlnadevices DLNARenderer
After about 2 minutes you can find all automatically created DLNA devices under "Unsorted".
Set
set <name> stream <value>
Set any URL to play.
set <name> on
Starts playing the last stream (reading stream).
set <name> off
Sends stop command to device.
set <name> stop
Stop playback.
set <name> volume 0-100 set <name> volume +/-0-100
Set volume of the device.
set <name> channel 1-10
Start playing channel X which must be configured as channel_X attribute first.
You can specify your channel also in DIDL-Lite XML format if your player doesn't support plain URIs.
set <name> mute on/off
Mute the device.
set <name> pause
Pause playback of the device. No toggle.
set <name> pauseToggle
Toggle pause/play for the device.
set <name> play
Initiate play command. Only makes your player play if a stream was loaded (currentTrackURI is set).
set <name> next
Play next track.
set <name> previous
Play previous track.
set <name> seek <seconds>
Seek to position of track in seconds.
set <name> speak "This is a test. 1 2 3."
Speak the text followed after speak within quotes. Works with Google Translate.
set <name> playEverywhere
Only available for Caskeid players.
Play current track on all available Caskeid players in sync.
set <name> stopPlayEverywhere
Only available for Caskeid players.
Stops multiroom audio.
set <name> addUnit <unitName>
Only available for Caskeid players.
Adds unit to multiroom audio session.
set <name> removeUnit <unitName>
Only available for Caskeid players.
Removes unit from multiroom audio session.
set <name> multiRoomVolume 0-100 set <name> multiRoomVolume +/-0-100
Only available for Caskeid players.
Set volume of all devices within this session.
set <name> enableBTCaskeid
Only available for Caskeid players.
Activates Bluetooth Caskeid for this device.
set <name> disableBTCaskeid
Only available for Caskeid players.
Deactivates Bluetooth Caskeid for this device.
set <name> stereo <left> <right> <pairName>
Only available for Caskeid players.
Sets stereo mode for left/right speaker and defines the name of the stereo pair.
set <name> standalone
Only available for Caskeid players.
Puts the speaker into standalone mode if it was member of a stereo pair before.
set <name> saveGroupAs <groupName>
Only available for Caskeid players.
Saves the current group configuration (e.g. saveGroupAs LivingRoom).
set <name> loadGroup <groupName>
Only available for Caskeid players.
Loads the configuration previously saved (e.g. loadGroup LivingRoom).
Attributes
ignoreUDNs
Define list (comma or blank separated) of UDNs which should prevent automatic device creation.
It is important that uuid: is also part of the UDN and must be included.
DOIF is a universal module. It works event- and time-controlled.
It combines the functionality of a notify, at-, watchdog command with logical queries.
Complex problems can be solved with this module, which would otherwise be solved only with several modules at different locations in FHEM. This leads to clear solutions and simplifies their maintenance.
Logical queries are created in conditions using Perl operators.
These are combined with information from states, readings, internals of devices or times in square brackets.
Arbitrary Perl functions can also be specified that are defined in FHEM.
The module is triggered by time or by events information through the Devices specified in the condition.
If a condition is true, the associated FHEM- or Perl commands are executed.
define <name> DOIF <Blockname> {<Perl with DOIF-Syntax>} <Blockname> {<Perl with DOIF-Syntax>} ...
The commands are always processed from left to right. There is only one command executed, namely the first, for which the corresponding condition in the processed sequence is true. In addition, only the conditions are checked, which include a matching device of the trigger (in square brackets).
Features
+ intuitive syntax, as used in branches (if - elseif-....elseif - else) in higher-level languages
+ in the condition of any logical queries can be made as well as perl functions are used (full perl support)
+ it can be any FHEM commands and perl commands are executed
+ syntax checking at the time of definition are identified missing brackets
+ status is specified with [<devicename>], readings with [<devicename>:<readingname>] or internals with [<devicename>:&<internal>]
+ time information on the condition: [HH:MM:SS] or [HH:MM] or [<seconds>]
+ indirect time on the condition: [[<devicename>]] or [[<devicename>:<readingname>]] or [{<perl-function>}]
+ time calculation on the condition: [(<time calculation in Perl with time syntax specified above>)]
+ time intervals: [<begin>-<end>] for <begin> and <end>, the above time format can be selected.
+ relative times preceded by a plus sign [+<time>] or [+<begin>-+<end>] combined with Perl functions
+ weekday control: [<time>|0123456789] or [<begin>-<end>|0123456789] (0-6 corresponds to Sunday through Saturday) such as 7 for $we, 8 for !$we, 9 for $we tomorrow ($twe)
+ statuses, readings, internals und time intervals for only queries without trigger with [?...]
+ DOELSEIF cases and DOELSE at the end are optional
+ delay specification with resetting is possible (watchdog function)
+ the execution part can be left out in each case. So that the module can be used for pure status display.
+ definition of the status display with use of any readings or statuses
Many examples with english identifiers - see german section.
dsb_class: The grade to filter for. Can be a regex, e.g. 5a|8b or 6.*c.
dsb_classReading: Has to be set if the column containing the class(es) is not named "Klasse(n)", i.e. the genarated reading is not "Klasse_n_"
dsb_interval: Interval in seconds to pull DSBMobile, value of 0 means disabled
dsb_outputFormat: can be used to format the output of the weblink. Takes the readingnames enclosed in % as variables, e.g. %Klasse_n_%
DSBMobile additionally provides three functions to display the information in weblinks:
DSBMobile_simpleHTML($name ["dsb","showInfoOfTheDay"]): Shows the timetable changes, if the second optional parameter is "1", the Info of the Day will be displayed additionally.
The format may be defined with the dsb_outputFormat attribute
Example defmod dsb_web weblink htmlCode {DSBMobile_simpleHTML("dsb",1)}
DSBMobile_tableHTML($name ["dsb","showInfoOfTheDay"]): Shows the timetable changes in a tabular format, if the second optional parameter is "1", the Info of the Day will be displayed additionally.
Example defmod dsb_web weblink htmlCode {DSBMobile_tableHTML("dsb",1)}
DSBMobile_infoHTML($name): Shows the postings with links to the Details.
Example defmod dsb_infoweb weblink htmlCode {DSBMobile_infoHTML("dsb")}
<code> specifies the radio code of the DuoFern device
Example:
define myDuoFern DUOFERN 49ABCD
Set
Universal commands (available to most actors):
remotePair
Activates the pairing mode of the actor.
Some actors accept this command in unpaired mode up to two hours afte power up.
remoteUnpair
Activates the unpairing mode of the actor.
getStatus
Sends a status request message to the DuoFern device.
manualMode [on|off]
Activates the manual mode. If manual mode is active
all automatic functions will be ignored.
timeAutomatic [on|off]
Activates the timer automatic.
sunAutomatic [on|off]
Activates the sun automatic.
dawnAutomatic [on|off]
Activates the dawn automatic.
duskAutomatic [on|off]
Activates the dusk automatic.
dusk
Move roller shutter downwards or switch on switch/dimming actor
if duskAutomatic is activated.
dawn
Move roller shutter upwards or switch off switch/dimming actor
if dawnAutomatic is activated.
sunMode [on|off]
Activates the sun mode. If sun automatic is activated,
the roller shutter will move to the sunPosition or a switch/dimming
actor will shut off.
reset [settings|full]
settings: Clear all settings and endpoints of the actor.
full: Complete reset of the actor including pairs.
Roller shutter actor commands:
up [timer]
Move the roller shutter upwards. If parameter timer is used the command will
only be executed if timeAutomatic is activated.
down [timer]
Move the roller shutter downwards. If parameter timer is used the command will
only be executed if timeAutomatic is activated.
stop
Stop motion.
position <value> [timer]
Set roller shutter to a desired absolut level. If parameter timer is used the
command will only be executed if timeAutomatic is activated.
toggle
Switch the roller shutter through the sequence up/stop/down/stop.
rainAutomatic [on|off]
Activates the rain automatic.
windAutomatic [on|off]
Activates the wind automatic.
sunPosition <value>
Set the sun position.
ventilatingMode [on|off]
Activates the ventilating mode. If activated, the roller
shutter will stop on ventilatingPosition when moving down.
ventilatingPosition <value>
Set the ventilating position.
windMode [on|off]
Activates the wind mode. If wind automatic and wind mode is
activated, the roller shutter moves in windDirection and ignore any automatic
or manual command.
The wind mode ends 15 minutes after last activation automatically.
windDirection [up|down]
Movemet direction for wind mode.
rainMode [on|off]
Activates the rain mode. If rain automatic and rain mode is
activated, the roller shutter moves in rainDirection and ignore any automatic
command.
The rain mode ends 15 minutes after last activation automatically.
rainDirection [up|down]
Movemet direction for rain mode.
runningTime <sec>
Set the motor running time.
motorDeadTime [off|short|long]
Set the motor dead time.
reversal [on|off]
Reversal of direction of rotation.
Switch/dimming actor commands:
on [timer]
Switch on the actor. If parameter timer is used the command will
only be executed if timeAutomatic is activated.
off [timer]
Switch off the actor. If parameter timer is used the command will
only be executed if timeAutomatic is activated.
level <value> [timer]
Set actor to a desired absolut level. If parameter timer is used the
command will only be executed if timeAutomatic is activated.
modeChange [on|off]
Inverts the on/off state of a switch actor or change then modus of a dimming actor.
stairwellFunction [on|off]
Activates the stairwell function of a switch/dimming actor.
stairwellTime <sec>
Set the stairwell time.
Blind actor commands:
blindsMode [on|off]
Activates the blinds mode.
slatPosition <value>
Set the slat to a desired absolut level.
defaultSlatPos <value>
Set the default slat position.
slatRunTime <msec>
Set the slat running time.
tiltInSunPos [on|off]
Tilt slat after blind moved to sun position.
tiltInVentPos [on|off]
Tilt slat after blind moved to ventilation position.
tiltAfterMoveLevel [on|off]
Tilt slat after blind moved to an absolute position.
tiltAfterStopDown [on|off]
Tilt slat after stopping blind while moving down.
Thermostat commands:
desired-temp <temp> [timer]
Set desired temperature. <temp> must be between -40 and 80
Celsius, and precision is half a degree. If parameter timer
is used the command will only be executed if timeAutomatic is activated.
tempUp [timer]
Increases the desired temperature by half a degree. If parameter timer
is used the command will only be executed if timeAutomatic is activated.
tempDown [timer]
Decrease the desired temperature by half a degree. If parameter timer
is used the command will only be executed if timeAutomatic is activated.
temperatureThreshold[1|2|3|4] <temp>
Set temperature threshold 1 to 4. <temp> must be between -40 and 80
Celsius, and precision is half a degree.
actTempLimit [timer]
Set desired temperature to the selected temperatureThreshold. If parameter
timer is used the command will only be executed if timeAutomatic is
activated.
Radiator Actuator commands:
desired-temp <temp> [timer]
Set desired temperature. <temp> must be between 4 and 35.5
Celsius, and precision is half a degree. If parameter timer
is used the command will only be executed if timeAutomatic is activated.
sendingInterval <minutes>
Sets the transmission interval of the status responds.
SX5 commands:
10minuteAlarm [on|off]
Activates the alarm sound of the SX5 when the door is left open for longer than 10 minutes.
2000cycleAlarm [on|off]
Activates the alarm sounds of the SX5 when the SX5 has run 2000 cycles.
automaticClosing [off|30|60|90|120|150|180|210|240]
Set the automatic closing time of the SX5 (sec).
openSpeed [11|15|19]
Set the open speed of the SX5 (cm/sec).
backJump [on|off]
If activated the SX5 moves briefly in the respective opposite direction after reaching the end point.
getConfig
Sends a config request message to the weather sensor.
Weather sensor commands:
getConfig
Sends a configuration request message.
getTime
Sends a time request message.
getWeather
Sends a weather data request message.
writeConfig
Write the configuration back to the weather sensor.
DCF [on|off]
Switch the DCF receiver on or off.
time
Set the current system time to the weather sensor.
interval <value>
Set the interval time for automatic transmittion of the weather data.
<value>: off or 1 to 100 minutes
latitude <value>
Set the latitude of the weather sensor position
<value>: 0 to 90
longitude <value>
Set the longitude of the weather sensor position
<value>: -90 to 90
timezone <value>
Set the time zone of the weather sensor
<value>: 0 to 23
triggerDawn <value1> ... [<value5>]
Sets up to 5 trigger values for a dawn event.
<value[n]>: off or 1 to 100 lux
triggerDusk <value1> ... [<value5>]
Sets up to 5 trigger values for a dusk event.
<value[n]>: off or 1 to 100 Lux
triggerRain [on|off]
Switch the trigger of the rain event on or off.
triggerSun <value1>:<sun1>:<shadow1>[:<temperature1>] ... [<value5>:<sun5>:<shadow5>[:<temperature5>]]
Sets up to 5 trigger values for a sun event.
<value[n]>: off or 1 to 100 kLux
<sun[n]>: time to detect sun, 1 to 30 minutes
<shadow[n]>: time to detect shadow, 1 to 30 minutes
<temperature[n]>: optional minimum temperature, -5 to 26 °C
triggerSunDirction <startangle1>:<width1> ... [<startangle5>:<width5>]
If enabled, the respective sun event will only be triggered, if sunDirection is in the specified range.
<startangle[n]>: off or 0 to 292.5 degrees (stepsize 22.5°)
<width[n]>: 45 to 180 degrees (stepsize 45°)
triggerSunHeight <startangle1>:<width1> ... [<startangle5>:<width5>]
If enabled, the respective sun event will only be triggered, if sunHeight is in the specified range.
<startangle[n]>: off or 0 to 65 degrees (stepsize 13°)
<width[n]>: 26 or 52 degrees
triggerTemperature <value1> ... [<value5>]
Sets up to 5 trigger values for a temperature event.
<value[n]>: off or -40 to 80 °C
triggerWind <value1> ... [<value5>]
Sets up to 5 trigger values for a wind event.
<value[n]>: off or 1 to 31 m/s
timeout <sec>
After sending a command to an actor, the actor must respond with its status within this time. If no status message is received,
up to two getStatus commands are resend.
Default 60s.
toggleUpDown
If attribute is set, a stop command is send instead of the up or down command if the roller shutter is moving.
positionInverse
If attribute is set, the position value of the roller shutter is inverted.
positionDeviation
Maximum deviation for displaying the desired position instead of the reported position.
pair
Set the DuoFern stick in pairing mode for 60 seconds. Any DouFern device set into
pairing mode in this time will be paired with the DuoFern stick.
unpair
Set the DuoFern stick in unpairing mode for 60 seconds. Any DouFern device set into
unpairing mode in this time will be unpaired from the DuoFern stick.
reopen
Reopens the connection to the device and reinitializes it.
statusBroadcast
Sends a status request message to all DuoFern devices.
remotePair <code>
Activates the pairing mode on the device specified by the code.
Some actors accept this command in unpaired mode up to two hours afte power up.
The Deutsche Wetterdienst (DWD) provides public weather related data via its Open Data Server. Any usage of the service and the data provided by the DWD is subject to the usage conditions on the Open Data Server webpage. An overview of the available content can be found at OpenData_weather_content.xls.
This module provides two elements of the available data:
You can request forecasts for different stations in sequence using the command get forecast <station code> or for one station continuously using the attribute forecastStation. To get continuous mode for more than one station you need to create separate DWD_OpenData devices.
In continuous mode the forecast data will be shifted by one day at midnight without requiring new data from the DWD.
After updating the alerts cache using the command get updateAlertsCache <mode> you can request alerts for different warncells in sequence using the command get alerts <warncell id>. Setting the attribute alertArea will enable continuous mode. To get continuous mode for more than one station you need to create separate DWD_OpenData devices.
Notes: This function is not suitable to rely on to ensure your safety! It will cause significant download traffic if used in continuous mode (more than 1 GB per day are possible). The device needs to keep all alerts for Germany in memory at all times to comply with the requirements of the common alerting protocol (CAP), even if only one warn cell is monitored. Depending on the weather activity this requires noticeable amounts of memory and CPU.
Installation notes:
This module requires the additional Perl module XML::LibXML for weather alerts. It can be installed depending on your OS and your preferences (e.g. sudo apt-get install libxml-libxml-perl or using CPAN).
Data is fetched from the DWD Open Data Server using the FHEM module HttpUtils. If you use a proxy for internet access you need to set the global attribute proxy to a suitable value in the format myProxyHost:myProxyPort.
Verify that your FHEM time is correct by entering {localtime()} into the FHEM command line. If not, check the system time and timezone of your FHEM server and adjust appropriately. It may be necessary to add export TZ=`cat /etc/timezone` or something similar to your FHEM start script /etc/init.d/fhem or your system configuration file /etc/profile. If /etc/timezone does not exists or is undefined execute tzselect to find your timezone and write the result into this file. After making changes restart FHEM and enter {$ENV{TZ}} into the FHEM command line to verify. To fix the timezone temporarily without restarting FHEM enter {$ENV{TZ}='Europe/Berlin'} or something similar into the FHEM command line. Again use tzselect to fine a valid timezone name.
The weekday of the forecast will be in the language of your FHEM system. Enter {$ENV{LANG}} into the FHEM command line to verify. If nothing is displayed or you see an unexpected language setting, add export LANG=de_DE.UTF-8 or something similar to your FHEM start script, restart FHEM and check again. If you get a locale warning when starting FHEM the required language pack might be missing. It can be installed depending on your OS and your preferences (e.g. dpkg-reconfigure locales, apt-get install language-pack-de or something similar).
The digits in a warncell id of a communeunion or a district are mostly identical to an Amtliche Gemeindekennziffer if you strip of the 1st digit from the warncell id. You can lookup an Amtliche Gemeindekennziffer using the name of a communeunion or district e.g. at Statistische Ämter des Bundes und der Länder. Then add 8 for a communeunion or 1 or 9 for a district at the beginning and try to find an exact or near match in the Warncell-IDs for CAP alerts catalogue. This approach is an alternative to guessing the right warncell id by the name of a communeunion or district.
Like some other Perl modules this module temporarily modifies the TZ environment variable for timezone conversions. This may cause unexpected results in multi threaded environments.
The forecast reading names do not contain absolute days or hours to keep them independent of summertime adjustments. Forecast days are counted relative to "today" of the timezone defined by the attribute of the same name or the timezone specified by the Perl TZ environment variable if undefined.
Starting on 17.09.2018 the forecast data from the DWD is no longer available in CSV format and is based on the KML format instead. While most of the properties of the CSV format are still available in KML format, their names have changed and you will have to adjust your existing installation accordingly.
This module provides sun position related information that is not available from the DWD. The properties for sunrise, sunset and sun up are calculated for the upper solar limb at given altitude and typical atmospheric refraction.
Define
define <name> DWD_OpenData
Get
get forecast [<station code>]
Fetch forecast for a station from DWD and update readings. The station code is either a 5 digit WMO station code or an alphanumeric DWD station code from the MOSMIX station catalogue. If the attribute forecastStation is set, no station code must be provided.
The operation is performed non-blocking.
get alerts [<warncell id>]
Set alert readings for given warncell id. A warncell id is a 9 digit numeric value from the Warncell-IDs for CAP alerts catalogue. Supported ids start with 8 (communeunion), 1 and 9 (district) or 5 (coast). If the attribute alertArea is set, no warncell id must be provided.
If the alerts cache is empty or older than 15 minutes the cache is updated first and the operation is non-blocking. If the cache is valid the operation is blocking. If a cache update is already in progress the operation fails.
To verify that alerts are provided for the warncell id you selected you should consult another source, wait for an alert situation and compare.
get updateAlertsCache { communeUnions|districts|all }
Fetch alerts to update the alerts cache. Note that 'coast' alerts are part of the 'communeUnion' cache data.
The operation is performed non-blocking because it typically requires several seconds. If a cache update is already in progress the operation fails.
This command can be used before querying several warncells in sequence or to force a higher update frequency than the built-in 15 minutes. Note that all DWD_OpenData devices share a single alerts cache so updating the cache via one of the devices is sufficient.
Attributes
disable {0|1}, default: 0
Disable fetching data.
timezone <tz>, default: OS dependent IANA TZ string for date and time readings (e.g. "Europe/Berlin"), can be used to assume the perspective of a station that is in a different timezone or if your OS timezone settings do not match your local timezone. Alternatively you may use tzselect on the Linux command line to find a valid timezone string.
forecast related:
forecastStation <station code>, default: none
Setting forecastStation enables automatic updates every hour.
The station code is either a 5 digit WMO station code or an alphanumeric DWD station code from the id column of the MOSMIX station catalogue.
Note: When value is changed all existing forecast readings will be deleted.
forecastDays <n>, default: 6
Limits number of forecast days. Setting 0 will still provide forecast data for today. The maximum value is 9 (for today and 9 future days).
forecastResolution {1|3|6}, default: 6 h
Time resolution (number of hours between 2 samples).
Note: When value is changed all existing forecast readings will be deleted.
forecastProperties [<p1>[,<p2>]...], default: Tx, Tn, Tg, TTT, DD, FX1, Neff, RR6c, RRhc, Rh00, ww
See the DWD forecast property defintions for more details.
Notes:
- Not all properties are available for all stations and for all hours.
- If you remove a property from the list then already existing readings must be deleted manually in continuous mode.
forecastWW2Text {0|1}, default: 0
Create additional wwd readings containing the weather code as a descriptive text in German language.
forecastPruning {0|1}, default: 0
Search for and delete forecast readings that are more then one day older then other forecast readings of the same day. Pruning will be performed after a successful forecast update.
Notes:
- Intended to maintain data consistency e.g. when a forecast station changes the reporting hour of a forecast property.
- Requires noticable extra computing resources and may cause side effects if your FHEM configuration depends on a reading that is deleted.
alert related:
alertArea <warncell id>, default: none
Setting alertArea enables automatic updates of the alerts cache every 15 minutes.
A warncell id is a 9 digit numeric value from the Warncell-IDs for CAP alerts catalogue. Supported ids start with 7 and 8 (communeunion), 1 and 9 (district) or 5 (coast). To verify that alerts are provided for the warncell id you selected you should consult another source, wait for an alert situation and compare.
alertLanguage [DE|EN], default: DE
Language of descriptive alert properties.
alertExcludeEvents <event code>, default: none
Comma separated list of numeric events codes for which no alerts should be created.
Only minor alerts may be suppressed. Use at your own risk!
Readings
The forecast readings are build like this:
fc<day>_[<sample>_]<property>
A description of the more than 70 properties available and their units of measurement can be found here. The units of measurement for temperatures and wind speeds are converted to °C and km/h respectively. Only a few choice properties are listed in the following paragraphs:
day - relative day (0 .. 9) based on the timezone attribute where 0 is today
sample - relative time (0 .. 3, 7 or 23) equivalent to multiples of 6, 3 or 1 hours UTC depending on the forecastResolution attribute
day properties (typically for 06:00 station time, see raw data of station for actual time relation)
date - date based on the timezone attribute
weekday - abbreviated weekday based on the timezone attribute in the language of your FHEM system
Tn [°C] - minimum temperature of previous 12 hours
Tx [°C] - maximum temperature of previous 12 hours (typically at 18:00 station time)
Tm [°C] - average temperature of previous 24 hours
Tg [°C] - minimum temperature 5 cm above ground of previous 12 hours
PEvap [kg/m2] - evapotranspiration of previous 24 hours
SunD [s] - total sunshine duration of previous day
hour properties
time - time based on the timezone attribute
TTT [°C] - dry bulb temperature at 2 meter above ground
Td [°C] - dew point temperature at 2 meter above ground
DD [°] - average wind direction 10 m above ground
FF [km/h] - average wind speed 10 m above ground
FX1 [km/h] - maximum wind speed in the last hour
SunD1 [s] - sunshine duration in the last hour
SunD3 [s] - sunshine duration in the last 3 hours
RR1c [kg/m2] - precipitation amount in the last hour
RR3c [kg/m2] - precipitation amount in the last 3 hours
RR6c [kg/m2] - precipitation amount in the last 6 hours
R600 [%] - probability of rain in the last 6 hours
RRhc [kg/m2] - precipitation amount in the last 12 hours
Rh00 [%] - probability of rain in the last 12 hours
RRdc [kg/m2] - precipitation amount in the last 24 hours
Rd00 [%] - probability of rain in the last 24 hours
ww - weather code (see WMO 4680/4677, SYNOP)
wwd - German weather code description
VV [m] - horizontal visibility
Neff [%] - effective cloud cover
Nl [%] - lower level cloud cover below 2000 m
Nm [%] - medium level cloud cover below 7000 m
Nh [%] - high level cloud cover above 7000 m
PPPP [hPa] - pressure equivalent at sea level
extra day properties, not provided by the DWD
SunRise - time of sunrise based on the timezone attribute
SunSet - time of sunset based on the timezone attribute
extra hour properties, not provided by the DWD
SunAz [°] - sun azimuth
SunEl [°] - sun elevation
SunUp - sun up (0: night, 1: day)
Additionally there are global forecast readings:
fc_state - state of the last forecast update, possible values are 'updated' and 'error: ...'
fc_station - forecast station code (WMO or DWD)
fc_description - station description
fc_coordinates - world coordinate and height of station
fc_time - time the forecast was issued based on the timezone attribute
fc_copyright - legal information, must be displayed with forecast data, see DWD usage conditions
The alert readings are ordered by onset and are build like this:
a_<index>_<property>
index - alert index, starting with 0, total a_count, ordered by onset
alert properties
category - 'Met' or 'Health'
event - numeric event code, see DWD documentation for details
eventDesc - short event description in selected language
eventGroup - event group, see DWD documentation for details
urgency - 'Immediate' = warning or 'Future' = information
severity - 'Minor', 'Moderate', 'Severe' or 'Extreme'
areaColor - RGB colour depending on urgency and severity, comma separated decimal triple
onset - start time of alert based on the timezone attribute
expires - end time of alert based on the timezone attribute
headline - headline in selected language, typically a combination of the properties urgency and event
description - description of the alert in selected language
instruction - safety instructions in selected language
area - numeric warncell id
areaDesc - description of area, e.g. 'Stadt Berlin'
altitude - min. altitude [m]
ceiling - max. altitude [m]
Additionally there are some global alert readings:
a_state - state of the last alerts update, possible values are 'updated' and 'error: ...'
a_time - time the last alerts update was downloaded, based on the timezone attribute
a_count - number of alerts available for selected warncell id
a_copyright - legal information, must be displayed with forecast data, see DWD usage conditions, not available if count is zero
Alerts should be considered active for onset <= now < expires and responseType != 'AllClear' independent of urgency.
Inactive alerts with responseType = 'AllClear' may provide relevant instructions.
Note that all alert readings are completely replaced and reindexed with each update!
Further information regarding the alert properties can be found in the documentation of the CAP DWS Profile.
Performance
Note that depending on your device configuration each forecast consists of quite a lot of readings and each reading update will cause a FHEM event that needs to be processed. Depending on your hardware and your FHEM configuration this will take several hundred milliseconds. If you need to improve overall performance you can limit the number of readings created by setting a) the attribute forecastProperties to the ones you actually use, b) the attribute forecastResolution to the highest value suitable for your purposes and c) the attribute forecastDays to the lowest number suitable for your purposes. To further reduce the event processing overhead you can set the attribute event-on-update-reading to a small list of important reading that really need events (e.g. state,fc_state,a_state). For almost the same reason be selective when creating a log device. If you use wildcards for all readings without filtering either at the source device with readingFnAttributes or at the destination device with a regexp you will get significant extra file IO when the readings are updated and quite a lot of data.
Creates a Dashboard in any group and/or devices can be arranged. The positioning may depend the objects and column width are made
arbitrarily by drag'n drop. Also, the width and height of an object can be increased beyond the minimum size.
Note:
A group name in the dashboard respectively the attribute "dashboard_tabXgroups" equates the group name in FHEM and depict the
devices which are contained in that group.
set <name> activateTab <TabNo>
The Tab with the defined number will be activated.
If the attribute "dashboard_homeTab" is set, this defined tab will be reactivated at next
browser refresh.
set <name> lock
Locks the Dashboard so that no position changes can be made.
set <name> unlock
Unlock the Dashboard,
Get
get <name> config
Delivers the configuration of the dashboard back.
get <name> icon <icon name>
Delivers the path and full name of the denoted icon back.
Example:
get <name> icon measure_power_meter
Attributes
dashboard_backgroundimage
Displays a background image for the complete dashboard. The image is not stretched in any way. So the size should
match/extend the dashboard height/width. The relative path to "./www/images" has to be used.
Example
attr dashboard_backgroundimage dashboard/cam_video.PNG
# File ./www/images/dashboard/cam_video.PNG is shown
attr dashboard_backgroundimage cam_video.PNG
# File ./www/images/cam_video.PNG is shown
dashboard_backgroundimage
Displays a background image for the complete dashboard. The image is not stretched in any way. So the size should
match/extend the dashboard height/width. Only the filename has to be set.
The file must be at any location below the directory "./www/images/". Suggestion: Create the directory "./www/images/dashboard" and put the image file into.
Example
attr dashboard_backgroundimage cam_video.PNG
dashboard_colcount
Number of columns in which the groups can be displayed. Nevertheless, it is possible to have multiple groups
to be positioned in a column next to each other. This is depend on the width of columns and groups.
Default: 1
dashboard_debug
Show Hiddenfields. Only for Maintainer's use.
Default: 0
dashboard_flexible
If set to a value > 0, the widgets are not positioned in columns any more but can be moved freely to any position in
the tab.
The value for this parameter also defines the grid, in which the position "snaps in".
Default: 0
dashboard_hideGroupHeader
If set, the header containing the group name and group icon above the pictured FHEM-group (see also dashboard_tab1groups) is hidden.
Default: 0
dashboard_homeTab
Specifies which tab is activated. If it isn't set, the last selected tab will also be the active tab.
Default: 1
dashboard_row
To select which rows are displayed. top only; center only; bottom only; top and center; center and bottom; top,center and bottom.
Default: center
dashboard_rowbottomheight
Height of the bottom row in which the groups may be positioned.
Default: 250
dashboard_rowcenterheight
Height of the center row in which the groups may be positioned.
Default: 400
dashboard_rowcentercolwidth
About this attribute, the width of each column of the middle Dashboardrow can be set. It can be stored for each column
a separate value.
The values ​​must be separated by a comma (no spaces). Each value determines the column width in%! The first value
specifies the width of the first column, the second value of the width of the second column, etc. Is the sum of the
width greater than 100 it is reduced.
If more columns defined as widths the missing widths are determined by the difference to 100. However, are less
columns are defined as the values ​​of ignores the excess values​​.
Default: 100
dashboard_rowtopheight
Height of the top row in which the groups may be positioned.
Default: 250
dashboard_showfullsize
Hide FHEMWEB Roomliste (complete left side) and Page Header if Value is 1.
Default: 0
dashboard_showtabs
Displays the Tabs/Buttonbar on top or bottom, or hides them. If the Buttonbar is hidden lockstate is "lock" is used.
Default: tabs-and-buttonbar-at-the-top
dashboard_showtogglebuttons
Displays a Toogle Button on each Group do collapse.
Default: 0
dashboard_tab1backgroundimage
Shows a background image for the tab. (also valid for further dashboard_tabXbackgroundimage)
The image is not stretched in any way, it should therefore match the tab size or extend it.
Only the filename has to be set.
The file must be at any location below the directory "./www/images/". Suggestion: Create the directory "./www/images/dashboard" and put the image file into.
Example
attr dashboard_tab1backgroundimage cam_video.PNG
dashboard_tab1colcount
Number of columns for a specific tab in which the groups can be displayed. (also valid for further dashboard_tabXcolcount)
Nevertheless, it is possible to have multiple groups to be positioned in a column next to each other.
This depends on the width of columns and groups.
Default: <dashboard_colcount>
dashboard_tab1devices
DevSpec list of devices that should appear in the tab. (also valid for further dashboard_tabXdevices)
The format is:
GROUPNAME:devspec1,devspec2,...,devspecX:ICONNAME
ICONNAME is optional. Also GROUPNAME is optional. In case of missing GROUPNAME, the matching devices are
not grouped, but shown as separate widgets without titles.
For further details on the DevSpec format see DevSpec.
dashboard_tab1groups
Comma separated list of FHEM groups (see attribute "group" in a device) to be displayed in Tab.
(also valid for further dashboard_tabXgroups)
Each group can be given an icon for this purpose the group name, the following must be
completed ":<icon>@<color>"
Additionally a group can contain a regular expression to show all groups matching a criteria.
Example:
.*Light.* to show all groups that contain the string "Light"
dashboard_tab1icon
Set the icon for a Tab. (also valid for further dashboard_tabXicon)
There must exist an icon with the name ico.(png|svg) in the modpath directory. If the image is
referencing an SVG icon, then you can use the @colorname suffix to color the image.
dashboard_tab1name
Title of Tab. (also valid for further dashboard_tabXname)
dashboard_tab1sorting
Contains the position of each group in Tab. (also valid for further dashboard_tabXsorting)
Value is written by the "Set" button. It is not recommended to take manual changes.
dashboard_noLinks
No link generation to the detail view of the devices takes place.
Note:
Some device types deliver the links to their detail view integrated in the device.
In such cases you have to deactivate the link generation inside of the device (for example in SMAPortalSPG).
dashboard_webRefresh
With this attribute the FHEMWEB-Devices are determined, which:
are activating the tab of a dashboard when the attribute "dashboard_homeTab" will be set
are positioning to the tab specified by command "set <name> activateTab"
Default: all
dashboard_width
To determine the Dashboardwidth. The value can be specified, or an absolute width value (eg 1200) in pixels in% (eg 80%).
Default: 100%
At first you need to install and setup the database.
The installation of database system itself is not described here, please refer to the installation instructions of your
database.
Note:
In case of fresh installed MySQL/MariaDB system don't forget deleting the anonymous "Everyone"-User with an admin-tool if
existing.
Sample code and Scripts to prepare a MySQL/PostgreSQL/SQLite database you can find in
SVN -> contrib/dblog/db_create_<DBType>.sql.
(Caution: The local FHEM-Installation subdirectory ./contrib/dblog doesn't contain the freshest scripts!)
The older standard installation of the MySQL/MariaDB database provided for the use of the utf8_bin collation.
With this setting, characters up to 3 bytes long can be stored, which is generally sufficient.
However, if characters with a length of 4 bytes (e.g. emojis) are to be stored in the database, the utf8mb4
character set must be used.
Accordingly, in this case the MySQL/MariaDB database would be created with the following statement:
Note the key utf8 if the MySQL database driver is used (MODEL = MYSQL).
The database contains two tables: current and history.
The latter contains all events whereas the former only contains the last event for any given reading and device.
Please consider the DbLogType implicitly to determine the usage of tables
current and history.
The columns have the following meaning:
TIMESTAMP
: timestamp of event, e.g. 2007-12-30 21:45:22
DEVICE
: device name, e.g. Wetterstation
TYPE
: device type, e.g. KS300
EVENT
: event specification as full string, e.g. humidity: 71 (%)
READING
: name of reading extracted from event, e.g. humidity
VALUE
: actual reading extracted from event, e.g. 71
UNIT
: unit extracted from event, e.g. %
create index
Due to reading performance, e.g. on creation of SVG-plots, it is very important that the index "Search_Idx"
or a comparable index (e.g. a primary key) is applied.
A sample code for creation of that index is also available in mentioned scripts of
SVN -> contrib/dblog/db_create_<DBType>.sql.
The index "Search_Idx" can be created, e.g. in database 'fhem', by these statements (also subsequently):
MySQL
: CREATE INDEX Search_Idx ON `fhem`.`history` (DEVICE, READING, TIMESTAMP);
MariaDB
: CREATE INDEX Search_Idx ON `fhem`.`history` (DEVICE, READING, TIMESTAMP);
SQLite
: CREATE INDEX Search_Idx ON `history` (DEVICE, READING, TIMESTAMP);
PostgreSQL
: CREATE INDEX "Search_Idx" ON history USING btree (device, reading, "timestamp");
For the connection to the database a configuration file is used.
The configuration file is copied e.g. to /opt/fhem and has the structure shown below.
The specifications are to be adapted according to the used environment (uncomment and change corresponding lines):
####################################################################################
# database configuration file
#
# NOTE:
# If you don't use a value for user / password please delete the leading hash mark
# and write 'user => ""' respectively 'password => ""' instead !
#
#
## for MySQL
####################################################################################
#%dbconfig= (
# connection => "mysql:database=fhem;host=<database host>;port=3306",
# # if want communication over socket-file instead of TCP/IP transport, use:
# # connection => "mysql:database=fhem;mysql_socket=</path/socket-file>",
# user => "fhemuser",
# password => "fhempassword",
# # optional enable UTF-8 support
# # (full UTF-8 support exists from DBD::mysql version 4.032, but installing
# # 4.042 is highly suggested)
# utf8 => 1,
# # optional enable communication compression between client and server
# compression => 1
#);
####################################################################################
#
## for MariaDB
####################################################################################
#%dbconfig= (
# connection => "MariaDB:database=fhem;host=<database host>;port=3306",
# # if want communication over socket-file instead of TCP/IP transport, use:
# # connection => "MariaDB:database=fhem;mariadb_socket=</path/socket-file>",
# user => "fhemuser",
# password => "fhempassword",
# # optional enable communication compression between client and server
# compression => 1
#);
####################################################################################
#
## for PostgreSQL
####################################################################################
#%dbconfig= (
# connection => "Pg:database=fhem;host=<database host>",
# user => "fhemuser",
# password => "fhempassword"
#);
####################################################################################
#
## for SQLite (username and password stay empty for SQLite)
####################################################################################
#%dbconfig= (
# connection => "SQLite:dbname=/opt/fhem/fhem.db",
# user => "",
# password => ""
#);
####################################################################################
If configDB is used, the configuration file has to be uploaded into the configDB!
Note about special characters:
If special characters, e.g. @,$ or % which have a meaning in the perl programming
language are used in a password, these special characters have to be escaped.
That means in this example you have to use: \@,\$ respectively \%.
DbLog specific events
DbLog generates events depending on the initialisation status of the DbLog device:
FRAME_INITIALIZED
- The basic framework is initialised. Blocking (Get) commands can be executed.
SUBPROC_INITIALIZED
- The SupProcess is ready for use. Non-blocking (set) commands and Data logging can be executed.
SUBPROC_DISCONNECTED
- The SupProcess was separated from the DB.
SUBPROC_STOPPED
- The SupProcess has been stopped.
Define
define <name> DbLog <configfilename> <regexp>
<configfilename> is the prepared configuration file. <regexp> is identical to the specification of regex in the FileLog definition.
Example:
define myDbLog DbLog /etc/fhem/db.conf .*:.*
all events will stored into the database
After you have defined your DbLog-device it is recommended to run the configuration check
get <name> configCheck
This check reports some important settings and gives recommendations back to you if proposals are indentified.
DbLog distinguishes between the synchronous (default) and asynchronous logmode. The logmode is adjustable by the
asyncMode. Since version 2.13.5 DbLog is supporting primary key (PK) set in table
current or history. If you want use PostgreSQL with PK it has to be at lest version 9.5.
The content of VALUE will be optimized for automated post-processing, e.g. yes is translated
to 1
The stored values can be retrieved by the following code like FileLog:
get myDbLog - - 2012-11-10 2012-11-10 KS300:temperature::
transfer FileLog-data to DbLog
There is the special module 98_FileLogConvert.pm available to transfer filelog-data to the DbLog-database.
The module can be downloaded here
or from directory ./contrib instead.
Further information and help you can find in the corresponding
Forumthread .
Reporting and Management of DbLog database content
By using SVG database content can be visualized.
Beyond that the module DbRep can be used to prepare tabular
database reports or you can manage the database content with available functions of that module.
Troubleshooting
If after successful definition the DbLog-device doesn't work as expected, the following notes may help:
Have the preparatory steps as described in commandref been done ? (install software components, create tables and index)
Was "get <name> configCheck" executed after definition and potential errors fixed or rather the hints implemented ?
If configDB is used ... has the database configuration file been imported into configDB (e.g. by "configDB fileimport ./db.conf") ?
When creating a SVG-plot and no drop-down list with proposed values appear -> set attribute "DbLogType" to "Current/History".
If the notes don't lead to success, please increase verbose level of the DbLog-device to 4 or 5 and observe entries in
logfile relating to the DbLog-device.
For problem analysis please post the output of "list <name>", the result of "get <name> configCheck" and the
logfile entries of DbLog-device to the forum thread.
Set
set <name> addCacheLine YYYY-MM-DD HH:MM:SS|<device>|<type>|<event>|<reading>|<value>|[<unit>]
In asynchronous mode a new dataset is inserted to the Cache and will be processed at the next database sync cycle.
Example:
set <name> addCacheLine 2017-12-05 17:03:59|MaxBathRoom|MAX|valveposition: 95|valveposition|95|%
set <name> addLog <devspec>:<Reading> [Value] [CN=<caller name>] [!useExcludes]
Inserts an additional log entry of a device/reading combination into the database.
Any readings specified in the "DbLogExclude" attribute (in the source device) will not be logged, unless
they are included in the "DbLogInclude" attribute or the addLog call was made with the "!useExcludes" option.
The specification of "Reading" is evaluated as a regular expression.
If the reading does not exist and the value "Value" is specified, the reading
will be inserted into the DB if it is not a regular expression and a valid reading name.
Value
Optionally, "Value" can be specified for the reading value.
If Value is not specified, the current value of the reading is inserted into the DB.
CN=<caller name>
With the key "CN=" (Caller Name) a string, e.g. the name of the calling device,
can be added to the addLog call.
With the help of the function stored in the attribute valueFn
this key can be evaluated via the variable $CN.
!useExcludes
addLog by default takes into account the readings excluded with the "DbLogExclude" attribute.
With the keyword "!useExcludes" the set attribute "DbLogExclude" is ignored.
The database field "EVENT" is automatically filled with "addLog".
There will be no additional event created in the system!
Examples:
set <name> addLog SMA_Energymeter:Bezug_Wirkleistung
set <name> addLog TYPE=SSCam:state
set <name> addLog MyWetter:(fc10.*|fc8.*)
set <name> addLog MyWetter:(wind|wind_ch.*) 20 !useExcludes
set <name> addLog TYPE=CUL_HM:FILTER=model=HM-CC-RT-DN:FILTER=subType!=(virtual|):(measured-temp|desired-temp|actuator)
set <name> addLog USV:state CN=di.cronjob
In the valueFn function the caller "di.cronjob" is evaluated via the variable $CN and depending on this the
timestamp of this addLog is corrected:
This function clears readings which were created by different DbLog-functions.
set <name> commitCache
In asynchronous mode (asyncMode=1), the cached data in memory will be written
into the database and subsequently the cache will be cleared.
Thereby the internal timer for the asynchronous mode Modus will be set new.
set <name> configCheck
Checks some important settings and give recommendations back to you if proposals are identified.
(Note: This command is deprecated and will be removed in next releases. Use "get <name> configCheck" instead.)
set <name> count
Determines the number of records in the tables current and history and writes the results to the readings
countCurrent and countHistory.
Note
During the runtime of the command, data to be logged are temporarily stored in the memory cache and written to the
database written to the database after the command is finished.
set <name> deleteOldDays <n>
Deletes records older than <n> days in table history.
The number of deleted records is logged in Reading lastRowsDeleted.
Note
During the runtime of the command, data to be logged are temporarily stored in the memory cache and written to the
database written to the database after the command is finished.
set <name> eraseReadings
This function deletes all readings except reading "state".
set <name> exportCache [nopurge | purgecache]
If DbLog is operated in asynchronous mode, the cache can be written to a text file with this command.
The file is created by default in the directory (global->modpath)/log/. The destination directory can be changed with
the expimpdir attribute.
The name of the file is generated automatically and contains the prefix "cache_<name>" followed by
the current timestamp.
Example
cache_LogDB_2017-03-23_22-13-55
The "nopurge" and "purgecache" options determine whether or not the cache contents are to be deleted after the export.
With "nopurge" (default) the cache content is preserved.
The exportCacheAppend attribute determines whether with each export
operation a new export file is created (default) or the cache content is appended to the latest existing export file.
set <name> importCachefile <file>
Imports a file written with "exportCache" into the database.
The available files are searched by default in the directory (global->modpath)/log/ and a drop-down list is generated
with the files are found.
The source directory can be changed with the expimpdir attribute.
Only the files matching the pattern "cache_<name>" are displayed.
Example
cache_LogDB_2017-03-23_22-13-55
if the DbLog device is called "LogDB".
After a successful import the file is prefixed with "impdone_" and no longer appears in the drop-down list.
If a cache file is to be imported into a database other than the source database, the name of the
DbLog device in the file name can be adjusted so that this file appears in the drop-down list.
Note
During the runtime of the command, data to be logged are temporarily stored in the memory cache and written
to the database after the command is finished.
set <name> listCache
Lists the data cached in the memory cache.
set <name> purgeCache
In asynchronous mode (asyncMode=1), the in memory cached data will be deleted.
With this command data won't be written from cache into the database.
set <name> reduceLog <no>[:<nn>] [average[=day]] [exclude=device1:reading1,device2:reading2,...]
Reduces historical records older than <no> days and (optionally) newer than <nn> days
to one record (the first) per hour per device & reading.
Inside device/reading SQL wildcards "%" and "_" can be used.
The optional specification of 'average' or 'average=day' not only cleans the database, but also reduces all
numerical values of an hour or a day are reduced to a single average value.
Optionally, the last parameter "exclude=device1:reading1,device2:reading2,...." can be specified
to exclude device/reading combinations from reduceLog.
Instead of "exclude", "include=device:reading" can be specified as the last parameter in order to
limit the SELECT query executed on the database. This reduces the RAM load and increases performance.
The option "include" can only be specified with a device:reading combination.
Examples:
set <name> reduceLog 270 average include=Luftdaten_remote:%
set <name> reduceLog 100:200 average exclude=SMA_Energymeter:Bezug_Wirkleistung
Note
During the runtime of the command, data to be logged is temporarily stored in the memory cache and written to
the database after the command is finished.
set <name> reopen [n]
Closes the database and then immediately opens it again if no time [n] in seconds has been specified.
If an optional delay time [n] in seconds has been specified, the connection to the database will be closed and
reconnected only after [n] seconds have elapsed.
During the time of the database closure, events to be logged are stored in the memory cache and written to the
database after the reconnect.
set <name> rereadcfg
The configuration file is read in again.
After reading, an existing database connection is terminated and re-established with the configured connection data.
set <name> stopSubProcess
A running SubProcess is terminated.
As soon as a new subprocess is required by a Log operation, an automatic reinitialization of a process takes place.
Note
The re-initialization of the sub-process during runtime causes an increased RAM consumption until
to a FHEM restart .
set <name> userCommand <validSelectStatement>
Executes simple SQL Select commands on the database.
The result of the statement is written to the reading "userCommandResult".
The result can be only one line.
The execution of SQL commands in DbLog is deprecated.
The DbRep evaluation module should be used for this
purpose.
Note
During the runtime of the command, data to be logged are temporarily stored in the memory cache and written to the
database written to the database after the command is finished.
Get
get <name> configCheck
A number of key settings are reviewed and recommendations are made if potential improvements are identified.
get <name> ReadingsMaxVal[Timestamp] <Device> <Reading> <default>
Determines the record with the largest value of the specified Device / Reading combination from the history table.
Only the value or the combination of value and timestamp is returned as string
"<Wert> , <Timestamp>".
<default> specifies a defined return value if no value can be determined.
Note:
This database retrieval works blocking and influences FHEM if the database does not respond or not responds
sufficiently fast. For non-blocking database queries is referred to the module DbRep.
.
get <name> ReadingsMinVal[Timestamp] <Device> <Reading> <default>
Determines the record with the smallest value of the specified device / reading combination from the history table.
Only the value or the combination of value and timestamp is returned as string
"<Wert> , <Timestamp>".
<default> specifies a defined return value if no value can be determined.
Note:
This database retrieval works blocking and influences FHEM if the database does not respond or not responds
sufficiently fast. For non-blocking database queries is referred to the module DbRep.
get <name> ReadingsAvgVal <Device> <Reading> <default>
Determines the average value of the specified Device / Reading combination from the history table.
The simple arithmetic average value is returned.
<default> specifies a defined return value if no value can be determined.
Note:
This database retrieval works blocking and influences FHEM if the database does not respond or not responds
sufficiently fast. For non-blocking database queries is referred to the module DbRep.
get <name> ReadingsVal[Timestamp] <Device> <Reading> <default>
Reads the last (newest) record stored in the history table of the specified Device / Reading
combination.
Only the value or the combination of value and timestamp is returned as string
"<Wert> , <Timestamp>".
<default> specifies a defined return value if no value can be determined.
Note:
This database retrieval works blocking and influences FHEM if the database does not respond or not responds
sufficiently fast. For non-blocking database queries is referred to the module DbRep.
get <name> ReadingsTimestamp <Device> <Reading> <default>
Reads the timestamp of the last (newest) record stored in the history table of the specified
Device/Reading combination and returns this value.
<default> specifies a defined return value if no value is found in the database.
Note:
This database retrieval works blocking and influences FHEM if the database does not respond or not responds
sufficiently fast. For non-blocking database queries is referred to the module DbRep.
get <name> retrieve <querytype> <device|table> <reading> <from> <to> <offset> <limit>
Reads data from the database table history and returns the results formatted as JSON.
The query method or the desired query result is determined by the specified <querytype>.
Each <querytype> may require additional parameters according to the following table. Parameters not entered
must always be entered as "" if another parameter is entered afterwards.
alldevices
Determines all devices stored in the database.
allreadings
Determines all readings stored in the database for a specific device.
required parameters: <device>
count
Returns the number of records of the specified table.
required parameters: <table> (history or current)
fetchrows
Determines the stored records of a certain period.
The number of records in the defined period is returned as the "totalcount" key.
Note:
This database retrieval works blocking and influences FHEM if the database does not respond or not responds
sufficiently fast. For non-blocking database queries is referred to the module DbRep.
Examples:
get LogSQLITE3 retrieve alldevices
get LogSQLITE3 retrieve allreadings MySTP_5000
get LogSQLITE3 retrieve last "" "" "" "" "" 50
get LogSQLITE3 retrieve count history
get LogSQLITE3 retrieve timerange MySTP_5000 etotal 2023-01-01_00:00:00 2023-01-25_00:00:00
get LogSQLITE3 retrieve fetchrows MySTP_5000 "" 2023-01-01_00:00:00 2023-01-25_00:00:00 0 100
get LogSQLITE3 retrieve fetchrows "" etotal 2023-01-01_00:00:00 2023-01-25_00:00:00 0 100
get LogSQLITE3 retrieve hourstats MySTP_5000 etotal 2023-01-01_00:00:00 2023-01-25_00:00:00
Get for the use of SVG plots
get <name> <in> <out> <from> <to> <column_spec>
Read data from the Database used by frontends to plot data without direct access to the Database.
<in>
A parameter to establish compatibility with Filelog.
In the definition of an SVG device this parameter corresponds to the specification of :<logfile> at the end of the definition.
The following characteristics are allowed:
current: the values are read from the "current" table.
history: the values are read from the "history" table.
table_<table>: the values are read from the specified alternative table. The table (name)
must be created in the database with lowercase letters.
(example: table_energy, "energy" is the alternative table created in the database)
-: identical as "history
<out>
A dummy parameter for FileLog compatibility. Setting by default to -
to check the output for plot-computing.
Set it to the special keyword
all to get all columns from Database.
ALL: get all colums from table, including a header
Array: get the columns as array of hashes
INT: internally used by generating plots
-: default
<from> / <to>
Used to select the data. Please use the following timeformat or
an initial substring of it:
YYYY-MM-DD_HH24:MI:SS
<column_spec>
For each column_spec return a set of data separated by
a comment line on the current connection.
<device>
The name of the device. Case sensitive. Using a the joker "%" is supported.
<reading>
The reading of the given device to select. Case sensitive. Using a the joker "%" is supported.
<default>
no implemented yet
<fn>
One of the following:
int
Extract the integer at the beginning of the string. Used e.g.
for constructs like 10%
int<digit>
Extract the decimal digits including negative character and
decimal point at the beginning og the string. Used e.g.
for constructs like 15.7°C
delta-h / delta-d
Return the delta of the values for a given hour or a given day.
Used if the column contains a counter, as is the case for the
KS300 rain column.
delta-ts
Replaced the original value with a measured value of seconds since
the last and the actual logentry.
<regexp>
The string is evaluated as a perl expression. The regexp is executed
before <fn> parameter.
Note: The string/perl expression cannot contain spaces,
as the part after the space will be considered as the
next column_spec.
Keywords
$val is the current value returned from the Database.
$ts is the current timestamp returned from the Database.
This Logentry will not print out if $val contains th keyword "hide".
This Logentry will not print out and not used in the following processing
if $val contains th keyword "ignore".
Examples:
get myDbLog - - 2012-11-10 2012-11-20 KS300:temperature
get myDbLog current ALL - - %:temperature
you will get all actual readings "temperature" from all logged devices.
Be careful by using "history" as inputfile because a long execution time will be expected!
get myDbLog - - 2012-11-10_10 2012-11-10_20 KS300:temperature::int1
like from 10am until 08pm at 10.11.2012
get myDbLog - all 2012-11-10 2012-11-20 KS300:temperature
get myDbLog - - 2012-11-10 2012-11-20 KS300:temperature KS300:rain::delta-h KS300:rain::delta-d
get myDbLog - - 2012-11-10 2012-11-20 MyFS20:data:::$val=~s/(on|off).*/$1eq"on"?1:0/eg
return 1 for all occurance of on* (on|on-for-timer etc) and 0 for all off*
get myDbLog - - 2012-11-10 2012-11-20 Bodenfeuchte:data:::$val=~s/.*B:\s([-\.\d]+).*/$1/eg
Example of OWAD: value like this: "A: 49.527 % B: 66.647 % C: 9.797 % D: 0.097 V"
and output for port B is like this: 2012-11-20_10:23:54 66.647
get DbLog - - 2013-05-26 2013-05-28 Pumpe:data::delta-ts:$val=~s/on/hide/
Setting up a "Counter of Uptime". The function delta-ts gets the seconds between the last and the
actual logentry. The keyword "hide" will hide the logentry of "on" because this time
is a "counter of Downtime"
<name>
The name of the defined DbLog, like it is given in fhem.cfg.
<in>
Always set to -
<out>
Is to be set to webchart.
<from> / <to>
Used to select the data. Please use the following timeformat:
YYYY-MM-DD_HH24:MI:SS
<device>
A string which represents the device to query.
<querytype>
A string which represents the method the query should use. Actually supported values are: getreadings to retrieve the possible readings for a given device getdevices to retrieve all available devices timerange to retrieve charting data, which requires a given xaxis, yaxis, device, to and from savechart to save a chart configuration in the database. Requires a given xaxis, yaxis, device, to and from, and a 'savename' used to save the chart deletechart to delete a saved chart. Requires a given id which was set on save of the chart getcharts to get a list of all saved charts. getTableData to get jsonformatted data from the database. Uses paging Parameters like start and limit. hourstats to get statistics for a given value (yaxis) for an hour. daystats to get statistics for a given value (yaxis) for a day. weekstats to get statistics for a given value (yaxis) for a week. monthstats to get statistics for a given value (yaxis) for a month. yearstats to get statistics for a given value (yaxis) for a year.
<xaxis>
A string which represents the xaxis. It must be a valid field name, typically 'TIMESTAMP', of the history table.
<yaxis>
A string representing the Y-axis to be set to the name of the reading to be evaluated.
<savename>
A string which represents the name a chart will be saved with.
<chartconfig>
A jsonstring which represents the chart to save.
<pagingstart>
An integer used to determine the start for the sql used for query 'getTableData'.
<paginglimit>
An integer used to set the limit for the sql used for query 'getTableData'.
Examples:
get logdb - webchart "" "" "" getcharts
Retrieves all saved charts from the Database
get logdb - webchart "" "" "" getdevices
Retrieves all available devices from the Database
get logdb - webchart "" "" ESA2000_LED_011e getreadings
Retrieves all available Readings for a given device from the Database
get logdb - webchart 2013-02-11_00:00:00 2013-02-12_00:00:00 ESA2000_LED_011e timerange TIMESTAMP day_kwh
Retrieves charting data, which requires a given xaxis, yaxis, device, to and from
Will ouput a JSON like this: [{'TIMESTAMP':'2013-02-11 00:10:10','VALUE':'0.22431388090756'},{'TIMESTAMP'.....}]
get logdb - webchart 2013-02-11_00:00:00 2013-02-12_00:00:00 ESA2000_LED_011e savechart TIMESTAMP day_kwh tageskwh
Will save a chart in the database with the given name and the chart configuration parameters
get logdb - webchart "" "" "" deletechart "" "" 7
Will delete a chart from the database with the given id
Attributes
addStateEvent [0|1]
As you probably know the event associated with the state Reading is special, as the "state: "
string is stripped, i.e event is not "state: on" but just "on".
Mostly it is desireable to get the complete event without "state: " stripped, so it is the default behavior of DbLog.
That means you will get state-event complete as "state: xxx".
In some circumstances, e.g. older or special modules, it is a good idea to set addStateEvent to "0".
Try it if you have trouble with the default adjustment.
asyncMode [0|1]
This attribute sets the processing procedure according to which the DbLog device writes the data to the database.
DbLog uses a sub-process to write the log data into the database and processes the data
generally not blocking for FHEM.
Thus, the writing process to the database is generally not blocking and FHEM is not affected in the case
the database is not performing or is not available (maintenance, error condition).
0 -
Synchronous log mode. The data to be logged is only briefly cached and immediately
written to the database. (default)
Advantages:
In principle, the data is immediately available in the database.
Very little to no data is lost when FHEM crashes.
Disadvantages:
An alternative storage in the file system (in case of database problems) is not supported.
1 -
Asynchroner Log-Modus. The data to be logged is first cached in a memory cache and written to the database
Change the usage of database autocommit- and/or transaction- behavior.
If transaction "off" is used, not saved datasets are not returned to cache in asynchronous mode.
This attribute is an advanced feature and should only be used in a concrete situation or support case.
basic_ta:on - autocommit server basic setting / transaktion on (default)
basic_ta:off - autocommit server basic setting / transaktion off
ac:on_ta:on - autocommit on / transaktion on
ac:on_ta:off - autocommit on / transaktion off
ac:off_ta:on - autocommit off / transaktion on (autocommit "off" set transaktion "on" implicitly)
cacheEvents [2|1|0]
0 -
No events are generated for CacheUsage.
1 -
Events are generated for the Reading CacheUsage when a new record is added to the cache.
2 -
Events are generated for the Reading CacheUsage when the write cycle to the database starts in
asynchronous mode. CacheUsage contains the number of records in the cache at this time.
(default: 0)
cacheLimit <n>
In asynchronous logging mode the content of cache will be written into the database and cleared if the number <n> datasets
in cache has reached. Thereby the timer of asynchronous logging mode will be set new to the value of
attribute "syncInterval". In case of error the next write attempt will be started at the earliest after
syncInterval/2.
(default: 500)
cacheOverflowThreshold <n>
In asynchronous log mode, sets the threshold of <n> records above which the cache contents are exported to a
file instead of writing the data to the database.
The executed function corresponds to the set command "exportCache purgecache" and uses its settings.
This attribute can be used to prevent an overload of the server memory if the database is not available for a
longer period of time (e.g. in case of error or maintenance). If the attribute value is less than or equal to the
value of the cacheLimit attribute, the value of cacheLimit is used for cacheOverflowThreshold.
In this case the cache will always be written to a file instead of to the database if the threshold value
has been reached.
With this setting, the data can be written to one or more files in order to import them into the database
at a later time with the set command "importCachefile".
colEvent <n>
The field length of database field EVENT is adapted user-specifically. The attribute can be used to change the
default value in the module if the field length in the database was changed manually.
With colEvent=0 the database field EVENT is not filled. Note:
With set attribute all field length limits are also valid for SQLite DB as shown in Internal COLUMNS!
colReading <n>
The field length of database field READING is adapted user-specifically. BThe attribute can be used to change the
default value in the module if the field length in the database was changed manually.
With colReading=0 the database field READING is not filled. Note:
With set attribute all field length limits are also valid for SQLite DB as shown in Internal COLUMNS!
colType <n>
The field length for the database field TYPE is adapted user-specifically. The attribute can be used to change the
default value in the module if the field length in the database was changed manually.
With colType=0 the database field TYPE is not filled. Note:
With set attribute all field length limits are also valid for SQLite DB as shown in Internal COLUMNS!
colValue <n>
The field length of database field VALUE is adapted user-specifically. The attribute can be used to change the
default value in the module if the field length in the database was changed manually.
With colValue=0 the database field VALUE is not filled. Note:
With set attribute all field length limits are also valid for SQLite DB as shown in Internal COLUMNS!
convertTimezone [UTC | none]
UTC - the local timestamp of the event will be converted to UTC.
(default: none)
Note:
The Perl modules 'DateTime' and 'DateTime::Format::Strptime' must be installed!
DbLogType [Current|History|Current/History]
This attribute determines which table or which tables in the database are wanted to use. If the attribute isn't set,
the adjustment history will be used as default.
The meaning of the adjustments in detail are:
Current
Events are only logged into the current-table.
The entries of current-table will evaluated with SVG-creation.
History
Events are only logged into the history-table. No dropdown list with proposals will created with the
SVG-creation.
Current/History
Events will be logged both the current- and the history-table.
The entries of current-table will evaluated with SVG-creation.
SampleFill/History
Events are only logged into the history-table. The entries of current-table will evaluated with SVG-creation
and can be filled up with a customizable extract of the history-table by using a
DbRep-device command
"set <DbRep-name> tableCurrentFillup" (advanced feature).
Note:
The current-table has to be used to get a Device:Reading-DropDown list when a SVG-Plot will be created.
This attribute, specific to DbLog devices, influences how the device-specific attributes
DbLogExclude and DbLogInclude
are evaluated. DbLogExclude and DbLogInclude are set in the source devices.
If the DbLogSelectionMode attribute is not set, "Exclude" is the default.
Exclude: Readings are logged if they match the regex specified in the DEF. Excluded are
the readings that match the regex in the DbLogExclude attribute.
The DbLogInclude attribute is not considered in this case.
Include: Only readings are logged which are included via the regex in the attribute DbLogInclude
are included.
The DbLogExclude attribute is not considered in this case, nor is the regex in DEF.
Exclude/Include: Works basically like "Exclude", except that both the attribute DbLogExclude
attribute and the DbLogInclude attribute are checked.
Readings that were excluded by DbLogExclude, but are included by DbLogInclude
are therefore still included in the logging.
The DbLogInclude attribute defines the readings to be stored in the database.
The definition of the readings to be stored is done by a regular expression and all readings that match the regular
expression are stored in the database.
The optional <MinInterval> addition specifies that a value is saved when at least <MinInterval>
seconds have passed since the last save.
Regardless of the expiration of the interval, the reading is saved if the value of the reading has changed.
With the optional modifier "force" the specified interval <MinInterval> can be forced to be kept even
if the value of the reading has changed since the last storage.
| Modifier | within interval | outside interval |
| | Value equal | Value changed | |
|----------+--------------------+-----------------+------------------|
| <none> | ignore | store | store |
| force | ignore | ignore | store |
Notes:
The DbLogInclude attribute is propagated in all devices when DbLog is used.
The DbLogSelectionMode attribute must be set accordingly
to enable DbLogInclude.
With the defaultMinInterval attribute a default for
<MinInterval> can be specified.
The DbLogExclude attribute defines the readings that should not be stored in the database.
The definition of the readings to be excluded is done via a regular expression and all readings matching the
regular expression are excluded from logging to the database.
Readings that have not been excluded via the regex are logged in the database. The behavior of the
storage is controlled with the following optional specifications.
The optional <MinInterval> addition specifies that a value is saved when at least <MinInterval>
seconds have passed since the last storage.
Regardless of the expiration of the interval, the reading is saved if the value of the reading has changed.
With the optional modifier "force" the specified interval <MinInterval> can be forced to be kept even
if the value of the reading has changed since the last storage.
| Modifier | within interval | outside interval |
| | Value equal | Value changed | |
|----------+--------------------+-----------------+------------------|
| <none> | ignore | store | store |
| force | ignore | ignore | store |
Notes:
The DbLogExclude attribute is propagated in all devices when DbLog is used.
The DbLogSelectionMode attribute can be set appropriately
to disable DbLogExclude.
With the defaultMinInterval attribute a default for
<MinInterval> can be specified.
If DbLog is used, the DbLogValueFn attribute is propagated in all devices.
This attribute is set in the source devices and allows to change the values before logging
or exclude the record from logging.
The variables $TIMESTAMP, $READING, $VALUE (value of the reading) and $UNIT (unit of the reading value)
can be accessed and modified before logging to the database.
Read access is available to $DEVICE (the name of the source device), $EVENT, $LASTTIMESTAMP, and $LASTVALUE.
The variables $LASTTIMESTAMP and $LASTVALUE contain time and value of the last logged record of
$DEVICE / $READING.
If $TIMESTAMP is to be changed, the form "yyyy-mm-dd hh:mm:ss" must be followed.
Otherwise the changed $TIMESTAMP variable will not be applied.
By setting the variable "$IGNORE=1" the record is excluded from logging.
The device specific function in "DbLogValueFn" is applied to the record before the function in the "valueFn"
attribute of the DbLog device.
This attribute is available for database types MySQL/MariaDB and PostgreSQL. The table names (current/history) are
extended by its database schema. It is an advanced feature and normally not necessary to set.
With this attribute a default minimum interval for devspec is defined.
If a defaultMinInterval is set, the logentry is dropped if the defined interval is not reached and the value vs.
lastvalue is equal.
If the optional parameter "force" is set, the logentry is also dropped even though the value is not
equal the last one and the defined interval is not reached.
Potential set DbLogExclude / DbLogInclude specifications in source devices are having priority over defaultMinInterval
and are not overwritten by this attribute.
This attribute can be specified as multiline input.
Examples attr dblog defaultMinInterval .*::120::force
# Events of all devices are logged only in case of 120 seconds are elapsed to the last log entry (reading specific) independent of a possible value change. attr dblog defaultMinInterval (Weather|SMA)::300
# Events of devices "Weather" and "SMA" are logged only in case of 300 seconds are elapsed to the last log entry (reading specific) and the value is equal to the last logged value. attr dblog defaultMinInterval TYPE=CUL_HM::600::force
# Events of all devices of Type "CUL_HM" are logged only in case of 600 seconds are elapsed to the last log entry (reading specific) independent of a possible value change.
The device/reading-combinations "devspec1#Reading", "devspec2#Reading" up to "devspec.." are globally excluded from
logging into the database.
The specification of a reading is optional.
Thereby devices are explicit and consequently excluded from logging without consideration of another excludes or
includes (e.g. in DEF).
The devices to exclude can be specified as device-specification.
Examples
attr <device> excludeDevs global,Log.*,Cam.*,TYPE=DbLog
# The devices global respectively devices starting with "Log" or "Cam" and devices with Type=DbLog are excluded from database logging.
attr <device> excludeDevs .*#.*Wirkleistung.*
# All device/reading-combinations which contain "Wirkleistung" in reading are excluded from logging.
attr <device> excludeDevs SMA_Energymeter#Bezug_WirkP_Zaehler_Diff
# The event containing device "SMA_Energymeter" and reading "Bezug_WirkP_Zaehler_Diff" are excluded from logging.
expimpdir <directory>
If the cache content will be exported by exportCache command,
the file will be written into or read from that directory. The default directory is
"(global->modpath)/log/".
Make sure the specified directory is existing and writable.
Example
attr <device> expimpdir /opt/fhem/cache/
exportCacheAppend [1|0]
If set, the export of cache ("set <device> exportCache") appends the content to the newest available
export file. If there is no exististing export file, it will be new created.
If the attribute not set, every export process creates a new export file . (default)
headerLinks [text|icon]
The links offered in the header area of the device for executing various functions are displayed either as icons (default)
or text. The text language is defined by the global attribute 'language'.
insertMode [1|0]
Toggles the insert mode of the database interface.
0 -
The data is passed as an array to the database interface. (default)
It is in most cases the most performant way to insert a lot of data into the database at once.
1 -
The records are passed sequentially to the database interface and inserted into the DB.
noSupportPK [1|0]
Deactivates the support of a set primary key by the module.
plotInputFieldLength <Ganzzahl>
Width of the Plot Editor input fields for Device:Reading and Function.
If the drop-down list is used as input help for Device:Reading, the width of the field is
set automatically.
(default: 40)
SQLiteCacheSize <number of memory pages used for caching>
The default is about 4MB of RAM to use for caching (page_size=1024bytes, cache_size=4000).
Embedded devices with scarce amount of RAM can go with 1000 pages or less. This will impact
the overall performance of SQLite.
(default: 4000)
SQLiteJournalMode [WAL|off]
Determines how SQLite databases are opened. Generally the Write-Ahead-Log (WAL) is the best choice for robustness
and data integrity.
Since WAL about doubles the spaces requirements on disk it might not be the best fit for embedded devices
using a RAM backed disk. off will turn the journaling off. In case of corruption, the database probably
won't be possible to repair and has to be recreated!
(default: WAL)
syncEvents [1|0]
events of reading syncEvents will be created.
showproctime [1|0]
If set, the reading "sql_processing_time" shows the required processing time (in seconds) for the
SQL execution of the executed function.
This does not consider a single SQL statement, but the sum of all executed SQL commands within the
respective function is considered.
The reading "background_processing_time" shows the time used in the SubProcess.
showNotifyTime [1|0]
If set, the reading "notify_processing_time" shows the required processing time (in seconds) for the
processing of the DbLog notify function.
The attribute is suitable for performance analyses and also helps to determine the differences
in the time required for event processing in synchronous or asynchronous mode.
(default: 0)
Hinweis:
The reading "notify_processing_time" generates a lot of events and burdens the system. Therefore, when using the
the event generation should be limited by setting the attribute "event-min-interval" to e.g.
"notify_processing_time:30".
syncInterval <n>
If the asynchronous mode is set in the DbLog device (asyncMode=1), this attribute sets the interval (seconds) for
writing data to the database.
(default: 30)
suppressAddLogV3 [1|0]
If set, verbose 3 Logfileentries done by the addLog-function will be suppressed.
suppressUndef
Suppresses all undef values when returning data from the DB via get.
timeout <n>
Sets the timeout value for the operations in the SubProcess in seconds.
If a started operation (logging, command) is not finished within the timeout value,
the running subprocess is terminated and a new process is started.
(default: 86400)
traceFlag <ALL|SQL|CON|ENC|DBD|TXN>
Trace flags are used to enable tracing of specific activities within the DBI and drivers. The attribute is only used for
tracing of errors in case of support.
ALL
turn on all DBI and driver flags
SQL
trace SQL statements executed (Default)
CON
trace connection process
ENC
trace encoding (unicode translations etc)
DBD
trace only DBD messages
TXN
trace transactions
traceLevel <0|1|2|3|4|5|6|7>
Switch on the tracing function of the module. Caution ! The attribute is only used for tracing errors or in case of support. If switched on very much entries
will be written into the FHEM Logfile !
0
Trace disabled. (Default)
1
Trace top-level DBI method calls returning with results or errors.
2
As above, adding tracing of top-level method entry with parameters.
3
As above, adding some high-level information from the driver
and some internal information from the DBI.
4
As above, adding more detailed information from the driver.
5-7
As above but with more and more internal information.
useCharfilter [0|1]
If set, only ASCII characters from 32 to 126 are accepted in event.
That are the characters " A-Za-z0-9!"#$%&'()*+,-.\/:;<=>?@[\\]^_`{|}~" .
Mutated vowel and "€" are transcribed (e.g. ä to ae). (default: 0).
valueFn {}
This attribute is set in the DbLog device and allows to modify the values before logging
or exclude the record from logging.
It is possible to access the variables $TIMESTAMP, $DEVICE (source device), $DEVICETYPE, $EVENT, $READING,
$VALUE (reading value) and $UNIT (unit of reading value) can be accessed and modified before logging to the database.
Read only access exists to $LASTTIMESTAMP, $LASTVALUE and $NAME (Name of the DbLog Device).
The variables $LASTTIMESTAMP and $LASTVALUE contain time and value of the last logged record of
$DEVICE / $READING.
If $TIMESTAMP is to be changed, the form "yyyy-mm-dd hh:mm:ss" must be followed.
Otherwise the changed $TIMESTAMP variable will not be applied.
By setting the variable "$IGNORE=1" the record is excluded from logging.
Examples
attr <device> valueFn {if ($DEVICE eq "living_Clima" && $VALUE eq "off" ){$VALUE=0;} elsif ($DEVICE eq "e-power"){$VALUE= sprintf "%.1f", $VALUE;}}
# change value "off" to "0" of device "living_Clima" and rounds value of e-power to 1f
attr <device> valueFn {if ($DEVICE eq "SMA_Energymeter" && $READING eq "state"){$IGNORE=1;}}
# don't log the dataset of device "SMA_Energymeter" if the reading is "state"
attr <device> valueFn {if ($DEVICE eq "Dum.Energy" && $READING eq "TotalConsumption"){$UNIT="W";}}
# set the unit of device "Dum.Energy" to "W" if reading is "TotalConsumption"
verbose4Devs <device1>,<device2>,<device..>
If verbose level 4/5 is used, only output of devices set in this attribute will be reported in FHEM central logfile.
If this attribute isn't set, output of all relevant devices will be reported if using verbose level 4/5.
The given devices are evaluated as Regex.
Example
attr <device> verbose4Devs sys.*,.*5000.*,Cam.*,global
# The devices starting with "sys", "Cam" respectively devices are containing "5000" in its name and the device "global" will be reported in FHEM
central Logfile if verbose=4 is set.
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 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.
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
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":
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:
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
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:
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)
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:
Summarized the relevant attributes to control this function are:
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").
# 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:
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".
# 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:
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>
Executes several set commands sequentially in a definable order.
The commands and certain modifiable attributes that are relevant for the commands are transferred in a
hash.
The commands to be executed (key cmd) and the attributes to be set for them are defined via keys in the
transferred hash. The order in which the commands are processed is determined via the command index in the
hash which must not be '0'.
Attribute keys that can be defined in the hash are:
Note: All of the above attributes are deleted before each command index is executed.
The attributes specified in the respective command index are set before the step is executed.
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.
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.
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.
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
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.
Executes any user-specific command.
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.
An SQL statement can be executed by specifying its list index:
set <name> sqlCmd ckey:<Index> (e.g. ckey:4)
The list index "ckey:latest" executes the last statement saved in the SQL history.
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)
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
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>
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.
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".
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).
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
Creation of the function results in time slices within the selection period.
no
- No aggregation (default)
minute
- the function results are summarized per minute
hour
- the function results are summarized per hour
day
- the function results are summarized per calendar day
week
- the function results are summarized per calendar week
month
- the function results are summarized per calendar month
year
- the functional results are summarized per calendar year
autoForward
If activated, the result threads of a function are transferred to one or more devices.
The definition takes the form:
Wildcards (.*) are permitted in the specification <source-reading>.
Example:
{
".*" => "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.
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-specific comment which is entered in the header of the file generated by "dumpMyQL clientSide".
dumpCompress
If set, the file created by "dumpMySQL" or "dumpSQLite" is then compressed and the uncompressed source file is deleted.
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/")
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.
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.
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)
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.
The part between the first and last double underscore ('__') of the created reading name is replaced with 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.
The readings can be specified as a regular expression.
(default: state)
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).
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.
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 <Month>-<Day> <Month>-<Day>
An annual period is determined for the database selection.
The annual period is calculated dynamically at execution time.
It is not possible to provide information during the year.
This attribute is primarily intended to create evaluations synchronized with a billing period, e.g. that of an energy or
gas supplier.
Example:
attr <name> timeYearPeriod 06-25 06-24
Evaluates the database in the time limits June 25 AAAA to June 24 BBBB.
The year AAAA or BBBB is calculated depending on the current date.
If the current date is >= June 25 and <= December 31, then AAAA = current year and BBBB = current year+1
If the current date is >= January 01 and <= June 24, then 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:
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:
# 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:
# 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:
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.
DoorBird
The DoorBird module establishes the communication between the DoorBird - door intercommunication unit and the fhem home automation based on the official API, published by the manufacturer.
Please make sure, that the user has been enabled the API-Operator button in the DoorBird Android/iPhone APP under "Administration -> User -> Edit -> Permission -> API-Operator".
The following packet - installations are pre-requisite if not already installed by other modules (Examples below tested on Raspbian):
<name> : The name of the device. Recommendation: "myDoorBird".
<IPv4-address> : A valid IPv4 address of the KMxxx. You might look into your router which DHCP address has been given to the DoorBird unit.
<Username> : The username which is required to sign on the DoorBird.
<Password> : The password which is required to sign on the DoorBird.
Set
The set function is able to change or activate the following features as follows:
set Light_On : Activates the IR lights of the DoorBird unit. The IR - light deactivates automatically by the default time within the Doorbird unit
set Live_Audio <on:off> : Activate/Deactivate the Live Audio Stream of the DoorBird on or off and toggles the direct link in the hidden Reading .AudioURL
set Live_Video <on:off> : Activate/Deactivate the Live Video Stream of the DoorBird on or off and toggles the direct link in the hidden Reading .VideoURL
set Open_Door <Value> : Activates the Relay of the DoorBird unit with the given address. The list of installed relay addresses are imported with the initialization of parameters.
set OpsMode<Value>DoorbellAudio : A selection of the audio files stored in the directory which is defined in the attribute "AudioFileDir". This file will be converted and send to the DoorBird to be played in case of doorbell activation.
set OpsMode<Value>DoorbellRelay : A selection of the installed relays which shall be activated in case of doorbell activation.
set OpsMode<Value>MotionAudio : A selection of the audio files stored in the directory which is defined in the attribute "AudioFileDir". This file will be converted and send to the DoorBird to be played in case of motion sensor triggering.
set OpsMode<Value>MotionRelay : A selection of the installed relays which shall be activated in case of motion sensor triggering.
set Receive_Audio <Path> : Receives an audio file and saves it. Requires a datapath to audio file to be saved. The user "fhem" needs to have write access to this directory.
set Restart : Sends the command to restart (reboot) the Doorbird unit
set Transmit_Audio <Path> : Converts a given audio file and transmits the stream to the DoorBird speaker. Requires a datapath to audio file to be converted and send. The user "fhem" needs to have write access to this directory.
Get
The get function is able to obtain the following information from the DoorBird unit:
get History_Request : Downloads the pictures of the last events of the doorbell and motion sensor. (Refer to attribute MaxHistory)
get Image_Request : Downloads the current Image of the camera of DoorBird unit.
get Video_Request <Value> : Downloads the current Video of the camera of DoorBird unit for the time in seconds given.
get Info_Request : Downloads the current internal setup such as relay configuration, firmware version etc. of the DoorBird unit. The obtained relay adresses will be used as options for the Open_Door command.
Attributes
The following user attributes can be used with the DoorBird module in addition to the global ones e.g. room.
disable : Stops the device from further reacting on UDP datagrams sent by the DoorBird unit. The default value is 0 = activated
KeepAliveTimeout : Timeout in seconds without still-alive UDP datagrams before state of device will be set to "disconnected". The default value is 30s
MaxHistory : Number of pictures to be downloaded from history for both - doorbell and motion sensor events. The default value is "50" which is the maximum possible.
PollingTimeout : Timeout in seconds before download requests are terminated in cause of no reaction by DoorBird unit. Might be required to be adjusted due to network speed. The default value is 10s.
UdpPort : Port number to be used to receice UDP datagrams. Ports are pre-defined by firmware. The default value is port 6524
SessionIdSec : Time in seconds for how long the session Id shall be valid, which is required for secure Video and Audio transmission. The DoorBird kills the session Id after 10min = 600s automatically. In case of use with CCTV recording units, this function must be disabled by setting to 0. The default value is 540s = 9min.
AudioFileDir : The relative (e.g. "audio") or absolute (e.g. "/mnt/NAS/audio") with or without trailing "/" directory path to which the audio files supposed to be stored. The default value is "" = disabled
AudioFileDirmaxSize : The maximum size of the AudioFileDir in Megabyte [MB]. If the maximum Size has been reached with audio files, the oldest files are deleted automatically The default value is 50 = 50MB
ImageFileDir : The relative (e.g. "images") or absolute (e.g. "/mnt/NAS/images") with or without trailing "/" directory path to which the image files supposed to be stored. The default value is "" = disabled
ImageFileDirmaxSize : The maximum size of the ImageFileDir in Megabyte [MB]. If the maximum Size has been reached with Image files, the oldest files are deleted automatically The default value is 50 = 50MB
VideoFileDir : The relative (e.g. "images") or absolute (e.g. "/mnt/NAS/images") with or without trailing "/" directory path to which the video files supposed to be stored. The default value is "" = disabled
VideoFileDirmaxSize : The maximum size of the VideoFileDir in Megabyte [MB]. If the maximum Size has been reached with Video files, the oldest files are deleted automatically The default value is 50 = 50MB
VideoFileFormat : The file format for the video file to be stored The default value is "mpeg"
VideoDurationDoorbell : Time in seconds for how long the video shall be recorded in case of an doorbbell event. The default value is 0 = disabled
VideoDurationMotion : Time in seconds for how long the video shall be recorded in case of an motion sensor event. The default value is 0 = disabled
EventReset : Time in seconds after wich the Readings for the Events Events (e.g. "doorbell_button", "motions sensor", "keypad") shal be reset to "idle". The default value is 5s
WaitForHistory : Time in seconds after wich the module shall wait for an history image triggered by an event is ready for download. Might be adjusted if fhem-Server and Doorbird unit have large differences in system time. The default value is 7s
OpsModeList : A space separated list of names for operational modes (e.g. "Normal Party Fire") on which the DoorBird reacts automatically on events. The default value is "" = disabled
HistoryFilePath : Creates relative datapaths to the last pictures, and videos in order to indicate them directly (e.g. fhem ftui widget "image") The default value is "0" = disabled
The Dooya protocol is used by a wide range of devices,
which are either senders or receivers/actuators.
The RECIVING and SENDING of Dooya commands is implemented in the SIGNALduino, so this module currently supports
devices like blinds and shutters. The Dooya protocol is used from a lot of different shutter companies in Germanyr. Examples are Rohrmotor24 or Nobily.
4: sduino/msg READ: MU;P0=4717;P1=-1577;P2=284;P3=-786;P4=649;P5=-423;D=01232345[......]445232;CP=2;4: sduino: Fingerprint for MU Protocol id 16 -> Dooya shutter matches, trying to demodulate4: sduino: decoded matched MU Protocol id 16 dmsg u16#370658E133 length 404: SIGNALduino_unknown Protocol: 164: SIGNALduino_unknown converted to bits: 00110111000001100101100011100001001100114: SIGNALduino_unknown / shutter Dooya 0011011100000110010110001110000100110011 received4: 00110111000001100101100 1110 0001 0011 00114: SIGNALduino_unknown found shutter from Dooya. id=3606104, remotetype=14, channel=1, direction=down, all_shutters=false
The id is a 28-digit binar code, that uniquely identifies a single remote control.
Pairing is done by setting the shutter in programming mode, either by disconnecting/reconnecting the power,
and by pressing the program button on an already associated remote.
Once the shutter is in programming mode, send the "prog" command from within FHEM to complete the pairing.
The shutter will peep shortly to indicate completion.
You are now able to control this blind from FHEM, the receiver thinks it is just another remote control or the real exist remote.
For the shutter it´s the same.
<id> is a 28 digit binar number that uniquely identifies FHEM as a new remote control.
You can use a different one for each device definition, and group them using a structure. You can use the same ID for a couple of shutters
and you can give every one an other channel. (0 to 15, 0 ist the MASTER and conrols all other channels.)
If you set one of them, you need to pick the same address as an existing remote. You can create the Device with autocreate with a real remote or manuel without remote control.
Examples:
define Rollo_Master Dooya 0011011100000110010110001110_0 Rollo_Master channel 0 controls all shutters (channel 1 - 15) with the same ID, in this case Rollo_1 and Rollo_2
on
off
stop
pos value (0..100) # see note
prog # Special, see note
Examples:
set rollo_1 on set rollo_1 on,sleep 1,rollo_2 on,sleep 1,rollo_3 on set rollo_1 off set rollo_1 pos 50
Notes:
prog is a special command used to pair the receiver to FHEM:
Set the receiver in programming mode and send the "prog" command from FHEM to finish pairing.
The shutter will peep shortly to indicate success.
pos value
The position is variying between 0 completely open and 100 for covering the full window.
The position must be between 0 and 100 and the appropriate
attributes drive-down-time-to-100, drive-down-time-to-close,
drive-up-time-to-100 and drive-up-time-to-open must be set.
The position reading distinuishes between multiple cases
Without timing values set only generic values are used for status and position:
open, closed, moving
are used
With timing values set but drive-down-time-to-close equal to drive-down-time-to-100 and drive-up-time-to-100 equal 0
the device is considered to only vary between 0 and 100 (100 being completely closed)
With full timing values set the device is considerd a window shutter (Rolladen) with a difference between
covering the full window (position 100) and being completely closed (position 200)
Get
N/A
Attributes
IODev
Set the IO or physical device which should be used for sending signals
for this "logical" device. It must be the SIGNALduino.
Note: The IODev has to be set, otherwise no commands will be sent!
channel
Set the channel of the remote. You can use 0 (MASTER) to 15.
Note: The MASTER conrols all remotes with the same ID!!!
SignalRepeats
Set the repeats for sending signal. You can use 5, 10, 15 and 20.
additionalPosReading
Position of the shutter will be stored in the reading pos as numeric value.
Additionally this attribute might specify a name for an additional reading to be updated with the same value than the pos.
eventMap
Replace event names and set arguments. The value of this attribute
consists of a list of space separated values, each value is a colon
separated pair. The first part specifies the "old" value, the second
the new/desired value. If the first character is slash(/) or comma(,)
then split not by space but by this character, enabling to embed spaces.
Examples:
attr store eventMap on:open off:closed
attr store eventMap /on-for-timer 10:open/off:closed/
set store open
dummy
Set the device attribute dummy to define devices which should not
output any radio signals. Associated notifys will be executed if
the signal is received. Used e.g. to react to a code from a sender, but
it will not emit radio signal if triggered in the web frontend.
ignore
Ignore this device, e.g. if it belongs to your neighbour. The device
won't trigger any FileLogs/notifys, issued commands will silently
ignored (no RF signal will be sent out, just like for the dummy attribute). The device won't appear in the
list command (only if it is explicitely asked for it), nor will it
appear in commands which use some wildcard/attribute as name specifiers
(see devspec). You still get them with the
"ignored=1" special devspec.
drive-down-time-to-100
The time the blind needs to drive down from "open" (pos 0) to pos 100.
In this position, the lower edge touches the window frame, but it is not completely shut.
For a mid-size window this time is about 12 to 15 seconds.
drive-down-time-to-close
The time the blind needs to drive down from "open" (pos 0) to "close", the end position of the blind.
This is about 3 to 5 seonds more than the "drive-down-time-to-100" value.
drive-up-time-to-100
The time the blind needs to drive up from "close" (endposition) to "pos 100".
This usually takes about 3 to 5 seconds.
drive-up-time-to-open
The time the blind needs drive up from "close" (endposition) to "open" (upper endposition).
This value is usually a bit higher than "drive-down-time-to-close", due to the blind's weight.
Generated events:
From a Dooya device you can receive one of the following events.
on
off
stop
Which event is sent is device dependent and can sometimes be configured on
the device.
Any physical device with request/response-like communication capabilities
over a serial line or TCP connection can be defined as ECMD device. A practical example
of such a device is the AVR microcontroller board AVR-NET-IO from
Pollin with
ECMD-enabled
Ethersex firmware. The original
NetServer firmware from Pollin works as well. There is a plenitude of use cases.
A physical ECMD device can host any number of logical ECMD devices. Logical
devices are defined as ECMDDevices in fhem.
ADC 0 to 3 and I/O port 0 to 3 of the above mentioned board
are examples of such logical devices. ADC 0 to 3 all belong to the same
device class ADC (analog/digital converter). I/O port 0 to 3 belong to the device
class I/O port. By means of extension boards you can make your physical
device drive as many logical devices as you can imagine, e.g. IR receivers,
LC displays, RF receivers/transmitters, 1-wire devices, etc.
Defining one fhem module for any device class would create an unmanageable
number of modules. Thus, an abstraction layer is used. You create a device class
on the fly and assign it to a logical ECMD device. The
class definition
names the parameters of the logical device, e.g. a placeholder for the number
of the ADC or port, as well as the get and set capabilities. Worked examples
are to be found in the documentation of the ECMDDevice device.
Note: this module requires the Device::SerialPort or Win32::SerialPort module
if the module is connected via serial Port or USB.
Character coding
ECMD is suited to process any character including non-printable and control characters.
User input for raw data, e.g. for setting attributes, and the display of raw data, e.g. in the log,
is perl-encoded according to the following table (ooo stands for a three-digit octal number):
character
octal
code
Bell
007
\a
Backspace
008
\008
Escape
033
\e
Formfeed
014
\f
Newline
012
\n
Return
015
\r
Tab
011
\t
backslash
134
\134 or \\
any
ooo
\ooo
In user input, use \134 for backslash to avoid conflicts with the way FHEM handles continuation lines.
Define
define <name> ECMD telnet <IPAddress:Port>
or
define <name> ECMD serial <SerialDevice>[<@BaudRate>]
Defines a physical ECMD device. The keywords telnet or
serial are fixed.
Examples:
define AVRNETIO ECMD telnet 192.168.0.91:2701 define AVRNETIO ECMD serial /dev/ttyS0 define AVRNETIO ECMD serial /dev/ttyUSB0@38400
Set
set <name> classdef <classname> <filename>
Creates a new device class <classname> for logical devices.
The class definition is in the file <filename>. You must
create the device class before you create a logical device that adheres to
that definition.
Example:
set AVRNETIO classdef /etc/fhem/ADC.classdef
set <name> reopen
Closes and reopens the device. Could be handy if connection is lost and cannot be
reestablished automatically.
Get
get <name> raw <command>
Sends the command <command> to the physical ECMD device
<name> and reads the response. In the likely case that
the command needs to be terminated by a newline character, you have to
resort to a <perl special>.
Example:
get AVRNETIO raw { "ip\n" }
Attributes
classdefs A colon-separated list of <classname>=<filename>.
The list is automatically updated if a class definition is added. You can
directly set the attribute. Example: attr myECMD classdefs ADC=/etc/fhem/ADC.classdef:GPIO=/etc/fhem/AllInOne.classdef
split <separator>
Some devices send several readings in one transmission. The split attribute defines the
separator to split such transmissions into separate messages. The regular expression for
matching a reading is then applied to each message in turn. After splitting, the separator
is still part of the single messages. Separator can be a single- or multi-character string,
e.g. \n or \r\n.
Example: attr myECMD split \n splits foo 12\nbar off\n into
foo 12\n and bar off\n.
logTraffic <loglevel> Enables logging of sent and received datagrams with the given loglevel. Control characters in the logged datagrams are escaped, i.e. a double backslash is shown for a single backslash, \n is shown for a line feed character, etc.
timeout <seconds> Time in seconds to wait for a response from the physical ECMD device before FHEM assumes that something has gone wrong. The default is 3 seconds if this attribute is not set.
partial <seconds> Some physical ECMD devices split responses into several transmissions. If the partial attribute is set, this behavior is accounted for as follows: (a) If a response is expected for a get or set command, FHEM collects transmissions from the physical ECMD device until either the response matches the expected response (reading ... match ... in the class definition) or the time in seconds given with the partial attribute has expired. (b) If a spontaneous transmission does not match the regular expression for any reading, the transmission is recorded and prepended to the next transmission. If the line is quiet for longer than the time in seconds given with the partial attribute, the recorded transmission is discarded. Use regular expressions that produce exact matches of the complete response (after combining partials and splitting).
requestSeparator <separator>
A single command from FHEM to the device might need to be broken down into several requests.
A command string is split at all
occurrences of the request separator. The request separator itself is removed from the command string and thus is
not part of the request. The default is to have no request separator. Use a request separator that does not occur in the actual request.
responseSeparator <separator>
In order to identify the single responses from the device for each part of the command broken down by request separators, a response separator can be appended to the response to each single request.
The response separator is only appended to commands split by means of a
request separator. The default is to have no response separator, i.e. responses are simply concatenated. Use a response separator that does not occur in the actual response.
autoReopen <timeout>,<delay>
If this attribute is set, the device is automatically reopened if no bytes were written for <timeout> seconds or more. After reopening
FHEM waits <delay> seconds before writing to the device. Use the delay with care because it stalls FHEM completely.
stop
Disables read/write access to the device if set to 1. No data is written to the physical ECMD device. A read request always returns an undefined result.
This attribute can be used to temporarily disable a device that is not available.
Set the partial attribute in combination with reading ... match ... in the class definition, if you receive datagrams with responses which are broken into several transmissions, like resp followed by onse\r\n.
Set the split attribute if you
receive several responses in one transmission, like reply1\r\nreply2\r\n.
When to use the requestSeparator and responseSeparator attributes?
Set the requestSeparator attribute, if you want to send several requests in one command, with one transmission per request. The strings sent to the device for set and get commands
as defined in the class definition are broken down into several request/response
interactions with the physical device. The request separator is not sent to the physical device.
Set the responseSeparator attribute to separate the responses received for a command
broken down into several requests by means of a request separator. This is useful for easier postprocessing.
Example: you want to send the requests request1 and request2 in one command. The
physical device would respond with response1 and response2 respectively for each
of the requests. You set the request separator to \000 and the response separator to \001 and you define
the command as request1\000request2\000. The command is broken down into request1
and request2. request1 is sent to the physical device and response1
is received, followed by sending request2 and receiving response2. The final
result is response1\001response2\001.
You can think of this feature as of a macro. Splitting and partial matching is still done per single
request/response within the macro.
Datagram monitoring and matching
Data to and from the physical device is processed as is. In particular, if you need to send a line feed you have to explicitely send a \n control character. On the other hand, control characters like line feeds are not stripped from the data received. This needs to be considered when defining a class definition.
For debugging purposes, especially when designing a class definition, it is advisable to turn traffic logging on. Use attr myECMD logTraffic 3 to log all data to and from the physical device at level 3.
Datagrams and attribute values are logged with non-printable and control characters encoded as here followed by the octal representation in parantheses.
Example: #!foo\r\n (\043\041\146\157\157\015\012).
Data received from the physical device is processed as it comes in chunks. If for some reason a datagram from the device is split in transit, pattern matching and processing will most likely fail. You can use the partial attribute to make FHEM collect and recombine the chunks.
Connection error handling
This modules handles unexpected disconnects of devices as follows (on Windows only for TCP connections):
Disconnects are detected if and only if data from the device in reply to data sent to the device cannot be received with at most two attempts. FHEM waits at most 3 seconds (or the time specified in the timeout attribute, see Attributes). After the first failed attempt, the connection to the device is closed and reopened again. The state of the device
is failed. Then the data is sent again to the device. If still no reply is received, the state of the device is disconnected, otherwise opened. You will have to fix the problem and then use set myECMD reopen to reconnect to the device.
Please design your class definitions in such a way that the double sending of data does not bite you in any case.
Class definition
The class definition for a logical ECMD device class is contained in a text file.
The text file is made up of single lines. Empty lines and text beginning with #
(hash) are ignored. Therefore make sure not to use hashes in commands.
The following commands are recognized in the device class definition:
Normally, the state reading is set to the latest command or reading name followed
by the value, if any. This command sets the state reading to the value of the
named reading if and only if the reading is updated.
Declares a new set or get command <commandname>. If the user invokes the set or get command <commandname>, the string that results from the execution of the <perl special> is sent to the physical device.
A request separator (see Attributes)
can be used to split the command into chunks. This is required for sending multiple Ethersex commands for one command in the class definition.
The result string for the command is the
concatenation of all responses received from the physical device, optionally with response separators
(see Attributes) in between.
set <commandname> expect "<regex>" get <commandname> expect "<regex>"
Declares what FHEM expects to receive after the execution of the get or set command <commandname>. <regex> is a Perl regular expression. The double quotes around the regular expression are mandatory and they are not part of the regular expression itself.
<regex> must match the entire reply, as in m/^<regex>$/.
Particularly, broken connections can only be detected if something is expected (see Connection error handling).
Declares a postprocessor for the command <commandname>. The data received from the physical device in reply to the get or set command <commandname> is processed by the Perl code <perl command>. The perl code operates on $_. Make sure to return the result in $_ as well. The result of the perl command is shown as the result of the get or set command.
set <commandname> params <parameter1> [<parameter2> [<parameter3> ... ]] get <commandname> params <parameter1> [<parameter2> [<parameter3> ... ]]
Declares the names of the named parameters that must be present in the
set or get command <commandname>. Be careful not to use a parameter name that
is already used in the device definition (see params above).
reading <reading> match "<regex>"
Declares a new reading named <reading>. A spontaneous data transmission from the physical device that matches the Perl regular expression <regex> is evaluated to become the value of the named reading. All ECMDDevice devices belonging to the ECMD device with readings with matching regular expressions will receive an update of the said readings.
<regex> must match the entire reply, as in m/^<regex>$/.
Declares a postprocessor for the reading <reading>. The data received for the named reading is processed by the Perl code <perl command>. This works analogously to the postproc spec for set and get commands.
The perl specials in the definitions above can
contain macros:
The macro %NAME will expand to the device name.
The macro %TYPE will expand to the device type.
The macro %<parameter> will expand to the
current value of the named parameter. This can be either a parameter
from the device definition or a parameter from the set or get
command.
The macro substitution occurs before perl evaluates the
expression. It is a plain text substitution. Be careful not to use parameters with overlapping names like
%pin and %pin1.
If in doubt what happens, run the commands with loglevel 5 and
inspect the log file.
The rules outlined in the documentation of perl specials
for the <perl command> in the postprocessor definitions apply.
Note: Beware of undesired side effects from e.g. doubling of semicolons!
Defines a logical ECMD device. The number of given parameters must match those given in
the class definition of the device class <classname>.
Normally, the logical ECMDDevice is attached to the latest previously defined physical ECMD device
for I/O. Use the IODev attribute of the logical ECMDDevice to attach to any
physical ECMD device, e.g. attr myRelais2 IODev myAVRNETIO. In such a case the correct
reference to the class cannot be made at the time of definition of the device. Thus, you need to
omit the <classname> and <parameter> references in the definition of the device and use the
classattribute instead.
set <name> <commandname> [<parameter1> [<parameter2> [<parameter3> ... ]]]
The number of given parameters must match those given for the set command <commandname> definition in
the class definition.
If set <commandname> is invoked the perl special in curly brackets from the command definition
is evaluated and the result is sent to the physical ECMD device.
Example:
set myRelais1 on set myDisplay text This\x20text\x20has\x20blanks!
Get
get <name> <commandname> [<parameter1> [<parameter2> [<parameter3> ... ]]]
The number of given parameters must match those given for the get command <commandname> definition in
the class definition.
If get <commandname> is invoked the perl special in curly brackets from the command definition
is evaluated and the result is sent to the physical ECMD device. The response from the physical ECMD device is returned
and the state of the logical ECMD device is updated accordingly.
Example:
get myADC value 3
Attributes
class
If you omit the <classname> and <parameter> references in the
definition of the device, you have to add them
separately as an attribute. Example: attr myRelais2 class relais 8.
noState
Changes of readings do not change the state reading if this attribute is set to a non-zero value.
For example, this is desirable if you need to avoid the second event created by changing the state
reading. Previously created state readings can be deleted by means of deletereading.
The user can define the value shown in the state of the device by means
of the stateFormat attribute.
The following example shows how to access the ADC of the AVR-NET-IO board from
Pollin with
ECMD-enabled
Ethersex firmware.
The class definition file /etc/fhem/ADC.classdef looks as follows:
get value cmd {"adc get %channel\n"}
get value params channel
get value expect "\d+\n"
get value postproc { s/^(\d+)\n$/$1/;; $_ }
In the fhem configuration file or on the fhem command line we do the following:
define AVRNETIO ECMD telnet 192.168.0.91:2701 # define the physical device
attr AVRNETIO classdefs ADC=/etc/fhem/ADC.classdef # define the device class ADC
define myADC ECDMDevice ADC # define the logical device myADC with device class ADC
get myADC value 1 # retrieve the value of analog/digital converter number 1
The get command is evaluated as follows: get value has one named parameter
channel. In the example the literal 1 is given and thus %channel
is replaced by 1 to yield "adc get 1\n" after macro substitution. Perl
evaluates this to a literal string which is send as a plain ethersex command to the AVR-NET-IO. The
board returns something like 024\n for the current value of analog/digital converter number 1. The postprocessor keeps only the digits.
Example 2
The following example shows how to switch a relais driven by pin 3 (bit mask 0x08) of I/O port 2 on for
one second and then off again.
The class definition file /etc/fhem/relais.classdef looks as follows:
params pinmask
set on cmd {"io set ddr 2 ff\n\000ioset port 2 0%pinmask\n\000wait 1000\n\000io set port 2 00\n"}
set on expect ".*"
set on postproc {s/^OK\nOK\nOK\nOK\n$/success/; "$_" eq "success" ? "ok" : "error"; }
In the fhem configuration file or on the fhem command line we do the following:
define AVRNETIO ECMD telnet 192.168.0.91:2701 # define the physical device
attr AVRNETIO classdefs relais=/etc/fhem/relais.classdef # define the device class relais
attr AVRNETIO requestSeparator \000
define myRelais ECMDDevice 8 # define the logical device myRelais with pin mask 8
set myRelais on # execute the "on" command
The set command is evaluated as follows: %pinmask
is replaced by 8 to yield
"io set ddr 2 ff\n\000io set port 2 08\n\000wait 1000\n\000io set port 2 00\n\000" after macro substitution. Perl
evaluates this to a literal string. This string is split into lines (with trailing newline characters)
io set ddr 2 ff\n
ioset port 2 08\n
wait 1000\n
io set port 2 00\n
These lines are sent as a plain ethersex commands to the AVR-NET-IO one by one. After
each line the answer from the physical device is read back. They are concatenated and returned
for further processing by the postproc command.
For any of the four plain ethersex commands, the AVR-NET-IO returns the string OK\n. They are
concatenated. The postprocessor takes the result from $_,
substitutes it by the string success if it is OK\nOK\nOK\nOK\n, and then either
returns the string ok or the string error. If the responseSeparator was set to \000,
the result string would be OK\n\000OK\n\000OK\n\000OK\n\000 instead of OK\nOK\nOK\nOK\n.
Example 3
The following example shows how to implement a sandbox.
The class definition file /etc/fhem/DummyServer.classdef looks as follows:
In the fhem configuration file or on the fhem command line we do the following:
define myDummyServer ECMD telnet localhost:9999 # define the physical device
set myDummyServer classdef DummyServer /etc/fhem/DummyServer.classdef # define the device class DummyServer
define myDummyClient ECDMDevice DummyServer # define a logical device with device class DummyServer
On a Unix command line, run netcat -l 9999. This makes netcat listening on port 9999. Data received on that port are printed on stdout. Data input from stdin is sent to the other end of an incoming connection.
Start FHEM.
Then enter the number 4711 at the stdin of the running netcat server.
FHEM sees 4711\n coming in from the netcat dummy server. The incoming string matches the regular expression of the foo reading. The postprocessor is used to strip any trailing garbage from the digits. The result 4711 is used to update the foo reading.
Defines a Socket from EGPM2LAN Module. If the global Module AUTOCREATE is enabled,
this device will be created automatically. For manual Setup, pls. see the description of EGPM2LAN.
Define
define <name> EGPM <device> <socket-nr>
Set
set <name> <[on|off|toggle]>
Switches the socket on or of.
set <name> <[on-for-timer|off-for-timer|on-till|off-till|blink|intervals]>
Switches the socket for a specified time+duration or n-times. For Details see set extensions
Creates a Gembird ® Energenie EG-PM2-LAN device to switch up to 4 sockets over the network.
If you have more than one device, it is helpful to connect and set names for your sockets over the web-interface first.
The name settings will be adopted to FHEM and helps you to identify the sockets. Please make sure that you´re logged off from the Energenie web-interface otherwise you can´t control it with FHEM at the same time.
Create a EGPM-Module to control a single socket with additional features. EG-PMS2-LAN with surge protector feature was not tested until now.
Set
set <name> password [<one-word>]
Encrypt and store device-password in FHEM. Leave empty to remove the password.
Before 04/2017, the password was stored in clear-text using the DEFINE-Command, but it should not be stored in the config-file.
set <name> <[on|off|toggle]> <socketnr.>
Switch the socket on or off.
set <name> <[on|off]> <all>
Switch all available sockets on or off.
set <name> <staterequest>
Update the device information and the state of all sockets.
If autocreate is enabled, an EGPM device will be created for each socket.
set <name> <clearreadings>
Removes all readings from the list to get rid of old socketnames.
Get
get <name> state
Returns a text like this: "1: off 2: on 3: off 4: off" or the last error-message if something went wrong.
Attributes
stateDisplay
Default: socketNumer changes between socketNumer and socketName in front of the current state. Call set statusrequest to update all states.
autocreate
Default: onEGPM-devices will be created automatically with a set-command.
Change this attribute to value off to avoid that mechanism.
Define a EM1010PC USB device. As the EM1010PC was not designed to be used
with a PC attached to it all the time, it won't transmit received signals
automatically, fhem has to poll it every 5 minutes.
Currently there is no way to read the internal log of the EM1010PC with
fhem, use the program em1010.pl in the contrib directory for this
purpose.
Examples:
define em EM /dev/elv_em1010pc
Set
set EM <value>
where value is either time or reset.
If time has arguments of the form YYYY-MM-DD HH:MM:SS, then the specified
time will be set, else the time from the host.
Note: after reset you should set the time.
Define up to 4 EM1000EM attached to the EM1010PC. The device number must
be between 5 and 8.
Defining an EMEM will schedule an internal task, which reads the
status of the device every 5 minutes, and triggers notify/filelog commands.
Note: Currently this device does not support a "set" function.
Example:
define emem EMEM 5
Set
N/A
Get
get EMEM status
This is the same command which is scheduled every 5 minutes internally.
Define up to 4 EM1000GZ attached to the EM1010PC. The device number must
be between 9 and 12.
Defining an EMGZ will schedule an internal task, which reads the
status of the device every 5 minutes, and triggers notify/filelog commands.
Example:
define emgz EMGZ 9
Set
set EMGZdevice <param> <value>
where param is:
price
The price of one KW in EURO (use e.g. 0.20 for 20 Cents). It is used
only on the EM1010PC display, it is of no interest for FHEM.
Get
get EMGZ status
This is the same command which is scheduled every 5 minutes internally.
The EMT7110 is a plug with integrated power meter functionality.
It can be integrated into FHEM via a JeeLink as the IODevice.
The EMT7110 sends with 9.579 kbit/s. Therefore it is necessary to set the JeeLink to a mode where it recieves this data rate.
This can be done using the initCommands attribute of the JeeLink.
If you have only 9.579 kbit/s sensors use this setting: attr myJeeLink initCommands 1r v
If you have also 17.241 kbit/s sensors (like TX29...) use this setting: attr myJeeLink initCommands 30t v
30t means that the JeeLink toggles the data rate every 30 Seconds.
Definedefine <name> EMT7110 <addr>
addr is a 4 digit hex number to identify the EMT7110 device.
To enable autocreate for a certain time you must set LaCrossePairForSec in the JeeLink IODevice device.
Set
resetAccumulatedPower
Sets the accumulatedPowerOffset attribute to the current value of accumulatedPowerMeasured.
Don't forget to call save to write the new value to fhem.cfg
Get
Readings
accumulatedPowerMeasured
The accumulated power sent by the EMT7110. The EMT7110 accumulates the power even if it was removed and reconnected to the power outlet.
The only way to reset it is to remove and reinsert the batteries in the EMT7110.
accumulatedPower
Is accumulatedPowerMeasured minus the value of the accumulatedPowerOffset attribute value
This reading is used for the A: part of state
costs
Is accumulatedPower * pricePerKWH attribute value
current
The measured current in mA
power
The measured power in Watt
voltage
The measured voltage in Volt
Attributes
accumulatedPowerOffset
See accumulatedPower reading
Define up to 4 EM1000WZ attached to the EM1010PC. The device number must
be between 1 and 4. Defining an EMWZ will schedule an internal task, which
reads the status of the device every 5 minutes, and triggers notify/filelog
commands.
Example:
define emwz EMWZ 1
Set
set EMWZdevice <param> <value>
where param is one of:
rperkw
Number of rotations for a KiloWatt of the EM1000WZ device (actually
of the device where the EM1000WZ is attached to). Without setting
this correctly, all other readings will be incorrect.
alarm
Alarm in WATT. if you forget to set it, the default value is
rediculously low (random), and if a value above this threshold is
received, the EM1010PC will start beeping once every minute. It can
be very annoying.
price
The price of one KW in EURO (use e.g. 0.20 for 20 Cents). It is used
only on the EM1010PC display, it is of no interest for FHEM.
Get
get EMWZ status
This is the same command which is scheduled every 5 minutes internally.
This module controls ENIGMA2 based devices like Dreambox or VUplus receiver via network connection.
Defining an ENIGMA2 device will schedule an internal task (interval can be set with optional parameter <poll-interval> in seconds, if not set, the value is 45 seconds), which periodically reads the status of the device and triggers notify/filelog commands.
Example:
define SATReceiver ENIGMA2 192.168.0.10
# With custom port
define SATReceiver ENIGMA2 192.168.0.10 8080
# With custom interval of 20 seconds
define SATReceiver ENIGMA2 192.168.0.10 80 20
# With HTTP user credentials
define SATReceiver ENIGMA2 192.168.0.10 80 20 root secret
Set
set <name> <command> [<parameter>]
Currently, the following commands are defined.
on - powers on the device and send a WoL magic package if needed
off - turns the device in standby mode
toggle - switch between on and off
shutdown - turns the device in deepstandby mode
reboot - reboots the device
restartGui - restarts the GUI / ENIGMA2 process
channel channel,0...999,sRef - zap to specific channel or service reference
channelUp - zap to next channel
channelDown - zap to previous channel
volume 0...100 - set the volume level in percentage
volumeUp - increases the volume level
volumeDown - decreases the volume level
mute on,off,toggle - controls volume mute
play - starts/resumes playback
pause - pauses current playback or enables timeshift
stop - stops current playback
record - starts recording of current channel
input tv,radio - switches between tv and radio mode
statusRequest - requests the current status of the device
remoteControl UP,DOWN,... - sends remote control commands; see 'remoteControl ?' for full command list
Note: You may add the word "long" after the command to simulate a long key press.
showText text - sends info message to screen to be displayed for 8 seconds
msg yesno,info... - allows more complex messages as showText, see commands as listed below
Note: If you would like to restrict access to admin set-commands (-> statusRequest, reboot, restartGui, shutdown) you may set your FHEMWEB instance's attribute allowedCommands like 'set,set-user'.
The string 'set-user' will ensure only non-admin set-commands can be executed when accessing FHEM using this FHEMWEB instance.
Messaging
showText has predefined settings. If you would like to send more individual messages to your TV screen, the function msg can be used. For this application the following commands are available:
Type Selection:
msg yesno
msg info
msg message
msg attention
The following parameter are essentially needed after type specification:
bouquet-tv - service reference address where the favorite television bouquet can be found (initially set automatically during define)
bouquet-radio - service reference address where the favorite radio bouquet can be found (initially set automatically during define)
disable - Disable polling (true/false)
http-method - HTTP access method to be used; e.g. a FritzBox might need to use POST instead of GET (GET/POST)
http-noshutdown - Set FHEM-internal HttpUtils connection close behaviour (defaults=1)
https - Access box via secure HTTP (true/false)
ignoreState - Do not check for available device before sending commands to it (true/false)
lightMode - reduces regular queries (resulting in less functionality), e.g. for low performance devices. (true/false)
macaddr - manually set specific MAC address for device; overwrites value from reading "lanmac". (true/false)
remotecontrol - Explicitly set specific remote control unit format. This will only be considered for set-command remoteControl as of now.
remotecontrolChannel - Switch between remote control commands used for set-commands channelUp and channelDown.
timeout - Set different polling timeout in seconds (default=6)
wakeupCmd - Set a command to be executed when turning on an absent device. Can be an FHEM command or Perl command in {}. Available variables: ENIGMA2 device name -> $DEVICE, ENIGMA2 device MAC address -> $MACADDR (default=Wake-on-LAN)
Generated Readings/Events:
acg - Shows Automatic Gain Control value in percent; reflects overall signal quality strength
apid - Shows the audio process ID for current channel
ber - Shows Bit Error Rate for current channel
channel - Shows the service name of current channel or media file name; part of FHEM-4-AV-Devices compatibility
currentMedia - The service reference ID of current channel; part of FHEM-4-AV-Devices compatibility
currentTitle - Shows the title of the running event; part of FHEM-4-AV-Devices compatibility
enigmaversion - Shows the installed version of ENIGMA2
eventcurrenttime - Shows the current time of running event as UNIX timestamp
eventcurrenttime_hr - Shows the current time of running event in human-readable format
eventcurrenttime_next - Shows the current time of next event as UNIX timestamp
eventcurrenttime_next_hr - Shows the current time of next event in human-readable format
eventdescription - Shows the description of running event
eventdescriptionextended - Shows the extended description of running event
eventdescriptionextended_next - Shows the extended description of next event
eventdescription_next - Shows the description of next event
evenduration - Shows the total duration time of running event in seconds
evenduration_hr - Shows the total duration time of running event in human-readable format
evenduration_next - Shows the total duration time of next event in seconds
evenduration_next_hr - Shows the total duration time of next event in human-readable format
eventname - Shows the name of running event
eventname_next - Shows the name of next event
eventremaining - Shows the remaining duration time of running event in seconds
eventremaining_hr - Shows the remaining duration time of running event in human-readable format
eventremaining_next - Shows the remaining duration time of next event in seconds
eventremaining_next_hr - Shows the remaining duration time of next event in human-readable format
eventstart - Shows the starting time of running event as UNIX timestamp
eventstart_hr - Shows the starting time of running event in human readable format
eventstart_next - Shows the starting time of next event as UNIX timestamp
eventstart_next_hr - Shows the starting time of next event in human readable format
eventtitle - Shows the title of the running event
eventtitle_next - Shows the title of the next event
fpversion - Shows the firmware version for the front processor
hddX_capacity - Shows the total capacity of the installed hard drive in GB
hddX_free - Shows the free capacity of the installed hard drive in GB
hddX_model - Shows hardware details for the installed hard drive
imageversion - Shows the version for the installed software image
input - Shows currently used input; part of FHEM-4-AV-Devices compatibility
iswidescreen - Indicates widescreen format - 0=off 1=on
lanmac - Shows the device MAC address
model - Shows details about the device hardware
mute - Reports the mute status of the device (can be "on" or "off")
nextTitle - Shows the title of the next event; part of FHEM-4-AV-Devices compatibility
onid - The ON ID
pcrpid - The PCR process ID
pmtpid - The PMT process ID
power - Reports the power status of the device (can be "on" or "off")
presence - Reports the presence status of the receiver (can be "absent" or "present"). In case of an absent device, control is basically limited to turn it on again. This will only work if the device supports Wake-On-LAN packages, otherwise command "on" will have no effect.
providername - Service provider of current channel
recordings - Number of active recordings
recordingsX_name - name of active recording no. X
recordingsX_servicename - servicename of active recording no. X
recordings_next - Shows the time of next recording as UNIX timestamp
recordings_next_hr - Shows the time of next recording as human-readable format
recordings_next_counter - Shows the time until next recording starts in seconds
recordings_next_counter_hr - Shows the time until next recording starts human-readable format
recordings_next_name - name of next recording
recordings_next_servicename - servicename of next recording
recordings_error - counter for failed recordings in timerlist
recordings_finished - counter for finished recordings in timerlist
servicename - Name for current channel
servicereference - The service reference ID of current channel
servicevideosize - Video resolution for current channel
sid - The S-ID
snr - Shows Signal to Noise for current channel in percent
snrdb - Shows Signal to Noise in dB
state - Reports current power state and an absence of the device (can be "on", "off" or "absent")
tsid - The TS ID
tuner_X - Details about the used tuner hardware
txtpid - The TXT process ID
videoheight - Height of the video resolution for current channel
videowidth - Width of the video resolution for current channel
volume - Reports current volume level of the receiver in percentage values (between 0 and 100 %)
vpid - The Video process ID
webifversion - Type and version of the used web interface
set <name> <command> [<parameter>]
The following commands are defined:
desiredTemperature [4.5...29.5] - set the temperature
boost on/off - activate boost command
mode manual/automatic - set manual/automatic mode
updateStatus - read current thermostat state and update readings
eco - set eco temperature
comfort - set comfort temperature
Get
n/a
attr
sshHost - FQD-Name or IP of ssh remote system / you must configure your ssh system for certificate authentication. For better handling you can config ssh Client with .ssh/config file
ESCVP21net implements Epson VP21 control via (W)LAN, uses VP.net.
Attention: To be able to switch the projector power on via (W)LAN, you have to enable wireless/LAN standby mode (or whatever it is called in your projector menu), so that the projector does NOT deactivate the (W)LAN in standby mode!
This module controls Epson Seiko Devices via TCP, using VP.net and ESC/VP21 commands.
For the time being, only Epson initilization is implemented (needs a special initialization string "ESC/VP.net").
IP_Address - the IP Address of the projector
port - ... guess? Yes, the port. If not given, Epson standard port 3629 is used.
model - defines your type of projector. It is used for loading a suitable pre-defined command set.
No parameter or default will provide you with a limit "set" (PWR, MUTE, LAMP, KEY, GetAll, GetStatus).
You can try TW5650 to get a typical set of implemented commands. Providing the maintainer with a suitable set for your projector will extend the module's capabilities ;-)
Individually supported by now: TW5650, EB2250U, TW6100, TW7400, TW9400, LS12000, HC2150
"Hidden Feature:" Type Scotty will give you everything (as he does always ;) ). Not every command will work for you. You are the Captain, so decide wisely what to choose...
a standard icon (it will use "it_camera", since I am not really a good designer)
webCmds for on, off, GetStatus, GetAll
cmdIcons for the webCmds
stateFormat as PWR
Set
Available set commands depend on your model, see above.
For the predefined commands, "nice" names will be shown in the readings, e.g. for PWR: Standby (Net on) instead of the boring PWR=04 (which is the device's answer if the projector is in Standby with LAN on).
Default set commands are
GetAll
This is a little bit special - it does not send just one command to the projector, but will select every command defined which has a get option, send it to the projector and update the corresponding reading. If a command gives no result or an error, this will be suppressed, the old value is silently kept.
The status of GetAll is shown in the GetAll reading. It will either show the read commands, or inform if an error was received.
GetStatus
Also special - also does not send just one command to the projector, but will select every command you defined in attr "statusCheckCmd" which has a get option, send it to the projector and update the corresponding reading. If a command gives no result or an error, this will be suppressed, the old value is silently kept.
The status of GetStatus is shown in the GetStatus reading. It will either show the read commands, or inform if an error was received.
LAMP
get to query lamp hours.
MUTE
on or off to mute video signal (i.e. blank screen), get to query current state.
KEY
sends the value you enter to the projector.
E.g.KEY 03 or KEY 3C should open the OSD menu, KEY 05 or or KEY 3D should close it.
Feel free to define your own KEY sets via the attribute "AdditionalSettings".
PWR
on or off to switch power, get to query current value.
(due to projector timeout on PWR, status reading update after issuing on/off will be delayed by ca 12s)
on
Hm, what could that mean ... OK, shortcut to switch your projector on - give it a try!
(due to projector timeout on PWR, status reading update will be delayed by ca 12s)
off
Wohoo ... want to switch it off again? Then use this command.
(due to projector timeout on PWR, status reading update will be delayed by ca 12s)
ASPECT
set/get aspect ratio. Values depend on your model.
AUTOHOME
set/get auto display of home screen.
AUTOKEYSTONE
set/get auto keystone correction.
BRIGHT
get brightness value.
BRIGHTset
Set brightness value.
BTAUDIO
set/get bluetooth audio (on/off).
CMODE
set/get color mode.
CONTRAST
get contrast enhancement value.
CONTRASTset
set contrast enhancement value.
DENSITY
get density value.
DENSITYset
set density value.
ERASEMEM
Erase picture setting memory slot (1...10), related to PUSHMEM, POPMEM.
GAMMA
set/get gamma value (-2...2)
HREVERSE
set/get horizontal reverse setting.
ILLUM
set/get illumination setting of on-device control lights.
IMGPROC
undocumented setting for image processing (fine/fast). Might not be available on some devices.
IRIS
undocumented setting for iris setting. Might not be available on some devices.
LIRIS
undocumented setting for L-iris setting (whatever that means...). Might not be available on some devices.
LUMINANCE
set/get luminance setting (high/low).
MCFI
set/get frame interpolation setting.
MSEL
set/get background color for A/V mute screen.
OVSCAN
set/get overscan ratio.
POPMEM
restore image setting from memory slot (1...10), related to PUSHMEM, ERASEMEM.
PUSHMEM
save current image setting to memory slot (1...10), related to POPMEM, ERASEMEM.
PWSTATUS
undocumented. Gets pwer status (see PWR).
SHARP
get sharpness value.
SHARPset
set sharpness value.
SIGNAL
set/get signal state (e.g 2D/3D).
SNO
get serial number of device.
SOURCE
set/get current source of video input.
TINT
get tint value.
TINTset
set tint value.
VOL
get volume setting. Normally a multiple of 12 (whyever...).
VOLset
set volume. Range is 1...20, since epson wants a multiple of 12 to be set (whyever...).
VREVERSE
set/get vertical reverse setting.
The following commands are only available if debug is set to 1. They are not meant for normal operation.
Use at your own risk, might crash fhem if used in the "wrong" situation.
But stay calm - restart always helps (at least I hope so...)
closeDevice
debug option. Closes connection to device.
connect
debug option. Closes active connection to device and forces reconnect.
decode
debug option. Decodes stored json values for set.
deleteNextOpen
debug option. Deletes timer for next device open command.
encode
debug option. Force new json encoding of set values.
isOpen
debug option. Query if connection to device is open and logs result in logfile (verbose 5 required).
openDevice
debug option. Force new connection to device. Handle with care.
reRead
debug option. Force update of set commands, useful if you changed e.g "AdditionalSettings".
removeTimer
debug option. Removes all timers for connection check.
Attributes
AdditionalSettings
cmd1:val_1,...,val_n cmd2:val_1,...,val_n You can specify own set commands here, they will be added to the set list.
Multiple own sets can be specified, separated by a blank.
command and values are separated by ":", values are separated by ",".
Example: ASPECT:get,10,20,30 SN:noArg Each command with get will we queried when unsing set <name> GetAll Might need a restart to be recognized, or use "reRead" setting.
Manufacturer
Epson|default - is not used currently.
PwrQueryDelay
(value in seconds) After setting PWR on/off, the projector needs some timeout before an PWR status query ("PWR get") can be sent. value defines the intervall in seconds to wait.
The perfect moment for a query depends (as many things in life do...), in this case on your projector.
I strongly recommend to use a value greater than 10 seconds to avoid race conditions. Lower values might work ... might. Feel free to test, but don't blame the module if you experience nice crashes.
Default value is 12 seconds.
connectionCheck
off|(value in seconds) value defines the intervall in seconds to perform an connection check. This is useful, since the standard connection handling of fhem (DevIo) will not detect an broken TCP connection, so the state disconnected will only trigger after TCP timeout (60-90 minutes). If you are ok with this, just set it to off.
Default value is 60 seconds.
cyclicConnect
off|(value in seconds) value defines the intervall in seconds to perform an periodic reconnect. Each interval we try to re-open the TCP connectionto the projector. Implemented to work around DevIo not recognizing a server-side broken connection, which can lead to a unnecessary, however non-blocking, system load.
Default value is 3600 seconds.
debug
You won't need it. But ok, if you insist...
debug will reveal some more set commands, namely encode, decode, reread. They will store the currents sets and results in json format to hidden readings (encode) or restore them (decode). reread will just restore the available set commands for your projector type in case they got "lost". Don't use the other debug commands - unnless you know what you do...
Default is 0, of course.
statusCheckCmd
(any command(s) you set) Defines the command(s) used by statusCheckInterval. Multiple commands can specified, e.g. PWR LAMP. Default: PWR to get power status. Please pay also attention to the helpful remarks at "statusCheckInterval".
Wrong commands or commands without a get will be ignored.
statusCheckInterval
off|(value in seconds) value defines the intervall in seconds to perform an status check. Each interval the projector is queried with the command defined by statusCheckCmd (default: PWR to get power status).
Attention: statusCheck is disabled - i.e. will NOT be done - when the projector is detected to be offline / unreachable. It does not make sense to poll an unreachable projector, doesn't it? If you want to query your projector regularly regardlessly, use the magic "cyclicConnect" attribute. Setting this will query the projector in the intervall you define, and update the settings "PWR" and "statusP" accordingly. This will e.g. help you to show "off" as status when the projector power was shut off outside fhem (who the hell wants to do that if you can do it infhem? Anyway...) instead of only standby (shutting power of, btw, is what I recommend, since it saves power, money and the environment)
Default value is 60 seconds.
statusOfflineMsg
(any message text you set) Defines the message to set in the Reading related to statusCheckCmd when the device goes offline. Status of device will be checked after each statusCheckInterval (default: 60s), querying the statusCheckCmd command (default: PWR), and if STATE is disconnected the Reading of statusCheckCmd will be set to this message. Default: offline.
statusPOfflineMsg
(any message text you set) The "P" makes the difference here ... Defines the message to set in "statusP" when the device is offline or unreachable. Status of device will be checked after each statusCheckInterval (default: 60s), querying the statusCheckCmd command (default: PWR), and if STATE is disconnected the Reading "statusP" will be set to this message. Default: off.
ESPEInk This module implements the possibility to send pictures generated in FHEM to an raw eInk paper connected to an ESP8266 or ESP32 eInk
WLAN driver board from waveshare (see details about the board at Wiki ESP8266 Waveshare Driver Board and Wiki ESP32 Waveshare Driver Board).
The module consists of 2 parts. One is the preparation of the picture to be send to the board. Here a template picture can be defined and additional texts can be added.
Furthermore it can be specified how the conversion should be done (e.g. if size of template picture should be automatically fit to eInk size, dithering, color mode or monochrome)
The second part converts the picture to the right format and sends it to the board and thus changes the display on the eInk paper.
Prerequisites
This module requires an eInk paper raw module from Waveshare (exisiting in different sizes, number of colors and resolutions)
and a WLAN driver board (Wiki Waveshare Driver Board).
The driver board needs the installation of an adruino sketch as described in the Wiki (see link before). After this the module together with the
eInk display only needs power supply. The data exchange between FHEM and the display is done via WLAN.
The module further needs installation of the GD library for perl (see installation instructions at GD for Perl and at Image::LibRSVG for Perl).
The picturefile parameter must be path to a readable file in the filesystem of FHEM.
[url] is the url of the WLAN driver board (typically an IP address but could also be a Web-URL). This parameter is optional but needed as soon as you want to not
only generate the picture but also upload it to the eInk display. For upload it is also necessary to specify the correct device type (default is 1.54inch_e-Paper_Module
see also attribute devicetype, for a list of all available device types use get devices).
[interval] is a time interval for regular updates of the information to the eInk display. It automatically converts the inputs and uploads the result to the eInk display and
defaults to 300 seconds.
[colormode] can be either color or monochrome and specifies if the inputs should be converted to a fitting color picture or if the conversion
should be done in monochrome format.
[convertmode] can be either level or dithering. If level is specified, the conversion transforms the given colors to the ones to the
closest color the display is capable of (depending on the display type this can be black, red or yellow). When dithering is specified, the conversion performs a Floyd Steinberg
dithering to fit the input picture better to the capabilities of the eInk display.
Set
set <name> <option> <value>
Options:
addtext
This option allows to specify a text that should be added to the template picture at any position.
The value must be given in the form: text#x#y#size#angle#color#font#linegap#blockwidth where:
text is the text that should be added. This is the only mandatory part of the value.
x is the x-position of the lower left corner of the text relative to the lower left corner of the display area
y is the y-position of the lower left corner of the text relative to the lower left corner of the display area
size is the size of the text in pixels. This parameter is only used if a TTF font type is specified (see below)
angle is the rotation angle (counterclockwise) that should be used when drawing the text. In case of not using TTF fonts (see below), the resulting rotation can be only 0 or 90 degrees.
color is an RGB hex string that specifies the RGB values of the color respectively (e.g. 00FF00 for green)
font is either one of smallmediumlargegiant or a path to a valid TTF font file in the FHEM file system.
linegap The distance between consecutive lines if blocksetting is used (see blockwidth below) positive values increase the distance negative values reduce the distance.
blockwidth The width in pixels of the text block generated by the text string. If the string width on the display is higher than the given width in pixels, an automatic linebreak will be added.
For each of the specified texts a list of readings and attributes is added to the device. The readings are holding the parameters finally taken for the generation of the output picture.
The attributes allow an easy change of the readings (see details in the description below). Once at least one text is specified, the set option removeobject is added.
addicon
This option allows to specify an icon that should be added to the template picture at any position.
The value must be given in the form: icon#x#y#size#angle#color where:
icon is the name of the icon that should be added. This is the only mandatory part of the value. Icons can either be specified as fhem icon names (any installed fhem icons are supported), or as url links to web icons
x is the x-position of the lower left corner of the icon relative to the lower left corner of the display area
y is the y-position of the lower left corner of the icon relative to the lower left corner of the display area
size is the size of the icon in pixels. This parameter is only used if a TTF font type is specified (see below)
angle is the rotation angle (counterclockwise) that should be used when drawing the icon. In case of not using TTF fonts (see below), the resulting rotation can be only 0 or 90 degrees.
color is an RGB hex string that specifies the RGB values of the color respectively (e.g. 00FF00 for green)
For each of the specified icons a list of readings and attributes is added to the device. The readings are holding the parameters finally taken for the generation of the output picture.
The attributes allow an easy change of the readings (see details in the description below). Once at least one icon is specified, the set option removeobject is added.
addsymbol
This option allows to specify an symbols (lines, ellipses, rectangles, arcs) that should be added to the template picture at any position.
The value must be given in the form: symbol#x#y#thickness#angle#color#width#height#segment where:
symbol is specifying which symbol should be drawn. Possible values are line or rectangle or ellipse or arc. If -filled is added, the symbol is filled, if -dotted or -dashed is added, the line is drawn dotted or dashed.
For example a symbol value given as 'line-dotted' will draw a dotted line, 'rectangle-filled' will draw a filled rectangle.
x is the x-position of the lower left corner of the symbol relative to the lower left corner of the display area
y is the y-position of the lower left corner of the symbol relative to the lower left corner of the display area
thickness is the thickness of lines or outlines of the symbols drawn.
angle is the rotation angle (counterclockwise) that should be used when drawing the symbol.
color is an RGB hex string that specifies the RGB values of the color respectively (e.g. 00FF00 for green)
width is the width of the symbol (in case of lines, the line is drawn width pixels in x direction and height pixels in y direction).
height is the width of the symbol (in case of lines, the line is drawn width pixels in x direction and height pixels in y direction).
segment is only used for arc type symbols. In this case angle (see above) specifies the start of the arc and segment specifices the width of the arc.
For each of the specified symbols a list of readings and attributes is added to the device. The readings are holding the parameters finally taken for the generation of the output picture.
The attributes allow an easy change of the readings (see details in the description below). Once at least one symbol is specified, the set option removeobject is added.
textreading
This option allows to specify a device:reading as trigger for adding texts to the template picture at any position.
The value m