Superstack Lua reference


Superstack devices such as the S2 Module run Lua. You upload your code with the Superstack CLI, and the device runs it. This reference lists every function your code can call to read sensors, drive IO, make web requests and receive messages from your application.

Each function runs C code in the firmware. Lua can’t reach the parts of the firmware that check in with Superstack and install updates, so no code you upload can stop the device from receiving new code.

Complete, ready-to-run code is in the example repository. If you write code with an AI agent, the Superstack plugin for Claude Code and Codex teaches it this reference.

Example code Agent plugin


Contents

  1. Function summary
  2. Coding principles and notation
  3. Standard libraries
  4. Hardware libraries
    1. Digital IO
    2. PWM output
    3. Analog input
    4. I2C communication
    5. SPI communication
    6. UART communication
    7. Microphone (PDM)
    8. Addressable LEDs (WS2812)
  5. Networking libraries
    1. Networking (LTE)
    2. Location (GPS)
  6. System libraries
    1. Logging
    2. Sleep
    3. Power
    4. Code files
    5. Timekeeping
    6. Device information
    7. JSON

Function summary

Every function and constant on this page, in page order. Each links to its full description.

FunctionWhat it does
device.digital.set_output()Set or clear a digital output on a pin
device.digital.get_input()Get the digital value on a pin
device.digital.assign_input_event()Assign an event handler for a pin input change
device.digital.unassign_input_event()Disable an input event handler on a pin
device.pwm.set_output()Output a PWM signal on a pin
device.analog.get_input()Read the analog value on a pin
device.analog.get_differential_input()Read the differential analog value across two pins
device.i2c.read()Read bytes from an I2C device
device.i2c.write()Write bytes to an I2C device
device.i2c.write_read()Write then read bytes from an I2C device
device.i2c.scan()Scan for I2C devices
device.spi.write_read()Write then read bytes from an SPI device
device.spi.write()Write bytes to an SPI device
device.spi.read()Read bytes from an SPI device
device.spi.transact()Transact bytes with an SPI device (write and read in parallel)
device.uart.write()Write UART data
device.uart.assign_read_event()Assign an event handler for UART data
device.uart.unassign_read_event()Disable the UART read event handler
device.pdm.read()Record audio from a PDM microphone
device.pdm.assign_read_event()Assign an event handler for microphone audio
device.pdm.unassign_read_event()Disable the microphone read event handler
device.ws2812.write()Set the colors of addressable LEDs
network.get()Send a GET or DELETE request to a web service
network.delete()Send a GET or DELETE request to a web service
network.post()Send a POST, PUT or PATCH request to a web service
network.put()Send a POST, PUT or PATCH request to a web service
network.patch()Send a POST, PUT or PATCH request to a web service
network.assign_message_event()Assign an event handler for messages
network.unassign_message_event()Disable the message event handler
network.connected()Check if the network is connected
network.low_power_mode()Set low power mode
location.enable()Enable GPS
location.get_latest()Get the latest GPS data
location.disable()Disable GPS
print()Post log to Superstack
device.sleep()Sleep for a duration
device.sleep_ms()Sleep for a short duration
device.power.battery.set_charger_cv_cc()Configure the battery charger
device.power.battery.get_voltage()Get the battery voltage
device.power.battery.get_charging_status()Get the battery charging status
device.power.set_vout()Set the IO voltage for all ports
require()Run another code file
time.get_unix_time()Get the current Unix timestamp
time.get_time_date()Get the current time and date
device.HARDWARE_VERSIONHardware version constant
device.FIRMWARE_VERSIONFirmware version constant
json.encode()Encode a value as JSON
json.decode()Decode JSON text

Coding principles and notation

The functions described in this reference typically represent single, atomic operations. For example device.digital.set_output() will output a high, or low voltage on a specified pin. Unlike most hardware level programming, a separate configuration step isn’t needed. All configuration is optional and is passed directly into this function if desired.

The functions may accept a combination of positional and named arguments. Positional arguments always come first, with the named arguments provided at the end as a Lua table of key-value pairs.

Most of the named arguments will take on a default value if not provided. These are marked as optional.

A pin name is the port letter and the pin number on that port: A0, A1, B0, B1, C0 to C4, D0 to D4, E0, E1, F0 and F1. The S2 pinout shows where each one is. Any other name raises an error, such as invalid pin.

-- Calling a function with only positional arguments
device.digital.set_output("A0", true)

-- Calling a function with both positional and named arguments
device.i2c.write(0x12, "\x4F\x01", { sda_pin="B0", scl_pin="B1" })

-- Calling a function with only named arguments. Note how the () can be omitted
location.enable{ accuracy="LOW" }

Event handlers, such as those assigned with device.digital.assign_input_event(), run only while the code is running. Code that reaches the end of main.lua ends, and its handlers stop. To keep handling events, end main.lua with a loop:

