From Domoticz
Jump to: navigation, search

Using the events system

Status of your Blockly:
Black = Enabled
Red = Disabled
Purple = Disabled because a missing device was used [ Domoticz stops this Blockly automatic! ]


- v1.813: Initial system
- v1.814: Send notifications from Lua using commandArray['SendNotification']='subject#body'
- v1.818: otherdevices_lastupdate table added to enable "notify me if door y has been open too long"
- v1.829: Events can be built using the Blockly UI. Please remove all saved events if you have been testing 
prior to this release. Events based on time (currently timeofday and weekday) are not working yet, they will be soon.
- v1.833: Events based on weekdays should now work. Time of day still doesn't. Reading sValues (temperatures etc) 
does not work either. 
- v1.835: Time of day implemented. 
- v1.836: Fixed issue where event kept running after being deleted. 
- v1.839: Save confirmation is no longer an alert box to avoid popup block protection in certain browsers
- v1.841: Temperature, humidity and barometer value checking implemented in blockly
- v1.842: Temperature, humidity and barometer value checking implemented in lua scripting, see scripting guide
- v1.844: Implemented blockly: set device[x] = "On" for 10 minutes
- v1.845: Implemented blockly: set device[x] = "On" random somewhere within x minutes
- v1.848: Implemented: Blockly enable/disable event. Time triggered Blockly events have their actions fired also now. 
All events will be disabled by default when upgrading to this version, enable them afterwards.
- v1.849: When a device that belongs to a Blockly event is deleted, the log warns and the event is disabled. Event is 
shown in purple text in the UI. 
- v1.855: Complex if statements should now all be parsed correctly from Blockly to Domoticz. 
Implemented "Set Level block", does not work with random and set for x minutes yet. 
- v1.858: Implemented button to list current states
- v1.867: Temp, hum and baro values are passed to Lua as proper numbers instead of strings. otherdevices_svalues[] is 
still passed as a string to access other measurement devices for the time being. 
- v1.873: Implemented sunrise/sunset in blockly, time blocks grouped, switches grouped by alphabet as workaround 
for blockly not using scrollable dropdowns. In the show current states list devicenames now update when changed. 
These changes will probably require the blockly events to be rebuilt through the interface by the user.
- v1.888: Implemented: tooltips in events UI, start implementing multi language support in events
- v1.899: Implemented: Scene switching in Blockly and scripts (does not work as if trigger), 
added Panic + related to blockly states, fixed small event bugs. Updated time example script. 
- v1.900: Implemented: Set Level and Random for dimmers, events triggers only after previous one completes, 
"Set Level" text in blockly shortened, other devices status and measurements now passed to lua as 
name instead of id, small fixes. 
- v1.911: Implemented: set for x minutes returns to previous state after timer
- v1.912: Implemented: security system status in Blockly and Lua scripts
- v1.928: Implemented: if.. else if.. in Blockly, new database structure to accommodate, fixed security status in blockly
- v1.933: Implemented: trigger url/api as Do command
- v1.1023: Scenes and groups on/off/active/inactive via events, fixed bug where inactive event would still trigger 
when multiple events apply. Comma now supported in event OpenURL. events now triggered by security state change
implemented script_security_name.lua for sec panel triggers in lua. 
- v1.1113: Implemented: Update device/sensor values using commandArray['UpdateDevice']='idx|nValue|sValue'
- v1.1137: Implemented: Added otherdevices_dewpointto, otherdevices_rain, otherdevices_rain_lasthour, otherdevices_uv,
otherdevices_winddir, otherdevices_windspeed, otherdevices_windgust to Lua scripts
- v1.1328: Implemented: day- and nighttime indicators for Lua
- V1.1331: Implemented: Notification Priority
- V1.1340: Implemented: "Send Email notification to" from lua using commandArray['SendEmail']='subject#body\nsecond [email protected]'
- v1.1905: Implemented blockly: set device[x] = "On" after 10 seconds
- v2.2437: Implemented: option to set uservariable AFTER xx seconds
- V2.2566: Implemented: "Send SMS" from lua using commandArray['SendSMS']='subject'
- V2.3865: Implemented: blockly: option to use expressions in notifications/email and SMS
- V3.7968: Implemented: dzVents event system.

