WEIGHING TECHNOLOGY · IN-HOUSE DEVELOPMENT · SUPPORT
+386 2 320 33 46info@preciz.si

This page is not yet available in Slovenščina. The English version is shown.

This page is not yet available in Slovenščina. The English version is shown.

NEUTRON APPENGINE · DEVELOPER MANUAL

Neutron AppEngine — JavaScript application development

JavaScript application development for CS-NEUTRON: runtime, weighing, digital I/O, settings, storage, communication modules and application management. Manual 1.0 · Neutron AppEngine 1.0.0 · API 1 · 15 November 2026.

1. Purpose and scope

Neutron AppEngine is an application development environment comprising a shared runtime and independent functional modules. An application uses only the modules it needs. The runtime is independent of the selected communication protocol.

Neutron AppEngine lets you develop custom JavaScript logic directly on the CS-NEUTRON weighing module. Applications can read measurements, perform basic scale operations, use timers and connect to external systems through supported communication modules. This manual is intended for developers, integrators and AI systems preparing applications for use with Scale Monitor.

This manual describes the neutron-js-1 profile, apiVersion: 1, as of 15 November 2026. The manual version is 1.0 and the Neutron AppEngine interpreter version is 1.0.0. All implemented functions, events, properties and operations described here are available from 1.0.0. The firmware version alone does not confirm support for every feature: check app.capabilities() on the device and test your application.
Table 1

Area

Status

Interface

JavaScript execution

Implemented

Neutron AppEngine interpreter; one persistently stored user application

Runtime and diagnostics

Implemented

app.capabilities(), app.stop(), console

Timers

Implemented

setTimeout, setInterval, cancellation by ID

Scale

Implemented

Read weight, tare, zero, preset tare and send CSCP commands with scale.cmd()

TCP client / server

Implemented

Claim the existing TCP interface, handle events and send data

MQTT

Implemented

Independent user broker; mqtt, mqtts, ws and wss

RS-232 / RS-485

Implemented

serial.rs232 and serial.rs485; claiming, SMD configuration, events and sending

Installation

Implemented

BLE, internal HTTP/HTTPS and MQTT through the existing APP channel

Digital inputs/outputs

Implemented

io.input(1..6), io.output(1..6); configuration, events, output claiming and counters

Parameters and counting application

Through supported CSCP commands

scale.cmd() executes commands supported by the device; a separate counting.* JavaScript API is not yet available.

Module settings

Implemented

device.cmd for RMD/SMD; device.settings.read/list/write

Files and local database

Implemented

storage; openRecords and indexed key lookup

REST/HTTP iz JS

Implemented

fetch for HTTP/HTTPS; status, headers, text, JSON and binary responses

The file is a regular UTF-8 .js script. Its size is measured in bytes, not lines or characters, with a maximum of 131,072 bytes. It is not an ES module: import/export, top-level await, Node.js, npm and the DOM are unavailable. Use globalThis, standard JavaScript objects, Promise, async/await, Map, JSON and Uint8Array. Browser TextEncoder/TextDecoder APIs are not part of this profile.

2. Your first application

Save the following code as first-application.js, upload it and select Run. It increments a counter every second and writes it to the configured debug channel. No scale or communication configuration is required.
let counter = 0;
setInterval(() => {
    counter += 1;
    console.log("Counter:", counter);
}, 1000);

In the local HTTP/HTTPS interface or BLE page, open JS application or App, select the file, enter its name and version, then select Upload. After validation, select Run. Use Stop to stop the application and Refresh to check its state and last error. Enable Auto run only after testing.

For asynchronous initialization, define and call a function. start is an arbitrary user-defined name with no special runtime meaning.
async function start() {
    const caps = app.capabilities();
    if (caps.apiVersion !== 1) {
        throw new Error("Unsupported API version");
    }
    console.info("Application ready", caps.runtime);
}
start().catch(error => {
    console.error(error.code || "START_FAILED", error.message);
    app.stop();
});

3. Runtime, events and lifecycle

Avoid blocking: do not use while (true), busy waiting, deep recursion or infinite Promise chains. The runtime allows approximately 1 s of active time per processing step; sleeping until an event does not consume that budget. Exceeding it or overflowing a queue can stop the application; do not use this as a normal control mechanism.
Environment preparation and application compilation have separate time limits of up to 5 seconds per phase. The compilation limit is the same during upload and startup. Initial user-code execution then receives a new one-second deadline; the same limit applies to event and timer processing. Waiting for network responses or timers does not consume this budget. TIMEOUT reports the phase and limit, for example TIMEOUT during application startup (limit 1000 ms). Interrupting execution does not automatically restart the module.
Table 2

Step

Behavior

Installation

The source code and attributes are saved in device storage. Integrity and syntax are checked without executing user code.

Run

Each run creates a new JavaScript context. The initial script runs once; variables from a previous run are not retained.

Waiting

After the initial script returns, the runtime remains active, waiting for the next timer or event. When there is no work, Neutron AppEngine waits without executing user code.

Event

An event from a supported module, timer expiry or operation result triggers the corresponding processing in Neutron AppEngine. A pending Promise resolves or rejects.

Stop or error

Timers and the context are removed. Stop does not undo effects of operations already performed.

Run again

Stop the previous run first and wait for busy: false. Installing a new version also requires the application to be stopped.
Neutron AppEngine executes callbacks sequentially. Handle events promptly and avoid unbounded numbers of pending operations. await yields execution, allowing other callbacks to run while waiting. An asynchronous callback is therefore not a transaction that blocks other events.

4. Application API

4.1 app.capabilities()

Available since: Neutron AppEngine 1.0.0
const capabilities = app.capabilities();
Purpose. Check supported features and limits before using an API.
Description. Synchronously returns a new object reporting support, versions and limits. It does not initialize individual modules or guarantee their current readiness.

Parameters

No parameters.

Result

The object shown below. features properties indicate module support. Settings and limits for each module are explained in its chapter.

Errors and special considerations

Does not return a Promise. Do not infer feature support from the device name or application version alone.

Example

const c = app.capabilities();
if (c.apiVersion !== 1) throw new Error("Neustrezen API");
console.info(c.interpreter, c.interpreterVersion, c.apiVersion);
const capabilities = {
  apiVersion: 1,
  runtime: "neutron-js-1",
  interpreter: "Neutron AppEngine",
  interpreterVersion: "1.0.0",
  features: {
    timers: true, scale: true, tcp: true,
    io: true, mqtt: true, serial: true, files: true, records: true, settings: true, http: true, websocket: true
  },
  scaleOperations: ["tare", "zero", "clearTare", "setPresetTare", "cmd"],
  tcp: { configuredMode: 1, requiresClaim: true },
  http: {
    protocols: ["http", "https"], methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"],
    maxActiveRequests: 1, maxQueuedRequests: 4, maxRequestBytes: 4096, maxResponseBytes: 4096,
    maxHeaderBytes: 2048, maxHeaders: 32, maxUrlBytes: 512, maxOptionsBytes: 4096,
    maxTimeoutMs: 60000, redirect: "manual", certificateProfiles: true, compression: false
  },
  settings: { maxKeysPerRequest: 16, maxPageKeys: 32, maxCommandBytes: 2048, maxValueBytes: 1024, automaticReboot: false },
  storage: {
    quotaBytes: 524288, reserveBytes: 131072, maxFileBytes: 262144,
    maxChunkBytes: 4096, maxFiles: 64, maxFindScanBytes: 65536,
    maxFindNeedleBytes: 128, maxDatabases: 8, maxOpenDatabases: 2,
    maxRecords: 2048, maxRecordBytes: 2048, maxRecordDepth: 16, maxKeyBytes: 64, indexedFields: 1
  },
  io: {
    available: true, inputCount: 6, outputCount: 6, indexBase: 1,
    inputFunctions: [{ id: 0, name: "disabled" } /* celoten seznam na napravi */],
    outputFunctions: [{ id: 0, name: "disabled" } /* celoten seznam na napravi */],
    maxListenersPerPin: 32, maxDebounceMs: 60000, maxGlitchUs: 12,
    counterType: "bigint", maxCounterValue: "9223372036854775807",
    requiresOutputClaim: true, defaultSafeState: false
  },
  mqtt: {
    transports: ["mqtt", "mqtts", "ws", "wss"], protocolVersion: "3.1.1",
    maxConnections: 1, qos: [0, 1], maxMessageBytes: 4096,
    maxTopicBytes: 192, maxSubscriptions: 16, maxListeners: 32,
    maxConfigurationBytes: 4096, maxPendingOperations: 8,
    maxOperationTimeoutMs: 60000, certificateProfiles: true
  },
  serial: {
    ports: ["rs232", "rs485"], requiresClaim: true, requiresDisabled: true,
    dataBits: [7, 8], stopBits: [1, 2], parity: ["none", "even", "odd"],
    minBaudRate: 300, maxBaudRate: 1000000, maxMessageBytes: 4096,
    maxLineBytes: 4096, maxListenersPerPort: 32,
    maxWriteTimeoutMs: 180000, maxDrainTimeoutMs: 60000
  },
  limits: {
    maxTimers: 16, maxPendingOperations: 8,
    maxTcpMessageBytes: 4096, maxLineBytes: 4096,
    maxHeapBytes: 1048576, callbackTimeoutMs: 1000,
    maxScaleCommandBytes: 2048, maxScaleResponseBytes: 4096, maxScaleCommandTimeoutMs: 60000
  }
}
Read the version with app.capabilities().interpreterVersion and the name with app.capabilities().interpreter. interpreterVersion identifies the Neutron AppEngine product version, apiVersion the API contract and runtime the profile. These are distinct from the user application version and device firmware version. Current versions: Neutron AppEngine 1.0.0, API 1 and manual 1.0.
console.info(app.capabilities().interpreter, app.capabilities().interpreterVersion);
At device startup, Neutron AppEngine interpreter v1.0.0 is logged at INFO level. Visibility depends on the debug channel and level settings. Use capabilities to check from a user application.

4.2 app.stop()

Available since: Neutron AppEngine 1.0.0
app.stop();
Purpose. Stop the user application normally.
Description. Requests execution to stop and prevents further callbacks. Does not reset the module. Releases resources claimed by the application; resource-specific behavior is described in the relevant module chapter.

Parameters

No parameters.

Result

undefined. This is a request, not a Promise confirming shutdown. Use APP status for external confirmation.

Errors and special considerations

Does not undo operations already performed. Use return after the call if subsequent statements in the current function must not execute. There is no user shutdown callback.

Example

if (app.capabilities().apiVersion !== 1) {
    console.error("API version is not supported");
    app.stop();
}

5. Diagnostics and console

Console sends output to the Neutron debug system, not the browser console. Existing debug settings DI and DL select the output and level. Messages receive the prefix [JS:application name]. The current transport configuration and connection determine where messages are visible.

5.1 console.log(...)

Available since: Neutron AppEngine 1.0.0
console.log(...values);
Purpose. Log measurements or status.
Description. Joins arguments with spaces. Attempts JSON.stringify for objects and text conversion for other values. Replaces control characters with spaces. All console methods share the same logging limit.

Parameters

Table 3

Parameter

Type / requirement

Description

values

any JavaScript values / optional

Zero or more arguments. Avoid large objects and circular structures.

Result

undefined; INFO log, visible with DL ≥ 3 and an appropriate DI.

Errors and special considerations

Logging does not itself stop the application, including console.error(). The shared limit is 10 calls/s and approximately 512 content bytes per call, excluding the prefix. Excess output is rejected or truncated; an additional rate-limit warning may appear. Conversion or memory errors can throw a JavaScript exception.

Example

console.log("Stanje aplikacije", { ready: true, counter: 5 });

5.2 console.info(...)

Available since: Neutron AppEngine 1.0.0
console.info(...values);
Purpose. Report startup or status information.
Description. Joins arguments with spaces. Attempts JSON.stringify for objects and text conversion for other values. Replaces control characters with spaces. All console methods share the same logging limit.

Parameters

Table 4

Parameter

Type / requirement

Description

values

any JavaScript values / optional

Zero or more arguments. Avoid large objects and circular structures.

Result

undefined; INFO log, visible with DL ≥ 3 and an appropriate DI.

Errors and special considerations

Logging does not itself stop the application, including console.error(). The shared limit is 10 calls/s and approximately 512 content bytes per call, excluding the prefix. Excess output is rejected or truncated; an additional rate-limit warning may appear. Conversion or memory errors can throw a JavaScript exception.

Example

console.info("Stanje aplikacije", { ready: true, counter: 5 });

5.3 console.warn(...)

Available since: Neutron AppEngine 1.0.0
console.warn(...values);
Purpose. Log a warning or a handled problem.
Description. Joins arguments with spaces. Attempts JSON.stringify for objects and text conversion for other values. Replaces control characters with spaces. All console methods share the same logging limit.

Parameters

Table 5

Parameter

Type / requirement

Description

values

any JavaScript values / optional

Zero or more arguments. Avoid large objects and circular structures.

Result

undefined; WARN log, visible with DL ≥ 2 and an appropriate DI.

Errors and special considerations

Logging does not itself stop the application, including console.error(). The shared limit is 10 calls/s and approximately 512 content bytes per call, excluding the prefix. Excess output is rejected or truncated; an additional rate-limit warning may appear. Conversion or memory errors can throw a JavaScript exception.

Example

console.warn("Stanje aplikacije", { ready: true, counter: 5 });

5.4 console.error(...)

Available since: Neutron AppEngine 1.0.0
console.error(...values);
Purpose. Describe an error.
Description. Joins arguments with spaces. Attempts JSON.stringify for objects and text conversion for other values. Replaces control characters with spaces. All console methods share the same logging limit.

Parameters

Table 6

Parameter

Type / requirement

Description

values

any JavaScript values / optional

Zero or more arguments. Avoid large objects and circular structures.

Result

undefined; ERROR log, visible with DL ≥ 1 and an appropriate DI.

Errors and special considerations

Logging does not itself stop the application, including console.error(). The shared limit is 10 calls/s and approximately 512 content bytes per call, excluding the prefix. Excess output is rejected or truncated; an additional rate-limit warning may appear. Conversion or memory errors can throw a JavaScript exception.

Example

console.error("Stanje aplikacije", { ready: true, counter: 5 });

5.5 console.debug(...)

Available since: Neutron AppEngine 1.0.0
console.debug(...values);
Purpose. Log details during development.
Description. Joins arguments with spaces. Attempts JSON.stringify for objects and text conversion for other values. Replaces control characters with spaces. All console methods share the same logging limit.

Parameters

Table 7

Parameter

Type / requirement

Description

values

any JavaScript values / optional

Zero or more arguments. Avoid large objects and circular structures.

Result

undefined; DEBUG log, visible with DL ≥ 4 and an appropriate DI.

Errors and special considerations

Logging does not itself stop the application, including console.error(). The shared limit is 10 calls/s and approximately 512 content bytes per call, excluding the prefix. Excess output is rejected or truncated; an additional rate-limit warning may appear. Conversion or memory errors can throw a JavaScript exception.

Example

console.debug("Stanje aplikacije", { ready: true, counter: 5 });

The debug level may filter output. Do not use console as a reliable transport for business data. Use a suitable supported communication module for reliable data exchange.

6. Timers

A timer specifies the earliest intended execution time. This is not a hard real-time JavaScript environment: measurement, communication, previous callbacks and scheduling can delay execution. Missed intervals do not create an unbounded queue of catch-up calls.

A periodic async callback may still be waiting when the next interval arrives. Use a busy flag or schedule the next setTimeout after the operation completes. The same applies to events from any module: if processing must be sequential, implement a bounded queue or reject new work until the previous operation finishes.

6.1 setTimeout()

Available since: Neutron AppEngine 1.0.0
const id = setTimeout(callback, delayMs = 0, ...args);
Purpose. Execute a function once after a delay.
Description. Returns immediately; the callback runs later. The timer is removed from the active set before invoking the callback, so the callback can schedule another execution.

Parameters

Table 8

Parameter

Type / requirement

Description

callback

function / required

A function; code supplied as a string is not supported.

delayMs

number / optional, default 0

Converted to a number and integer. Invalid, negative or zero delays become at least 1 ms. Maximum: 2,147,483,647 ms.

...args

any values / optional

Arguments passed to the callback by the runtime.

Result

Numeric ID accepted by clearTimeout. Valid only during the current application run.

Errors and special considerations

Synchronous INVALID_ARGUMENT if the callback is not a function; QUOTA_EXCEEDED if 16 timers are already active. An unhandled exception or callback rejection can stop the application.

Example

const id = setTimeout(message => {
    console.info(message);
}, 2000, "Two seconds after scheduling");

6.2 setInterval()

Available since: Neutron AppEngine 1.0.0
const id = setInterval(callback, delayMs = 0, ...args);
Purpose. Read or send data periodically.
Description. The first call occurs after the delay. Further callbacks are scheduled periodically; the runtime does not await Promises returned by async callbacks. Delays do not cause unbounded catch-up execution.

Parameters

Table 9

Parameter

Type / requirement

Description

callback

function / required

A function; code supplied as a string is not supported.

delayMs

number / optional, default 0

Converted to a number and integer. Invalid, negative or zero delays become at least 1 ms. Maximum: 2,147,483,647 ms.

...args

any values / optional

Arguments passed to the callback by the runtime.

Result

Numeric ID accepted by clearInterval. The interval remains active until cancelled or the application stops.

Errors and special considerations

The same synchronous errors as setTimeout. Protect asynchronous work against overlap and catch rejections inside the async function.

Example

let working = false;
let counter = 0;
const id = setInterval(async () => {
    if (working) return;
    working = true;
    try {
        // Example asynchronous step; Promise yields execution.
        const next = await Promise.resolve(counter + 1);
        counter = next;
        console.info("Completed step:", counter);
    } catch (error) {
        console.warn(error.code || error.name, error.message);
    } finally {
        working = false;
    }
}, 1000);

6.3 clearTimeout()

Available since: Neutron AppEngine 1.0.0
clearTimeout(id);
Purpose. Cancel future timer execution.
Description. Both functions use the same timer registry and can cancel either timer type. Using the corresponding set/clear pair is recommended.

Parameters

Table 10

Parameter

Type / requirement

Description

id

number / required

ID returned by setTimeout or setInterval. Converted with Number(id).

Result

undefined. An unknown ID has no effect.

Errors and special considerations

Does not interrupt a callback or asynchronous operation that has already started. Converting an unsuitable JavaScript value to a number may throw a standard JavaScript exception.

Example

const id = setTimeout(() => console.info("Pozneje"), 1000);
clearTimeout(id);

6.4 clearInterval()

Available since: Neutron AppEngine 1.0.0
clearInterval(id);
Purpose. Cancel future timer execution.
Description. Both functions use the same timer registry and can cancel either timer type. Using the corresponding set/clear pair is recommended.

Parameters

Table 11

Parameter

Type / requirement

Description

id

number / required

ID returned by setTimeout or setInterval. Converted with Number(id).

Result

undefined. An unknown ID has no effect.

Errors and special considerations

Does not interrupt a callback or asynchronous operation that has already started. Converting an unsuitable JavaScript value to a number may throw a standard JavaScript exception.

Example

const id = setInterval(() => console.info("Interval"), 1000);
clearInterval(id);

7. Scale API

7.1 scale.read()

Available since: Neutron AppEngine 1.0.0
const measurement = scale.read();
Purpose. Read the latest available scale snapshot without waiting for stability.
Description. Synchronously returns the latest available scale data snapshot. Does not trigger a new measurement. Read one object and use its fields together for consistent net/gross/tare values.

Parameters

No parameters.

Result

An object with the fields below. When measurement is unavailable, net, gross and tare are NaN and stable is false. Unit and status remain diagnostic information.

Errors and special considerations

An unavailable scale is reported as available=false rather than a NO_MEASUREMENT exception. available=true does not imply stable=true. A synchronous call can throw if JavaScript memory is exhausted.

Example

const m = scale.read();
if (m.available && Number.isFinite(m.net)) {
    console.log(m.net, m.gross, m.tare, m.unit, m.stable);
} else {
    console.warn("Ni veljavne meritve", m.status);
}
Table 12

Field

Tip

Meaning

available

boolean

The scale is available, the weighing interface is enabled and the measurement is valid.

net

number

Net weight calculated from gross and tare, rounded to the configured decimal places.

gross

number

Gross weight in the configured unit.

tare

number

Current tare in the configured unit.

stable

boolean

The valid measurement is stable according to the current scale configuration.

unit

string

Current scale unit, such as kg or g. It is not necessarily kg.

status

number

Current scale status value. The JavaScript profile provides no separate named enumeration; do not invent code mappings.

sequence

number

32-bit published-measurement counter; wraps on overflow. Not a persistent weighing-record ID.

timeMs