while true do
    device.sleep(1)
end

An error that the code doesn’t catch with pcall ends the code. The log shows Code crashed: followed by the error, and the code’s run state becomes crashed. An error inside a handler or a request callback ends the code the same way. Handlers and callbacks can’t call coroutine.yield(), and doing so raises an error. To run the code again, upload it or run superstack device start <imei>.

If the code makes the S2 restart, the S2 doesn’t run it again after the restart. The log shows Code crashed the device, so it was not started again.


Standard libraries

The device runs Lua 5.5. Most of the standard Lua libraries that you would find on the desktop installation of Lua are included:

The remaining standard libraries are not included:

  • ❎ File IO functions - Lua has no file access beyond require
  • ❎ Operating system functions - Replaced by the timekeeping and device information libraries
  • ❎ Debug library
  • ❎ Package library - require loads code files without it

Three basic functions differ from desktop Lua:

  • require loads another code file. See code files
  • load accepts only text, not precompiled bytecode
  • dofile and loadfile are not available. Use require instead

Hardware libraries

Digital IO

Set or clear a digital output on a pin

device.digital.set_output(pin, value)

Parameters

  • pin - string - The pin name. E.g. "A0"
  • value - boolean - The level to set. true for high, false for low

Returns

  • nil

Setting an output on a pin removes any input event handler assigned to the pin.

Example

-- Set pin B1 to a high value
device.digital.set_output("B1", true)

Get the digital value on a pin

device.digital.get_input(pin, { pull="PULL_DOWN" })

Parameters

  • pin - string - The pin name. E.g. "A0"

Optional parameters

  • pull - string - The pull mode on the pin. Can be "PULL_UP", "PULL_DOWN", or "NO_PULL"

Returns

  • boolean - true if the pin is high, false if low

Reading a pin removes any input event handler assigned to the pin.

Example

-- Print the value on pin D0
local val = device.digital.get_input("D0")
print(val)

Assign an event handler for a pin input change

device.digital.assign_input_event(pin, handler, { pull="PULL_DOWN" })

Parameters

  • pin - string - The pin name. E.g. "A0"
  • handler - function - The function to call when the pin goes high or low. Called with two arguments:
    • pin - string - The pin name that generated the event. E.g. "A0"
    • state - boolean - The pin value when the event occurred. true if high, false if low

Optional parameters

  • pull - string - The pull mode on the pin. Can be "PULL_UP", "PULL_DOWN", or "NO_PULL"

Returns

  • nil

If the pin changes several times before the handler runs, the handler runs once, with the latest state. Using the pin for anything else, such as PWM, an analog read or I2C, stops the handler firing.

Example

-- Assign a function that triggers when the input value of C3 changes
function my_pin_handler(pin, state)
    if state == true then
        print(pin.." went high")
    else
        print(pin.." went low")
    end
end

device.digital.assign_input_event("C3", my_pin_handler)

Disable an input event handler on a pin

device.digital.unassign_input_event(pin)

Parameters

  • pin - string - The pin name. E.g. "A0"

Returns

  • nil

Example

-- Disable the event and detach the pin from the handler
device.digital.unassign_input_event("C3")

PWM output

Output a PWM signal on a pin

device.pwm.set_output(pin, duty_cycle, { frequency=1000 })

Parameters

  • pin - string - The pin name. E.g. "A0"
  • duty_cycle - number - The percentage of each period that the pin is high. From 0 to 100

Optional parameters

  • frequency - number - The PWM frequency in Hz. From 4 to 5000000

Returns

  • nil

Up to four pins can output PWM at once. Starting PWM on a fifth pin stops it on the pin that started first. Any other function that uses the pin, such as device.digital.set_output(), also stops it.

Example

-- Dim an LED on pin A0 to 25% brightness
device.pwm.set_output("A0", 25, { frequency=2000 })

Analog input

Read the analog value on a pin

device.analog.get_input(pin, { acquisition_time=10 })

Parameters

  • pin - string - The pin name. Must be an analog capable pin: "C2" to "C4", or "D0" to "D4"

Optional parameters

  • acquisition_time - integer - The measurement time in microseconds. Can be 3, 5, 10, 15, 20, or 40. Higher values support greater source resistances (10kΩ, 40kΩ, 100kΩ, 200kΩ, 400kΩ, 800kΩ respectively)

Returns

  • number - The voltage present on the pin in volts

Example

-- Read the analog voltage on pin D0
local voltage = device.analog.get_input("D0")
print(voltage)

Read the differential analog value across two pins

device.analog.get_differential_input(positive_pin, negative_pin, { acquisition_time=10 })

Parameters

  • positive_pin - string - The pin name of the positive pin. Must be an analog capable pin. E.g. "D0"
  • negative_pin - string - The pin name of the negative pin. Must be an analog capable pin, and different from positive_pin. E.g. "D1"