Note: As of version V3.7968 there is a new Lua-based event system for Domoticz called dzVents which makes writing events very simple and almost trivial. Check out 'dzVents': next generation LUA scripting.

the events system in Domoticz uses a scripting engine called Lua, which is used in many popular software titles like Photoshop and World of Warcraft. By using Lua, you can add extensive logic to your Domoticz system. See <> for more information and <> for some script tutorials. Domoticz contains Lua version 5.2.

Example scripts here: Event script examples
Post script examples and discussion here: <>
Post your own Blockly examples in forum: <>

The event system will have two options to create events:

Using script creation & editing functionality within Domoticz itself

You can find the interface here: Setup -> More options -> Events.

The Events page has three key fields at the top right hand side.

  1. Script name. There are no special rules associated with this name.
  2. Interpreter. The Editor/Event Engine that will be used for the script. Drop down values:
    1. Blockly - the default.
    2. Lua
    3. Python - Only if Domoticz was built from source with Python support explicitly enabled.
  3. Event Type. Controls what events events will cause Domoticz to execute the script. Drop down values:
    1. All - Will run whenever anything happens that triggers the event system to run a script
    2. Device - Will run whenever ANY device state/value change
    3. Security - Will run whenever there is a security event
    4. Time - Will run once per minute. Scripts are executed one at a time.
    5. User Variable - Will run when User Variables are updated

Events can be enabled or disabled using the "event active" checkbox. Disabled events are marked red in the events list.

Scripts will be stored in the Domoticz database itself so do not need to be backed up separately.

The "blockly" interface

Not all browsers seem to work at the moment, please report in thread which browsers work/don't. 
Blockly also doesn't seem to work on mobile devices. 
  • this really needs a manual with pictures later...*

To learn the basics on how to use Blockly, try the examples found here:

Domoticz examples can be found in the forum:

Start by dragging in an if/do block from the control area, or an if.. else if block (use the + symbol to create extra "else if" connectors). The "if" part is your set of criteria that will trigger devices. It is possible to link a single statement using the top block from the logic area. If you want several combined statements, select the block that says "and", and put in two statement blocks. Drag a device from the devices area to the first part of the statement block, and the "on" block to the second. You can then change the device and states from the dropdowns. It is also possible to drag in a "day" block and say "if day of week is greater than wednesday, or if day of week is not saturday). For temperature, humidity and barometer drag in the value piece from the logic area (the one that says "0") and change the value as desired.

I have tested nested booleans up to "if ((devicea = on and deviceb = on) and (devicec = off and deviced = off)", theoretically it should do larger ones but that will only make it harder to follow the event anyway.

In the "do" connection you can either place a set block from the logic area or a notification block from the messages area. Only set switchable devices (i.e. not a thermometer) or notifications. There are three set blocks:

1. Normal set: just switches the device
2. Set for x minutes: switches the device back to its opposite state after specified amount of minutes 
3. Set random within x minutes: switch a device somewhere random within the specified number of minutes.  

To specify the number of minutes use the number block in the logic area.

Triggering mechanism: As with the scripting logic, the blockly events are triggered by:

- time: every minute, the system checks all blockly rules that mention a time condition and evaluates them.

- device: if a device changes state for whatever reason, the system checks all blockly rules to see if the device is mentioned and then evaluates the "if" condition(s).

Stuff to keep in mind:

(if weekday > wednesday) set lamp=on will set the lamp on every one minute from thursday through tuesday. So always put on a second check, for instance (if weekday > wednesday and lamp = off) set lamp=on

Try to avoid single if statements.

The same event will not fire unless the previous one completes. If an action is set using "Set For x minutes" or "Random within x minutes" or "Set After x seconds", the same event will not schedule until the first one completes.

