Skip to main content

JavaScript API iRidi

The iRidi API is a set of JavaScript functions that allow you to control an iRidi visualization project. Follow this guide to add JavaScript to your project.

This guide is intended for developers familiar with JavaScript programming and the object-oriented development paradigm. It describes the basic concepts used in the API and methods for solving common iRidi project control tasks.

Updated: 01.01.2024

Tip

Parent language: JavaScript
Language version: 1.5
Specification: ECMAScript Edition 3
Yes, our version of JS is far from new and does not support newer constructs, but this functionality is sufficient for a Panel Project in 99% of cases. For the remaining percentage, there are converters such as https://babeljs.io and, of course, the developer's experience and skills Report an error

All available API objects are described in detail in the reference for the programming interface.

Attend free training webinars:

iRidi Script Part 1: Extending the control interface

iRidi Script Part 2: Working with iRidi drivers

Creating animated items in iRidi interfaces

General provisions​

The iRidi JavaScript API is a set of iRidi API and JavaScript 1.5 functions and events designed to control the visual interface and drivers in an iRidi project. The iRidi API interacts with the application, which interprets and executes JavaScript files. The iRidi API functions refer to the .IR object and are available only in the original application whose version matches the API version.

Using the API​

To use JavaScript, add a JavaScript file (.js) to an iRidi project (.irpz) created using the iRidi Studio application.

The file is stored inside the iRidi project and is downloaded to the application together with the project. Script execution begins when the project starts in the application.

Create a JavaScript file in iRidi Studio:

  1. Open iRidi Script Editor
  2. Click "New script"
  3. Enter the file name and click OK

ScriptEditor1.png

The file can be exported from the iRidi project in *.js format and reused.

Add an existing JavaScript file in iRidi Studio

  1. Open iRidi Script Editor
  2. Click "Add script from file"
  3. Select a file with the *.js extension; it will be added to the list of JavaScript files

ScriptEditor2.png

Script execution​

A JavaScript file can contain the required set of iRidi API functions and events. A function executes when an iRidi API event occurs. Such an event may be application startup, a press on a graphical item, receipt of data from equipment, etc.

  • A JavaScript file is a file with the *.js extension attached to a project
  • An event is a process exposed to scripts that has an identifier for monitoring
  • A listener is a function that executes when its specified event occurs
  • IR is a global object containing all iRidi API functions and constants

Code is placed in files. Listeners are placed in the code. Events, objects, and functions are passed to listeners.

The IR.AddListener() listener​

A script can be called by a system event, for example when data is received from equipment or a graphical item is pressed. You can monitor various events that occur while the project is running. An event monitored by a listener calls an anonymous function and can pass it parameters whose values change with the event.

An event is a process exposed to scripts that has an identifier for monitoring.

A listener is a function that executes when its specified event occurs

Add a listener using the method IR.AddListener

IR.AddListener(event, input, action);
  • event is the identifier of the event monitored by the listener
  • input is an input parameter required to create the listener. If there is no parameter, specify 0
  • action is an anonymous function or a reference to a declared function in which actions are performed
  • pointer is a pointer to the listener's invocation context (optional). You can access the context using the this operator. The context may change while the program is running

Example 1 (without specifying a context):


IR.AddListener(IR.EVENT_START, 0, function()
{
IR.Log("Hello World!")
});

In addition to the three main listener parameters (event, input, action), there is a pointer parameter that lets the listener pass a pointer to an object serving an external function to that function.

Example: we will use a listener to call a named function and pass it a reference to an interface object as the function's execution context. You can access the context using the this operator. The context may change while the program is running.

Example 2 (with a specified context):


var page = IR.GetItem("Page 1")
for(var i = 0; i < page.ItemsCount; i++)
{
// page.GetItem(i) будет контекстом выполнения функции ShowName
IR.AddListener(IR.EVENT_ITEM_PRESS, page.GetItem(i), ShowName, page.GetItem(i));
}
function ShowName()
{
// оператор this позволяет обратиться к контексту: объекту page.GetItem(i)
IR.Log(this.Name);
}

For details on using the IR.AddListener method, see the Reference.

The IR.SetGlobalListener() global listener​

A global listener executes when its specified event occurs. It can work with only two events: IR.EVENT_GLOBAL_TAG_CHANGE (occurs when any tag in iRidi changes).

Unlike IR.AddListener, a global listener can be declared only 1 time. If it is declared again, only the last listener created by the interpreter when the script starts will work.

For the listener to be triggered when a tag changes in an iRidi project, subscribe to that change using the method IR.SubscribeTagChange.

Example:


// Set global listener
IR.SetGlobalListener(IR.EVENT_GLOBAL_TAG_CHANGE, function(name, value)
{
IR.Log("Active Global Listener: " + name + "\tValue: " + value);
});
// Subscribe
IR.SubscribeTagChange("Drivers.KNX IP Router.Address 1");
IR.SubscribeTagChange("Drivers.AV & Custom Systems (TCP).Online");
IR.SubscribeTagChange("UI.Page 1.Item 1.Text");
IR.SubscribeTagChange("System.Time.24");

The Script call command​

A script can be called using the Script call command assigned to a graphical item. The command can only be passed a pointer to a function without input parameters, but it allows you to execute a script at any time by pressing a button, without creating a separate listener:

ScriptEditor3.png

The drop-down list for the Script call command displays functions without input parameters. You cannot pass parameters to a function using this command.

Script execution rules​

Code executes asynchronously. When iRidi accesses a device, it does not interrupt interface operation, but receives data in a separate thread, as if you were accessing a remote website from your browser.