Optional parameters

  • acquisition_time - integer - The measurement time in microseconds. Can be 3, 5, 10, 15, 20, or 40. Higher values support greater source resistances (10kΩ, 40kΩ, 100kΩ, 200kΩ, 400kΩ, 800kΩ respectively)

Returns

  • number - The voltage across the pins in volts. Negative when negative_pin is at the higher voltage

Example

-- Read the differential analog voltage across pins D0 and D1
local voltage = device.analog.get_differential_input("D0", "D1")
print(voltage)

I2C communication

Optional parameters for every I2C function

  • port - string - The 4-pin port the I2C device is connected to. Can be "PORTA", "PORTB", "PORTE", or "PORTF". Defaults to "PORTA". Assumes the Stemma QT/Qwiic pinout, with SDA on pin 3 and SCL on pin 4. Cannot be used with scl_pin and sda_pin
  • scl_pin - string - The pin name for the SCL signal, for any other pins or pin order. E.g. "C3". Must be used with sda_pin
  • sda_pin - string - The pin name for the SDA signal. E.g. "C4". Must be used with scl_pin
  • frequency - integer - The I2C frequency in kHz. Can be 100, 250, or 400. Defaults to 100

A single I2C transaction may read or write at most 8191 bytes. A transaction fails, and returns success=false, if the device does not acknowledge or does not finish within 2 seconds.

Read bytes from an I2C device

device.i2c.read(address, length, { port="PORTA", frequency=100 })

Parameters

  • address - integer - The 7-bit address of the I2C device
  • length - integer - The number of bytes to read

Returns

  • table - A table of key-value pairs:
    • success - boolean - true if the transaction was successful, false otherwise
    • data - string - The bytes read. Always of size length. Absent if success is false
    • value - integer - The first byte read, useful if only one byte was requested. Absent if success is false or length is 0

Example

-- Read multiple bytes from the device and print the fourth byte
local result = device.i2c.read(0x23, 4)

if result.success then
    print(string.byte(result.data, 4))
end

Write bytes to an I2C device

device.i2c.write(address, data, { port="PORTA", frequency=100 })

Parameters

  • address - integer - The 7-bit address of the I2C device
  • data - string - The data to write to the device. Can be a hexadecimal string containing zeros. E.g. "\x1A\x50\x00\xF1"

Returns

  • table - A table of key-value pairs:
    • success - boolean - true if the transaction was successful, false otherwise

Example

-- Write 0x1234 to the register 0xF9
device.i2c.write(0x23, "\xF9\x12\x34")

Write then read bytes from an I2C device

device.i2c.write_read(address, write_data, read_length, { port="PORTA", frequency=100 })

Parameters

  • address - integer - The 7-bit address of the I2C device
  • write_data - string - The data to write to the device. Can be a hexadecimal string containing zeros. E.g. "\x1A\x50\x00\xF1"
  • read_length - integer - The number of bytes to read

Returns

  • table - A table of key-value pairs:
    • success - boolean - true if both the write and the read were successful, false otherwise
    • data - string - The bytes read. Always of size read_length. Absent if success is false
    • value - integer - The first byte read, useful if only one byte was requested. Absent if success is false or read_length is 0

Example

-- Read a byte from register 0x1F on a device with address 0x23
local result = device.i2c.write_read(0x23, "\x1F", 1)

if result.success then
    print(result.value)
end

Scan for I2C devices

device.i2c.scan({ port="PORTA", frequency=100 })

Returns

  • nil - The scan logs Scanning for I2C devices, then Device found: 0x23 for each device it finds, then I2C scan complete

Example

-- Log the address of every device on PORTF
device.i2c.scan({ port="PORTF" })

SPI communication

Optional parameters for every SPI function

  • sclk_pin - string - The pin name for the SCK signal. Defaults to "C0"
  • mosi_pin - string - The pin name for the MOSI signal. Defaults to "C1"
  • miso_pin - string - The pin name for the MISO signal. Defaults to "C2"
  • cs_pin - string - The pin name for the CS signal. Defaults to "C3"
  • mode - integer - The SPI mode. Can be 0, 1, 2, or 3. Defaults to 0
  • frequency - integer - The SPI frequency in kHz. Can be 125, 250, 500, 1000, 2000, 4000, or 8000. Defaults to 4000
  • bit_order - string - The bit order for transactions. Can be "MSB_FIRST" or "LSB_FIRST". Defaults to "MSB_FIRST"
  • hold_cs - boolean - If true, the CS pin remains held after the transaction completes. Useful for multi-step transactions. Defaults to false
  • cs_active_high - boolean - If true, the CS pin is set high during the transaction and low once completed. Defaults to false
  • miso_pull - string - The pull mode on the MISO pin. Can be "PULL_UP", "PULL_DOWN", or "NO_PULL". Defaults to "NO_PULL"