number

Time of the last measurement publication in milliseconds since device startup. Not UTC; this 32-bit counter can wrap.

Shortcuts scale.net, scale.gross and scale.available are live getters reading a fresh snapshot on every access. scale.tare is a function; obtain numeric tare from scale.read().tare. Do not use two separate getters for a gross/net pair that must share the same snapshot.

7.2 scale.tare()

Available since: Neutron AppEngine 1.0.0
const measurement = await scale.tare();
Purpose. Tare using the current load.
Description. Performs the corresponding scale function without bypassing stability, range, protection, concurrent commands or configuration. Executes weighing command T; this is not immediate taring with TI.

Parameters

No parameters.

Result

Promise<Measurement>: after a successful response, reads a new JavaScript snapshot with the scale.read() structure. This does not guarantee that the next measurement has arrived; monitor subsequent measurements to confirm the effect.

Errors and special considerations

BUSY, OUT_OF_MEMORY, NO_MEASUREMENT, PERMISSION_DENIED, SCALE_REJECTED or TIMEOUT. Handle rejected Promises with await/try/catch. Stopping destroys the context; Promise continuation is not guaranteed.

Example

async function apply() {
    try {
        const m = await scale.tare();
        console.info("Operation successful", m.net, m.tare, m.unit);
    } catch (error) {
        console.warn(error.code || "SCALE_FAILED", error.message);
    }
}
apply();

7.3 scale.zero()

Available since: Neutron AppEngine 1.0.0
const measurement = await scale.zero();
Purpose. Zero the scale.
Description. Performs the corresponding scale function without bypassing stability, range, protection, concurrent commands or configuration. Executes Z, which is different from taring. Success depends on operating conditions and the permitted zeroing range.

Parameters

No parameters.

Result

Promise<Measurement>: after a successful response, reads a new JavaScript snapshot with the scale.read() structure. This does not guarantee that the next measurement has arrived; monitor subsequent measurements to confirm the effect.

Errors and special considerations

BUSY, OUT_OF_MEMORY, NO_MEASUREMENT, PERMISSION_DENIED, SCALE_REJECTED or TIMEOUT. Handle rejected Promises with await/try/catch. Stopping destroys the context; Promise continuation is not guaranteed.

Example

async function apply() {
    try {
        const m = await scale.zero();
        console.info("Operation successful", m.net, m.tare, m.unit);
    } catch (error) {
        console.warn(error.code || "SCALE_FAILED", error.message);
    }
}
apply();

7.4 scale.clearTare()

Available since: Neutron AppEngine 1.0.0
const measurement = await scale.clearTare();
Purpose. Clear tare.
Description. Performs the corresponding scale function without bypassing stability, range, protection, concurrent commands or configuration. Executes TAC to request removal of the current tare.

Parameters

No parameters.

Result

Promise<Measurement>: after a successful response, reads a new JavaScript snapshot with the scale.read() structure. This does not guarantee that the next measurement has arrived; monitor subsequent measurements to confirm the effect.

Errors and special considerations

BUSY, OUT_OF_MEMORY, NO_MEASUREMENT, PERMISSION_DENIED, SCALE_REJECTED or TIMEOUT. Handle rejected Promises with await/try/catch. Stopping destroys the context; Promise continuation is not guaranteed.

Example

async function apply() {
    try {
        const m = await scale.clearTare();
        console.info("Operation successful", m.net, m.tare, m.unit);
    } catch (error) {
        console.warn(error.code || "SCALE_FAILED", error.message);
    }
}
apply();

7.5 scale.setPresetTare(value)

Available since: Neutron AppEngine 1.0.0
const measurement = await scale.setPresetTare(value);
Purpose. Set a preset tare.
Description. Performs the corresponding scale function without bypassing stability, range, protection, concurrent commands or configuration. Executes TA with a numeric tare in the current scale unit. Values are not automatically converted from another unit.

Parameters

Table 13

Parameter

Type / requirement

Description

value

number / required

Finite number ≥ 0 within scale capacity, in scale.read().unit. Strings, NaN and Infinity are not permitted.

Result

Promise<Measurement>: after a successful response, reads a new JavaScript snapshot with the scale.read() structure. This does not guarantee that the next measurement has arrived; monitor subsequent measurements to confirm the effect.

Errors and special considerations

An invalid type, negative or non-finite value rejects with INVALID_ARGUMENT; values above capacity reject with OUT_OF_RANGE. Other errors: BUSY, OUT_OF_MEMORY, NO_MEASUREMENT, PERMISSION_DENIED, SCALE_REJECTED or TIMEOUT. Handle rejection with await/try/catch. Stopping destroys the context; Promise continuation is not guaranteed.

Example

async function apply() {
    try {
        const m = await scale.setPresetTare(2.5);
        console.info("Operation successful", m.net, m.tare, m.unit);
    } catch (error) {
        console.warn(error.code || "SCALE_FAILED", error.message);
    }
}
apply();

A weighing operation waits for the configured scale-command window plus approximately 2 seconds for processing. There is no per-call timeout parameter for these JavaScript operations. A scale processing another command may return BUSY. Execute dependent commands with sequential await calls rather than unbounded Promise.all.

7.6 scale.cmd()

Available since: Neutron AppEngine 1.0.0
const response = await scale.cmd(command, { timeoutMs });
Purpose. Execute one CSCP command and read its original response.
Description. Access scale commands, configuration and other functions supported by the device through CSCP. Existing parameter validation and data-protection rules apply. RSD and configuration queries do not require a valid measurement. S and SX wait for a stable measurement; SI and SXI query immediately.

Parameters

Table 14

Parameter

Type / requirement

Description

command

string / required

One CSCP command, at most 2048 UTF-8 bytes after trimming surrounding whitespace and an optional trailing CRLF. Empty commands, NUL, embedded CR/LF and other control characters are prohibited. Syntax and case follow CSCP.

options

object / optional, default {}

Wait options. Unit, stability and permissions are determined by the command and scale settings.

options.timeoutMs

integer / optional

1–60000 ms. Defaults to the configured scale wait window plus 2 seconds for processing. Does not extend the command's internal stability wait.

Result

Promise<string> containing the original CSCP response, at most 4096 UTF-8 bytes. One trailing CRLF is removed; internal multiline endings remain. The string is not a Measurement object and is not parsed automatically. S I, ES, FT L and ERRAUTH are valid CSCP results and do not reject the Promise. Determine command success using its CSCP reference.

Errors and special considerations

INVALID_ARGUMENT for incorrect use; MESSAGE_TOO_LARGE for an oversized command; UNSUPPORTED_COMMAND for multi-response/silent commands or reset; BUSY for an occupied scale or concurrent-operation limit; TIMEOUT for excessive waiting; NO_RESPONSE when a command finishes without a response; RESPONSE_TOO_LARGE for an oversized response; OUT_OF_MEMORY for insufficient memory. Responses are never silently truncated. Stop interrupts pending execution; its Promise does not continue in the destroyed context.

Example

async function start() {
    try {
        const stable = await scale.cmd("S", { timeoutMs: 10000 });
        console.info("CSCP weight:", stable);
        const settings = await scale.cmd("RSD");
        console.info("Configuration length:", settings.length);
        const result = await scale.cmd("FT=512");
        console.info("CSCP filter:", result);
    } catch (error) {
        console.warn(error.code || error.name, error.message);
    }
}
start();

Only one weighing command may be pending at a time. Use await for sequential execution. A new request receives BUSY while another command is pending; there is no hidden command queue. This also applies when combining scale.cmd() with tare/zero/clearTare/setPresetTare. Cancellation or timeout does not undo settings already changed. A late response is not assigned to the next request.

The function returns one response. SIR, SR, SXIR, RAS, RASI, CAL, RST, CWRESULTA and CWDEBUG are rejected before execution, including commands containing a P= credential field. Multiline content within one response, such as I0, is allowed. Use a timer and scale.read() for repeated measurement; scale.cmd() does not open a response stream.

A command may include supported parameters and a CSCP credential; the function does not bypass scale protection. Follow CSCP syntax when a protected command requires credentials. Handle ERRAUTH and ERRLOCK in the returned text. Application installation commands and other management channels do not belong in scale.cmd().

Check support with app.capabilities().scaleOperations.includes("cmd"). Limits are published as limits.maxScaleCommandBytes, limits.maxScaleResponseBytes and limits.maxScaleCommandTimeoutMs. Available from Neutron AppEngine 1.0.0; features flags describe dedicated modules. io.* is documented in the separate I/O chapter. Module settings and data storage have their own chapters and separate device and storage APIs.

Table 15

Call

Result / behavior

scale.cmd("S")

Next stable measurement or a CSCP failure response such as S I.

scale.cmd("SI")

Immediate response with the current weight.

scale.cmd("RSD")

Scale data and configuration as a string; works without an available weight.

scale.cmd("FT=?")

Current filter setting, for example FT A 512.

scale.cmd("FT=512")

Changes and saves the filter according to CSCP; inspect the returned response.

scale.cmd("UNKNOWN")

Usually ES as the resolved Promise result, not a JavaScript rejection.

scale.cmd("SIR")

UNSUPPORTED_COMMAND rejection; no continuous stream starts.

7.7 Scale module errors

Table 16

Code

Meaning for the scale

NO_MEASUREMENT

Scale operation without a valid measurement or available scale.

OUT_OF_RANGE

Preset tare exceeds capacity.

PERMISSION_DENIED

Scale command rejected by protection/authorization.

SCALE_REJECTED

The scale rejected the operation; inspect message and scale conditions.

7.8 Periodic weight logging

Standalone .js file without a TCP requirement. Logs a valid measurement once per second. Use Stop in the application manager to stop it.

// Runtime stays active until Stop. No overlap: this callback is synchronous.
console.info(app.capabilities());
setInterval(() => {
    const measurement = scale.read();
    if (measurement.available) {
        console.log("Neto:", measurement.net, "Bruto:", measurement.gross, measurement.unit);
    }
}, 1000);

8. Digital inputs and outputs

The io module monitors six inputs and six outputs, configures their functions, directly controls claimed outputs and reads input counters. Indices are always 1–6. All functions, properties and events in this chapter are available from Neutron AppEngine 1.0.0. API support: app.capabilities().features.io; physical I/O availability: app.capabilities().io.available.

Reading state and observing events require no claim. You can observe an output controlled by a system function; before writing directly, explicitly disable its function and claim it. The module shares the device I/O processing, so the same ownership rules apply through other interfaces.

io.input(index) / io.output(index)

Available since: Neutron AppEngine 1.0.0
const input = io.input(1);
const output = io.output(1);
Purpose. Obtain the object for a physical input or output.
Description. Repeated calls for the same pin return the same object. Does not change configuration, register events or switch an output.

Parameters

Table 17

Parameter

Type / requirement

Description

index

integer / required

1..6. Strings, zero, fractional values and indices above 6 are rejected.

Result

Input or output object. Both support read, configure, on, once and off. Outputs add claim, write and release; inputs add counter and resetCounter.

Errors and special considerations

INVALID_ARGUMENT for an invalid index. The object can be obtained without an I/O board; check read().available.

Example

const input = io.input(1);
const output = io.output(2);
console.info(input.read().available, output.read().value);

input.read() / output.read()

Available since: Neutron AppEngine 1.0.0
const inputState = io.input(1).read();
const outputState = io.output(1).read();
Purpose. Synchronously read the latest state and configuration snapshot.
Description. Reading requires no claim and emits no change event. The snapshot is refreshed by shared device processing and on changes; read performs no additional physical sampling. After a successful await configure/write, the snapshot includes the corresponding operation's results.

Parameters

No parameters.

Result

Input: {index, available, value, functionId, function, mode, debounceMs, glitchUs, pull, counter}. Output: {index, available, value, functionId, function, claimed}. Types and meanings are listed below.

Errors and special considerations

value is null for unavailable I/O and inputs in disabled or counter mode. counter is BigInt only for an available counter input; otherwise null. Output value represents the commanded state; confirming actual switching of an external contactor or device requires feedback on an input.

Example

const s = io.input(1).read();
console.info(s.mode, s.value, s.function);
if (s.counter !== null) console.info(s.counter.toString());
Table 18

Field since Neutron AppEngine 1.0.0

Tip

Meaning

index

number

Pin number 1..6.

available

boolean

I/O is present on the device.

value

boolean | null

true is logical 1, false is logical 0. Input values are debounced; null means no digital value is available.

functionId / function

number / string

Existing function number and its JavaScript API name. unknown indicates an unsupported stored number.

mode

string / input only

disabled, digital or counter.

debounceMs

number / input only

Digital change confirmation time in milliseconds.

glitchUs

number / input only

Counter short-pulse filter in microseconds. Used in counter mode.

pull

string / input only

none, up or down.

counter

bigint | null / input only

Latest counter value without loss of large-integer precision.

claimed

boolean / output only

The output is claimed by the user application. Does not mean the output is on.

input.configure(options)

Available since: Neutron AppEngine 1.0.0
await io.input(1).configure({ mode: "digital", function: "disabled", debounceMs: 20, pull: "down" });
Purpose. Configure and save the selected input's mode, function and processing.
Description. Changes supplied properties and retains others where compatible with the selected mode. Saves and applies configuration without restarting, through the existing shared input-configuration path. disabled and counter modes disable the input's system function. Initializing a new mode emits no change and does not count an initially active level as a new press.

Parameters

Table 19

Parameter

Type / requirement

Description

options.mode

string / optional

disabled, digital or counter. If omitted, retains the current mode.

options.function

string | integer / optional

Name or ID from the input-function table. An active function is allowed only in digital mode.

options.debounceMs

integer / optional

0..60000 ms, digital mode only. The existing initial setting is 20 ms; explicitly specify the desired value when switching from another mode.

options.pull

string / optional

none, up or down; digital mode only.

options.glitchUs

integer / optional

0..12 µs, counter mode only. 0 disables filtering. When switching to counter without specifying a filter, uses the previous nonzero filter or 5 µs.

Result

Promise<InputState> with the read() structure. Settings persist after Stop and device restart.

Errors and special considerations

INVALID_ARGUMENT for invalid types or incompatible properties, NOT_AVAILABLE, RESOURCE_IN_USE during active dosing or checkweighing, CONFIGURE_FAILED if applying or saving fails, and BUSY. Counter mode may be rejected if the selected input has no available counting resource. Do not configure in a fast periodic loop.

Example

await io.input(1).configure({ mode: "digital", function: "tare", debounceMs: 30, pull: "down" });
// For independent JavaScript handling of the same input:
await io.input(1).configure({ function: "disabled" });

output.configure(options)

Available since: Neutron AppEngine 1.0.0
await io.output(1).configure({ function: "disabled" });
Purpose. Select and save an output's system function or disable it.
Description. Changing the function does not directly switch the output. An active function controls its state according to device rules. disabled enables manual control and JavaScript claiming; it does not automatically switch the current output level off.

Parameters

Table 20

Parameter

Type / requirement

Description

options.function

string | integer / required

Name or ID from the output-function table.

Result

Promise<OutputState>. The setting is persistent and applies without restarting.

Errors and special considerations

RESOURCE_IN_USE if the output is claimed or dosing/checkweighing is active. Call release(), then configure(). Other channels also cannot change a claimed output's function. Other errors: INVALID_ARGUMENT, NOT_AVAILABLE, CONFIGURE_FAILED, BUSY.

Example

await io.output(2).configure({ function: "inTolerance" });
// Monitoring is allowed even when the system controls the output.
io.output(2).on("change", e => console.info(e.value));

Function names and IDs

Table 21

Input ID

JavaScript name since Neutron AppEngine 1.0.0

Meaning

0

disabled

No system function

1

zero

Zeroing

2

tare

Taring

3

clearTare

Clear tare

4

dosingStart

Start dosing

5

dosingPause

Pause dosing

6

dosingStop

Stop dosing

7

checkweigherSensor

Product sensor

8

checkweigherStart

Start checkweighing

9

checkweigherPause

Pause checkweighing

10

checkweigherStop

Stop checkweighing

11

checkweigherReset

Reset checkweighing

12

checkweigherEnable

Enable CONS

13

checkweigherTrigger

Trigger rejection

Table 22

Output ID

JavaScript name since Neutron AppEngine 1.0.0

Meaning

0

disabled

No system function

1

inTolerance

Within tolerance

2

underTolerance

Below tolerance

3

overTolerance

Above tolerance

4

dosingActive

Dosing active

5

dosingFast

Coarse dosing

6

dosingMedium

Medium dosing

7

dosingFine

Fine dosing

8

dosingFly

Waiting for inflow

9

dosingUnloading

Discharging

10

dosingInTolerance

Dosing within tolerance

11

dosingOutOfTolerance

Dosing outside tolerance

12

dosingEnd

Dosing complete

13

dosingError

Dosing error

14

checkweigherBelt

Conveyor

15

checkweigherLow

Underweight reject

16

checkweigherHigh

Overweight reject

17

checkweigherGood

Acceptable-weight pulse

18

checkweigherCommon

Common reject / error

19

checkweigherActive

Checkweighing active

20

checkweigherAlarm

Alarm

21

checkweigherBuffer

Hopper warning

Device functionality determines the actual rules for these system functions. Registering change does not disable a function: an input assigned to tare can trigger both system taring and a JavaScript event. If JavaScript will perform the operation, first set function="disabled" to avoid performing it twice. ID/name lists are also available in capabilities.io.inputFunctions and outputFunctions.

output.claim(options?)

Available since: Neutron AppEngine 1.0.0
await io.output(1).claim({ safeState: false });
Purpose. Claim exclusive manual output control for the current application run.
Description. Allowed only with function=disabled. Does not automatically disable an assigned system function or change the current level. The same application may claim the same output again to update safeState.

Parameters

Table 23

Parameter

Type / requirement

Description

options.safeState

boolean / false

Output state on release() or application termination. Applies to the current run; not saved as the device startup state.

Result

Promise<OutputState> with claimed=true.

Errors and special considerations

RESOURCE_IN_USE for an active system function or another owner. NOT_AVAILABLE, INVALID_ARGUMENT, BUSY. Claimed outputs reject external writes and function changes, including through other channels. Observing change remains allowed.

Example

const out = io.output(1);
await out.configure({ function: "disabled" });
await out.claim({ safeState: false });
await out.write(true);

output.write(value)

Available since: Neutron AppEngine 1.0.0
await io.output(1).write(true);
Purpose. Set a claimed output to the requested logical state.
Description. Writes through shared I/O processing. An actual change emits change; writing the same value again emits no event. State is not saved on every switch. The Promise and change event are separate notifications; do not rely on their relative order.

Parameters

Table 24

Parameter

Type / requirement

Description

value

boolean / required

true switches on, false switches off; 0, 1 and strings are not allowed.

Result

Promise<OutputState> after writing the control output.

Errors and special considerations

NOT_OWNER before claim or after release. NOT_AVAILABLE, INVALID_ARGUMENT, RESOURCE_IN_USE, BUSY. Confirmation does not prove physical operation of the external device.

Example

const out = io.output(1);
await out.claim();
await out.write(true);
await out.write(false);

output.release()

Available since: Neutron AppEngine 1.0.0
await io.output(1).release();
Purpose. Set the output to safeState and release ownership.
Description. Automatic release also occurs in service processing after Stop, an unhandled error or application replacement. The previous system function is not restored automatically: configure is an explicit persistent change. Releasing an output not claimed in the current run has no effect.

Parameters

No parameters.

Result

Promise<undefined>. If safeState changes the level, change is emitted while the application is still running.

Errors and special considerations

NOT_OWNER for another owner, NOT_AVAILABLE, BUSY. Delivery of a final event is not guaranteed at application termination. After a hardware reset, normal device startup output state applies (off), not the previous safeState. This is not a substitute for a hardware safety circuit.

Example

await io.output(1).release();
// A system function can now be assigned again:
await io.output(1).configure({ function: "inTolerance" });

pin.on() / pin.once() / pin.off()

Available since: Neutron AppEngine 1.0.0
pin.on("change", callback);
pin.once("change", callback);
pin.off("change", callback);
Purpose. Observe changes on the selected input or output.
Description. on observes subsequent changes. once unregisters before the first subsequent change, which can be either on or off. off removes registrations of the same function. Registration alone emits no initial event. The supported event is change, with up to 32 listeners per pin.

Parameters

Table 25

Parameter

Type / requirement

Description

eventName

string / required

Only "change".

callback

function / required

Receives {index, value, previousValue, timeMs}. off requires the same function reference.

Result

Returns the same pin object for chaining. Events are independent of the source of change: JavaScript, CSCP, other management interfaces or a system function.

Errors and special considerations

