Documentation · v1
PROMIN Scripting Guide
Learn PROMIN scripting for controller v1.20: JavaScript automation, Global helpers, parameters, controller API methods, code examples, operating limits, and troubleshooting.
Controller software v1.20 · Script API v1
1. Introduction
This guide describes the Scripts page and the controller API available in Promin controller software v1.20. Scripts are JavaScript programs used to combine controller operations, exchange data with other equipment, and implement logic that is difficult to express as a single trigger action.
A script can be started from the Scripts page or from a trigger. It can read parameters, call the controller API, wait, write messages to the console, and return a result. API calls that change a layout, output, trigger, or external device have real effects on the installation. Check IDs, equipment connections, and the selected parameters before running an example.
The examples use illustrative IDs and addresses. Replace them with values from your controller. Timelines must be prepared and baked after changes before they are played.
2. Scripts workspace
2.1. Page layout
Open Scripts from the main menu. Figure 1 identifies the main working areas: the page controls (1), the Scripts list (2), the Source editor (3), the test and diagnostics panel (4), and the Properties / API panel (5). Selecting a script updates its source, properties, test parameters and available run information.
Total shows the number of ordinary scripts; Global is a separate shared item. Running shows the number of executions currently reported as running. Refresh reloads the script list and run status. The list button beside Refresh hides or shows the left panel.
Stop all scripts requests cancellation of every running script. It becomes available when scripts are running. Commands already sent to the controller or external equipment are not undone. This button stops script execution; it is separate from stopping layout playback.
Use Hide properties at the top of the right panel to give the editor more room. Show properties in the Source header restores that panel. These controls change the workspace view.
2.2. Scripts list
New script (1) creates an ordinary script and selects it for editing. Search scripts (2) filters ordinary scripts by name. Clear the search text to show the complete list. Global script (3) remains pinned above the ordinary scripts and contains shared variables and helper functions.
Each ordinary script card (4) displays its name and Enabled or Disabled state. A running item also shows Running and an activity indicator. Select a card to open it. The selected card is highlighted; its name also appears in the Source header.
Unsaved changes marks a local draft. Switching to another item keeps drafts in the current Scripts workspace; leaving the page or reloading the browser can discard them. Save each draft that should be retained. A warning appears before leaving the page when unsaved changes exist.
Ordinary script cards can be dragged to change their order. The drop indicator shows whether the item will be placed before or after another card. Global remains pinned. Reordering changes the list order; it does not schedule script execution.
Server version changed means another saved version is available while your draft is still open. Copy any changes you need, then use Reload saved before saving again. Deleted on controller means the original item was removed elsewhere; copy any draft you need before leaving.
2.3. Source editor and toolbar
The Source editor displays the selected JavaScript document with line numbers and syntax highlighting. The name in the header (6) identifies the current item; an asterisk after the name indicates unsaved changes. Code completion and parameter hints help when entering the documented controller API.
Save (1) stores the current source and editable properties. A disabled Save button normally means there are no changes to save or the workspace is temporarily busy. Saving an ordinary script does not run it.
Undo / Redo (2) step through source edits. The shortcuts are Ctrl+Z for Undo and Ctrl+Y or Ctrl+Shift+Z for Redo. These controls apply to source editing; use Save to store the resulting revision.
Run (3) starts the selected enabled ordinary script using the JSON array in Parameters. When the draft contains changes, the button reads Save & Run: it saves the draft before starting execution. Run is unavailable while that script is already running, when it is disabled, or when a conflict or request prevents execution.
Stop (4) requests cancellation of the selected script's running execution. Read the confirmation before proceeding: stopping a run can also interrupt other scripts that share the environment. Completed controller commands remain in effect.
Reload saved restores the selected item's saved source and properties. If a draft has changes, the interface asks before discarding them. Duplicate creates a new ordinary script from the saved revision; unsaved edits are not included. Delete removes the selected ordinary script after confirmation and can be blocked by references or active execution. Global has its own Apply control instead of Run, Duplicate and Delete.
The Errors / Warnings summary (7) reports editor analysis. Use the summary button or F8 to move to the next reported problem. Analysis helps locate code issues; a zero count does not prove that IDs, parameters or external devices will be valid when the script runs.
2.4. Parameters and diagnostics
The panel below Source has four tabs. Parameters prepares a manual invocation; Console, Result and Problems help inspect execution and code issues. When recent runs are available, Console, Result and Problems show a Run selector. Choose the required execution by its start time, status and short run ID before interpreting its messages or result. Selecting a past run does not execute it again.
2.4.1. Parameters
Enter a valid JSON array in the input (2), such as [] for no arguments or ["Scene A", 75] for two arguments. These values are passed to ctx.params in the same order. Parameters is data, not JavaScript source; use double quotes for strings and omit comments and trailing commas.
Test parameters are associated with the selected ordinary script in the workspace. They do not replace the parameters configured in a trigger action. Entering parameters does not start a run; use Run or Save & Run. If validation fails, the panel displays an error that must be corrected.
The footer shows the saved revision and the last available run status. No recent runs means there is no run to inspect in the current workspace. Global has no manual test parameters.
2.4.2. Console
Console displays ctx.log messages for the selected execution, with a time, severity and message text. Use it to follow progress and identify which step completed before an error. While the selected execution is running, the console refreshes periodically; Refresh console (2) requests another read.
If several runs are listed, select the correct Run first. No ctx.log messages for this run means a run exists but has no displayed log messages; Select or start a run to view its messages means no run is selected or available. The empty state in Figure 5 does not represent a failed execution.
2.4.3. Result
After selecting a run, Result displays its status, script revision, Global revision, start time and, when available, duration. For a completed run, it also displays the JSON value returned by main(ctx). A running execution shows that it is still in progress; an unsuccessful execution shows its error code and message.
Use the revision information to distinguish an older run from the source currently open in the editor. A successful return value does not confirm the physical response of external equipment, and viewing a result does not repeat or undo the run.
2.4.4. Problems
Problems collects editor errors and warnings together with execution or save errors that include a source location. The number beside the tab indicates the available problems. An entry can identify Source or Global and include a line and column.
Select the location button beside a problem to open the corresponding document and reveal that position. An error reported in Global can therefore take you from an ordinary script to the shared source. Correct the relevant document and save it; shared changes also require Apply before ordinary runs use them.
No problems found means there are no currently displayed diagnostics for the script or Global. Runtime checks, API calls and communication with external devices can still report an error during execution.
2.5. Properties
Script ID (1) is the stable identifier used for references and script actions. Use the copy button to copy it; renaming the script does not change its ID. Name (2) is the human-readable label shown in the list and Source header.
Enabled (3) controls whether the ordinary script may be started. Save a changed setting before relying on it in trigger actions. Timeout, ms (4) limits one execution and accepts an integer from 1 to 300000 milliseconds. Include the planned waits and external operations when choosing the timeout.
Description (5) documents the purpose, expected parameters and effects of the script; it accepts up to 4096 characters. Changes to Name, Enabled, Timeout and Description belong to the draft and are stored by Save or Save & Run.
Revision (6) identifies the saved script version. API identifies its controller scripting API version. These are information fields, not the controller software version. Properties for Global are different and are described in section 2.7.
2.6. API reference panel
Select API at the top of the right panel. Search (1) filters methods using their names and reference text. The grouped list (2) covers context functions, timelines, layouts and color, runtime, digital I/O, TCP / UDP, RS232, HTTP and triggers. Scroll inside the method list to reach the remaining groups.
Select a method to display its description and Signature (3). Parameters (4) gives argument names, types, descriptions and optional markers. Returns (5) describes the result or promise. Read these fields before adapting an example; a method name alone does not show all required arguments.
Copy (6) copies the displayed example to the clipboard. It does not insert code into Source, save a script or execute a command. Paste the example into the editor, replace illustrative IDs and values, and include the required await or error handling. Scroll the reference panel if the example or notes are below the visible area.
Switch back to Properties to view the selected script's settings. The method reference belongs to the installed controller version; use section 7 of this guide for the API overview and section 8 for complete examples.
2.7. Global script controls and status
Select Global script in the pinned list item. The toolbar provides Save, Undo, Redo, Apply and Reload saved. Save (1) stores shared source; Apply (2) loads the saved revision for use by ordinary scripts. The interface asks for confirmation because applying resets shared variable values.
The status row (3) displays Environment and Loaded revision. In Properties, Saved revision is the version stored by Save; Applied revision records the applied shared version; Loaded revision identifies the revision currently loaded. Compare these values when a helper function behaves differently from the editor source.
Changes (5) distinguishes Unsaved changes, Saved, not applied and Applied. Save a dirty Global draft before Apply. Apply is also unavailable while scripts are running, while a conflicting revision or request is unresolved, or when the reported environment status does not allow it. The hint near the toolbar explains the current condition.
Global is not started with Run and has no ordinary script parameters. After saving and applying shared changes, select an ordinary script and test the intended use of those helpers. Section 6 explains shared definitions and variable lifetime.
3. Creating and running a script
1. Open Scripts and select New script. Give the script a clear name and description and set an appropriate timeout.
2. Enter the source in the editor. An ordinary script uses an async main function receiving ctx, as shown below.
3. Select Save. Check Problems and correct any errors.
4. In Parameters, enter a valid JSON array, for example []. Parameters are positional; [] supplies no arguments.
5. Select Run and inspect Console and Result. Run performs real operations: it is not a simulation.
6. If necessary, select Stop to request cancellation. Check the actual state of the controlled equipment afterwards.
async function main(ctx) {
ctx.log.info('Script started');
await ctx.sleep(500);
ctx.log.info('Script finished');
return { ok: true };
}Save a script before relying on it in a trigger. After changing the source, save and test the intended revision. The timeout must allow for all waits and external operations, including a reasonable margin. Avoid long waits when the trigger must respond quickly.
4. JavaScript structure and asynchronous operations
A script combines JavaScript logic with the controller functions exposed through ctx. Use an ordinary script for a specific job, such as looking up a layout, choosing a scene or exchanging a command with another device. Use Global for definitions that several jobs need. This section explains how the two sources work together and how to keep asynchronous work within one execution.
4.1. Ordinary script and Global script: different roles
An ordinary script is an executable job with its own ID, Enabled setting, parameters and timeout. Global is a shared source document containing reusable functions and initial values. Applying Global prepares those definitions; it does not run every ordinary script or call a function simply because it is named main.
| Aspect | Ordinary script | Global script |
|---|---|---|
| Purpose | Perform one defined job. | Provide shared helpers, constants and variables. |
| How it starts | Run / Save & Run, or a Run Script trigger action. | Apply loads and evaluates the saved Global source. |
| Entry point | The controller calls main(ctx). | Top-level declarations and initialization; no ordinary Run entry point. |
| Input | Receives this execution's ctx and ctx.params. | Helpers receive values or ctx explicitly from their caller. |
| Local and shared data | Local declarations are recreated for each run. | Shared values can survive between ordinary runs until reset. |
| Activating an edit | Save makes the revision available for the next run. | Save stores source; Apply activates the saved revision. |
| Result | Return JSON-compatible data for the run's Result panel. | A helper returns data to its caller; Global has no ordinary run result. |
| Reusing code | Local helpers belong to this script's source. | Shared helpers can be called by different ordinary scripts. |
Table 1. Ordinary and Global scripts.
Write plain JavaScript source. TypeScript type annotations and import / export statements are not part of this scripting format. Put reusable declarations in Global and call them by name. Declaring a function prepares it for later calls; statements that call the function actually execute its body.
4.2. Structure of an ordinary script
Start with async function main(ctx). Keep the executable steps inside main or functions it calls. The controller supplies ctx when the run begins, so do not call main yourself at the bottom of the source. Return a small JSON-compatible value when the job is complete.
async function main(ctx) {
ctx.log.info('Reading layouts');
const layouts = await ctx.api.layouts.list();
return { layoutCount: layouts.length };
}async allows the function to use await and return its eventual result. main is the entry-point name. ctx is the argument containing this run's parameters and controller tools. const declares a value that will not be reassigned. The API call obtains the layouts; return finishes the function and supplies the value shown in Result.
Use let when a variable must be reassigned, and const otherwise. const does not freeze an object: its properties can still change. Names declared inside a function or block are local to that scope. You may also declare local helper functions outside main in the ordinary source; those helpers are created again for each run.
Always return a JSON-compatible value explicitly. Use return null when no result is needed. Reaching the end of main without return produces undefined, which is not a valid run result. Avoid returning functions, promises nested inside objects, circular objects or values such as BigInt.
4.5. Working with ctx
ctx.params is the JSON array supplied for this run. Indexes start at zero: the first argument is ctx.params[0]. Check presence, type and allowed range before using an argument. A missing array element is undefined; avoid treating 0, false or an empty string as missing unless that is the intended rule.
ctx.api contains the documented controller methods. Use the API panel to check argument shapes and return values. Object names are useful to people, but methods usually require saved IDs. Keep calculations in JavaScript and call the API when controller data or an operation is needed.
ctx.log.info, ctx.log.warn and ctx.log.error write messages to Console and the SCRIPT journal. They are synchronous logging calls and do not need await. Add a small JSON details object when it helps explain the step, input or result.
ctx.sleep(ms) returns a promise for a delay. Await it to pause this run between steps. ctx.scriptId identifies the script, ctx.runId identifies this particular execution, ctx.operationId identifies its operation, and ctx.triggeredBy describes the caller. Include the run ID in diagnostic output when comparing several executions.
Keep ctx attached to the current execution. Pass it down to helpers as a function argument and use ctx.params as input data. Do not overwrite its API, logging or identity fields.
4.6. What async and await actually do
An asynchronous API call returns a Promise: a value representing work that has not necessarily finished. await waits for that promise to resolve and gives you its result. If it rejects, await throws an error at that line, so try / catch can handle it.
Without await, the variable contains a promise.
async function main(ctx) {
const pending = ctx.api.layouts.list();
const layouts = await pending;
return { layoutCount: layouts.length };
}Do not read pending.length as if it were the returned layout array. Either await the call immediately or keep its promise and await it before using the result. Await every operation that must complete before main returns; starting work without waiting can let the execution finish before its outcome is available.
await only waits for what the selected method promises. For example, awaiting timelines.play returns the playback identifiers after playback has been started; it does not wait for the timeline to reach its end. A delay of a chosen length is also not a playback-finished notification. Read each method's description before using it as a sequencing boundary.
An async helper follows the same rule. Its caller must await the helper, or return the helper's promise as the final result of an async function. Adding async to a function does not make all unawaited calls inside it finish before the function returns.
4.7. Sequential steps, loops and parallel reads
Use successive await statements when order matters. In a loop, for...of with await processes one item at a time. This is useful when later work depends on earlier results or when commands must be sent in a defined order.
async function main(ctx) {
const layouts = await ctx.api.layouts.list();
const results = [];
for (const layout of layouts) {
const state = await ctx.api.layouts.getState(layout.id);
results.push({
layoutId: layout.id,
playbackCount: state.playbacks.length
});
}
return results;
}Do not use forEach(async (...) => ...) when main must wait for every item. forEach does not wait for the promises returned by its callbacks. Start with a sequential for...of loop; only introduce parallel work when the requests are independent.
For a small set of independent reads, Promise.all can start the requests together and wait for all their results. The array of results follows the input order, even when the requests finish in a different order.
async function main(ctx) {
const [layouts, timelines] = await Promise.all([
ctx.api.layouts.list(),
ctx.api.timelines.list()
]);
return {
layoutCount: layouts.length,
timelineCount: timelines.length
};
}If one promise rejects, Promise.all rejects, but other requests may already be running or completed. It does not cancel or undo them. Do not use parallel writes when their order affects the installation. Avoid starting a large unbounded batch of requests.
4.8. Delays, bounded repetition and timeout
Use await ctx.sleep(ms) for a delay instead of an empty loop that repeatedly checks time. A sleep accepts an integer from 0 to 300000 milliseconds. Waiting still counts towards the script's Timeout, ms, whose maximum is 300000 milliseconds for the whole run.
async function main(ctx) {
for (let sample = 1; sample <= 3; sample += 1) {
const layouts = await ctx.api.layouts.list();
ctx.log.info('Sample', {
sample,
layoutCount: layouts.length
});
if (sample < 3) await ctx.sleep(500);
}
return { samples: 3 };
}This example reads three times and waits only between samples. Set the script timeout to allow both waits, the API reads and a reasonable margin. A delay or an HTTP request with its own timeout cannot extend the remaining script timeout.
Give repeated work a clear stopping condition or fixed count. An endless loop is eventually stopped by the run timeout; it is not a permanent background task. Different scripts may overlap, but a second active invocation of the same ordinary script is rejected as busy.
Stop or timeout can interrupt the sequence before later lines execute. Earlier controller commands can remain in effect, and shared values may be reset during recovery. Design an explicit way to inspect and restore the required output state after an interrupted run.
4.9. Errors, logging and the final result
Use throw new Error(...) to reject invalid input with a clear explanation. Put dependent asynchronous calls inside try / catch when you need to add context to an error or handle a known condition. Re-throw an error that should make the execution fail.
async function main(ctx) {
try {
const id = ctx.params[0];
if (typeof id !== 'string' || !id.trim()) {
throw new Error('Parameter 1 must be a layout ID');
}
const layout = await ctx.api.layouts.get(id.trim());
ctx.log.info('Read completed', { layoutId: layout.id });
return { ok: true, layoutId: layout.id };
} catch (error) {
ctx.log.error('Could not read the layout', {
message: String(error)
});
throw error;
}
}Logging with ctx.log.error does not itself fail the execution. If you catch an error and then return { ok: false }, the JavaScript run can still be marked completed with that object as its result. Throw the error when the failure must be visible as a failed run.
Some failures are represented in a successful API response. HTTP, for example, can return a response with a 4xx or 5xx status; check response.status explicitly. Use try / catch for a rejected request and separate status checks for the returned HTTP response.
finally is useful for ordinary control flow, such as recording the end of a handled operation. Do not rely on it as guaranteed output cleanup after Stop, timeout or another interruption. Completed actions are not automatically reversed when main returns or throws.
4.10. A practical editing and testing sequence
- Decide which part is the job and which part is reusable. Keep job-specific decisions in the ordinary script and shared helpers in Global.
- Define the parameter order and types. Start with reads and validation before adding commands that change outputs.
- Edit Global if needed, Save it and Apply the intended revision. Confirm that it is loaded before testing an ordinary caller.
- Save the ordinary script, enter a representative JSON array in Parameters and Run it. Check Problems, then Console and Result for that execution.
- Test missing or invalid parameters and an unavailable object as well as the successful case. Check that a failure is reported clearly and that already completed actions leave the intended state.
- Configure the trigger's script action only after the manual example behaves as expected. Test the complete trigger path with the same parameter contract.
When a helper is missing, check the applied Global revision and spelling before changing the caller. When a result is a promise or undefined, check the await and return statements. When the order is wrong, check for unawaited calls, forEach with async callbacks, or shared variables changed by another run. See sections 5, 6 and 9 for parameter details, shared-state rules and operational limits.
5. Parameters and results
5.1. Manual parameters
Parameters is a JSON array, not JavaScript source. Use double quotes for strings, no comments, and no trailing commas. The first element is ctx.params[0], the second is ctx.params[1], and so on. Objects and arrays can be nested. For example:
["Main hall", 75, {"fadeMs": 1000}]Validate both the presence and the type of input before operating equipment. Decide whether missing values should cause an error or use an explicit default. An empty array means no parameters; a missing element must not be assumed to contain a value.
async function main(ctx) {
const name = ctx.params[0];
const level = ctx.params[1];
if (typeof name !== 'string' ||
typeof level !== 'number' || level < 0 || level > 100) {
throw new Error('Expected a name and brightness from 0 to 100');
}
ctx.log.info('Parameters accepted', { name, level });
return { name, level };
}5.2. Trigger parameters
A trigger can receive incoming parameters and pass them to its actions, including a script action. Configure the action to supply the required values and document their order and types. The script reads them through the same ctx.params array as in a manual run. Test the script manually with representative values, then test the complete trigger path.
When a script calls another trigger through ctx.api.triggers.run, pass that trigger's parameter array explicitly. Do not assume the current ctx.params are automatically forwarded. A trigger can cause further actions, so avoid accidental recursive trigger chains.
Configure trigger events and input parameters in the Controller User Guide.
5.3. Return value
Return a JSON-compatible value to present a useful result in the Result panel. For example, return an object containing IDs, a success flag, and calculated values. A returned value does not undo controller changes. Report errors with a clear message; catch an error only when the script can handle it or add useful context before rethrowing it.
6. Controller API reference
Use the Controller API to read saved objects, inspect live state and perform controller operations from JavaScript. Open the API panel in the Scripts workspace to check the signatures available on the installed version. Names shown in the interface help you find objects, but calls normally require their IDs. Obtain IDs through list() methods or pass them explicitly in the script's Parameters array; do not substitute a display name for an ID.
All ctx.api methods are asynchronous: await the call before using its result or starting a dependent step. ctx.sleep is also asynchronous; ctx.log methods are synchronous. The examples below are complete ordinary scripts unless stated otherwise. Replace sample addresses and parameter values with those of your installation.
A successful call means the operation reached the completion point described for that method. Starting playback does not wait until the timeline ends, starting a fade does not wait for the fade to finish, and sending a message does not prove that the receiving device carried out the command. Read the relevant state or use the receiving device's response when confirmation is needed. API failures reject the call; handle them with try/catch or allow them to fail the run. Completed actions are not automatically undone.
6.1. General functions
ctx.sleep(ms) — wait without blocking script scheduling.
Pass an integer delay from 0 to 300000 milliseconds and use await ctx.sleep(ms). For example, 250 means a quarter of a second. The wait counts towards the script's overall timeout; a valid delay can therefore still exceed the time remaining in the run. Stop or timeout interrupts the wait. It returns no data. Use it between bounded polling attempts or timed steps rather than a loop that repeatedly checks the clock.
ctx.log.info(message, details?), ctx.log.warn(message, details?), ctx.log.error(message, details?) — record diagnostics.
message may be a JSON-compatible value. The optional details argument is an object containing JSON-compatible values, such as { layoutId, count: 3 }. Use info for normal progress, warn for an unexpected condition that you can handle, and error for a failed operation. These calls return no value and do not need await. Their entries are available in Console and the controller's journal with the run's context.
Writing an error-level message does not by itself fail the script. Throw an error when execution must fail; return a value when it should complete normally. Keep repeated messages useful: log a change or a summary rather than every iteration of a fast loop.
Example: record progress, wait 250 ms and return an explicit result.
async function main(ctx) {
ctx.log.info('Check started', { runId: ctx.runId });
await ctx.sleep(250);
ctx.log.info('Check complete');
return { checked: true };
}6.2. Timelines
ctx.api.timelines.list() — discover saved timelines.
Returns an array of summaries with id, name, layoutId, durationMs, loop and clockSource. durationMs is the saved duration in milliseconds; clockSource is internal or artnet_timecode. An empty array means there are no saved timelines. The list contains settings, not tracks or clips, and does not indicate whether a timeline is currently playing.
ctx.api.timelines.get(timelineId) — read one timeline's settings.
Returns the same summary fields plus fadeInMs, fadeOutMs and autoTrim. Use this to inspect the saved target Layout, timing and playback options before starting it. The argument is the timeline's ID. An unknown ID rejects with timeline_not_found; get does not create or prepare a timeline.
ctx.api.timelines.play(timelineId, options?) — start playback.
The timeline plays on its saved layoutId. options accepts positionMs and fadeInMs; both are non-negative numbers in milliseconds. positionMs defaults to 0 and must not exceed the saved duration. If fadeInMs is omitted, the saved fade-in is used; 0 requests no fade-in. The saved loop, clock source and fade-out settings are used. There is no Layout override in this call.
The result is { layoutId, timelineId, playbackId }. Keep playbackId when you need to distinguish this playback from another start of the same timeline. Await waits for the start command's result, not for the full playback duration. The timeline must already be available for playback, its Layout must exist, and any required external timecode must be available. Failures can include timeline_not_ready, timecode_unavailable or runtime_unavailable.
Example Parameters: ["your-timeline-id"]. The script checks the ID and starts at the beginning with a 500 ms fade-in.
async function main(ctx) {
const [timelineId] = ctx.params;
const timeline = await ctx.api.timelines.get(timelineId);
ctx.log.info('Starting timeline', { name: timeline.name });
return await ctx.api.timelines.play(timeline.id, {
positionMs: 0,
fadeInMs: 500
});
}6.3. Layouts
Reading configuration: list() and get(layoutId).
ctx.api.layouts.list() returns an array of { id, name }. ctx.api.layouts.get(layoutId) returns { id, name, gridW, gridH }; gridW and gridH describe the Layout's dimensions. These calls read saved configuration. They do not return the patch, pixel buffer or current rendered image, and do not change playback.
ctx.api.layouts.getState(layoutId) — inspect live state.
Returns { layoutId, blackoutEnabled, playbacks, color }. playbacks is an array and may be empty; do not assume that element 0 exists. Each playback includes playbackId, timelineId, layoutId, clockSource, phase, paused, stopping, loop, positionMs, durationMs, fadeInMs and fadeOutMs. phase can be pending, active or fading. positionMs can be null when a position is not available; do not interpret null as zero.
color is null when no color layer is active. Otherwise it contains instanceId, layoutId, color, brightness, phase, fadeInMs, durationMs, fadeOutMs, indefinite and remainingHoldMs. remainingHoldMs can be null; indefinite identifies an unlimited hold. blackoutEnabled reports the controller-wide blackout state, which can affect the visible output even while playback or a color layer is present.
Playback controls: pause, resume and seek.
await ctx.api.layouts.pause(layoutId) pauses playback and returns { layoutId, paused: true }. resume(layoutId) resumes it and returns { layoutId, paused: false }. These operate on the current playback of the Layout; they do not start a selected timeline. If no playback is active, they can reject with playback_not_active.
await ctx.api.layouts.seek(layoutId, positionMs) requests a non-negative position in milliseconds and returns { layoutId }. Use 1500 for 1.5 seconds. The requested position and the playback's clock mode must support seeking; an invalid position or unsupported operation rejects the call. Re-read getState when you need the resulting playback position.
ctx.api.layouts.stop(layoutId, options?) — stop one Layout's playback.
options accepts fadeOutMs. Omit it to use the playback's fade-out setting, or set it to 0 to stop immediately. The result is { layoutId, stopping, alreadyStopped }. stopping indicates that stopping is in progress; alreadyStopped indicates that there was no active playback to stop. A resolved call can therefore precede the end of a fade. Treat playback stop and color-layer removal as separate operations; use clearColor to remove an applied color.
ctx.api.layouts.setColor(layoutId, options) — apply the Replace color layer.
The options object is required, but each of its fields is optional. color is a six-digit #RRGGBB string, default #FFFFFF. brightness is a number from 0 to 100 percent, default 100. fadeInMs, durationMs and fadeOutMs are non-negative timings in milliseconds, each defaulting to 0. Do not pass CSS color names, an RGB array, or a brightness value on the 0–255 scale.
fadeInMs controls appearance, durationMs controls the hold, and fadeOutMs controls disappearance after a timed hold. durationMs: 0 holds indefinitely; it does not mean an immediate flash. The result { layoutId, instanceId } identifies the applied color layer. The call returns after application is confirmed, without waiting for its entire fade/hold/fade-out sequence.
ctx.api.layouts.clearColor(layoutId, options?) — remove the color layer.
options accepts fadeOutMs, default 0. The result is { layoutId }. Clearing the layer reveals the underlying content if any is active. It does not start a stopped timeline or disable blackout. Coordinate color and playback commands when both are used on the same Layout.
Example Parameters: ["your-layout-id"]. Apply blue at 75% brightness with a 300 ms fade-in, a 2 second hold and a 300 ms fade-out. The returned state is a snapshot immediately after application, not after the hold.
async function main(ctx) {
const [layoutId] = ctx.params;
await ctx.api.layouts.setColor(layoutId, {
color: '#00A0FF',
brightness: 75,
fadeInMs: 300,
durationMs: 2000,
fadeOutMs: 300
});
return await ctx.api.layouts.getState(layoutId);
}To remove an indefinite color explicitly, use the following call inside main; it leaves the underlying playback available.
await ctx.api.layouts.clearColor(layoutId, { fadeOutMs: 300 });6.4. Runtime
ctx.api.runtime.getState() — inspect the whole controller.
Returns { blackoutEnabled, activePlaybacks, layoutColors }. activePlaybacks and layoutColors contain the same playback and color fields described for layouts.getState, but across all Layouts. Use this method for a system-wide overview, or layouts.getState for one Layout. The result is a snapshot and does not subscribe the script to future changes.
ctx.api.runtime.setBlackout(enabled) — set global blackout.
Pass the Boolean true to enable blackout or false to disable it; strings such as "true" and numbers such as 1 are not accepted. Returns { blackoutEnabled } with the confirmed state. Blackout affects the controller's output globally. Disabling it can make the content that is still active visible again; it is not a command to start a particular timeline.
ctx.api.runtime.stopAll() — stop all Layouts and clear their color layers.
Takes no arguments and returns { stopped: true }. This affects playback and color layers throughout the installation, unlike layouts.stop(layoutId). It is not a command to stop all scripts, switch digital outputs, or send an off command to external equipment.
Example: read a global snapshot and return a compact summary without changing outputs.
async function main(ctx) {
const state = await ctx.api.runtime.getState();
return {
blackoutEnabled: state.blackoutEnabled,
playbackCount: state.activePlaybacks.length,
colorLayerCount: state.layoutColors.length
};
}6.5. Digital inputs and outputs
Discovering channels: listInputs() and listOutputs().
ctx.api.digital.listInputs() and listOutputs() return arrays of { ref, name } for local controller channels and configured relay-module channels. Use the returned ref object in subsequent calls. A configured channel appearing in the list does not prove that its remote module is currently online.
A local reference is { kind: 'local', portId: 'port1' } or the equivalent with port2. A relay-module reference is { kind: 'module', moduleSerial: 'YOUR_SERIAL', channel: 0 }. moduleSerial identifies the configured module, and channel is zero-based: 0 is the first channel and 7 is the eighth. Do not replace the serial with the module's display name or use 1–8 numbering in this field.
ctx.api.digital.getInput(ref) and getOutput(ref) — read a known state.
Both return { value, cached, moduleStatus? }. value is the number 0 or 1, or null when no level is known. Test it explicitly; null must not be treated as a confirmed off state. Local reads have cached: false. A module read has cached: true and uses its last known status; repeated reads do not force a fresh query to the module.
For a module, inspect moduleStatus as well as value. It includes serial, availability, identityConflict, profileVerified, stateRevision, lastResponseAt and lastError. A cached value can remain present when the module is unavailable or its status is stale. Use availability and lastResponseAt to judge whether the value is suitable for the decision you are making.
ctx.api.digital.setOutput(ref, value) — write an output or relay.
Pass numeric 0 or 1; Boolean true, the string "1" and a toggle command are not supported values. The call targets an output reference, not an input reference. It returns { value, confirmation } and, for a module, may also return stateRevision and relayMask.
confirmation: 'local_write' means the local write completed. confirmation: 'module_status' means the module's reported relay state confirmed the write; stateRevision identifies the resulting status revision and relayMask represents its relay states. Neither independently proves that an attached contact, lamp or circuit physically operated. A failed or unconfirmed write rejects the call rather than returning a successful confirmation.
Example: read the first local input and return an explicit known/unknown state. The code does not switch any output.
async function main(ctx) {
const ref = { kind: 'local', portId: 'port1' };
const state = await ctx.api.digital.getInput(ref);
if (state.value === null) {
ctx.log.warn('Input level is unknown');
return { known: false };
}
return { known: true, value: state.value, cached: state.cached };
}Example Parameters: ["your-module-serial", 0, 1]. Select the module channel and desired numeric level explicitly; this script changes the selected relay.
async function main(ctx) {
const [moduleSerial, channel, value] = ctx.params;
const target = { kind: 'module', moduleSerial, channel };
return await ctx.api.digital.setOutput(target, value);
}6.6. Ethernet and RS232
Ethernet discovery and state.
ctx.api.ethernet.listSockets() returns configured TCP and UDP sockets with id, name, protocol, enabled, localPort and timeoutMs; UDP entries can also include type. Use id to select the socket. protocol is tcp or udp and is determined by its configuration; send has no separate protocol selector.
ctx.api.ethernet.getState(socketId) returns { id, protocol, enabled, ready, listening }. Use it to inspect the controller-side socket state. ready or listening does not prove that a remote device is reachable or that it has accepted a command. An unknown or disabled socket cannot be used for a successful send.
ctx.api.ethernet.send(socketId, payload, destination) — send text.
All three arguments are required. payload is a UTF-8 string, at most 8192 bytes. destination is { host, port }, where host is the receiving device's address or hostname and port is its numeric destination port. localPort from listSockets describes the controller-side configuration; it is not automatically used as the remote port.
UDP sends the string as one datagram using the selected socket. TCP performs an outgoing send to the specified destination; it does not reply through a previously accepted incoming connection. The result is { sent: true }. This confirms completion of the send operation, not an application response or execution by the remote device.
Example Parameters: ["your-socket-id", "192.168.1.20", 5000]. Include CRLF explicitly if required by the receiver.
async function main(ctx) {
const [socketId, host, port] = ctx.params;
return await ctx.api.ethernet.send(
socketId, 'PING\r\n', { host, port }
);
}RS232 discovery, settings and state.
ctx.api.rs232.listPorts() returns { portId, settings } entries for port1 and port2. settings includes baudRate, dataBits, parity, stopBits and flowControl. Configure these settings in the controller interface to match the external device; the scripting send method does not change them.
ctx.api.rs232.getState(portId) returns { portId, open, available, settings, error }. Check available and open and inspect error when diagnosing a port. Use the logical IDs port1 or port2, not an interface label invented for the connected device.
ctx.api.rs232.send(portId, payload) — write serial text.
payload is a UTF-8 string with the same 8192-byte limit. The result is { sent: true } after the serial write has drained. It does not wait for the device to answer. For both send APIs, the byte limit can be reached before 8192 characters when the text contains multi-byte characters. Supply the exact string expected by the receiver, including any required terminator; no terminator is added automatically.
Example: send a line to port1 using its configured serial settings.
async function main(ctx) {
return await ctx.api.rs232.send('port1', 'POWER ON\r\n');
}Receiving messages and handling failures.
Incoming TCP and RS232 messages are delimited by CRLF (\r\n); UDP messages follow datagram boundaries. To react to incoming data, configure the corresponding Trigger event and a Run Script action, then bind the required incoming values to the action's parameters. send does not return the received message, and this API has no message subscription or read-next-message method.
Handle unavailable sockets/ports, connection failures and failed writes with try/catch when recovery is appropriate. A timeout or failed reply check does not prove that the previous command was not received; avoid blindly repeating commands whose effects would be duplicated.
6.7. HTTP
ctx.api.http.request(url, options?) — perform an HTTP or HTTPS request.
url is the complete address, including http:// or https:// and any path or query. Do not use a relative path. The optional options object accepts only method, headers, body and timeoutMs. With no options, the method is GET, headers are empty, body is an empty string and timeoutMs is 10000.
method can be GET, POST, PUT, PATCH, DELETE, HEAD or OPTIONS. headers is an object whose names and values are strings. Use headers such as Accept, Content-Type and Authorization as required by the receiving service. The client manages connection framing headers such as Content-Length. body must be a string; for JSON, call JSON.stringify(value) and set Content-Type to application/json.
timeoutMs is an integer from 100 to 60000. It limits the request, while the script's overall timeout still applies. A request cannot extend the time remaining in the script. Stop or script timeout cancels the outstanding request.
Reading the response.
The resolved value is { status, body, headers }. status is the numeric HTTP status, body is a string and headers contains response header values as strings or arrays of strings. This is a plain data object: use response.body directly, not response.json() or response.text(). When JSON is expected, validate the status first and then parse the string with JSON.parse; invalid or empty JSON still needs handling.
HTTP statuses including 3xx, 4xx and 5xx resolve normally. A 404 or 500 therefore does not enter catch automatically. Define the successful status range for the service and throw or handle other statuses explicitly. Network failures and timeouts reject instead; relevant error codes include timeout, dns_error, connection_error, tls_error, http_busy, response_too_large and cancelled.
Payload and response limits.
The request body is limited to 64 KiB of UTF-8 data and request headers to 16 KiB. The received body has a 128 KiB limit, and the complete response object must also fit the script's JSON data limit; a body close to 128 KiB can exceed that limit once its headers and JSON encoding are included. Read a smaller resource or use pagination when the service supports it.
Redirects, retries and cookies are not handled automatically. A redirect response must be handled deliberately; sending another request is a separate operation. The method has no responseTriggerId or errorTriggerId option: process the response in the script and call a trigger explicitly if required.
Example Parameters: ["https://your-service.example/api/status"]. Read JSON and reject an unsuccessful HTTP status.
async function main(ctx) {
const [url] = ctx.params;
const response = await ctx.api.http.request(url, {
headers: { Accept: 'application/json' },
timeoutMs: 5000
});
if (response.status < 200 || response.status >= 300) {
throw new Error('HTTP status ' + response.status);
}
return JSON.parse(response.body);
}Example Parameters: ["https://your-service.example/api/mode", "party"]. Send a JSON object with POST; the service's response body is returned as text so an empty response is also valid.
async function main(ctx) {
const [url, mode] = ctx.params;
const response = await ctx.api.http.request(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mode }),
timeoutMs: 5000
});
if (response.status < 200 || response.status >= 300) {
throw new Error('HTTP status ' + response.status);
}
return { status: response.status, body: response.body };
}6.8. Triggers
ctx.api.triggers.list() and get(triggerId) — read trigger summaries.
list returns an array of { id, name, description, enabled, eventType, actionCount }; get returns the same fields for one ID. These are summaries, not the complete event conditions, action definitions or parameter bindings. Use them to locate an existing trigger and check whether it is enabled; configure its event and actions in the Triggers interface.
ctx.api.triggers.run(triggerId, params?) — invoke an enabled trigger.
Pass the saved trigger ID and an optional JSON-compatible array. The default is []; values from ctx.params are not forwarded automatically. To forward them unchanged, pass ctx.params explicitly. To send different values, build an array in the order expected by the trigger, for example ["party", 75]. Use numbers, Booleans, objects or arrays in their original JSON types rather than converting every value to text.
The array supplies trigger parameters for that invocation. Actions consume them through their configured parameter bindings; a literal value saved in an action does not become a binding automatically. This is an explicit trigger invocation and does not wait for its configured external event to occur. A disabled or missing trigger rejects with trigger_disabled or trigger_not_found.
Completion and action reports.
The call waits for the trigger's action execution and returns { triggerId, operationId, actions }. Each action report has actionId and status: completed, skipped or failed, with an optional error object. A completed playback-start action means its start operation completed, not that the timeline has finished playing. A skipped action did not execute; do not count it as a completed change.
If an action fails, the call can reject with trigger_action_failed. When supplied, error.details.report contains the action report, including completed and failed actions. Inspect it when diagnosing a partial execution. Earlier actions are not rolled back automatically. A timeout or interrupted call can leave already completed actions in effect.
Avoid invocation chains in which a script starts a trigger that starts the same script again. Check the complete dependency path before combining Run Script and triggers.run. The caller's timeout must allow for the trigger's delays and actions; use separate event-driven steps for processes that should continue beyond a single script run.
Example Parameters: ["your-trigger-id", "party", 75]. The script explicitly forwards the second and third values as the trigger's first and second parameters.
async function main(ctx) {
const [triggerId, mode, brightness] = ctx.params;
const trigger = await ctx.api.triggers.get(triggerId);
if (!trigger.enabled) {
throw new Error('Target trigger is disabled');
}
return await ctx.api.triggers.run(
trigger.id, [mode, brightness]
);
}Connect scripts to trigger actions in the Controller User Guide.
7. Examples
Replace every example ID, address, and payload with the correct value for the installation. Begin with non-destructive reads and review the controlled equipment before enabling action examples.
7.1. Find a layout and start a timeline
async function main(ctx) {
const timelineId = ctx.params[0];
if (typeof timelineId !== 'string' || !timelineId) {
throw new Error('Pass the timeline ID as parameter 1');
}
const timeline = await ctx.api.timelines.get(timelineId);
ctx.log.info('Starting timeline', { id: timelineId });
const playback = await ctx.api.timelines.play(timelineId, {
positionMs: 0,
fadeInMs: 1000
});
return { timeline, playback };
}7.2. Set and clear a layout color
async function main(ctx) {
const layoutId = ctx.params[0];
if (typeof layoutId !== 'string' || !layoutId) {
throw new Error('Pass the layout ID as parameter 1');
}
await ctx.api.layouts.setColor(layoutId, {
color: '#FF0000', brightness: 50, fadeInMs: 1000
});
await ctx.sleep(3000);
await ctx.api.layouts.clearColor(layoutId, { fadeOutMs: 1000 });
return { layoutId, finished: true };
}If the script is stopped during the wait, the clearColor call might not run. Inspect the layout and clear the color explicitly if required.
7.3. Inspect digital references
async function main(ctx) {
const inputs = await ctx.api.digital.listInputs();
const outputs = await ctx.api.digital.listOutputs();
ctx.log.info('Digital references', { inputs, outputs });
return { inputs, outputs };
}Use the returned reference for the desired port or module channel with getInput, getOutput, or setOutput. Check that the selected output and value are correct before writing.
7.4. Send an RS232 message
async function main(ctx) {
const port = 'port1';
const state = await ctx.api.rs232.getState(port);
ctx.log.info('Sending serial command', { port, state });
await ctx.api.rs232.send(port, 'PING\r\n');
return { sent: true };
}PING and CRLF are examples only. Use the command, encoding and terminator expected by the connected device. A successful send does not guarantee that the device accepted or acted on the command.
7.5. Make an HTTP request
async function main(ctx) {
const url = ctx.params[0];
if (typeof url !== 'string' || !url) throw new Error('URL required');
try {
const response = await ctx.api.http.request(url, {
method: 'GET', timeoutMs: 5000
});
if (response.status < 200 || response.status >= 300) {
throw new Error('HTTP status ' + response.status);
}
return { status: response.status, body: response.body };
} catch (error) {
ctx.log.error('HTTP request failed', { message: String(error) });
throw error;
}
}7.6. Run a trigger with parameters
async function main(ctx) {
const triggerId = ctx.params[0];
if (typeof triggerId !== 'string' || !triggerId) {
throw new Error('Pass the trigger ID as parameter 1');
}
return await ctx.api.triggers.run(triggerId, ['Scene A', 75]);
}8. Operational limits
Execution time: each ordinary script has its own timeout, from 1 to 300000 ms. A request to stop or a timeout interrupts waiting and outstanding operations; already completed controller actions are not automatically reversed. Check the resulting device and layout states.
Sleep: ctx.sleep accepts an integer from 0 to 300000 ms. A sleep that exceeds the remaining script time will not extend the script timeout.
HTTP: request timeout is 100–60000 ms, default 10000 ms; request body is at most 64 KiB in UTF-8. HTTP status codes must be checked. Automatic redirects, retries, and cookie handling are not provided.
Ethernet and RS232: each outgoing payload is at most 8192 UTF-8 bytes. Delivery or a successful write does not prove that the external device performed the requested action.
Parameters and results: use JSON-compatible data for parameters, return values, and log details. Parameters must be an array. Validate incoming values and handle absent or unexpected values. Do not rely on large or continuous data streams being handled as one script parameter.
Shared environment: applying Global resets shared variables. Shared values are not persistent storage, and concurrent scripts can change them. Coordinate operations where order matters.
API scope: use the controller functions documented in the API panel. Available methods, argument shapes, and limits depend on the installed software version. An external device, configured socket, timeline, layout, or relay module must exist and be available before a dependent call can succeed.
Project effects: a script may change playback, colors, outputs and external equipment. It is the author's responsibility to design a safe final state, particularly when a run is stopped, times out, or an intermediate call fails. Bake changed timelines before playback.
9. Troubleshooting
| Situation | What to check |
|---|---|
| Script does not run | check Enabled, syntax in Problems, the saved revision, the entry function, and whether the timeout is suitable. Check the run result and Console for the reported error. |
| Unexpected parameter value | check that Parameters contains a valid JSON array, that the trigger action passes the intended values, and that the script uses the correct zero-based indexes and types. |
| Shared helper is missing or has an old value | save Global and Apply it; then rerun the ordinary script. Applying Global resets shared variables. |
| A timeline or layout does not respond | verify the ID, object state, and API result. Check blackout, playback state, and whether the timeline was baked after edits. |
| A relay or digital output does not behave as expected | verify the reference returned by listOutputs, module connection and channel, and the actual external circuit. A reported state is not a substitute for checking the connected equipment. |
| Ethernet, RS232, or HTTP fails | verify the configured endpoint, port settings, payload and terminator, request timeout, response status, and availability of the other device. Check the exact message in Console and the SCRIPT journal. |
| A script stopped before finishing | determine whether Stop or timeout interrupted it. Earlier commands can remain in effect. Inspect the installation and explicitly restore the intended state if necessary. |