However, when a large number of operations are performed, such as loops, the entire GUI pauses and waits for the operation to finish before continuing.

Regular listeners can be declared multiple times. Global listeners can be declared only once.

Script files share a single namespace when the project starts. Do not use variables and functions with the same names in different script files.

Do not delete a graphical item before it has finished its associated operations; this will cause a command execution error.

Namespace​

JavaScript files in an iRidi project execute in a single namespace, and files are initialized sequentially from top to bottom. Take this into account when choosing function names and defining scopes. If variables or functions with the same identifier (name) are defined in different JS files, the function placed in memory last, i.e. in the file lower in the list, will be used at runtime.

This does not apply to listeners. If listeners for the same events are defined in a project, both execute.

JavaScript editor​

The JavaScript editor is used to create and place JavaScript files in an iRidi project.

Editor interface:

  1. Script tree.

Right-clicking a script file opens a menu:

  • Open: open the file,
  • Open in an external editor: open the file in an external editor,
  • Rename: rename the file,
  • Save: save the script,
  • Save as: save the script as a separate file,
  • Active: activate the script,
  • Disable: deactivate the script,
  • Set password: set a password for the script file,
  • Delete: delete the script file.
  1. Workspace.

Right-clicking a script name opens a menu:

  • Save: save the script,
  • Save as: save the script as a separate file,
  • Set password: set a password for the script file,
  • Close: close the script,
  • Close all: close all script files.
  1. Help on IR methods and events.

  2. Toolbar:

IconDescription
JSTree.pngShow the script tree.
ScriptEditor5.pngAdd:
* New script (a new script);
* Add script from file (an existing script file);
* New script folder (a new folder).
JSdel.pngDelete the script file selected in the list.
JSpass.pngSet a password for viewing and editing the script file (save and reopen the project for the password to take effect).
JSupdown.pngMove the file up/down.
JSapply.pngApply changes made to the script.
JSsavefile.pngSave to a *.js file
JSExternal_editor.pngOpen in an external editor.
JSundoredo.pngUndo/redo a change.
JSColor.pngInsert a color value in the editor.
JShelp.pngShow/hide help on IR methods and events.
JSserch.pngSearch for a word or string (Ctrl+F).

ScriptEditor4.png

Intelligent suggestions​

iRidi Studio includes an intelligent suggestion system to speed up script writing. It

  • Helps build correct command chains
  • Identifies the function you are writing and suggests the available functions, methods, and objects for it, reducing syntax errors and speeding up input
  • Displays a list of local resources, such as the audio files in the project

Ctrl + Space displays suggestions when they do not appear automatically.

ScriptEditor6.png

Debugging​

Code written in iRidi is debugged using the built-in debugging tool, the iRidi Log output console. The iRidi Log console is used to:

  • output data for debugging script operation
  • automatically find errors and indicate the line number where an error was found
  • save logging results to a file

The iRidi Log window can only be opened on Windows. iOS and Android use remote debugging: log data is sent to a remote Syslog Server.

i3 pro for Windows (unlike iOS, Android, and Mac) allows you to view the system log directly in the application (local logging) and also supports sending the log to a remote PC (remote logging).

Local logging​

You can open the i3 pro client application log for Windows by pressing F4 in the application window (or in the Emulator). To ensure that the required data appears in the log:

  1. Specify the logging depth for iRidi systems and subsystems in iRidi Studio. Configure it on the Debug tab in the Panel Project settings window. Logging depth ranges from EMERGENCY (errors only) to DEBUG (detailed information);

  2. Specify the logging depth for each driver added to the project;

  3. If your project contains JavaScript, use the IR.Log("text") method to output messages. Log1.png Log2.png

  4. Start the i3 pro application or Emulator on Windows and press F4 to open the log. Log_window.png

Remote logging​

The i3 pro log can be sent to a remote PC. It is sent using system log recording programs, collectively called Syslog Servers. An example of such a program is www.winsyslog.com

Install and configure the server:

  1. specify the service's UDP port: 514, the same as in the i3 pro system settings
  2. start the Syslog Server

Configure i3 pro to connect to the Syslog Server:

  1. On the Debug tab in the Panel Project settings window, activate remote debugging and enter the IP address of the PC running the Syslog Server in IP address. The logging port is 514. Specify the logging depth for iRidi systems and subsystems in iRidi Studio. Logging depth ranges from EMERGENCY (errors only) to DEBUG (detailed information).

  2. Specify the logging depth for each driver added to the project. Log1.png Log2.png

  3. i3 pro remote logging can be configured not only in the project on a PC, but also through the i3 pro system menu. Open the menu using the Show System Menu command by right-clicking the panel in iRidi Transfer, by pressing and holding an unused area of the project, or by swiping from the left edge of the screen. In Remote debug, turn on Enable and enter the IP address of the PC running the Syslog Server in Syslog host, the port (514), and the logging level. Log3-4.png

Output data to the log:


IR.AddListener(IR.EVENT_START, 0, function()
{
var test = 10;
IR.Log(test); // 10
});

Object hierarchy​

To access an interface object (a page, popup, item, or item property), driver (a connection, command, or tag), system parameters, sounds, etc., construct an access chain in which each element refers to the result of the preceding access operation. Follow the object hierarchy:

IR is the global object containing all iRidi API functions and constants, the top level of the hierarchy. You can view the object list in the Script Editor's intelligent suggestions. The nesting depth depends on the object you want to access and its level in the hierarchy.

Examples of hierarchical structure:


IR.GetPage("Page 1").GetItem("Item 1").Width = 100; // ссылка на ширину графического элемента


IR.AddListener(IR.EVENT_START,0,test); // создание слушателя


IR.CreateDevice(IR.DEVICE_CUSTOM_HTTP_TCP, "Driver", "myhost.com" 80); // создание HTTP драйвера


IR.GetDevice("Driver").Send(['string\r\n']); // отправка команды

Accessing interface objects​

Interface objects are pages, popups, and graphical items in an iRidi project.

Creating an object​

IR.CreateItem(IR.ITEM_BUTTON,"Button", 30, 40, 800, 150);
  • IR.ITEM_BUTTON is the type of item being created
  • "Button" is the item name
  • 30, 40, 800, 150 are the basic (required) item properties: X coordinate, Y coordinate, Width, Height

Item types:

  • IR.ITEM_BUTTON
  • IR.ITEM_LEVEL
  • IR.ITEM_MULTI_STATE_BUTTON
  • IR.ITEM_MULTI_STATE_LEVEL
  • IR.ITEM_JOYSTICK
  • IR.ITEM_EDIT_BOX
  • IR.ITEM_UPDOWN_BUTTON
  • IR.ITEM_TRIGGER_BUTTON
  • IR.ITEM_VIRTUAL_KEY_BUTTON
  • IR.ITEM_PAGE
  • IR.ITEM_POPUP
  • IR.ITEM_LISTBOX
  • IR.ITEM_STATIC_LISTBOX

The basic set of parameters is sufficient to create an item. However, each item type has its own set of specific properties:

Page

  • a page has no specific properties, but can process gestures

Popup

  • LifeTime: specified in milliseconds, determines how long after appearing the popup will close.
  • Effects: sets the popup's appearance and disappearance effects.
  • Drags: allows the popup to be moved anywhere while the application is running

Button

  • Active: active / does not accept presses
  • Hit: event handling type
  • Password Number: password for activating actions

Trigger Button

  • Active: active / does not accept presses
  • Hit: event handling type
  • Trigger Value 1: value for activating the 1st state
  • Trigger Value 2: value for activating the 2nd state

Multistate Button

  • Active: active / does not accept presses
  • Loop: cyclic repetition
  • TimeUp: forward animation playback time
  • TimeDown: reverse animation playback time
  • Hit: event handling type
  • Password Number: password for activating actions

Up/Down Button

  • Active: active / does not accept presses
  • Up/Down Value: value by which the current value is increased or decreased
  • Max/Min Value: maximum or minimum value
  • Hit: event handling type

Level

  • Min: minimum level value
  • Max: maximum level value
  • Range Type: value type
  • Direction: level direction
  • Focus Look Receive: ability to receive focus
  • Hit: event handling type
  • Invert: inversion, values reversed
  • Slider: graphical representation of the slider
  • Slider Color: slider color

Multistate Level

  • Min: minimum value
  • Max: maximum value
  • Direction: level direction
  • Focus Look Receive: ability to receive focus
  • Hit: event handling type
  • Invert: inversion, values reversed

EditBox

  • Active: active / does not accept presses

Virtual Key

  • Active: active / does not accept presses
  • Key Type: key type
  • Key Action: action performed by the key

Joystick

  • Range Type: value type
  • Active: active / does not accept presses
  • Focus Look Receive: ability to receive focus
  • Hit: event handling type
  • MinX: minimum X value
  • MinY: minimum Y value
  • InvertX: inversion along the X axis
  • InvertY: inversion along the Y axis
  • Cursor: graphical image of the cursor, which can be set from a script
  • Cursor Color: cursor color

Accessing an object​

Graphical interface objects are accessed according to their hierarchy. You can access an interface object:

By dragging the item into the JS editor window:

Script_editor1.png

By specifying the top-level item:

IR.GetItem("Page 1").GetItem("Item 1").GetState(0).FillColor
  • GetPage("Page 1"): page
  • GetItem("Item 1"): item on the page
  • GetState(0): item state, counted from zero
  • FillColor: state property

By specifying the page:

IR.GetPage("Page 1").GetItem("Item 1").Value
  • GetPage("Page 1"): page
  • GetItem("Item 1"): item on this page
  • Value: item property

By specifying the popup:

IR.GetPopup("Popup 1").GetItem("Item 1")
  • GetPopup("Popup 1"): popup
  • GetItem("Item 1"): item on this popup

By accessing an item on the current page:

IR.CurrentPage.GetItem("Item 1")
  • IR.CurrentPage: current page
  • GetItem("Item 1"): item on the current page

Through a variable that stores a reference to the object:

var item = IR.GetPage("Page 1").GetItem("Item 1")
  • var item: variable to which we assign the item
  • IR.GetPage("Page 1"): page
  • GetItem("Item 1"): item on the page

IR.AddListener(IR.EVENT_START,0,function()
{
IR.GetItem("Page 1").GetItem("Item 1").Width = 100; // обращение через GetItem("Item_Name")
IR.GetPage("Page 1").GetItem("Item 1").Height = 50; // обращение через GetPage("Page_Name")
IR.GetPopup("Popup 1").GetItem("Item 1").Text = "This is text"; // обращение через GetPopup("Popup_Name")
IR.CurrentPage.GetItem("Item_Name").Text = "This is item on current page"; //Обращение к текущей странице
var item = IR.GetPage("Page_Name") // запись идентификатора объекта в переменную
item.X = 20; // обращение к свойству объекта через переменную
});

An item can have multiple states, and each state has its own properties.

Therefore, to access a state property, use the statement

