### Contents

Introduction
FHEM command types
Device specification
Attributes
FHEM commands

apptime attr cancel createlog define defmod delete deleteattr deletereading displayattr get IF include inform list modify notice quit reload rename rereadcfg save set setdefaultattr setreading setstate shutdown sleep trigger usb

Devices

global

Helper modules

CustomReadings DOIF Dashboard dewpoint FLOORPLAN HCS Heating_Control HMinfo HourCounter MaxScanner PachLog RandomTimer rain remotecontrol statistics Twilight THRESHOLD WeekdayTimer WOL

Perl specials
gnuplot file syntax

### Introduction

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 minimal configuration file looks like:

        attr global logfile log/fhem.log
        attr global modpath .
        attr global statefile log/fhem.save
        attr global verbose 3
        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:

`telnet <fhemhost> 7072
<NL>` (This newline switches into "prompt" mode)`
<command>...
quit`

or

`fhem.pl <fhemhost>:7072 "<fhem-command>" "..."`

### FHEM command types

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 \) .

### Device specification (devspec)

The commands attr, deleteattr, displayattr, delete, get, list, set, setreading, setstate, trigger can take a more complex device specification as argument, which will be expanded to a list of devices. A device specification (short devspec) can be:

- 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.
- 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 TYPE=FS20 STATE`
`list i:TYPE=FS20 STATE`

Notes:

- the spec may not contain space characters.</n>
- 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.

### Attributes

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. 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.
- room
  Filter/group devices. Recognized by web-pgm2 and web-pgm3. 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 to selectively disable rooms for certain FHEMWEB instances.
- 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 enclused in {}, then it is evaluated. This attribute is evaluated each time a reading is updated.

- 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:

1. If both attributes are not set, any update of any reading of the device creates an event.
2. If any of the attributes is set, no events occur for updates or changes of readings not listed in any of the attributes.
3. 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 timestamps of the listed readings will not be changed 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 function 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.

Examples:
`attr myPowerMeter event-aggregator EP_POWER_METER:300:linear:mean,EP_ENERGY_METER:300:none:v`
`attr myBadSensor event-aggregator TEMP::none:median:300`
`attr mySunMeter event-aggregator SUN_INTENSITY_24H::const:integral:86400`

- 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.

- userReadings
  A comma-separated list of definitions of user-defined readings. Each definition has the form:
  `<reading>[:<trigger>] [<modifier>] { <perl code> }`
  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:
  `attr myEnergyMeter userReadings energy { ReadingsVal("myEnergyMeter","counters.A",0)/1250.0;; }
  attr myMultiMeter userReadings energy1:counters.A.* { ReadingsVal("myMultiMeter","counters.A",0)/1250.0;; }, energy2:counters.B.* { ReadingsVal("myMultiMeter","counters.B",0)/1250.0;; }`
  `<modifier>` can take one of these values:
  - 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.
- Special: attribute disable can be toggled
  Attribute "disable" can be toggled by issuing the following command:
  `attr <device> disable toggle`
  Attribute "disable" must be offered by the corresponding module

### attr

`attr <devspec> <attrname> [<value>]`
Set an attribute for a device defined by define. 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.
Examples:

`attr global verbose 3`
`attr lamp room kitchen`
`attr lamp group lights`
`attr lamp loglevel 6`
`attr weatherstation event-on-update-reading wind,temperature,humidity`
`attr weatherstation event-on-change-reading israining`
`attr weatherstation event-on-change-reading israining,state`
`attr heating stateFormat Temp:measured-temp, Valve:actuator`

Notes:

- See deleteattr to delete attributes.

### cancel

`cancel [<id> [quiet]]`
Cancels a named sleep.

### define

`define [option] <name> <type> <type-specific>`
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.

### defmod

`defmod <name> <type> <type-specific>`
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.

### delete

`delete <devspec>`
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 lamp`

### deleteattr

`deleteattr <devspec> [<attrname>]`
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>.
After deleting the attribute, the global event "DELETEATTR" will be generated.
Examples:

`deleteattr lamp follow-on-for-timer`
`deleteattr lamp`

### deletereading

`deletereading <devspec> <readingname>`
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>.
Examples:

`deletereading mySensor temp1`
`deletereading mySensor temp\d+`

### displayattr

`displayattr <devspec> [<attrname>]`
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.
`

### get

`get <devspec> <type-specific>`
Ask a value directly from the device, and wait for an answer. In general, you can get a list of possible parameters by

`get <device> ?`

See the Device specification section for details on <devspec>.
Each device has different get parameters, see the corresponding device section for details.

### include

`include <filename>`
Read in the file, and process every line as a FHEM command. Note: only experts should use this command.

### inform

`inform {on|off|timer|raw} [regexp]`
If set to on, and a device state changes, send a notification to the current client. This command can be used by other programs/modules to receive a notification.
The option timer prepends a timerstamp to the line. Note: this command is a nice way to check which events are generated, to help you when creating notify or FileLog entries.

### list

`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 (like DEF, TYPE, etc) or reading (actuator, measured-temp) for all devices from the devspec.
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.

