OpenWrt uloop event loop

The uloop binding provides functions for integrating with the OpenWrt uloop library.

Functions can be individually imported and directly accessed using the named import syntax:

import { init, handle, timer, interval, process, signal, task, run } from 'uloop';

init();

handle(…);
timer(…);
interval(…);
process(…);
signal(…);
task(…);

run();

Alternatively, the module namespace can be imported using a wildcard import statement:

import * as uloop from 'uloop';

uloop.init();

uloop.handle(…);
uloop.timer(…);
uloop.interval(…);
uloop.process(…);
uloop.signal(…);
uloop.task(…);

uloop.run();

Additionally, the uloop binding namespace may also be imported by invoking the ucode interpreter with the -luloop switch.

Classes

uloop.handle

Represents a uloop handle instance as returned by handle().

uloop.interval

Represents a uloop interval timer instance as returned by interval().

uloop.pipe

Represents a uloop task communication pipe instance, passed as sole argument to the task function by task().

uloop.process

Represents a uloop process instance as returned by process().

uloop.signal

Represents a uloop signal Unix process signal handler as returned by signal().

uloop.task

Represents a uloop task instance as returned by task().

uloop.timer

Represents a uloop timer instance as returned by timer().

Methods

cancelling() → {boolean}

Checks if the uloop event loop is currently shutting down.

This function checks whether the uloop event loop is currently in the process of shutting down.

Returns: boolean

Returns true if uloop is currently shutting down, false otherwise.

Example
// Check if the uloop event loop is shutting down
const shuttingDown = uloop.cancelling();
if (shuttingDown)
    printf("uloop event loop is currently shutting down\n");
else
    printf("uloop event loop is not shutting down\n");

done() → {void}

Stops the uloop event loop and cancels pending timeouts and events.

This function immediately stops the uloop event loop, cancels all pending timeouts and events, unregisters all handles, and deallocates associated resources.

Returns: void

This function does not return any value.

Example
// Stop the uloop event loop and clean up resources
uloop.done();

end() → {void}

Halts the uloop event loop.

This function halts the uloop event loop, stopping its execution and preventing further processing of scheduled events and callbacks.

Expired timeouts and already queued event callbacks are still run to completion.

Returns: void

This function does not return any value.

Example
// Halt the uloop event loop
uloop.end();

error() → {string}nullable

Retrieves the last error message.

This function retrieves the last error message generated by the uloop event loop. If no error occurred, it returns null.

Returns: string

Returns the last error message as a string, or null if no error occurred.

Example
// Retrieve the last error message
const errorMessage = uloop.error();

if (errorMessage)
    printf(`Error message: ${errorMessage}\n`);
else
    printf("No error occurred\n");

handle(handle, callback, events) → {handle}nullable

Creates a handle instance for monitoring file descriptor events.

This function creates a handle instance for monitoring events on a file descriptor, file, or socket. It takes the file or socket handle, a callback function to be invoked when the specified IO events occur, and bitwise OR-ed flags of IO events (ULOOP_READ, ULOOP_WRITE) that the callback should be invoked for.

Parameters:
NameTypeDescription
handlenumber | module:fs.file | module:fs.proc | module:socket.socket

The file handle (descriptor number, file or socket instance).

callbackfunction

The callback function to be invoked when the specified IO events occur.

eventsnumber

Bitwise OR-ed flags of IO events (ULOOP_READ, ULOOP_WRITE) that the callback should be invoked for.

Returns: handle

Returns a handle instance for monitoring file descriptor events. Returns null when the handle, callback or signal arguments are invalid.

Example
// Create a handle for monitoring read events on file descriptor 3
const myHandle = uloop.handle(3, (events) => {
    if (events & ULOOP_READ)
        printf("Read event occurred!\n");
}, uloop.ULOOP_READ);

// Check socket for writability
const sock = socket.connect("example.org", 80);
uloop.handle(sock, (events) => {
    sock.send("GET / HTTP/1.0\r\n\r\n");
}, uloop.ULOOP_WRITE)

init() → {boolean}nullable

Initializes the uloop event loop.

This function initializes the uloop event loop, allowing subsequent usage of uloop functionalities. It takes no arguments.

Returns true on success. Returns null if an error occurred during initialization.

Returns: boolean

Returns true on success, null on error.

Example
// Initialize the uloop event loop
const success = uloop.init();

if (success)
    printf("uloop event loop initialized successfully\n");
else
    die(`Initialization failure: ${uloop.error()}\n`);

interval(timeoutopt, callback) → {interval}nullable

Creates an interval instance for scheduling repeated callbacks.

This function creates an interval instance for scheduling repeated callbacks to be executed at regular intervals. It takes an optional timeout parameter, which defaults to -1, indicating that the interval is initially not armed and can be armed later with the .set(timeout) method. A callback function must be provided to be executed when the interval expires.

Parameters:
NameTypeDescription
timeoutnumber(optional, default: -1)

Optional. The interval duration in milliseconds. Defaults to -1, indicating the interval is not initially armed.

callbackfunction

The callback function to be executed when the interval expires.

Returns: interval

Returns an interval instance for scheduling repeated callbacks. Returns null when the timeout or callback arguments are invalid.

Example
// Create an interval with a callback to be executed every 1000 milliseconds
const myInterval = uloop.interval(1000, () => {
    printf("Interval callback executed!\n");
});

// Later arm the interval to start executing the callback every 500 milliseconds
myInterval.set(500);

process(executable, argsopt, envopt, callback) → {process}nullable

Creates a process instance for executing external programs.