INVALID_ARGUMENT, QUOTA_EXCEEDED. Inputs emit events after debounce. Digital events are unavailable in counter or disabled mode. Outputs emit events only when the commanded level actually changes. An exception or unhandled rejected Promise in a callback can stop the application under runtime rules. Without listeners, no events for that pin are sent to JavaScript.

Example

const onInput = event => {
    console.info(event.index, event.previousValue, "->", event.value, event.timeMs);
    if (event.value) console.info("Input activated");
};
io.input(1).on("change", onInput);
io.output(2).once("change", e => console.info("First output change:", e.value));
// Later: io.input(1).off("change", onInput);
Table 26

Event field since Neutron AppEngine 1.0.0

Tip

Meaning

index

integer

1..6 for the pin with the listener.

value

boolean

New state: true is logical 1, false is logical 0.

previousValue

boolean

Previous confirmed state.

timeMs

number

Monotonic change time in milliseconds since device startup; may be fractional. Not a date, UTC time or callback delivery time. For inputs, this is the confirmation time after debounce.

The activation-duration example needs no polling. timeMs restarts when the device restarts. Configuration changes and initial samples in a new mode are not physical change events.

let activatedAt;
io.input(1).on("change", event => {
    if (event.value) activatedAt = event.timeMs;
    else if (activatedAt !== undefined) {
        console.info("Active duration:", event.timeMs - activatedAt, "ms");
        activatedAt = undefined;
    }
});

input.counter()

Available since: Neutron AppEngine 1.0.0
const count = io.input(1).counter();
Purpose. Return the latest total of detected positive pulses on a counter input.
Description. Counting uses the existing device mechanism without invoking JavaScript for every pulse. BigInt preserves precision above 2^53. Maximum: 9223372036854775807; the value saturates at this limit. Normal device counter persistence remains active; a sudden power loss may lose pulses not yet saved.

Parameters

No parameters.

Result

bigint. The same value appears in input.read().counter. Use count.toString() for JSON; JSON.stringify cannot directly serialize BigInt.

Errors and special considerations

INVALID_MODE if the input is not in counter mode; NOT_AVAILABLE if I/O is absent. This is a snapshot, not a guarantee that no new pulse arrived while reading.

Example

await io.input(1).configure({ mode: "counter", glitchUs: 5 });
const count = io.input(1).counter();
console.info(count.toString());
console.info(JSON.stringify({ count: count.toString() }));

input.resetCounter()

Available since: Neutron AppEngine 1.0.0
await io.input(1).resetCounter();
Purpose. Reset the selected counter and save the new baseline.
Description. Asynchronous; allowed only in counter mode. Emits no digital change event. Pulses can arrive during or immediately after reset.

Parameters

No parameters.

Result

Promise<bigint> containing the latest counter snapshot after execution. New pulses mean it may no longer be 0n.

Errors and special considerations

INVALID_MODE, NOT_AVAILABLE, WRITE_FAILED, BUSY. A save failure may occur after the in-memory counter has reset; the error does not undo that effect. Do not reset in a fast loop.

Example

await io.input(1).resetCounter();
console.info(io.input(1).counter().toString());

Complete example: input controls output

The example explicitly saves input 1 configuration and disables output 1's system function. It then claims the output with safeState=false, monitors input 1 and separately observes output 2. It bounds overlapping asynchronous writes and applies the latest input state after a write finishes.

// Input 1 controls output 1; output 2 is only monitored.
// configure() settings persist. The active system function on output 1
// is explicitly disabled; during dosing/checkweighing the call is rejected.
const input = io.input(1);
const output = io.output(1);
let ready = false;
let updating = false;
let dirty = false;

// Bounded change coalescing: apply the latest state after a slow write.
async function updateOutput() {
    if (!ready) return;
    dirty = true;
    if (updating) return;
    updating = true;
    try {
        while (dirty) {
            dirty = false;
            await output.write(input.read().value);
        }
    } catch (error) {
        console.error(error.code || error.name, error.message);
        app.stop();
    } finally {
        updating = false;
    }
}

input.on("change", event => {
    console.info("Input", event.index, event.value, "timeMs:", event.timeMs);
    updateOutput(); // The function handles its own errors.
});

io.output(2).on("change", event => {
    // Also works when a CSCP command or system function switches output 2.
    console.info("Output", event.index, event.previousValue, "->", event.value);
});

async function start() {
    const caps = app.capabilities();
    if (!caps.features.io || !caps.io.available) throw new Error("I/O unavailable");
    await input.configure({ mode: "digital", function: "disabled", debounceMs: 20, pull: "down" });
    await output.configure({ function: "disabled" });
    await output.claim({ safeState: false });
    ready = true;
    await updateOutput(); // Initial state emits no change event.
    console.info("I/O application ready");
}

start().catch(error => {
    console.error(error.code || error.name, error.message);
    app.stop(); // Stopping sets the claimed output to safeState.
});

Testing an I/O application

Table 27

Test

Expected result

Initial state

read returns a value; registering on/once emits no event.

Switch input 1 on and off

Two change events after debounce, with opposite previousValue/value and corresponding timeMs.

Short contact bounce

No duplicate events for one confirmed change.

External SOT for unclaimed output 2

A JavaScript change event on each actual change; repeating the same value emits none.

Output 2 controlled by a system function

JavaScript can observe changes without claim.

External SOT/SOF or function change for claimed output 1

Rejected without overwriting the application's output.

Stop or application error with a claimed output on

Transition to safeState and release during service processing.

Counter and large values

BigInt without precision loss; no digital change event for each pulse.

Unavailable I/O or invalid index

available=false or INVALID_ARGUMENT; no access to another pin.

9. Module settings: RMD and SMD

The device module manages Neutron settings. It is separate from scale, which controls weighing, and application data in storage. All functions and properties in this chapter are available from Neutron AppEngine 1.0.0. Support: app.capabilities().features.settings.

Changes use existing SMD validation and storage. They respect busy interfaces and claimed outputs. Settings that can apply during operation use existing live application mechanisms. Others report that a restart is required. The API never automatically restarts the device.

device.cmd(command)

Available since: Neutron AppEngine 1.0.0
const raw = await device.cmd("RMD");
const result = await device.cmd("SMD;S0B=19200;S0P=0;");
Purpose. Execute a supported RMD or SMD management command.
Description. RMD returns a text list of settings and basic states in the existing format. SMD uses the same result as settings.write(). Other management commands such as REB are not supported here. Do not repeat SMD between individual settings.

Parameters

Table 28

Parameter

Type / requirement

Description

command

string / required

RMD or SMD;KEY=value;... . Maximum 2048 UTF-8 bytes; no control characters. SMD accepts up to 16 distinct keys.

Result

RMD: Promise<string>. SMD: Promise<SettingsWriteResult>, described below.

Errors and special considerations

INVALID_ARGUMENT, UNSUPPORTED_COMMAND, BUSY, NO_RESPONSE, RESPONSE_TOO_LARGE. RMD can exceed 4096 bytes; use settings.read for selected keys or settings.list for pagination. The API does not read passwords, PINs or private certificate data. Manage certificates through the existing certificate provisioning process.

Example

try {
    const raw = await device.cmd("RMD");
    console.info(raw);
} catch (error) {
    if (error.code !== "RESPONSE_TOO_LARGE") throw error;
    console.info("Use device.settings.list() for paged settings");
}

device.settings.read(keys)

Available since: Neutron AppEngine 1.0.0
const values = await device.settings.read(["S0B", "S0P"]);
Purpose. Read selected stored settings without a large RMD response.
Description. Returns values as strings, including numbers. A missing key has value null. Reading changes no device state or settings and does not guarantee that pending hardware application has completed.

Parameters

Table 29

Parameter

Type / requirement

Description

keys

string[] / required

1..16 keys. Names contain 1..15 characters: A–Z, 0–9 or _.

Result

Promise<object>, for example {S0B:"19200", S0P:"0", UNKNOWN:null}.

Errors and special considerations

INVALID_ARGUMENT, PERMISSION_DENIED for protected data, RESPONSE_TOO_LARGE, BUSY. Do not invent APIs using unknown keys; supported settings are defined by the device and its documentation.

Example

const values = await device.settings.read(["S0B", "S0I", "S0P", "S0S"]);
const baudRate = values.S0B === null ? null : Number(values.S0B);
console.info(baudRate);

device.settings.list(options?)

Available since: Neutron AppEngine 1.0.0
const page = await device.settings.list({ cursor: null, limit: 16 });
Purpose. Read publicly accessible stored settings in pages.
Description. Keys are sorted ascending. cursor is the exclusive last key of the previous page. The response may contain fewer than limit keys because of its size limit. Pages are not a single snapshot: settings can change between calls.

Parameters

Table 30

Parameter

Type / requirement

Description

options.cursor

string | null / omitted

nextCursor from the previous response; null or omission starts at the beginning.

options.limit

integer / 16

1..32 keys per page; response limit remains 4096 bytes.

Result

Promise<{values:object, nextCursor:string|null}>. null indicates the end.

Errors and special considerations

INVALID_ARGUMENT, RESPONSE_TOO_LARGE for a single oversized value, BUSY. The list contains stored keys; dynamic RMD states are not necessarily stored settings. Confidential data is omitted.

Example

let cursor = null;
do {
    const page = await device.settings.list({ cursor, limit: 16 });
    console.info(page.values);
    cursor = page.nextCursor;
} while (cursor !== null);

device.settings.write(values)

Available since: Neutron AppEngine 1.0.0
const result = await device.settings.write({ S0B: "19200", S0P: "0" });
Purpose. Save a group of settings through existing SMD processing.
Description. Validates the overall format before starting. Individual validation and hardware failures then follow existing SMD rules. The group is not a transaction: one failure does not undo other saved values. Check result.ok and result.errors even after await succeeds.

Parameters

Table 31

Parameter

Type / requirement

Description

values

object / required

1..16 keys. Values may be strings, booleans (0/1) or integers in −2147483648..4294967295. Supply decimals as strings in the setting's format. At most 1024 UTF-8 bytes per value; no semicolons, control characters or special value ?. The entire request must fit within 4096 bytes.

Result

Promise<{ok:boolean, applied:string[], errors:object, rebootRequired:boolean, applyPending:boolean}>. applied lists keys with no immediate save error; it is not independent confirmation of physical interface readiness. A final application error may have a separate key in errors.

Errors and special considerations

Invalid format rejects with INVALID_ARGUMENT or MESSAGE_TOO_LARGE. Individual setting failures return ok=false and errors, such as CHECKWEIGHER_BUSY or INVALID_OR_WRITE_FAILED. applyPending indicates pending serial-interface application; monitor interface state or device status. rebootRequired never triggers an automatic restart. Do not write persistent settings in a fast measurement loop.

Example

const result = await device.settings.write({ S0B: "19200", S0I: "1", S0P: "0", S0S: "1" });
if (!result.ok) console.warn("Some settings failed:", result.errors);
if (result.rebootRequired) console.info("A device restart is required");
if (result.applyPending) console.info("Serial configuration is still being applied");

Settings read example

async function start() {
    if (!app.capabilities().features.settings) throw new Error("Settings API is unavailable");
    console.info("Selected settings:", await device.settings.read(["S0B", "S0I", "S0P", "S0S"]));
    // Changes persist. Uncomment only the desired keys before use.
    // const result = await device.settings.write({ S0B: "19200", S0I: "1", S0P: "0", S0S: "1" });
    // console.info(result.ok, result.errors, result.rebootRequired, result.applyPending);
    // Equivalent: await device.cmd("SMD;S0B=19200;S0I=1;S0P=0;S0S=1;");
    // Use pagination for more settings; complete RMD may exceed 4096 bytes.
    const page = await device.settings.list({ limit: 8 });
    console.info("First settings page:", page.values);
}
start().catch(error => { console.error(error.code || error.name, error.message); app.stop(); });

10. Storage and files

The storage module provides persistent application data storage. All functions in this chapter are available from Neutron AppEngine 1.0.0. Support: app.capabilities().features.files. Application files are separate from system files, certificates and installed application code. The API cannot access anything outside this data space.

File names contain 1..64 characters. The first must be A–Z/a–z or a digit; subsequent characters may also include _, - or a dot. Consecutive dots, slashes, subdirectories and absolute paths are prohibited. Names are case-sensitive. Data survives Stop, restart and normal application replacement. The installed application shares one data space; a new version or different application on the device may use the same data. Factory default deletes user files and local databases. Normal application Delete does not delete them.

Operations are asynchronous and use a bounded service queue. Do not load an entire large file into JavaScript, create unbounded write queues or send all chunks without await. Stopping does not undo a write already started; its result may no longer reach the stopped application.

storage.info()

Available since: Neutron AppEngine 1.0.0
const info = await storage.info();
Purpose. Report usage, quota and available space.
Description. Files and local databases share the application quota. Actual availability also depends on other device data and the system reserve. Temporary copies for atomic replacement or compaction require additional physical space.

Parameters

No parameters.

Result

{quotaBytes, usedBytes, reserveBytes, freeBytes, availableBytes, maxFileBytes, databases:[{name,bytes}]}. usedBytes is the combined logical size of committed files and databases; freeBytes is total free storage. availableBytes estimates possible growth within the quota and reserve.

Errors and special considerations

NOT_AVAILABLE or a read error. A snapshot, not a reservation for a future write. Availability is checked again during the operation.

Example

const info = await storage.info();
console.info(info.usedBytes, info.availableBytes, info.databases);

storage.write() / storage.writeText()

Available since: Neutron AppEngine 1.0.0
await storage.write(name, data);
await storage.writeText(name, text);
Purpose. Create a file or replace its entire contents.
Description. write accepts string or Uint8Array; writeText accepts only string. Strings are stored as UTF-8; binary data as exact bytes. Adds no newline or NUL. Full replacement uses a temporary write followed by replacement of the committed file.

Parameters

Table 32

Parameter

Type / requirement

Description

name

string / required

Valid file name.

data / text

string | Uint8Array / required

0..4096 bytes per call after UTF-8 encoding. writeText does not accept Uint8Array.

Result

Promise<undefined> after successful writing and storage confirmation. An empty payload creates or empties the file.

Errors and special considerations

INVALID_ARGUMENT, MESSAGE_TOO_LARGE, QUOTA_EXCEEDED, NO_SPACE, WRITE_FAILED, NOT_AVAILABLE, BUSY. Failed replacement retains the previous committed file. For larger contents, write the first chunk, then append sequentially; this multi-step construction is not one atomic operation.

Example

await storage.writeText("config.json", JSON.stringify({ target: 25, tolerance: 0.1 }));
await storage.write("data.bin", new Uint8Array([0, 255, 10, 13]));

storage.append() / storage.appendText()

Available since: Neutron AppEngine 1.0.0
await storage.append(name, data);
await storage.appendText(name, text);
Purpose. Append data to a file, suitable for logs.
Description. Creates a missing file without overwriting previous contents. Append is not a multi-record transaction; errors or power loss may leave the last addition incomplete. Design logs to detect such partial final records.

Parameters

Table 33

Parameter

Type / requirement

Description

name

string / required

Valid file name.

data / text

string | Uint8Array / required

At most 4096 bytes per call; appendText requires string. Maximum file size: 262144 bytes.

Result

Promise<undefined>. A delivered success confirms the write; a missing response does not mean the write did not happen.

Errors and special considerations

MESSAGE_TOO_LARGE, QUOTA_EXCEEDED, NO_SPACE, WRITE_FAILED, BUSY. Part of the addition may already exist after an error. Do not blindly retry business records without a unique ID or verification.

Example

await storage.appendText("measurements.jsonl", JSON.stringify({ id: 1, net: scale.net }) + "\n");

storage.read() / storage.readText()

Available since: Neutron AppEngine 1.0.0
const bytes = await storage.read(name, { offset: 0, length: 4096 });
const text = await storage.readText(name);
Purpose. Read binary bytes or UTF-8 text.
Description. read returns Uint8Array; readText returns string. offset and length always use bytes. Starting beyond the end returns an empty result. A read near the end can return fewer bytes than requested.

Parameters

Table 34

Parameter

Type / requirement

Description

name

string / required

File name.

options.offset

integer / 0

0..262144 bytes from the start.

options.length

integer / optional

0..4096 bytes. read defaults to up to 4096 bytes. Without length, readText requires the remaining text to fit in one response; otherwise RESPONSE_TOO_LARGE.

Result

Promise<Uint8Array> or Promise<string>. read preserves binary NUL and all other bytes.

Errors and special considerations

NOT_FOUND, INVALID_ARGUMENT, READ_FAILED, RESPONSE_TOO_LARGE. Respect multibyte character boundaries when splitting UTF-8 text; decoding arbitrary chunks independently can split a character. readText is not a JSON or JSONL parser; use JSON.parse for small JSON documents.

Example

const config = JSON.parse(await storage.readText("config.json"));
let offset = 0;
for (;;) {
    const part = await storage.read("data.bin", { offset, length: 4096 });
    if (!part.length) break;
    console.info("Read bytes:", part.length);
    offset += part.length;
}

storage.list(options?) / storage.stat(name)

Available since: Neutron AppEngine 1.0.0
const page = await storage.list({ cursor: null, limit: 16 });
const info = await storage.stat("data.bin");
Purpose. List files or obtain a file's size.
Description. list includes regular application files only, not internal database files. Names sort ascending; cursor excludes the last name already returned. Databases appear in storage.info().databases.

Parameters

Table 35

Parameter

Type / requirement

Description

options.cursor

string | null / omitted

nextCursor from the previous page.

options.limit

integer / 16

1..32 files.

name for stat

string / required

Valid name.

Result

list: {files:[{name,size}], nextCursor:string|null}. stat: {name,size}. Size is in bytes. null marks the end of the list.

Errors and special considerations

NOT_FOUND for stat, INVALID_ARGUMENT, READ_FAILED, OUT_OF_MEMORY. Pages are not an immutable snapshot during concurrent additions or deletions.

Example

let cursor = null;
do {
    const page = await storage.list({ cursor, limit: 16 });
    for (const file of page.files) console.info(file.name, file.size);
    cursor = page.nextCursor;
} while (cursor !== null);

storage.remove(name) / storage.rename(name, to)

Available since: Neutron AppEngine 1.0.0
const removed = await storage.remove("old.jsonl");
await storage.rename("measurements.jsonl", "archive.jsonl");
Purpose. Delete or rename a regular file.
Description. remove cannot access internal database data. rename does not overwrite an existing destination; explicitly remove it first if required.

Parameters

Table 36

Parameter

Type / requirement

Description

name

string / required

Source file name.

to for rename

string / required

New valid name with no existing file.

Result

remove: Promise<boolean>, false if absent. rename: Promise<undefined>.

Errors and special considerations

NOT_FOUND for a missing rename source, ALREADY_EXISTS for an existing destination, WRITE_FAILED, INVALID_ARGUMENT. Deletion cannot be undone.

Example

await storage.remove("measurements-old.jsonl");
await storage.rename("measurements.jsonl", "measurements-old.jsonl");

storage.findText(name, text, options?)

Available since: Neutron AppEngine 1.0.0
const page = await storage.findText("measurements.jsonl", "ART-001", { offset: 0, limit: 16 });
Purpose. Find exact text in a regular file without loading all contents into JavaScript.
Description. Sequential, case-sensitive UTF-8 byte search, not a regular expression. Supports overlapping matches. Each call scans at most 65536 bytes or stops at the match limit. Use a local database for fast key lookup instead of repeatedly scanning files.

Parameters

Table 37

Parameter

Type / requirement

Description

name

string / required

File name.

text

string / required

1..128 UTF-8 bytes, without NUL.

options.offset

integer / 0

Starting byte offset, 0..262144.

options.limit

integer / 16

1..64 matches per page.

Result

{offsets:number[], nextOffset:number|null}. offsets are absolute match starting positions in bytes. Continue with exactly the returned nextOffset; it preserves possible partial matches across page boundaries. null marks end of file.

Errors and special considerations

NOT_FOUND, INVALID_ARGUMENT, READ_FAILED, CANCELLED. Do not modify the file during a multi-step search if you need stable results. Total sequential search time is proportional to file size.

Example

let offset = 0;
do {
    const page = await storage.findText("measurements.jsonl", "ART-001", { offset, limit: 16 });
    console.info(page.offsets);
    offset = page.nextOffset;
} while (offset !== null);

JSONL logs and rotation

JSONL stores one independent JSON object per line, with no commas between lines or surrounding []. This supports appending measurements. Generate each line with JSON.stringify(record)+"\n". Detect and separately handle an incomplete final line after interruption. JSONL provides no automatic index or automatic deletion of old measurements.