GetState(State_Number)

Where State_Number is the state number, numbered from zero:


IR.AddListener(IR.EVENT_START,0,function()
{
// присвоить текст второму состоянию элемента. Нумерация начинается в нуля, State 2 = GetState(1)
IR.GetItem("Page 1").GetItem("Item 1").GetState(1).text = 'state 2';
});

Interface events​

Event listeners are used to monitor user actions and interface changes.

A particular feature of interface listeners is that there is no global "interface change" event. Each button press must be processed by a separate listener. Keep this in mind if you plan to monitor a large number of items.

The number of listeners of all types in a project must not exceed 1024 .

Examples of events: pressing an item, displaying the keyboard, rotating the device.


// событие сработает при нажатии на элемент Item 1, который расположен на странице Page 1
IR.AddListener(IR.EVENT_ITEM_PRESS, IR.GetItem("Page 1").GetItem("Item 1"), function ()
{
IR.HidePopup("Popup 1"); // закрытие попапа по имени
});

<!--T:106-->

IR.EVENT_ITEM_PRESS is the event that activates the listener. Event list:

  • IR.EVENT_ITEM_PRESS
  • IR.EVENT_ITEM_RELEASE
  • IR.EVENT_ITEM_SELECT
  • IR.EVENT_ITEM_CHANGE
  • IR.EVENT_ITEM_HOLD
  • IR.EVENT_ITEM_SHOW
  • IR.EVENT_ITEM_HIDE
  • IR.EVENT_MOUSE_DOWN
  • IR.EVENT_MOUSE_UP
  • IR.EVENT_MOUSE_MOVE
  • IR.EVENT_TOUCH_DOWN
  • IR.EVENT_TOUCH_UP
  • IR.EVENT_TOUCH_MOVE
  • IR.EVENT_GESTURE_BEGIN
  • IR.EVENT_KEYBOARD_SHOW
  • IR.EVENT_ORIENTATION
  • IR.EVENT_APP_ENTER_BACKGROUND
  • IR.EVENT_APP_ENTER_FOREGROUND
  • IR.EVENT_APP_WILL_TERMINATE
  • IR.EVENT_RECIEVE_NOTIFY
  • IR.EVENT_RECIEVE_QR_CODE
  • IR.EVENT_RECIEVE_SCHEME
  • IR.ANDROID_MENU_PRESS
  • IR.ANDROID_BACK_PRESS
  • IR.BACKGROUND_OFF
  • IR.BACKGROUND_ON
Note

Mouse events cannot be used on devices without a mouse, such as tablets or smartphones. The TOUCH event works only on devices equipped with a touchscreen

Accessing drivers​

Drivers are used to interact with automation equipment, remote servers, and for other operations that require a TCP, UDP, HTTP(s), or RS232 connection. Using iRidi Script, you can:

  • create a driver
  • change driver settings
  • connect and disconnect
  • send a command
  • receive and process data

Creating a driver​

You can create a driver of type AV & Custom Systems based on freely configurable TCP, HTTP, or UDP transport. You can also create a TCP or UDP server based on AV & Custom Systems. Drivers of this type can process arbitrary data and send arbitrary commands. AV & Custom Systems is used to create drivers for equipment not supported by iRidi out of the box.

AMX, KNX, BAOS, Global Cache, and Crestron drivers can also be created from a script, but you cannot send arbitrary data to them. Commands for these drivers follow strict rules listed in the description of the Set command:

IR.GetDevice("driver").Set("name", "data")

To access drivers that cannot be created from a script, create the driver and commands in iRidi Studio > Project Device Panel (using the standard procedure described in the iRidi instructions for your equipment).

Driver creation command:


var driver = IR.CreateDevice(IR.DEVICE_CUSTOM_TCP, "AV Device (TCP)",
{Host: "192.168.0.47",
Port: 80
});
IR.Log(driver);

  • IR.DEVICE_CUSTOM_TCP is a driver type from the list of available types
  • "AV Device (TCP)" is the driver name, a string
  • "192.168.0.100" is the address to which the driver should connect
  • 8080 is the connection port

Each driver has its own set of connection parameters. See the detailed description in the reference.

Driver types (Device Type):

  • IR.DEVICE_CUSTOM_TCP
  • IR.DEVICE_CUSTOM_UDP
  • IR.DEVICE_CUSTOM_HTTP_TCP
  • IR.DEVICE_CUSTOM_SERVER_TCP
  • IR.DEVICE_CUSTOM_SERVER_UDP
  • IR.DEVICE_AMX
  • IR.DEVICE_EIB_UDP
  • IR.DEVICE_BAOS_1
  • IR.DEVICE_BAOS_2
  • IR.DEVICE_CRESTRON
  • IR.DEVICE_GLOBAL_CACHE
  • IR.DEVICE_UPNP_CONTROL
Note

The driver connects to the specified address immediately after it is created. If you do not want the driver to connect to equipment, leave the connection address ("host") empty.

Accessing a driver​

Once a driver has been created, you can access it to change settings, send commands, and process data received from it.

To access a driver, drag it into the JS editor window or manually enter the driver / network name in the command as shown in the example below:

Script_editor2.png


IR.GetDevice("driver_name");

A reference to the driver object can be assigned to a variable:


var driver = IR.GetDevice("driver_name");
driver.Disconnect();

Controlling a driver​

You can apply commands for connecting, disconnecting, and changing operating parameters to the created driver.


