Skip to content
Page cover
For the complete documentation index, see llms.txt. This page is also available as Markdown.

Scripts

Automate your workflow with tasks based on events, jobs, schedules, and more. Limitless capabilities with custom resources to fit your needs.

Introduction

Code is wrritten in Lua, which is a lightweight, high-level programming language designed for embedded use, known for its simplicity and efficiency. Created in Brazil in 1993, it features dynamic typing, first-class functions, and a powerful table data structure, making it versatile for various applications. Lua is widely used in game development for scripting game logic, as well as in embedded systems and applications due to its extensibility and small footprint, allowing developers to easily integrate it with other languages and platforms.

LUA 5.1 Manual

How It Works

To extend Oktopus capabilities and adress the most diverse possible use cases we opted to use a scripting language on top of the actual code, so the gopher-lua library provides Go APIs that allows to easily embed LUA scripts to Go programs.

The Go software can interact to the LUA script and vice-versa. That way, it's possible to pass functions, parameters and events through both USP Controller/ACS and the user created automations.

Core Concepts

A "custom function", is as a function called from LUA which translates to a Go function that can interact with NATS, MongoDB, USP Controller, TR-069 ACS and all the other components of the software stack.

Diagram of Lua Scripts

The "custom functions" will be detailed above in the next topics as just "functions" and separated into domain areas. We hope to provide usefull examples, and the limitation is on each person creativity.

Event listener concurrency

listen_to_cwmp_event(), listen_to_usp_event() and listen_to_new_device() are listeners: they subscribe to a stream of events and run your callback once per event. How a listener processes events concurrently matters when you write the script.

Each unit of parallelism is a fully isolated Lua VM running its own copy of the script. When a listener asks for parallelism N, Oktopus starts N independent VMs and load-balances incoming events across them — every event is handled by exactly one VM, and each VM handles one event at a time. The VMs never share Lua state with each other.

What that means for your script:

  • Top-level code runs once per VM. Keep the top level to declaring constants and functions and the listen_to_* call itself. Real work done at the top level (an http_request(), a print, initialising a counter) happens N times.

  • Callbacks cannot share mutable Lua state. A table or variable that a callback updates is local to one VM, not shared across the pool. Persist anything that must be shared through an external system (http_request() to your own API, the device database, a service instance).

  • Parallelism is a hard resource limit. Each VM is a real interpreter with its own memory. The requested value is capped by the MAX_LISTENER_PARALLELISM setting (default 64); larger requests are clamped and a warning is logged.

  • Running more than one instance of the scripts service is safe — the instances share one pool per listener and balance events between them.

Devices on TR-069 and TR-369

A CPE is one device in Oktopus, whether it connects over TR-069 (CWMP), TR-369 (USP) or both at the same time (dual-stack). Each device has three identifiers:

Field
What it is

sn

The device key: the serial number the ACS knows the CPE by, or the serial number reported over USP for a TR-369-only CPE

sn_v2

The serial number the CPE reports (over USP, or the same as sn)

usp_endpoint_id

The USP Agent Endpoint ID (e.g. os::012345-ABC); empty for a TR-069-only CPE

Every function that takes a device identifier accepts any of the three. Each protocol is still addressed with its own identifier behind the scenes: send_cwmp_message() talks to the ACS with the serial number and send_usp_message() talks to the agent with the Endpoint ID, whatever identifier the script passes.

Every device table returned by the functions also tells which protocols the CPE has and which ones are online:

Field
Type
Meaning

status

integer

The device as a whole: 2 (online) when at least one of its connections is online

protocol

string

"tr069", "tr369" or "dual-stack"

cwmp

boolean

The CPE is known to the ACS (TR-069), even if that connection is down right now

usp

boolean

The CPE is known over TR-369, even if that connection is down right now

cwmp_online

boolean

The TR-069 connection is online

usp_online

boolean

The TR-369 connection is online

preferred_protocol

string

The protocol to talk to the CPE with: "usp" when TR-369 is online, otherwise "cwmp" when the ACS knows the CPE, otherwise "usp"

