Luup Lua extensions

From MiOS
Revision as of 21:45, 19 May 2012 by Micasaverde (Talk | contribs)

Jump to: navigation, search

In addition to the [Lua] commands described in the [Lua reference manual], you can also reference in your Lua code variables and functions from modules which the Luup engine provides as follows:


Module: luup

These are general purpose functions and variables. Call them by using the luup. module, such as:

luup.log('Now running version: ' .. luup.version)

variable: device

The ID of this device instance, if it's running as part of a device

variable: version, version_branch, version_major, version_minor

version contains the version of the luup engine, such as "1.0.843", as a string. The version consists of 3 numbers separated by a period: the branch, the major version, and the minor version. To make it easier to compare against a minimum acceptable version, version_branch, version_major and version_minor return each component as a number. You can put a comparison in the startup function in your Luup plugin and return false if the minimum version isn't met. The user will then see that the Luup device's startup check failed:

if( version_branch ~= 1 or version_major ~= 0 or version_minor < 843 ) then
    luup.log("I need version 1.0.843 minimum to run")
    return false

variable: longitude

Contains the longitude as a number, as found on the location tab in the setup UI.

variable: latitude

Contains the latitude as a number, as found on the location tab in the setup UI.

variable: timezone

Contains the timezone as a number of hours offset from UTC, as found on the location tab in the setup UI. It accounts for DST, so, for example, Pacific Standard time will be -8 or -9 depending on DST.

Note: Contains 0 for MiOS < 1.5.250 (Vera V2) / < 1.5.249 (Vera V3).

variable: city

Contains the city as a string, as found on the location tab in the setup UI.

variable: devices

Contains all the devices in the system as a table indexed by the device number.

The members are:

  • room_num: (number) This is the number of the room the device is in.
  • device_type: (string) This is a string representing the type of the device.
  • category_num: (number) This is a category for the device. See: Luup_Device_Categories for a list.
  • device_num_parent: (number) This is the number of the parent device. See: Lua Device Structure for details.
  • ip: (string) If this device is IP based, this is the IP address.
  • mac: (string) If this device is IP based, this is the MAC address.
  • user: (string) If this device is IP based and requires http authentication, this is the username
  • pass: (string) If this device is IP based and requires http authentication, this is the password
  • id: (string) If this device has an internal ID that is specific to the device, it is contained here. For example, for Z-Wave devices this is the Node ID, and for Insteon device it is the Insteon ID.
  • embedded: (boolean) If this device is embedded, it means that it doesn't have its own room or exist as a separate device. It should be considered part of its parent. Like a 3-in-1 sensor is a device with 3 embedded child devices.
  • hidden: (boolean) If true the user checked the 'hidden' box and doesn't want to see the device on the dashboard.
  • invisible: (boolean) If true the device is 'for internal use only' and shouldn't be presented to the user.
  • description: (string) This is the text description for the device as supplied by the user in the web UI.
  • udn: (string) This is the UDN for the UPnP device.

Example to log device #5's IP addess and its internal ID:

luup.log('Device #5 ip: ' .. luup.devices[5].ip .. ' id: ' .. luup.devices[5].id)

This code will log all the attributes from all the devices:

for k, v in pairs(luup.devices) do
    for k2, v2 in pairs(v) do
        luup.log("Device #" .. k .. ":" .. k2 .. "=" .. "v2")

variable: rooms

Contains all the rooms as a table of strings indexed by the room number. Example:

luup.log('Room #1 is called: ' .. luup.rooms[1])

variable: scenes

Contains all the scenes in the system as a table indexed by the scene number. The members are: room_num (number), description(string), hidden(boolean)

variable: remotes

Contains all the remotes in the system as a table indexed by the remote id. The members are: remote_file (string), room_num (number), description(string)

function: log

parameters: what_to_log (string), log_level (optional, number)

return: nothing