// Size-limited JSONL log with one archive file.
let writing = false;
async function start() {
    if (!app.capabilities().features.files) throw new Error("Storage API is unavailable");
    console.info("Storage:", await storage.info());
    setInterval(async () => {
        if (writing) return;
        writing = true;
        try {
            const m = scale.read();
            if (!m.available) return;
            let size = 0;
            try { size = (await storage.stat("measurements.jsonl")).size; }
            catch (error) { if (error.code !== "NOT_FOUND") throw error; }
            if (size >= 32768) {
                await storage.remove("measurements-old.jsonl");
                await storage.rename("measurements.jsonl", "measurements-old.jsonl");
            }
            await storage.appendText("measurements.jsonl", JSON.stringify({ timeMs: m.timeMs, net: m.net, gross: m.gross, unit: m.unit }) + "\n");
        } catch (error) {
            console.warn(error.code || error.name, error.message);
        } finally {
            writing = false;
        }
    }, 10000);
}
start().catch(error => { console.error(error.code || error.name, error.message); app.stop(); });

Shared storage limits

Table 38

Limit since Neutron AppEngine 1.0.0

Value

Shared application quota

524288 bytes for files and databases combined.

System reserve

131072 physically free bytes before additional writes. Other device functions may change actual availability.

File or single-database log

262144 bytes.

Read / write call

4096 bytes.

Regular files

At most 64 names.

Ordering

Storage requests run in one bounded service queue. Multiple calls are not a transaction.

Application termination

Open database objects are released; committed data remains.

Factory default

Also deletes application files and databases.

11. Simple local record database

The local database stores small JSON objects with a unique key, such as a product code, recipe code or business-record ID. All functions in this chapter are available from Neutron AppEngine 1.0.0. Support: app.capabilities().features.records. Data shares the file storage space and quota, but internal database files are separate from the regular file API.

Opening validates the record log and builds a sorted key index. get uses the index and direct record offset without scanning the whole database. Opening and compaction scan data and may take longer; open once during startup and reuse the object. One indexed key per database is supported. There is no SQL, relations, automatic secondary indexing or multi-record transaction.

storage.openRecords(name, options?)

Available since: Neutron AppEngine 1.0.0
const articles = await storage.openRecords("articles", { key: "code" });
Purpose. Create or open a database and prepare its index.
Description. The database name and key-field name are permanently associated at creation. Use the same key-field name when reopening. Opening an already open name is rejected; reuse the returned object. Objects are valid only during the current application run.

Parameters

Table 39

Parameter

Type / requirement

Description

name

string / required

1..32 characters following file-name rules.

options.key

string / "id"

Top-level object field name. 1..32 ASCII characters: first a letter or _, then also digits. Every record must contain this field as a nonempty string.

Result

Promise<RecordStore> with name and key properties and put/get/delete/list/stat/compact/close methods.

Errors and special considerations

SCHEMA_MISMATCH for a different key field in an existing database; ALREADY_OPEN; QUOTA_EXCEEDED; NO_SPACE; CORRUPT; CANCELLED; OUT_OF_MEMORY. At most 8 persistent databases and 2 open simultaneously. An incomplete final record is removed on opening; an integrity failure in a complete record rejects opening rather than silently deleting data.

Example

const articles = await storage.openRecords("articles", { key: "code" });
// Reuse articles in application events and timers.
console.info(await articles.stat());

records.put(record)

Available since: Neutron AppEngine 1.0.0
await articles.put({ code: "ART-001", name: "Flour", target: 25 });
Purpose. Insert an object or fully replace the record with the same key.
Description. put replaces the whole object, not individual fields. Data is appended to the log and the committed record updates the index. Keys are case-sensitive. Multiple sequential put calls are not a single transaction.

Parameters

Table 40

Parameter

Type / requirement

Description

record

object / required

JSON-serializable object, at most 2048 UTF-8 bytes after JSON.stringify and at most 16 nested object/array levels. The key field must be a string of 1..64 UTF-8 bytes without control characters. Explicitly convert numeric IDs with String.

Result

Promise<object> containing the stored JSON object.

Errors and special considerations

INVALID_ARGUMENT, MESSAGE_TOO_LARGE, QUOTA_EXCEEDED, NO_SPACE, WRITE_FAILED, CLOSED, CORRUPT. BigInt and circular references cannot be serialized as JSON. A commit failure may leave the write outcome uncertain; reopen and check get before retrying. Do not record every pulse without bounds.

Example

await articles.put({ code: "ART-001", name: "Flour", target: 25 });
await articles.put({ code: "ART-001", name: "Flour", target: 30 });
// The second call replaces the complete first record with that code.

records.get(key)

Available since: Neutron AppEngine 1.0.0
const article = await articles.get("ART-001");
Purpose. Quickly retrieve the latest committed record by unique key.
Description. Uses a sorted index: key lookup requires logarithmic comparisons and reading the selected record. Does not scan all objects. Returns a new object; changing it in JavaScript does not itself change the database.

Parameters

Table 41

Parameter

Type / requirement

Description

key

string / required

Exact key, 1..64 UTF-8 bytes, without control characters.

Result

Promise<object|null>. null means the key is absent.

Errors and special considerations

INVALID_ARGUMENT, CLOSED, READ_FAILED, CORRUPT. Other fields are not indexed. Do not treat string IDs as numbers: "001" and "1" are distinct keys.

Example

const article = await articles.get("ART-001");
if (article === null) console.warn("Article not found");
else console.info(article.name, article.target);

records.delete(key)

Available since: Neutron AppEngine 1.0.0
const deleted = await articles.delete("ART-001");
Purpose. Remove a record from the database's active list.
Description. Normally appends a committed deletion record; old data may remain until compaction. Deletion is not secure erasure of physical media. Deleting an absent key is allowed.

Parameters

Table 42

Parameter

Type / requirement

Description

key

string / required

Key following the same rules as get.

Result

Promise<boolean>: true if the record existed, otherwise false.

Errors and special considerations

INVALID_ARGUMENT, CLOSED, NO_SPACE, WRITE_FAILED, CORRUPT. At the log limit, deletion may trigger compaction requiring temporary space.

Example

const deleted = await articles.delete("ART-002");
console.info("Deleted:", deleted);

records.list(options?)

Available since: Neutron AppEngine 1.0.0
const page = await articles.list({ cursor: null, limit: 16 });
Purpose. Read active records in key order, page by page.
Description. Records follow byte order of keys. cursor excludes the previous page's last key. Response-size limits may shorten a page below limit. For non-indexed fields, scan pages and filter in JavaScript; this is not fast indexed lookup.

Parameters

Table 43

Parameter

Type / requirement

Description

options.cursor

string | null / omitted

Returned nextCursor from the previous page.

options.limit

integer / 16

1..32 records, also constrained by object and response sizes.

Result

{records:object[], nextCursor:string|null}. null marks the end. Changing the database between pages means results are not an immutable snapshot.

Errors and special considerations

INVALID_ARGUMENT, CLOSED, READ_FAILED, CORRUPT, OUT_OF_MEMORY. Avoid accumulating every page in one large array when only one result is needed.

Example

let cursor = null;
do {
    const page = await articles.list({ cursor, limit: 8 });
    for (const record of page.records) {
        if (record.target >= 25) console.info(record.code, record.target);
    }
    cursor = page.nextCursor;
} while (cursor !== null);

records.stat()

Available since: Neutron AppEngine 1.0.0
const status = await articles.stat();
Purpose. Read the active record count, log size and key field.
Description. Log size includes replaced records and deletions, not just currently active objects.

Parameters

No parameters.

Result

{count:number, bytes:number, key:string}.

Errors and special considerations

CLOSED or CORRUPT. At most 2048 active records per database; size limits and shared quota may reduce the achievable count.

Example

console.info(await articles.stat());

records.compact()

Available since: Neutron AppEngine 1.0.0
await articles.compact();
Purpose. Remove old versions and deletions from the log to reclaim space.
Description. Copies only active records into a temporary file, validates and commits it, then replaces the old database. Interruption retains either the old or new committed database. put or delete may also trigger compaction when the log reaches 262144 bytes.

Parameters

No parameters.

Result

Promise<undefined>. Active keys and values remain unchanged.

Errors and special considerations

NO_SPACE for the temporary copy, WRITE_FAILED, READ_FAILED, CANCELLED, CORRUPT, OUT_OF_MEMORY. May take longer and occupy the storage service queue; do not run after every measurement. After shared QUOTA_EXCEEDED, explicit compaction may remove obsolete contents before retrying a write.

Example

await articles.compact();
console.info("After compaction:", await articles.stat());

records.close()

Available since: Neutron AppEngine 1.0.0
await articles.close();
Purpose. Release the open object and index while retaining data.
Description. Subsequent object methods return CLOSED. Repeated close is harmless. Reopen using the same database name and key field when needed. Application termination releases its open objects automatically.

Parameters

No parameters.

Result

Promise<undefined>.

Errors and special considerations

BUSY if the queue is full. Operations queued before close may complete first; using a closed object is rejected.

Example

try {
    console.info(await articles.get("ART-001"));
} finally {
    await articles.close();
}

storage.removeRecords(name)

Available since: Neutron AppEngine 1.0.0
const removed = await storage.removeRecords("articles");
Purpose. Delete an entire local database and its schema.
Description. The database must be closed. Find names in storage.info().databases. After deletion, the same name may be created with a different key field.

Parameters

Table 44

Parameter

Type / requirement

Description

name

string / required

Database name, 1..32 characters.

Result

Promise<boolean>: true if it existed, otherwise false.

Errors and special considerations

RESOURCE_IN_USE for an open database, INVALID_ARGUMENT, WRITE_FAILED. Entire-database deletion cannot be undone.

Example

await articles.close();
// Execute only if you want to remove all products:
// await storage.removeRecords("articles");

Complete local product database example

// Simple local product database. Data survives Stop and restart.
async function start() {
    if (!app.capabilities().features.records) throw new Error("Local records API is unavailable");
    const articles = await storage.openRecords("articles", { key: "code" });
    try {
        // put inserts or fully replaces the record with the same code.
        await articles.put({ code: "ART-001", name: "Flour", target: 25, tolerance: 0.1 });
        await articles.put({ code: "ART-002", name: "Sugar", target: 10, tolerance: 0.05 });
        const article = await articles.get("ART-001");
        console.info("Article:", article);
        let cursor = null;
        do {
            const page = await articles.list({ cursor, limit: 8 });
            for (const record of page.records) console.info(record.code, record.name);
            cursor = page.nextCursor;
        } while (cursor !== null);
        console.info("Database:", await articles.stat());
        // await articles.delete("ART-002");
        // await articles.compact(); // Reclaim obsolete records after many updates.
    } finally {
        await articles.close();
    }
}
start().catch(error => {
    console.error(error.code || error.name, error.message);
    app.stop();
});

Testing persistence and recovery

Table 45

Test

Expected result

put the same code twice

get returns the latest complete version; count does not increase.

Stop, new Run or normal restart

The same name and key open stored data; the index is rebuilt.

Power loss during append

Fully committed records remain; an incomplete final record is discarded on opening. The last unconfirmed operation's outcome may be uncertain.

Integrity failure in a complete record

CORRUPT; the entire database is not automatically deleted.

compact and reopen

Active records remain unchanged; the log shrinks if old versions existed.

Quota reached

QUOTA_EXCEEDED or NO_SPACE without unbounded data growth.

Factory default

User files and databases are deleted.

Access a closed object or one from a previous run

CLOSED or rejection of a stale request.

12. Communication modules

Communication modules are separate from the runtime, weighing module and application management. Each has its own requirements, functions, events, errors and limits. Applications without communication modules can use the runtime, diagnostics, timers and scale normally.

Table 46

Module

Support in Neutron AppEngine 1.0.0

Chapter

TCP

Implemented; features.tcp=true

RS-232 / RS-485

Implemented; features.serial=true

MQTT

Implemented; features.mqtt=true

HTTP / REST

Implemented; features.http=true

WebSocket

Implemented; features.websocket=true

Uploading an application through MQTT, HTTP or BLE is a management operation. It does not enable that protocol in user code. See Installation and APP protocol for management procedures.

13. TCP communication

configuredMode: 0 disabled, 1 server, 2 client, 3 both. The example value 1 is illustrative. maxLineBytes is the maximum configurable limit; the parser defaults to 1024 bytes.

The TCP module configures the existing server and client, claims their streams for a custom protocol, sends data and reports connection events. Modes: disabled, server, client, both. In both mode there is one server with one active peer and one outbound client connection. The API does not open arbitrary numbers of sockets and supports neither TLS nor DNS names; client.host must be IPv4. All functions and events in this chapter are available from Neutron AppEngine 1.0.0.

Before network configuration or claiming, disable the system weighing protocol on I_TCP and TCP–MQTT and TCP–RS-232/RS-485 bridges; otherwise RESOURCE_IN_USE. Network configuration and claiming are separate: configure saves and applies settings; claim redirects data to the application. After configure succeeds, use await tcp.claim().

13.1 tcp.configure()

Available since: Neutron AppEngine 1.0.0
const status = await tcp.configure(options);
Purpose. Configure TCP roles, network parameters and text-line framing.
Description. Omitted fields remain unchanged. Network settings are saved persistently through existing module attributes and apply without restarting the device. A changed role reinitializes while the other retains its connection. Identical values do not interrupt healthy connections. exclusive changes affect new connections without disconnecting the current peer. The Promise confirms application of settings, not connection to a remote system. Without a network, settings remain saved and the role stays in waitingNetwork. Monitor state/status for connection failures. Local line settings apply after success and discard partial lines. Supplying only delimiter/maxLineBytes applies them immediately for compatibility but still returns a Promise.

Parameters

Table 47

Parameter

Type / requirement

Description

options

object / required

Object with optional fields; unknown fields are rejected.

options.mode

string / optional

disabled, server, client or both. CTY: 0, 1, 2, 3. Disabled stops both roles and releases ownership.

options.server

object / optional

Server configuration: port and exclusive.

options.server.port

integer / optional

1–65535; existing attribute S0C. S0P configures a serial port, not TCP.

options.server.exclusive

boolean / optional

S0M: true=1, false=0. True rejects new peers while the current peer is connected; false permits replacement by a new peer.

options.client

object / optional

Outbound connection configuration: host and port.

options.client.host

string / optional

Remote server IPv4 address, for example 192.168.50.100. SIP attribute; no leading zeros in octets. 0.0.0.0 and 255.255.255.255 are prohibited.

options.client.port

integer / optional

1–65535; SPO attribute.

options.delimiter

string / default CRLF

1–8 ASCII bytes. Applies only to the current application's parser; not saved to attributes.

options.maxLineBytes

integer / default 1024

1–4096 content bytes excluding the delimiter. Current application only.

Result

Promise<object> with a tcp.status() snapshot. Active-role settings must be complete even when changing only part of the object. A partial update suffices with an existing valid configuration. SMD changes through BLE, MQTT, HTTP or device.settings.write use the same application mechanism.

Errors and special considerations

INVALID_ARGUMENT for invalid or incomplete active settings; JavaScript argument validation throws synchronously. Network requests may reject with RESOURCE_IN_USE, BUSY, WRITE_FAILED, CONFIGURE_FAILED or OUT_OF_MEMORY. Some settings may already be saved after a write failure; server startup failures retain settings and retry startup. Check status and correct the cause. CONFIG_CHANGED interrupts pending writes for the changed role. An oversized line raises MESSAGE_TOO_LARGE before the line callback and stops the application; try/catch inside that callback cannot catch it.

Example

async function start() {
    await tcp.configure({
        mode: "server", server: { port: 5000, exclusive: true },
        delimiter: "\r\n", maxLineBytes: 512
    });
    await tcp.claim();
    console.info(JSON.stringify(tcp.status()));
}
start().catch(error => { console.error(error.code, error.message); app.stop(); });
// Alternative: outbound connection or both roles.
async function configureClient() {
    await tcp.configure({mode: "client", client: {host: "192.168.50.100", port: 5000}});
    await tcp.claim();
}
// For both roles use mode: "both" and supply server and client.
// The example does not call configureClient() to avoid automatic configuration changes.

13.2 tcp.claim()

Available since: Neutron AppEngine 1.0.0
const result = await tcp.claim();
Purpose. Claim the existing TCP channel for a custom protocol.
Description. Requests transfer of existing TCP streams to the user application. Register callbacks before claiming. The operation does not guarantee that a remote peer is connected.

Parameters

No parameters.

Result

Promise<string>, "claimed" on success. Data events and sending become available when connected. Diagnostic connection/state events are available without claiming; register listeners before configure/claim.

Errors and special considerations

NOT_CONFIGURED for disabled/invalid TCP mode, RESOURCE_IN_USE for system-protocol or bridge conflicts; also BUSY and OUT_OF_MEMORY.

Example

async function start() {
    tcp.configure({ delimiter: "\r\n", maxLineBytes: 512 });
    tcp.on("line", event => console.log(event.connectionId, event.line));
    await tcp.claim();
    console.info("TCP protocol ready; waiting for connection");
}
start().catch(error => { console.error(error.code, error.message); app.stop(); });

13.3 tcp.release()

Available since: Neutron AppEngine 1.0.0
const result = await tcp.release();
Purpose. Return the claimed TCP interface to firmware.
Description. Closes claimed server/client connections, releases ownership and discards partial lines. JavaScript listeners and timers remain. The configured service remains available; the system client may reconnect.

Parameters

No parameters.

Result

Promise<string>, "released" on success. The application keeps running.

Errors and special considerations

Shared errors BUSY and OUT_OF_MEMORY. Cancel sending timers and handle pending writes before release.

Example

async function releaseTcp() {
    try { console.info(await tcp.release()); }
    catch (error) { console.warn(error.code, error.message); }
}
releaseTcp();

13.4 tcp.write()

Available since: Neutron AppEngine 1.0.0
const bytesWritten = await tcp.write(data, { connectionId });
Purpose. Send text or binary data over a claimed connection.
Description. Encodes strings as UTF-8 and sends Uint8Array as bytes. Adds no CRLF or other delimiter. Sending is asynchronous; submitted writes on one connection retain order, but asynchronous user logic can change submission order.

Parameters

Table 48

Parameter

Type / requirement

Description

data

string or Uint8Array / required

At most 4096 bytes per call. String limits apply after UTF-8 encoding.

options

object / optional, default {}

Sending options.

options.connectionId

integer / optional

0 or omitted: select the only connected TCP role. With multiple connected roles, use the ID from the event; range 0–4,294,967,295.

Result

Promise<number> with bytes accepted for TCP transmission. Does not confirm remote receipt or processing. Define acknowledgements in your protocol if required.

Errors and special considerations

Rejects with INVALID_ARGUMENT, MESSAGE_TOO_LARGE, NOT_OWNER, NOT_CONNECTED, CONFIG_CHANGED, BUSY, OUT_OF_MEMORY or TIMEOUT. Write wait limit is approximately 3 s. Some data may already have been sent after an error; do not blindly retry non-idempotent commands. An active write error/timeout may close the connection. Incorrect JavaScript argument use can also throw TypeError.

Example

tcp.on("line", async event => {
    try {
        const n = await tcp.write("OK\r\n", { connectionId: event.connectionId });
        console.debug("Bytes sent:", n);
    } catch (error) {
        console.warn("Sending:", error.code, error.message);
    }
});

13.5 tcp.on()

Available since: Neutron AppEngine 1.0.0
tcp.on(eventName, callback);
Purpose. Register a TCP event listener.
Description. Invokes the callback for matching events until off or application termination. The same function can register repeatedly; every registration counts toward the limit.

Parameters

Table 49

Parameter

Type / requirement

Description

eventName

string / required

Only "data", "line", "connection" or "state".

callback

function / required

Function receiving one event object. Retain the same reference for off.

Result

The tcp object, allowing chained registration.

Errors and special considerations

Synchronous INVALID_ARGUMENT for an unknown event or non-function. At most 32 on/once listeners combined; excess raises QUOTA_EXCEEDED. An unhandled callback exception or Promise rejection stops the application. off has no effect for an absent registration.

Example

function receive(event) { console.log(event.line); }
tcp.on("line", receive);

13.6 tcp.once()

Available since: Neutron AppEngine 1.0.0
tcp.once(eventName, callback);
Purpose. Register a one-time listener.
Description. Removes the listener before invoking it for the first matching event. Remains registered if no event arrives.

Parameters

Table 50

Parameter

Type / requirement

Description

eventName

string / required

Only "data", "line", "connection" or "state".

callback

function / required

Function receiving one event object. Retain the same reference for off.

Result

The tcp object, allowing chained registration.

Errors and special considerations

Synchronous INVALID_ARGUMENT for an unknown event or non-function. At most 32 on/once listeners combined; excess raises QUOTA_EXCEEDED. An unhandled callback exception or Promise rejection stops the application. off has no effect for an absent registration.

Example

tcp.once("connection", event => {
    console.info("Prva sprememba povezave", event.connectionId, event.connected);
});

13.7 tcp.off()

Available since: Neutron AppEngine 1.0.0
tcp.off(eventName, callback);
Purpose. Remove a listener.
Description. Removes all registrations of the same callback reference for the selected event. Does not interrupt an async callback already started. Do not pass a new anonymous function to remove an existing listener.

Parameters

Table 51

Parameter

Type / requirement

Description

eventName

string / required

Only "data", "line", "connection" or "state".

callback

function / required

Function receiving one event object. Retain the same reference for off.

Result

The tcp object, allowing chained registration.

Errors and special considerations

Synchronous INVALID_ARGUMENT for an unknown event or non-function. At most 32 on/once listeners combined; excess raises QUOTA_EXCEEDED. An unhandled callback exception or Promise rejection stops the application. off has no effect for an absent registration.

Example

function receive(event) { console.log(event.line); }
tcp.on("line", receive);
tcp.off("line", receive);

13.8 TCP event structure

Table 52

Event

Fields

Meaning

data

{ connectionId, data: Uint8Array }

Raw TCP stream chunk. One event is not necessarily one command or network packet.

line

{ connectionId, line: string }

Complete UTF-8 decoded line without the delimiter. Empty lines are allowed; whitespace is not trimmed automatically.

connection

{ connectionId, connected: boolean, role: "server" | "client", remoteAddress, remotePort, reason, timeMs }

Connection established or lost while the application runs, independently for each role. connectionId identifies the session; use a new ID after reconnecting.

connection.reason: CONNECTED on success, CONFIG_CHANGED after address/port/role changes, REPLACED when a server peer is replaced, NETWORK_DOWN for network service loss, CONNECTION_LOST for detected connection loss, DISCONNECTED for normal closure, APP_STOPPED for release after application termination, RESOURCE_IN_USE for conflicts. Events after application termination are not delivered. timeMs is monotonic device time in milliseconds, not a date or connection duration. A server peer's remote port is usually ephemeral, not the server's listening port.

state contains role, state, connected, connectionId, port, revision, error and timeMs plus role properties from tcp.status(). Server states: disabled, waitingNetwork, listening, error. Client states: disabled, waitingNetwork, connecting, reconnecting, connected, error. Conflict-driven release may emit {role:"all",state:"released",reason:"RESOURCE_IN_USE"}. Client connection attempts do not block the application or measurements; each lasts up to approximately 3 s, with another starting approximately 5 s after failure or detected disconnection. Server startup failure retries approximately every 5 s. Physical disconnection detection is not immediate; it depends on traffic and connection monitoring.

tcp.on("state", event => console.info("TCP state", JSON.stringify(event)));
tcp.on("connection", event => {
    console.info(event.role, event.connected, event.connectionId,
        event.remoteAddress, event.remotePort, event.reason, event.timeMs);
});
Registration does not replay event history. Claiming may notify you of an already established connection. Always reply using event.connectionId; never persist it or invent IDs.
TCP is a stream. WEIGHT?\r\n can arrive in several chunks, and several commands in one chunk. The parser retains partial lines per connection, assembling partial UTF-8 characters before decoding line events. Delimiters and incomplete lines are discarded on disconnection.

With a line listener, lines are prepared from a stream chunk first, then data fires, followed by individual line callbacks. Registering both gives two views of the same data; do not process commands twice. Without a line listener, binary data is not accumulated in a line buffer. Binary protocols must implement their own length limits and message assembly.

tcp.on("data", async event => {
    // Binary echo example; adds no terminators.
    try { await tcp.write(event.data, { connectionId: event.connectionId }); }
    catch (error) { console.warn(error.code, error.message); }
});

13.9 TCP module errors

Table 53

Code

Meaning for TCP

NOT_CONFIGURED

TCP is not configured for client/server operation.

RESOURCE_IN_USE

The system TCP weighing protocol or a bridge conflicts with claiming.

NOT_OWNER

The application does not own TCP or a routing conflict has arisen.

NOT_CONNECTED

The requested TCP session is no longer connected.

MESSAGE_TOO_LARGE

Write exceeds 4096 bytes or received line is too long. An internal line error stops the application.

13.10 TCP module limits

Table 54

Vir

Limit

TCP message

At most 4096 bytes per write; received streams may be split into smaller chunks.

Lines

Default 1024; configurable 1–4096 bytes excluding the delimiter; ASCII delimiter length 1–8 bytes.

Listeners

At most 32 on/once registrations combined across data, line, connection and state.

13.11 Custom TCP protocol with CONT / CCONT

Standalone example for a configured TCP server or client without conflicting system routing. Each line ends with actual CR LF bytes. External tools must send those bytes, not four literal backslash-r-backslash-n characters. In JavaScript source, "\r\n" represents the correct terminator bytes.

Table 55

Received command + CRLF

Response + CRLF

WEIGHT?

net,gross,unit or ERR,NO_MEASUREMENT

CONT

OK; then one measurement per second for the same connection. Repeating does not create an extra interval.

CCONT

OK; cancels future periodic sends on this connection. A write already started may complete.

TARE / ZERO / CLEAR_TARE

OK after a confirmed operation or ERR,&lt;code&gt;.

PRESET_TARE 2.5

Sets tare in the currently configured unit; returns OK or ERR,&lt;code&gt;.

Other command

ERR,UNKNOWN_COMMAND

// Disable system TCP protocol and RS-232/RS-485/MQTT bridges.
// On startup this example configures and saves a TCP server on port 5000.
// CONT starts sending each second; CCONT stops it for the same connection.
const streams = new Map();

function weightReply() {
    const m = scale.read();
    return m.available ? m.net + "," + m.gross + "," + m.unit : "ERR,NO_MEASUREMENT";
}

function stopStream(connectionId) {
    const stream = streams.get(connectionId);
    if (!stream) return;
    clearInterval(stream.intervalId);
    streams.delete(connectionId);
}

function startStream(connectionId) {
    if (streams.has(connectionId)) return;
    const stream = { intervalId: 0, sending: false };
    stream.intervalId = setInterval(async () => {
        if (stream.sending) return;
        stream.sending = true;
        try {
            await tcp.write(weightReply() + "\r\n", { connectionId });
        } catch (error) {
            stopStream(connectionId);
            console.warn("Continuous send stopped:", error.code, error.message);
        } finally {
            stream.sending = false;
        }
    }, 1000);
    streams.set(connectionId, stream);
}

tcp.configure({ delimiter: "\r\n", maxLineBytes: 512 });

tcp.on("connection", event => {
    if (!event.connected) stopStream(event.connectionId);
    console.info("TCP", event.connectionId, event.connected ? "connected" : "disconnected");
});

tcp.on("line", async event => {
    let reply;
    try {
        switch (event.line.trim()) {
        case "WEIGHT?": {
            reply = weightReply();
            break;
        }
        case "TARE":
            await scale.tare(); reply = "OK"; break;
        case "ZERO":
            await scale.zero(); reply = "OK"; break;
        case "CLEAR_TARE":
            await scale.clearTare(); reply = "OK"; break;
        case "CONT":
            startStream(event.connectionId);
            reply = "OK";
            break;
        case "CCONT":
            stopStream(event.connectionId);
            reply = "OK";
            break;
        default:
            if (event.line.startsWith("PRESET_TARE ")) {
                await scale.setPresetTare(Number(event.line.substring(12)));
                reply = "OK";
            } else {
                reply = await scale.cmd(event.line.trim());
            }
        }
    } catch (error) {
        reply = "ERR," + (error.code || "FAILED");
    }
    try {
        await tcp.write(reply + "\r\n", { connectionId: event.connectionId });
    } catch (error) {
        console.warn("Reply failed:", error.code, error.message);
    }
});

async function start() {
    await tcp.configure({mode: "server", server: {port: 5000, exclusive: true}});
    await tcp.claim();
    console.info("Custom TCP scale protocol ready");


}

start().catch(error => {
    console.error(error.code || error.name, error.message);
    app.stop();
});

The connection listener removes the interval on disconnection; periodic write failure also stops it. A sending flag prevents overlapping periodic writes per connection. The example implements no persistent log, remote-processing acknowledgement or request IDs. Add bounded IDs, responses and retry rules when needed.

13.12 TCP shutdown and concurrency

app.stop() closes claimed TCP connections and releases ownership. The configured server remains available and the client may reconnect under system logic. Use tcp.release() to return TCP without stopping the application. Multiple received commands can overlap asynchronous processing; for strict sequencing, have the client await a response or implement a bounded queue. clearInterval does not cancel a write already started.

13.13 Testing a TCP application

Table 56

Test

Expected result

TCP command split across receives

The line callback fires only after the complete delimiter.

CONT twice, then CCONT twice

One interval per connection; repeated cancellation is harmless.

Disconnect/reconnect

Old intervals and IDs are not reused; the new session is independent.

Slow/failed TCP write

No overlapping periodic work or unbounded queue.

13.14 tcp.status()

Available since: Neutron AppEngine 1.0.0
const status = tcp.status();
Purpose. Read current configuration and state of both TCP roles.
Description. Synchronous snapshot from the latest service cycle. Opens no connections, claims no interface and reads no stream data. pending means saved settings await application in the next service cycle. Connection state continues changing after configure; use connection/state events to continue once connected.

Parameters

No parameters.

Result

Object: mode (disabled/server/client/both), configuredMode (0/1/2/3), claimed, pending, server and client. Both roles contain state, connected, connectionId (0 if disconnected), port, revision and error. Server additionally includes listening, exclusive, remoteAddress and remotePort; client includes host, remoteAddress and remotePort. Empty error means no recorded error. revision changes with endpoint/role changes; it is not a received-data counter. This informational snapshot may change immediately after reading.

Errors and special considerations

No network request. A connected snapshot does not guarantee a later write will succeed; always handle write rejection.

Example

const status = tcp.status();
console.info(status.mode, status.claimed, status.server.state, status.client.state);
console.info(JSON.stringify(status));

Configuration and basic WEIGHT? protocol example for both roles: choose the desired mode in configuration and adjust address/port. Replies use the received event's connectionId, so they work with both roles connected.

// Neutron AppEngine 1.0.0. Disable system TCP protocol and TCP/MQTT/serial bridges.
// Settings persist. Adjust the object below for client/both.
const configuration = {
    mode: "server",
    server: { port: 5000, exclusive: true },
    // mode: "client", client: { host: "192.168.50.100", port: 5000 },
    delimiter: "\r\n",
    maxLineBytes: 512
};

tcp.on("state", event => console.info("TCP state", JSON.stringify(event)));
tcp.on("connection", event => {
    console.info("TCP", event.role, event.connected ? "connected" : "disconnected",
        event.remoteAddress, event.remotePort, event.connectionId, event.reason);
});
tcp.on("line", async event => {
    try {
        const m = scale.read();
        const reply = event.line.trim() === "WEIGHT?"
            ? (m.available ? m.net + "," + m.gross + "," + m.unit : "ERR,NO_MEASUREMENT")
            : "ERR,UNKNOWN_COMMAND";
        await tcp.write(reply + "\r\n", { connectionId: event.connectionId });
    } catch (error) {
        console.warn("TCP reply", error.code, error.message);
    }
});

async function start() {
    console.info("TCP configured", JSON.stringify(await tcp.configure(configuration)));
    await tcp.claim();
    console.info("TCP ready", JSON.stringify(tcp.status()));
}
start().catch(error => {
    console.error(error.code, error.message);
    app.stop();
});

14. RS-232 / RS-485

A port is available to the application only when its system function is Disabled: S0E=0 for RS-232 or S1E=0 for RS-485. It must not be assigned to a system weighing protocol, Modbus, debug output or forwarding. claim() does not automatically disable these functions.

The serial module provides two independent objects: serial.rs232 and serial.rs485, with the same API. An application can claim either or both ports. No other communication module is required. All functions and events in this chapter are available from Neutron AppEngine 1.0.0.

const port = serial.rs232; // or serial.rs485

14.1 port.claim()

Available since: Neutron AppEngine 1.0.0
const result = await port.claim();
Purpose. Exclusively claim the selected serial port.
Description. Checks that the port is Disabled and free, then prepares it using stored physical settings. Waits for successful initialization. Repeating a successful claim is allowed without reinitializing unchanged settings.

Parameters

No parameters.

Result

Promise<string>, "claimed" on success. Register listeners before claiming if needed. Remote device presence is not checked.

Errors and special considerations

RESOURCE_IN_USE for an enabled system function or other conflict; BUSY for concurrent control operations; RECONFIGURE_FAILED, TIMEOUT or OUT_OF_MEMORY. An incorrectly configured port is not silently claimed.

Example

async function start() {
    await serial.rs232.claim();
    console.info("RS-232 prevzet");
}
start().catch(error => console.error(error.code, error.message));

14.2 port.configure()

Available since: Neutron AppEngine 1.0.0
const result = await port.configure(options);
Purpose. Configure baud rate, character format and local message parsing.
Description. Asynchronous, allowed after claim(). Maps physical parameters to existing SMD settings, validates and saves persistently. Reinitializes the port once for the whole request; the Promise resolves after application. Omitted settings stay unchanged. Reapplying identical successfully applied values avoids unnecessary reinitialization.

Parameters

Table 57

Parameter

Type / requirement

Description

options

object / required

Object with the optional fields below. Unknown fields are rejected.

baudRate

integer / optional

300–1,000,000 bit/s. Maps to S0B or S1B.

dataBits

integer / optional

7 or 8. S0I/S1I mapping: 0 means 7 bits, 1 means 8 bits.

stopBits

integer / optional

1 or 2. Maps to S0S/S1S.

parity

string / optional

"none", "even" or "odd". S0P/S1P mapping: 0, 1 or 2.

delimiter

string / optional, default CRLF

1–8 ASCII characters, only for line-event assembly in the current application.

maxLineBytes

integer / optional, default 1024

1–4096 line-content bytes excluding the delimiter. Current application only.

Result

Promise<string>, "configured" on success. Physical settings persist after release(), Stop and restart. Delimiter and maxLineBytes are not saved in SMD; they apply to the current JavaScript parser.

Errors and special considerations

INVALID_ARGUMENT, NOT_OWNER, RESOURCE_IN_USE, BUSY, SETTINGS_FAILED, RECONFIGURE_FAILED, CONFIG_CHANGED, TIMEOUT or OUT_OF_MEMORY. A save failure may leave some physical settings saved; an application failure does not mean settings were not saved. Correct the cause and retry configuration/claiming. Local parser configuration changes only after success. If another channel changes requested physical settings before confirmation, the call rejects with CONFIG_CHANGED.

Example

async function configurePort() {
    const port = serial.rs485;
    await port.claim();
    await port.configure({
        baudRate: 19200, dataBits: 8, parity: "even", stopBits: 1,
        delimiter: "\r\n", maxLineBytes: 512
    });
    console.info("Nastavitve uveljavljene");
}
configurePort().catch(error => console.warn(error.code, error.message));

14.3 Settings changes without restart

The same application path handles SMD requests from all management channels. Changing baud rate, data bits, stop bits, parity or port function requires no Neutron restart. System terminators, terminator-appending settings, RS-485 address and related port assignments are also refreshed. The other port reinitializes only if affected.

During transition, new writes are temporarily rejected or held. Previously submitted bytes are drained within a bounded deadline; incomplete receive frames are discarded. Old weighing requests, continuous system output and affected-port sessions end. Baud-rate or format changes can lose data, so perform them during agreed communication downtime. Failure to finish transmission or open the new configuration reports RECONFIGURE_FAILED.

If external SMD assigns another system function or causes a conflict during JavaScript ownership, the claim is revoked. The application receives state with reason="RESOURCE_IN_USE" and claimed=false; new writes return NOT_OWNER. Permitted physical-setting changes retain ownership and emit RECONFIGURED. Partial JavaScript lines are discarded; the configured JavaScript delimiter remains.

Table 58

Checking through RMD

Meaning

S0APPLY / S1APPLY

PENDING: awaiting application; OK: configuration applied; ERROR: application failed.

S0JS / S1JS

1 means claimed by the application; 0 means no JavaScript claim.

S0REV / S1REV

Applied port-state change counter; not a persistent session ID.

S0STATE / S1STATE

Latest state: READY, DISABLED, CLAIMED, RECONFIGURED, RELEASED, RESOURCE_IN_USE or RECONFIGURE_FAILED.

A normal SMD response confirms saving; physical application follows in the next device processing cycle. For external confirmation, use RMD APPLY fields or debug logs. port.configure() already waits for application. These RMD fields are diagnostic, not writable SMD settings. Repeating identical SMD after failure retries application; after success, identical values do not reopen the port.

14.4 port.write()

Available since: Neutron AppEngine 1.0.0
const bytes = await port.write(data, { timeoutMs });
Purpose. Asynchronously send text or binary bytes.
Description. Encodes strings as UTF-8; sends Uint8Array unchanged. Adds no terminator, RS-485 address or checksum. Writes on one port follow request order; their Promises do not confirm remote processing.

Parameters

Table 59

Parameter

Type / requirement

Description

data

string or Uint8Array / required

At most 4096 bytes after UTF-8 encoding; empty writes are allowed.

options

object / optional, default {}

Wait options.

options.timeoutMs

integer / optional

1–180000 ms. The default is calculated from length and baud rate with a margin and minimum 3 s.

Result

Promise<number> with bytes accepted for transmission. Use drain() to wait for physical transmission completion.

Errors and special considerations

INVALID_ARGUMENT, MESSAGE_TOO_LARGE, NOT_OWNER, BUSY, PORT_UNAVAILABLE, CONFIG_CHANGED, TIMEOUT or OUT_OF_MEMORY. Some bytes may already be sent after interruption or timeout. CONFIG_CHANGED means configuration changed while waiting; remaining old-request bytes are not sent under new settings.

Example

async function send() {
    await serial.rs232.write("WEIGHT?\r\n");
    await serial.rs232.write(new Uint8Array([0, 1, 255]));
}
send().catch(error => console.warn(error.code, error.message));

14.5 port.drain()

Available since: Neutron AppEngine 1.0.0
await port.drain({ timeoutMs });
Purpose. Wait for physical transmission completion.
Description. Waits behind earlier writes on the same port, then checks that pending bytes have been transmitted. The runtime processes other events while waiting.

Parameters

Table 60

Parameter

Type / requirement

Description

options

object / optional, default {}

Wait options.

options.timeoutMs

integer / optional, default 6000

1–60000 ms.

Result

Promise<undefined>. Does not wait for a remote reply or confirm that an RS-485 bus used by other devices is free.

Errors and special considerations

INVALID_ARGUMENT, NOT_OWNER, BUSY, PORT_UNAVAILABLE, CONFIG_CHANGED, TIMEOUT or OUT_OF_MEMORY. Set a suitable communication deadline; expiry does not undo transmitted bytes.

Example

async function sendAndWait() {
    await serial.rs485.write("READ\r\n");
    await serial.rs485.drain({ timeoutMs: 5000 });
}
sendAndWait().catch(error => console.warn(error.code, error.message));

14.6 port.release()

Available since: Neutron AppEngine 1.0.0
const result = await port.release();
Purpose. Release the selected port's application claim.
Description. Stops new application writes, completes the transition and releases ownership. A port still system-Disabled with no other use closes. Persistently stored physical settings remain. Does not disable a system function that has since taken over the port.

Parameters

No parameters.

Result

Promise<string>, "released" on success. Repeating is allowed. Partial local reception is discarded; registered callbacks and timers remain.

Errors and special considerations

BUSY, RECONFIGURE_FAILED, TIMEOUT or OUT_OF_MEMORY. Cancel sending timers before release. Bytes already transmitted cannot be withdrawn. Application Stop automatically releases both its ports.

Example

async function releasePort() {
    console.info(await serial.rs232.release());
}
releasePort().catch(error => console.warn(error.code, error.message));

14.7 port.on()

Available since: Neutron AppEngine 1.0.0
port.on(eventName, callback);
Purpose. Register a serial event listener.
Description. Events belong to the selected port. once removes registration before invoking the callback. off requires the same function reference and does not interrupt an async callback already started.

Parameters

Table 61

Parameter

Type / requirement

Description

eventName

string / required

"data", "line" or "state".

callback

function / required

Function receiving one event object.

Result

The selected port object; listener registration can be chained.

Errors and special considerations

INVALID_ARGUMENT for an invalid event or callback; QUOTA_EXCEEDED above 32 listeners per port. Unhandled callback exceptions or rejections stop the application. off has no effect on an absent registration.

Example

function receive(event) { console.info(event.line); }
serial.rs232.on("line", receive);

14.8 port.once()

Available since: Neutron AppEngine 1.0.0
port.once(eventName, callback);
Purpose. Listen only for the first matching event.
Description. Events belong to the selected port. once removes registration before invoking the callback. off requires the same function reference and does not interrupt an async callback already started.

Parameters

Table 62