The pin options sclk_pin, mosi_pin, miso_pin and cs_pin must all be specified together. Providing only some of them raises an error. A single transfer may read or write at most 8191 bytes.

Write then read bytes from an SPI device

device.spi.write_read(write_data, read_length, { mode=0, frequency=4000 })

Parameters

  • write_data - string - The data to write to the device
  • read_length - integer - The number of bytes to read from the device after the write. CS stays active between the two

Returns

  • string - The bytes read. Always of size read_length

Example

-- Read data from an SPI flash device
local data = device.spi.write_read("\x03\x00\x00\x00", 11)
print(data)

Write bytes to an SPI device

device.spi.write(data, { mode=0, frequency=4000 })

Parameters

  • data - string - The data to write to the device

Returns

  • nil

Example

-- Wake up the flash with the 0xAB command
device.spi.write("\xAB")

Read bytes from an SPI device

device.spi.read(length, { mode=0, frequency=4000 })

Parameters

  • length - integer - The number of bytes to read from the device

Returns

  • string - The bytes read. Always of size length

Example

-- Read 4 bytes from an SPI device
local data = device.spi.read(4)
print(data)

Transact bytes with an SPI device (write and read in parallel)

device.spi.transact(write_data, read_length, { mode=0, frequency=4000 })

Parameters

  • write_data - string - The data to write to the device
  • read_length - integer - The number of bytes to read from the device while writing

Returns

  • string - The bytes read. Always of size read_length

Example

-- Write and read data simultaneously
local data = device.spi.transact("\x9F", 3)
print(data)

UART communication

Write UART data

device.uart.write(data, { tx_pin="A1", baudrate=9600, parity=false, stop_bits=1 })

Parameters

  • data - string - The data to send

Optional parameters

  • tx_pin - string - The pin name for the transmit signal. E.g. "C1"
  • baudrate - integer - The baudrate in bits-per-second. Can be 1200, 2400, 4800, 9600, 14400, 19200, 28800, 31250, 38400, 56000, 57600, 76800, 115200, 230400, 250000, 460800, 921600, or 1000000
  • parity - boolean - If true, enables the parity bit
  • stop_bits - integer - The number of stop bits. Can be 1 or 2

Returns

  • nil - Returns once all the data is sent

Example

-- Send UART data
device.uart.write("Hello there. This is some data\n", { baudrate=19200 })

Assign an event handler for UART data

device.uart.assign_read_event(terminator, handler, { rx_pin="A0", baudrate=9600, parity=false, stop_bits=1 })

Parameters

  • terminator - string - The character to wait for before calling handler. E.g. "\n". A string that isn’t exactly one character raises an error. If nil, handler is called with whatever data has arrived
  • handler - function - The function to call when data is received. Called with one argument:
    • data - string - The bytes received since the last call, including the terminator

Optional parameters

  • rx_pin - string - The pin name for the receive signal. E.g. "C0"
  • baudrate - integer - The baudrate in bits-per-second. Takes the same values as device.uart.write()
  • parity - boolean - If true, enables the parity bit
  • stop_bits - integer - The number of stop bits. Can be 1 or 2

Returns

  • nil

Only one UART read event can be assigned at a time. Assigning another replaces it. If 512 bytes arrive without a terminator, handler is called with them anyway. If more than 2048 bytes arrive before the code handles them, they are dropped.

Example

-- Log each line received
device.uart.assign_read_event("\n", function(line)
    print("Got a new line: " .. line)
end, { baudrate=19200 })

Disable the UART read event handler

device.uart.unassign_read_event()

Returns

  • nil

Example

-- Stop receiving UART data
device.uart.unassign_read_event()

Microphone (PDM)

Record audio from a PDM microphone

device.pdm.read(samples, { port="PORTA", channel="LEFT", sample_rate=16000, gain=0 })

Parameters

  • samples - integer - The number of samples to record from each channel. E.g. 16000 for one second at the default sample rate

Optional parameters

  • port - string - The 4-pin port the microphone is connected to. Can be "PORTA", "PORTB", "PORTE", or "PORTF". Defaults to "PORTA". The clock is on pin 4 and the data on pin 3, the pins that carry SCL and SDA in the Stemma QT/Qwiic pinout. Cannot be used with clk_pin and data_pin
  • clk_pin - string - The pin name for the clock. E.g. "C0". Must be specified with data_pin
  • data_pin - string - The pin name for the data. E.g. "C1". Must be specified with clk_pin
  • channel - string - The channel to record. Can be "LEFT", "RIGHT", or "STEREO". A PDM microphone sends the left or the right channel, which a pin or jumper on the microphone selects. "STEREO" records two microphones that share the clock and data pins, one set to each channel. Defaults to "LEFT"
  • sample_rate - integer - The samples per second. Can be 12500, 16000, or 20000. Defaults to 16000
  • gain - number - The gain in dB. From -20 to 20 in steps of 0.5. Defaults to 0