### modify

`modify <name> <type-dependent-options>`
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.
Example:

`define lampon at 19:00 set lamp on`
`modify lampon *19:00`
`modify lampon 19:00 set lamp on-for-timer 16`

### quit

`quit`
If used in a TCP/IP session, terminate the client session.
If used in a script, terminate the parsing of the current script.
Example:

`quit`

### reload

`reload <module>`
Reload the given module from the module directory. It is a convenient way to test modules whithout restarting the program.
Example:

`reload 99_PRIV`

### rename

`rename <oldname> <newname>`
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.
Example:

`rename FHT_1234 fht.kitchen`

### rereadcfg

`rereadcfg [fhem-config-file]`
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.
Example:

`rereadcfg`

### save

`save [<configfile>]`
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.

### set

`set <devspec> <type-specific>`
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:reading] with the corresponding reading of device, if both device and reading exists.
- [device:reading:d] same as above, but only the number is retrieved, see ReadingsNum
- {(perlExpression)} with the result of perlExpression. The $DEV variable is additionally available, designating the set device name.

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.

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
`

### setdefaultattr

`setdefaultattr [<attrname> [<value>]]`
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:

`setdefaultattr room kitchen`
`setdefaultattr loglevel 4`
`define lamp1 FS20 1234 11`
`define lamp2 FS20 1234 12`
`define lamp3 FS20 1234 13`
`setdefaultattr`

Notes:

- There is no way to delete a single default-attribute from the list

### setreading

`setreading <devspec> <reading> <value>`
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.
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.

### setstate

`setstate <devspec> <value>`
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

### shutdown

`shutdown [restart|exitValue]`
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.
Example:

`shutdown`
`shutdown restart`
`shutdown 1`

### sleep

`sleep <sec> [<id>] [quiet]`
sleep followed by another command is comparable to a nameless at, it executes the following commands after waiting the specified time. The unit is seconds, with millisecond accuracy, as you can specify decimal places.
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.

### trigger

`trigger <devspec> <state>`
Trigger a notify definition. See the Device specification section for details on <devspec>.
Example:

`trigger btn3 on`

### global

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

Attributes

- archivedir
- archivecmd
- nrarchive
- 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.
- 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.:
  `"/etc/fhem.cfg /var/log/fhem/fhem.save /usr/share/fhem/contrib /usr/share/fhem/FHEM /usr/share/fhem/foo /usr/share/fhem/foobar /usr/share/fhem/www"`
  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.
- 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" (default), then a full commandref will be generated after each update. If set to modular, there is only a short description at the beginning, and the module documentation is loaded from FHEM dynamically.
- 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.
- holiday2we
  If this attribute is set, then the $we variable will be true, if the value of the holiday variable referenced by this attribute is not none.
  Example:
  attr global holiday2we hessen
- 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.
- 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 }`.
- 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. SecurityCheck is setting motd if it is not defined upon startup, to avoid this set the motd value to none. motd is also used to show collected error messages upon FHEM start.
- 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.
- 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.
- sendStatistics
- 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.
- title
- uniqueID
- 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 additinal 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.

### Perl specials

If you want to automate some tasks via FHEM, then you'll probably use at or notify. For more complex tasks you'll use either a shell-script or a perl "oneliner" as the at/notify argument. This chapter gives some tips in using the perl oneliners.
- To test the following perl oneliners, type them on the telnet prompt (or FHEMWEB text input) by enclosing it in {}, one line at once. The last line will only write something in the logfile, the output of the other lines is directly visible.
  { "Hello" }
  { 1+3*4 }
  { `ls /etc` }
  { Log 1, "Hello" }
- Perl expressions are separated by ;, in FHEM oneliners they have to escaped with ;;
  { my $a = 1+1;; Log 1, "Hello $a" }
- To use FHEM commands from the perl expression, use the function fhem(), which takes a string argument, this string will be evaluated as a FHEM command:
  { fhem "set light on" }
  define n1 notify piri:on { fhem "set light on" }
  Note: if this function returns a value, it will also be logged into the global FHEM log. Use 1 as a second argument to disable this logging, this makes sense when obtainig some values via FHEM "get...".
- Notify can be used to store macros for manual execution. Use the trigger command to execute the macro:
  define MyMacro notify MyMacro { Log 1, "Hello"}
  trigger MyMacro
  define MacroWithArg notify MyMacro { Log 1, "Hello %"}
  trigger MyMacro MyArg
- To make date and time handling easier, the variables $sec, $min, $hour, $mday, $month, $year, $wday, $yday, $isdst are available in the perl oneliners (see also perldoc -f localtime). Exceptions: $month is in the range of 1 to 12, and $year is corrected by 1900 (as I would expect). Additionally the variable $hms contains the time in the HH:MM:SS format.
  Additionally the variabe $we is 1 if it is weekend (i.e $wday == 0 or $wday == 6), and 0 otherwise. If the holida2we global attribute is set, $we is 1 for holidays too.
  define n2 notify piri:on { if($hour > 18 || $hour < 5) { fhem "set light on" } }
  define roll_en *07:45:00 { fhem "trigger SwitchAllRoll on" if(!$we) }
  define roll_en *08:30:00 { fhem "trigger SwitchAllRoll on" if($we) }