Parameter

Type / requirement

Description

eventName

string / required

"data", "line" or "state".

callback

function / required

Function receiving one event object.

Result

The selected port object; listener registration can be chained.

Errors and special considerations

INVALID_ARGUMENT for an invalid event or callback; QUOTA_EXCEEDED above 32 listeners per port. Unhandled callback exceptions or rejections stop the application. off has no effect on an absent registration.

Example

function receive(event) { console.info(event.line); }
serial.rs232.once("line", receive);

14.9 port.off()

Available since: Neutron AppEngine 1.0.0
port.off(eventName, callback);
Purpose. Remove a listener.
Description. Events belong to the selected port. once removes registration before invoking the callback. off requires the same function reference and does not interrupt an async callback already started.

Parameters

Table 63

Parameter

Type / requirement

Description

eventName

string / required

"data", "line" or "state".

callback

function / required

Function receiving one event object.

Result

The selected port object; listener registration can be chained.

Errors and special considerations

INVALID_ARGUMENT for an invalid event or callback; QUOTA_EXCEEDED above 32 listeners per port. Unhandled callback exceptions or rejections stop the application. off has no effect on an absent registration.

Example

function receive(event) { console.info(event.line); }
serial.rs232.off("line", receive);

14.10 Events and framing

Table 64

Event

Object

Description

data

{ data: Uint8Array }

Raw stream chunk; one event is not necessarily one protocol packet. NUL and other binary bytes are preserved.

line

{ line: string }

Assembled UTF-8 line without the delimiter; split message chunks are reassembled. Whitespace is not trimmed automatically.

state

{ port, claimed, reason, generation }

port is rs232 or rs485. claimed is boolean; reason identifies the transition; generation changes when port state is applied.

With a line listener, reception is assembled until the delimiter. A data listener on the same port receives another view of that stream; do not process a command twice. Oversized lines cause MESSAGE_TOO_LARGE before the line callback and may stop the application. Without line listeners, raw binary data is not accumulated in a line buffer. Events from before reinitialization are not reused as data under the new configuration.

Serial ports have no connection event: unplugged cables or powered-off devices generally cannot be reliably detected. state describes Neutron AppEngine ownership and settings, not physical connectivity. Verify reachability using your protocol's replies and timeouts. RS-485 applications implement addressing, CRC and shared-bus access rules; the system R4A filter is not applied to raw data during JavaScript ownership.

14.11 Complete RS-232 / RS-485 application

Set the chosen port's function to Disabled and remove other assignments. The application below claims it, persistently configures 19200/8N1 and replies to WEIGHT? with net,gross,unit. For the other port, change only the selected object. Configure the same character format on the remote device.

// Neutron AppEngine 1.0.0. Port must be Disabled, with no system protocol,
// Modbus, debug output or BLE forwarding.
async function start() {
    if (!app.capabilities().features.serial) throw new Error("Serial API is unsupported");
    const port = serial.rs232; // For RS-485 use serial.rs485.

    port.on("state", event => {
        console.info(event.port, event.reason, "claimed:", event.claimed);
        if (event.reason === "RESOURCE_IN_USE" || event.reason === "RECONFIGURE_FAILED") {
            app.stop();
        }
    });

    port.on("line", async event => {
        try {
            if (event.line.trim() === "WEIGHT?") {
                const m = scale.read();
                const reply = m.available ? m.net + "," + m.gross + "," + m.unit : "ERR,NO_MEASUREMENT";
                await port.write(reply + "\r\n");
            } else {
                await port.write("ERR,UNKNOWN_COMMAND\r\n");
            }
        } catch (error) {
            console.warn(error.code || error.name, error.message);
        }
    });

    await port.claim();
    // Physical settings persist through the same path as SMD.
    await port.configure({
        baudRate: 19200, dataBits: 8, parity: "none", stopBits: 1,
        delimiter: "\r\n", maxLineBytes: 512
    });
    console.info("Serial protocol ready");
}
start().catch(error => {
    console.error(error.code || error.name, error.message);
    app.stop();
});

14.12 Integration testing

Table 65

Test

Expected result

Claim with a system function enabled

RESOURCE_IN_USE; system use remains unchanged.

Configure through JavaScript and separately through SMD

Baud rate/parity/bits apply without restarting the device.

Change one port

The other port retains data and operation if unaffected.

External takeover during JavaScript operation

state RESOURCE_IN_USE, claimed=false; new writes return NOT_OWNER.

Binary bytes and a line split across receives

No NUL loss or duplicate delimiters; one correctly assembled line.

Reconfigure during partial reception or writing

Old partial lines are discarded; remaining old writes are not sent under new settings.

Release / Stop and claim again

No permanently occupied port; physical settings persist.

15. MQTT module

This module does not execute CSCP commands automatically. The application defines topic meanings, payload format and allowed commands. mqtt.connect() connects to the user broker, does not change the system Scale Monitor connection and requires no claim().
The mqtt module gives a user application one independent broker connection, separate from the system Scale Monitor connection. Both can operate simultaneously with different addresses, identities, credentials and subscriptions. The application does not claim system topics. Support: app.capabilities().features.mqtt === true. All functions, events and properties in this chapter are available from Neutron AppEngine 1.0.0.
Table 66

URL

Connection

Example

mqtt://

MQTT over TCP

mqtt://broker.example.com:1883

mqtts://

MQTT with TLS server authentication

mqtts://broker.example.com:8883

ws://

MQTT over WebSocket

ws://broker.example.com:8080/mqtt

wss://

MQTT over secure WebSocket

wss://broker.example.com/mqtt

Protocol: MQTT 3.1.1; API supports QoS 0 and 1. A WebSocket URL must point to the broker's MQTT listener, not an arbitrary WebSocket server. Network access, correct DNS settings and a reachable broker are prerequisites. The device clock must be correct for certificate validity checks.

Connection lifecycle

Register listeners first, then await mqtt.configure(...), await mqtt.connect() and await mqtt.subscribe(...). Configuration lasts for the current application run and is discarded at termination. Include it in startup for automatic application startup. Do not reconnect on every timer iteration.
After a successful connection, disconnection triggers automatic reconnection by default, with a bounded delay doubling up to 60 seconds. Successfully confirmed subscriptions are restored automatically, asynchronously. connect and completion of connect() confirm the connection, not completion of all restored subscriptions. Restoration failures emit error. Before the first successful connection, a failed attempt rejects; the application decides whether to retry.
Explicit disconnect(), authentication failure or event-queue overflow stops automatic reconnection. Ordinary network loss after a successful connection reconnects if enabled. Stopping or replacing the application closes only its own MQTT connection. Asynchronous orderly closure does not confirm delivery of final publications. The system connection continues independently.

mqtt.configure(options)

Available since: Neutron AppEngine 1.0.0
await mqtt.configure(options);
Purpose. Configure the broker and application identity.
Description. Validates and replaces settings only when the user client is neither connected, connecting nor awaiting reconnect. Await disconnect() before changing them. A successful new configuration clears remembered subscriptions; failure retains the previous configuration.

Parameters

Table 67

Parameter

Type / requirement

Description

options

object / required

Properties are listed below. Unknown properties are rejected; values must use the documented types.

Result

Promise<undefined>. Confirms configuration and loading of requested certificate profiles; does not connect.

Errors and special considerations

INVALID_ARGUMENT, MESSAGE_TOO_LARGE, BUSY, CERTIFICATE_NOT_FOUND, CERTIFICATE_TOO_LARGE, OUT_OF_MEMORY. Invalid PEM content may fail only during TLS connection.

Example

await mqtt.configure({
    url: "mqtts://broker.example.com:8883",
    clientId: "scale-01-app",
    username: "integrator", password: "replace-me",
    keepAlive: 60, cleanSession: true, reconnect: true,
    connectTimeoutMs: 10000, reconnectDelayMs: 1000
});
Table 68

options property

Type / default

Meaning and limits

url

string / required

Up to 512 UTF-8 bytes. One of the four schemes. No username/password in the URL, whitespace or # fragment. Include the correct ws/wss path, such as /mqtt.

clientId

string / automatic

Up to 64 UTF-8 bytes. If absent or empty, the device assigns a stable user-application identity. Two simultaneous connections to the same broker must not share a clientId.

username, password

string / none

At most 256 and 512 UTF-8 bytes respectively. Never log them to console; application code is not a secret vault.

keepAlive

integer / 60

Seconds, 5..3600.

cleanSession

boolean / true

false enables a persistent broker session for the same clientId. The application API still restores its confirmed subscriptions; broker-only subscriptions are not part of its local list.

reconnect

boolean / true

Automatic reconnection after losing an established connection. Does not repeat failed initial login or explicit disconnect().

connectTimeoutMs

integer / 10000

1000..60000 ms. Client connection and network-operation deadline.

reconnectDelayMs

integer / 1000

1000..60000 ms. Initial delay, doubling on repeated disconnections up to 60000 ms and resetting after success.

will

object / none

{topic, payload, qos?, retain?}. topic is a publication topic; payload is string. qos: 0 or 1, default 0; retain: boolean, default false. The broker publishes the will after unexpected disconnection under MQTT rules; do not rely on it after orderly closure.

tls

object / none

mqtts/wss only. Properties: caProfile, clientCertificateProfile, clientKeyProfile. See TLS below.

The complete options JSON must fit within 4096 UTF-8 bytes, including property names and escapes. Actual will.payload capacity is therefore below 4096 bytes. Configuration strings cannot contain NUL; use publish() for binary data. User-client settings are independent of system broker settings.

mqtt.connect(options?)

Available since: Neutron AppEngine 1.0.0
await mqtt.connect({ timeoutMs: 15000 });
Purpose. Connect to the configured broker.
Description. The Promise fulfills on successful broker connection acknowledgement. Already-connected calls succeed. A second simultaneous connection attempt rejects with BUSY.

Parameters

Table 69

Parameter

Type / requirement

Description

options.timeoutMs

integer / optional

1..60000 ms; defaults to configured connectTimeoutMs. Applies to the connection attempt; service-queue waiting and client shutdown may extend total time.

Result

Promise<undefined>. Connection information is also available in connect and status().

Errors and special considerations

NOT_CONFIGURED, BUSY, START_FAILED, AUTH_FAILED, CONNECTION_REFUSED, NOT_CONNECTED, TIMEOUT, CANCELLED. More detailed network/TLS causes may appear in error or status().lastError. Bound retries of failed initial attempts.

Example

try {
    await mqtt.connect({ timeoutMs: 20000 });
    console.info("Broker connected");
} catch (error) {
    console.error(error.code, error.message);
    app.stop();
}

mqtt.disconnect()

Available since: Neutron AppEngine 1.0.0
await mqtt.disconnect();
Purpose. Close the user connection cleanly and stop reconnection.
Description. Cancels pending connect, publish, subscribe and unsubscribe operations; handle their Promises. Configuration and confirmed subscriptions remain for the next connect in the same run; configure replaces them.

Parameters

No parameters.

Result

Promise<undefined> after client closure. Already-disconnected calls succeed.

Errors and special considerations

NOT_CONFIGURED before initial configuration. Interrupted operations receive CANCELLED. Does not undo publications already accepted by the broker. Sends no automatic business offline message; publish and confirm one before disconnect() if required.

Example

if (mqtt.status().connected) {
    await mqtt.publish("scale/status", "offline", { qos: 1, retain: true });
}
await mqtt.disconnect();

mqtt.status()

Available since: Neutron AppEngine 1.0.0
const status = mqtt.status();
Purpose. Return current user-connection status without waiting.
Description. Returns a copy of the latest state, not a guarantee of the next network operation's success. Reveals no username, password or certificates.

Parameters

No parameters.

Result

{configured:boolean, connected:boolean, state:string, reconnectAttempts:number, lastError:string}. state: unconfigured, disconnected, connecting, connected, reconnecting. reconnectAttempts counts automatic reconnection starts since the last configure. lastError is empty or the latest error code; successful connection clears it.

Errors and special considerations

Synchronous; does not connect. Network state can change between reading and the next operation.

Example

const status = mqtt.status();
console.info(status.state, status.connected, status.lastError);

mqtt.subscribe(topic, options?)

Available since: Neutron AppEngine 1.0.0
await mqtt.subscribe("factory/+/command", { qos: 1, timeoutMs: 10000 });
Purpose. Subscribe to a topic or topic filter.
Description. Waits for broker SUBACK; broker refusal is not success. Confirmed subscriptions are remembered for reconnect. Repeating a filter uses no extra slot; successful confirmation replaces requested QoS. The broker may grant lower QoS.

Parameters

Table 70

Parameter

Type / requirement

Description

topic

string / required

1..192 UTF-8 bytes. + must occupy a whole level, # the whole final level; for example factory/+/command or factory/#.

options.qos

integer / 0

0 or 1.

options.timeoutMs

integer / 10000

1..60000 ms for broker acknowledgement.

Result

Promise<undefined> after successful SUBACK. Incoming publications emit message.

Errors and special considerations

NOT_CONFIGURED, NOT_CONNECTED, SUBSCRIBE_FAILED, QUOTA_EXCEEDED, BUSY, TIMEOUT. At most 16 filters. Concurrent subscribe/unsubscribe for the same filter receives BUSY. Offline requests are not queued for later.

Example

await mqtt.subscribe("factory/scale-01/command", { qos: 1 });

mqtt.unsubscribe(topic, options?)

Available since: Neutron AppEngine 1.0.0
await mqtt.unsubscribe("factory/scale-01/command");
Purpose. Unsubscribe the exact filter and remove it from the reconnect list.
Description. Confirmed on UNSUBACK. Unknown filters may be unsubscribed. Does not remove already received messages or other overlapping subscriptions.

Parameters

Table 71

Parameter

Type / requirement

Description

topic

string / required

Exact filter to unsubscribe; up to 192 UTF-8 bytes.

options.timeoutMs

integer / 10000

1..60000 ms.

Result

Promise<undefined> after UNSUBACK.

Errors and special considerations

NOT_CONFIGURED, NOT_CONNECTED, BUSY, TIMEOUT, CANCELLED. To replace remembered filters while disconnected, use configure; it replaces the complete local list but does not guarantee removal of the old broker session.

Example

await mqtt.unsubscribe("factory/+/command", { timeoutMs: 5000 });

mqtt.publish(topic, payload, options?)

Available since: Neutron AppEngine 1.0.0
await mqtt.publish(topic, payload, { qos: 1, retain: false });
Purpose. Publish text or binary data.
Description. Sends strings as UTF-8 and Uint8Array as exact bytes; adds no CR, LF or NUL. Copies payload at call time. Sending starts from a separate communication task after request processing. QoS 0 confirms a successful transport write; QoS 1 waits for broker PUBACK. Neither confirms processing by the final subscriber.

Parameters

Table 72

Parameter

Type / requirement

Description

topic

string / required

1..192 UTF-8 bytes, without + or #.

payload

string | Uint8Array / required

0..4096 bytes after UTF-8 encoding; binary data may contain NUL.

options.qos

integer / 0

0 or 1; QoS 2 is unsupported.

options.retain

boolean / false

Retain the message on the broker. Empty payload with retain=true removes the topic's retained value.

options.timeoutMs

integer / 10000

1..60000 ms. QoS 1 PUBACK deadline; QoS 0 does not wait for the broker.

Result

Promise<undefined>; acknowledgement meaning depends on QoS.

Errors and special considerations

NOT_CONNECTED offline; no unbounded offline queue. BUSY for a full outbound queue (32768 bytes including protocol overhead) or pending-operation limit. MESSAGE_TOO_LARGE, INVALID_ARGUMENT, NETWORK_ERROR, TIMEOUT, CANCELLED. The broker may already have received a message after timeout/disconnection. QoS 1 may duplicate delivery; use request IDs and deduplication for business operations.

Example

const m = scale.read();
if (m.available && mqtt.status().connected) {
    await mqtt.publish("factory/scale-01/weight", JSON.stringify({
        net: m.net, gross: m.gross, unit: m.unit
    }), { qos: 1 });
}
await mqtt.publish("factory/scale-01/binary", new Uint8Array([0, 10, 255]));

mqtt.on() / mqtt.once() / mqtt.off()

Available since: Neutron AppEngine 1.0.0
mqtt.on(eventName, callback);
mqtt.once(eventName, callback);
mqtt.off(eventName, callback);
Purpose. Register or remove a user-broker event listener.
Description. Events execute sequentially. An async callback yields at await; use overlap protection when order matters. once removes registration before invocation. off removes all registrations of the same function for the selected event.

Parameters

Table 73

Parameter

Type / requirement

Description

eventName

string / required

connect, disconnect, message or error.

callback

function / required

Receives one object with fields listed below. Keep the same function reference for off.

Result

Returns mqtt for chaining. At most 32 listeners across all MQTT events.

Errors and special considerations

INVALID_ARGUMENT, QUOTA_EXCEEDED. error alone does not stop the application; an unhandled listener exception or rejected Promise does under runtime rules. Operation rejection and error are separate notifications with no guaranteed relative order.

Example

mqtt.on("message", async event => {
    try {
        if (event.topic !== "factory/scale-01/request" || event.retain) return;
        const request = JSON.parse(event.text);
        console.info(request.id, request.command);
    } catch (error) {
        console.warn(error.code || error.name, error.message);
    }
});
mqtt.on("error", error => console.warn(error.code, error.message));
Table 74

Event

Fields since Neutron AppEngine 1.0.0

Meaning

connect

connected: true, reconnected: boolean, sessionPresent: boolean

CONNACK accepted. reconnected indicates an earlier successful connection under the current configuration. sessionPresent is the broker's restored-session flag, not the locally confirmed subscription list.

disconnect

connected: false, reason: string

Loss of an established connection or explicit disconnect. Handle the Promise for a failed initial connect. No event is guaranteed at application termination.

message

topic: string, data: Uint8Array, text: string, qos: number, retain: boolean

Complete MQTT message, assembled from fragments first. text is a UTF-8 view; use data for arbitrary binary payloads. qos is the received message QoS (the API requests at most 1, but the broker may retain older subscriptions).

error

Error with code: string and message: string

Connection, TLS, subscription restoration, oversized-message or queue error. The application decides how to continue; inspect status() and outstanding operations.

TLS and certificate profiles

mqtts and wss verify server name and certificate trust. Without caProfile, built-in public-CA trust is used. Use a custom profile for private CAs. Disabling certificate verification is not part of the API. System-broker settings and certificates do not apply to user connections.

Table 75

tls field

Stored profile

Purpose

caProfile: "company-ca"

JCA_company-ca

Trusted CA PEM or CA chain.

clientCertificateProfile: "device-01"

JCC_device-01

Client certificate PEM for mutual TLS.

clientKeyProfile: "device-01"

JCK_device-01

Client private-key PEM; required together with the certificate. Password-encrypted keys are unsupported in this version.

Profile names contain 1..48 characters: A–Z, a–z, 0–9, _ or -. Each normalized PEM is at most 16384 bytes. An authorized integrator provisions profiles through the existing SMD certificate path, for example JCA_company-ca=<PEM>, with the complete PEM certificate as the value. This is neither a file path, public URL nor system MCA profile. An empty value deletes a profile under existing certificate rules. Applications load profiles during configure; changing stored profiles does not replace active-connection certificates. Disconnect, configure, then connect.
await mqtt.configure({
    url: "mqtts://mqtt.company.example:8883",
    clientId: "scale-01-app",
    tls: {
        caProfile: "company-ca",
        clientCertificateProfile: "device-01",
        clientKeyProfile: "device-01"
    }
});
await mqtt.connect();

Limits, errors and recovery

Table 76

Limit since Neutron AppEngine 1.0.0

Value / handling

Connections

One user connection, separate from the system Scale Monitor connection.

Payload

4096 bytes per sent or received message: the entire message, not each fragment.

Topic / subscriptions / listeners

192 UTF-8 bytes / 16 confirmed filters / 32 listeners.

Pending operations

At most 8 shared with other asynchronous runtime operations. MQTT outbound queue: 32768 bytes.

Rok

At most 60000 ms for connection or broker acknowledgement. Not a guarantee of an exact device response time.

Oversized incoming message

Entire message discarded; error MESSAGE_TOO_LARGE. Partial messages are not delivered.

Service queue overflow

EVENT_OVERFLOW closes the user connection and stops reconnect. The runtime has another bounded queue; its overflow stops the application.

Acknowledgement timeout

The pending operation rejects and reconnect follows configured rules. Other operations may receive NOT_CONNECTED. A late acknowledgement from an old connection never confirms a new request.

Disconnect during publication

Unconfirmed operations reject; the application decides whether to retry. Effects already performed are not undone.