Writes what_to_log to the log, /var/log/cmh/LuaUPnP.log, with the given log_level, which is 50 by default. See: Luup Loglevels

function: task

parameters: message (string), status (number), description (string), handle (number)

return: handle (number)

When the Luup engine is starting status messages are displayed for the various modules as they're initialized. Normally each device, including Luup devices, automatically log their status and the user is shown an error if the device doesn't start, such as if the 'startup' function returns an error.

If you have other startup sequences which you want the user to see to know that startup hasn't finished yet, call this function passing in a handle of -1 for the first call. The status should be: 1=Busy, 2=Error, 4=Successful. Message is the current state, such as 'downloading', and description describes the module, like 'Smartphone UI'. After the first call, store the handle and pass it on future calls to update the status rather than add a new one.

function: call_delay

parameters: function_name (string), seconds (number), data (string), thread (bool)

returns: result (number)

The function function_name (the first parameter), which must be passed as a string, will be called in seconds seconds (the second parameter), and will be passed the string data. The function returns 0 if successful. See: Luup Declarations#timed_function_callback for the names and syntax of the parameters that will be passed to function_name. function_name will only be called once and you must call call_delay again if you want it called again, or use call_timer instead.

If thread is specified and is true or 1, the call back will be made in it's own thread and can block if needed. Normally it is called by a worker thread and is expected to return immediately.

As of December 19, 2011, for all builds after 1.5.237, the 'thread' will be ignored. Each Lua state has its own worker thread now, so all calls to call_delay and call_timer will occur in a separate thread.

function: call_timer

parameters: function_name (string), type (number), time (string), days (string), data (string)

returns: result (number)

The function 'function_name', which must be passed as a string, will be called when the timer is triggered, and will be passed the string 'data'. The function returns 0 if successful. See: Luup Declarations#timed_function_callback for the names and syntax of the parameters that will be passed to function_name.

Type is 1=Interval timer, 2=Day of week timer, 3=Day of month timer, 4=Absolute timer. For an interval timer, days is not used, and Time should be a number of seconds, minutes, or hours using an optional 'h' or 'm' suffix. Example: 30=call in 30 seconds, 5m=call in 5 minutes, 2h=call in 2 hours. For a day of week timer, Days is a comma separated list with the days of the week where 1=Monday and 7=Sunday. Time is the time of day in hh:mm:ss format. Time can also include an 'r' at the end for Sunrise or a 't' for Sunset and the time is relative to sunrise/sunset. For example: Days="3,5" Time="20:30:00" means your function will be called on the next Wed or Fri at 8:30pm. Days="1,7" Time="-3:00:00r" means your function will be called on the next Monday or Sunday 3 hours before sunrise. Day of month works the same way except Days is a comma separated list of days of the month, such as "15,20,30". For an absolute timer, Days is not used, and Time should be in the format: "yyyy-mm-dd hh:mm:ss"

Data can be a string passed back to the function. The function should be declared so it takes a single argument, which is this data.

function refreshCache(stuff)
function startup()
    -- Setup an interval-based timer to call refreshCache after 30 minutes.
    -- Note that if you want it to "recur" then you need to call this function again
    -- at the end of the refreshCache() implementation.
    luup.call_timer("refreshCache", 1, "30m", "", "SomeStuff")

function: is_ready

parameters: device (string or number)

returns: ready (boolean)

version: UI5 and above

Checks whether a device has successfully completed it's startup sequence. If so, is_ready returns true. If your device shouldn't process incoming data until the startup sequence is finished, you may want to add a condition to the <incoming> block that only processes data if is_ready(lul_device) is true.

The device parameter, if it's a string, is interpreted as a udn. If it's a number, it's interpreted as a device number.

    if (luup.is_ready(lul_device) == false) then

function: call_action

parameters: service (string), action (string), arguments (table), device (string or number)

returns: error (number), error_msg (string), job (number), arguments (table)