User variables can be checked and set using the compare and set blocks. Use the numeric and string fields (available in the user variables box) to compare and set them. Keep the type of variable in mind (e.g. for an integer variable use the numeric box to check and set it).

You can use expressions in your notifications/email and SMS messages like:

"My temperature is {{temperaturedevice[1234]}} degrees, and the humidity is {{humiditydevice[1234]}} %"

Possible expressions:


Where 1234 is the Idx of the sensor

Lua (& Python) Interface

Lua events maintain through the editor work in the way that file based Lua scripts do and use the same 'commandArray' interface. There are samples and help on this Wiki. Currently Python is only an option if Domoticz is built from source with Python enabled.

The Lua editor is context sensitive and will prompt with auto-complete options and show common errors to help with debugging. The editor theme can be changed by pressing the control and comma keys at the same time. Domoticz will save the scheme when events are saved.

To create a new Lua event:

  1. Set the Interpreter drop down to Lua
  2. Set the Event Type drop down to the type of event.
  3. Press the 'New' button.

A template script will be shown that shows one way of processing that type of event. For example for Device events this template is shown:

-- Domoticz passes information to scripts through a number of global tables
-- device changed contains state and svalues for the device that changed.
--   devicechanged['yourdevicename'] = state 
--   devicechanged['svalues'] = svalues string 
-- otherdevices, otherdevices_lastupdate and otherdevices_svalues are arrays for all devices: 
--   otherdevices['yourotherdevicename'] = "On"
--   otherdevices_lastupdate['yourotherdevicename'] = "2015-12-27 14:26:40"
--   otherdevices_svalues['yourotherthermometer'] = string of svalues
-- uservariables and uservariables_lastupdate are arrays for all user variables: 
--   uservariables['yourvariablename'] = 'Test Value'
--   uservariables_lastupdate['yourvariablename'] = '2015-12-27 11:19:22'
-- other useful details are contained in the timeofday table
--   timeofday['Nighttime'] = true or false
--   timeofday['SunriseInMinutes'] = number
--   timeofday['Daytime'] = true or false
--   timeofday['SunsetInMinutes'] = number
--   globalvariables['Security'] = 'Disarmed', 'Armed Home' or 'Armed Away'
-- To see examples of commands see:
-- To get a list of available values see:
-- Based on your logic, fill the commandArray with device commands. Device name is case sensitive. 
commandArray = {}
-- loop through all the changed devices
for deviceName,deviceValue in pairs(devicechanged) do
    print ("Device based event fired on '"..deviceName.."', value '"..tostring(deviceValue).."'");
--    if (deviceName=='myDevice') then
--        if deviceValue == "On" then
--            print("Device is On")
--        elseif deviceValue == "Off" then
--            commandArray['a device name'] = "On"
--            commandArray['another device name'] = "Off AFTER 10"
--            commandArray['Scene:MyScene'] = "On"
--            commandArray['Group:My Group'] = "Off AFTER 30"
--        end
--    end
return commandArray

The LUA_commands page has more information on the available commands that can be passed back to Domoticz.

By adding your own scripts to the scripts/lua/ dir in your domoticz installation folder.

The lua scripts folder has two demo scripts that can serve as a starting point. The script filename has 3 components each sub-divided by an underscore : script_trigger_name.lua Trigger can be 'time', 'device', 'variable' or 'security', name can be any string for your reference, script_device_MyOtherDeviceNameOnWhenMyDeviceNameOn.lua for instance.

Domoticz will execute all time, variable and device triggers when the relevant trigger occurs, e.g. the device scripts are run when a device changes, the variable scripts are run when a variable changes, the time scripts will run every minute. Also scripts don't run in background. Domoticz will wait for the script to complete so don't use sleep() statements and get the script done as fast as possible.

Domoticz ignores all scripts named "demo" and scripts without the .lua extension, so copy the examples and change the name.

Make sure that if you are using non-ansi characters you save the file in UTF-8 encoding, without a BOM header