Returns

  • string - The samples, each a signed 16-bit little-endian integer. Read one with string.unpack("<i2", data, position). In stereo, left and right samples alternate, starting with the left. Returns once every sample is recorded

Each read starts the microphone, which sends nothing for its start-up time, often tens of milliseconds. The S2 also filters out the steady level of the audio, and this filter takes about a second to settle after the start. Until it does, the audio sits on an offset that fades. The offset can’t be heard, but code that measures the level in that first second includes it, and at a high gain the first samples can reach the limit of the range. To record without the start-up, keep a read event running.

A read holds all its samples in memory, so one read can hold about 4 seconds of audio from one channel at 16000 samples per second. A larger read raises not enough memory. Only one read or read event can use the microphone at a time. Another raises the microphone is already being read.

Example

-- Record two seconds, and log the loudest sample once the start-up has settled
local data = device.pdm.read(32000)
local loudest = 0

for position = 32001, #data, 2 do
    loudest = math.max(loudest, math.abs(string.unpack("<i2", data, position)))
end

print("Loudest sample: " .. loudest)

Assign an event handler for microphone audio

device.pdm.assign_read_event(samples, handler, { port="PORTA", channel="LEFT", sample_rate=16000, gain=0 })

Parameters

  • samples - integer - The number of samples from each channel in every block. From 1 to 32767, or 16383 in stereo
  • handler - function - The function to call with each block. Called with one argument:
    • data - string - The block’s samples, in the same form that device.pdm.read() returns

Optional parameters

  • port, clk_pin, data_pin, channel, sample_rate, and gain - The same options as device.pdm.read()

Returns

  • nil

The microphone records without a break until the event is unassigned or the code ends, so each block follows on from the last. The first second of blocks carries the start-up that device.pdm.read() describes. Only one PDM read event can be assigned at a time. Assigning another replaces it. If the code falls more than three blocks behind, the blocks waiting for it are dropped.

Example

-- Keep the most recent second of audio, ready for the moment it's needed
local recent = {}

device.pdm.assign_read_event(1600, function(block)
    table.insert(recent, block)

    if #recent > 10 then
        table.remove(recent, 1)
    end
end)

-- Later, such as when a button is pressed
local audio = table.concat(recent)

Disable the microphone read event handler

device.pdm.unassign_read_event()

Returns

  • nil

Example

-- Stop recording
device.pdm.unassign_read_event()

Addressable LEDs (WS2812)

Set the colors of addressable LEDs

device.ws2812.write(pin, colors, { order="GRB", frequency=800000 })

Parameters

  • pin - string - The pin name connected to the data input of the first LED. E.g. "B0"
  • colors - table - One color for each LED, in the order the LEDs are chained. Each color is a table of red, green and blue values, then white when order includes W, each an integer from 0 to 255. E.g. { { 255, 0, 0 }, { 0, 0, 255 } }

Optional parameters

  • order - string - The order in which the LEDs take each color’s values, as the letters R, G, B, and optionally W, each once. E.g. "GRB" for most WS2812 and SK6812 LEDs, or "GRBW" for most RGBW LEDs. Check the LEDs’ datasheet. Defaults to "GRB"
  • frequency - integer - The data rate in Hz. Can be 800000, or 400000 for LEDs such as the WS2811 in its slow mode. Defaults to 800000

Returns

  • nil - Returns once every color is sent

One write can set up to 1365 LEDs, or 1023 when order includes W. The LEDs keep their colors until the next write. A write uses one of the four PWM instances while it sends. When PWM uses all four, the pin that started PWM first stops.

The data swings to the IO voltage of the port, which starts at 1.8V, so call device.power.set_vout(3.3) first. PORTA to PORTC share 100mA, as do PORTD to PORTF, and a single LED at full brightness can draw tens of milliamps. Power more LEDs than that allows from a separate supply.

Example

-- Light a ring of 12 RGBW LEDs dim red
device.power.set_vout(3.3)

local colors = {}

for led = 1, 12 do
    colors[led] = { 32, 0, 0, 0 }
end

device.ws2812.write("B0", colors, { order="GRBW" })

Networking libraries

Networking (LTE)

Send a GET or DELETE request to a web service

network.get(url, { headers=nil, callback=nil })
network.delete(url, { headers=nil, callback=nil })

Parameters

  • url - string - The full address, starting with https:// or http://, including any query string. E.g. "https://example.com/api?city=Oslo". It must name a host, and any port must be a number. It can’t contain control characters or invalid UTF-8, and outside the query a % must start an escape such as %20

Optional parameters

  • headers - table - The request headers, as names mapped to values. E.g. { ["Authorization"]="Bearer abc" }. A name can contain only letters, digits and !#$%&'*+-.^_`|~. A value can’t contain control characters other than tab, or invalid UTF-8
  • callback - function - If given, the call returns at once and this function is called when the request finishes. Called with the same response and error that the call would otherwise return