- The following helper functions are defined in 99_Util.pm (which will be loaded automatically, as every module with prefix 99):
  - min(a,b), max(a,b)
  - time_str2num("YYYY-MM-DD HH:MM:SS") returns a numerical value, which makes computation of time differences easier
  - abstime2rel("HH:MM:SS") converts an absolute time to a relative one
- To access the device states/attributes, use the following functions:
  - Value(<devicename>)
    returns the state of the device (the string you see in paranthesis in the output of the list command).
  - OldValue(<devicename>)
  - OldTimestamp(<devicename>)
    returns the old value/timestamp of the device.
  - ReadingsVal(<devicename>,<reading>,<defaultvalue>)
    Return the reading (the value in the Readings section of "list device")
  - ReadingsNum(<devicename>,<reading>,<defaultvalue>)
    Return the reading as a number, i.e. delete non-numerical values.
  - AttrVal(<devicename>,<attribute>,<defaultvalue>)
    Return the attribute of the device
    { Value("wz") }
    { OldValue("wz") }
    { time_str2num(OldTimestamp("wz")) }
    { ReadingsVal("wz", "measured-temp", "20")+0 }
    { ReadingsTimestamp("wz", "measured-temp", 0)}
    { AttrVal("wz", "room", "none") }
  - InternalVal(<devicename>,<property>,<defaultvalue>)
    Return the internal value (the value in the Internals section of "list device").
- By using the 99_SUNRISE_EL.pm module, you have access to the following functions:
  sunset($offset, $min, $max)
  sunrise($offset, $min, $max)
  isday()
  offset is in seconds, and the format of min/max is "HH:MM" or "HH:MM:SS". isday returns 1 if the sun is visible, and 0 else.

### gnuplot file syntax

The .gplot files are also used by the FHEMWEB/SVG module when the plotmode attribute is set to SVG. In this case only a subset of the .gnuplot attributes are used, and some lines have special meanings: the difference will be explained in this chapter. See also this FHEM Wiki entry on creating logs.
Following is a minimal .gplot definition (valid only for plotmode SVG):

      set terminal size <SIZE>
      #FileLog 4:::
      plot title 'Temperature' with lines

The .gnuplot file consists of 3 parts:

- set commands
  Following sets are recognized:
  - terminal, only the size parameter.
    This is usually set to <SIZE>, which is replaced by the plotsize attribute of the FHEMWEB or weblink instance.
  - title
    Usually set to <TL> which is replace by the weblink title attribute, or to <Lx>, which is replaced by the weblink label attribute.
  - ylabel,y2label
    Left and right labels, printed vertically. Are also subject to label replacement.
  - yrange,y2range
    Specify the range of the left and right axis. Examples:
    set yrange [-0.1:1.1]
    set y2range [0:]
  - ytics,y2tics
    the label for the left/right axis tics. Examples:
    set ytics ("on" 0, "off" 1)
    set y2tics
- #FileLog entries
  Each line from the plot section must have one corresponding #FileLog line. For the syntax see the column_spec paragraph of the Filelog get description. Note that for SVG plots the first column of the input file always has to be in the standard fhem timestamp format (YYYY-MM-DD_HH:MM:SS)
- plot entries
  There is always one plot command with comma separated argument-blocks. Each argument-block represents one line, and has its own parameters. Following parameters are recognized:
  - axes x1y1 / x1y2
    tells the program to assign the current line to one of the two axes (left or right).
  - title
    Caption of the line. Whan clicking on this title, a small javascript program will change the title to the min/max and last values of the plot, will enable copying this line or pasting an already copied one (the existing scale of the plot wont'be changed, only the pasted line will be scaled), and other lines of the plot will temporarily be hidden.
  - with <linetype>
    Specify the line type. Following types are recognized: points, steps, fsteps, histeps and lines. Everything unknown will be mapped to the type lines. SVG special: cubic and quadratic, are mapped to the SVG path types C, and Q respectively.
  - ls <linestyle>
    The linestyle defaults to l0 for the first line, l1 for the second, and so on. It is defined in the svg_style.css file. There are two sets defined here: l0-l8 and l0fill-l6fill. The second set must be specified explicitly. If the name of the linestyle contains the word fill, then plots of the lineytype "lines" will have an additional starting and ending segment, so that filling is done correctly.
    See the SVG spec for details of this CSS file. Note: if you plan to use this attribute, you have to specify it for all the lines (attribute-blocks) in the plot command.
  - lw <linewidth>
    Sets the stroke-width style of the line. This attribute is deprecated, the corresponding feature of the CSS file / (attribute ls) should be used instead.