Device scripts each receive 7 tables from Domoticz: devicechanged, otherdevices, otherdevices_lastupdate, otherdevices_svalues, otherdevices_idx, uservariables and uservariables_lastupdate

Variable scripts receive 7 tables from Domoticz: otherdevices, otherdevices_lastupdate, otherdevices_svalues, otherdevices_idx, , uservariables, uservariables_lastupdate and uservariablechanged

Time scripts receive 6 tables: otherdevices, otherdevices_lastupdate, otherdevices_svalues, otherdevices_utility, otherdevices_idx, uservariables and uservariables_lastupdate

The devicechanged table contains a devicename entry, indicating the new state for the device that triggered the device event:

 devicechanged['devicename']='Status', e.g. devicechanged['MyLamp']='On'

if the device that triggered a device-event measures temperature, humidity or barometric pressure, there will obviously not be a devicechanged['devicename']='Status' value because these values are analogue and not digital (on or off). Instead, the value type is appended (added) to the devicename and can be checked as follows:

 devicechanged['devicename_Temperature'] = value
 devicechanged['devicename_Humidity'] = value
 devicechanged['devicename_Barometer'] = value

The whole string (devicename + type) is case sensitive, value type should start with uppercase. If your thermometer is named "MyThermometer", check its incoming temperature value by stating something like "if devicechanged['MyThermometer_Temperature'] > 20 then". If you're not sure which values are coming in:

 for i, v in pairs(devicechanged) do print(i, v) end

The otherdevices table contains the status for all other devices, e.g.: otherdevices['yourotherdevicename']='On'. When a script is triggered by time, there will be no devicechanged value, so use otherdevices to access device states.

The otherdevices_lastupdate table contains the date + time of last update for all other devices, e.g.:

otherdevices_lastupdate['Door'] = '2013-07-10 18:14:32'

Temperature, humidity and barometer values for other devices can be found in otherdevices_temperature['yourdevice'],otherdevices_humidity['yourdevice'] and otherdevices_barometer['yourdevice'] tables.

The otherdevices_idx table contains the indexes for devices (which can be seen in 'Devices' tab, used in json sequests etc)

otherdevices_idx['Door'] = 42