Key codes: INVALID_ARGUMENT, MESSAGE_TOO_LARGE, NOT_CONFIGURED, NOT_CONNECTED, BUSY, QUOTA_EXCEEDED, OUT_OF_MEMORY, START_FAILED, AUTH_FAILED, CONNECTION_REFUSED, NETWORK_ERROR, TLS_ERROR, SUBSCRIBE_FAILED, CERTIFICATE_NOT_FOUND, CERTIFICATE_TOO_LARGE, TIMEOUT, CANCELLED, EVENT_OVERFLOW, INVALID_MESSAGE. Error messages are diagnostic; base program decisions on code. For TLS failures, check device time, server name, trust chain and required client certificate.

Complete example: publish weight and receive commands

Adjust brokerUrl, baseTopic and credentials before running. Each device needs its own clientId and topics. Send commands to /command without retain. The example publishes weight periodically, automatically restores confirmed subscriptions and does not repeat taring for retained commands. For systems retrying QoS 1 requests, add request IDs and a record of executed commands; retain alone does not prevent duplicate delivery.

// Set your broker address and a unique base topic for this device.
// Supports mqtt://, mqtts://, ws:// and wss://.
const brokerUrl = "mqtt://192.168.1.10:1883";
const baseTopic = "factory/scale-01";
let sending = false;
let commandBusy = false;

mqtt.on("error", error => console.warn(error.code, error.message));
mqtt.on("connect", event => console.info("MQTT connected; reconnected:", event.reconnected));
mqtt.on("disconnect", event => console.warn("MQTT disconnected:", event.reason));

mqtt.on("message", async event => {
    if (event.topic !== baseTopic + "/command") return;
    // Do not execute retained commands on every resubscription.
    if (event.retain || commandBusy) return;
    commandBusy = true;
    try {
        let reply;
        switch (event.text.trim()) {
        case "WEIGHT?": reply = JSON.stringify(scale.read()); break;
        case "TARE": await scale.tare(); reply = "OK"; break;
        case "ZERO": await scale.zero(); reply = "OK"; break;
        case "CLEAR_TARE": await scale.clearTare(); reply = "OK"; break;
        default: reply = "ERR,UNKNOWN_COMMAND";
        }
        await mqtt.publish(baseTopic + "/reply", reply, { qos: 1 });
    } catch (error) {
        console.warn("Command failed:", error.code || error.name, error.message);
    } finally {
        commandBusy = false;
    }
});

async function start() {
    if (!app.capabilities().features.mqtt) throw new Error("MQTT API unsupported");
    await mqtt.configure({
        url: brokerUrl,
        clientId: "scale-01-user-app", // Each device needs its own clientId.
        // username: "user", password: "password",
        keepAlive: 60, reconnect: true, reconnectDelayMs: 1000,
        will: { topic: baseTopic + "/status", payload: "offline", qos: 1, retain: true }
        // For a private CA: mqtts/wss in tls: { caProfile: "company-ca" }.
    });
    await mqtt.connect();
    await mqtt.subscribe(baseTopic + "/command", { qos: 1 });
    // The subscription restores automatically after disconnection.
    await mqtt.publish(baseTopic + "/status", "online", { qos: 1, retain: true });
    mqtt.on("connect", async () => {
        try { await mqtt.publish(baseTopic + "/status", "online", { qos: 1, retain: true }); }
        catch (error) { console.warn(error.code, error.message); }
    });
    setInterval(async () => {
        if (sending || !mqtt.status().connected) return;
        sending = true;
        try {
            const m = scale.read();
            if (m.available) await mqtt.publish(baseTopic + "/weight", JSON.stringify({ net: m.net, gross: m.gross, unit: m.unit }), { qos: 1 });
        } catch (error) {
            console.warn("Publish failed:", error.code, error.message);
        } finally {
            sending = false;
        }
    }, 1000);
}

start().catch(error => {
    console.error(error.code || error.name, error.message);
    app.stop();
});

Integration testing

Table 77

Test

Expected result

System connection and user broker simultaneously

Scale Monitor continues; user topics are handled only by the application.

Publish WEIGHT? to the selected /command

Measurement JSON arrives on /reply; /weight updates approximately every second.

Network loss and restoration

status becomes reconnecting, then connect with reconnected=true and automatic subscription restoration.

Incorrect password / CA / server name

Connect rejects; error/status provide diagnostics. Failed authentication does not loop without bounds.

Send 4096 binary bytes

All bytes, including NUL, remain unchanged. Topic does not count toward payload size.

Receive a message above 4096 bytes

MESSAGE_TOO_LARGE without a partial message event.

Application Stop

The user connection closes; the system connection remains active.

mqtt, mqtts, ws, wss

Test each URL against the appropriate broker listener; ws/wss require the correct path.

16. HTTP / REST client

Global fetch() connects applications to external REST APIs over HTTP or HTTPS. Support: app.capabilities().features.http. All functions, properties and options in this chapter are available from Neutron AppEngine 1.0.0. This is a documented subset of fetch, not a complete browser environment.

The device acts as an HTTP client. This API adds no custom REST routes to Neutron's internal HTTP server. Requests provide no automatic retries, persistent queue, automatic event transmission or response storage. The application defines call timing, data formats and failure handling.

fetch(url, options?)

Available since: Neutron AppEngine 1.0.0
const response = await fetch(url, options);
Purpose. Send a request to an external HTTP/HTTPS server and receive a bounded complete response.
Description. The Promise fulfills after receiving the entire body, not just initial headers. HTTP 400, 401, 404 and 500 are normal responses and do not reject. Connection, TLS, timeout and size failures reject. Network processing runs outside the JavaScript callback without blocking it while waiting.

Parameters

Table 78

Parameter

Type / requirement

Description

url

string / required

Absolute http:// or https:// URL, at most 512 ASCII bytes. Encode Unicode and whitespace in paths/query values; use encodeURIComponent for individual values. A # fragment is removed. URL credentials are prohibited.

options

object / optional

method, headers, body, timeoutMs, tls and redirect. Unknown options are rejected. Details follow below.

Result

Promise<Response>, described below. body and encoded options have separate limits; binary payloads are not JSON- or Base64-encoded.

Errors and special considerations

INVALID_ARGUMENT, MESSAGE_TOO_LARGE, HEADERS_TOO_LARGE, RESPONSE_TOO_LARGE, NETWORK_ERROR, TLS_ERROR, TIMEOUT, CANCELLED, INVALID_RESPONSE, INCOMPLETE_RESPONSE, UNSUPPORTED_ENCODING, CERTIFICATE_NOT_FOUND, CERTIFICATE_TOO_LARGE, OUT_OF_MEMORY, BUSY. After interruption/timeout the server may already have processed the request; retrying POST can duplicate its business effect.

Example

async function sendWeight() {
    const m = scale.read();
    const response = await fetch("https://api.example.com/measurements", {
        method: "POST",
        headers: { "Content-Type": "application/json", "Authorization": "Bearer replace-me" },
        body: JSON.stringify({ net: m.net, gross: m.gross, unit: m.unit }),
        timeoutMs: 10000
    });
    if (!response.ok) {
        console.warn("HTTP", response.status, await response.text());
        return;
    }
    if (response.status !== 204) console.info(await response.json());
}
sendWeight().catch(error => console.warn(error.code || error.name, error.message));
Table 79

Option since Neutron AppEngine 1.0.0

Type / default

Meaning

method

string / GET

GET, POST, PUT, PATCH, DELETE or HEAD. Converted to uppercase. Other methods are unsupported in this version.

headers

object / none

Custom header names and string values. Names are case-insensitive; duplicate names differing only in case are rejected. ASCII values only, without CR/LF or control characters other than tab.

body

string | Uint8Array | null / none

At most 4096 bytes after UTF-8 encoding. null means no body. GET and HEAD cannot have a body. Strings without explicit Content-Type receive text/plain;charset=UTF-8; for JSON use JSON.stringify and application/json. Uint8Array receives no automatic Content-Type.

timeoutMs

integer / 10000

1..60000 ms; a documented Neutron AppEngine extension, not a standard browser fetch option. Starts at call time and includes queue waiting and body transfer. Error delivery is not a real-time guarantee; underlying name resolution or connection calls may finish later.

tls

object / none

HTTPS only. caProfile and optionally the clientCertificateProfile/clientKeyProfile pair. See TLS.

redirect

string / manual

Only manual is supported. Returns 3xx responses so the application can inspect Location. No automatic following.

At most 32 supplied headers and 2048 bytes combined (names, values and separators); names up to 64 characters, values up to 1024. The client manages automatic protocol headers. Host, Content-Length, Connection, Transfer-Encoding, Accept-Encoding, Expect, Trailer, Upgrade, Proxy-Connection, TE and Keep-Alive cannot be set. Encoded request options have an additional combined 4096 UTF-8 byte limit.

Response: status and metadata

Available since: Neutron AppEngine 1.0.0
const response = await fetch("https://api.example.com/articles/ART-001");
Purpose. Inspect the HTTP result before converting its body.
Description. An object with read-only properties and methods for consuming the body once. Does not confirm business meaning of the status or validity of received JSON.

Parameters

No parameters.

Result

{status, statusText, ok, url, redirected, headers, bodyUsed, text(), json(), arrayBuffer()}. status is the HTTP code; ok means 200..299. url is the requested URL without a fragment; redirected is false; statusText is an empty string in this version.

Errors and special considerations

Handle fetch rejection separately from response.ok. Expect an empty body for 204 or HEAD; response.json() on an empty body throws SyntaxError. No streaming response.body, clone(), Blob, FormData, Request or global Response constructor.

Example

const response = await fetch("https://api.example.com/articles/ART-001");
if (response.status === 404) console.info("Article not found");
else if (!response.ok) console.warn("HTTP status:", response.status);
else console.info(await response.json());

response.text()

Available since: Neutron AppEngine 1.0.0
const text = await response.text();
Purpose. Convert the received body to UTF-8 text once.
Description. Removes an initial UTF-8 BOM. Performs no further network request; fetch already received the body. bodyUsed becomes true at the first body-consumption method call.

Parameters

No parameters.

Result

Promise<string>. Use arrayBuffer() for arbitrary binary data.

Errors and special considerations

Repeated reading throws TypeError with code=BODY_USED. Decodes UTF-8; other character sets are not automatically supported.

Example

const response = await fetch("https://api.example.com/status");
const text = await response.text();
console.info(response.status, text);

response.json()

Available since: Neutron AppEngine 1.0.0
const value = await response.json();
Purpose. Decode the UTF-8 body and run JSON.parse once.
Description. Returns an object, array or other valid JSON value. Content-Type does not change JSON.parse rules. Check status first if your API returns different error-body formats.

Parameters

No parameters.

Result

Promise<JSON value>. bodyUsed becomes true even if JSON parsing fails.

Errors and special considerations

SyntaxError for invalid/empty JSON; TypeError/BODY_USED for repeated reading. Store the result in a variable to reuse it.

Example

const response = await fetch("https://api.example.com/settings");
const settings = await response.json();
console.info(settings);
// Do not also call response.text() on the same response.

response.arrayBuffer()

Available since: Neutron AppEngine 1.0.0
const buffer = await response.arrayBuffer();
Purpose. Return received binary bytes once, without text conversion.
Description. Use Uint8Array to access individual bytes, including NUL. Store them or forward them to another supported module.

Parameters

No parameters.

Result

Promise<ArrayBuffer>, at most 4096 bytes.

Errors and special considerations

TypeError/BODY_USED on repeated reading. No automatic gzip or other content decompression.

Example

const response = await fetch("https://api.example.com/data.bin");
if (!response.ok) throw new Error("HTTP " + response.status);
const data = new Uint8Array(await response.arrayBuffer());
await storage.write("download.bin", data);

response.headers

Available since: Neutron AppEngine 1.0.0
const contentType = response.headers.get("Content-Type");
Purpose. Read response headers case-insensitively.
Description. Read-only object supporting get, has, entries, keys, values, forEach and iteration. Repeated header names are comma-joined; this is not an automatic cookie manager.

Parameters

Table 80

Parameter

Type / requirement

Description

name for get/has

string / required

Valid HTTP header name.

callback for forEach

function / required

Receives value, name and headers. An optional second argument sets thisArg.

Result

get returns string or null; has returns boolean; entries/keys/values return iterators. forEach returns no result. Iteration uses lowercase header names.

Errors and special considerations

INVALID_ARGUMENT for invalid header names or callbacks. No global Headers constructor or response set/append/delete methods. If the server exceeds 32 headers, 2048 combined bytes or supported name/value lengths, fetch rejects instead of silently truncating.

Example

const response = await fetch("https://api.example.com/status");
console.info(response.headers.get("Content-Type"));
for (const [name, value] of response.headers) console.info(name, value);

Authentication

Supply Bearer tokens, API keys or pre-encoded Basic values in headers. Do not place credentials in URLs. No automatic login, token refresh, HTTP Digest authentication or shared session with system connections. Cookies are not saved or sent automatically. This device client is not subject to browser CORS restrictions.

const response = await fetch("https://api.example.com/status", {
    headers: { "Authorization": "Bearer replace-me" }
});
// For example, Basic user:pass uses header "Authorization": "Basic dXNlcjpwYXNz".
// Basic/Base64 is not encryption: use HTTPS for credentials.

HTTPS and certificate profiles

HTTPS always verifies server name and certificate trust. Without caProfile, uses built-in public-CA trust. Use a custom profile for private CAs. The device clock must be correct for certificate validity checks. No insecure option or hostname-verification bypass.

Table 81

tls option

Stored profile

Purpose

caProfile: "company"

JHCA_company

Trusted CA PEM or CA chain.

clientCertificateProfile: "scale01"

JHCC_scale01

Client certificate for mutual TLS.

clientKeyProfile: "scale01"

JHCK_scale01

Private key; required together with the client certificate.

Profile names: 1..48 characters A–Z/a–z, 0–9, _ or -. Each PEM is at most 16384 bytes. Authorized integrators provision profiles through the existing SMD certificate path, for example JHCA_company=&lt;PEM&gt;. This is not an arbitrary file path. Profiles are separate from system MQTT and internal HTTP-server certificates and are loaded per request. Password-encrypted private keys are unsupported.

const response = await fetch("https://api.company.example/status", {
    tls: {
        caProfile: "company",
        clientCertificateProfile: "scale01",
        clientKeyProfile: "scale01"
    },
    timeoutMs: 15000
});
console.info(response.status);

Limits and execution

Table 82

Property since Neutron AppEngine 1.0.0

Handling

Execution

One active request and up to four queued. The shared runtime limit of eight pending asynchronous operations also applies.

Size

4096-byte request body and a separate 4096-byte response body limit. Oversized responses raise RESPONSE_TOO_LARGE; partial bodies are never returned as success.

Timeout

Default 10000 ms, maximum 60000 ms, including queue waiting. Slow incoming data does not reset the deadline. Actual error delivery time is not guaranteed in real time.

Connections

Connections are released after each request. No persistent HTTP session or automatic retry. HTTPS therefore establishes a new secure connection on each call.

Redirects

Always manual. 3xx remains a response; Location can be read. Authentication headers are not automatically forwarded to another server.

Body encoding

Requests identity. gzip/br and other encodings are unsupported; a nonempty encoded response causes UNSUPPORTED_ENCODING.

Application Stop

Queued requests from a previous run are discarded; active transfer is interrupted when stopping is detected or the underlying connection call finishes. This does not undo server effects already performed.

API subset

No AbortController/signal, streaming body, clone, Blob, FormData, URL/Request/Response/Headers constructors or automatic CORS/cookie environment.

Protect periodic calls against overlap. Use request IDs and an agreed server protocol for reliable business retries. Timeout or response loss does not prove the server has not processed POST/PUT/PATCH/DELETE.

Complete example: send weight

// Adjust the URL and, if required, Authorization for your REST server.
const endpoint = "https://api.example.com/measurements";
let sending = false;

async function sendWeight() {
    if (sending) return;
    const m = scale.read();
    if (!m.available) return;
    sending = true;
    try {
        const response = await fetch(endpoint, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
                // "Authorization": "Bearer replace-me"
            },
            body: JSON.stringify({ device: "scale-01", timeMs: m.timeMs, net: m.net, gross: m.gross, unit: m.unit }),
            timeoutMs: 10000
        });
        if (!response.ok) {
            console.warn("REST status:", response.status, await response.text());
            return;
        }
        console.info("REST status:", response.status);
        // If the API returns JSON: const result = await response.json();
        // 204 has no body. A body can be consumed only once.
    } catch (error) {
        console.warn(error.code || error.name, error.message);
    } finally {
        sending = false;
    }
}

if (!app.capabilities().features.http) {
    console.error("REST API is unavailable");
    app.stop();
} else {
    sendWeight();
    setInterval(sendWeight, 10000);
}

Integration testing

For local testing, the source package includes tools/rest-test-server.py and tools/examples/rest-self-test.js for the device. The server listens locally by default; explicitly use --host 0.0.0.0 for Neutron access and set the computer's IP in the test application. Optional --cert/--key enable HTTPS; --ca enables client-certificate validation. Certificate/profile provisioning remains a separate management procedure.

Table 83

Test

Expected result

GET/POST/PUT/PATCH/DELETE/HEAD

Correct request and status; HEAD has no body.

404 or 500

The Promise fulfills; response.ok is false.

302

Status and Location without an automatic new request.

JSON / UTF-8 / chunked

Complete correctly decoded body; chunks are not separate JavaScript events.

Binary body with NUL and 0xff

Exactly 4096 bytes in each direction.

Read the body again

TypeError with code=BODY_USED.

Slow response or slow header stream

TIMEOUT; weighing and runtime continue.

Oversized response / headers

Explicit rejection without silent truncation.

HTTPS with incorrect CA / name / client certificate

TLS_ERROR; verification remains enabled.

Stop during transfer

Resources released; no stale response delivered into a new application run.

17. WebSocket client

Available since: Neutron AppEngine 1.0.0 / API 1.
WebSocket provides a persistent bidirectional connection to an external server. Applications send text or binary messages and receive events. Each message retains its boundary; line delimiters are unnecessary. Use fetch() for REST and mqtt for an MQTT broker.
Each application has one independent connection, separate from module WebSocket settings, MQTT and Scale Monitor. Supports ws://, wss://, DNS names and IPv4. Check app.capabilities().features.websocket; limits are in app.capabilities().websocket.

new WebSocket(url, protocols?, options?)

Available since: Neutron AppEngine 1.0.0
Creates a client and starts asynchronous connection. Returns a WebSocket object, not a Promise. Success emits open; failure emits error and close. Invalid arguments throw synchronously.
  • url: absolute address, at most 512 bytes, such as wss://system.example.com/scales?device=01. Default ports: 80 for ws, 443 for wss. Encode paths and parameters; URL credentials, fragments and IPv6 are unsupported.
  • protocols: omitted or empty array []. Subprotocol negotiation is unavailable in this version; other values raise UNSUPPORTED_PROTOCOL.
  • options: optional object containing timeoutMs, headers and tls. May also be supplied directly as the second argument.
  • timeoutMs: integer connection limit 1000–15000 ms, default 10000 ms. DNS/network details may affect actual return time. Does not limit the connection's entire lifetime.
  • headers: string-valued HTTP headers, such as Authorization or X-API-Key. At most 32 headers and 512 bytes combined. Connection and Sec-WebSocket-* headers are client-managed and cannot be set. The complete upgrade request, including path, hostname and automatic headers, must be shorter than 1024 bytes; an oversized combination raises HEADERS_TOO_LARGE.
  • tls: wss only. caProfile, clientCertificateProfile and clientKeyProfile use REST profiles. Supply client certificate and key together. Profile names: 1–48 characters A–Z, a–z, 0–9, _ or -. Without caProfile, uses default trust. Server name and certificate verification are always enabled.
const ws = new WebSocket("wss://system.example.com/scales", [], {
  headers: { Authorization: "Bearer demo-token" },
  timeoutMs: 10000,
  tls: { caProfile: "company" }
});
ws.onopen = () => ws.send(JSON.stringify(scale.read()));
ws.onerror = event => console.warn(event.code, event.message);

Certificate checks require correct device time. Send credentials over wss. Redirects are not followed automatically. If the connection slot is occupied, the new object receives BUSY and closes; the existing connection remains active.

Basic authentication with username and password