var driver = IR.GetDevice("driver_name");
driver.Disconnect(); // отключиться от оборудования
driver.SetParameters({Host: "192.168.0.21", Port: "9090"}); // изменить настройки подключения
driver.Connect(); // подключиться к оборудованию

Note

When connection settings change, the driver automatically disconnects from the equipment and reconnects using the new settings. You do not need to disconnect manually when executing the SetParameters command.

Sending commands​

Different methods can be used to send commands depending on the driver type. There are two methods in total, called Set and Send, and they work differently.

The Send method:


IR.GetDevice("Device_Name").Send(['send string\r\n']);

  • can only be used with a driver based on AV & Custom Systems. The method allows you to send an arbitrary string or number (DEC, HEX, ASCII) to equipment. Construct the string using the documentation for the equipment you want to control. The Send method works only with AV & Custom Systems!

The data to send is constructed directly in the script and is not associated with commands created using the standard procedure in iRidi Studio > Project Device Panel.

The Send method for drivers with multiple transports:


IR.GetDevice("Device_Name").Send(['send string\r\n'], transport_id);

  • transport_id is a number from 0 to n identifying the transport to which the command should be sent. 0 means send to all; 1...n means send to a specific ID
  • Drivers with multiple transports include Global Cache, since it uses ports 4998, 4999, and 5000. AV & Custom Systems TCP Server and UDP Server also use multiple transports because multiple clients can connect to them, each opening its own socket that can be accessed.

The Set method:

The Set method allows you to send a value to any previously created driver. To add a template, simply drag the command into the JS editor window and replace "0" with the value to send to the command:

Script_editor3.png


IR.GetDevice("Driver_Name").Set("Subdevice_name:Command_name", 100);

  • Driver_Name is the driver name;
  • Subdevice_name is the subdevice name (for a Network driver);
  • Сommand_name is the command name;
  • 100 is the number to pass to the command (a string can also be passed).
  • can be used with any iRidi driver you have created in iRidi Studio > Devices. Create and configure commands in the project tree beforehand; you can then call them at any time and pass any value to them. If a command only needs to be activated without passing a value, the syntax is:
IR.GetDevice("Device_Name").Set(["command_name", ""]);

Receiving and parsing data​

An AV & Custom Systems driver created in scripts or in Project Device Panel can receive arbitrary data, since the equipment it connects to is not predetermined. All other iRidi drivers receive data in a defined format already known to iRidi.

This results in two methods of parsing received data:

  • a method for arbitrary AV & Custom Systems data
  • a method for data received by preconfigured Feedbacks in the project tree (Project Device Panel)

Processing uses a listener that responds to a data reception event (for AV & Custom Systems) or a feedback channel change (for all other drivers).

IR.EVENT_RECEIVE_TEXT and IR.EVENT_RECEIVE_DATA


var driver = IR.GetDevice("AV Control") // указываем имя драйвера
// слушатель реагирует на получение данных
IR.AddListener(IR.EVENT_RECEIVE_TEXT, driver, function(text)
{
IR.Log(text) // выводим полученные данные в лог
// данные можно обработать внутри этого слушателя
});

IR.EVENT_RECEIVE_TEXT determines the format in which received information is displayed

  • IR.EVENT_RECEIVE_TEXT: text format
  • IR.EVENT_RECEIVE_DATA: byte format
Note

These methods work only with AV & Custom Systems drivers. They cannot be used with other drivers! The methods return the string or bit sequence received by the driver.

IR.EVENT_TAG_CHANGE


// указываем имя драйвера
// событие срабатывает при изменении тегов настроенных в проекте, вкладка Feedbacks
IR.AddListener(IR.EVENT_TAG_CHANGE, IR.GetDevice("driver_name"), function(name, value)
{
IR.Log(name+" : "+value) // в лог выводим имя тега и его новое значение
});

Note