To modify an otherdevice value, you should use commandArray['UpdateDevice']='idx|nValue|sValue' where idx is the device index, nValue and sValue the values to modify (see json page for details - Domoticz API/JSON URL's)

For using user variables in Lua scripts, there are three tables available: uservariables, uservariables_lastupdate and uservariablechanged. The uservariablechanged table (with only the variable that triggered the event) is only available in your event scripts (script_variable_name.lua), the other two are always available. Reference your variable by name, e.g. if uservariables["MyVar"] = ...

The state of the Domoticz built-in security system can be checked via globalvariables['Security']. This will return "Disarmed", "Armed Home" or "Armed Away". It is not a true device, so it will not be picked up as one in a device script. Use a security script to trigger on security status changes. Time and device script can however be triggered by time or another device and then check the status of globalvariables['Security'] as well.

Each script has to return a commandArray, which is filled based on succesful execution of your script. Commands in the commandArray will only be executed after the array has been returned back to Domoticz to be executed at the end of the script. This means that is is not possible to have one Lua script do multiple actions on the same device.

Using the 3 or 2 tables (depending on event type), build your own event logic, for instance:

 commandArray = {}
 if (devicechanged['MyDeviceName'] == 'On' and otherdevices['MyOtherDeviceName'] == 'Off') then
 return commandArray

Put device names and states between the square brackets exactly like they appear in Domoticz, the string is case sensitive and spaces need to be included e.g. devicechanged['Blue Light'].

When adding device states to the command array, choose the required command for your device, e.g. 'On', 'Off', 'Group On', etc. For dimmable devices, use command 'Set Level X' where X is a percentage (0-100) integer (do not put a percentage symbol after the value). There are three ways to set a device state. The most basic one is to just specify the new state (e.g. On/Off), which will set the new state immediately when the script logic evaluates to true.

It is also possible to change the state for a device for a fixed period of time; if the device only needs to be turned on for 10 minutes, use 'On FOR 10'.

To add a randomized timer to a device change, for instance to turn on a device somewhere in the next 30 minutes, use 'On RANDOM 30'. FOR and RANDOM are in minutes.

To change the state for a device after a fixed period of time; if the device only needs to be turned on after 10 seconds, use 'On AFTER 10'. AFTER is in seconds and accepts 3 seconds at least. ('On AFTER 2' doesn't work).

The keywords FOR RANDOM AFTER must be written in CAPITAL LETTER.

To switch a scene or group, put prefix 'Scene:' or 'Group:' in front of the scene name. Note that it is not possible to check the state of a scene or group, since that is not its intended use. Check a (significant) single device from the scene/group table before switching scenes. Scenes can only be turned on, groups can be turned on and off. It is also possible to activate or deactivate a group or scene schedule by using 'Active' or 'Inactive'. This for instance enables the activation of presence simulation; when an alarm device is activated, also activate lighting schedules to simulate presence.

Using the 'SendNotification' command a message can be sent to email or the notification system, whichever is set in Domoticz preferences.
Use a # to separate subject, message body, priority and sound (pushover only).

Priority values:

-2 Low (Not available on Pushover)
-1 Moderate (Prowl/NMA) Quiet (Pushover)
0 Normal
1 High (Prowl/NMA) bypasses quiet hours (Pushover)
2 Emergency (Prowl/NMA) requires confirmation (Pushover)

The Pushover system also supports different sounds. See [1]

Using 'OpenURL' it is possible to trigger a url/api based on an event. The url will not retrieve/parse any data, use it for one way communication.

By prepending "Variable:" an existing variable can be updated.

Some valid examples:

 commandArray['Scene:Livingroom']='On'         -- remember, Scene cannot be turned Off!
 commandArray['Keyfob']='Group On'
 commandArray['DimmableDevice']='Set Level 50'
 commandArray['Selector']='Set Level: 50'
 commandArray['SendEmail']=[email protected]'
 commandArray['Blinds']='On RANDOM 30'
 commandArray['Porch Light']='On FOR 2'
 commandArray['Variable:MyVar']='Some value'
 commandArray['Variable:MyVar']='Some value AFTER 3'
 commandArray[textDeviceIdx] = { ['UpdateDevice'] = textDeviceIdx..'|0|'..'some text' }
 commandArray[tempDeviceIdx] = { ['UpdateDevice'] = tempDeviceIdx..'|0|'..temp }
 commandArray[tempHumDevIdx] = { ['UpdateDevice'] = tempHumDevIdx..'|0|'.. temp ..';'.. hum ..';'.. hum_stat }

-- ... (see json page Domoticz API/JSON URL's for exact number of arguments)

In device scripts, *always* do a check on the state of the changed device first. The device scripts are triggered fairly often, especially when you have a lot of thermometers and other measurement devices. If you just set the commandArray without any conditions, the script always just execute those commands at every device change, and those changes will trigger the scripts again and again resulting in a loop.

The same event will not fire unless the previous one completes. If an action is set using "Set FOR x minutes" or "RANDOM within x minutes", the same event will not schedule until the first one completes.

Using time conditions:

 time ="*t")
 commandArray = {}
 if (devicechanged['MyDeviceName'] == 'On' and otherdevices['MyOtherDeviceName'] == 'Off' and time.hour >= 22) then
 return commandArray

For checking day- or nighttime use the timeofday array with boolean variables "Daytime" and "Nighttime":

 if (timeofday['Nighttime']) then
      print('its nighttime')

If you want sunrise or sunset in a numeric value, use timeofday['SunriseInMinutes'] and timeofday['SunsetInMinutes']. So when sunrise is at 7:13, timeofday['SunriseInMinutes'] will be 433.

Note: start each "commandArray" line with a tab to indent it under the "if" statement. You can give multiple commands by specifying multiple command array entries:

 commandArray = {}
 if (devicechanged['MyDeviceName'] == 'On' and otherdevices['MyOtherDeviceName'] == 'Off') then
    commandArray['Variable:MyVar']='Some value'
 return commandArray

The Lua print command will output its statements to the domoticz log, so you can use that to check on values or your logic. For instance, if you want to check the other device states that get passed into Lua, add line:

 for i, v in pairs(otherdevices) do print(i, v) end

Make sure to disable it after debugging as it clutters the log.

The commandArray also supports nested tables to send the same command type multiple times. To do this, give the command a numeric index (not alphanumeric with or without quotes!) and place the required action in a nested table:

 commandArray = {}
 commandArray[1]={['OpenURL']='' }
 commandArray[2]={['OpenURL']='' }
 commandArray[3]={['OpenURL']='' }
 return commandArray

This will run three url commands with separate addresses. Always start the commandarray index at 1; Lua uses 1 based indexes, so commandArray[0] will not run.

Some examples (not meaningful, just to explain what will happen):

 commandArray = {}
 return commandArray

This will turn "Lamp" on 4 times (the last array item overwrites the first).

 commandArray = {}
 return commandArray

This will turn "Lamp" on 3 times (the last array item overwrites the first and the zero index is ignored).

Current state of the event system:

- Not all device states are correctly passed to Lua at the moment, but the most common ones like On/Off, Open/Closed are. - There is no check on the command in the commandArray. When you return commandArray['Kitchen light']="Up", we will not indicate that kitchen lights aren't meant to go up. Make sure you pass a valid command for the device.

Unfortunately, Domoticz doesn't report which device changed state thereby causing a script_device_xxx.lua script to run. However the devicechanged table gives the game away. The following can be used to identify which device was the culprit so include it at the beginning of your device scripts:

 logging = true
 d = otherdevices
 device = ""
 for i, v in pairs(devicechanged) do
   if (#device == 0 or #i < #device) then device = i end
 if (logging) then print("Triggered by " .. device .. " now " .. d[device]) end

Subsequently, you can use something like the following to decide what to do next:

 if (device == "PIR_1" or device == "PIR_2" or device == "PIR_3") then
   if (d[device] == "Motion" and not globalvariables["Security"] == "Disarmed" ) then
   return commandArray
 if (device == "Keyfob" and d[device] == "On") then
   return commandArray

... and so on

The power of Domoticz and Lua can be generalised by writing Smart Lua Scripts, this method of combining a switch naming convention and a Lua script, allows a simple script to be used multiple times and simplifies both the addition and maintenance of further devices.

Post any issues here: <>

Configuring Pushover

To connect Pushover to Domoticz, you need two things:

  • A user key, which can be found on the Pushover website as soon as you have logged in
  • An API-key. This can be made by filling in this wizard:

Fill in both the keys into the correct fields inside Domoticz, and the Pushover notifications should be working.

Configuring Pushsafer

To connect Pushsafer to Domoticz, you need a private or alias key from

  • A private or alias key, which can be found on the Pushsafer website as soon as you have logged in
  • private key > send the notification to all devices with standard notification parameter
  • alias key > send the notification to the devices stored in the alias with predefined parameter

Fill in the key into the correct field inside the Domoticz notification settings, and the Pushsafer notifications should be working.

Optionally you can send an image with the push-notification. Simply add an absolute image url, e.g. from an ip camera or a door bell.

Example Image-URL: http://user:[email protected]:8080/snapshot.cgi

Advanced Pushsafer configuration

To customize your notification to your fit, you can enter Pushsafer parameters in the "Custom Message" field.

The following parameters are available and must always be entered separately in this order by a PIPE character.



XXXXXXXXXXXXXXXXXXXX|269|82|6|3|Domoticz|Switch on|http://user:[email protected]:8080/snapshot.cgi||Open Pushsafer|1000
XXXXXXXXXXXXXXX||83|7|1|Domoticz|Switch off|http://user:[email protected]:8080/snapshot.cgi|||

Pushsafer Domoticz:

Pushsafer HowTo:

Pushsafer API: