Skip to main content
Version: Next

Common

General Functions

This category contains functions that are used for all devices.

API NameBrief Description
api.ledControl(state, timeout, period, offState, pattern, Ts, patternTimeout)Turns ON or OFF the on board LED.
api.delayms(ms,mode)Pauses the execution for ms milliseconds.
api.randInt(min, max)Generates random number within given range.
api.getUniqueNumber()Generates unique number.
api.getBatteryVoltage()Returns the current voltage level of the battery in mV.
api.getTick(clock, reset)Returns current number of milliseconds since startup.
api.dumpArray(str,opt)Prints contents of variable as hexadecimal string (dumps array into console).
api.float()Performs operation with given floating point data. Multiple variants. See below.
api.setVar()Saves a persistent variable value. Multiple variants. See below.
api.getVar()Returns persistent variable value. Multiple variants. See below.
api.wakeUpAt(day, hour, minute, second, resetOnFail)Schedules the next wake up event of the device to provided day of month, hour, minute and second.
api.wakeUpIn(day, hour, minute, second, resetOnFail, milisecond)Schedules the next wake up event of the device after specified time interval.
api.getTimeDate(timezoneShift)Returns current date and time set on this device.
api.setTimeDate()Set date and time on this device, or calculate the difference and synchronize the date and time. Multiple variants. See below.
api.voltageSourceState()Controls voltage source. Multiple variants. See below.
api.stdin()Reads stdin (standard input) data or control button (get status, wait for button). Multiple variants. See below.
api.stdout(out, size, offset)Writes to stdout (standard output) without adding line termination.
api.bsprintf(binData, format, offset, endian)Formats binary stream data according to various format specifiers, including support for characters, integers, short and long integers, floats, and doubles.
api.setVerbosity()Controls the number of messages printed to the serial line. Multiple variants. See below.
api.exec()Executes a system command or Lua fragment. Multiple variants. See below.
api.table()Interface to create and manipulate memory-efficient tables and maps. Multiple variants. See below.
api.aes(operation, data, iv, key)Encrypts or decrypts provided payload using a key and IV with AES-CTR.

api.ledControl(state, timeout, period, offState, pattern, Ts, patternTimeout)


api.ledControl(1) --turn on the LED

Controls the device’s blue LED. Supports solid on/off, duty-cycled blinking via (timeout, period), and custom patterns with optional timeouts.

Arguments

  • state (integer): Applied immediately every call.
    • 1 for ON.
    • 0 for OFF.

Optional

  • timeout (integer, optional, default: -1): The amount of time, that LED turns on for in miliseconds. After said amount, LED turns off.
  • period (integer, optional, default: -1): Length of one full cycle when using simple blinking. On each cycle edge, the LED turns to state (typically ON) and stays ON for timeout before turning OFF for the remainder of the period. -1 disables simple blinking.
  • offState (integer, optional, default: -2): What value the driver treats as “off.” Only updates if you pass a value other than -2.
  • pattern (string or nil, optional, default: nil): Pattern to play; overrides and clears current simple blinking (period/timeout). Pass nil (or omit) to stop any running pattern.
  • Ts (integer, optional, default: 50): Tick duration for pattern stepping (each pattern character lasts Ts units).
  • patternTimeout (integer, optional, default: -1): Total time to run the pattern before stopping pattern stepping. -1 disables pattern timeout.

Simple blinking (duty cycle)

When period >= 0 (and no pattern is active), the LED cycles as follows:

  1. Every time the period elapses, the driver reloads both timers and sets the LED to the state value (LEDblue(ledOnState)).
  2. The timeout then counts down. When it reaches zero, the LED is forced to off (LEDblue(ledOffState)).
  3. The LED remains off until the next period edge, when step 1 repeats.

This means the effective duty cycle is approximately: duty = timeout / period (same time base).

All counters are decremented by the LED tick; in many builds this is one millisecond, but treat these as driver ticks unless specified.

Pattern mode

Providing a pattern cancels any existing pattern and clears simple blinking/timeout. The LED is then driven by the pattern engine. Each pattern character lasts Ts ticks.

Supported characters (from the driver):

  • H — Force LED on (LEDblue(1))
  • L — Force LED off (LEDblue(0))
  • Z or F — High‑impedance / special off (LEDblue(-1))
  • 0..9PWM-like brightness levels in tenths (0–9). Digits use the simple blinking engine under the hood with a fixed base period of 10 ticks and an ON‑time equal to the digit value in ticks. Concretely: the driver sets period = 10, timeout = digit, starts from OFF, and lets the period/timeout logic generate a duty cycle ≈ digit/10.

Additional details:

  • The pattern wraps when it reaches the end.
  • If patternTimeout is set (not -1), a running total increases by Ts after each character step. When it reaches or exceeds patternTimeout, the pattern engine stops stepping (internal timers are zeroed and the position resets). The LED remains in whichever state the last step left it in until another api.ledControl(...) call changes it.

Behavior & precedence

  1. state is applied immediately every call.
  2. If pattern is provided: previous pattern is freed; simple period & timeout are cleared; pattern controls the LED. Digits within the pattern temporarily enable the duty‑cycle engine with period=10 and timeout=digit to emulate brightness.
  3. If pattern is not provided and a pattern was running, that pattern is stopped and simple blinking is cleared.
  4. If period >= 0 (and no pattern), the duty‑cycle behavior runs using timeout and period as described above.
  5. offState only updates when a value other than -2 is passed.

All time values (timeout, period, Ts, patternTimeout) are measured in the driver’s tick unit; many targets wire this to milliseconds.

Example

api.ledControl(1) -- LED is turned on, needs to be turned off, else it shines indefinitely

api.ledControl(0) -- LED is turned off

api.ledControl(1,500) -- LED blinks once for half a second

led(1,0,0,0,"L123456789H987654321LLLLL", 50) -- LED Blinking on lower intensity

api.ledControl(1, 0, 0, 0, "H9L1", 50, 3000) -- LED Blinking on lower intensity for three seconds, than stays on on lower intensity

api.delayms(ms, mode)


api.delayms(1000) -- Delay one second

Pauses execution of code for a specified number of milliseconds.

Arguments

  • ms (integer): Number of milliseconds to delay (0 to 2,147,483,647).

Optional

  • mode (integer, optional): Use sleep for longer intervals:
    • 1: Sleep if interval is longer than 10 ms.
    • 2: Sleep for the defined milliseconds.

Example

-- Delay one second
api.delayms(1000)

--------------------------------

-- Turn on blue LED, wait 1 second, then turn off
api.ledControl(1)
api.delayms(1000)
api.ledControl(0)

--------------------------------

-- Sleep for one second, then continue
api.delayms(1000, 2)

api.randInt(min, max)


api.randInt(5, 20) -- Generates a random number between 5 and 20

Generates and returns a random number within a specified range.

Note: LoRaWAN devices generate this number via a module, whereas other device use pseudorandom generation – this has in practicality little impact. You may also use native Lua function math.random(min, max) for the same purpose.

Arguments

  • min (integer): Start of the range (0 to 2,147,483,647).
  • max (integer): End of the range (0 to 2,147,483,647).

Return

  • number (integer): Random number within the specified range.

Example

-- Generates a random number between curLow and curHigh variables
ran = api.randInt(curLow, curHigh)

api.getUniqueNumber()


api.getUniqueNumber() -- Get a unique number

Generates and returns a unique number (int32).

Info: Increments a uint32_t variable by one each time the function is called and returns its value (0 to 2^32).

Return

  • num (integer): Unique number (0 to 2^32).

Example

-- Get a unique number
num = api.getUniqueNumber()

api.getBatteryVoltage()


api.getBatteryVoltage() -- Return battery voltage value in mV

Returns the current battery voltage level in millivolts (mV).

Return

  • voltage (integer): Battery voltage level in mV.

Example

-- Get battery voltage value in mV
mv = api.getBatteryVoltage()

--------------------------------

-- Function that prints all the information upon booting, includes battery voltage
function bootMessage (joinMethod, rxTimeout, port)
local sysinfo = ex("_sysinfo")
model = sysinfo["model"]["name"]
sn = sysinfo["SN"]
fwma = sysinfo["ver"]["major"]
fwmi = sysinfo["ver"]["minor"]
fwbf = sysinfo["ver"]["bugfix"]
local battVol = api.getBatteryVoltage()
local cpuTemp = ex("_cpu_temp")
local bootMsg = model .. b(0) .. pp("<i", sn) .. b(fwma) .. b(fwmi) .. b(fwbf) .. ver .. pp("<i", battVol) .. b(cpuTemp)
local msgPrint = "Model: " .. model .. ", Serial number: " .. sn .. ", FW version: " .. fwma .. "." .. fwmi .. "." .. fwbf .. ", Script version: " .. ver .. ", Battery voltage: " .. battVol .. " mV, CPU temperature: " .. cpuTemp .. " C"
print(msgPrint)

api.getTick(clock, reset)


api.getTick() -- Read uptime in ms

Returns the current uptime tick.

  • clock selects the source and units.
  • Values are masked to 31 bits (& 0x7FFFFFFF) to stay positive in Lua.
  • Default is an RTC-derived tick that keeps counting in sleep.

In most builds, clock = 3 returns two values: seconds and milliseconds. In special SPEEDUP_256x builds, clock = 3 returns a single millisecond tick (same masking rules as other single-value variants).

Arguments

Optional

  • clock (integer, optional):
    • 3: Use SysTick; returns seconds, milliseconds (two values; see note above for SPEEDUP_256x).
    • 2: Use RTC-derived tick; returns seconds.
    • 1: Use RTC-derived tick; returns milliseconds (default).
    • 0: Use SysTick; returns milliseconds.
  • reset (integer, optional; applies to clock = 0 and clock = 3):
    • 1: Reset the SysTick base (internally sets uwTick = 1).
    • 0: Do not reset (default).

Return

  • For clock = 1 or 0: tick (integer, milliseconds; masked to 31 bits).
  • For clock = 2: tick (integer, seconds; masked to 31 bits).
  • For clock = 3:
    • seconds, milliseconds (two integers; each masked to 31 bits), or
    • tick (single integer, milliseconds; masked) if built with SPEEDUP_256x.

Example

-- Default: RTC-based milliseconds (masked to 31 bits)
local ms = api.getTick()

--------------------------------

-- RTC-based seconds
local s = api.getTick(2)

--------------------------------

-- SysTick milliseconds
local ms_systick = api.getTick(0)

--------------------------------

-- SysTick seconds + milliseconds (two returns in normal builds)
local seconds, millis = api.getTick(3)

--------------------------------

-- Reset SysTick base, then read ms
api.getTick(0, 1)
local ms_after_reset = api.getTick(0)

--------------------------------

-- Reset SysTick base, then read split seconds/ms (normal builds)
api.getTick(3, 1)
local sec2, ms2 = api.getTick(3)

--------------------------------

-- Onwake function using getTick to make sure time is correct
function onWake()
print("Periodic wake up - send a ping, that we are alive")
processInputs()
api.setVar(1, api.getTick()) -- update also the timestamp
end

api.dumpArray(str, opt)


api.dumpArray("123ef") -- Print as hex

Prints the contents of a variable as a hexadecimal string (dumps array into console).

Arguments

  • str (string): Variable to print.

Optional

  • opt (string, optional): Defines the type of print:
    • "normal": Default printing method.
    • "raw": Prints only raw values.
    • "return": Returns the hex string.

Example

-- Print string "123ef" as hexadecimal
api.dumpArray("123ef")
-- Output: 00 : 31 32 33 65 66

--------------------------------

-- Print string "123ef" as hexadecimal raw
api.dumpArray("123ef", "raw")
-- Output: 31 32 33 65 66

--------------------------------

-- Return string "123ef" as hexadecimal string
ret = api.dumpArray("123ef", "return")

--------------------------------

-- Example of how a detected error may be turned into HEX before sending via LoRaWAN
txbuf = txbuf .. pack.pack("<I2", directState, detectedError)

api.dumpArray(txbuf)
acked = api.loraSend(useAcking, 6000, txbuf, port)

api.float()

Performs operation with given floating point data. Note that float operations are disabled by default. In order to use these, please request a custom version of firmware.

API NameBrief Description
api.float("add", form, arg1, arg2)Performs addition of arg1 and arg2 with given floating point data. Only available if allowed by the firmware.
api.float("sub", form, arg1, arg2)Performs subtraction of arg2 from arg1 with given floating point data. Only available if allowed by the firmware.
api.float("mul", form, arg1, arg2)Performs multiplication of arg1 and arg2 with given floating point data. Only available if allowed by the firmware.
api.float("div", form, arg1, arg2)Performs division of arg1 by arg2 with given floating point data. Only available if allowed by the firmware.
api.float("coerce", form, arg1)Performs coercion of arg1 with given floating point data (unary operation). Only available if allowed by the firmware.
api.float("convert", form, arg1)Performs conversion of integer to float for arg1 with given floating point data (unary operation). Only available if allowed by the firmware.

api.float("add", form, arg1, arg2)


api.float("add", "SSS", "12.8", "1000.0") -- add

Performs addition of arg1 and arg2 with given floating-point data.

Warning: Only available if allowed by the firmware.

Arguments

  • "add" (string, command): command for addition.

    ❗command - the argument needs to have this exact form❗

  • form (string): Two or three characters specifying input/output data format:

    • "B": Binary.
    • "S": String.
    • "I": Integer.
    • "N": Little endian integer.
    • First position: Format for arg1.
    • Second position: Format for arg2 or return data.
    • Optional "N": Coerces and returns little endian integer.
  • arg1 (string): First operation argument, formatted as specified.

  • arg2 (string): Second operation argument, formatted as specified.

Return

  • result (string or integer): Result of the operation, either 4-byte little/big endian IEEE 754 float, string float representation, or integer value.

Example

-- Add two string float representations
ret = api.float("add", "SSS", "12.8", "1000.0")
print(ret)
-- Output: 1012.8000

api.float("sub", form, arg1, arg2)


api.float("sub", "SSS", "1000.0", "12.8") -- subtract

Performs subtraction of arg2 from arg1 with given floating-point data.

Warning: Only available if allowed by the firmware.

Arguments

  • "sub" (string, command): command for subtraction.

    ❗command - the argument needs to have this exact form❗

  • form (string): Two or three characters specifying input/output data format:

    • "B": Binary.
    • "S": String.
    • "I": Integer.
    • "N": Little endian integer.
    • First position: Format for arg1.
    • Second position: Format for arg2 or return data.
    • Optional "N": Coerces and returns little endian integer.
  • arg1 (string): First operation argument, formatted as specified.

  • arg2 (string): Second operation argument, formatted as specified.

Return

  • result (string or integer): Result of the operation, either 4-byte little/big endian IEEE 754 float, string float representation, or integer value.

Example

-- Subtract two string float representations
ret = api.float("sub", "SSS", "1000.0", "12.8")
print(ret)
-- Output: 987.2000

api.float("mul", form, arg1, arg2)


api.float("mul", "SSS", "12.8", "1000.0") -- multiply

Performs multiplication of arg1 and arg2 with given floating-point data.

Warning: Only available if allowed by the firmware.

Arguments

  • "mul" (string, command): Command for multiplication.

    ❗command - the argument needs to have this exact form❗

  • form (string): Two or three characters specifying input/output data format:

    • "B": Binary.
    • "S": String.
    • "I": Integer.
    • "N": Little endian integer.
    • First position: Format for arg1.
    • Second position: Format for arg2 or return data.
    • Optional "N": Coerces and returns little endian integer.
  • arg1 (string): First operation argument, formatted as specified.

  • arg2 (string): Second operation argument, formatted as specified.

Return

  • result (string or integer): Result of the operation, either 4-byte little/big endian IEEE 754 float, string float representation, or integer value.

Example

-- Multiply IEEE 754 float with a floating-point constant and return coerced value
ret = api.float("mul", "SSN", "12.8", "1000.0")
print(ret)
-- Output: 12800

--------------------------------

ret = api.float("mul", "SSS", "12.8", "1000.0")
print(ret)
-- Output: 12800.0000

--------------------------------

-- Hexadecimal interpretation of 12.8 is 0x414CCCCD (IEEE 754)
x = string.char(0xCD, 0xCC, 0x4C, 0x41)
ret = api.float("mul", "BSS", x, "1000.0")
print(ret)
-- Output: 12800.0000

api.float("div", form, arg1, arg2)


api.float("div", "SSS", "12800.0", "1000.0") -- divide

Performs division of arg1 by arg2 with given floating-point data.

Warning: Only available if allowed by the firmware.

Arguments

  • "div" (string, command): Command for division.

    ❗command - the argument needs to have this exact form❗

  • form (string): Two or three characters specifying input/output data format:

    • "B": Binary.
    • "S": String.
    • "I": Integer.
    • "N": Little endian integer.
    • First position: Format for arg1.
    • Second position: Format for arg2 or return data.
    • Optional "N": Coerces and returns little endian integer.
  • arg1 (string): First operation argument, formatted as specified.

  • arg2 (string): Second operation argument, formatted as specified.

Return

  • result (string or integer): Result of the operation, either 4-byte little/big endian IEEE 754 float, string float representation, or integer value.

Example

-- Divide two string float representations
ret = api.float("div", "SSS", "12800.0", "1000.0")
print(ret)
-- Output: 12.8000

api.float("coerce", form, arg1)


api.float("coerce", "SS", "12.8") -- coerce to float

Performs coercion of arg1 with given floating-point data (unary operation).

Warning: Only available if allowed by the firmware.

Arguments

  • "coerce" (string, command): Command for coercion.

    ❗command - the argument needs to have this exact form❗

  • form (string): Two or three characters specifying input/output data format:

    • "B": Binary.
    • "S": String.
    • "I": Integer.
    • "N": Little endian integer.
    • First position: Format for arg1.
    • Second position: Format for return data.
    • Optional "N": Coerces and returns little endian integer.
  • arg1 (string): Operation argument, formatted as specified.

Return

  • result (string or integer): Result of the operation, either 4-byte little/big endian IEEE 754 float, string float representation, or integer value.

Example

-- Coerce a string float representation
ret = api.float("coerce", "SS", "12.8")
print(ret)
-- Output: 12.8000

api.float("convert", form, arg1)


api.float("convert", "NB>", 125) -- int to IEEE754 bytes

Performs conversion of integer to float for arg1 with given floating-point data (unary operation).

Warning: Only available if allowed by the firmware.

Arguments

  • "convert" (string, command)

    ❗command - the argument needs to have this exact form❗

  • form (string): Two or three characters specifying input/output data format:

    • "B": Binary.
    • "S": String.
    • "I": Integer.
    • "N": Little endian integer.
    • First position: Format for arg1.
    • Second position: Format for return data.
    • Optional "N": Coerces and returns little endian integer.
  • arg1 (string): Operation argument, formatted as specified.

Return

  • result (string or integer): Result of the operation, either 4-byte little/big endian IEEE 754 float, string float representation, or integer value.

Example

-- Convert integer to IEEE 754 float
y = string.char(0xCD, 0xCC, 0x4C, 0x42)
ret = api.float("convert", "IB", y)
api.dumpArray(ret)
-- Output: 9A 99 84 4E

--------------------------------

y = 125
ret = api.float("convert", "NB>", y)
api.dumpArray(ret)
-- Output: 42 FA 00 00

api.setVar()

API NameDescription
api.setVar(index, value, bool)Stores an integer value (0 to 2147483647) at the specified index (0-15 for RAM, 16-47 for HEE, 48-1071 for EEPROM), with optional bitwise negation at the next address.
api.setVar(index, mode, value)Stores a string array buffer at the specified index (0-15 for RAM, 16-47 for HEE, 48-1071 for EEPROM) using the specified memory mode ("bytes" supported).

api.setVar(index, value, bool)


api.setVar(1000, 3424) -- store number

Stores an integer value (0 to 2,147,483,647) at the specified index (0-15 for RAM, 16-47 for HEE, 48-1071 for EEPROM), with optional bitwise negation at the next address.

Info: Can be used between different wake-up iterations.

Arguments

  • index (integer): Index of the variable to write:
    • 0 to 15: RAM variables (lost on reset).
    • 16 to 47: High Endurance EEPROM (HEE) variables (6.4M writes).
    • 48 to 1071: EEPROM variables (100k writes).
  • value (integer): Value to store (0 to 2,147,483,647).

Optional

  • bool (boolean, optional): Stores bitwise negation of the value at the next address.

Example

-- Set persistent variable at index 1000 to 3424
api.setVar(1000, 3424)

-- get and format S0 inputs
function getS0Data()
s01 = api.S0readCounter(1)
print("S0-1: "..tostring(s01))
s02 = api.S0readCounter(2)
print("S0-2: "..tostring(s02))

-- read old values
s01_l = api.getVar(16)
s02_l = api.getVar(17)

s01_ll = api.getVar(20)
s02_ll = api.getVar(21)

-- update old values
api.setVar(16, s01)
api.setVar(17, s02)

api.setVar(20, s01_l)
api.setVar(21, s02_l)

api.setVar(index, mode, value)


api.setVar(30, "bytes", "Hello") -- store bytes

Stores a string array buffer at the specified index (0-15 for RAM, 16-47 for HEE, 48-1071 for EEPROM) using the specified memory mode ("bytes" supported).

Info: Can be used between different wake-up iterations.

Arguments

  • index (integer): Index of the variable to write:
    • 0 to 15: RAM variables (lost on reset).
    • 16 to 47: High Endurance EEPROM (HEE) variables (6.4M writes).
    • 48 to 1071: EEPROM variables (100k writes).
  • mode (string): Explicit memory mode, currently supports "bytes".
  • value (string): String array buffer to write.

Example

-- Store a string in EEPROM
myVariable = "This is some string to store to eeprom"
api.setVar(29, #myVariable) -- Save the length
api.setVar(30, "bytes", myVariable) -- Consumes ceil(#myVariable / 4) 32-bit indexes

--------------------------------

-- Stores a default list of primary addresses
api.setVar(32, "bytes", defaultListOfPrimaryAddresses)
api.setVar(30, #defaultListOfPrimaryAddresses, true)
listOfPrimaryAddresses = defaultListOfPrimaryAddresses

api.getVar()

Schedules the next wake up event of the device to provided day of month, hour, minute and second.

API NameBrief Description
api.getVar(index, default)Returns an integer value from the specified index (0-15 for RAM, 16-47 for HEE, 48-1071 for EEPROM), returning the default value if the stored value matches the bitwise negation of the next address.
api.getVar(index, mode, length)Returns a string array buffer of specified length from the index (0-15 for RAM, 16-47 for HEE, 48-1071 for EEPROM) using the specified memory mode ("bytes" supported).

api.getVar(index, default)


slotNumber = api.getVar(1000) -- read number

Returns an integer value from the specified index (0-15 for RAM, 16-47 for HEE, 48-1071 for EEPROM), returning the default value if the stored value matches the bitwise negation of the next address.

Info: Can be used between different wake-up iterations.

Arguments

  • index (integer): Index of the variable to read:
    • 0 to 15: RAM variables (lost on reset).
    • 16 to 47: High Endurance EEPROM (HEE) variables (6.4M writes).
    • 48 to 1071: EEPROM variables (100k writes).

Optional

  • default (integer, optional): Default value returned if the stored value matches the bitwise negation at the next address.

Return

  • value (integer): Value of the 32-bit variable.

Example

-- Get persistent variable from index 1000
slotNumber = api.getVar(1000)

--------------------------------


-- Loads and sets stored values for initial delay and readout period
initialDelay = api.getVar(60, initialDelay)
periodMinutes = api.getVar(62, periodMinutes)

api.getVar(index, mode, length)


data = api.getVar(30, "bytes", 16) -- read 16 bytes

Returns a string array buffer of specified length from the index (0-15 for RAM, 16-47 for HEE, 48-1071 for EEPROM) using the specified memory mode ("bytes" supported).

Info: Can be used between different wake-up iterations.

Arguments

  • index (integer): Index of the variable to read:
    • 0 to 15: RAM variables (lost on reset).
    • 16 to 47: High Endurance EEPROM (HEE) variables (6.4M writes).
    • 48 to 1071: EEPROM variables (100k writes).
  • mode (string): Mode to use, currently supports "bytes".
  • length (integer): Length in bytes to read.

Return

  • value (string): String array buffer.

Example

-- Read a string from EEPROM
stringLength = api.getVar(29)
myReadout = api.getVar(30, "bytes", stringLength)
print(myReadout) -- Prints the stored string

--------------------------------

-- Populate filter with a value returned by getVar
api.mbusVifDifFilter("populate", api.getVar(22, "bytes", vifDifFilterLength))

api.wakeUpAt(day, hour, minute, second, resetOnFail)


status = api.wakeUpAt(25, 2, 22, 58)

Schedules the next wake-up event at a specific date and time.

Info: The wake-up date is absolute, unlike api.wakeUpIn().

Arguments

  • day (integer): Day of the month (1 to 31).
  • hour (integer): Hour (0 to 23).
  • minute (integer): Minute (0 to 59).
  • second (integer): Second (0 to 59).
  • resetOnFail (integer, optional): Reboot device if setting the wake-up fails:
    • 1: True.
    • 0 or omitted: False.

Return

  • status (integer): 0 for success, -1 for error.

Example

-- Schedules next wake-up to the 25th at 2:22:58
status = api.wakeUpAt(25, 2, 22, 58)

api.wakeUpIn(day, hour, minute, second, resetOnFail, millisecond)


status = api.wakeUpIn(1, 0, 122, 0)

Schedules the next wake-up event after a specified time interval.

Info: The wake-up date is relative, unlike api.wakeUpAt().

Note: Arguments are not limited, but the total period must not exceed 31 days (e.g., hour = 40, days = 2 gives 3 days and 16 hours).

Arguments

  • day (integer): Days (0 to 31).
  • hour (integer): Hours (0 to 2,147,483,647).
  • minute (integer): Minutes (0 to 2,147,483,647).
  • second (integer): Seconds (0 to 2,147,483,647).

Optional

  • resetOnFail (integer, optional): Reboot device if setting the wake-up fails:
    • 1: True.
    • 0 or omitted: False.
  • millisecond (integer, optional): Milliseconds (0 to 2,147,483,647).

Return

  • status (integer): 0 for success, -1 for error.

Example

-- Schedules next wake-up in 1 day and 122 minutes
status = api.wakeUpIn(1, 0, 122, 0)

--------------------------------

-- This code handles whther the next action is beacon or gather, and schedules said action
if insec >= insecb or (pDays == 0 and pHrs == 0 and pMins == 0) then
print("beacon next", insec, insecb)
nextWR = 0 -- next is beacon
api.wakeUpIn(0,0,0,insecb)
else
print("gather next",insec, insecb)
nextWR = 1 -- next is gather
api.wakeUpIn(0,0,0,insec)

api.getTimeDate(timezoneShift)


y, M, d, h, m, s = api.getTimeDate()

Returns the current date and time set on the device.

Info: Time can be synchronized over LoRa or when uploading a Lua script using the Lua scripting interface.

Arguments

  • timezoneShift (integer, optional): Return time zone shift:
    • 1: ON.
    • 0: OFF.

Return

  • year (integer): Current year.
  • month (integer): Current month.
  • day (integer): Current day of the month.
  • hour (integer): Current hour.
  • minute (integer): Current minute.
  • second (integer): Current second.

Optional

  • time zone shift (integer, optional): Time zone shift in minutes.

Example

-- Read current date and time
y, M, d, h, m, s = api.getTimeDate()

--------------------------------

-- Here is getTimeDate used to generate a timestamp for a beacon used in JSON sent by an MQTT script
local function sendBeacon(rcntr, reason, uptime, sinceTau, lastGatherTs, lastBeaconTs, version)
lBTs = ns()
local ans, res = api.nbAT("AT+CSQ", 6000, nil, "+CSQ:", "99", 3)
local tn = mqtt_topic_base .. "beacon"
local y,M,d,h,m,sec = api.getTimeDate()
json("signal", tonumber(string.match(ans, "+CSQ: ([0-9]+),%d.*")) or 0, 1)
json("relative-message-counter", rcntr)
json("time", string.format("%04d-%02d-%02dT%02d:%02d:%02d", y,M,d,h,m,sec))
json("wake-up-reason", reason)
json("uptime-seconds", uptime)
json("power-mV", api.getBatteryVoltage())
json("lua-version", version)
MQTT_publishJson(tn)

api.setTimeDate()

Set date and time on this device, or calculate the difference and synchronize the date and time.

API NameBrief Description
api.setTimeDate(year, month, day, hour, minute, second, subsecond, timezone)Set date and time on this device, or calculate the difference and synchronize the date and time.
api.setTimeDate("DIFF", day, hour, minute, second)Calculates and synchronizes the device date and time if it differs from the provided day (1-31), hour (0-23), minute (0-59), and second (0-59).

api.setTimeDate(year, month, day, hour, minute, second, subsecond, timezone)


api.setTimeDate(2025, 5, 6, 12, 0, 0) -- set date/time

Sets the date and time on the device.

Arguments

  • year (integer): Year (2016 or greater).
  • month (integer): Month (1 to 12).
  • day (integer): Day (1 to 31).
  • hour (integer): Hour (0 to 23).
  • minute (integer): Minute (0 to 59).
  • second (integer): Second (0 to 59).

Optional

  • subsecond (integer, optional): Subsecond.
  • timezone (integer, optional): Time zone shift in minutes.

Example

-- Set date and time
api.setTimeDate(2022, 1, 31, 23, 59, 0)

api.setTimeDate("DIFF", day, hour, minute, second)


api.setTimeDate("DIFF", 31, 23, 59, 0) -- sync time

Calculates and synchronizes the device date and time if it differs from the provided day, hour, minute, and second.

Arguments

  • "DIFF" (string, command)

❗command - the argument needs to have this exact form❗

  • day (integer): Day (1 to 31).
  • hour (integer): Hour (0 to 23).
  • minute (integer): Minute (0 to 59).
  • second (integer): Second (0 to 59).

Example

-- Synchronize date and time
api.setTimeDate("DIFF", 31, 23, 59, 0)

api.voltageSourceState()

Controls voltage source.

API NameBrief Description
api.voltageSourceState(state, voltage)Controls voltage source.
api.voltageSourceState("measure", voltage)Returns the source voltage value for the specified voltage source.
api.voltageSourceState("set-comp-value", voltage)Sets the comparator value for the specified voltage source.
api.voltageSourceState("get-comp-value", voltage)Returns the comparator value for the specified voltage source.

api.voltageSourceState(state, voltage)


api.voltageSourceState(1) -- turn on voltage source

Controls the voltage source.

Warning: Only available for variants with a voltage source. Adjustable voltage is only available for variants with an adjustable voltage source.

Arguments

  • state (integer): 1 for ON, 0 for OFF.
  • voltage (integer, optional): Sets the voltage (mV) to the closest possible value (only for adjustable voltage variants).

Example

-- Turn on voltage source
api.voltageSourceState(1)

--------------------------------

-- Turn off voltage source
api.voltageSourceState(0)

--------------------------------

-- RS45 external power up
function RS485ExternalPower(state)
print("Setting up RS485 and External power state to: " .. state)
api.voltageSourceState(state)
if state == 1 then
api.delayms(500) -- Allow RS485-IRDA heads to bootup
end
end

api.voltageSourceState("measure", voltage)


value = api.voltageSourceState("measure") -- measure voltage

Returns the source voltage value for the specified voltage source.

Warning: Only available for variants with a voltage source. Adjustable voltage is only available for variants with an adjustable voltage source.

Arguments

  • "measure" (string, command)

    ❗command - the argument needs to have this exact form❗

  • voltage (integer, optional): Sets the voltage (mV) to the closest possible value (only for adjustable voltage variants).

Example

-- Measure voltage source
value = api.voltageSourceState("measure")

api.voltageSourceState("set-comp-value", voltage)


api.voltageSourceState("set-comp-value", 3300) -- set comparator

Sets the comparator value for the specified voltage source.

Warning: Only available for variants with a voltage source. Adjustable voltage is only available for variants with an adjustable voltage source.

Arguments

  • "set-comp-value" (string, command)

❗command - the argument needs to have this exact form❗

  • voltage (integer, optional): Sets the voltage (mV) to the closest possible value (only for adjustable voltage variants).

Example

-- Set comparator value
api.voltageSourceState("set-comp-value", 3300)

api.voltageSourceState("get-comp-value", voltage)


value = api.voltageSourceState("get-comp-value") -- get comparator

Returns the comparator value for the specified voltage source.

Warning: Only available for variants with a voltage source. Adjustable voltage is only available for variants with an adjustable voltage source.

Arguments

  • "get-comp-value" (string, command)

❗command - the argument needs to have this exact form❗

  • voltage (integer, optional): Sets the voltage (mV) to the closest possible value (only for adjustable voltage variants).

Return

  • value (integer): Comparator value.

Example

-- Get comparator value
value = api.voltageSourceState("get-comp-value")

api.stdin()

Reads stdin (standard input) data or control button (get status, wait for button).

API NameBrief Description
api.stdin("start", size)Starts reading standard input data with an optional memory size (default 1024).
api.stdin("stop")Stops reading standard input data.
api.stdin("waitbutton", timeout)Waits for a control button press with an optional timeout (default 0).
api.stdin("read", maxsize)Reads standard input data up to an optional maximum size (default 0).
api.stdin("readblock", maxsize, timeout)Reads a block of standard input data up to an optional maximum size (default 0) with an optional timeout (default 0).
api.stdin("readuntil", maxsize, stopByte, timeout)Reads standard input data up to an optional maximum size (default 0) until a specified stop byte (default "\n") or an optional timeout (default 0).

api.stdin("start", size)


api.stdin("start", 1024) -- begin buffered stdin

Starts reading standard input data with an optional memory size.

Note: Uses the serial line, so it cannot be used in an interactive console (GUI).

Arguments

  • "start" (string, command)

❗command - the argument needs to have this exact form❗

  • size (integer, optional): Memory size (default: 1024).

Example

-- Start reading stdin
api.stdin("start", 1024)

api.stdin("stop")


api.stdin("stop") -- stop stdin capture

Stops reading standard input data.

Note: Uses the serial line, so it cannot be used in an interactive console (GUI).

Arguments

  • "stop" (string, command)

❗command - the argument needs to have this exact form❗

Example

-- Stop reading stdin
api.stdin("stop")

api.stdin("waitbutton", timeout)


res = api.stdin("waitbutton", 1000) -- wait up to 1s

Waits for a control button press with an optional timeout.

Note: Uses the serial line, so it cannot be used in an interactive console (GUI).

Arguments

  • "waitbutton" (string, command)

❗command - the argument needs to have this exact form❗

Optional

  • timeout (integer, optional): Default is 0.

Return

  • res (integer): -1 if failed, or time (in ms) when pressed since the function was called.

Example

-- Wait for button press
res = api.stdin("waitbutton", 1000)

api.stdin("read", maxsize)


num, data = api.stdin("read", 512) -- read up to 512 bytes

Reads standard input data up to an optional maximum size.

Note: Uses the serial line, so it cannot be used in an interactive console (GUI).

Arguments

  • "read" (string, command)

❗command - the argument needs to have this exact form❗

Optional

  • maxsize (integer, optional): Maximum data size (default: 0).

Return

  • num (integer): Received amount of bytes.
  • data (string): Received data.

Example

-- Read stdin data
num, data = api.stdin("read", 512)

api.stdin("readblock", maxsize, timeout)


num, data = api.stdin("readblock", 512, 1000) -- read a block with 1s timeout

Reads a block of standard input data up to an optional maximum size with an optional timeout.

Note: Uses the serial line, so it cannot be used in an interactive console (GUI).

Arguments

  • "readblock" (string, command)

❗command - the argument needs to have this exact form❗

Optional

  • maxsize (integer, optional): Maximum data size (default: 0).
  • timeout (integer, optional): Default is 0.

Return

  • num (integer): Received amount of bytes.
  • data (string): Received data.

Example

-- Read block of stdin data
num, data = api.stdin("readblock", 512, 1000)

api.stdin("readuntil", maxsize, stopByte, timeout)


num, data = api.stdin("readuntil", 512, "\n", 1000) -- stop at newline or 1s

Reads standard input data up to an optional maximum size until a specified stop byte or timeout.

Note: Uses the serial line, so it cannot be used in an interactive console (GUI).

Arguments

  • "readuntil" (string, command)

❗command - the argument needs to have this exact form❗

Optional

  • maxsize (integer, optional): Maximum data size (default: 0).
  • stopByte (integer, optional): Default is "\n".
  • timeout (integer, optional): Default is 0.

Return

  • num (integer): Received amount of bytes.
  • data (string): Received data.

Example

-- Read stdin until newline
num, data = api.stdin("readuntil", 512, "\n", 1000)

api.stdout(out, size, offset)


api.stdout("Hello, world!") -- raw write without newline

Writes to standard output (stdout) without adding line termination.

Tip: Useful for implementing raw serial protocols.

Arguments

  • out (string): String buffer to print to serial console (raw print).

Optional

  • size (integer, optional): Size of out to print (default: entire out).
  • offset (integer, optional): Number of bytes to skip in out (default: 0).

Example

-- Write to stdout
api.stdout("Hello, world!")

api.bsprintf(binData, format, offset, endian)


print(api.bsprintf(pack.pack("b4", 1, 2, 3, 4), "%d")) -- parse little-endian int

Formats binary stream data according to various format specifiers, including support for characters, integers, short and long integers, floats, and doubles.

Arguments

  • binData (string): String buffer to format.
  • format (string): Format specifier.

Optional

  • offset (integer, optional): Number of bytes to skip (default: 0).
  • endian (string, optional): "little" (default) or "big".

Supported Formats:

  • Character: "c"
  • Short integers: "hd", "hi", "hu", "hx", "hX", "ho", "hb", "h"
  • Long long integers: "lld", "lli", "llu", "llx", "llX", "llo", "llb", "ll"
  • Integers: "d", "i", "u", "x", "X", "o", "b"
  • Doubles: "e", "E", "g", "G", "lf"
  • Floats: "f", "F"

Example

-- Binary string
x = pack.pack("b8", 1, 2, 3, 4, 5, 6, 7, 8)
api.dumpArray(x) -- Output: 00 : 01 02 03 04 05 06 07 08

y = api.bsprintf(x, "%d") -- Format 4-byte integer, little endian
print(y) -- Output: 67305985

api.setVerbosity()

Controls the number of messages printed to the serial line.

API NameBrief Description
api.setVerbosity(num, opt)Controls the number of messages printed to the serial line.
api.setVerbosity(num, "TIMESTAMP_MODE")Sets the verbosity level with timestamp information when "TIMESTAMP_MODE" is specified.

api.setVerbosity(num, opt)


api.setVerbosity(4) -- INFO level

Controls the number of messages printed to the serial line.

Arguments

  • num (integer): General verbosity level:
    • 0: NONE
    • 1: IMPORTANT
    • 2: ERROR
    • 3: WARNING
    • 4: INFO (default)
    • 5: SLOW
    • 6: MAX

Optional

  • opt (string, optional): Specific function verbosity:
    • "LORA", "LORA_HW", "RADIO", "LORA_TIMER", "NBIOT", "RTC", "HWAPI_COMMON", "HWAPI_DALI", "HWAPI_DIO", "HWAPI_DS18B20", "HWAPI_LORA", "HWAPI_MBUS", "HWAPI_MEMORY", "HWAPI_RS485", "HWAPI_S0", "HWAPI_SENSIRION", "HWAPI_TIME", "HWAPI_UART", "HWAPI_WMBUS", "WMBUS_HW"

Example

-- Set verbosity to INFO
api.setVerbosity(4)

--------------------------------

-- Sets verbosity for the main module and M-Bus module before the scan
function scan(cfg, addonly, tout)
api.setVerbosity(4)
api.setVerbosity(4,"MBUS")
baud=api.getVar(16, baudDefault)
api.mbusSetup(baud,parity,stopBits,dataBits)
api.mbusState(1)
-- use 15 seconds initial delay (requirement of some devices)
api.delayms(15000)

api.setVerbosity(num, "TIMESTAMP_MODE")


api.setVerbosity(0, *"TIMESTAMP_MODE"*) -- disable timestamps

Sets the verbosity level with timestamp information when "TIMESTAMP_MODE" is specified.

Arguments

  • num (integer): Timestamp verbosity level:
    • 0: NONE
    • 1: TICK
    • 2: RTC_TICK
    • 3: TIME
    • 4: DATETIME

Optional

  • "TIMESTAMP_MODE" (string, optional)

    ❗command - the argument needs to have this exact form❗

Example

-- Turn off timestamp
api.setVerbosity(0, "TIMESTAMP_MODE")

api.exec()

Executes a system command or Lua fragment.

API NameBrief Description
api.exec("_get_wake_info")Returns information about the device's wake-up event.
api.exec("_free_mem")Returns the amount of free memory available on the device.
api.exec("_sysinfo")Provides system information about the device.
api.exec("_format_eeprom", filler)Erases the internal device EEPROM to an optional provided value.
api.exec("_get_last_error", reportType, action, start, end)Returns error information based on the specified report type ("SHORT", "TRACEBACK", "STDOUT", "STDOUT_RAW", "TRACEBACK_RAW", "ALL") and action ("len", "clear", or byte offset).
api.exec("_current_serial_log")Returns the current serial log from the device.
api.exec("_sleep", seconds, milliseconds)Puts the device to sleep for the specified seconds and milliseconds (default 0), without RTC timeout if seconds is 0.
api.exec("acrComTx", data)Sends a payload as an "acrCom" communication protocol frame.
api.exec("_reset", softReset)Performs a device reset, with an optional soft reset (1 for application-only restart).
api.exec("_interactive_line_maxlen", value)Sets the size of the input command buffer in bytes (default 2048).
api.exec("_cpu_temp")Returns the CPU temperature of the device.
api.exec("_acrComHeader", data)Computes the header for the provided string buffer using CRC16 calculation.
api.exec("_print_mode", mode)Configures print mode ("ALL", "CONNECTED", "NONE") to control serial output behavior.
api.exec("clearSwWdogNoCom")Clears the no-communication software watchdog.
api.exec("clearSwWdogNoSleep")Clears the no-sleep software watchdog.
api.exec("setSwWdogNoComReloadValue", value)Sets the no-communication watchdog reload value (default 7 days).
api.exec("setSwWdogNoSleepReloadValue", value)Sets the no-sleep watchdog reload value (default 3 days).
api.exec("_set_crlf_handler", mode)Configures CRLF handling ("noprint", "asis", "space", "newline") for serial output.
api.exec("_has_new_reset_log")Checks if a new reset log is available.
api.exec("_get_unix_time")Returns the current UNIX timestamp from the device.
api.exec("_set_unix_time", time)Sets the device's UNIX timestamp to the specified value.
api.exec("_serialInterrupt", enable, waitConfig)Enables or disables serial interrupts and optionally waits for configuration in the onWake function.
api.exec("_sysclk", clock)Sets the microcontroller clock speed in Hz (options: 100000 to 48000000).
api.exec("_reset_reason")Returns the reason for the last device reset.
api.exec("_sleep_mode", mode)Configures global sleep mode (1 for sleep if interval > 10 ms, 2 for defined milliseconds).
api.exec("_keep_source_in_sleep", state)Enables or disables keeping the power supply active during sleep (available for converters with power supply).
api.exec("_cc", cmd)Manages Coulomb Counter operations ("set" or "dump") or returns values if no command is provided (available for converters with Coulomb Counter).
api.exec("_sc", option)Controls supercapacitor connection (1 for connect, 0 for disconnect, -1 for floating).
api.exec("_SENSUS_BUP_parse", data, key, keyIndex)Parses input data using an optional key and key index, defaulting to a predefined key if none provided.
api.exec("_hw_features", option)Returns hardware feature report or checks specific features (e.g., "SIM7022", "SC", "NB") if an option is provided.
api.exec("_fastWake", state)Enables or disables fast wake mode (1 for enable, 0 for disable).
api.exec("_noNBIOTinit", state)Enables or disables NB-IoT initialization (1 for enable, 0 for disable).


api.exec("_get_wake_info")


local wakeup_status = api.exec("_get_wake_info")

Returns information about the device's previous wake-up event. It is in form of strings, that describe the wakr up reason, serial status and NB-IoT status (if NB-IoT device).

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_get_wake_info" (string, command)

    ❗command - the argument needs to have this exact form❗

Return

  • wake-up reason (string): "button", "serial", "timer".
  • serial status (string): "connected", "disconnected".

Only for NB-IoT Device

  • NB-IoT serial status (string): "active", "inactive".

Example

-- Get wake-up information
reason, serial, nbiot = api.exec("_get_wake_info")
print ("reason of waking: "..reason, "serial status: "..status, "NB-IoT: "..status)

api.exec("_free_mem")


print(api.exec("_free_mem").."bytes of memory remain")

Returns the amount of free memory available on the device.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_free_mem" (string, command)

    ❗command - the argument needs to have this exact form❗

Return

  • freeheap (integer): Free heap memory in bytes.

Example

-- Get free memory
freeheap = api.exec("_free_mem")

--------------------------------

-- Two phase use of _free_mem within two functions
function get_mem()
if memDebug then
print("freemem: ", api.exec("_free_mem"))
end
end

function createDataTable() -- Create Data Tables
get_mem()
api.table("set-max-id",3)
lowMemory=api.exec("_free_mem") < 80000
if lowMemory then
print("Low memory: creating smaller tables")
mbC=5
api.table("new", 2, "U32", mbC) -- ID
api.table("new", 1, "STR", mbC) -- payload
else
print("High memory: creating bigger tables")
mbC=16

api.table("new", 2, "U32", mbC) -- ID
api.table("new", 1, "STR", mbC) -- payload
end
get_mem()
insIDdataT=0
end

api.exec("_sysinfo")


local info = api.exec("_sysinfo")

Provides system information about the device.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_sysinfo" (string, command)

    ❗command - the argument needs to have this exact form❗

Return

  • values (table):
    • SN: Serial number (-1 for old devices).
    • ver: Firmware version (e.g., 2.9.12).
    • tim: Build time (hour, minute, second).
    • date: Build date (year, month, day).
    • model: Device model (name, source).

Example

-- Get system info
print(api.exec("_sysinfo")["model"]["name"]) -- e.g., ACR_CV_101N_R_EAC
print(api.exec("_sysinfo")["model"]["source"]) -- e.g., ac
local sysinfo = api.exec("_sysinfo") -- putting sysinfo into a variable

api.exec("_format_eeprom", filler)


api.exec("_format_eeprom")

Erases the internal device EEPROM to an optional provided value. Useful to ensure, that a device is clear if a major change is happening (using interactive mode is ideal for performing such action).

Info: Deletes last Lua error report and all values set by api.setVar().

Arguments

  • "_format_eeprom" (string, command)

    ❗command - the argument needs to have this exact form❗

Optional

  • filler (string, optional): Value to erase EEPROM to.

Example

-- Erase EEPROM
api.exec("_format_eeprom")

api.exec("_get_last_error", reportType, action, start, end)


local err = api.exec("_get_last_error", "SHORT", "len", 0, -1)

Returns error information based on the specified report type and action.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_get_last_error" (string, command)

    ❗command - the argument needs to have this exact form❗

Optional

  • reportType (string, optional): "SHORT", "TRACEBACK", "STDOUT", "STDOUT_RAW", "TRACEBACK_RAW", "ALL".
  • action (string/integer, optional): "len", "clear", or byte offset.
  • start (integer, optional): Start index of buffer.
  • end (integer, optional): End index of buffer (-1 for all).

Return

  • error (string): Last error entry.

Example

-- Get last error
error = api.exec("_get_last_error", "SHORT", "len", 0, -1)

--------------------------------

-- Function that returns error using the command
function err(...) return api.exec("_get_last_error", ...) end

api.exec("_current_serial_log")


local log = api.exec("_current_serial_log")

Returns the current serial log from the device.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_current_serial_log" (string, command)

    ❗command - the argument needs to have this exact form❗

Return

  • log (string): Serial log history (1024 bytes).

Example

-- Get serial log
log = api.exec("_current_serial_log")

--------------------------------

-- Command sent down to the device
elseif cmd == 10 then
e = api.exec("_current_serial_log")
e = string.sub(e,-500)
c,rxlen = tx(b(0xF1) .. "LOG:" .. e, tout)
e = nil

api.exec("_sleep", seconds, milliseconds)


api.exec("_sleep", 1, 0)

Puts the device to sleep for the specified seconds and milliseconds (default 0), without RTC timeout if seconds is 0.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • seconds (integer, optional): Default is 0.
  • milliseconds (integer, optional): Default is 0.

Example

-- Sleep for 1 second
api.exec("_sleep", 1, 0)

--------------------------------

-- Command specifying how long a device should sleep
elseif cmd == 11 then
noSl = 1
nextWR = 1
_,spe,Ssec,Tsec,lDays,lHrs,lMins,Msec,ift,deferred = pu(c, "b9", 1) -- temporary change only, reloaded onWake()
if deferred == 1 then
print("Sleep before gathering...")
api.exec("_sleep", lDays*86400+lHrs*3600+lMins*60)
elseif deferred == 2 then
print("Sleep before gathering & update GTs...")
api.exec("_sleep", lDays*86400+lHrs*3600+lMins*60)
lGTs = ns()
end

api.exec("acrComTx", data)


api.exec("acrComTx", "data")

Sends a payload as an "acrCom" communication protocol frame.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "acrComTx" (string, command)

    ❗command - the argument needs to have this exact form❗

  • data (string): Payload for "acrCom" protocol.

Example

-- Send acrCom payload
api.exec("acrComTx", "data")

api.exec("_reset", softReset)


api.exec("_reset", 1)

Performs a device reset, with an optional soft reset.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_reset" (string, command)

    ❗command - the argument needs to have this exact form❗

Optional

  • softReset (integer, optional): 1 for soft reset (restart application only).

Example

-- Perform soft reset
api.exec("_reset", 1)

--------------------------------

-- Piece of code re attempting to connect to LoRaWAN on boot
for i = 1, 5 do
status, _, answer = api.loraSend(1, timeout, bootMsg, port)
if status >= 0 then break
elseif i == 5 and status < 0 then
print("Failed to send boot message to LoRaWAN, restarting ...")
api.exec("_reset")
end
timeout = timeout + 2000
end

api.exec("_interactive_line_maxlen", value)


local length = api.exec("_interactive_line_maxlen", 2048)

Sets the size of the input command buffer in bytes.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_interactive_line_maxlen" (string, command)

    ❗command - the argument needs to have this exact form❗

Optional

  • value (integer, optional): Size of input buffer (default: 2048 bytes).

Return

  • length (integer): Max length of input for interactive mode.

Example

-- Set interactive line max length
length = api.exec("_interactive_line_maxlen", 2048)

api.exec("_cpu_temp")


local temp = api.exec("_cpu_temp")

Returns the CPU temperature of the device.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_cpu_temp" (string, command)

    ❗command - the argument needs to have this exact form❗

Return

  • temperature (integer): CPU temperature in Celsius (±5°C).

Example

-- Get CPU temperature
temp = api.exec("_cpu_temp")

--------------------------------

-- Function that prints all the information upon booting, includes CPU temperature
function bootMessage (joinMethod, rxTimeout, port)
local sysinfo = ex("_sysinfo")
model = sysinfo["model"]["name"]
sn = sysinfo["SN"]
fwma = sysinfo["ver"]["major"]
fwmi = sysinfo["ver"]["minor"]
fwbf = sysinfo["ver"]["bugfix"]
local battVol = api.getBatteryVoltage()
local cpuTemp = ex("_cpu_temp")
local bootMsg = model .. b(0) .. pp("<i", sn) .. b(fwma) .. b(fwmi) .. b(fwbf) .. ver .. pp("<i", battVol) .. b(cpuTemp)
local msgPrint = "Model: " .. model .. ", Serial number: " .. sn .. ", FW version: " .. fwma .. "." .. fwmi .. "." .. fwbf .. ", Script version: " .. ver .. ", Battery voltage: " .. battVol .. " mV, CPU temperature: " .. cpuTemp .. " C"
print(msgPrint)

api.exec("_acrComHeader", data)


local header = api.exec("_acrComHeader", "data")

Computes the header for the provided string buffer using CRC16 calculation.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_arcComGeader" (string, command)

    ❗command - the argument needs to have this exact form❗

  • data (string): Buffer to compute header from.

Return

  • header (string): 7-byte ACR-COM header.

Example

-- Compute ACR-COM header
header = api.exec("_acrComHeader", "data")

if cmd == 15 then
api.nbReceiveBuffer(nbrbidx+10, 7, api.exec("_acrComHeader", raw))
api.nbReceiveBuffer(nbrbidx+17, #raw, raw)
end

api.exec("_print_mode", mode)


api.exec("_print_mode", "CONNECTED")

Configures print mode to control serial output behavior.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_print_mode" (string, command)

    ❗command - the argument needs to have this exact form❗

  • mode (string): "ALL", "CONNECTED", "NONE".

Return

  • mode (string): Print mode.

Example

-- Set print mode to CONNECTED
api.exec("_print_mode", "CONNECTED")

--------------------------------

-- Ensuring printing to serial happens only when needed
function onStartup()
print("--- NB-IoT - S0 default script ---")

-- print to serial only when serial is connected
api.exec("_print_mode", "CONNECTED")

api.exec("clearSwWdogNoCom")


api.exec("clearSwWdogNoCom")

Clears the no-communication software watchdog.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "clearSwWdogNoCom" (string, command)

    ❗command - the argument needs to have this exact form❗

Example

-- Clear no-communication watchdog
api.exec("clearSwWdogNoCom")

if top ~= nil then
api.exec("clearSwWdogNoCom")
end

api.exec("clearSwWdogNoSleep")


api.exec("clearSwWdogNoSleep")

Clears the no-sleep software watchdog.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "clearSwWdogNoSleep" (string, command)

    ❗command - the argument needs to have this exact form❗

Example

-- Clear no-sleep watchdog
api.exec("clearSwWdogNoSleep")

--------------------------------

-- Clear no-sleep watchdog onWake in MQTT script
function onWake()
api.getTick(0,1)
api.exec("_sysclk", "48000000")
api.exec("clearSwWdogNoSleep")
api.exec("_print_mode","CONNECTED")
MQTT_SSL_Start()
if not MQTT_checkConnected() then
MQTT_stop()
MQTT_SSL_Start()
end

api.exec("setSwWdogNoComReloadValue", value)


api.exec("setSwWdogNoComReloadValue", 7)

Sets the no-communication watchdog reload value.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "clearSwWdogNoComReloadValue" (string, command)

    ❗command - the argument needs to have this exact form❗

  • value (integer): No-communication watchdog value (default: 7 days).

Example

-- Set no-communication watchdog value
api.exec("setSwWdogNoComReloadValue", 7)

--------------------------------

function onStartup()
print("--- NB-IoT - S0 default script ---")

-- print to serial only when serial is connected
api.exec("_print_mode", "CONNECTED")

-- set APN and PLMNID explicitely
api.nbAT("APN=" .. APN)
api.nbAT("PLMNID=" .. PLMNID)

api.exec("setSwWdogNoComReloadValue", noComWdg)

api.exec("setSwWdogNoSleepReloadValue", value)


api.exec("setSwWdogNoSleepReloadValue", 3)

Sets the no-sleep watchdog reload value.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "clearSwWdogNoSleepReloadValue" (string, command)

    ❗command - the argument needs to have this exact form❗

  • value (integer): No-sleep watchdog value (default: 3 days).

Example

-- Set no-sleep watchdog value
api.exec("setSwWdogNoSleepReloadValue", 3)

api.exec("_set_crlf_handler", mode)


api.exec("_set_crlf_handler", "newline")

Configures CRLF handling for serial output.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_set_ctrlf_handler" (string, command)

    ❗command - the argument needs to have this exact form❗

  • mode (string): "noprint", "asis", "space", "newline".

Example

-- Set CRLF handling to newline
api.exec("_set_crlf_handler", "newline")

api.exec("_has_new_reset_log")


local hasNew = api.exec("_has_new_reset_log")

Checks if a new reset log is available.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_has_new_reset_log" (string, command)

    ❗command - the argument needs to have this exact form❗

Return

  • flag (boolean): Asynchronous serial log detected.

Example

-- Check for new reset log
flag = api.exec("_has_new_reset_log")

--------------------------------

-- Sending last error, if there is a new one in the onStartup() procedure
if ex("_has_new_reset_log") then
sendError("STDOUT_RAW", 10, 120, usedInterfaces)
end

api.exec("_get_unix_time")


local unixTime = api.exec("_get_unix_time")

Returns the current UNIX timestamp from the device.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_get_unix_time" (string, command)

    ❗command - the argument needs to have this exact form❗

Return

  • time (integer): UNIX timestamp.

Example

-- Get UNIX timestamp
time = api.exec("_get_unix_time")

function prepareDataTable(tn,save) -- Prepare JSON data for Publishing (topic)
for idx=1, insIDdataT do
local payload=api.table("get-index", 1, idx)
local id=api.table("get-index", 2, idx)
local utime=api.exec("_get_unix_time")
json("ID", id, 1)
json("send-time",utime)
json("raw-data", payload)
MQTT_publishJson(tn .. id .. "/raw")
end
clearDataTable(save)
end

api.exec("_set_unix_time", time)


api.exec("_set_unix_time", 1625097600)

Sets the device's UNIX timestamp to the specified value.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_set_unix_time" (string, command)

    ❗command - the argument needs to have this exact form❗

  • time (integer): UNIX timestamp.

Example

-- Set UNIX timestamp
api.exec("_set_unix_time", 1625097600)

api.exec("_serialInterrupt", enable, waitConfig)


api.exec("_serialInterrupt", true, false)

Enables or disables serial interrupts and optionally waits for configuration in the onWake function.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_serialInterrupt" (string, command)

    ❗command - the argument needs to have this exact form❗

  • enable (boolean): true to enable, false to disable.

  • waitConfig (boolean): Wait for config in onWake.

Example

api.exec("_serialInterrupt", true, false) -- Enable serial interrupts

api.exec("_sysclk", clock)


api.exec("_sysclk", 32000000)

Sets the microcontroller clock speed in Hz.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_sysclk" (string, command)

    ❗command - the argument needs to have this exact form❗

  • clock (integer): Clock speed in Hz (pick one of these options):

    • 32000000 - 32000000 Hz (default)
    • 48000000 - 48000000 Hz
    • 24000000 - 24000000 Hz
    • 16000000 - 16000000 Hz
    • 2000000 - 2000000 Hz
    • 1000000 - 1000000 Hz
    • 800000 - 800000 Hz
    • 400000- 400000 Hz
    • 200000 - 200000 Hz
    • 100000 - 100000 Hz

Return

  • clock (integer): Microcontroller clock in Hz.

Example

-- Set clock speed to 32 MHz
api.exec("_sysclk", 32000000)

api.exec("_reset_reason")


api.exec("_reset_reason")

Returns the reason for the last device reset.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_reset_reason" (string, command)

    ❗command - the argument needs to have this exact form❗

Return

  • number (integer): Reset reason number.
  • reason (string): Reset reason.

Example

-- Get reset reason
number, reason = api.exec("_reset_reason")

--------------------------------

-- Process resulting in the print of the last reset reason
api.exec("_noNBIOTinit",1)
api.nbAT("APN=auto")
awT = 0
api.nbAT("ON_TAU_EVENT",1)
api.nbAT("SLEEP_MONITOR",1)
local resRStr
resR, resRStr = api.exec("_reset_reason")
print("Reset - " .. resRStr)

api.exec("_sleep_mode", mode)


api.exec("_sleep_mode", 1)

Configures global sleep mode.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_sleep_mode" (string, command)

    ❗command - the argument needs to have this exact form❗

  • mode (integer):

    • 1 (sleep if interval > 10 ms)
    • 2 (sleep for defined ms)

Return

  • mode (integer): Global sleep mode.

Example

-- Set sleep mode
api.exec("_sleep_mode", 1)

--------------------------------

mBusControl(1)
api.exec("_sleep_mode",99)
api.ledControl(1,0,0,0,"L123456789H987654321LLLLL", 50) -- LED Signalization M-Bus scan process
--mbusSecondary(SSCAN, nil) -- Uncomment for initial secondary scan
mbusPrimary(0,252,nil) -- Uncomment for initial primary scan
api.exec("_sleep_mode",0)

api.exec("_keep_source_in_sleep", state)


api.exec("_keep_source_in_sleep", 1)

Enables or disables keeping the power supply active during sleep.

Info: Only available for converters with power supply. Supports Configuration API extension as per IEEE document.

Arguments

  • "_keep_source_in_sleep" (string, command)

    ❗command - the argument needs to have this exact form❗

  • state (integer):

    • 1 to enable.
    • 0 to disable.

Return

  • state (integer): Supply status during sleep.

Example

-- Keep power supply on during sleep
api.exec("_keep_source_in_sleep", 1)

api.exec("_cc", cmd, value)


api.exec("_cc")

Manages Coulomb Counter operations ("set" or "dump") or returns values if no command is provided.

Info: Only available for converters with Coulomb Counter. Supports Configuration API extension as per IEEE document.

Arguments

  • "_cc" (string, command)

    ❗command - the argument needs to have this exact form❗

Optional

  • cmd (string, optional): "set", "dump", or none.
    • For "set": value (integer): Value to set.
    • For "dump": No additional arguments.
  • value (integer): if "set" was used.

Return

  • "set": result (integer, 0 for success).
  • "dump": Dumps registers from the Coulomb Counter.
  • Default:
    • result (integer): Result of register readout (0 for success).
    • mAh (integer): Accumulated charge in mAh.
    • ESR (integer): Equivalent Series Resistance estimate of battery (mOhm).
    • in100V (integer): Input voltage at 100 mA (mV).
    • inV (integer): Input voltage in ultra-low power mode (mV).
    • SC100 (integer): Output voltage at 100 mA (mV).
    • SC (integer): Output voltage in ultra-low power mode (mV).
    • temp (integer): Temperature in °C.

Example

-- Set Coulomb Counter
api.exec("_cc", "set", 100)

--------------------------------

if api.exec("_hw_features", "CC:1") or false then
local res1,res2,res3,res4,res5,res6,res7,res8 = api.exec("_cc")
json("consumed-energy", res2)
json("input-voltage", res4)
json("system-voltage", res6)
json("temperature", res8)
end
MQTT_publishJson(tn)

api.exec("_sc", option)


api.exec("_sc", 1)

Controls supercapacitor connection.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_sc" (string, command)

    ❗command - the argument needs to have this exact form❗

  • option (integer):

    • 1 to connect.
    • 0 to disconnect.
    • -1 floating.

Example

-- Connect supercapacitor
api.exec("_sc", 1)

--------------------------------

-- forcing connection in onWake()
function onWake ()

if hasAdvancedSCManagement then
api.exec("_sc", 1) -- force connection of
end

api.exec("_SENSUS_BUP_parse", data, key, keyIndex)


api.exec("_SENSUS_BUP_parse", "data")

Parses input data using an optional key and key index, defaulting to a predefined key if none provided.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • data (string): Input data to parse.

Optional

  • key (string, optional): Default key if omitted.
  • keyIndex (integer, optional): Key index.

Return

  • meterId (string): Meter ID.
  • value (string): Value.
  • flags (string): Flags.
  • frameType (string): Frame type.
  • originalFrame (string): Original frame.

Example

-- Parse Bubble Up Protocol message
meterId, value, flags, frameType, original = api.exec("_SENSUS_BUP_parse", "data")

--------------------------------

-- Checking if BUP is used and parsing its data
if raw ~= nil then
if mtbl[curMode][1]:sub(1,3) == "BUP" then
if api.exec("_SENSUS_BUP_parse", raw, bupKey) == 0 then
print("Rxed BUP!")
break
end
raw = nil
else
print("Rxed!")
break
end
end

api.exec("_hw_features", option)


api.exec("_hw_features")

Returns hardware feature report or checks specific features if an option is provided.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_hw_features" (string, command)

    ❗command - the argument needs to have this exact form❗

Optional

  • option (string, optional): Specific hardware feature (e.g., "SIM7022", "SC", "NB").

Return

  • hwCheck (boolean): Feature presence.
  • boardVersion (string): Board version.
  • productionTime (string): Production time.
  • featureSet (string): Feature set.
  • variantChar1-4 (string): Variant characters.
  • variantMajor (string): Variant major version.
  • variantMinor (string): Variant minor version.
  • variantBugfix (string): Variant bugfix version.
  • variantFormFactor (string): Variant form factor.

Example

-- Check for specific hardware feature
hasNGMbus = api.exec("_hw_features", "MBUSNG:1")
print(hasNGMbus) -- Returns true/false

--------------------------------

-- Checking for compatible HW within onStartup()
function onStartup()

print("NBIoT - MQTT MBus , V"..ver)
if not api.exec("_hw_features", "SIM7022:1") then
print("Your hardware is not supported!")
api.ledControl(1)
while true do end
end

api.exec("_fastWake", state)


api.exec("_fastWake", 1)

Enables or disables fast wake mode, skipping the onWake() event.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • "_fastWake" (string, command)

    ❗command - the argument needs to have this exact form❗

  • state (integer):

    • 1 to enable.
    • 0 to disable.

Example

-- Enable fast wake mode
api.exec("_fastWake", 1)

api.exec("_noNBIOTinit", state)


api.exec("_noNBIOTinit", 1)

Enables or disables NB-IoT initialization.

Info: Supports Configuration API extension as per IEEE document.

Arguments

  • state (integer):
    • 1 to enable.
    • 0 to disable.

Example

-- Disable NB-IoT initialization
api.exec("_noNBIOTinit", 0)

--------------------------------

-- Enable NB-IoT initialization
api.exec("_noNBIOTinit", 1)

api.table()

Interface to create and manipulate memory-efficient tables and maps.

API NameBrief Description
api.table("set-max-id", maxId)Sets the maximum table index to the specified value (must be >= 1).
api.table("get-max-id")Returns the current maximum table index.
api.table("new", tableId, type, maxLength)Creates a new table with the specified ID, type ("U32", "I8", "U32-I8", "STR"), and maximum number of entries.
api.table("dispose", tableId)Disposes of the table with the specified ID.
api.table("insert", tableId, value)Inserts a value (integer for U32/I8, key-value for U32-I8, string for STR) into the table with the specified ID.
api.table("index-of", tableId, value)Returns the index of the specified value in the table with the given ID.
api.table("get-index", tableId, index)Returns the value at the specified index or key in the table with the given ID.
api.table("get-index-length", tableId, index)Returns the length of the value at the specified index or key in the table with the given ID.
api.table("set-index", tableId, index, value)Sets the value at the specified index or key in the table with the given ID.
api.table("used", tableId)Checks if the table with the specified ID is in use.
api.table("clear", tableId)Clears all entries in the table with the specified ID.

api.table("set-max-id", maxId)


api.table("set-max-id", 1)

Sets the maximum table index to the specified value.

Tip: Check multimode script or sendOnce script for examples.

Arguments

  • "set-max-id" (string, command)

    ❗command - the argument needs to have this exact form❗

  • maxId (integer): Maximum table index (>= 1).

Example

-- Set maximum table index
api.table("set-max-id", 1)

--------------------------------

function onStartup()

--set table to maximum 255 id (= maximum Modbus ID)
api.table("set-max-id", 254)

api.table("get-max-id")


api.table("get-max-id")

Returns the current maximum table index.

Tip: Check multimode script or sendOnce script for examples.

Return

  • maxId (integer): Maximum table index.

Example

-- Get maximum table index
maxId = api.table("get-max-id")

api.table("new", tableId, type, maxLength)


api.table("new", 1, "STR", 100)

Creates a new table with the specified ID, type, and maximum number of entries.

Tip: Check multimode script or sendOnce script for examples.

Arguments

  • "new" (string, command)

    ❗command - the argument needs to have this exact form❗

  • tableId (integer): ID of the new table (use set-max-id first).

  • type (string): Table type ("U32", "I8", "U32-I8", "STR").

  • maxLength (integer): Maximum number of table entries.

Example

-- Create a new string table
api.table("new", 1, "STR", 100)

--------------------------------

function createDataTable() -- Create Data Tables
get_mem()
api.table("set-max-id",3)
lowMemory=ex("_free_mem") < 80000
if lowMemory then
print("Low memory: creating smaller tables")
mbC=5
api.table("new", 2, "U32", mbC) -- ID
api.table("new", 1, "STR", mbC) -- payload
else
print("High memory: creating bigger tables")
mbC=16

api.table("new", 2, "U32", mbC) -- ID
api.table("new", 1, "STR", mbC) -- payload
end
get_mem()
insIDdataT=0

api.table("dispose", tableId)


api.table("dispose", 1)

Disposes of the table with the specified ID.

Tip: Check multimode script or sendOnce script for examples.

Arguments

  • "dispose" (string, command)

    ❗command - the argument needs to have this exact form❗

  • tableId (integer): ID of the table to delete.

Example

-- Dispose of table
api.table("dispose", 1)

--------------------------------

-- remove table command
elseif cmd == 4 then
pos, ModAdd = pack.unpack(rx, "b", pos)
api.table("dispose",ModAdd)
sendmsg(pack.pack("b",0xF4)..ModAdd,true)

api.table("insert", tableId, value)


api.table("insert", 1, "Hello")

Inserts a value (integer for U32/I8, key-value for U32-I8, string for STR) into the table with the specified ID.

Tip: Check multimode script or sendOnce script for examples.

Arguments

  • "insert" (string, command)

    ❗command - the argument needs to have this exact form❗

  • tableId (integer): Table ID.

  • value (integer or string): Value to insert (depends on table type).

  • For U32-I8: Additional key (integer).

Return

  • status (integer): 0 on success.
  • used (integer): Number of entries in the table.
  • maxLength (integer): Maximum number of entries in the table.

Example

-- Insert string into table
api.table("insert", 1, "Hello")

--------------------------------

-- Function that adds new entries to a table
function addToTable(id,payload)
print("Adding to Data Tables",id,payload)
api.table("insert", 2, id)
api.table("insert", 1, payload)
insIDdataT=insIDdataT + 1
get_mem()
end

api.table("index-of", tableId, value)


api.table("index-of", 1, "Hello")

Returns the index of the specified value in the table with the given ID.

Tip: Check multimode script or sendOnce script for examples.

Arguments

  • "index-of" (string, command)

    ❗command - the argument needs to have this exact form❗

  • tableId (integer): Table ID.

  • value (integer or string): Value to search for.

Return

  • index (integer): Index of the first occurrence of value in the table, nil if not found.

Example

-- Get index of value
s = api.table("index-of", 1, "Hello")
print(s) -- Output: 1

--------------------------------

-- checking whether index of a table is filled
if api.table("index-of", 1, ri) ~= nil then
print(string.format("%08X",ri), " already rcvd.")

api.table("get-index", tableId, index)


api.table("get-index", 1, 1)

Returns the value at the specified index or key in the table with the given ID.

Tip: Check multimode script or sendOnce script for examples.

Arguments

  • "get-index" (string, command)

    ❗command - the argument needs to have this exact form❗

  • tableId (integer): Table ID.

  • index (integer): Key or index to read.

Return

  • value (integer or string): Value at given index, nil if not found.

Example

-- Get value at index
y = api.table("get-index", 1, 1)
print(y) -- Output: Hello

--------------------------------

for idx = 1, mtC do
print("Sending Idx :" .. tostring(idx))
local rft = modeToStr(tonumber(api.table("get-index", 5, idx))) -- mode to string
sendSingleMeter(api.table("get-index", 6, idx),rft , tb("get-index", 4, idx),
api.table("get-index", 3, idx), api.table("get-index", 2, idx))
end

api.table("get-index-length", tableId, index)


api.table("get-index-length", 1, 1)

Returns the length of the value at the specified index or key in the table with the given ID.

Tip: Check multimode script or sendOnce script for examples.

Arguments

  • "get-index-length" (string, command)

    ❗command - the argument needs to have this exact form❗

  • tableId (integer): Table ID.

  • index (integer): Key or index to get length.

Return

  • length (integer): Length of the value at given index, nil if not found.

Example

-- Get length of index
a = api.table("get-index-length", 1, 1)
print(a) -- Output: 5

api.table("set-index", tableId, index, value)


api.table("set-index", 1, 1, "Updated")

Sets the value at the specified index or key in the table with the given ID.

Tip: Check multimode script or sendOnce script for examples.

Arguments

  • "set-index" (string, command)

    ❗command - the argument needs to have this exact form❗

  • tableId (integer): Table ID.

  • index (integer): Key or index to set.

  • value (integer): Value to set.

Example

-- Set value at index
api.table("set-index", 1, 1, "Updated")

api.table("used", tableId)


api.table("used", 1)

Checks if the table with the specified ID is in use.

Tip: Check multimode script or sendOnce script for examples.

Arguments

  • "used" (string, command)

    ❗command - the argument needs to have this exact form❗

  • tableId (integer): Table ID to check.

Return

  • used (integer): Number of entries in the table.

Example

-- Check table usage
used = api.table("used", 1)

function onWake()
for tableNum = 1, 254 do
if api.table("used", tableNum) ~= -1 then
for index = 1, perdev do
local configStr = api.table("get-index", tableNum, index)
if configStr == nil or #configStr == 0 then
break
else
processRequest(configStr,false)
end
end
else
break
end
end

api.table("clear", tableId)


api.table("clear", 1)

Clears all entries in the table with the specified ID.

Tip: Check multimode script for examples.

Arguments

  • "clear" (string, command)

    ❗command - the argument needs to have this exact form❗

  • tableId (integer): Table ID to clear.

Example

-- Clear table
api.table("clear", 1)

--------------------------------

-- clear index
elseif cmd == 3 then
pos, ModAdd, index = pack.unpack(rx, "b2", pos)
api.table("clear",ModAdd,index)
sendmsg(pack.pack("b",0xF3)..ModAdd..index,true)

api.aes(operation, data, iv, key)


api.aes("encrypt", "data", "0000000000000000", "0000000000000000")

Encrypts or decrypts a payload using AES-CTR with a key and initialization vector.

Tip: See this section for more information and examples.

Arguments

  • operation (string):
    • "encrypt" to encrypt.
    • "decrypt" to decrypt.
  • data (string): Data to encode or decode.
  • iv (string): Initialization vector (16 bytes).
  • key (string): Key (16 bytes).

Example

-- Assemble initialization vector
function getIV()
return pack.pack("<I4", wmbusID, wmbusID, transmissionCounter, transmissionCounter)
end

-- Encrypt payload
encpayload = api.aes("encrypt", payload, getIV(), key)