• No results found

Control4 Driver Works SDK - Driver Works API Reference Guide

N/A
N/A
Protected

Academic year: 2021

Share "Control4 Driver Works SDK - Driver Works API Reference Guide"

Copied!
62
0
0

Loading.... (view fulltext now)

Full text

(1)

Control4 DriverWorks Software

Development Kit

(2)

Control4 DriverWorks SDK – API Reference Guide Page 2 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

The information contained in this document is the intellectual property of

Control4 Technologies. The holder of this document shall keep all

information contained herein confidential and shall protect this

information in whole or in part from disclosure to any and all third parties

except as specifically authorized in writing by Control4 Technologies.

Disclaimer

Control4® makes no representations or warranties with respect to this publication, and specifically disclaims any express or implied warranties of merchantability or fitness for any particular purpose. Control4 reserves the right to make changes to any and all parts of this publication at any time, without any obligation to notify any person or entity of such changes.

Trademarks

Control4 and the Control4 logo and DriverWorks are trademarks or registered trademarks of Control4 Corporation. Other product and company names mentioned in this document may be the trademarks or registered trademarks of their respective owners.

Copyright

Copyright © 2004-2009 Control4. All rights reserved. No part of this publication may be reproduced, photocopied, stored on a retrieval system, or transmitted without the express written consent of the publisher.

Contact Us

Control4 Corporation 11734 S. Election Road Salt Lake City, UT 84020 USA http://www.control4.com

(3)

Control4 DriverWorks SDK – API Reference Guide Page 3 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

Table of Contents

Table of Contents ... 3

 

1.0 Proxy Interface ... 8

 

SendToProxy ... 8 

ReceivedFromProxy ... 9 

1.1 Director Command Interface ... 10

 

ExecuteCommand ... 10  GetVersionInfo ... 11  GetUniqueMAC ... 11 

1.2 Serial/Network/Device Interface ... 11

  SendToSerial... 11  ReceivedFromSerial ... 12  SendToNetwork ... 13  ReceivedFromNetwork ... 13  NetConnect ... 14  NetDisconnect ... 14  OnConnectionStatusChanged ... 14  OnNetworkBindingChanged ... 15  SendToDevice ... 15 

1.3 Variable Interface ... 17

  AddVariable ... 17  SetVariable ... 17  DeleteVariable ... 18  OnVariableChanged ... 18 

DriverWorks Variables Table ... 18 

GetVariable ... 19  GetDeviceVariable ... 19  SetDeviceVariable ... 19  RegisterVariableListener ... 20  UnregisterVariableListener ... 21  OnWatchedVariableChanged ... 21 

1.4 Timer Interface ... 22

  AddTimer ... 22  KillTimer ... 22  OnTimerExpired... 23  OnDriverDestroyed ... 23 

(4)

Control4 DriverWorks SDK – API Reference Guide Page 4 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

1.5 Event Interface ... 24

  FireEvent ... 24 

1.6 IR Interface ... 24

  SendIR ... 24  SendIRStart ... 24  SendIRStop ... 25 

1.7 Properties Interface ... 25

  UpdateProperty ... 25  OnPropertyChanged ... 25 

DriverWorks Properties Table ... 26 

1.8 Log Interface ... 27

 

DebugLog ... 27 

ErrorLog ... 28 

1.9 Miscellaneous ... 28

 

DriverWorks PersistData Table ... 28 

GetDeviceID ... 28  GetCapability ... 28  OnBindingChanged ... 29  AddDynamicBinding ... 29  RemoveDynamicBinding ... 31  Base64Encode ... 31  Base64Decode ... 31  OnPoll ... 32  XMLEscapeString ... 32  CRC32 ... 33  TEAEncrypt ... 33  TEADecrypt ... 33  ntoh_l ... 34  hton_l ... 34  GetProxyDevices ... 35 

1.10 Helper Functions ... 35

  Print ... 35  tohex ... 36  hexdump ... 36 

1.11 Debug Interface Section ... 36

 

EnableRemoteDebugging ... 36 

DisableRemoteDebugging ... 37 

(5)

Control4 DriverWorks SDK – API Reference Guide Page 5 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

OnEndDebugSession ... 37 

1.12 Media Management - Generic ... 38

 

MediaRemoveAllMedia ... 38 

MediaSetDeviceContext ... 38 

MediaGetDeviceContext ... 38 

1.13 Media Management – Movies ... 39

 

MediaAddMovieInfo ... 39  MediaGetMovieInfo ... 39  MediaGetMovieLocation ... 40  MediaGetAllMovies ... 40  MediaRemoveMovie... 40  MediaRemoveAllMovies ... 40  MediaModifyMovieInfo ... 41 

1.14 Media Management – Albums ... 42

 

MediaAddAlbumInfo ... 43  MediaGetAlbumInfo ... 43  MediaGetAlbumLocation ... 43  MediaGetAllAlbums ... 44  MediaRemoveAlbum ... 44  MediaRemoveAllAlbums ... 44  MediaModifyAlbumInfo ... 45 

1.15 Media Management – Songs ... 45

 

MediaGetSongInfo ... 45  MediaGetSongLocation ... 45  MediaRemoveSong... 46  MediaLinkSongToAlbum ... 46  MediaGetSongsforAlbum ... 46  MediaModifySongInfo ... 46 

1.16 List Navigator Functionality ... 48

 

ListSetCapabilities... 48  ListStart ... 49  ListStop ... 49  ListGetItems ... 50  ListSendCommand ... 50  ListGetRoomID ... 51  ListGoToRoot ... 51  ListIsStarted ... 51  ListIsInNavigation ... 51  ListNewList ... 53  ListMIBReceived ... 53  ListNewControl ... 54 

(6)

Control4 DriverWorks SDK – API Reference Guide Page 6 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

ListEvent ... 55 

Encoded Item Values ... 56

 

DriverWorks and Zigbee Functionality ... 57

 

Send/Receive Data from Zigbee ... 57 

SendZigbeePacket ... 57 

OnZigbeePacketIn... 58 

OnZigbeePacketSuccess ... 59 

OnZigbeePacketFailed ... 59 

OnZigbeeOnlineStatusChanged ... 60 

Updating Zigbee Device firmware Using DriverWorks ... 60 

Encoded BLOB data in the .c4i file ... 60 

GetBlobByName ... 61  RequestReflashLock ... 62  KeepReflashLock ... 62  ReleaseReflashLock ... 62  OnReflashLockGranted ... 62  OnReflashLockRevoked ... 62 

(7)

Control4 DriverWorks SDK – API Reference Guide Page 7 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

Control4 DriverWorks SDK Reference Guide

Description

The Control4 DriverWorks SDK can be used to create two-way serial and network drivers for third party devices. A DriverWorks driver is completely

defined by a .c4i file that is not compiled by the driver creator before it is used by the Control4 system. An embedded Lua interpreter exists on the Control4

Controller that executes the Lua code found within the .c4i file.

How do I learn about DriverWorks in order to write a driver?

There are two reference materials from Control4 that you will find useful:

1. Getting Started with DriverWorks explains the basic concepts and how to get started with the development of a DriverWorks driver. This is not an exhaustive reference document but is intended to teach you what you need to know to get started.

2. DriverWorks Reference Guide (this document) – this guide documents all APIs available through DriverWorks. This is required reference

material for driver creators.

In addition to this source material, you may benefit from referencing material on In addition to this source material, you may benefit from referencing material on Lua.

Official Lua Website http://www.lua.org

Lua FAQ http://lua-users.org/wiki/LuaFaq

Programming In Lua (online version) http://www.lua.org/pil/

Lua 5.1 Reference Manual http://www.lua.org/manual/5.1/

Lua vs. Other Languages http://lua-users.org/wiki/LuaComparison

Lua Testimonials http://www.lua.org/quotes.html

Lua Wikipedia Entry http://en.wikipedia.org/wiki/Lua

1996 DDJ article on Lua goals and purposes: http://www.lua.org/ddj.html

Note: Some of the functions used in the samples found in this section use “C4:”as a

prefix, for example: C4:SendToProxy. Other functions do not use the “C4:” prefix, for example ReceivedFromProxy. Functions that DriverWorks drivers call utilize the “C4:” Functions that are called by Director, do not.

(8)

Control4 DriverWorks SDK – API Reference Guide Page 8 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

1.0 Proxy Interface

SendToProxy

C4:SendToProxy(idBinding, strCommand, tParams, strmessage)

or

C4:SendToProxy(idBinding, strCommand, strParam)

Function called from DriverWorks driver to send a Control4 BindMessage to the proxy bound to the specified binding.

Returns None Parameters

idBinding - Binding ID for the proxy you wish to send to strCommand - Command to send to the proxy

tParams - Lua table containing parameters to the command.

TBD: Show how to send things other than strings or numbers, which are auto-converted.

Strmessage - COMMAND or NOTIFY – Overrides the default message type that SendToProxy will send by default. SendToProxy will send a NOTIFY if it is equal to or more than a 1000 and a Command if it is less than a 1000.

Examples

C4:SendToProxy(11, "CLOSED", {})

Notify the attached contact binding that the contact has closed. Note that tParams is required, if there are no parameters, send an empty Lua table. C4:SendToProxy(5001, "TEMPERATURE_CHANGED", {TEMPERATURE = 76}) Notify the attached thermostat binding that the temperature is now 76. C4:SendToProxy(5001, "DISPLAY_TEXT", "<text>SYSTEM ARMED</text>") Send the ‘System Armed’ text to the attached security proxy Display Text. or:

C4:SendToProxy(idBinding, strCommand, strParam)

Function called from DriverWorks driver to send a Control4 BindMessage to the proxy bound to the specified binding. This version sends a single parameter to the Proxy, not a set of Key/Value pairs of parameters. Returns

None Parameters

idBinding - Binding ID for the proxy you wish to send to strCommand - Command to send to the proxy

strParam - String containing single parameter to the command. Examples

C4:SendToProxy(5001, "DISPLAY_TEXT", "<text>SYSTEM ARMED</text>") Send the ‘System Armed’ text to the attached security proxy Display Text.

(9)

Control4 DriverWorks SDK – API Reference Guide Page 9 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

ReceivedFromProxy

ReceivedFromProxy(idBinding, strCommand, tParams)

Function called by Director when a proxy bound to the specified binding sends a BindMessage to the DriverWorks driver.

Returns None Parameters

idBinding - Binding ID of the proxy that sent a BindMessage to the DriverWorks driver.

strCommand - Command that was sent

tParams - Lua table of received command parameters Example

Print all commands received from the proxy, including all parameters: function ReceivedFromProxy(idBinding, strCommand, tParams)

print("ReceivedFromProxy [" .. idBinding .. "]: " .. strCommand) if (tParams ~= nil) then

for ParamName, ParamValue in pairs(tParams) do print(ParamName, ParamValue)

end end end

Map the idBinding to a variable for proxy; evaluate the command coming in – if it’s a simple command, get the command equivalent out of the CMDS table, otherwise call a function to process the command. The following example comes from: [DriverWorks_232_sample_receiver_Integra_dtr-4.5.c4i] function ReceivedFromProxy(idBinding, strCommand, tParams) proxy = "Undefined"

if idBinding == 5001 then proxy = "Receiver"

elseif idBinding == 5002 then proxy = "Tuner"

end

print("ReceivedFromProxy [" .. idBinding .. "]: " .. strCommand .. " for " .. proxy)

cmd = CMDS[strCommand] if (cmd ~= nill) then

print( "Received from Proxy: " .. strCommand .. "; Send to Device: " .. cmd) emit(cmd) else CommandInterpreter(strCommand, tParams) end end

(10)

Control4 DriverWorks SDK – API Reference Guide Page 10 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

1.1 Director Command Interface

ExecuteCommand

ExecuteCommand(strCommand, tParams)

Function called by Director when a command is received for this DriverWorks driver. This includes commands created in Composer programming.

Parameters

strCommand - Command to be sent

tParams - Lua table of parameters for the sent command Example

Print all commands received for this protocol driver, including all parameters: function ExecuteCommand (strCommand, tParams)

print("ExecuteCommand: " .. strCommand) if (tParams ~= nil) then

for ParamName, ParamValue in pairs(tParams) do print(ParamName, ParamValue)

end end end

This sample function evaluates the commands received from Director and calls the correct function. It also looks for LUA_ACTION commands, which are sent from Composer’s Actions tab and processes them. The following example comes from: [DriverWorks_232_Template_Security.c4i]

function ExecuteCommand(strCommand, tParams)

print("ExecuteCommand function called with : " .. strCommand) if (tParams == nil) then

if (strCommand =="GET_PROPERTIES") then GET_PROPERTIES()

else

print ("From ExecuteCommand Function - Unutilized command: " .. strCommand)

end end

if (strCommand == "LUA_ACTION") then if tParams ~= nil then

for cmd,cmdv in pairs(tParams) do print (cmd,cmdv)

if cmd == "ACTION" then

if cmdv == "Reset Security System" then ResetSecuritySystem()

else

