Skip to content

Latest commit

 

History

History
501 lines (452 loc) · 28.5 KB

QUICKREF.md

File metadata and controls

501 lines (452 loc) · 28.5 KB

Quick Reference Guide

Table of contents

Script structure

A dzVents script has this structure:

return {
    active = true/false,
    -- or:
    active = function(domoticz) return <boolean> end,
    on = {
        <device name>,
        <device id>,
        timer,
        timer = '<timer definition>',
        timer = { '<timer definition1>', '<timer definition2>', .. },
        devices = { '<device name>', '<device name>' , <device id> .. }
    },
    data = {
        var1 = { initial = <initial value> }
        historicalVar1 = {
	        history = true,
	        maxItem = xxx,
	        maxHours = xxx,
	        maxMinutes = xxx,
	        getValue = function (item)
		        return item.....; -- return a number
		    end
    },
    execute = function(domoticz, device, triggerInfo)
		-- check for device == nil for timer events
		-- triggerInfo.type = domoticz.EVENT_TYPE_TIMER  or domoticz.EVENT_TYPE_DEVICE
		-- triggerInfo.trigger = timer rule that triggered the script
    end
}

timer definitions

All times are in 24hr format:

  • every minute: every minute
  • every other minute: minutes: xx:00, xx:02, xx:04, ..., xx:58
  • every <xx> minutes, -- starting from xx:00 triggers every xx minutes (0 > xx < 60)
  • every hour: 00:00, 01:00, ..., 23:00 (24x per 24hrs)
  • every other hour: 00:00, 02:00, ..., 22:00 (12x per 24hrs)
  • every <xx> hours: starting from 00:00, triggers every xx hours (0 > xx < 24)
  • at 13:45: specific time
  • at *:45: every 45th minute in the hour
  • at 15:*: very minute between 15:00 and 16:00
  • at 13:45 on mon,tue: at 13:45 only on Monday en Tuesday (english)
  • every hour on sat: you guessed it correctly
  • at sunset: uses sunset/sunrise info from Domoticz
  • at sunrise
  • at sunset on sat,sun

Domoticz object API

Domoticz attributes:

  • changedDevices: Table. A collection holding all the devices that have been updated in this cycle.
  • devices: Table. A collection with all the device objects. You can get a device by its name or id: domoticz.devices[123] or domoticz.devices['My switch']. See Device object API below.
  • groups: Table: A collection with all the groups.
  • scenes: Table: A collection with all the scenes.
  • security: Holds the state of the security system e.g. Armed Home or Armed Away.
  • time: Current system time:
    • day: Number
    • getISO: Function. Returns the ISO 8601 formatted date.
    • hour: Number
    • isToday: Boolean. Indicates if the device was updated today
    • month: Number
    • min: Number
    • raw: String. Generated by Domoticz
    • rawDate: String. Returns the date part of the raw data.
    • rawTime: String. Returns the time part of the raw data.
    • sec: Number
    • year: Number
    • isDayTime
    • isNightTime
    • sunsetInMinutes
    • sunriseInMinutes
  • variables: Table. A collection holding all the user variable objects as defined in Domoticz. See Variable object API for the attributes.

Domoticz methods

  • email(subject, message, mailTo): Function. Send email.
  • fetchHttpDomoticzData: Function. This will trigger a script that will download the device data from Domoticz and stores this on the filesystem for dzVents to use.
  • log(message, [level]): Function. Creates a logging entry in the Domoticz log but respects the log level settings. You can provide the loglevel: domoticz.LOG_INFO, domoticz.LOG_DEBUG or domoticz.LOG_ERROR. In dzVents_settings.lua you can specify which kind of log message will be printed.
  • notify(subject, message, priority, sound): Function. Send a notification (like Prowl). Priority can be like domoticz.PRIORITY_LOW, PRIORITY_MODERATE, PRIORITY_NORMAL, PRIORITY_HIGH, PRIORITY_EMERGENCY. For sound see the SOUND constants below.
  • openURL(url): Function. Have Domoticz 'call' a URL.
  • sendCommand(command, value): Function. Generic command method (adds it to the commandArray) to the list of commands that are being sent back to domoticz.
  • setScene(scene, value): Function. E.g. domoticz.setScene('My scene', 'On'). Supports timing options. See below.
  • sms(message): Function. Sends an sms if it is configured in Domoticz.
  • switchGroup(group, value): Function. E.g. domoticz.switchGroup('My group', 'Off'). Supports timing options. See below.

Iterators

Available on the collections: devices, variables, scenes, groups:

  • forEach(function( item, key): Executes a provided function once per array element.
  • filter(function( device )): returns items in the collection for which the function returns true.

Contants

  • ALERTLEVEL_GREY,
  • ALERTLEVEL_GREEN,
  • ALERTLEVEL_ORANGE,
  • ALERTLEVEL_RED,
  • ALERTLEVEL_YELLOW: For updating text sensors.
  • BARO_CLOUDY,
  • BARO_CLOUDY_RAIN,
  • BARO_STABLE,
  • BARO_SUNNY,
  • BARO_THUNDERSTORM,
  • BARO_UNKNOWN,
  • BARO_UNSTABLE: For updating barometric values.
  • HUM_COMFORTABLE,
  • HUM_DRY,
  • HUM_NORMAL,
  • HUM_WET: Constant for humidity status.
  • EVENT_TYPE_TIMER,
  • EVENT_TYPE_DEVICE: triggerInfo.type that is passed to execute function.
  • LOG_DEBUG,
  • LOG_ERROR,
  • LOG_INFO: For logging messages.
  • PRIORITY_LOW,
  • PRIORITY_MODERATE,
  • PRIORITY_NORMAL,
  • PRIORITY_HIGH,
  • PRIORITY_EMERGENCY: For notification priority.
  • SECURITY_ARMEDAWAY,
  • SECURITY_ARMEDHOME,
  • SECURITY_DISARMED: For security state.
  • SOUND_ALIEN ,
  • SOUND_BIKE,
  • SOUND_BUGLE,
  • SOUND_CASH_REGISTER,
  • SOUND_CLASSICAL,
  • SOUND_CLIMB ,
  • SOUND_COSMIC,
  • SOUND_DEFAULT ,
  • SOUND_ECHO,
  • SOUND_FALLING ,
  • SOUND_GAMELAN,
  • SOUND_INCOMING,
  • SOUND_INTERMISSION,
  • SOUND_MAGIC ,
  • SOUND_MECHANICAL,
  • SOUND_NONE,
  • SOUND_PERSISTENT,
  • SOUND_PIANOBAR ,
  • SOUND_SIREN ,
  • SOUND_SPACEALARM,
  • SOUND_TUGBOAT ,
  • SOUND_UPDOWN: For notification sounds.
  • EVOHOME_MODE_AUTO,
  • EVOHOME_MODE_TEMPORARY_OVERRIDE
  • EVOHOME_MODE_PERMANENT_OVERRIDE: for EvoHome set point controlling.

Device object API

Device attributes

  • batteryLevel: Number (note this is the raw value from Domoticcz and can be 255). Only available when http fetching is enabled.
  • bState: Boolean. Is true for some common states like 'On' or 'Open' or 'Motion'.
  • barometer: Only when applicable.
  • changed: Boolean. True if the device was changed
  • counterToday: String. Today's counter value for counter devices. Formatted string with unit. Only available when http fetching is enabled.
  • counterTotal: String. Total counter value for counter devices. Formatted string with unit. Only available when http fetching is enabled.
  • description: String. Description of the device. Only available when http fetching is enabled.Only available when http fetching is enabled.
  • deviceSubType: String. Only available when http fetching is enabled.Only available when http fetching is enabled.
  • deviceType: String. Only available when http fetching is enabled.
  • dewpoint: Only when applicable.
  • hardwareName: String. See Domoticz devices table in Domoticz GUI. Only available when http fetching is enabled.
  • hardwareId: Number. Only available when http fetching is enabled.
  • hardwareType: String. Only available when http fetching is enabled.
  • hardwareTypeValue: Number. Only available when http fetching is enabled.
  • heatingMode: String. For zoned thermostats like EvoHome. Only available when http fetching is enabled.
  • humidity: Only when applicable.
  • id: Number. Id of the device
  • lastUpdate:
    • day: Number
    • getISO: Function. Returns the ISO 8601 formatted date.
    • hour: Number
    • hoursAgo: Number. Number of hours since the last update.
    • isToday: Boolean. Indicates if the device was updated today
    • month: Number
    • min: Number
    • minutesAgo: Number. Number of minutes since the last update.
    • raw: String. Generated by Domoticz
    • rawDate: String. Returns the date part of the raw data.
    • rawTime: String. Returns the time part of the raw data.
    • sec: Number
    • secondsAgo: Number. Number of seconds since the last update.
    • year: Number
  • level: Number. For dimmers and other 'Set Level..%' devices this holds the level like selector switches.
  • lux: Number. Lux level for light sensors. Only available when http fetching is enabled.
  • name: String. Name of the device
  • rain: Only when applicable.
  • rainLastHour: Only when applicable.
  • rawData: Table. Raw data passed by Domoticz.
  • signalLevel: String. Only available when http fetching is enabled.
  • setPoint: Number. Holds the set point for thermostat like devices. Only available when http fetching is enabled.
  • state: String. For switches this holds the state like 'On' or 'Off'. For dimmers that are on, it is also 'On' but there is a level attribute holding the dimming level. For selector switches (Dummy switch) the state holds the name of the currently selected level. The corresponding numeric level of this state can be found in the rawData attribute: device.rawData[1]. For groups, the state can be "On", "Off" or "Mixed".
  • switchType: String. See Domoticz devices table in Domoticz GUI. Only available when http fetching is enabled.
  • switchTypeValue: Number. Only available when http fetching is enabled.
  • temperature: Only when applicable.
  • text: Text value of dummy text devices. Only available when http fetching is enabled.
  • timedOut: Boolean. Is true when the device couldn't be reached. Only available when http fetching is enabled.
  • utility: Only when applicable.
  • uv: Only when applicable.
  • weather: Only when applicable.
  • WActual: Number. Current Watt usage. Only available when http fetching is enabled.
  • WhToday: Number. Total Wh usage of the day. Note the unit is Wh and not kWh. Only available when http fetching is enabled.
  • WhTotal: Number. Total Wh (incremental). Only available when http fetching is enabled.
  • winddir: Only when applicable.
  • windgust: Only when applicable.
  • windspeed: Only when applicable.

Device methods

  • attributeChanged(attributeName): Function. Returns a boolean (true/false) if the attribute was changed in this cycle. E.g. device.attributeChanged('temperature').
  • close(): Function. Set device to Close if it supports it. Supports timing options. See below.
  • dimTo(percentage): Function. Switch a dimming device on and/or dim to the specified level. Supports timing options. See below.
  • kodiExecuteAddOn(addonId): Function. Will send an Execute Addon command sending no parameters. Addon IDs are embedded in the addon configuration and are not to be confused with the Addon Name. For example: http://forums.homeseer.com/showthread.php?p=1213403.
  • kodiPause(): Function. Will send a Pause command, only effective if the device is streaming.
  • kodiPlay(): Function. Will send a Play command, only effective if the device was streaming and has been paused.
  • kodiPlayFavorites([position]): Function. Will play an item from the Kodi's Favorites list optionally starting at position. Favorite positions start from 0 which is the default.
  • kodiPlayPlaylist(name, [position]): Function. Will play a music or video Smart Playlist with name optionally starting at position. Playlist positions start from 0 which is the default.
  • kodiSetVolume(level): Function. Set the volume for a Kodi device, 0 <= level <= 100.
  • kodiStop(): Function. Will send a Stop command, only effective if the device is streaming.
  • kodiSwitchOff(): Function. Will turn the device off if this is supported in settings on the device.
  • open(): Function. Set device to Open if it supports it. Supports timing options. See below.
  • setState(newState): Function. Generic update method for switch-like devices. E.g.: device.setState('On'). Supports timing options. See below.
  • stop(): Function. Set device to Stop if it supports it (e.g. blinds). Supports timing options. See below.
  • switchOff(): Function. Switch device off it is supports it. Supports timing options. See below.
  • switchOn(): Function. Switch device on if it supports it. Supports timing options. See below.
  • switchSelector(level): Function. Switches a selector switch to a specific level (numeric value, see the edit page in Domoticz for such a switch to get a list of the values). Supports timing options. See below.
  • update(< params >): Function. Generic update method. Accepts any number of parameters that will be sent back to Domoticz. There is no need to pass the device.id here. It will be passed for you. Example to update a temperature: device.update(0,12). This will eventually result in a commandArray entry ['UpdateDevice']='<idx>|0|12'
  • toggleSwitch(): Function. Toggles the state of the switch (if it is togglable) like On/Off, Open/Close etc.
  • updateAirQuality(quality): Function.
  • updateAlertSensor(level, text): Function. Level can be domoticz.ALERTLEVEL_GREY, ALERTLEVEL_GREE, ALERTLEVEL_YELLOW, ALERTLEVEL_ORANGE, ALERTLEVEL_RED
  • updateBarometer(pressure, forecast): Function. Update barometric pressure. Forecast can be domoticz.BARO_STABLE, BARO_SUNNY, BARO_CLOUDY, BARO_UNSTABLE, BARO_THUNDERSTORM, BARO_UNKNOWN, BARO_CLOUDY_RAIN
  • updateCounter(value): Function.
  • updateCustomSensor(value): Function.
  • updateDistance(distance): Function.
  • updateElectricity(power, energy): Function.
  • updateGas(usage): Function.
  • updateHumidity(humidity, status): Function. Update humidity. status can be domoticz.HUM_NORMAL, HUM_COMFORTABLE, HUM_DRY, HUM_WET
  • updateLux(lux): Function.
  • updateP1(sage1, usage2, return1, return2, cons, prod): Function.
  • updatePercentage(percentage): Function.
  • updatePressure(pressure): Function.
  • updateRain(rate, counter): Function. Update rain sensor.
  • updateSetPoint(setPoint, mode, until): Function. Update set point for dummy thermostat devices, OpenThermGW and EvoHome Zone devices. This uses http json calls to update setpoints so make sure your http settings are correct. For EvoHome devices mode can be domoticz.EVOHOME_MODE_AUTO, EVOHOME_MODE_TEMPORARY_OVERRIDE or EVOHOME_MODE_PERMANENT_OVERRIDE. You can provide an until date (in ISO 8601 format e.g.: os.date("!%Y-%m-%dT%TZ")). Note that there is a bug in the EvoHome code which ignores the time zone so you may have to add/remove some hours depending on your time zone.
  • updateTemperature(temperature): Function. Update temperature sensor.
  • updateTempHum(temperature, humidity, status): Function. For status options see updateHumidity.
  • updateTempHumBaro(temperature, humidity, status, pressure, forecast): Function.
  • updateText(text): Function.
  • updateUV(uv): Function.
  • updateVoltage(voltage): Function.
  • updateWind(bearing, direction, speed, gust, temperature, chill): Function.

Switch timing options (delay, duration)

  • after_sec(seconds): Function. Activates the command after a certain amount of seconds.
  • after_min(minutes): Function. Activates the command after a certain amount of minutes.
  • for_min(minutes): Function. Activates the command for the duration of a certain amount of minutes (cannot be specified in seconds).
  • within_min(minutes): Function. Activates the command within a certain period randomly.

Note that dimTo() doesn't support duration().

Variable object API

User variables created in Domoticz have these attributes and methods:

Variable attributes

  • nValue: Number. value cast to number.
  • value: Raw value coming from Domoticz
  • lastUpdate:
    • day: Number
    • getISO: Function. Returns the ISO 8601 formatted date.
    • hour: Number
    • hoursAgo: Number. Number of hours since the last update.
    • isToday: Boolean. Indicates if the device was updated today
    • min: Number
    • minutesAgo: Number. Number of minutes since the last update.
    • month: Number
    • raw: String. Generated by Domoticz
    • rawDate: String. Returns the date part of the raw data.
    • rawTime: String. Returns the time part of the raw data.
    • sec: Number
    • year: Number

Variable methods

  • set(value): Function. Tells Domoticz to update the variable. No need to cast it to a string first (it will be done for you).

Time object API

You can create dzVents time objects like this:

local Time = require('Time')
local t = Time('2016-12-12 7:35:00')

local tonight = Time(domoticz.time.rawDate .. ' 20:00:00')
print (tonight.getISO())
-- will print something like: 2016-12-12T20:00:00Z

Time Properties:

  • day: Number
  • getISO: Function. Returns the ISO 8601 formatted date.
  • hour: Number
  • hoursAgo: Number. Number of hours since the last update.
  • isToday: Boolean. Indicates if the device was updated today
  • month: Number
  • min: Number
  • minutesAgo: Number. Number of minutes since the last update.
  • raw: String. Generated by Domoticz
  • rawDate: String. Returns the date part of the raw data.
  • rawTime: String. Returns the time part of the raw data.
  • sec: Number
  • secondsAgo: Number. Number of seconds since the last update.
  • year: Number

Persistent data

Script level persistent variables

Script level persistent variables are created in the data section of your script:

data = {
       var1 = { initial = <initial value> }
       historicalVar1 = {
	        history = true,
	        maxItem = xxx,
	        maxHours = xxx,
	        maxMinutes = xxx,
	        getValue = function (item)
		        return item.....; -- return a number
		    end
		},
}

Access these variables in the execute block of your script:

    execute = function(domoticz, switch)
	    domoticz.data.var1 = 'new value'
	    print(domoticz.data.var1)
    end

Global persistent variables

Create a file global_data.lua with this structure:

    return {
    	data = {
    		globalvar1 = { initial = false },
    		globalvar2 = { initial = false },
    		...
    	}
    }

Access these globals in your scripts:

	execute = function(domoticz, device)
		domoticz.globalData.globalvar1 = 10
		print(domoticz.globalData.globalvar2)
    }

Persistent variables with historical data

Define like this in your script with history = true:

data = {
       historicalVar1 = {
	        history = true,
	        maxItem = xxx,
	        maxHours = xxx,
	        maxMinutes = xxx,
	        getValue = function (item)
		        return item.....; -- return a number
		    end
		},
}
  • maxItems: Number. Controls how many items are stored in the variable. maxItems wins over maxHours and maxMinutes.
  • maxHours: Number. Data older than maxHours from now will be discarded. So if you set it to 2 than data older than 2 hours will be removed at the beginning of the script.
  • maxMinutes: Number. Same as maxHours but, you guessed it: for minutes this time.

Adding a new value

When you defined your historical variable you can add a new value to the list like this:

domoticz.data.myVar.add(value)

Getting

local item = domoticz.data.myVar.get(5)
print(item.data) -- the stored value
print(item.time.minutesAgo) -- minutes ago since the 5 item was stored

The time attribute by itself is a table with many properties that help you inspect the data points more easily:

  • day: Number.
  • getISO: Function. Returns the ISO 8601 formatted date.
  • hour: Number
  • isToday: Boolean.
  • month: Number
  • min: Number
  • minutesAgo: Number. How many minutes ago from the current time the data was stored.
  • raw: String. Formatted time.
  • rawDate: String. Returns the date part of the raw data.
  • rawTime: String. Returns the time part of the raw data.
  • sec: Number
  • secondsAgo: Number. Number of seconds since the last update.
  • year: Number
  • utcSystemTime: Table. UTC system time:
    • day: Number
    • hour: Number
    • month: Number
    • min: Number
    • sec: Number
    • year: Number
  • utcTime: Table. Time stamp in UTC time:
    • day: Number
    • hour: Number
    • month: Number
    • min: Number
    • sec: Number
    • year: Number

API

  • add( data ): Adds new data to the set. The data is added to the set and is time-stamped.
  • avg( [fromIdx], [toIdx], [default] ): Calculates the average of all item values within the range fromIdx to toIdx. You can specify a default value for when there is no data in the set.
  • avgSince( timeAgo, default ): Calculates the average of all data points since timeAgo. Returns default if there is no data. E.g.: local avg = myVar.avgSince('00:30:00') returns the average over the past 30 minutes.
  • delta( fromIdx, toIdx, [smoothRange], [default] ): Returns the delta (difference) between items specified by fromIdx and toIdx. You have to provide a valid range (no nil values). Supports data smoothing when providing a smoothRange value. Returns default if there is not enough data.
  • deltaSince( timeAgo, [smoothRange], [default] ): Same as delta but now within the timeAgo interval.
  • get( [idx] ): Returns the idx-th item in the set. Same as myVar.storage[idx].
  • getAtTime( timeAgo ): Returns the data point closest to the moment as specified by timeAgo. So myVar.getAtTime('1:00:00') returns the item that is closest to one hour old. So it may be a bit younger or a bit older than 1 hour.
  • filter(function): Create a filtered set of items. The function receives the item and returns true if the item should be in the result set. E.g. get a set with item values larger than 20: subset = myVar.filter( function (item) return (item.data > 20) end ).
  • find(function): Search for a specific item in the set: E.g. find the first item with a value higher than 20: local item = myVar.find( function (item) return (item.data > 20) end ).
  • forEach(function): Loop over all items in the set: E.g.: myVar.forEach( function( item, index, collection) ... end )
  • getLatest( ): Returns the youngest item in the set. Same as print(myVar.get(1).data).
  • getOldest( ): Returns the oldest item in the set. Same as print(myVar.get(myVar.size).data).
  • localMin( [smoothRange], default ): Returns the first minimum value (and the item holding the minimal value) in the past. Supports data smoothing.
  • localMax([smoothRange], default): Same as localMin but now for the maximum value. Supports data smoothing when providing a smoothRange value.
  • max( [fromIdx], [toIdx] ): Returns the highest value in the range defined by fromIdx and toIdx.
  • maxSince( timeAgo ): Same as max but now within the timeAgo interval.
  • min( [fromIdx], [toIdx] ): Returns the lowest value in the range defined by fromIdx and toIdx.
  • minSince( timeAgo ): Same as min but now within the timeAgo interval.
  • size: Return the amount of data points in the set.
  • subset( [fromIdx], [toIdx] ): Returns a subset of the stored data. If you omit fromIdx then it starts at 1. If you omit toIdx then it takes all items until the end of the set (oldest). So myVar.subset() returns all data. The result set supports forEach, filter, find and reduce.
  • subsetSince( [timeAgo] ): Returns a subset of the stored data since the relative time specified by timeAgo. The result set supports forEach, filter, find and reduce.
  • reduce(function, initial): Loop over all items in the set and do some calculation with it. You call reduce with the function and the initial value. Each iteration the function is called with the accumulator. The function does something with the accumulator and returns a new value for it.
  • reset( ): Removes all the items from the set.
  • smoothItem(itemIdx, [smoothRange]): Returns a the value of itemIdx in the set but smoothed by averaging with its neighbors. The amount of neighbors is set by smoothRange. See About data smoothing.
  • sum( [fromIdx], [toIdx] ): Returns the summation of all values in the range defined by fromIdx and toIdx.
  • sumSince( timeAgo ): Same as sum but now within the timeAgo interval.

Settings

  • Domoticz ip: Number. IP-address of your Domoticz instance.

  • Domoticz port: Number. Port number used to contact Domoticz over IP.

  • Enable http fetch: Boolean: Controls wether or not dzVents will fetch device data using http.

  • Fetch interval: String. Default is 'every 30 minutes' but you can increase this if you need more recent values in your device objects. See timer trigger options.

  • Log level: Number.

  • Log level: Number:

    • 1: Errors,
    • 1.5: Errors + info about the execution of individual scripts and a dump of the commands sent back to Domoticz,
    • 2: Errors + info
    • 3: Debug info + Errors + Info
    • 0: As silent as possible.

    This part is stil a bit experimental and may not give you all the information you need in the logs. Besides, Domoticz tends to choke on too many log messages and may decide not to show them all. You can alway put a print statement here or there or use the domoticz.log() API (see Domoticz object API).