Returns

  • response - table - A table of key-value pairs, or nil if error is set:
    • status - integer - The HTTP status code. E.g. 200
    • content - string - The response body
  • error - string - nil, or the reason no response arrived:
    • "no network" - The request did not reach Superstack, or Superstack did not accept it
    • "timeout" - The web service did not answer in time, or its answer did not reach the device
    • "connection failed" - Superstack could not connect to the web service
    • "too large" - The response body was too long
    • "no credit" - The fleet has no credit, so the device did not send the request

With callback, the call returns only error, which is nil

Superstack makes the request on the device’s behalf. Receive requests from a device lists the limits the web service must meet, how Superstack follows redirects, and which responses reach Lua. Only one request can wait at a time, with or without callback, and making another raises an error.

A url or headers that breaks a rule above raises an error that names the rule. The URL and headers fit in about 5000 bytes, and a longer request raises the error url and headers are too long.

Example

local response, err = network.get("https://example.com/api/weather?city=Oslo")

if response then
    print(response.status, response.content)
else
    print("Request failed: " .. err)
end

Send a POST, PUT or PATCH request to a web service

network.post(url, body, { headers=nil, callback=nil })
network.put(url, body, { headers=nil, callback=nil })
network.patch(url, body, { headers=nil, callback=nil })

Parameters

  • url - string - The full address, with the same rules as network.get()
  • body - string - The request body, sent unchanged. At most 4096 bytes

Optional parameters

  • headers - table - The request headers, with the same rules as network.get()
  • callback - function - Called with response and error when the request finishes

Returns

The URL and headers fit in about 980 bytes beside a 4096-byte body. A longer request raises the error url and headers are too long.

Example

-- Send a reading as JSON without waiting for the answer
network.post("https://example.com/api/readings", json.encode{ temperature=21.5 }, {
    headers={ ["Content-Type"]="application/json" },
    callback=function(response, err)
        print(err or response.status)
    end,
})

Assign an event handler for messages

network.assign_message_event(handler)

Parameters

  • handler - function - The function to call when a message arrives from your application through Superstack. Called with one argument:
    • content - string - The message exactly as your application sent it

Returns

  • nil

A message that arrives while no handler is assigned, or while the code is stopped, is discarded. How a message reaches a device describes when messages arrive and how many the device holds.

Example

-- Switch an output from a JSON message such as {"led":true}
network.assign_message_event(function(content)
    device.digital.set_output("B1", json.decode(content).led)
end)

Disable the message event handler

network.unassign_message_event()

Returns

  • nil

Example

-- Stop handling messages. Later messages are discarded
network.unassign_message_event()

Check if the network is connected

network.connected()

Returns

  • boolean - true if the LTE network is connected, false otherwise

Example

if network.connected() then
    print("Network is up")
end

Example

-- Keep the newest 200 readings in RAM while the network is down
local readings = {}

while not network.connected() do
    if #readings == 200 then
        table.remove(readings, 1)
    end

    table.insert(readings, device.power.battery.get_voltage())
    device.sleep(60)
end

-- Send the buffered readings once the network returns
if #readings > 0 then
    network.post("https://example.com/api/readings", table.concat(readings, "\n"))
end

A Lua table is held in RAM, so buffered readings are lost when the code ends, crashes, stops or restarts, or when the S2 restarts. A table that outgrows the free memory raises not enough memory. The example keeps 200 readings so that they fit in one 4096-byte request body.


Set low power mode

network.low_power_mode(enabled)

Parameters

  • enabled - boolean - true to enable PSM (Power Saving Mode), false to disable it

Returns

  • nil

Enabling PSM introduces up to 15 minutes of latency for code uploads, messages, and starting, stopping or restarting the code, because the S2 receives them only at its check-in every 15 minutes. To return to real-time updates, call network.low_power_mode(false) and wait up to 15 minutes for the modem to re-register.

PSM stays on after the code ends, crashes or is stopped, until code turns it off or the S2 restarts.

Example

-- Enable low power mode when the network is not needed
network.low_power_mode(true)

Location (GPS)

Enable GPS

location.enable{ accuracy="HIGH", power_saving="OFF", tracking_interval=1 }

Optional parameters

The table itself is required. Pass {} to use every default

  • accuracy - string - The accuracy of the fix. "LOW" requires three satellites, "HIGH" requires four satellites
  • power_saving - string - The power saving level. Can be "OFF", "MEDIUM", or "MAX". Higher power saving reduces accuracy and increases time to fix
  • tracking_interval - integer - The period to poll for new location updates. 1 for continuous 1-second updates, or a value between 10 and 65535 seconds for slower updates to save power

Returns

  • nil