print("From ExecuteCommand Function - Undefined

Action")

print("Key: " .. cmd .. " Value: " .. cmdv) end

else

print("From ExecuteCommand Function - Undefined Command")

print("Key: " .. cmd .. " Value: " .. cmdv) end

(11)

Control4 DriverWorks SDK – API Reference Guide Page 11 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

GetVersionInfo

C4:GetVersionInfo()

GerVersionInfo returns the version of Director currently running. Return   buildtime  13:35:13    builddate  Sep 29 2008    version  1.7.0.222    buildtype  DEBUG  Parameters None Example

local tVers = C4:GetVersionInfo() local strVers = tVers["version"]

local major, minor, rev, build = string.match(strVers, "(%d+)\.(%d+)\.(%d+)\.(%d+)")

print("Major: " .. major .. " Minor: " .. minor .. " Rev: " .. rev .. " Build: " .. build)

if (tonumber(major) < 2) then if (tonumber(minor) < 8) then

print("This Code requires at least version 1.8 to operate properly. You are currently running version " .. strVers) end

end

GetUniqueMAC

C4:GetUniqueMAC()

Returns the unique MAC address of the controller running Director Returns

String Parameters None Example

print(C4:GetUniqueMAC()) -- Returns 000fff665FDE

1.2 Serial/Network/Device Interface

SendToSerial

C4:SendToSerial(idBinding, strData)

Simple function which sends the command out serial port on binding 1 and adds the \r terminator to the end of the command being sent

Returns None

(12)

Control4 DriverWorks SDK – API Reference Guide Page 12 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

Parameters

idBinding - Binding ID of the serial interface to send on. strData - Data to send out the specified serial interface Remarks

Serial data to be sent can contain NULL characters. NULL (‘\0’) is a valid character and Lua strings handle embedded NULL characters.

Example

The following example comes from:

[DriverWorks_232_sample_receiver_Integra_dtr-4.5.c4i] function emit(strCommand) print("Emit: " .. strCommand) C4:SendToSerial("1", strCommand .. "\r") end ReceivedFromSerial ReceivedFromSerial(idBinding, strData)

Function which dumps the data received from serial (hex format) for inspection via print. It then evaluates the response for specific delimiters and extracts the

necessary components which are then used to do something. Parameters

idBinding - Binding ID of the serial interface the data was received on strData - Data received from the serial interface

Remarks

Serial data received may contain NULL characters. NULL (‘\0’) is a valid character and Lua strings handle embedded NULL characters.

Serial data received may only include part of a protocol command from the connected device. It is the driver’s responsibility to re-constitute and parse the commands received from the device.

Example

The following example comes from:

[DriverWorks_232_sample_receiver_Integra_dtr-4.5.c4i] function ReceivedFromSerial(idBinding, strData)

print("Received something from serial on binding " .. idBinding) hexdump(strData) responseCount=0 l_string = strData for w in string.gmatch(strData, "!1(...)") do retType = w responseCount=responseCount +1 delimPos = string.find(l_string,tohex("1A"))

retValue = string.sub(l_string,6, tonumber(delimPos)-1) l_string = string.sub(l_string,delimPos+1)

sendNotify() end

(13)

Control4 DriverWorks SDK – API Reference Guide Page 13 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

SendToNetwork

C4:SendToNetwork(idBinding, nPort, strData)

Function which sends an HTTP request to a network binding / port. Returns

None Parameters

idBinding - Binding ID of the network interface to send on nPort - Network port to send on

strDat - Data to send out specified network interface Remarks

Data to be sent can contain NULL characters. NULL (‘\0’) is a valid character and Lua strings handle embedded NULL characters.

Example

The following example comes from [weatherbug.c4i] -- Send 'queued' HTTP request to WeatherBug: C4:SendToNetwork(6001, 80, g_URLPacket)

ReceivedFromNetwork

ReceivedFromNetwork(idBinding, nPort, strData)

Function which combines the data received from the network into a variable for processing when the connection status changes.

Returns None Parameters

idBinding - Binding ID of the interface the data was received from nPort - Network Port the data was received on

strData - Network data from the specified binding and port Remarks

Network data received may contain NULL characters. NULL (‘\0’) is a valid character and Lua strings handle embedded NULL characters.

Network data received may only include part of a protocol command from the connected device. It is the driver’s responsibility to re-constitute and parse the commands received from the device.

Example

The following example comes from [weatherbug.c4i]

function ReceivedFromNetwork(idBinding, nPort, strData)

-- Save up things coming back on HTTP port, process when done sending to us...

g_Receivebuffer = g_Receivebuffer .. strData end

(14)

Control4 DriverWorks SDK – API Reference Guide Page 14 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

NetConnect

C4:NetConnect(idBinding, nPort)

Function used to tell the system to make a connection. An established connection can be validated through OnConnectionStatusChanged.

Returns None Parameters

idBinding - Binding ID of the network interface nPort - Network port to connect to

Example

The following example comes from: [weatherbug.c4i]:

-- Connect to WeatherBug HTTP server. Once it's connected, the g_URLPacket will be sent.

C4:NetConnect(6001, 80)

NetDisconnect

C4:NetDisconnect(idBinding, nPort)

Function called from DriverWorks driver to disconnect from a specific idBinding and nPort.

Returns None Parameters

idBinding - Binding ID of the network interface to disconnect from nPort - Network port

Example

The following example disconnects the current connection on binding 5001, port 80.

C4:NetDisconnect(5001, 80)

OnConnectionStatusChanged

OnConnectionStatusChanged(idBinding, nPort, strStatus)

Function based on the return from the system used by weatherbug driver to process the communication.

Retrurns None Parameters

idBinding - ID of the network binding whose status has changed nPort - Port number whose status has changed

strStatus - “OFFLINE” or “ONLINE” Example

The following example comes from: [weatherbug.c4i]

function OnConnectionStatusChanged(idBinding, nPort, strStatus) if (idBinding == 6001) then

if (strStatus == "ONLINE") then

-- Connect was successful. Send URL packet. -- Other actions…

(15)

Control4 DriverWorks SDK – API Reference Guide Page 15 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

C4:SendToNetwork(6001, 80, g_URLPacket) else

-- OFFLINE... This means the receive buffer is full and ready to process... -- Other actions… end end end OnNetworkBindingChanged OnNetworkBindingChanged(idBinding, bIsBound)

Function called by Director when a network connection has been addressed (‘identified’ on Network Connections Page) or unaddressed (‘disconnect’). Returns

None Parameters

idBinding - ID of the network binding whose addressing status has changed bIsBound - Whether the network binding has a bound address

Example

function OnNetworkBindingChanged(idBinding, bIsBound) print("Network Binding " .. idBinding .. " Changed.") if (bIsBound) then

print("Binding is bound.") else

print("Binding is not bound.") end

end

SendToDevice

C4:SendToDevice(idDevice, strCommand, tParams)

Function called from DriverWorks driver to send a Control4 CommandMessage to the specified Control4 device driver.

Returns None Parameters

idDevice - Device ID of the driver you wish to send the command to strCommand - Command to be sent

tParams - Lua table of parameters to the command Example

Toggles the Light registered with the system as device 41: C4:SendToDevice(41, "TOGGLE", {})

Ramps the Light registered with the system as device 41 to 60% over 3 seconds:

(16)

Control4 DriverWorks SDK – API Reference Guide Page 16 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

(17)

Control4 DriverWorks SDK – API Reference Guide Page 17 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

1.3 Variable Interface

AddVariable

C4:AddVariable(strName, strValue, strVarType, [bReadOnly], [bHidden]) Function called from a DriverWorks driver to create a Control4 variable for the driver. Returns

None Parameters

strName - Name of Control4 variable strValue - Value of Control4 variable

strVarType - Variable Type. Valid types: STRING, NUMBER, LEVEL, BOOL bReadOnly - Optional, defaults to false. Determines if the variable can be modified externally.

bHidden - Optional, defaults to false. Determines if the variable can be seen

in Composer.

Remarks

Variables should always be added in the same order. Control4 Composer programming is based on VariableID’s, which are allocated in order during

AddVariable calls. In other words, if you add a set of variables then later delete them and re-add different variables or in a different order, Composer programming will be incorrect.

Example

C4:AddVariable("Driver Variable", 0, "NUMBER")

Creates the device variable named “Driver Variable” within the Control4 system.

SetVariable

C4:SetVariable(strName, strValue)

Function called from a DriverWorks driver to set the value of a Control4 variable for the driver.

Returns None Parameters

strName - Name of variable to set strValue - Value to set variable Example

Sets the value of the device variable named “Driver Variable” to 90: C4:SetVariable("Driver Variable", 90)

Sets the device variable named “FORECAST_SUMMARY” to the value indicated by strSummary for use within the Control4 system. The following example comes from:[weatherbug.c4i]:

(18)

Control4 DriverWorks SDK – API Reference Guide Page 18 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

DeleteVariable

C4:DeleteVariable(strName)

Function called from a DriverWorks driver to delete a Control4 variable for the driver. Returns

None Parameters

strName - Name of variable to delete

Example

Deletes the device variable named "Driver Variable" from the Control4 system.

C4:DeleteVariable("Driver Variable")

OnVariableChanged

OnVariableChanged(strName)

Function called by Director when one of this driver’s variables’ values is changed. Parameters

strName - Name of variable that has changed. Remarks

OnVariableChanged is NOT called on a driver when it changes its own variable’s value. The value of the variable that has changed can be found with: Variables[strName].

Example

This simple function prints to the Lua Output window in Composer when any variable on that device changes and includes the variable name and value. function OnVariableChanged(strName)

print("Variable value changed - variable named: " .. strName) print(" ... new value is: " .. Variables[strName])

end

DriverWorks Variables Table

Variables[strName]

The Lua Table ‘Variables’ contains the current value of this driver’s variables. Although you can read directly from this table, to change the value of a device variable, you should use C4:SetVariable(strName, strValue).

Returns None Parameters

strName – Variable name. Examples

Use Variables in a comparison:

if (Variables["Power State"] == "OFF") then C4:SendToSerial(idSerialBinding, "__ON__") C4:SetVariable("Power State", "ON")

(19)

Control4 DriverWorks SDK – API Reference Guide Page 19 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

Print out all Variables:

for VariableName, VariableValue in pairs(Variables) do print(VariableName, VariableValue)

end

GetVariable

C4:GetVariable(idDevice, idVariable)

This function has been deprecated and should not be used for future driver

development. It was replaced by ‘GetDeviceVariable’ since it is used to get variables on different devices other than the DriverWorks driver.

GetDeviceVariable

C4:GetDeviceVariable(idDevice, idVariable)

Function called by a DriverWorks driver to get the value of another device’s variable. Returns

strValue - String Value of the requested variable, nil if not found. Parameters

idDevice - Device ID of the device that owns the specified variable idVariable - Variable ID of the specified variable

Remarks

User Variables belong to the Variable Agent, with a DeviceID of 100001. Examples

Gets and prints the value of the HVAC mode and temperature variables of a Control4 Thermostat registered in the project as Device ID 84:

print(C4:GetDeviceVariable(84, 1000)) print(C4:GetDeviceVariable(84, 1003))

Gets and prints the User Variable registered with the project as variable 209: print(C4:GetDeviceVariable(100001, 209))

SetDeviceVariable

C4:SetDeviceVariable(idDevice, idVariable, strValue)

Sets the Device Variable specified to the value passed to the function. Returns

None Parameters

idDevice - Device ID of the Device that owns the specified variable idVariable - Variable ID of the specified variable

strValue - Value of the variable to set. Remarks

User Variables belong to the Variable Agent, with a Device ID of 100001. Examples

Sets the value of the Heat Setpoint on a Control4 Thermostat registered with the project as Device ID 84 to 70 degrees:

(20)

Control4 DriverWorks SDK – API Reference Guide Page 20 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

RegisterVariableListener

C4:RegisterVariableListener(idDevice, idVariable)

Function called from a DriverWorks driver to set a listener on a particular device’s variable. When a listener is set on a variable, whenever the variable changes, the Lua OnWatchedVariableChanged call is called.

Returns None Parameters

idDevice - Device ID of the device that owns the requested variable idVariable - Variable ID of the requested variable

Remarks

User Variables belong to the Variable Agent, with a DeviceID of 100001. The OnWatchedVariableChanged function will be called immediately after the listener is successfully set.

Example

This example watches the value of the temperature and HVAC mode variables on a Control4 Thermostat registered with the system as device 84. It also registers to watch for changes to the user variable 209:

C4:UnregisterVariableListener(84, 1000) C4:UnregisterVariableListener(84, 1003) C4:UnregisterVariableListener(100001, 209) C4:RegisterVariableListener(84, 1000) C4:RegisterVariableListener(84, 1003) C4:RegisterVariableListener(100001, 209)

function OnWatchedVariableChanged(idDevice, idVariable, strValue) print("Variable changed...")

print(" device: " .. idDevice) print(" variable: " .. idVariable) print(" value: " .. strValue) print("---")

end WARNING

When registering variable listeners with this function, you MUST call UnregisterVariableListener when the driver is destroyed (in the

OnDriverDestroyed function). Failure to do this may cause Director to crash when the variable changes value. Example:

function StartMonitoring()

C4:RegisterVariableListener(devid, 1000) -- Register for LIGHT_STATE (1000) Changes...

C4:RegisterVariableListener(devid, 1001) -- Register for LIGHT_LEVEL (1001) Changes...

end

function StopMonitoring()

-- Unregister Variable Listeners...

C4:UnregisterVariableListener(devid, 1000) C4:UnregisterVariableListener(devid, 1001) end

(21)

Control4 DriverWorks SDK – API Reference Guide Page 21 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

function OnDeviceDestroyed() -- Called when the driver is about to go away...

StopMonitoring() end

UnregisterVariableListener

C4:UnregisterVariableListener(idDevice, idVariable)

Function called from DriverWorks driver to remove a listener on a particular device’s variable. Variable changes for the particular Device’s Variable will no longer be reported.

Returns None Parameters

idDevice - Device ID of the device that owns the requested variable idVariable - Variable ID of the requested variable

Remarks

User Variables belong to the Variable Agent, with a DeviceID of 100001.

Example

This stops the system from reporting variable value changes for the specified device and variables:

C4:UnregisterVariableListener(84, 1000) C4:UnregisterVariableListener(84, 1003) C4:RegisterVariableListener(100001, 209)

OnWatchedVariableChanged

OnWatchedVariableChanged(idDevice, idVariable, strValue) Function called by Director when a Control4 variable changes value. Parameters

idDevice - Device ID of the device that owns the changed variable idVariable - Variable ID of the changed variable

strValue - New value of variable that has changed Remarks

Watched variables are variables that belong to other devices in the system, not variables that necessarily belong to a DriverWorks driver.

Example

This example function prints the value of the device ID, variable ID, and variable value when any watched variable changes:

function OnWatchedVariableChanged(idDevice, idVariable, strValue) print("Variable changed...")

print(" device: " .. idDevice) print(" variable: " .. idVariable) print(" value: " .. strValue) print("---")

(22)

Control4 DriverWorks SDK – API Reference Guide Page 22 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

1.4 Timer Interface

AddTimer

C4:AddTimer(nInterval,[strUnits],[bRepeat])

Function called from DriverWorks driver to create a C4 timer.

Returns

idTimer - Timer ID of the newly added timer. Can be used to KillTimer or to know which timer has expired in OnTimerExpired.

Parameters

nInterval - Number of seconds/milliseconds/hours/minutes before the timer expires

strUnits - Optional, defaults to SECONDS. Units of timer measurement. Valid units include: MILLISECONDS, SECONDS, MINUTES and HOURS.

bRepeat - Optional, defaults to FALSE. Is the timer a repeating timer? Repeating timers will expire continually, until killed.

Example

This example starts a repeating timer to use for a countdown function. It can be found in: [DriverWorks_232_Template_Security.c4i]

exitTimer = C4:AddTimer(1,"SECONDS",true)

This example starts a non-repeating timer to use for a delay before checking device status. It can be found in:

[DriverWorks_232_sample_receiver_Integra_dtr-4.5.c4i] tunerqDelay = C4:AddTimer(100, "MILLISECONDS")

KillTimer

C4:KillTimer(idTimer)

Function called from DriverWorks driver to kill a C4 timer. Returns

None Parameters

idTimer - Timer ID to kill Remarks

This call stops the timer, and removes it from Control4’s list of valid timers. Note that C4: KillTimer does NOT change the value of idTimer, since Lua doesn’t support passing parameters by reference, but KillTimer does return 0, so it can be used to set the value of the timer to 0 in the same call:

idSendTimer = C4:KillTimer(idSendTimer) Example

(23)

Control4 DriverWorks SDK – API Reference Guide Page 23 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

This example stops a repeating timer used for a countdown function. It can be found in: [DriverWorks_232_Template_Security.c4i]

if exitDelay == 0 then C4:KillTimer(exitTimer) -- do stuff here end OnTimerExpired OnTimerExpired(idTimer)

Function called by Director when the specified Control4 timer expires. Returns

None Parameters

idTimer - Timer ID of expired timer. Example

This function is called by Director when a timer expires. Based on the idTimer passed in, you program what you want to do. This example is used for handling several timers. It can be found in:

[DriverWorks_232_sample_receiver_Integra_dtr-4.5.c4i]: function OnTimerExpired(idTimer)

if idTimer == tunerqDelay then

emit("!1TUNQSTN") -- Query Channel after a short delay elseif idTimer == volrampTimer then

-- do stuff

elseif idTimer == channelrampTimer then -- do stuff

end end

OnDriverDestroyed

OnDriverDestroyed()

OnDriverDestroyed is called by Director when the DriverWorks driver has been deleted from the system and/or Director is shutting down. It is a good idea to use this function to kill any running DriverWorks timers created by your driver.

Failure to do so may cause your driver to crash Director.

Returns

None Parameters

None Example

This OnDriverDestroyed kills any timers that are in use: function OnDriverDestroyed()

if (g_dbgTimer ~= nil) then C4:KillTimer(g_dbgTimer) end

if (gPopupTimer ~= nil) then C4:KillTimer(gPopupTimer)

(24)

Control4 DriverWorks SDK – API Reference Guide Page 24 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

end end

1.5 Event Interface

FireEvent

C4:FireEvent(strEvent)

Function called from DriverWorks driver to Fire the specified event on this driver. Returns

None Parameters

strEvent – Desired event. Example

Fires the "Forecast Received" event for use by the system. This example can be found in: [weatherbug.c4i]:

C4:FireEvent("Forecast Received")

1.6 IR Interface

SendIR

C4:SendIR(idBinding, idIRCode)

Function called from DriverWorks driver to send an IR Code. Returns

None Parameters

idBinding - IR Binding ID to send the IR Code idIRCode - ID of the IR Code to send from .c4i

Remarks

The IR code to send must be declared as an <ircode> in the <irsection> of the driver’s .c4i file.

Example

This example sends the specified IR Code out the specified IR Binding: C4:SendIR(1, 22)

SendIRStart

C4:SendIRStart(idBinding, idIRCode)

Causes Director to start sending the specified IR Code out the specified binding. This is typically used on button press events.

Returns None Parameters

idBindingIR - Binding ID to send the IR Code

(25)

Control4 DriverWorks SDK – API Reference Guide Page 25 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

Remarks

Failure to call the SendIRStop function will cause the IR code to be sent continually, which (in the case of volume ramps) could be catastrophic to equipment. The IR code to send must be declared as an <ircode> in the <irsection> of the driver’s .c4i file.

Example

This example starts sending the specified IR Code out the specified IR Binding: C4:SendIRStart(1, 22)

SendIRStop

C4:SendIRStop(idBinding, idIRCode)

Causes Director to stop sending the specified IR Code out the specified binding. This is typically used on button release events.

Returns None Parameters

idBinding - IR Binding ID to send the IR Code.

idIRCode- Id of the IR Code to start sending from the .c4i Remarks

The IR code to send must be declared as an <ircode> in the <irsection> of the driver’s .c4i file.

Example

This example stops sending the specified IR Code out the specified IR Binding:

C4:SendIRStop(1, 22)

1.7 Properties Interface

UpdateProperty

C4:UpdateProperty(strName, strValue)

Function called from DriverWorks driver to update driver properties. Returns

None

Parameters

strName - Name of property to update strValue - New value of property Example

Various examples of how the properties are updated by the driver. This example can be found in: [DriverWorks_232_template_security.c4i] C4:UpdateProperty("Security State","Armed "..armMode) C4:UpdateProperty("Security State","Disarmed")

OnPropertyChanged

(26)

Control4 DriverWorks SDK – API Reference Guide Page 26 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

Function called by Director when a property changes value. Returns

None

Parameters

strName - Name of property that has changed.

Remarks

The value of the property that has changed can be found with: Properties[strName]. Note that OnPropertyChanged is not called when the Property has been changed by the driver calling the UpdateProperty command, only when the Property is changed by the user from the Properties Page.

Example

An example function used to process property value changes. This example can be found in: [DriverWorks_232_template_security.c4i]

function OnPropertyChanged(strProperty) propertyValue = Properties[strProperty]

print("strProperty = " .. strProperty .. " changed to: " .. propertyValue)

if (strProperty == "Security State") then if propertyValue == "Disarmed" then -- do stuff

elseif propertyValue == "Armed Stay" then -- do stuff

elseif propertyValue == "Armed Away" then -- do stuff

elseif propertyValue == "Alarm Activated" then -- do stuff

end

elseif (string.find(strProperty,"Zone") ~= nil) then -- do stuff

else

print("No action performed for " .. strProperty .. " which has been set to: " .. Properties[strProperty])

end end

DriverWorks Properties Table

Properties[strName]

The Lua Table ‘Properties’ contains the current value of this driver’s properties. Although you can read from this table, and change properties’ values on the devices’ Properties page, to change the value of a device property programmatically, you should use C4: UpdateProperty.

Returns

None Parameters

strName – Desired device Property Examples

(27)

Control4 DriverWorks SDK – API Reference Guide Page 27 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

if (Properties[“CalculateWindShear”] == “true”) then CalculateWindShear()

end

Print out all Properties:

for PropertyName, PropertyValue in pairs(Properties) do print(PropertyName, PropertyValue)

end

1.8 Log Interface

DebugLog

C4:DebugLog(strLogText)

Function called from DriverWorks driver to send messages to Control4’s debug log. Returns

None Parameters

strLogText - Text to log Example

Here is an example from the weatherbug driver of using a Property to set an error logging mode: This example can be found in: [weatherbug.c4i]

(28)

Control4 DriverWorks SDK – API Reference Guide Page 28 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

ErrorLog

C4:ErrorLog(strLogText)

Function called from DriverWorks driver to send messages to Control4’s error log. Returns

None Parameters

strLogText - Example

Here is an example from the weatherbug driver of using a Property to set an error logging mode: This example can be found in: [weatherbug.c4i]

function dbg(strDebugText)

if (g_debugprint) then print(strDebugText) end if (g_debuglog) then C4:ErrorLog(strDebugText) end end

1.9 Miscellaneous

DriverWorks PersistData Table

PersistData = {}

The Lua Table ‘PersistData’ is available for drivers to keep persistent data across director restarts. Any values placed into the PersistData table will exist in the PersistData table when the driver is loaded after a director restart.

GetDeviceID

C4:GetDeviceID()

Function called from DriverWorks driver to get this driver’s Device ID. Returns

Driver Device ID Parameters

None Example

local myid = C4:GetDeviceID()

print("My Device's ID is: " .. myid)

GetCapability

C4:GetCapability(strName)

Function called from DriverWorks driver to get a capability from the driver’s .c4i file. Returns

strCapability - The value of the capability retrieved from the .c4i file Parameters

strName - The name of the capability to retrieve Examples

(29)

Control4 DriverWorks SDK – API Reference Guide Page 29 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

If this device supports discrete volume control, send discrete volume, otherwise, send a Volume Up or Volume Down command:

if (C4:GetCapability("has_discrete_volume_control") == "False") then

if (VolumeValue > CurVolumeValue) then SendVolumeUp() else SendVolumeDown() end else SendVolumeDiscrete(VolumeValue) end OnBindingChanged

OnBindingChanged(idBinding, strClass, bIsBound)

Function called by Director when a binding changes state (bound or unbound). Returns

None Parameters

IdBinding - ID of the binding whose state has changed

StrClass - Class of binding that has changed. A single binding can have multiple classes: COMPONENT, STEREO, etc. This indicates which has been bound or unbound.

BIsBound - Whether the binding has been bound or unbound. Remarks

Protocol drivers do not get OnBindingChanged notifications for AV and Room bindings being bound, only *control*-type bindings (Serial, IR, etc.). It is intended to be used specifically for when serial bindings are made, so the driver knows it can send initialization, etc. to the now-connected device. Example

function OnBindingChanged(idBinding, strClass, bIsBound)

print("Binding " .. idBinding .. " (Class " .. strClass .. ") Changed.")

if (bIsBound) then

print("Binding is bound.") else

print("Binding is not bound.") end

end

AddDynamicBinding

C4:AddDynamicBinding(idBinding, strType, bIsProvider, strName, strClass, bHidden, bAutoBind)

Note: Currently, the AddDynamicBinding does not work for audio and Video

(30)

Control4 DriverWorks SDK – API Reference Guide Page 30 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

Function called by a DriverWorks driver to add a dynamic binding (a binding added at runtime). This is typically done by security panels or other devices whose number of bindings are unknown when the driver is created.

Returns

None Parameters

IdBinding - ID of the dynamic binding.

StrType - Type of dynamic binding. Valid types include: CONTROL, PROXY, VIDEO, AUDIO, and ROOM_CONTROL

bIsProvider - Whether the binding is a Provider or a Consumer binding. StrName - Name of binding that will appear in Composer’s connections page. StrClass - Class of dynamic binding that is being created.

BHidden - Whether the dynamic binding is hidden. Should typically be false. BAutoBind - Whether the dynamic binding should be auto-bound. Should typically be false.

Examples

Dynamically create 4 Zone Contact Bindings for a Security Driver: C4:AddDynamicBinding(101, "CONTROL", true, "Zone 1", "CONTACT_SENSOR", false, false)

C4:AddDynamicBinding(102, "CONTROL", true, "Zone 2", "CONTACT_SENSOR", false, false)

C4:AddDynamicBinding(103, "CONTROL", true, "Zone 3", "CONTACT_SENSOR", false, false)

Remarks

It is the responsibility of the DriverWorks driver to maintain the Dynamic bindings and to restore them from persistent data upon the driver being initialized. If this is not done, the bindings will not be available after a Director restart.

If dynamic bindings have been connected in Composer, if they are properly restored by the DriverWorks driver, the connections made between the bindings will be automatically restored.

Below is an example of how to create and save bindings for three security contacts:

if (nil == PersistData) then PersistData = {}

end

PersistData["zonebindings"] = {}

PersistData["zonebindings"][101] = "Zone 1"

C4:AddDynamicBinding(101, "CONTROL", true, "Zone 1", "CONTACT_SENSOR", false, false)

PersistData["zonebindings"][102] = "Zone 2"

C4:AddDynamicBinding(102, "CONTROL", true, "Zone 2", "CONTACT_SENSOR", false, false)

PersistData["zonebindings"][103] = "Zone 3"

C4:AddDynamicBinding(103, "CONTROL", true, "Zone 3", "CONTACT_SENSOR", false, false)

(31)

Control4 DriverWorks SDK – API Reference Guide Page 31 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

The following is an example of how to restore saved bindings This code should be in the main body of the script section of the driver, not within any declared function:

if (PersistData ~= nil) then

for key,value in pairs(PersistData["zonebindings"]) do C4:AddDynamicBinding(key, "CONTROL", true, value,

"CONTACT_SENSOR", false, false) end

end

RemoveDynamicBinding

RemoveDynamicBinding(idBinding)

Function called by a DriverWorks driver to remove a dynamically-created binding. Returns

None Parameters

IdBinding - ID of the dynamic binding to remove. Example

Removes dynamic binding created with AddDynamicBinding above: C4:RemoveDynamicBinding(103)

Base64Encode

Base64Encode(strToEncode)

Function called in a DriverWorks driver to encode the specified string as a Base64-encoded string.

Returns

String encoded in Base64 encoding. Parameters

StrToEncode - String to be encoded in Base64 encoding Example

Example Base64 encodes a string, and then decodes it: local str = "Control4 DriverWorks SDK"

print("Original String: " .. str) local enc = C4:Base64Encode(str) print("Encoded: " .. enc)

local dec = C4:Base64Decode(enc) print("Decoded: " .. dec)

Base64Decode

C4:Base64Decode(strToDecode)

Function called in a DriverWorks driver to decode the specified string from a Base64-encoded string.

(32)

Control4 DriverWorks SDK – API Reference Guide Page 32 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

Returns

String decoded from Base64 encoding. Parameters

StrToDecode - String to be decoded from Base64 encoding

Example

Example Base64 encodes a string, and then decodes it: local str = "Control4 DriverWorks SDK"

print("Original String: " .. str) local enc = C4:Base64Encode(str) print("Encoded: " .. enc)

local dec = C4:Base64Decode(enc) print("Decoded: " .. dec)

OnPoll

OnPoll()

Function called by Director when Director’s internal Poll timer expires. This only occurs in drivers that have requested polling within their .c4i files, by setting the <can_poll_serial> capability to “True”.

Parameters None Returns

None Remarks

You can also implement polling yourself within your driver by using DriverWorks system timers.

Example function OnPoll() -- Serial polling C4:SendToSerial(1, "STATUS\r\n") end XMLEscapeString C4:XMLEscapeString(strRawInput)

‘Escapes’ the passed in string, rendering any XML characters in the string as characters that are valid in an XML value.

Returns

strEscaped - The passed in string, with all XML characters properly escaped. Parameters

strRawInput - Raw input string, with possibly invalid characters for an XML value.

Remarks

You must escape all strings that are put into XML, otherwise invalid characters could cause the XML to be invalid.

Examples

Builds an XML string with a string that could have invalid XML characters in it: strXmlListItem = "<text>" .. C4:XMLEscapeString .. "</text>"

(33)

Control4 DriverWorks SDK – API Reference Guide Page 33 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

CRC32

C4:CRC32(strInput)

Calculates the CRC32 value for the input string. Returns

nCRC32 - The calculated CRC32 value of the input string (a number). Parameters

strInput - String of data to calculate the CRC32 of. Example

Calculate and print the CRC32 value of some common valid CRC32 test vectors.

print(string.format("%x", C4:CRC32(""))) -- should print "0"

print(string.format("%x", C4:CRC32("Test vector from febooti.com")))

-- should print "c877f61"

TEAEncrypt

C4:TEAEncrypt(strBuf, strKey)

Encrypt the input string with Corrected Block TEA (XXTEA) Algorithm, using the specified key.

Returns

strEncrypted - TEA Encrypted version of input string. Parameters

strBuf - String to be encrypted.

strKey - Key to use for encryption. Keys are 32 hex digits, encoded as a string (128-bit).

Remarks

Key must be the same for encryption / decryption to function properly. The input string (strBuf) must be padded to a 4-byte boundary.

More information about the Corrected Block TEA algorithm (XXTEA) as well as a compatible C implementation of XXTEA may be found at Wikipedia:

http://en.wikipedia.org/wiki/XXTEA Examples

Encrypt then Decrypt a string, then print the original string out: local key = "1234567887654321abcdefabcabcdefa"

e = C4:TEAEncrypt("Control4 Rocks! ", key) print(C4:TEADecrypt(e, key))

-- prints "Control4 Rocks! "

TEADecrypt

C4:TEADecrypt(strBuf, strKey)

Decrypt the input string with Corrected Block TEA (XXTEA) Algorithm, using the specified key.

Returns

(34)

Control4 DriverWorks SDK – API Reference Guide Page 34 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

Parameters

strBuf - String to be decrypted.

strKey - Key to use for decryption. Keys are 32 hex digits, encoded as a string (128-bit).

Remarks

Key must be the same for encryption / decryption to function properly. The input string (strBuf) must be padded to a 4-byte boundary.

More information about the Corrected Block TEA algorithm (XXTEA) as well as a compatible C implementation of XXTEA may be found at Wikipedia:

http://en.wikipedia.org/wiki/XXTEA Examples

Encrypt then Decrypt a string, then print the original string out: local key = "1234567887654321abcdefabcabcdefa"

e = C4:TEAEncrypt("Control4 Rocks! ", key) print(C4:TEADecrypt(e, key))

-- prints "Control4 Rocks! "

ntoh_l

C4:ntoh_l(nVal)

Converts the numeric value passed in to host byte order. Returns

nHostVal - The nVal parameter converted to host byte order Parameters

nVal - The input unsigned long value. Remarks

This function is typically used to convert numeric values received over a network, when the byte order of the two ends is unknown or may be different from each other. This way, ‘little-endian’ and ‘big-endian’ machines can communicate without confusion.

‘Host’ byte order is the byte order of values on the local machine, and ‘Network’ byte order is the standard byte order on Ethernet networks. Example

i_network = 0x1234ABCD

i_native = C4:ntoh_l(i_network ) print("native order = " .. i_native)

little endian machine prints: native order = cdab3412

hton_l

C4:hton_l(nVal)

Converts the numeric value passed in to network byte order. Returns

(35)

Control4 DriverWorks SDK – API Reference Guide Page 35 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

nNetVal - The nVal parameter converted to network byte order. Parameters

paramName paramText Remarks

This function is typically used to convert numeric values to be passed over a network, when the byte order of the two ends is unknown or may be different from each other. This way, ‘little-endian’ and ‘big-endian’ machines can communicate without confusion.

‘Host’ byte order is the byte order of values on the local machine, and ‘Network’ byte order is the standard byte order on Ethernet networks. Example

i_native = 0x1234ABCD

i_network = C4:hton_l(i_native)

print("netowrk order = " .. i_network)

little endian machine prints: netowrk order = cdab3412

GetProxyDevices

C4:GetProxyDevices()

Function that returns the proxy device id(ids if device has multiple proxies) associated with the current driver.

Parameters None Returns

proxy id, proxy id, … Example

local proxyId = C4:GetProxyDevices() print("proxy is: " .. proxyId)

prints: proxy is: 393 

1.10 Helper Functions

Print

print(strPrintText)

Function called from DriverWorks driver to prints items out the drivers’ properties page console.

Returns None Parameters

strPrintText - Text to print Remarks

Note that for convenience, the print function can be called without prefacing

with C4:

(36)

Control4 DriverWorks SDK – API Reference Guide Page 36 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

print("Test Stuff")

tohex

tohex(strHex)

Function called from DriverWorks driver to convert a text string of hex into a string with hex values in it. Typically used when a protocol sends commands that are hex values.

Returns None Parameters

strHex - Text to convert to binary hex Example

Store the HEX code for a discrete Power On command for a Mitsubishi TV: POWER_ON = tohex("DF 80 70 F8 02 00 00")

hexdump

hexdump(strDump)

Prints out the values of a string in both hex and ascii representation. All characters that are not ‘A-Z’ or ‘0-9’ are printed as a ‘.’ In the ascii representation. The print goes to the Lua tab on the properties page of the driver.

Returns None Parameters

strDump - Text to print out in a hexdump Example

hexdump(tohex("00 ff de ad be ef ") .. "Test Text") Prints out the following:

00000000 00 FF DE AD BE EF 54 65 ...Te 00000008 73 74 20 54 65 78 74 st.Text

1.11 Debug Interface Section

EnableRemoteDebugging

C4:EnableRemoteDebugging(strHostAndPort)

Enables remote debugging of DriverWorks Lua scripts through an external IDE with a debugger. Full instructions on use of remote debugging of DriverWorks drivers may be found in the “Control4 DriverWorks SDK – Getting Started Guide”.

(37)

Control4 DriverWorks SDK – API Reference Guide Page 37 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

Returns None Parameters strHostAndPort – paramText Example C4:EnableRemoteDebugging("192.168.0.118:8888") DisableRemoteDebugging C4:DisableRemoteDebugging()

Disables remote debugging of DriverWorks Lua scripts. Full instructions on use of remote debugging of DriverWorks drivers may be found in the “Control4 DriverWorks SDK – Getting Started Guide”.

Returns None Parameters None Example C4:DisableRemoteDebugging() Attach Attach()

Function called by Director when remote debugging of the DriverWorks script has started. Returns None Parameters None Example function Attach()

-- Initial debug setup bDebug = true

end

OnEndDebugSession

OnEndDebugSession()

Function called by Director when remote debugging of the DriverWorks script has ended.

Returns

None Parameters None

(38)

Control4 DriverWorks SDK – API Reference Guide Page 38 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

Example

function OnEndDebugSession() bDebug = false

end

1.12 Media Management - Generic

MediaRemoveAllMedia

Removes all albums songs and movies from the device. Returns None Parameters None Example MediaSetDeviceContext C4:MediaSetDeviceContext()

Function that sets a device id to be used for media related call. If set to any value other than “0” then adding, modifying, retrieving or removing functionality will use the supplied device id.

Parameters

New device id to be associated with media related api’s. If set to “0” then the media related api’s will use the current driver’s device id.

Returns None Example C4:MediaSetDeviceContext(391) MediaGetDeviceContext C4:MediaGetDeviceContext()

Function that returns the what the device context is currently set to. If “0” then all media api’s are using the current driver’s device id.

Parameters None Returns

Driver Device ID Example

local contextId = C4:MediaGetDeviceContext() print("context is: " .. contextId)

(39)

Control4 DriverWorks SDK – API Reference Guide Page 39 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

1.13 Media Management – Movies

The examples used in the Movies section of this document will reference the following movie:

shrekMovie = {

directors = "Andrew Adamson; Vicky Jenson",

description = "In this fully computer-animated fantasy", cast = "Mike Myers; Eddie Murphy; John Lithgow",

rating = "", genre = "Children's/Family", release_date = "2001", release_company = "DreamWorks", cover_art = "/9j/4AAQSkZJRgABAQEBLAEsAAD/" } MediaAddMovieInfo C4:MediaAddMovieInfo("http://127.0.0.1/movies/shrek1", "shrek1", shrekMovie) Returns

Number – The new Media ID for the movie Parameters string location string title table information Example mediaId1 = C4:MediaAddMovieInfo("http://127.0.0.1/movies/shrek1", "shrek1", shrekMovie) MediaGetMovieInfo C4:MediaGetMovieInfo(mediaId) Function that returns movie properties. Returns

Table information. The table may have entries for: • string location

• string title

• string directors – comma separated • string description

• string cast – comma separated • string rating • string rating_reason • string reviews • string genre • string aspect_ratio • string release_date • string release_company

• string length – time span in minutes

(40)

Control4 DriverWorks SDK – API Reference Guide Page 40 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

Parameters

Number – Media ID – This is the Media ID of the movie. Example

myMovieInfo = C4:MediaGetMovieInfo(mediaId1) print(myMovieInfo[“title”])

MediaGetMovieLocation

C4:MediaGetMovieLocation(mediaId) Function that returns the movie location. Parameters

number – The Media ID of the movie. Returns

string – The location of this media as stored in the database. Example

myLocation = C4:MediaGetMovieLocation(mediaId1)

MediaGetAllMovies

C4:MediaGetAllMovies()

Function that returns a table of all movies.

Returns

Table containing Media IDs and locations. Parameters

None Example

allMovies = C4:MediaGetAllMovies() for key,value in pairs(allMovies) do

print("mediaId is "..key.. " location is "..value) end

MediaRemoveMovie

C4:MediaRemoveMovie(mediaId) Removes a movie based on media ID Returns

None Parameters

Number – the Media ID of the movie being removed. Example

C4:MediaRemoveMovie(mediaId3)

MediaRemoveAllMovies

(41)

Control4 DriverWorks SDK – API Reference Guide Page 41 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

Function to remove all movies from the database. Returns

None Parameters

None - Removes all movies Example

C4:MediaRemoveAllMovies()

MediaModifyMovieInfo

Function to modify the data associated with an existing media id. Returns None Parameters Media ID Location Name

Movie table information - movie information is required. None

Example

shrekMovie["genre"] = "Horror"

C4:MediaModifyMovieInfo(mediaId1,

"http://127.0.0.1/movies/shrek1Modified", "shrek1", shrekMovie) Remarks

A modify call does not change the media’s ID number where a delete or add

call will. Modify calls are useful if programming relies on the current Media ID. For example, if a button push has is programmed to play the media, and a modify call is used, the media’s current ID is maintained and programming is

(42)

Control4 DriverWorks SDK – API Reference Guide Page 42 Copyright 2009 Control4 Corporation, All Rights Reserved Version 1.7.3

1.14 Media Management – Albums

The examples used in the Albums section of this document will reference the following album/songs:

mediaId1 = C4:MediaAddAlbumInfo("http://127.0.0.1/music/Album1", "Funky Music", Album1) songLocation1="http://127.0.0.1/music/song1.mp3" songLocation2="http://127.0.0.1/music/song2.mp3" songLocation3="http://127.0.0.1/music/song3.mp3" SomeSong1 = { --required fields

title="Title Test Song Number 1", location=songLocation1,

track_no="6", --optional fields

name = "Name Test Song Number 1", artist = "C4 Music Factory", record_label="Island",

release_date="15 Jun 2004", }

SomeSong2 = {

title="Test Song Number 2", location=songLocation2, track_no="1",

name = "Name Test Song Number 2", artist = "C4 Music Factory", record_label="Dos Record Label", release_date="15 Jun 2222", }

SomeSong3 = {

title="Test Song Number 3", track_no="7",

location=songLocation3,

name = "Name Test Song Number 3", artist = "C4 Music Factory", record_label="Boat",

release_date="3 Dec 2002", }

Album1 = {

artist = "Jimmy Joe",

description = "Worst episode ever", genre = "Blues & Browns",

release_date = "1992",

release_label = "Grass and Cash",

songs = {SomeSong1, SomeSong2, SomeSong3}, }

References

Related documents