This function creates a process instance for executing external programs. It takes the executable path string, an optional string array as the argument vector, an optional dictionary describing environment variables, and a callback function to be invoked when the invoked process ends.

Parameters:
NameTypeDescription
executablestring

The path to the executable program.

argsstring[](optional)

Optional. An array of strings representing the arguments passed to the executable.

envObject<string: *>(optional)

Optional. A dictionary describing environment variables for the process.

callbackfunction

The callback function to be invoked when the invoked process ends.

Returns: process

Returns a process instance for executing external programs. Returns null on error, e.g. due to exec() failure or invalid arguments.

Example
// Create a process instance for executing 'ls' command
const myProcess = uloop.process("/bin/ls", ["-l", "/tmp"], null, (code) => {
    printf(`Process exited with code ${code}\n`);
});

run(timeoutopt) → {boolean}nullable

Runs the uloop event loop.

This function starts running the uloop event loop, allowing it to handle scheduled events and callbacks. If a timeout value is provided and is non-negative, the event loop will run for that amount of milliseconds before returning. If the timeout is omitted or negative, the event loop runs indefinitely until explicitly stopped.

Parameters:
NameTypeDescription
timeoutnumber(optional, default: -1)

Optional. The timeout value in milliseconds for running the event loop. Defaults to -1, indicating an indefinite run.

Returns: boolean

Returns true on success, null on error.

Example
// Run the uloop event loop indefinitely
const success = uloop.run();
if (success)
    printf("uloop event loop ran successfully\n");
else
    die(`Error occurred during uloop execution: ${uloop.error()}\n`);

// Run the uloop event loop for 1000 milliseconds
const success = uloop.run(1000);
if (success)
    printf("uloop event loop ran successfully\n");
else
    die(`Error occurred during uloop execution: ${uloop.error()}\n`);

running() → {boolean}

Checks if the uloop event loop is currently running.

This function checks whether the uloop event loop is currently started and running.

Returns: boolean

Returns true if the event loop is currently running, false otherwise.

Example
// Check if the uloop event loop is running
const isRunning = uloop.running();
if (isRunning)
    printf("uloop event loop is currently running\n");
else
    printf("uloop event loop is not running\n");

signal(signal, callback) → {signal}nullable

Creates a signal instance for handling Unix signals.

This function creates a signal instance for handling Unix signals. It takes the signal name string (with or without "SIG" prefix) or signal number, and a callback function to be invoked when the specified Unix signal is caught.

Parameters:
NameTypeDescription
signalstring | number

The signal name string (with or without "SIG" prefix) or signal number.

callbackfunction

The callback function to be invoked when the specified Unix signal is caught.

Returns: signal

Returns a signal instance representing the installed signal handler. Returns null when the signal or callback arguments are invalid.

Example
// Create a signal instance for handling SIGINT
const mySignal = uloop.signal("SIGINT", () => {
    printf("SIGINT caught!\n");
});

task(taskFunction, outputCallbackopt, inputCallbackopt) → {task}nullable

Creates a task instance for executing background tasks.

This function creates a task instance for executing background tasks. It takes the task function to be invoked as a background process, an optional output callback function to be invoked when output is received from the task, and an optional input callback function to be invoked when input is required by the task.

Parameters:
NameTypeDescription
taskFunctionfunction

The task function to be invoked as a background process.

outputCallbackfunction(optional)

Optional. The output callback function to be invoked when output is received from the task. It is invoked with the output data as the argument.

inputCallbackfunction(optional)

Optional. The input callback function to be invoked when input is required by the task. It is invoked with a function to send input to the task as the argument.

Returns: task

Returns a task instance for executing background tasks. Returns null on error, e.g. due to fork failure or invalid arguments.

Example
// Create a task instance for executing a background task
const myTask = uloop.task(
    (pipe) => {
        // Task logic
        pipe.send("Hello from the task\n");
        const input = pipe.receive();
        printf(`Received input from main thread: ${input}\n`);
    },
    (output) => {
        // Output callback, invoked when task function calls pipe.send()
        printf(`Received output from task: ${output}\n`);
    },
    () => {
        // Input callback, invoked when task function calls pipe.receive()
        return "Input from main thread\n";
    }
);

timer(timeoutopt, callback) → {timer}nullable

Creates a timer instance for scheduling callbacks.

This function creates a timer instance for scheduling callbacks to be executed after a specified timeout duration. It takes an optional timeout parameter, which defaults to -1, indicating that the timer is initially not armed and can be enabled later by invoking the .set(timeout) method on the instance.

A callback function must be provided to be executed when the timer expires.

Parameters:
NameTypeDescription
timeoutnumber(optional, default: -1)

Optional. The timeout duration in milliseconds. Defaults to -1, indicating the timer is not initially armed.

callbackfunction

The callback function to be executed when the timer expires.

Returns: timer

Returns a timer instance for scheduling callbacks. Returns null when the timeout or callback arguments are invalid.

Example
// Create a timer with a callback to be executed after 1000 milliseconds
const myTimer = uloop.timer(1000, () => {
    printf("Timer expired!\n");
});

// Later enable the timer with a timeout of 500 milliseconds
myTimer.set(500);

Type Definitions

Event Mode Constants

The ULOOP_* constants are passed as bitwise OR-ed number to the handle() function to specify the IO events that should be monitored on the given handle.

Properties
NameTypeDescription
ULOOP_READnumber

File or socket is readable.

ULOOP_WRITEnumber

File or socket is writable.

ULOOP_EDGE_TRIGGERnumber

Enable edge-triggered event mode.

ULOOP_BLOCKINGnumber

Do not make descriptor non-blocking.