To check whether a message can reach the CPE right now, use usp_online / cwmp_online, not usp / cwmp:

Functions

send_usp_message()

Params:

  1. Device identifier [string]

    Serial number, sn_v2 or USP Agent Endpoint ID of the CPE (see Devices on TR-069 and TR-369). The message is sent to the CPE's Endpoint ID; the TR-369 connection must be online (usp_online).

  2. JSON payload [string]

    Request body to be sent to the CPE. Current supported bodies are : - Get - Set - Add - Delete - Operate

Return:

  • If the usp message generates an error:

  • In the case of a successful transaction each key of the table will correspond to one of the parameters requested in the payload.

Example:

send_cwmp_message()

Params:

  1. Device identifier [string]

    Serial number, sn_v2 or USP Agent Endpoint ID of the CPE (see Devices on TR-069 and TR-369). The RPC is sent to the ACS with the serial number the ACS knows the CPE by, so a dual-stack CPE can be addressed by its Endpoint ID too.

  2. XML payload [string]

    Request body to be sent to the CPE.

  3. Message Type [integer]

    CWMP message type. 0 = getParameterValues 1 = setParameterValues 2 = addObject 3 = deleteObject 4 = getParameterNames

Return:

The data returned depends on the TR-069 message type:

  • If the CWMP message generates an error:

  • If it is a read or add operation the function will return a table.

  • If it is a delete or set operation the data returned will be a boolean indicating if the result was a success or failure.

Example:

send_cwmp_async_message()

Works the same way as the send_cwmp_message() function, but does not use the CWMP Connection Request mechanism, which means this RPC will only reach the CPE in the next Inform event of it. This allows to reach CPEs behind NAT, although it takes longer for the RPC to reach and be processed by the device.

listen_to_cwmp_event()

Listen to TR-069 events as defined in the standard.

Params:

  1. Event [string] (optional) Possible events:

    If no value is set or the value is "*", than it listens to all events.

  2. Device identifier [string] (optional) Serial number, sn_v2 or USP Agent Endpoint ID of the CPE. If it's not set or the value is "*", then it listens to all CPEs event(s).

  3. Callback function (required)

  4. Parallelism [integer] (optional) Number of isolated Lua VMs the listener runs to process events concurrently. Defaults to 1 (one event at a time). Capped by the MAX_LISTENER_PARALLELISM setting (default 64). See Event listener concurrency.

  5. Discard if processing [boolean] (optional) When true, an incoming event for a device that already has an event being processed (i.e. still running the callback, on any VM) is discarded instead of being handled. Useful to avoid piling up stale events for a slow or unresponsive device. Defaults to false.

Return:

serial_number is the serial number the ACS knows the CPE by (the device sn).

Example:

To process up to 10 events concurrently, and discard new events arriving for a device that's still being processed:

listen_to_usp_event()

Listen to TR-369 (USP) notifications sent by the devices: OnBoardRequest and Event notifications.

A device sends OnBoardRequest on its own, but it only sends an Event it has a subscription for. For example, to receive Boot!, the device needs an entry in Device.LocalAgent.Subscription. with NotifType set to Event and ReferenceList set to Device.Boot!, which a script can create with send_usp_message().

Params:

  1. Event [string] (optional) Possible events:

    If no value is set or the value is "*", than it listens to all events.

  2. Device identifier [string] (optional) USP Agent Endpoint ID, serial number or sn_v2 of the CPE. If it's not set or the value is "*", then it listens to all devices event(s).

  3. Callback function (required)

  4. Parallelism [integer] (optional) Number of isolated Lua VMs the listener runs to process events concurrently, as for listen_to_cwmp_event(). Defaults to 1. See Event listener concurrency.

  5. Discard if processing [boolean] (optional) When true, an incoming event for a device that already has an event being processed is discarded instead of being handled. Defaults to false.

Return:

notify is the USP Notify message as sent by the device, in JSON (protojson) format. serial_number is the USP Agent Endpoint ID of the device that sent it (its usp_endpoint_id).

Example:

listen_to_qoe_event()