location.enable() automatically activates PSM to allow the modem to share hardware with the GPS. This introduces up to 15 minutes of latency for code uploads, messages, and starting, stopping or restarting the code. To return to real-time updates, call location.disable() followed by network.low_power_mode(false), then wait up to 15 minutes.

GPS and PSM stay on after the code ends, crashes or is stopped, until code turns them off or the S2 restarts.

Example

-- Start GPS with default settings
location.enable{}

-- Start GPS with low accuracy to save power
location.enable{ accuracy="LOW", power_saving="MAX" }

Get the latest GPS data

location.get_latest()

Returns

  • table - A table of key-value pairs:
    • valid - boolean - true if the latest fix is valid. If false, the location and speed values are from the last valid fix, or 0 before the first. The latest fix stays until the S2 restarts, even after location.disable() or after the code ends, so valid can be true for a fix from an earlier run
    • latitude - number - The latitude in degrees
    • longitude - number - The longitude in degrees
    • altitude - number - The altitude in meters
    • accuracy - number - The location accuracy in meters
    • speed - number - The horizontal speed in meters per second
    • speed_accuracy - number - The speed accuracy in meters per second
    • satellites - table - A table of key-value pairs:
      • tracked - integer - The number of satellites currently being tracked
      • in_fix - integer - The number of satellites currently being used for measurement
      • unhealthy - integer - The number of satellites that could not be used for measurement

Example

-- GPS must be enabled before getting a location fix
location.enable{}

-- Avoid network activity while waiting for a fix. It competes
-- for the modem hardware and delays acquisition
device.sleep(60)

local fix = location.get_latest()

if fix.valid then
    print(string.format("%.5f, %.5f", fix.latitude, fix.longitude))
else
    print("No fix yet. Tracking " .. fix.satellites.tracked .. " satellites")
end

Disable GPS

location.disable()

Returns

  • nil

Disabling GPS alone does not restore real-time code updates. PSM remains active until network.low_power_mode(false) is called. After calling it, wait up to 15 minutes for the modem to re-register before code updates arrive in real time.

Example

-- Stop GPS and restore real-time connectivity
location.disable()
network.low_power_mode(false)

System libraries

Logging

Post log to Superstack

print(...)

Parameters

  • ... - any - One or more values to print. They are converted to strings and joined with tabs into one log

Returns

  • nil

Example

-- Simple print
print("hello world")

-- Print several values in one log, separated by tabs
print("count", 4 + 3)

-- C printf style formatted prints
print(string.format("pi = %.4f", math.pi))

print never waits for the network. Logs wait on the device in a 2048-byte buffer until they are sent, and a log that does not fit is dropped whole. A single print of more than 2045 bytes is always dropped. When a fleet runs out of credit, the device discards logs instead of sending them.


Sleep

Sleep for a duration

device.sleep(time)

Parameters

  • time - number - The duration to sleep in seconds. E.g. 1.5

Returns

  • nil

Assigned event handlers continue to fire during sleep. See assign an event handler.

Example

-- Sleep for 1.5 seconds
device.sleep(1.5)

Sleep for a short duration

device.sleep_ms(time)

Parameters

  • time - integer - The duration to sleep in milliseconds. From 0 to 1000

Returns

  • nil

Event handlers do not fire during device.sleep_ms(), and stopping the code waits for it to return. Use device.sleep() for anything longer.

Example

-- Pulse pin B1 high for 5 milliseconds
device.digital.set_output("B1", true)
device.sleep_ms(5)
device.digital.set_output("B1", false)

Power

Configure the battery charger

device.power.battery.set_charger_cv_cc(voltage, current)

Parameters

  • voltage - number - The termination voltage. Can be 3.50, 3.55, 3.60, 3.65, 4.00, 4.05, 4.10, 4.15, 4.20, 4.25, 4.30, 4.35, 4.40, or 4.45
  • current - integer - The constant charge current in mA. Must be between 32 and 800 in steps of 2

Returns

  • nil

This setting reverts to the firmware default (3.50V termination, 32mA charge current) at reboot. Configure the charger near the top of your code so that it is reapplied whenever the code restarts.

Example

-- Configure the battery charger for a 4.2V 200mAh rated Li-Po cell
device.power.battery.set_charger_cv_cc(4.2, 200)

Get the battery voltage

device.power.battery.get_voltage()

Returns

  • number - The voltage of the cell in volts

Example

local voltage = device.power.battery.get_voltage()
print("Battery voltage is "..tostring(voltage).."V")

Get the battery charging status

device.power.battery.get_charging_status()

Returns

  • string - The charging status: "charging", "charged", or "discharging" if a battery is connected, or "external_power" if no battery is installed or the battery has a fault

Example

local status = device.power.battery.get_charging_status()

if status ~= "external_power" then
    print("Battery is "..status)
else
    print("Battery not connected. On external power")
end

Set the IO voltage for all ports

device.power.set_vout(voltage)

