CSCP — CloudScale Communication Protocol
CSCP command reference for Neutron: message structure, weighing, configuration, counting, checkweighing and digital I/O.
This page is not yet available in Hrvatski. The English version is shown.
This page is not yet available in Hrvatski. The English version is shown.
NEUTRON APPENGINE · DEVELOPER MANUAL
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.
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.
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.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 |
.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.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.
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();
});Avoid blocking: do not usewhile (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.
TIMEOUT during application startup (limit 1000 ms). Interrupting execution does not automatically restart the module.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. |
await yields execution, allowing other callbacks to run while waiting. An asynchronous callback is therefore not a transaction that blocks other events.const capabilities = app.capabilities();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
}
}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);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.app.stop();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();
}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.console.log(...values);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 });console.info(...values);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 });console.warn(...values);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 });console.error(...values);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 });console.debug(...values);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.
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.
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.const id = setTimeout(callback, delayMs = 0, ...args);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");const id = setInterval(callback, delayMs = 0, ...args);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);clearTimeout(id);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);clearInterval(id);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);const measurement = scale.read();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);
}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. |
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.const measurement = await scale.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.tare();
console.info("Operation successful", m.net, m.tare, m.unit);
} catch (error) {
console.warn(error.code || "SCALE_FAILED", error.message);
}
}
apply();const measurement = await scale.zero();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();const measurement = await scale.clearTare();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();const measurement = await scale.setPresetTare(value);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.
const response = await scale.cmd(command, { timeoutMs });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.
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. |
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. |
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);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.
const input = io.input(1);
const output = io.output(1);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);const inputState = io.input(1).read();
const outputState = io.output(1).read();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());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. |
await io.input(1).configure({ mode: "digital", function: "disabled", debounceMs: 20, pull: "down" });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" });await io.output(1).configure({ function: "disabled" });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));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 |
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.
await io.output(1).claim({ safeState: false });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);await io.output(1).write(true);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);await io.output(1).release();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("change", callback);
pin.once("change", callback);
pin.off("change", callback);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);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;
}
});const count = io.input(1).counter();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() }));await io.input(1).resetCounter();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());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.
});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. |
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.
const raw = await device.cmd("RMD");
const result = await device.cmd("SMD;S0B=19200;S0P=0;");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");
}const values = await device.settings.read(["S0B", "S0P"]);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);const page = await device.settings.list({ cursor: null, limit: 16 });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);const result = await device.settings.write({ S0B: "19200", S0P: "0" });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");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(); });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.
const info = await storage.info();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);await storage.write(name, data);
await storage.writeText(name, text);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]));await storage.append(name, data);
await storage.appendText(name, text);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");const bytes = await storage.read(name, { offset: 0, length: 4096 });
const text = await storage.readText(name);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;
}const page = await storage.list({ cursor: null, limit: 16 });
const info = await storage.stat("data.bin");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);const removed = await storage.remove("old.jsonl");
await storage.rename("measurements.jsonl", "archive.jsonl");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");const page = await storage.findText("measurements.jsonl", "ART-001", { offset: 0, limit: 16 });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 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(); });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. |
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.
const articles = await storage.openRecords("articles", { key: "code" });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());await articles.put({ code: "ART-001", name: "Flour", target: 25 });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.const article = await articles.get("ART-001");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);const deleted = await articles.delete("ART-001");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);const page = await articles.list({ cursor: null, limit: 16 });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);const status = await articles.stat();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());await articles.compact();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());await articles.close();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();
}const removed = await storage.removeRecords("articles");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");// 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();
});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. |
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.
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 |
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().
const status = await tcp.configure(options);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.const result = await tcp.claim();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(); });const result = await tcp.release();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();const bytesWritten = await tcp.write(data, { connectionId });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);
}
});tcp.on(eventName, callback);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.once(eventName, callback);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);
});tcp.off(eventName, callback);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);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);
});event.connectionId; never persist it or invent IDs.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); }
});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. |
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. |
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.
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,<code>. |
PRESET_TARE 2.5 | Sets tare in the currently configured unit; returns OK or ERR,<code>. |
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.
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.
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. |
const status = tcp.status();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();
});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.rs485const result = await port.claim();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));const result = await port.configure(options);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));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.
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.
const bytes = await port.write(data, { timeoutMs });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));await port.drain({ timeoutMs });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));const result = await port.release();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));port.on(eventName, callback);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);port.once(eventName, callback);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);port.off(eventName, callback);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);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.
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();
});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. |
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 noclaim().
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.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.
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.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.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.await mqtt.configure(options);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
});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.
await mqtt.connect({ timeoutMs: 15000 });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();
}await mqtt.disconnect();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();const status = mqtt.status();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);await mqtt.subscribe("factory/+/command", { qos: 1, timeoutMs: 10000 });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 });await mqtt.unsubscribe("factory/scale-01/command");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 });await mqtt.publish(topic, payload, { qos: 1, retain: false });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(eventName, callback);
mqtt.once(eventName, callback);
mqtt.off(eventName, callback);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));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. |
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.
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. |
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();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.
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();
});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. |
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.
const response = await fetch(url, options);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));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.
const response = await fetch("https://api.example.com/articles/ART-001");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());const text = await response.text();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);const value = await response.json();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.const buffer = await response.arrayBuffer();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);const contentType = response.headers.get("Content-Type");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);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 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.
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=<PEM>. 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);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.
// 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);
}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.
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. |
fetch() for REST and mqtt for an MQTT broker.ws://, wss://, DNS names and IPv4. Check app.capabilities().features.websocket; limits are in app.capabilities().websocket.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.
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);/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.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.
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]));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);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");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.
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.
An outertry { 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.
error.code and error.message.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.
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.
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.
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.
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.
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.
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.
{
"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.
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.
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.
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.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. |
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. |
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.
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.
Call app.capabilities() on the device. Check apiVersion, interpreterVersion, features and module-specific limits before using a function.
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.
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.
CSCP command reference for Neutron: message structure, weighing, configuration, counting, checkweighing and digital I/O.
Neutron Modbus RTU/TCP reference for PLC, SCADA and HMI integration: connection, addressing, registers, calibration and automatic checkweigher control.
OPC UA integration for Neutron: secure connections, live weighing data, stable capture and PLC/SCADA integration.
Need help with software, connectivity or using a solution? Describe the issue so we can help with the next step.