Listen to the QoE (network quality) events of the script's organization. A QoE event is published whenever the health of a CPE metric, or of the whole organization, changes band, so a script can react to it, for example by sending a message with notify().

Params:

  1. Metric [string] (optional) One of overall, ping, throughput, wifi_signal, hardware, channel_noise, pon, cellular, stability, interface_errors. If no value is set or the value is "*", it listens to all metrics.

  2. Kind [string] (optional) CPE events: degraded (the metric dropped to poor or bad), persistent (still degraded after more evaluations) and recovered. Organization events: network_degraded and network_recovered. If no value is set or the value is "*", it listens to all kinds.

  3. Callback function (required)

  4. Parallelism [integer] (optional) Number of isolated Lua VMs the listener runs to process events concurrently. Defaults to 1. Capped by the MAX_LISTENER_PARALLELISM setting (default 64). See Event listener concurrency.

  5. Discard if processing [boolean] (optional) When true, an event is discarded while another event of the same CPE (or, for organization events, of the same organization) is still being processed. Defaults to false.

  6. Include simulated events [boolean] (optional) When true, the listener also receives the simulated events sent when a rule is tested in the AI Engineer page. Defaults to false.

Return:

The callback receives the event as a table. A CPE event:

An organization event has scope network, no sn, device or inputs, and a network table with dimension (org or model_firmware), model, firmware, total, evaluated, bad_share and previous_bad_share.

inputs only carries the values synapse had for that evaluation (e.g. cpuPercent, memoryPercent, temperatureC, pingRttMs, pingLossPercent, downloadMbps, uploadMbps, wifiRssiDbm, noiseDbm, ponRxDbm, ponTxDbm, reboots, errorRatePercent). previous_score is absent on the first evaluation, and mock is true on simulated events.

Example:

To handle up to 4 events at the same time and drop new events of a CPE that is still being handled:

get_device()

Get device attributes from any of its identifiers.

Params:

  1. Device identifier [string]

    Serial number, sn_v2 or USP Agent Endpoint ID of the CPE. All of them return the same device (see Devices on TR-069 and TR-369).

Return:

If the CPE was not found in the database the function returns a boolean with false value. In case the CPE is found it returns a table with all attributes:

See Devices on TR-069 and TR-369 for the meaning of the identifier and protocol fields.

data_model reflects the CWMP root data model reported by the CPE, either "TR-098" (InternetGatewayDevice.) or "TR-181" (Device.); it is empty for USP-only devices.

Example:

listen_to_new_device()

Receive all new device attributes that connect to Oktopus, independent of the protocol.

Params:

  1. Callback function with new device data (required)

    A CPE already known on one protocol that connects over the other one is the same device, not a new one.

  2. Parallelism [integer] (optional)

    Number of isolated Lua VMs the listener runs to process events concurrently, as for listen_to_cwmp_event(). Defaults to 1. See Event listener concurrency.

Example:

sleep()

Blocks the code execution for certain time.

Params:

  1. Time duration [integer] Seconds of blocking the code execution.

Example:

cron()

Run a callback on a schedule, e.g. every day at 03:00 or every Monday at 08:30. Unlike a while true loop with sleep(), runs happen at fixed times of the day and don't drift.

cron() never returns while the script is running, the same way the listeners don't. It must be the last statement of the script, a script can have only one cron() call, and it can't be combined with listen_to_cwmp_event(), listen_to_usp_event() or listen_to_new_device(): whichever comes first blocks the other.

Params:

  1. Expression [string]

    Standard 5-field cron expression: minute hour day-of-month month day-of-week. The shortcuts @hourly, @daily, @weekly, @monthly and @every <duration> (e.g. @every 30m) are also accepted.

  2. Callback function (required)

    Receives a table describing the current run (see Return).

  3. Options [table] (optional)

    • timezone [string]: IANA time zone the expression is evaluated in, e.g. "America/Sao_Paulo". Defaults to "UTC". Don't use a CRON_TZ= prefix inside the expression, use this option instead.

    • duration [integer or string]: length of the run window, in seconds like sleep() (7200) or as a duration string ("2h", "90m"). See Run window.

    • run_on_start [boolean]: also run once as soon as the script starts, instead of waiting for the first scheduled time. Defaults to false.