Parameters

  • voltage - number - The IO voltage of PORTA - PORTF. Can be between 1.8 and 3.3 in steps of 0.1, or 0 to switch the power pins of every port off. Any other value raises voltage must be between 1.8 and 3.3 in steps of 0.1

Returns

  • nil

At boot, the port rails default to 1.8V. If a connected sensor requires a higher IO voltage, call this function before communicating with it. The voltage applies to every port at once. It stays set after the code ends, until the code changes it or the S2 restarts.

Example

-- Set the voltage of Vout to 3.3V
device.power.set_vout(3.3)

Code files

Run another code file

require(name)

Parameters

  • name - string - The path of a code file in the bundle, without .lua. E.g. "sensors" for sensors.lua, or "lib/sensors" for lib/sensors.lua

Returns

  • any - The value the file returns, or true if it returns nothing

A file runs once. Later calls with the same name return the value from the first call without running the file again. Files can require other files up to 8 levels deep. A deeper require raises require is nested too deeply, and a missing file raises module not found.

Unlike desktop Lua, a . in the name is not a folder separator, so require("lib.sensors") looks for lib.sensors.lua. To put sensors.lua in a lib folder on the device, upload the folder that holds lib. See what an upload sends.

Example

-- sensors.lua returns a table of functions
local sensors = require("sensors")
print(sensors.read_temperature())

Timekeeping

The time is not known until the device first checks in to Superstack, which sets its clock to within 2 seconds and corrects it whenever it drifts further. While location is enabled, each GPS fix also sets the clock, to the millisecond of the fix.

Get the current Unix timestamp

time.get_unix_time()

Returns

  • integer - The current Unix timestamp (i.e the number of non-leap milliseconds that have elapsed since 00:00:00 UTC on 1 January 1970), or if the time is not yet known, returns the uptime of the device in milliseconds

Example

-- Repeat something for 30 seconds
local t = time.get_unix_time()

while t + 30000 > time.get_unix_time() do
    print("waiting")
    device.sleep(5)
end

Note: the returned value is in milliseconds, so 30 seconds is 30000


Get the current time and date

time.get_time_date({ unix_epoch=nil, timezone="+00:00" })

Optional parameters

  • unix_epoch - integer - A Unix timestamp in milliseconds to convert, as returned by time.get_unix_time(). If nil, the current time is used, and an error is raised if the time is not yet known
  • timezone - string - The timezone offset as "+HH:MM" or "-HH:MM", from "-12:59" to "+14:59". E.g. "+02:00" or "-07:30". Defaults to "+00:00"

Returns

  • table - A table of key-value pairs:
    • year - integer - The current year
    • month - integer - The current month
    • day - integer - The current day
    • yearday - integer - The day of the year. 1 on 1 January
    • weekday - integer - The days since Sunday. 0 on Sunday
    • hour - integer - The current hour
    • minute - integer - The current minute
    • second - integer - The current second

Example

-- Print the current time and date
local now = time.get_time_date()

print(string.format("The current time is: %02d:%02d", now.hour, now.minute))
print(string.format("The current date is: %d/%d/%d", now.year, now.month, now.day))

Device information

Hardware version constant

device.HARDWARE_VERSION

Returns

  • string - Always "s2-module"

Example

print(device.HARDWARE_VERSION)

Firmware version constant

device.FIRMWARE_VERSION

Returns

  • string - A string representing the current firmware version. E.g. "3.0.0"

Example

print(device.FIRMWARE_VERSION)

JSON

Encode a value as JSON

json.encode(value)

Parameters

  • value - any - A table, string, number, boolean, nil or json.null. nil and json.null become null. A table whose keys are all whole numbers from 1 up becomes an array, with null for each missing key. E.g. {[1]=1, [3]=3} becomes [1,null,3]. Any other table becomes an object. An empty table becomes {}

Returns

  • string - The JSON text

Tables can nest up to 16 levels deep. A value that JSON cannot hold, such as a function, raises an error.

An array table whose highest key is above 10 and more than twice its number of keys, such as {[20]=1}, raises the error Cannot serialise table: excessively sparse array.

An integer is written exactly. Any other number is written to 14 significant digits. A / in a string is written as \/, so "https://example.com" becomes "https:\/\/example.com", which any JSON parser reads back as the same string.

Example

-- Prints {"temperature":21.5,"readings":[1,2,3]}, with the keys in any order
print(json.encode{ temperature=21.5, readings={1, 2, 3} })

Decode JSON text

json.decode(text)

Parameters

  • text - string - The JSON text

Returns

  • any - The decoded value. Objects and arrays become tables, and null becomes json.null

Text that is not valid JSON, or that nests more than 16 levels deep, raises an error. Use pcall to handle text that might be invalid.

Example

local ok, message = pcall(json.decode, '{"led":true,"level":null}')

if ok and message.level == json.null then
    print("No level given")
end