Available since: Neutron AppEngine 1.0.0
Enter username/password as strings and use the helper below to build Authorization. Basic does not hash credentials: it Base64-encodes username:password. Encoding is reversible; use wss:// for credentials.
basicAuth(username, password) is defined in this example, not built into Neutron AppEngine. Returns the full Basic <Base64> header value. Supports UTF-8 if the server expects it and needs neither btoa nor TextEncoder. Both arguments must be strings or TypeError is thrown. Usernames cannot contain a colon; passwords can. The example address and credentials are fictitious.
function basicAuth(username, password) {
    if (typeof username !== "string" || typeof password !== "string")
        throw new TypeError("Username and password must be strings");
    if (username.includes(":"))
        throw new Error("Username must not contain ':'");

    // Encode username:password as UTF-8 bytes, then Base64.
    const text = encodeURIComponent(username + ":" + password)
        .replace(/%([0-9A-F]{2})/g,
            (_, hex) => String.fromCharCode(parseInt(hex, 16)));
    const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let encoded = "";

    for (let i = 0; i < text.length; i += 3) {
        const n = (text.charCodeAt(i) << 16)
            | ((text.charCodeAt(i + 1) || 0) << 8)
            | (text.charCodeAt(i + 2) || 0);
        encoded += alphabet[(n >>> 18) & 63];
        encoded += alphabet[(n >>> 12) & 63];
        encoded += i + 1 < text.length ? alphabet[(n >>> 6) & 63] : "=";
        encoded += i + 2 < text.length ? alphabet[n & 63] : "=";
    }
    return "Basic " + encoded;
}

// Fictional address and credentials; replace with your server settings.
const username = "demo_operator";
const password = "DemoOnly-42!";
const socket = new WebSocket("wss://gateway.example.com:9443/scale/auth", {
    headers: { Authorization: basicAuth(username, password) }
});
socket.onopen = () => socket.send(JSON.stringify(scale.read()));
socket.onerror = event => console.warn(event.code, event.message);
socket.onclose = event => console.info("WebSocket closed", event.code, event.wasClean);
Replace /scale/auth with the actual server endpoint. The helper itself needs no changes when credentials change. Never log Authorization or passwords. HTTP 401/403 during authentication emits error with AUTH_FAILED, then close. basicAuth also works in fetch Authorization headers over HTTPS.

socket.send(data)

Available since: Neutron AppEngine 1.0.0

In OPEN state, queues one message. Accepts string, ArrayBuffer or a buffer view such as Uint8Array or DataView. Strings send as UTF-8 text; other values as binary messages. Binary data is copied at call time, allowing later source changes. Empty messages and binary bytes 0 and 255 are permitted.

Returns undefined. Do not await it as delivery confirmation: sending does not confirm server processing. Add request IDs and replies to your protocol. bufferedAmount counts local queued bytes, not unacknowledged server messages.

At most 4096 bytes per message and 16384 bytes in the local queue; the shared pending-operation limit also applies. Oversized messages raise MESSAGE_TOO_LARGE; a full queue raises BUSY. CONNECTING raises INVALID_STATE; CLOSING/CLOSED ignore send. Later transfer errors arrive through error and may close the connection.

ws.send("WEIGHT?");
ws.send(JSON.stringify({ net: scale.net, gross: scale.gross }));
ws.send(new Uint8Array([0, 127, 255]));

Events and listeners

Available since: Neutron AppEngine 1.0.0
Use onopen, onmessage, onerror, onclose or addEventListener(type, callback, { once: true }). Remove with removeEventListener(type, callback). Only these four event types and function callbacks are supported; at most 32 registered listeners per object. Duplicate type/function pairs are not added. No DOM events, capture or AbortSignal.
  • open: connection and protocol upgrade succeeded; readyState is OPEN.
  • message: event.data is string for text or ArrayBuffer for binary data. Fragments assemble into one message, including UTF-8 characters split across fragments. Ping/pong is not delivered as message.
  • error: event.code, event.message and an Error in event.error. Callback errors follow runtime rules; catch inside the callback to continue.
  • close: event.code, event.reason, event.wasClean. 1006 indicates interrupted closing; 1005 means the received frame had no code. The object remains CLOSED. All events also contain type, target and currentTarget.
ws.onmessage = event => {
  try {
    if (typeof event.data === "string") {
      if (event.data.trim() === "WEIGHT?") ws.send(JSON.stringify(scale.read()));
    } else {
      const bytes = new Uint8Array(event.data);
      console.info("Binarni bajti:", bytes.length);
    }
  } catch (error) { console.warn(error.code || error.name, error.message); }
};
ws.addEventListener("open", () => console.info("Povezava odprta"), { once: true });
ws.onclose = event => console.info(event.code, event.reason, event.wasClean);

socket.close(code?, reason?) and connection state

Available since: Neutron AppEngine 1.0.0
close() starts asynchronous closure and returns undefined. Defaults: code 1000, empty reason. User codes: 1000 or 3000–4999; reason at most 123 UTF-8 bytes. Invalid arguments raise INVALID_ARGUMENT. Repeated close in CLOSING/CLOSED has no effect. Closing during connection suppresses open; the client completes the current attempt then closes. No closing reply within approximately 3 seconds forces an unclean close.
readyState: WebSocket.CONNECTING = 0, OPEN = 1, CLOSING = 2, CLOSED = 3. Constants also exist on the object. url contains the address; protocol and extensions are empty. binaryType is always arraybuffer; blob is unsupported.
if (ws.readyState === WebSocket.OPEN) ws.send("PING");
ws.close(1000, "Application finished");

Limits, recovery and errors

This version supports one client connection per application, ws/wss, binary/text transfer and certificate verification. No WebSocket server, subprotocols, compression, Blob or automatic reconnection. Create a new object after close; use delayed setTimeout if needed. This socket is separate from MQTT over ws/wss.

Reception waits for available data and requires no setInterval polling. The client sends ping approximately every 30 seconds and waits up to 10 seconds for pong. Network operations after connection have approximately 3-second bounded waits. Oversized incoming messages or invalid UTF-8 cause error and closure. app.stop(), application deletion or runtime errors close the connection and release resources; an active network operation may take seconds to finish. JavaScript events no longer run after stopping.

Error codes: INVALID_ARGUMENT, INVALID_STATE, UNSUPPORTED_PROTOCOL, BUSY, QUOTA_EXCEEDED, MESSAGE_TOO_LARGE, HEADERS_TOO_LARGE, OUT_OF_MEMORY, AUTH_FAILED (HTTP 401/403 during connection), HANDSHAKE_FAILED, NETWORK_ERROR, TLS_OR_NETWORK_ERROR, TIMEOUT, PROTOCOL_ERROR, INVALID_UTF8. For TLS_OR_NETWORK_ERROR check connectivity, time, server name and certificate. Runtime event-queue failures follow its general rules.

Integration testing

On a computer, run python tools/websocket-test-server.py --host 0.0.0.0. Set the computer address in tools/examples/websocket-self-test.js and upload it to Neutron. Tests cover UTF-8, fragments with an intervening ping, empty messages, binary transfers up to 4096 bytes and orderly closure. Weight sending example: tools/examples/websocket-scale.js. The server supports --cert/--key for wss and --token for testing Authorization. Use the appropriate CA profile for custom certificates.

Also test BIG (oversized response), incorrect certificate/token, network loss and Stop/Delete during transfer. Computer-side JavaScript API tests do not replace network and TLS testing on the device.

18. Errors, try/catch and continuation

An outer try { setInterval(...) } catch (...) { ... } catches registration errors, not later callback failures. Similarly, try { asyncOperation() } without await does not catch Promise rejection. Catch inside the callback or on the returned Promise.
Distinguish synchronous JavaScript exceptions, asynchronous Promise rejection and whole-runtime failures. Standard TypeError, ReferenceError, SyntaxError and RangeError have name/message but not necessarily code. Operation and argument-validation errors generally include error.code and error.message.
Table 84

Code

General meaning

INVALID_ARGUMENT

Invalid argument type/value; details depend on the called function.

QUOTA_EXCEEDED

Module limit exceeded; remove unused registrations.

BUSY

Resource busy, too many pending operations or full queue. Wait and bound concurrency/retries.

OUT_OF_MEMORY

Insufficient operation memory. JavaScript memory failures may instead use a standard exception without this code.

TIMEOUT

Interrupted or timed-out asynchronous operation. Check the previous operation's effect before retrying.

Catch expected failures in the function where they occur to continue. Choose shutdown with app.stop() or leave the error unhandled. No global configurable error-policy API exists. Console error logging alone does not stop the application.

async function readSettings() {
    return JSON.parse('{"enabled":true}');
}
async function start() {
    try {
        const settings = await readSettings();
        console.info("Enabled:", settings.enabled);
    } catch (error) {
        console.warn(error.code || error.name, error.message);
        // Handled error: application continues.
        // Use app.stop() to stop.
    }
}
start();

Unhandled exceptions/rejections, exhausted active time, excessive call nesting or event-queue overflow stop the application and set lastError. Internal queue/time-budget errors do not necessarily provide an object with code; status may contain EVENT_OVERFLOW or Active JS execution budget exceeded. Device system failures and power loss are not JavaScript exceptions and cannot be caught with try/catch.

Module-specific errors and responses are documented with their functions. General try/catch rules apply regardless of the operation's source.

19. Limits and resource planning

Table 85

Vir

Limit / behavior

Name / version

Name: 1–64 UTF-8 bytes; version: 1–32 bytes; no control characters. Version is text, not necessarily semantic versioning.

Source code

One UTF-8 file, 1–131,072 bytes.

Application memory

1,048,576 bytes for Neutron AppEngine data and objects; source size is checked separately.

Function nesting

Avoid deep recursion and long call chains. Excessive nesting may cause application failure.

Active time

Approximately 1 s per runtime processing step; 5 s budget during code validation. Not a guaranteed scale response time.

Timers

16 active timers.

Concurrent operations

At most 8 pending operations. Process events promptly; excessive backlog may stop the application with EVENT_OVERFLOW.

Console

10 calls/s combined, approximately 512 content bytes per call.

Upload

768 raw bytes/chunk; existing BLE UI: 192 raw bytes/chunk; session expires after 5 minutes of inactivity.

Without events or timers, Neutron AppEngine waits while other device functions continue normally. Waiting does not consume active JavaScript budget. Evaluate CPU load on the actual configuration; no fixed CPU percentage is guaranteed here.

Bound Map/Array growth, per-command data and retries. Timers for slow communication generally need a sending flag. Do not accumulate new requests when operations cannot finish promptly. Storage retains installed applications after restart; JavaScript variables disappear on Stop/reset. Use the documented storage API for persistent application data.

20. Installation, attributes and auto run

Table 86

Attribute

Description

name

Application display name and part of the JavaScript log prefix.

version

User application version; separate from interpreterVersion, apiVersion and device firmware version.

autorun

Boolean: automatically start after boot unless recovery protection blocks startup.

size / sha256

Length and SHA-256 of actual source-file UTF-8 bytes. SHA-256 is not an author signature or a substitute for authorization.

In the internal web server or BLE page, select a file, set attributes and Upload. Save attributes updates the existing application; Run starts a fresh execution; Stop requests shutdown; Refresh shows state; Abort upload cancels transfer; Delete removes the installed application. busy=true while running: stop and wait before changing attributes or installing. Delete while running initiates shutdown; the initial response is state=stopping, and deletion completes afterward. Check status for empty. Status also includes runtimeActive, runtimeTaskAllocated and resourcesReleased; after shutdown these are false, false and true. Releasing active communication requests is asynchronous; a new Run may return BUSY meanwhile. The interpreter does not execute without a running application.

Successful Upload confirms validated stored code, not a successfully executed program. Run afterward and check logs/status. Auto run occurs after firmware initialization and at least 10 s from boot, not on every MQTT reconnect. Enabling autorun in attributes does not immediately trigger manual Run.

Initial console output may be invisible if the debug transport is disconnected; check APP status/lastError. A program may remain running after a single console.log because the runtime waits for future events.

21. APP protocol for clients and Scale Monitor

Uploading requires no new communication channel. Use the existing authenticated command path. This is a protocol for external management clients, not functions the JavaScript application can invoke itself.

Table 87

Transport

Request

Response

Internal HTTP/HTTPS

Authenticated POST /api/cmd, Content-Type: text/plain; body APP <JSON>. Use the device's existing login session.

JSON object; check ok, not only HTTP status.

BLE

Existing command characteristic and credential-framed APP <JSON> command. Use the same send queue/fragmentation as other commands.
Existing notifications channel, APP <JSON> with possible interleaved debug output.

MQTT

Existing device CMP/RX topic. DATA contains Base64 of the complete UTF-8 JSON request. Publish with retain=false.

CMP/TX, APP <JSON>.
APP;MID=<device MID>;P=<existing credential>;DATA=<base64 UTF-8 JSON>;

Retain existing MID/credential checks and MQTT authentication. Retained APP commands are rejected. MQTT upload is separate from using MQTT inside JavaScript. Decoded APP request JSON is at most 2048 bytes.

21.1 File transfer

Send stop and check busy=false with status before starting. Calculate size and SHA-256 over original file bytes. Then perform begin → chunk sequence → commit → status. Await every chunk response; do not send all chunks concurrently.

APP {"op":"begin","rid":"install-001","name":"TCP tehtnica","version":"1.0.0","autorun":false,"size":1234,"sha256":"<64 hex characters>"}
APP {"op":"chunk","rid":"chunk-001","uploadId":"<id from begin>","offset":0,"data":"<base64 source bytes>"}
APP {"op":"commit","rid":"commit-001","uploadId":"<id from begin>"}
APP {"op":"status","rid":"status-001"}

This is a message schema, not a ready-to-send transfer: replace size, hash, uploadId and data with actual values. begin returns uploadId, offset=0 and chunkSize=768. Offset is a byte position; split bytes before Base64 encoding. The existing BLE UI uses 192 source bytes per APP request and further fragments credential-framed messages into GATT writes.

Table 88

Operation

Parameters besides op/rid

Result / conditions

begin

name, version, autorun:boolean, size:integer, sha256:string

Creates a session; returns uploadId, offset and chunkSize. Requires at least size × 2 + 4096 free storage bytes. Abort any other active session first.

chunk

uploadId, offset:integer, data:base64

1–768 decoded bytes. Returns the confirmed total offset. A previous chunk may be repeated only with identical bytes wholly within the confirmed range.

commit

uploadId

Allowed after all bytes arrive. Starts asynchronous SHA/syntax validation and activation; ok=true does not confirm completed activation. Poll status until busy=false.

abort

uploadId

Removes staged file and session. Allowed when not busy. Sessions belonging to other transports cannot be taken over using uploadId alone.

configure

name, version, autorun:boolean

Changes all existing application attributes and starts asynchronous validation/activation. Requires an installed application, no active upload and busy=false.

run

—

Starts the installed application and returns state. Upload must be completed/aborted and busy=false.

stop

—

Cancels pending automatic startup and requests stopping. Acknowledgement confirms command acceptance; poll status for completion.

status

—

Current state, installed attributes, error and recovery. Also allowed during execution.

delete

—

Deletes the active application, its backup, intermediate files and recovery record. Stop first and abort any upload.

Check boolean ok in every response. Failure returns ok=false and error text, distinct from JavaScript Promise error.code. Optional rid is a text correlation ID up to 64 bytes. Retry an ID with identical JSON only; different contents under the same ID are rejected. Successful-mutation cache retains only the last six requests per process, not a persistent exactly-once guarantee. For chunks, use uploadId/offset and confirmed bytes.

A session belongs to its initial transport and uploadId and may expire after 5 minutes of inactivity. After a lost response, inspect status/received; do not guess offsets. Hash/syntax failure is not successful installation. After commit check name/version/sha256 and lastError.

21.2 Status and operation completion

{
  "ok": true, "rid": "status-001",
  "state": "running", "busy": true,
  "name": "TCP tehtnica", "version": "1.0.0", "autorun": false,
  "size": 1234, "sha256": "<64 hex characters>", "lastError": "",
  "uploadId": "", "received": 0, "maxSize": 131072,
  "recovery": {
    "healthy": true, "crashes": 0, "limit": 3,
    "autoRunDisabled": false, "stableAfterMs": 60000,
    "lastState": "starting", "lastResetReason": 1, "error": ""
  }
}

The example is illustrative; read actual values. State may be empty, ready, validating, running, stopped, error or blocked. Busy is also true during normal long-running execution. For validation completion, wait for busy=false and inspect lastError and installed-code identity. For Run, check running and monitor later failures. Recovery lastState and lastResetReason are firmware diagnostics, not business-protocol status.

Table 89

Example APP error

Meaning / client response

BUSY

Send stop and await completion; poll status during validation.

Invalid APP JSON

Invalid JSON or request exceeds 2048 bytes.

Invalid metadata / Invalid name, version, autorun, size or sha256

Check UTF-8 lengths, boolean autorun, hash and size.

Invalid upload session

Incorrect uploadId, transport or expired session.

Invalid offset / Overlapping chunk / Duplicate chunk differs

Match offset to confirmed received; do not change the file during transfer.

Upload incomplete

Commit before all bytes arrive.

Insufficient filesystem space

Insufficient space for safe transfer and replacement.

No application installed

Run/configure without an installed application.

Application storage not ready / Task allocation failed…

Storage or RAM not ready; inspect status/logs and device diagnostics.

The text-error list is not exhaustive. Preserve full error/lastError in client diagnostics. An external client timeout does not prove device rejection.

22. Auto run and crash protection

Before startup, Neutron AppEngine stores application identity and monitors startup success. An unexpected device restart during this period records an unstable attempt on the next boot. After three consecutive unstable attempts, auto run is blocked before a fourth automatic attempt. Code remains stored for inspection or replacement.

Unexpected resets from system faults or power issues may increase the unstable-attempt counter. Normal power-on and planned restarts are treated differently from application crashes. An unstable attempt alone does not prove a user-code defect; inspect device diagnostics too.

Approximately 60 s of confirmed operation clears the failure sequence, including normal event waiting rather than CPU time alone. Normal Stop closes the marker. An existing auto-run block remains until successful explicit installation or Save attributes/configure. Manual Run remains possible and is monitored. Recovery-record save failure may prevent Run for protection.

An ordinary unhandled JavaScript error stops the application and sets lastError; it is different from a module reset. Factory default deletes installed code, its backup, staged files, recovery state and application storage including local databases. JavaScript try/catch cannot prevent hardware reset.

23. Rules for ScaleGuru AI and integrators

Use this section as a contract for application generation. ScaleGuru AI should return one complete UTF-8 .js file and separately list required system configuration and test steps. Documentation does not automatically authorize AI to upload or execute code on a user's device.

Target: CS-NEUTRON application, Neutron AppEngine 1.0.0, API 1.
1. Identify required modules and verify support with app.capabilities().
2. Use only documented functions of supported modules. Never invent APIs.
3. Produce one UTF-8 file without top-level await, import/export or npm.
4. Define and call an async initialization function; handle its rejection.
5. Use standard timers; setInterval does not await async callbacks.
6. Handle rejected operations with await/try/catch or .catch().
7. Choose error handling: continue, bounded retry or app.stop().
8. Respect memory, active-time and module limits.
9. No busy waiting, deep recursion or unbounded queues and buffers.
10. Find configuration, events, errors and examples in the relevant module chapter.
11. The installation channel does not determine the application's communication module.
12. Test manual Run first; enable auto run only after functional testing.
13. If a required module is unsupported, explain the limit instead of generating fake calls.

23.1 Testing before application release

Table 90

Test

Expected result

Device without a valid measurement

No uncontrolled exception; the application clearly reports unavailable measurement.

Multiple commands in one receive

Handle every command; consider response ordering for asynchronous commands.

Busy scale / rejected operation

Expected rejection is handled without infinite retries.

Stop with no active timers

The idle runtime wakes and terminates normally.

Restart with auto run

The validated installed version starts; lastError and recovery are inspected.

24. Revisions and related documentation

Table 91

Manual

Date

Changes

1.0

15. 11. 2026

First API release: runtime, scale, I/O, module settings, files, local database, TCP, serial interfaces, MQTT, REST/HTTP, APP protocol and startup protection.

Related documentation: CSCP — Neutron communication protocol. CSCP describes system commands and configuration; these do not automatically become JavaScript functions. This reference follows purpose, syntax, parameters, result, errors and example.

Examples are included as static code and remain readable without JavaScript. Page search, code copying and printing are documentation tools; they do not execute applications or communicate with a device. The documentation is not embedded in firmware.

Frequently asked questions

Can I use Node.js, npm or browser APIs?

No. Upload one UTF-8 JavaScript script and use the documented neutron-js-1 APIs. Node.js, npm, the DOM, import/export and top-level await are unavailable.

How do I check available features?

Call app.capabilities() on the device. Check apiVersion, interpreterVersion, features and module-specific limits before using a function.

Does application data survive Stop and restart?

JavaScript variables do not survive. Files and local record databases in storage persist after Stop, restart and normal application replacement. Factory default deletes this data.

When should I enable Auto run?

First upload, run manually and test the required behavior, limits and failure cases. Enable Auto run only after functional testing. Startup protection can block repeated unstable automatic starts.

Need help?

Need help with software, connectivity or using a solution? Describe the issue so we can help with the next step.

Prepare a request →