This method works with any driver except AV & Custom Systems. The method returns the name of the channel that changed and its new value. The channel must be created in the project tree using the standard procedure (on the driver's Feedback tab).

Accessing tokens​

A token is a variable not associated with commands to automation equipment. It stores data about iRidi operation that can be accessed. There are three types of tokens.

Project tokens​

Project Tokens are named variables that can be created in iRidi. You can write a string, number, or data array to a variable and access the data using graphical item Relations or the iRidi API. Information in variables can be retained between launches of the iRidi application on the control panel.

  • are stored in the project's device tree, Project Device Panel
  • can be created using an iRidi API command while the application is running
  • can store a number, string, or array (DEC, ASCII).
  • can be created, deleted, copied, sorted, and grouped in folders
  • variable data can be retained after the iRidi application closes
  • data can be written using a command from an item or from iRidi Script

Creating a token and writing values

Use the function IR.SetVariable to write values to Project Tokens.

If the token being written to does not exist in the project, it will be created automatically by a call to IR.SetVariable*

IR.SetVariable("Tokens.TokenName", value)
  • Tokens. is a pointer for accessing a project token. Global. can also be used.
  • TokenName is the token name in Project Tokens on Project Device Panel
  • value is any value (a number, string, array of numbers, or array of strings)

Example:


IR.AddListener(IR.EVENT_START, 0, function()
{
// создадим токен test (его нет в Project Device Panel) и запишем в него число 23
IR.SetVariable("Tokens.test", 23);
// выведем данные из токена в консоль
IR.Log(IR.GetVariable("Tokens.test")); // 23
});

For writing arrays to Projects Token and retrieving them, see the JavaScript API usage examples

Reading values

Use the function IR.GetVariable to read values from Project Tokens.

If the token did not previously exist, it returns undefined. If the token was created in Project Device Panel but no value was written to it, it returns undefined

IR.GetVariable("Tokens.TokenName")
  • Tokens. is a pointer for accessing a project token. Global. can also be used.
  • TokenName is the name of any token in the Project Tokens folder on Project Device Panel

Example:


IR.AddListener(IR.EVENT_START, 0, function()
{
IR.SetVariable("Tokens.test", 23);
var gTest = IR.GetVariable("Tokens.test");
IR.Log(gTest); // 23
});

System tokens​

System Token returns control panel system parameter values: time, date, battery charge, GPS coordinates, etc. A token can be linked to any graphical item to display the information it receives.

You cannot write a value to a system token; the control panel's operating system supplies its data.

Accessing a token

Use the command IR.GetVariable to obtain data from a system token:


IR.GetVariable("System.Time.Seconds")

  • System. is a pointer to the type of variable to retrieve: a system variable
  • Time.Seconds is the system variable name, the same as in Project Device Panel

example:


IR.AddListener(IR.EVENT_START, 0, function()
{
var time = IR.GetVariable("System.Time.Seconds");
IR.Log(time);
});

For the full list of system tokens, see the reference.

Driver tokens​

Driver variables are read-only. The set of variables is the same for every driver.


IR.AddListener(IR.EVENT_START, 0, function()
{
// Driver Tokens
var tag1 = IR.GetVariable("Drivers.AV & Custom Systems.Online"); // Online..Offline = 1..0
var tag2 = IR.GetVariable("Drivers.AV & Custom Systems.Status"); // Offline..Connecting..Online..Waiting = 0..1..2..3
var tag3 = IR.GetVariable("Drivers.AV & Custom Systems.Host"); // domain name of remote equipment
var tag4 = IR.GetVariable("Drivers.AV & Custom Systems.HostPort"); // port of remote device
var tag5 = IR.GetVariable("Drivers.AV & Custom Systems.IP"); // IP address of Control Panel
var tag6 = IR.GetVariable("Drivers.AV & Custom Systems.HostIP"); // IP address of remote equipment
var tag7 = IR.GetVariable("Drivers.AV & Custom Systems.Port"); // local port on Control Panel
});

Accessing sounds​

iRidi can play audio files in multiple streams, called slots. The iRidi API provides:

  • starting and stopping audio file playback
  • stopping sound in a slot or in all slots
  • looping sound
  • volume control

To play an audio file, first add it to the project Gallery under Sound.

For a detailed description of all sound control functions, see the reference.

Accessing Server databases​

An SQL database is created in iRidi Server together with the server project. It allows Server variable states to be stored for charts and logs. There are two types of databases:

  • System database: data is written to it only through the server variable settings in iRidi Studio. It can be read using JavaScript, but cannot be edited or deleted
  • User database: accessed only through JavaScript. It can be written to, read, edited, and deleted using special JavaScript methods.

For all database methods, see the DataBase API.

System database​

The system database is read-only; the Server writes data to it.

The database consists of the following tables:

  • FLOAT_TAG_HISTORY: tags to which a decimal number was written
  • INTEGER_TAG_HISTORY: tags to which an integer was written
  • PROJECTS: projects downloaded to the server
  • QUALITY_LIST - [reserved]
  • STRING_TAG_HISTORY: tags to which a string was written
  • TAG_STATUSES - [reserved]
  • TAG_TYPES_LIST - [reserved]
  • TAGS_PASSPORT: all tag types (string, integer, float)
  • VERSION - [reserved]

Accessing the system database. For all database methods, see the DataBase API.


// присвоили переменной sql свойства системной базы
var sql = IR.GetDatabase();
// создадим запрос по базе
// присвоим переменной examp свойство Request базы sql. В кавычках тело запроса
var examp = sql.Request('SELECT ...');
IR.Log(examp.Columns); // количество полей (столбцов) в запросе
IR.Log(examp.Rows); // количество записей (строк) в запросе
IR.Log(examp.GetRowValue(0,1)); // значение ячейки в строке 1 и столбце 2
IR.Log(examp.GetColumnName(0)); // имя поля, у которого индекс соответствует числу в скобках

Example: select information from the database about tags that contain a value


var i;
var j;
IR.AddListener(IR.EVENT_START,0,function()
{
var sql = IR.GetDatabase();
var examp = sql.Request('SELECT DISTINCT(ID), VALUE, TAG_ID FROM FLOAT_TAG_HISTORY WHERE VALUE<1500');
for (i=0;i<examp.Columns;i++) // организовали цикл для вывода значений
for (j=0;j<examp.Rows;j++)
{
IR.Log(examp.GetRowValue(i,j)); // выводим в лог значения полей
};
});

User database​

You can create a database and add/update/delete its tables/fields/values. Store the database properties in a JavaScript variable to access its properties. The database is accessed using SQL queries.

For all database methods, see the DataBase API.

Create a database,

new SQL()
  • database definition in the iRidi JavaScript API
var mybase = new SQL();

Create the database file that we will work with

mybase.Open('Example.db');
.Open
  • open the database file. If the file does not exist, it will be created in the program's documents folder. For example, C:\Users\UserName\Documents\iRidium mobile 3\Settings\ Server\Database\Example.db is the database name with its extension.

For fast and correct database writes, use the logical commands


mybase.Execute("BEGIN");
...
// actions with DataBase
...
mybase.Execute("COMMIT");
mybase.Close();

  • .Execute is the function for performing a database operation
  • "BEGIN" starts writing to the database
  • "COMMIT" ends writing to the database
  • .Close() closes the database

The newly created database is empty. To create a table in the database, use the function

mybase.Execute('CREATE TABLE Info(ID int, Value double, Name string)');
  • CREATE TABLE is the function for creating a table named Info
  • ID, Value, Name are the names of table fields that will contain values of types int, double, and string, respectively. You can change the field names, but you must specify the field type.

To write to the database, use the structure:

mybase.Execute('INSERT INTO Info(ID, Value, Name) VALUES(1,2.5,"sunny day")');
  • INSERT INTO writes to the Info table, specifically to the fields ID, Value, Name; VALUES are the parameters that will be written to the fields. The ID field will contain the number 1, the Value field will contain the number 2.5, and the Name field will contain the text "sunny day".

The number of parameters in parentheses after VALUE must equal the number of fields declared in parentheses after

INSERT INTO <Имя таблицы>()

.

Writing values to table fields

Enclose text in double quotation marks:

VALUES("iRidi", "Mobile");

Write numbers without quotation marks, using a period for decimal numbers:

VALUES( 1, 2.5, 36.788);

Declare a variable beforehand and surround its name with single quotation marks and plus signs before and after it:


// var CV;
// var V;
...
VALUES( '+CV+', '+V+' );

Creating database queries​

To create database queries, familiarize yourself with the SQL language. Queries are needed when data must be selected from a database according to specific conditions. For all database methods, see the DataBase API.

For example: retrieve the day, hour, and minute when the temperature was > 10 degrees from a database containing weather information:


// создали переменную и присвоили ей объект sql.Request, в скобках указали тело запроса
var RecordSet = sql.Request("select * from TEST WHERE grades>10");
function inquiry()
{
sql.Open('weather.db'); // открыть базу данных "weather.db"
sql.Execute("BEGIN");
var RecordSet = sql.Request("select * from TEST WHERE grades>10");
// вывод в лог имена полей с 1 по 3
IR.Log(RecordSet.GetColumnName(0) +'\t'+ RecordSet.GetColumnName(1) +'\t'+ RecordSet.GetColumnName(2));
for (i=0;i<RecordSet.Rows;i++) // цикл будет выводить данные по строкам
IR.Log(RecordSet.GetRowValue(0,i)+'\t'+RecordSet.GetRowValue(1,i)+'\t' + RecordSet.GetRowValue(2,i));
sql.Execute("COMMIT"); // конец работы с базой
sql.Close();
};
IR.SetInterval(60000, inquiry); // вызов функции каждую минуту

Animation library​

attend a free training webinar

The animation library is a ready-made JavaScript file containing functions and methods for animating items in your project.

Standard methods use frame-by-frame animation and item state changes. The iRidi animation library allows you to create complex effects for individual items and groups.

Current library version and instructions

The iDate object​

iDate represents a date as a 64-bit floating-point number. It can handle dates and times from January 1, 100 to December 31, 9999.

The integer part represents the number of days since December 30, 1899; for example, the number 2 represents January 1, 1900. To specify dates before December 30, 1899, use a negative number; for example, -1 represents January 29, 1899.

The fractional part determines the time. To increase the time by 1 hour, add 1/24; to add 1 minute, add 1/1440. A drawback of the object is its low precision when working with milliseconds, with an error of +/-150 milliseconds.

iDate without arguments

When created without arguments, the object is initialized with the current date and time.


var date = new iDate();
IR.Log("Date " + date.year + "." + date.month + "." + date.day);
IR.Log("Time " + date.hours + ":" + date.minutes + ":" + date.seconds + "." + date.ms);
IR.Log("Value " + date.value);
/* result:
Date 2014.11.29
Time 20:49:20.778
Value 41972.86760159722
*/

iDate with 1 argument

The argument is value, a floating-point number representing the combined date and time.

When the object is created, the floating-point number is converted into an object from which the date and time can then be obtained.


// создадим объект iDate, передав ему целое положительное число.
var d1 = new iDate(16384);
IR.Log("Date 1 " + d1.year + "." + d1.month + "." + d1.date);
IR.Log("Time 1 " + d1.hours + ":" + d1.minutes + ":" + d1.seconds + "." + d1.ms);
IR.Log("Value 1" + d1.value);
/* result:
Date 1 1944.11.8
Time 1 0:0:0.0
Value 1 16384
*/
// создадим объект iDate, передав ему целое отрицательное число.
var d2 = new iDate(-16384);
IR.Log("Date 2" + d2.year + "." + d2.month + "." + d2.date);
IR.Log("Time 2" + d2.hours + ":" + d2.minutes + ":" + d2.seconds + "." + d2.ms);
IR.Log("Value 2" + d2.value);
/* result:
Date 2 1855.2.20
Time 2 0:0:0.0
Value 2 -16384
*/

iDate with more than 1 argument

Arguments:

  • year is the year
  • month is the month
  • date is the day
  • hours is the hour
  • minutes is the minute
  • seconds is the second
  • ms is the millisecond

When the object is created, the year, month, date, hour, minute, second, and millisecond are set separately. If not all parameters are supplied, the remaining parameters use their current values.


// создание объекта iDate, с текущими значениями даты и времени.
var cur = new iDate();
IR.Log("Cur Date " + cur.year + "." + cur.month + "." + cur.date);
IR.Log("Cur Time " + cur.hours + ":" + cur.minutes + ":" + cur.seconds + "." + cur.ms);
IR.Log("Cur Value" + cur.value);
/* result:
Cur Date 2014.11.29
Cur Time 21:6:45.128
Cur Value41972.879688981484
*/
// создание объекта iDate, с указанием года, месяца и числа
var date2 = new iDate(1999, 1, 21);
IR.Log("Date 2 " + date2.year + "." + date2.month + "." + date2.date);
IR.Log("Time 2 " + date2.hours + ":" + date2.minutes + ":" + date2.seconds + "." + date2.ms);
IR.Log("Value 2 " + date2.value);
/* result:
Date 2 1999.1.21
Time 2 21:6:45.133
Value 2 36181.87968903935
*/
// создание объекта iDate, с указанием года, месяца, числа, часа и минуты
var date4 = new iDate(1999, 1, 21, 4, 16);
IR.Log("Date 4 " + date4.year + "." + date4.month + "." + date4.date);
IR.Log("Time 4 " + date4.hours + ":" + date4.minutes + ":" + date4.seconds + "." + date4.ms);
IR.Log("Value 4 " + date4.value);
/* result:
Date 4 1999.1.21
Time 4 4:16:45.138
Value 4 36181.17830020833
*/
// создание объекта iDate, с указанием года, месяца, числа, часа, минуты, секунды и миллисекунды
var date6 = new iDate(1999, 1, 21, 4, 16, 12, 400);
IR.Log("Date 6 " + date6.year + "." + date6.month + "." + date6.date);
IR.Log("Time 6 " + date6.hours + ":" + date6.minutes + ":" + date6.seconds + "." + date6.ms);
IR.Log("Value 6 " + date6.value);
/* result:
Date 6 1999.1.21
Time 6 4:16:12.400
Value 6 36181.177921296294
*/

Ready-made iRidi modules​

iRidi modules are ready-made iRidi projects containing JavaScript files, created by iRidi Mobile or third-party developers. You can merge them with your own iRidi project to use additional functionality without programming it yourself.

Depending on its purpose (a clock, weather display, calendar, audio/video control, etc.), a module may or may not require an iRidi license. This information is usually provided in the module description.

Note

Any module that uses the AV & Custom Systems driver or another driver requires a license. A module that uses IR.EVENT_RECEIVE_TEXT and IR.EVENT_RECEIVE_DATA listeners requires a license with the "Pro" suffix in its name.

Usage instructions are not available for all modules. General procedure:

  1. download the module (a project file with the *.irpz extension)
  2. open the module in iRidi Studio
  3. open the project to which you want to add the module in iRidi Studio
  4. in Project Overview, drag the module into your project to merge them
  5. use the module's pages and popups as part of your project

Coding standard for ready-made modules​

Naming convention:

  1. Separate words using changes in character case (camel case). Tabulation: 3 characters, not spaces.

  2. Constructor functions used with the new operator start with an uppercase letter


function AbstractDriver () {
};
var Driver_1 = new AbstractDriver ();

  1. Functions and public object method functions start with a lowercase letter

function updateRequest () {
};
function AbstractDriver () {
this.getData () {
};
};
var Driver_1 = new AbstractDriver ();
Driver_1.getData ();

  1. Public but temporary or private object method functions start with an underscore followed by a lowercase letter

function AbstractDriver () {
this._getPassword () {
};
_prepare = function () {
}
_prepare (); // private method
};
var Driver_1 = new AbstractDriver ();
Driver_1._getPassword (); // temporary API method

  1. Property names start with a lowercase letter

var lastIndex = 0;

  1. Constants use uppercase characters, with words separated by underscores

var EVENT_GENERATED_END = 0;

  1. Function input parameters use the in_ prefix, with the first syllable in lowercase

function resizeProject (in_width, in_height) {
};

  1. Function output parameters use the out_ prefix, with the first syllable in lowercase

function checkConnection () {
return out_status;
};

  1. Namespaces use uppercase characters throughout

KNX = {};

  1. Spacing: after keywords, before opening parentheses, before braces, and after commas

function name (in_arg1, in_arg_2) {
return out_arg;
};

  1. Semicolons: at the end of a line, after a closing brace

  2. Documenting methods and constructors


/**
* Purpose of the function - the method appointment
* * @namespace Name of the namespace - name of space
* @method / @onstructor Name of the function - name of method or constructor
* @param {Type} Description - input data
* @return {Type} Description - output data
*/
/**
* Create the data base of the app
* * HDL
* @method createDataBase
* @param {String} Path of the file
* @return {Boolean} Success of the action
*/
function createDataBase (in_path) {
return out_result;
};

Books and websites about JavaScript​

If you have not encountered JavaScript before and are unfamiliar with the object-oriented development paradigm, visiting informational websites and studying the literature is recommended. The websites listed here are ones we like; you can always find a resource better suited to your needs.

Websites:

Books: "Eloquent JavaScript" Knowledge level: beginner, language: ENG, author: Marijn Haverbeke. An introductory book on JavaScript and programming in general.

"Learning Javascript Design Patterns" Knowledge level: beginner, language: ENG, author: Addy Osmani The book covers classic and modern JavaScript programming patterns

"jQuery Fundamentals" Knowledge level: beginner, language: ENG, author: Rebecca Murphey A community-created book on JavaScript and jQuery.

"Javascript Enlightenment" Knowledge level: intermediate, language: ENG, author: Cody Lindley A thorough overview of JavaScript's worldview through an examination of built-in objects and nuances.

"Smooth CoffeeScript" Knowledge level: intermediate, language: ENG, author: E. Hoigaard An introduction to CoffeScript focusing on clarity, abstraction, and verification.

"Building A JavaScript Framework" Knowledge level: advanced, language: ENG, author: Alex Young, Selected articles from the "Let's Make a Framework" series.