Return:

The callback receives a table:

  • unix and iso are the time the run was scheduled to start, iso in the configured timezone.

  • ends_at is the end of the run window as a unix timestamp. It's only present when duration is set.

  • window_open() is a function that returns false once ends_at has passed. Without duration it always returns true.

Run window

A cron expression only sets when a run starts; the callback then runs until it returns. To limit work to a time window, e.g. from 03:00 to 05:00, set duration and call window_open() between units of work. The callback is never interrupted, so a device is never left half-processed, but a run can end a little after ends_at.

If the script starts inside a window — it was edited, reactivated or the service restarted at 04:00 for a 03:00–05:00 window — the run resumes right away and still ends at 05:00. @every schedules have no fixed start time, so they don't resume.

The Lua os library isn't available to scripts, so use window_open() rather than os.time() to check the window.

Behaviour

  • Runs never overlap: if a run is still going when the next one is due, that run is skipped, not delayed.

  • An error inside the callback is written to the script log and the schedule continues.

  • An invalid expression, timezone or duration makes the script fail at startup, with the error in the script log.

  • Every instance of the scripts service runs every active script, so with more than one instance the job runs once per instance.

Example:

create_or_update_device_credential()

Params:

  1. Username [string]

  2. Password [string]

Return:

Bool value indicating true if the operation was successfull or false if there was an error.

Example:

generate_random_string()

Params:

  1. Length [int] Size of the string to be generated

Example:

delete_device()

Remove the device from the database, with all its connections: a dual-stack CPE loses both its TR-069 and its TR-369 side, and the ACS forgets it. The device shows up again only when it reconnects, without its alias, labels or map location.

To drop only one protocol of a CPE — e.g. its TR-069 side after migrating it to TR-369 — use remove_device_protocol() instead.

Params:

  1. Device identifier [string]

    Serial number, sn_v2 or USP Agent Endpoint ID of the CPE to be removed.

Return:

Bool value indicating true if the operation was successfull and the device was removed from database or false if there was an error.

Example:

remove_device_protocol()

Remove one protocol from a device and keep the other one. Use it after migrating a CPE from TR-069 to TR-369 (or the other way round), so the device keeps its TR-369 side, alias, labels and map location while its old connection is dropped.

  • "cwmp" removes the TR-069 side: the ACS forgets the CPE and the device is no longer cwmp. If the CPE calls the ACS again, it is registered back on the same device.

  • "usp" removes the TR-369 side: its connections and its Endpoint ID.

The device status is recalculated from the connection left. If the CPE had no other protocol, the device is removed, as with delete_device().

Params:

  1. Device identifier [string]

    Serial number, sn_v2 or USP Agent Endpoint ID of the CPE.

  2. Protocol [string]

    "cwmp" or "usp".

Return:

  • true when the protocol was removed.

  • false and an error message otherwise, e.g. "Device not found (code 404)", "device is not linked on that protocol (code 400)" or a usage error for an invalid protocol.

Example:

set_device_model()

Update the model attribute of a device in the database.

Params:

  1. Serial Number [string]

    The CPE unique identifier.

  2. Model [string]

    The new model value to set.

Return:

Bool value indicating true if the operation was successfull or false if there was an error.

Example:

get_device_labels()

Get the labels of a device.

Labels are name:value pairs, and a label can have labels of its own in children, forming a tree (e.g. condominium:residencial > block:A > floor:331). Labels named connection are added and removed by Oktopus from the results of the Connection Requests sent to the device (connection:timeout, connection:cpe busy, ...).

Params:

  1. Serial Number [string]

    The CPE unique identifier.

Return:

A table with ok [boolean], error_message [string], error_code [number] and, when ok is true, labels [table]: a list of labels, each one with name [string], value [string] and, when it has labels of its own, children [table] in the same format. A device without labels returns an empty list. An unknown device returns error_code 404.

get_device() also returns the labels, in its label field, as JSON text.

Example:

change_device_labels()

Add, remove and move labels of a device, leaving its other labels as they are.

The changes are applied to the labels stored when the call is handled, so a connection label Oktopus adds or removes at the same time is kept. Prefer it to set_device_labels() when the script only cares about some labels.

Params:

  1. Serial Number [string]

    The CPE unique identifier.

  2. Changes [table]

    • add [table, optional]: labels to add, each one a table with name and value and, to nest it, parent: a table with the name and value of a label the device has or that is added in the same call. Adding a label the device already has moves it, with its children, under parent, or to the top level without parent.

    • remove [table, optional]: labels to remove, each one a table with name and value. Their children move to the removed label's parent. Removing a label the device doesn't have changes nothing.

Names and values are strings of up to 100 characters; numbers are taken as text (value = 331 is "331"). A name:value pair appears once per device, a label can't be nested under itself or one of its children, connection labels stay at the top level, and a device has at most 50 labels.

Return:

A table with ok [boolean], error_message [string] and error_code [number]. When a change breaks a rule, error_code is 400, error_message says why and no label is changed.

Example:

set_device_labels()

Replace all the labels of a device, the connection ones included, with a list of labels.

Params:

  1. Serial Number [string]

    The CPE unique identifier.

  2. Labels [table]

    A list of labels in the format get_device_labels() returns: each one a table with name, value and, optionally, children. An empty list removes all the labels.

The same rules as change_device_labels() apply.

Return:

A table with ok [boolean], error_message [string] and error_code [number].

Example:

get_all_devices()

Retrieve all devices saved on the database.

Return:

List of device objects.

A dual-stack CPE is listed once.

Example:

list_devices()

List the devices that match a set of filters, one page at a time. It accepts the same filters as the device list in the Oktopus API and UI. Only devices of the script's own organization are returned.

Params:

  1. Filters [table] (optional)

    All filters are optional and combined with AND. Empty strings are ignored.

    Filter
    Type
    Matches

    sn

    string

    Exact serial number or USP Agent Endpoint ID

    sn_v2

    string

    Exact device serial number

    vendor

    string

    Exact vendor

    model

    string

    Exact model

    version

    string

    Exact software version

    type

    string

    Exact product class

    alias

    string

    Alias containing the text, case insensitive

    status

    integer

    0 offline, 1 associating, 2 online, 3 unknown

    protocol

    string

    "tr069" (known to the ACS), "tr369" (known over USP) or "dual-stack" (both)

    datamodel

    string

    "TR-181" or "TR-098"

    ip

    string

    Exact public IP

    connection_ip

    string

    Connection IP starting with the text

    pppoe_user

    string

    Exact PPPoE username

    wan_mac

    string

    Exact WAN MAC address

    label

    table

    Devices with all the labels listed, e.g. { { name = "City", value = "SP" } }

    sn and sn_v2 look up a single device, so they can't be combined with other filters.

    With protocol, status is the status of that protocol's connection: { protocol = "tr369", status = 2 } lists the CPEs whose TR-369 connection is online, including dual-stack CPEs whose TR-069 side is offline. Without protocol, status is the status of the device as a whole.

    Sorting and pagination options:

    • status_order, last_seen_order or uptime_order [string]: "asc" or "desc". Only one sort can be used at a time. Defaults to status_order = "asc".

    • page_number [integer]: page to return, starting at 0. Defaults to 0.

    • page_size [integer]: devices per page, from 1 to 100. Defaults to 20.

    An unknown filter name or a value of the wrong type returns an error instead of listing devices.

Return:

A table is always returned:

  • total is the number of devices matching the filters, across all pages; pages is the number of pages for the chosen page_size.

  • When no device matches, or page_number is past the last page, ok is true and devices is empty.

  • When ok is false, error_message and error_code explain why: 400 for invalid filters, 503 when the device service isn't available.

  • last_seen and created_at are RFC 3339 dates in UTC, and are absent when unknown.

Example:

Pages are read one at a time, so devices that change while the script runs can move between pages. If the changes your script makes remove devices from the filter (e.g. filtering by version and upgrading the firmware), always request page_number = 0 until no devices are left, otherwise part of the devices are skipped. In that case, stop once a page only returns devices the script already tried, so devices that fail don't keep the loop running forever.

refresh_device_parameters()

Sync device saved parameters, as PPPoE user, IP address and WAN MAC.

Params:

  1. Serial number / USP agent endpoint id [string] The unique identifier of the CPE to be removed.

Return: Bool value indicating f the operation was successfully executed ot not.

Example:

http_request()

Make an HTTP call to a third-party REST API to gather or send data. Useful for integrating scripts with external systems (billing, ticketing, monitoring, etc).

Only http/https URLs are accepted; URLs with embedded credentials (e.g. http://user:pass@host/) are rejected; this function can only reach external/public hosts.

Params:

  1. Method [string]

    HTTP method, e.g. "GET", "POST", "PUT", "PATCH", "DELETE". Defaults to "GET" if empty.

  2. URL [string]

    Full request URL. Must start with http:// or https://.

  3. Headers [table] (optional)

    Table of header name/value pairs to send with the request.

  4. Body [string] (optional)

    Request body. Commonly used with POST/PUT/PATCH. Use json_encode() to build a JSON body.

Return:

A table is always returned:

  • ok is true when the request completed with a 2xx status code.

  • error_message is populated when the request could not be completed at all (invalid URL, blocked target, timeout, connection error) — it does not mean the remote API returned an HTTP error.

  • Use body together with json_decode() to parse JSON responses.

Example:

json_decode()

Parse a JSON string into a Lua table (or scalar value). Commonly used to read the body returned by http_request().

Params:

  1. JSON string [string]

Return:

Two values are returned: the decoded value (table, string, number, boolean or nil), and an error message [string] that is nil when decoding succeeds.

Example:

json_encode()

Convert a Lua table (or scalar value) into a JSON string. Commonly used to build the body sent through http_request().

Params:

  1. Value [table, string, number or boolean]

Return:

Two values are returned: the encoded JSON [string], and an error message [string] that is nil when encoding succeeds.

Example:

get_service_instances()

List the service instances attached to a device.

Params:

  1. Serial Number [string]

    The CPE unique identifier.

Return:

A table with ok [boolean], error_message [string], error_code [number] and, on success, instances [table] — an array of tables, each with id, device_id, service_id, status and variables:

Example:

create_service_instance()

Attach a service definition to a device, creating a new service instance.

Params:

  1. Serial Number [string] — the CPE unique identifier.

  2. Service Definition ID [string].

  3. Variables [table, optional] — the service-specific variable values for this device.

Return:

A table with ok [boolean], error_message [string] and error_code [number]. The created instance's id is not returned — call get_service_instances() to look it up.

Example:

edit_service_instance()

Replace an existing service instance's device and variables. The service definition id cannot be changed.

Params:

  1. Service Instance ID [string].

  2. Serial Number [string] — the CPE unique identifier.

  3. Service Definition ID [string] — must match the instance's current service definition.

  4. Variables [table, optional] — the new service-specific variable values.

Return:

A table with ok [boolean], error_message [string] and error_code [number].

Example:

delete_service_instance()

Delete a service instance.

Params:

  1. Service Instance ID [string].

Return:

A table with ok [boolean], error_message [string] and error_code [number].

Example:

apply_service_instance()

Run a service instance's provisioning script against its device right away, instead of waiting for its trigger event (see Manual Execution).

Params:

  1. Service Instance ID [string].

Return:

A table with ok [boolean], error_message [string], error_code [number] and, on success, status [string] ("provisioned" or "failed"). ok reflects whether the request itself succeeded; status is the actual provisioning outcome — a script can legitimately fail provisioning even though the request succeeded (ok = true, status = "failed").

Example:

apply_service_instance_and_forget()

Trigger a service instance's provisioning script the same way apply_service_instance() does, but don't wait for it to run to completion — the request is enqueued and the function returns immediately. Because it doesn't wait for a response, it can't report the final status, and ok only reflects whether the message was enqueued locally, not whether the zero-touch-provisioning service actually received or ran it.

Use this when applying a service instance whose script may run long (e.g. it calls sleep() or does several sequential CPE round trips) and the caller doesn't need to wait for the outcome.

Params:

  1. Service Instance ID [string].

Return:

A table with ok [boolean], error_message [string] and error_code [number]. There is no status field.

Example:

notify()

Send a message through connectors of the organization (Slack, webhook, e-mail), configured in Settings › Connectors. The call waits while the connectors are delivered, retries included, so it can take a few seconds when a connector is failing.

Params:

  1. Connector IDs [string or table] (required) A connector ID, or a list of connector IDs. In the Flow view, the Notify step lists the connectors by name and writes their IDs in the code; through the API they are the id of each connector returned by GET /api/notifications/channels. The ID does not change when a connector is renamed.

  2. Message [table] (required)

    • title [string] and text [string]: at least one of them is required

    • severity [string] (optional): info (default), warning or error

    • fields [table] (optional): name = value pairs shown with the message; numbers and booleans are written as text

    • topic [string] (optional): groups the message in the deliveries list. Defaults to script

Return:

A table with ok [boolean], error_message [string], error_code [number] and, when the notifier answered, deliveries: one entry per connector with channel_id, type, status (sent or failed), error and at.

error_code is 400 for an invalid argument, an unknown connector or a message with neither title nor text, 503 when the notifier is not running and 504 when it does not answer in time.

Example:

Notify on every degraded CPE metric:

device_qoe()

Get the last QoE (network quality) evaluation of a CPE.

Params:

  1. Serial number [string] (required)

Return:

The evaluation as a table, with the health score of each metric (overallHealthScore, pingHealthScore, throughputHealthScore, badSignalHealthScore, hardwareHealthScore, channelNoiseHealthScore, ponHealthScore, cellularHealthScore, stabilityHealthScore, interfaceErrorsHealthScore) and the inputs synapse used. On failure it returns a table with error_message [string] and error_code [number]: 400 empty serial number, 404 CPE never evaluated, 503 service not running, 504 timeout. Check error_message before reading the scores.

Example:

Examples

The scripts below are adapted from real-world scenario automations built by Oktopus.

Migrate CWMP (TR-069) CPE to USP (TR-369)

Some CPE vendors ship devices with a proprietary, disabled-by-default USP agent running alongside the TR-069 agent (e.g. Zyxel's X_ZYXEL_Enable parameter). This is a common pattern to migrate such a fleet from CWMP to USP without a firmware upgrade: listen for CWMP events, bootstrap the on-board USP agent entirely through CWMP SetParameterValues/AddObject calls, confirm the device shows up connected over USP, then disable CWMP so the device is fully USP-managed going forward.

While the migration runs the CPE is one dual-stack device: when the USP agent connects, its TR-369 side joins the device the ACS already knows. The script therefore checks usp_online (not usp, which is already true for a CPE known over TR-369 whose agent is down) and ends with remove_device_protocol(), which drops only the TR-069 side — delete_device() would remove the whole CPE, TR-369 side included.

This flow is vendor-specific in a few places — namely the X_ZYXEL_Enable and X_ZYXEL_ROMD_Action parameters, and the CA certificate download command. Other CPE vendors with an on-board USP agent typically expose an equivalent enable flag and a way to download/trust a CA certificate; adjust those parameter paths to match your CPE's data model.

Provision USP settings across an existing fleet

Once devices are on USP, a common pattern is a script that walks every device with get_all_devices() and applies a USP configuration if it isn't already present — useful for periodically rolling out a new setting to a whole fleet.

Both examples write MQTT topics that must carry the USP Agent Endpoint ID, so they use device.usp_endpoint_id — device.sn is the serial number — and only touch devices whose TR-369 connection is online (usp_online).

Creates (idempotently) a Device.BulkData.Profile. that periodically publishes device data over MQTT, then enables it.

Replaces any existing subscriptions with a standard set — one for operation-complete notifications on diagnostics, and one for transfer-complete events — and points them at this controller's MQTT notify topic.

Last updated