Invokes the UPnP service + action, passing in the arguments (table of string->string pairs) to the device, which, if it's a string, is interpreted as a udn, and if it's a number, is the device number. If the invocation could not be made, only error will be returned with a value of -1. Otherwise, all 4 values are returned. error is 0 if the UPnP device reported the action was successful. arguments is a table of string->string pairs with the return arguments from the action. If the action is handled asynchronously by a Luup job, then the job number will be returned as a positive integer.

Example to dim device #5 to 50%:

local lul_arguments = {}
lul_arguments["newLoadlevelTarget"] = 50
lul_resultcode, lul_resultstring, lul_job, lul_returnarguments = luup.call_action("urn:upnp-org:serviceId:Dimming1",
                                                                                  "SetLoadLevelTarget", lul_arguments,

function: variable_set

parameters: service (string), variable (string), value (string), device (string or number), [startup (bool)]

returns: nothing

The UPnP service+variable will be set to value for device, which if it's a string, is interpreted as a udn, and if it's a number, as a device id. If there are events or notifications tied to the variable they will be fired.

Optionally, you can add an argument 'startup'. If startup is true, this change will be considered a startup value, and if the variable is set to it's existing value, events and notifications will not be fired.

function: variable_get

parameters: service (string), variable (string), device (string or number)

returns: value (string), time (number)

If the service+variable or device does not exist, it returns nothing. Otherwise it returns the value of the UPnP service+variable and the time when the variable was last modified, as a unix time stamp (number of seconds since 1/1/1970). You can assign just the value to a variable, as follows:

local value = luup.variable_get("urn:upnp-org:serviceId:Dimming1", "LoadLevelTarget", 5)
luup.log("Dim level for device #5 is: " .. value)

function: attr_set

parameters: attribute (string), value(string), device (string or number)

returns: none

Sets the top level attribute for the device to value. Examples of attributes are 'mac', 'name', 'id', etc.

function: attr_get

parameters: attribute (string), device (string or number)

returns: string or none

Gets the top level attribute for the device. Examples of attributes are 'mac', 'name', 'id', etc. If the attribute doesn't exist, it returns nothing. If nothing is passed in for device, it gets the top level attribute from the master userdata, like firmware_version.

function: register_handler

parameters: function_name (string), request_name (string)

returns: nothing

When a certain URL is requested from a web browser or other HTTP get, function_name will be called and whatever string it returns will be returned.

See the WAP mobile phone plugin as an example:

function lug_WapRequest (lul_request, lul_parameters, lul_outputformat)
    local lul_html = "<head>\n" ..
                     "<title>Main</title>\n" ..
                     "</head>\n" ..
                     "<body>\n" ..
                     "Choose a room:<br/>\n"
    return lul_html

The request is made with the URL: data_request?id=lr_[the registered name] on port 49451. So: will return the web page defined in the function lug_WapRequest in the example above.

function: variable_watch

parameters: function_name (string), service (string), variable (string or nil), device (string or number)

returns: nothing

Whenever the UPnP variable is changed for the specified device, which if a string is interpreted as a UDN and if a number as a device ID, function_name will be called. See Luup Declarations#watch_callback for the values that will be passed to function_name. If variable is nil, function_name will be called whenever any variable in the service is changed.

function: devices_by_service



function: device_supports_service

parameters: service ID (string), device (string or number)

returns: true if the device supports the service, false otherwise

A device supports a service if there is at least a command or state variable defined for that device using that service. Setting UPnP variables is unrestricted and free form, and the engine doesn't really know if a device actually uses it or does anything with it. So this function isn't really definitive.

function: set_failure

parameters: value (boolean), device (string or number)


Luup maintains a 'failure' flag for every device to indicate if it is not functioning. You can set the flag to true if the device is failing. If device is a string it is interpreted as a udn, if it's a number, as a device id.

function: is_night

parameters: none

returns: boolean

Returns true if it's past sunset and before sunrise.

function: sleep

parameters: number of milliseconds

returns: none

Sleeps a certain number of milliseconds

Warning: luup.sleep doesn't work reliably:

function: sunset / sunrise

parameters: none

returns: The next sunset / sunrise in a Unix timestamp (i.e. the number of seconds since 1/1/1970 in UTC time). You can do a diff with os.time to see how long it will be for the next event. luup.sunset-os.time is the number of seconds before the next sunset. Be sure the location and timezone are properly set or the sunset/sunrise will be wrong.

Firmware required: 1.5.353

Module: luup.inet

function: wget

parameters: URL (String), Timeout (Number), Username (String), Password (String)

returns httpStatusCode (Number), content (String)

This reads the URL and returns 2 variables: the first is a numeric error code which is 0 if successful, and the second is a string containing the contents of the page. If Timeout is specified, the function will timeout after that many seconds. The default value for Timeout is 5 seconds. If Username and Password are specified, they will be used for HTTP Basic Authentication.

Module: luup.chdev

Contains functions for a parent to synchronize its child devices. Whenever a device has multiple end-points, the devices are represented in a parent/child fashion where the parent device is responsible for reporting what child devices it has and giving each one a unique id. For example in the sample Luup Somfy Walkthrough there is a parent device, which is the interface module that controls up to 16 blinds, and up to 16 child devices, one for each blind. As shown in that sample, the parent calls start, then enumerates each child device with append, and finally calls sync. You will need to pass the same value for device to append and sync that you passed to start.

function: start

parameters: device (string or number)

returns: ptr (binary object)

Tells Luup you will start enumerating the children of device. If device is a string it is interpreted as a udn, if it's a number, as a device id. The return value is a binary object which you cannot do anything with in Lua, but you do pass it to the append and sync functions.

function: append

parameters: device (string or number), ptr (binary object), id (string), description (string), device_type (string), device_filename (string), implementation_filename (string), parameters (string), embedded (boolean) [, invisible (boolean)]

returns: nothing

Adds one child to device. If device is a string it is interpreted as a udn, if it's a number, as a device id.

Pass in the ptr which you received from the luup.chdev.start call. Give each child a unique id so you can keep track of which is which. You can optionally provide a description which the user sees in the user interface.

device_type is the UPnP device type, such as urn:schemas-upnp-org:device:BinaryLight:1.

If device_filename is specified, that is the name of the XML file with the UPnP device specification. The deviceType from the filename will override any device_type you set manually. If the device_file contains the implementation file for this child device you do not need to specify it in implementation_filename. Otherwise, if there is a Luup implementation for this child device and it's not being handled by the parent device, you can specify it in implementation_filename.

If embedded is true, the 'embedded' flag is set for the device which generally means that the parent and all the children will be displayed as one compound device, or group, rather than as separate devices which you can put in their own rooms.

The parameters are UPnP service,variables you want set when the device is created. You can specify multiple variables by separating them with a line feed (\n) and use a , and = to separate service, variable and value, like this: service,variable=value\nservice...

luup.chdev.append(device, children,
    string.format("Input-%d", i), string.format("Input %d", i),
    "urn:schemas-micasaverde-com:device:TemperatureSensor:1", "D_TemperatureSensor1.xml",
    "", "urn:upnp-org:serviceId:TemperatureSensor1,CurrentTemperature=50", true)

function: sync

parameters: device (string or number), ptr (binary object),

returns: nothing

If device is a string it is interpreted as a udn, if it's a number, as a device id. Pass in the ptr which you received from the start function. Tells the Luup engine you have finished enumerating the child devices. If the child devices have changed in any way, the new device tree will be written to the configuration file and the Luup engine is reset.

Module: io

function: open

parameters: device (string or number), ip (string) port (number),

returns: nothing

If 'device' is a string it is interpreted as a UDN; if it's a number, as a device ID. This opens a socket on 'port' to 'ip' and stores the handle to the socket in 'device'. The opening of a socket can take time depending on the network, and a Luup function should return quickly whenever possible because each top-level device's Lua implementation runs in a single thread. So the actual opening of the socket occurs asynchronously and this function returns nothing. You will know that the socket opening failed if your subsequent call to write fails.

Generally you do not need to call the open function because the socket is usually started automatically when the Luup engine starts. This is because the user typically either (a) associates a device with the destination io device, such as selecting an RS232 port for an alarm panel, where the RS232 is proxied by a socket, or (b) because the configuration settings for the device already include an IP address and port.

function: write

parameters: data (string), device (string or number)

returns: result (boolean)

In Lua a string can contain binary data, so data may be a binary block. If 'device' is a string it is interpreted as a UDN; if it's a number, as a device ID. This sends data on the socket that was opened automatically or with the open function above, and associated to 'device'. If the socket is not already open, write will wait up to 5 seconds for the socket before it returns an error. Result is 'true' if the data was sent successfully, and is 'false' or nill if an error occurred.

function: intercept

parameters: device (string or number)

returns: nothing

Normally when data comes in on a socket (I/O Port), the block of data is first passed to any pending jobs that are running for the device and are marked as 'waiting for data'. If there are none, or if none of the jobs' incoming data handlers report that they consumed (i.e. processed) the data, then the block of data is passed to the general 'incoming' function handler for the device. If you want to bypass this normal mechanism and read data directly from the socket, call intercept first to tell Luup you want to read incoming data with the read function. This is generally used during the initialization or startup sequences for devices. For example, you may need to send some data (a), receive some response (b), send some more data (c), receive another response (d), etc. In this case you would call 'intercept' first, then send a, then call read and confirm you got b, then call intercept again, then send c, then read d, and so on.

You can call the read function without calling intercept and any incoming data will be returned by that function after it's called. The reason why you generally must call intercept is because normally you want to send some data and get a response. If you write the code like this send(data) data=read() then it's possible the response will arrive in the brief moment between the execution of send() and read(), and therefore get sent to the incoming data handler for the device. Intercept tells Luup to buffer any incoming data until the next read, bypassing the normal incoming data handler. So intercept() send(data) data=read() ensures that read will always get the response. If the device you're communicating with sends unsolicited data then there's the risk that the data you read is not the response you're looking for. If so, you can manually pass the response packet to the incoming data handler.

    • TBD: Add a function to do this**

function: read

parameters: timeout (number), device (string or number)

returns: data (string)

This reads a block of data from the socket. You must have called intercept previously so the data is passed. The time unit for timeout is seconds.

function: is_connected

parameters: device (string or number)

returns: connected (boolean)

This function returns true if there is a valid IO port connected, otherwise returns false

Module: luup.job

function: status

parameters: job_number (number), device (string or number)

returns: job_status (number), notes (string)

If job_number is invalid the function returns -1. If device is a string it is interpreted as an UDN, if it's a number, as a device ID.

This is the list with all job statuses and their meaning:

  • -1: No job, i.e. job doesn't exist.
  • 0: Job waiting to start.
  • 1: Job in progress.
  • 2: Job error.
  • 3: Job aborted.
  • 4: Job done.
  • 5: Job waiting for callback. Used in special cases.
  • 6: Job requeue. If the job was aborted and needs to be started, use this special value.
  • 7: Job in progress with pending data. This means the job is waiting for data, but can't take it now.

function: set

parameters: job (userdata), setting (string), value (string)

returns: nothing

This stores a setting for a job.

    luup.job.set(lul_job, "comments", "In progress...")
    local comments = luup.job.setting(lul_job, "comments")
    luup.log("job comments = " .. comments)

function: setting

parameters: job (userdata), setting (string)

returns: value (string)

This returns a setting for a job.

Personal tools