diff --git a/plugins/superstack/skills/s2-lua/references/lua-api.md b/plugins/superstack/skills/s2-lua/references/lua-api.md index aec7378..af77e6a 100644 --- a/plugins/superstack/skills/s2-lua/references/lua-api.md +++ b/plugins/superstack/skills/s2-lua/references/lua-api.md @@ -5,28 +5,26 @@ python3 scripts/generate-references.py --docs --write --> -# Superstack Lua Library Reference +# Superstack Lua reference --- -Superstack devices such as the S2 Module run Lua—an incredibly lightweight, efficient and simple to learn language. +Superstack devices such as the S2 Module run Lua. You upload your code with the [Superstack CLI](/pages/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. -The built-in Lua libraries provide complete hardware and network level functionality to **read sensors**, **report data**, **compute on-device algorithms** and take actions such as **driving IO** automatically. +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. -The Lua engine is almost as performant as writing native C firmware as it's a lightweight wrapper around native C functions built into the Superstack firmware. - -Compared to writing firmware, the Superstack Lua engine allows for remote and realtime development of IoT code without the need for compiler tools, hardware debuggers or physical access to the device. There's also no risk of bricking devices as Lua runs in a container, and is always updatable and isolated from sensitive internal functions such as network management. - -Complete ready-to-run scripts are available in the example repository, and if you write code with an AI assistant, our plugin for Claude teaches it this entire reference. +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. --- ## Contents +- [Function summary](#function-summary) - [Coding principles and notation](#coding-principles-and-notation) - [Standard libraries](#standard-libraries) - [Hardware libraries](#hardware-libraries) - [Digital IO](#digital-io) + - [PWM output](#pwm-output) - [Analog input](#analog-input) - [I2C communication](#i2c-communication) - [SPI communication](#spi-communication) @@ -38,9 +36,69 @@ Complete ready-to-run scripts are available in the example repository, and if yo - [Logging](#logging) - [Sleep](#sleep) - [Power](#power) + - [Code files](#code-files) - [Temporary files](#temporary-files) - [Timekeeping](#timekeeping) - [Device information](#device-information) + - [JSON](#json) + +--- + +## Function summary + +Every function and constant on this page, in page order. Each links to its full description. + +| Function | What it does | +| --- | --- | +| [`device.digital.set_output()`](#set-or-clear-a-digital-output-on-a-pin) | Set or clear a digital output on a pin | +| [`device.digital.get_input()`](#get-the-digital-value-on-a-pin) | Get the digital value on a pin | +| [`device.digital.assign_input_event()`](#assign-an-event-handler-for-a-pin-input-change) | Assign an event handler for a pin input change | +| [`device.digital.unassign_input_event()`](#disable-an-input-event-handler-on-a-pin) | Disable an input event handler on a pin | +| [`device.pwm.set_output()`](#output-a-pwm-signal-on-a-pin) | Output a PWM signal on a pin | +| [`device.analog.get_input()`](#read-the-analog-value-on-a-pin) | Read the analog value on a pin | +| [`device.analog.get_differential_input()`](#read-the-differential-analog-value-across-two-pins) | Read the differential analog value across two pins | +| [`device.i2c.read()`](#read-bytes-from-an-i2c-device) | Read bytes from an I2C device | +| [`device.i2c.write()`](#write-bytes-to-an-i2c-device) | Write bytes to an I2C device | +| [`device.i2c.write_read()`](#write-then-read-bytes-from-an-i2c-device) | Write then read bytes from an I2C device | +| [`device.i2c.scan()`](#scan-for-i2c-devices) | Scan for I2C devices | +| [`device.spi.write_read()`](#write-then-read-bytes-from-an-spi-device) | Write then read bytes from an SPI device | +| [`device.spi.write()`](#write-bytes-to-an-spi-device) | Write bytes to an SPI device | +| [`device.spi.read()`](#read-bytes-from-an-spi-device) | Read bytes from an SPI device | +| [`device.spi.transact()`](#transact-bytes-with-an-spi-device-write-and-read-in-parallel) | Transact bytes with an SPI device (write and read in parallel) | +| [`device.uart.write()`](#write-uart-data) | Write UART data | +| [`device.uart.assign_read_event()`](#assign-an-event-handler-for-uart-data) | Assign an event handler for UART data | +| [`device.uart.unassign_read_event()`](#disable-the-uart-read-event-handler) | Disable the UART read event handler | +| [`network.get()`](#send-a-get-or-delete-request-to-a-web-service) | Send a GET or DELETE request to a web service | +| [`network.delete()`](#send-a-get-or-delete-request-to-a-web-service) | Send a GET or DELETE request to a web service | +| [`network.post()`](#send-a-post-put-or-patch-request-to-a-web-service) | Send a POST, PUT or PATCH request to a web service | +| [`network.put()`](#send-a-post-put-or-patch-request-to-a-web-service) | Send a POST, PUT or PATCH request to a web service | +| [`network.patch()`](#send-a-post-put-or-patch-request-to-a-web-service) | Send a POST, PUT or PATCH request to a web service | +| [`network.assign_message_event()`](#assign-an-event-handler-for-messages) | Assign an event handler for messages | +| [`network.unassign_message_event()`](#disable-the-message-event-handler) | Disable the message event handler | +| [`network.connected()`](#check-if-the-network-is-connected) | Check if the network is connected | +| [`network.low_power_mode()`](#set-low-power-mode) | Set low power mode | +| [`location.enable()`](#enable-gps) | Enable GPS | +| [`location.get_latest()`](#get-the-latest-gps-data) | Get the latest GPS data | +| [`location.disable()`](#disable-gps) | Disable GPS | +| [`print()`](#post-log-to-superstack) | Post log to Superstack | +| [`device.sleep()`](#sleep-for-a-duration) | Sleep for a duration | +| [`device.sleep_ms()`](#sleep-for-a-short-duration) | Sleep for a short duration | +| [`device.power.battery.set_charger_cv_cc()`](#configure-the-battery-charger) | Configure the battery charger | +| [`device.power.battery.get_voltage()`](#get-the-battery-voltage) | Get the battery voltage | +| [`device.power.battery.get_charging_status()`](#get-the-battery-charging-status) | Get the battery charging status | +| [`device.power.set_vout()`](#set-the-io-voltage-for-all-ports) | Set the IO voltage for all ports | +| [`require()`](#run-another-code-file) | Run another code file | +| [`storage.open()`](#open-a-temporary-file) | Open a temporary file | +| [`handle:write()`](#write-data-to-a-temporary-file) | Write data to a temporary file | +| [`handle:append()`](#append-data-to-a-temporary-file) | Append data to a temporary file | +| [`handle:read()`](#read-data-from-a-temporary-file) | Read data from a temporary file | +| [`handle:close()`](#close-a-temporary-file) | Close a temporary file | +| [`time.get_unix_time()`](#get-the-current-unix-timestamp) | Get the current Unix timestamp | +| [`time.get_time_date()`](#get-the-current-time-and-date) | Get the current time and date | +| [`device.HARDWARE_VERSION`](#hardware-version-constant) | Hardware version constant | +| [`device.FIRMWARE_VERSION`](#firmware-version-constant) | Firmware version constant | +| [`json.encode()`](#encode-a-value-as-json) | Encode a value as JSON | +| [`json.decode()`](#decode-json-text) | Decode JSON text | --- @@ -52,17 +110,31 @@ The functions may accept a combination of **positional** and **named** arguments 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](/pages/s2-module#pinout) shows where each one is. Any other name raises an error, such as `invalid pin`. + ```lua -- 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", { scl_pin="B0", sda_pin="B1" }) +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 -network.send_data{ sensor_value=31.5 } +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: + +```lua +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 `. + +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 @@ -81,6 +153,13 @@ The remaining standard libraries are not included, as they are superseded by sim - ❎ File IO functions - Replaced by the [temporary files](#temporary-files) library - ❎ Operating system functions - Replaced by the [timekeeping](#timekeeping) and [device information](#device-information) libraries - ❎ Debug library +- ❎ Package library - `require` loads [code files](#code-files) without it + +Three basic functions differ from desktop Lua: + +- `require` loads another code file. See [code files](#code-files) +- `load` accepts only text, not precompiled bytecode +- `dofile` and `loadfile` cannot open files. Use `require` instead --- @@ -103,6 +182,8 @@ device.digital.set_output(pin, value) - **nil** +**Note:** Setting an output on a pin removes any input event handler assigned to the pin. + **Example** ```lua @@ -130,6 +211,8 @@ device.digital.get_input(pin, { pull="PULL_DOWN" }) - **boolean** - `true` if the pin is high, `false` if low +**Note:** Reading a pin removes any input event handler assigned to the pin. + **Example** ```lua @@ -149,7 +232,7 @@ 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 value changes. Called with two arguments: +- `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 @@ -161,6 +244,8 @@ device.digital.assign_input_event(pin, handler, { pull="PULL_DOWN" }) - **nil** +**Note:** 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** ```lua @@ -201,6 +286,38 @@ device.digital.unassign_input_event("C3") --- +### PWM output + +#### Output a PWM signal on a pin + +```lua +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** + +**Note:** 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** + +```lua +-- 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 @@ -211,7 +328,7 @@ device.analog.get_input(pin, { acquisition_time=10 }) **Parameters** -- `pin` - **string** - The pin name. Must be an analog capable pin. E.g. `"D0"` +- `pin` - **string** - The pin name. Must be an analog capable pin: `"C2"` to `"C4"`, or `"D0"` to `"D4"` **Optional parameters** @@ -239,8 +356,8 @@ device.analog.get_differential_input(positive_pin, negative_pin, { acquisition_t **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" +- `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** @@ -248,7 +365,7 @@ device.analog.get_differential_input(positive_pin, negative_pin, { acquisition_t **Returns** -- **number** - The voltage present across the pins in volts +- **number** - The voltage across the pins in volts. Negative when `negative_pin` is at the higher voltage **Example** @@ -262,12 +379,19 @@ print(voltage) ### I2C communication -**Note:** A single I2C transaction may read or write at most **8191 bytes**. +**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](https://learn.adafruit.com/introducing-adafruit-stemma-qt/what-is-stemma)/[Qwiic](https://www.sparkfun.com/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` + +**Note:** 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 ```lua -device.i2c.read(address, length, { port="PORTA", scl_pin="A1", sda_pin="A0", frequency=100 }) +device.i2c.read(address, length, { port="PORTA", frequency=100 }) ``` **Parameters** @@ -275,19 +399,12 @@ device.i2c.read(address, length, { port="PORTA", scl_pin="A1", sda_pin="A0", fre - `address` - **integer** - The 7-bit address of the I2C device - `length` - **integer** - The number of bytes to read -**Optional parameters** - -- `port` - **string** - The 4-pin port the I2C device is connected to. Can be `"PORTA"`, `"PORTB"`, `"PORTE"`, or `"PORTF"`. Assumes [Stemma QT](https://learn.adafruit.com/introducing-adafruit-stemma-qt/what-is-stemma)/[Qwiic](https://www.sparkfun.com/qwiic) pinout. For a different pin order, use `scl_pin` and `sda_pin` instead -- `scl_pin` - **string** - The pin name for the SCL signal. E.g. `"C3"`. Must be used with `sda_pin`. Cannot be used with `port` -- `sda_pin` - **string** - The pin name for the SDA signal. E.g. `"C4"`. Must be used with `scl_pin`. Cannot be used with `port` -- `frequency` - **integer** - The I2C frequency in kHz. Can be `100`, `250`, or `400` - **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` as specified in the function call - - `value` - **integer** - The first data byte, useful if only one byte was requested + - `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** @@ -305,7 +422,7 @@ end #### Write bytes to an I2C device ```lua -device.i2c.write(address, data, { port="PORTA", scl_pin="A1", sda_pin="A0", frequency=100 }) +device.i2c.write(address, data, { port="PORTA", frequency=100 }) ``` **Parameters** @@ -313,13 +430,6 @@ device.i2c.write(address, data, { port="PORTA", scl_pin="A1", sda_pin="A0", freq - `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"` -**Optional parameters** - -- `port` - **string** - The 4-pin port the I2C device is connected to. Can be `"PORTA"`, `"PORTB"`, `"PORTE"`, or `"PORTF"` -- `scl_pin` - **string** - The pin name for the SCL signal. E.g. `"C3"` -- `sda_pin` - **string** - The pin name for the SDA signal. E.g. `"C4"` -- `frequency` - **integer** - The I2C frequency in kHz. Can be `100`, `250`, or `400` - **Returns** - **table** - A table of key-value pairs: @@ -337,7 +447,7 @@ device.i2c.write(0x23, "\xF9\x12\x34") #### Write then read bytes from an I2C device ```lua -device.i2c.write_read(address, write_data, read_length, { port="PORTA", scl_pin="A1", sda_pin="A0", frequency=100 }) +device.i2c.write_read(address, write_data, read_length, { port="PORTA", frequency=100 }) ``` **Parameters** @@ -346,19 +456,12 @@ device.i2c.write_read(address, write_data, read_length, { port="PORTA", scl_pin= - `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 -**Optional parameters** - -- `port` - **string** - The 4-pin port the I2C device is connected to. Can be `"PORTA"`, `"PORTB"`, `"PORTE"`, or `"PORTF"` -- `scl_pin` - **string** - The pin name for the SCL signal. E.g. `"C3"` -- `sda_pin` - **string** - The pin name for the SDA signal. E.g. `"C4"` -- `frequency` - **integer** - The I2C frequency in kHz. Can be `100`, `250`, or `400` - **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 `read_length` as specified in the function call - - `value` - **integer** - The first data byte, useful if only one byte was requested + - `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** @@ -376,24 +479,17 @@ end #### Scan for I2C devices ```lua -device.i2c.scan({ port="PORTA", scl_pin="A1", sda_pin="A0", frequency=100 }) +device.i2c.scan({ port="PORTA", frequency=100 }) ``` -**Optional parameters** - -- `port` - **string** - The 4-pin port the I2C device is connected to. Can be `"PORTA"`, `"PORTB"`, `"PORTE"`, or `"PORTF"` -- `scl_pin` - **string** - The pin name for the SCL signal. E.g. `"C3"` -- `sda_pin` - **string** - The pin name for the SDA signal. E.g. `"C4"` -- `frequency` - **integer** - The I2C frequency in kHz. Can be `100`, `250`, or `400` - **Returns** -- **nil** +- **nil** - The scan logs `Scanning for I2C devices`, then `Device found: 0x23` for each device it finds, then `I2C scan complete` **Example** ```lua --- Scan a port for devices +-- Log the address of every device on PORTF device.i2c.scan({ port="PORTF" }) ``` @@ -401,31 +497,31 @@ device.i2c.scan({ port="PORTF" }) ### SPI communication -**Note:** 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**. +**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"` + +**Note:** 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 ```lua -device.spi.write_read(write_data, read_length, { sclk_pin="C0", mosi_pin="C1", miso_pin="C2", cs_pin="C3", mode=0, frequency=4000, bit_order="MSB_FIRST", hold_cs=false, cs_active_high=false, miso_pull="NO_PULL" }) +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 - -**Optional parameters** - -- `sclk_pin` - **string** - The pin name for the SCK signal. E.g. `"D0"` -- `mosi_pin` - **string** - The pin name for the MOSI signal. E.g. `"D1"` -- `miso_pin` - **string** - The pin name for the MISO signal. E.g. `"D2"` -- `cs_pin` - **string** - The pin name for the CS signal. E.g. `"D3"` -- `mode` - **integer** - The SPI mode. Can be `0`, `1`, `2`, or `3` -- `frequency` - **integer** - The SPI frequency in kHz. Can be `125`, `250`, `500`, `1000`, `2000`, `4000`, or `8000` -- `bit_order` - **string** - The bit order for transactions. Can be `"MSB_FIRST"` or `"LSB_FIRST"` -- `hold_cs` - **boolean** - If `true`, the CS pin remains held after the transaction completes. Useful for multi-step transactions -- `cs_active_high` - **boolean** - If `true`, the CS pin is set high during the transaction and low once completed -- `miso_pull` - **string** - The pull mode on the MISO pin. Can be `"PULL_UP"`, `"PULL_DOWN"`, or `"NO_PULL"` +- `read_length` - **integer** - The number of bytes to read from the device after the write. CS stays active between the two **Returns** @@ -444,26 +540,13 @@ print(data) #### Write bytes to an SPI device ```lua -device.spi.write(data, { sclk_pin="C0", mosi_pin="C1", miso_pin="C2", cs_pin="C3", mode=0, frequency=4000, bit_order="MSB_FIRST", hold_cs=false, cs_active_high=false, miso_pull="NO_PULL" }) +device.spi.write(data, { mode=0, frequency=4000 }) ``` **Parameters** - `data` - **string** - The data to write to the device -**Optional parameters** - -- `sclk_pin` - **string** - The pin name for the SCK signal. E.g. `"D0"` -- `mosi_pin` - **string** - The pin name for the MOSI signal. E.g. `"D1"` -- `miso_pin` - **string** - The pin name for the MISO signal. E.g. `"D2"` -- `cs_pin` - **string** - The pin name for the CS signal. E.g. `"D3"` -- `mode` - **integer** - The SPI mode. Can be `0`, `1`, `2`, or `3` -- `frequency` - **integer** - The SPI frequency in kHz. Can be `125`, `250`, `500`, `1000`, `2000`, `4000`, or `8000` -- `bit_order` - **string** - The bit order for transactions. Can be `"MSB_FIRST"` or `"LSB_FIRST"` -- `hold_cs` - **boolean** - If `true`, the CS pin remains held after the transaction completes -- `cs_active_high` - **boolean** - If `true`, the CS pin is set high during the transaction and low once completed -- `miso_pull` - **string** - The pull mode on the MISO pin. Can be `"PULL_UP"`, `"PULL_DOWN"`, or `"NO_PULL"` - **Returns** - **nil** @@ -480,26 +563,13 @@ device.spi.write("\xAB") #### Read bytes from an SPI device ```lua -device.spi.read(length, { sclk_pin="C0", mosi_pin="C1", miso_pin="C2", cs_pin="C3", mode=0, frequency=4000, bit_order="MSB_FIRST", hold_cs=false, cs_active_high=false, miso_pull="NO_PULL" }) +device.spi.read(length, { mode=0, frequency=4000 }) ``` **Parameters** - `length` - **integer** - The number of bytes to read from the device -**Optional parameters** - -- `sclk_pin` - **string** - The pin name for the SCK signal. E.g. `"D0"` -- `mosi_pin` - **string** - The pin name for the MOSI signal. E.g. `"D1"` -- `miso_pin` - **string** - The pin name for the MISO signal. E.g. `"D2"` -- `cs_pin` - **string** - The pin name for the CS signal. E.g. `"D3"` -- `mode` - **integer** - The SPI mode. Can be `0`, `1`, `2`, or `3` -- `frequency` - **integer** - The SPI frequency in kHz. Can be `125`, `250`, `500`, `1000`, `2000`, `4000`, or `8000` -- `bit_order` - **string** - The bit order for transactions. Can be `"MSB_FIRST"` or `"LSB_FIRST"` -- `hold_cs` - **boolean** - If `true`, the CS pin remains held after the transaction completes -- `cs_active_high` - **boolean** - If `true`, the CS pin is set high during the transaction and low once completed -- `miso_pull` - **string** - The pull mode on the MISO pin. Can be `"PULL_UP"`, `"PULL_DOWN"`, or `"NO_PULL"` - **Returns** - **string** - The bytes read. Always of size `length` @@ -517,30 +587,17 @@ print(data) #### Transact bytes with an SPI device (write and read in parallel) ```lua -device.spi.transact(write_data, read_length, { sclk_pin="C0", mosi_pin="C1", miso_pin="C2", cs_pin="C3", mode=0, frequency=4000, bit_order="MSB_FIRST", hold_cs=false, cs_active_high=false, miso_pull="NO_PULL" }) +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 - -**Optional parameters** - -- `sclk_pin` - **string** - The pin name for the SCK signal. E.g. `"D0"` -- `mosi_pin` - **string** - The pin name for the MOSI signal. E.g. `"D1"` -- `miso_pin` - **string** - The pin name for the MISO signal. E.g. `"D2"` -- `cs_pin` - **string** - The pin name for the CS signal. E.g. `"D3"` -- `mode` - **integer** - The SPI mode. Can be `0`, `1`, `2`, or `3` -- `frequency` - **integer** - The SPI frequency in kHz. Can be `125`, `250`, `500`, `1000`, `2000`, `4000`, or `8000` -- `bit_order` - **string** - The bit order for transactions. Can be `"MSB_FIRST"` or `"LSB_FIRST"` -- `hold_cs` - **boolean** - If `true`, the CS pin remains held after the transaction completes -- `cs_active_high` - **boolean** - If `true`, the CS pin is set high during the transaction and low once completed -- `miso_pull` - **string** - The pull mode on the MISO pin. Can be `"PULL_UP"`, `"PULL_DOWN"`, or `"NO_PULL"` +- `read_length` - **integer** - The number of bytes to read from the device while writing **Returns** -- **string** - The bytes read. Always of size `read_length` as specified in the function call +- **string** - The bytes read. Always of size `read_length` **Example** @@ -554,12 +611,10 @@ print(data) ### UART communication -**Warning:** The UART functions are **not yet functional** in the current firmware release. Calls succeed silently but perform no UART operation. This section describes the planned interface. - #### Write UART data ```lua -device.uart.write(data, { baudrate=9600, tx_pin="B1", cts_pin=nil, parity=false, stop_bits=1 }) +device.uart.write(data, { tx_pin="A1", baudrate=9600, parity=false, stop_bits=1 }) ``` **Parameters** @@ -568,15 +623,14 @@ device.uart.write(data, { baudrate=9600, tx_pin="B1", cts_pin=nil, parity=false, **Optional parameters** -- `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` - `tx_pin` - **string** - The pin name for the transmit signal. E.g. `"C1"` -- `cts_pin` - **string** - The pin name for the clear-to-send signal. E.g. `"C3"`. If `nil`, the signal isn't used +- `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** +- **nil** - Returns once all the data is sent **Example** @@ -590,103 +644,191 @@ device.uart.write("Hello there. This is some data\n", { baudrate=19200 }) #### Assign an event handler for UART data ```lua -device.uart.assign_read_event(terminator, handler, { baudrate=9600, rx_pin="B0", tx_pin="B1", rts_pin=nil, cts_pin=nil, parity=false, stop_bits=1 }) +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 triggering the event. If `nil`, the event triggers for every character received +- `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** - All buffered bytes since the last event or since the event was enabled + - `data` - **string** - The bytes received since the last call, including the terminator **Optional parameters** -- `baudrate` - **integer** - The baudrate in bits-per-second - `rx_pin` - **string** - The pin name for the receive signal. E.g. `"C0"` -- `rts_pin` - **string** - The pin name for the ready-to-send signal. E.g. `"C2"`. If `nil`, the signal isn't used +- `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** +**Note:** 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** ```lua --- Create a handler for receiving UART data -function my_receive_handler(data) - print("Got a new line: "..data) -end +-- 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 + +```lua +device.uart.unassign_read_event() +``` + +**Returns** + +- **nil** + +**Example** -device.uart.assign_read_event("\n", my_receive_handler, { baudrate=19200 }) +```lua +-- Stop receiving UART data +device.uart.unassign_read_event() ``` --- -#### Disable a UART read event handler +## Networking libraries + +### Networking (LTE) + +#### Send a GET or DELETE request to a web service ```lua -device.uart.unassign_read_event(rx_pin) +network.get(url, { headers=nil, callback=nil }) +network.delete(url, { headers=nil, callback=nil }) ``` **Parameters** -- `rx_pin` - **string** - The pin name of the receive signal. E.g. `"C0"` +- `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** -- **nil** +- `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](/pages/superstack/credit), so the device did not send the request + +With `callback`, the call returns only `error`, which is `nil` + +**Note:** Superstack makes the request on the device's behalf. [Receive requests from a device](/pages/superstack/api#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** ```lua --- Disable the event and detach the pin from the handler if no longer needed -device.uart.unassign_read_event("B0") +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 ``` --- -## Networking libraries +#### Send a POST, PUT or PATCH request to a web service -### Networking (LTE) +```lua +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()`](#send-a-get-or-delete-request-to-a-web-service) +- `body` - **string** - The request body, sent unchanged. At most 4096 bytes + +**Optional parameters** -#### Send data to Superstack +- `headers` - **table** - The request headers, with the same rules as [`network.get()`](#send-a-get-or-delete-request-to-a-web-service) +- `callback` - **function** - Called with `response` and `error` when the request finishes + +**Returns** + +- `response` and `error` - The same as [`network.get()`](#send-a-get-or-delete-request-to-a-web-service) + +**Note:** 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** ```lua -network.send_data{ data } +-- 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 + +```lua +network.assign_message_event(handler) ``` **Parameters** -- `data` - **table** - A table of key-value pairs. Converted to JSON when sent to Superstack. Use descriptive key names (e.g. `temperature_celsius = 43.5`) to help AI tools infer meaning +- `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** -**Warning:** If the Device has no network connection, the data is **dropped** — it is not buffered by the firmware. If data must survive connectivity gaps, check `network.connected()` and buffer to a [temporary file](#temporary-files) until the connection returns. - -**Note:** The table must not be empty, and top-level keys must be strings. A complete encoded message may be around **1KB** — keep individual payloads below **900 bytes** to be safe, and split larger data across multiple sends. The call is synchronous and can block for a few seconds on a poor connection. If the Deployment's data allowance has been exceeded, `send_data` and `print` become inactive until the allowance resets or code is re-deployed. +**Note:** A message that arrives while no handler is assigned, or while the code is stopped, is discarded. [How a message reaches a device](/pages/superstack/api#how-a-message-reaches-a-device) describes when messages arrive and how many the device holds. **Example** ```lua --- A simple sensor value -my_sensor_value = 23.5 +-- 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) +``` -network.send_data{ temperature=my_sensor_value } +--- --- Network send can contain any arbitrary data -network.send_data{ - my_int = -42, - my_float = 23.1, - my_string = "my string", - my_array = {1, 2, 3, 4}, - my_table = { - my_other_int = 54, - my_other_string = "another string" - } -} +#### Disable the message event handler + +```lua +network.unassign_message_event() +``` + +**Returns** + +- **nil** + +**Example** + +```lua +-- Stop handling messages. Later messages are discarded +network.unassign_message_event() ``` --- @@ -725,7 +867,9 @@ network.low_power_mode(enabled) - **nil** -**Warning:** Enabling PSM introduces up to **15 minutes of latency** for code updates from Superstack. To return to real-time updates, call `network.low_power_mode(false)` and wait up to 15 minutes for the modem to re-register. +**Warning:** 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** @@ -741,11 +885,13 @@ network.low_power_mode(true) #### Enable GPS ```lua -location.enable({ accuracy="HIGH", power_saving="OFF", tracking_interval=1 }) +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 @@ -754,7 +900,9 @@ location.enable({ accuracy="HIGH", power_saving="OFF", tracking_interval=1 }) - **nil** -**Warning:** `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 updates from Superstack. To return to real-time updates, call `location.disable()` followed by `network.low_power_mode(false)`, then wait up to 15 minutes. +**Warning:** `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** @@ -777,13 +925,13 @@ location.get_latest() **Returns** - **table** - A table of key-value pairs: - - `valid` - **boolean** - `true` if the GPS data is valid, or `false` otherwise - - `latitude` - **number** - The current latitude - - `longitude` - **number** - The current longitude - - `altitude` - **number** - The current altitude - - `accuracy` - **number** - The location and altitude accuracy - - `speed` - **number** - The current speed - - `speed_accuracy` - **number** - The speed accuracy + - `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 @@ -793,25 +941,19 @@ location.get_latest() ```lua -- GPS must be enabled before getting a location fix -location.enable{ accuracy="HIGH", power_saving="OFF" } +location.enable{} --- Avoid sending logs or data while waiting for a fix — network --- activity competes for the modem hardware and delays acquisition +-- Avoid network activity while waiting for a fix. It competes +-- for the modem hardware and delays acquisition device.sleep(60) -local l = location.get_latest() - -print("valid: " .. tostring(l["valid"])) -print("latitude: " .. tostring(l["latitude"])) -print("longitude: " .. tostring(l["longitude"])) -print("altitude: " .. tostring(l["altitude"])) -print("accuracy: " .. tostring(l["accuracy"])) -print("speed: " .. tostring(l["speed"])) -print("speed_accuracy: " .. tostring(l["speed_accuracy"])) +local fix = location.get_latest() -print("satellites tracked: " .. tostring(l["satellites"]["tracked"])) -print("satellites in fix: " .. tostring(l["satellites"]["in_fix"])) -print("satellites unhealthy: " .. tostring(l["satellites"]["unhealthy"])) +if fix.valid then + print(string.format("%.5f, %.5f", fix.latitude, fix.longitude)) +else + print("No fix yet. Tracking " .. fix.satellites.tracked .. " satellites") +end ``` --- @@ -826,7 +968,7 @@ location.disable() - **nil** -**Warning:** 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 Superstack can push updates in real time. +**Warning:** 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** @@ -845,12 +987,12 @@ network.low_power_mode(false) #### Post log to Superstack ```lua -print(log) +print(...) ``` **Parameters** -- `log` - **string** - String to print +- `...` - **any** - One or more values to print. They are converted to strings and joined with tabs into one log **Returns** @@ -862,15 +1004,14 @@ print(log) -- Simple print print("hello world") --- Print variables -local my_num = 4 + 3 -print(my_num) +-- 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)) ``` -**Note:** Each log message is truncated to **1023 characters**. Prefer a single string argument: `print("a", "b")` produces **separate log entries** for each argument and separator, so use `string.format` or concatenation to combine values into one message. Logs stop being sent once the Deployment's data allowance is exceeded. +**Note:** `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](/pages/superstack/credit#when-a-fleet-runs-out-of-credit), the device discards logs instead of sending them. --- @@ -901,6 +1042,33 @@ device.sleep(1.5) --- +#### Sleep for a short duration + +```lua +device.sleep_ms(time) +``` + +**Parameters** + +- `time` - **integer** - The duration to sleep in milliseconds. From `0` to `1000` + +**Returns** + +- **nil** + +**Note:** 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** + +```lua +-- 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 @@ -912,13 +1080,13 @@ 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` - **number** - The constant charge current in mA. Must be between `32` and `800` in steps of `2` +- `current` - **integer** - The constant charge current in mA. Must be between `32` and `800` in steps of `2` **Returns** - **nil** -**Note:** 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 script restarts. +**Note:** 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** @@ -980,13 +1148,13 @@ 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 port power outputs off entirely +- `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** -**Note:** 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. +**Note:** 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** @@ -997,9 +1165,39 @@ device.power.set_vout(3.3) --- +### Code files + +#### Run another code file + +```lua +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 + +**Note:** Each call runs the file again, so call `require` once per file and keep the result. 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](/pages/superstack/cli#what-an-upload-sends). + +**Example** + +```lua +-- sensors.lua returns a table of functions +local sensors = require("sensors") +print(sensors.read_temperature()) +``` + +--- + ### Temporary files -**Note:** A temporary file is created by `storage.open()` and reached only through the handle it returns. Closing the handle deletes the file, and every temporary file is deleted when the code starts, stops or restarts. Storage is shared with the code files in the bundle, and provides roughly **48kB** of usable space in total. +**Note:** A temporary file is created by `storage.open()` and reached only through the handle it returns. Closing the handle deletes the file, and every temporary file is deleted when the code starts, ends, crashes, stops or restarts. Temporary files share storage with the code files in the bundle. The storage is **96KB**, and the file system uses part of it. #### Open a temporary file @@ -1016,19 +1214,14 @@ storage.open() ```lua -- Buffer readings in a temporary file while the network is down local readings = storage.open() -local count = 0 while not network.connected() do readings:append(device.power.battery.get_voltage() .. "\n") - count = count + 1 device.sleep(60) end -- Send the buffered readings once the network returns -for i = 1, count do - network.send_data{ battery_voltage=tonumber(readings:read{ line=i }) } -end - +network.post("https://example.com/api/readings", readings:read{ length=4096 }) readings:close() ``` @@ -1102,11 +1295,11 @@ handle:read{ line=1, length=nil, offset=0 } - `line` - **integer** - The line index to return. `1` is the first line, `2` the second, etc. Negative values index from the end: `-1` is the last line, `-2` the second to last, etc. Cannot be `0`, and cannot be combined with `length` or `offset` - `length` - **integer** - The number of bytes to read. Cannot be used with `line`. If longer than the file, a shorter result is returned -- `offset` - **integer** - When `length` is specified, read from this byte offset within the file +- `offset` - **integer** - The number of bytes to skip before reading. `0` reads from the start. Requires `length` **Returns** -- **string** - The contents read +- **string** - The contents read. A line is returned without its newline. `nil` if the line does not exist **Example** @@ -1117,7 +1310,7 @@ print(file:read()) -- Print the last line from the file print(file:read{ line=-1 }) --- Read 16 bytes starting from the 8th byte +-- Skip the first 8 bytes, then read 16 print(file:read{ length=16, offset=8 }) ``` @@ -1175,13 +1368,13 @@ Note: the returned value is in **milliseconds**, so 30 seconds is `30000` #### Get the current time and date ```lua -time.get_time_date({ unix_epoch, timezone }) +time.get_time_date({ unix_epoch=nil, timezone="+00:00" }) ``` **Optional parameters** -- `unix_epoch` - **number** - A Unix timestamp to convert to a time and date -- `timezone` - **string** - The timezone offset. E.g. `"+02:00"` or `"-07:30"` +- `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** @@ -1189,8 +1382,8 @@ time.get_time_date({ unix_epoch, timezone }) - `year` - **integer** - The current year - `month` - **integer** - The current month - `day` - **integer** - The current day - - `yearday` - **integer** - The current day of the year - - `weekday` - **integer** - The current day of the week since Sunday + - `yearday` - **integer** - The days since 1 January. `0` 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 @@ -1235,10 +1428,69 @@ device.FIRMWARE_VERSION **Returns** -- **string** - A string representing the current firmware version. E.g. `"0.1.0+0"` +- **string** - A string representing the current firmware version. E.g. `"3.0.0"` **Example** ```lua print(device.FIRMWARE_VERSION) ``` + +--- + +### JSON + +#### Encode a value as JSON + +```lua +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 + +**Note:** 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** + +```lua +-- 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 + +```lua +json.decode(text) +``` + +**Parameters** + +- `text` - **string** - The JSON text + +**Returns** + +- **any** - The decoded value. Objects and arrays become tables, and `null` becomes `json.null` + +**Note:** 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** + +```lua +local ok, message = pcall(json.decode, '{"led":true,"level":null}') + +if ok and message.level == json.null then + print("No level given") +end +``` diff --git a/plugins/superstack/skills/superstack-cli/references/api.md b/plugins/superstack/skills/superstack-cli/references/api.md new file mode 100644 index 0000000..016939a --- /dev/null +++ b/plugins/superstack/skills/superstack-cli/references/api.md @@ -0,0 +1,193 @@ + + +# Superstack API reference + +--- + +Your application sends data to S2 Modules with an HTTP `POST` to Superstack. Each request carries one message, such as a command, a setting or a JSON document. Superstack holds the message until each device collects it, and the Lua on the device receives it through [`network.assign_message_event`](/pages/superstack/lua#assign-an-event-handler-for-messages). + +Lua on the device sends data to your application with an HTTP request, which Superstack makes on the device's behalf. [Receive requests from a device](#receive-requests-from-a-device) describes what your application receives and how it must answer. + +To manage fleets, devices and code, use the [Superstack CLI](/pages/superstack/cli). + +--- + +## Contents + +- [Create a fleet key](#create-a-fleet-key) +- [Send a message](#send-a-message) +- [How a message reaches a device](#how-a-message-reaches-a-device) +- [Receive a message in Lua](#receive-a-message-in-lua) +- [Message errors](#message-errors) +- [Receive requests from a device](#receive-requests-from-a-device) + +--- + +## Create a fleet key + +A fleet key lets your application send messages to the devices in one fleet. The owner and any member of the fleet can create one. + +1. Find the id of your fleet: + + ```sh + superstack fleet list + ``` + +1. Create a fleet key, with a label that names the application that will use it: + + ```sh + superstack key create greenhouse-controller + ``` + + The CLI prints the fleet key once. Store it where your application can read it, because anyone who holds it can send messages to every device in the fleet. + +A fleet key starts with `ssf_` and reaches only its own fleet. It works until you revoke it or delete the fleet, even after the member who created it leaves the fleet. The owner and any member can revoke one: find its id with `superstack key list`, then run `superstack key revoke `. + +A fleet can have at most 100 fleet keys, and a label is at most 100 characters. + +--- + +## Send a message + +``` +POST https://supernext.siliconwitchery.com/fleets/{fleet_id}/messages +``` + +**Authentication** + +- Send the fleet key in the `Authorization` header as `Bearer ` +- The fleet key must belong to the fleet in the path + +**Query parameters** + +- `imei` - optional - The 15-digit IMEI of a device paired with the fleet. Repeat it to send the message to several devices. Leave it out to send the message to every device paired with the fleet +- `expires_in` - optional - How many seconds Superstack keeps the message for a device that has not collected it. From `30` to `1209600` (14 days). Defaults to `3600` (1 hour) + +**Request body** + +The message, at most 4096 bytes. It can be text or binary, such as JSON or a packed struct. Lua receives exactly these bytes as a string. Superstack ignores `Content-Type`. + +**Response (202 Accepted)** + +The body is empty. Superstack has queued the message for every device the request names, but no device has received it yet. A request without `imei` to a fleet that has credit but no paired devices also gets `202 Accepted`, and queues nothing. + +Send settings to one device: + +```sh +curl -X POST "https://supernext.siliconwitchery.com/fleets//messages?imei=" \ + -H "Authorization: Bearer " \ + --data-binary '{"interval":60,"led":true}' +``` + +Send the same settings to two devices, and keep them for a day: + +```sh +curl -X POST "https://supernext.siliconwitchery.com/fleets//messages?imei=&imei=&expires_in=86400" \ + -H "Authorization: Bearer " \ + --data-binary '{"interval":60,"led":true}' +``` + +Send a settings file to every device in the fleet: + +```sh +curl -X POST "https://supernext.siliconwitchery.com/fleets//messages" \ + -H "Authorization: Bearer " \ + --data-binary @settings.json +``` + +Use `--data-binary` rather than `--data`, because `--data` removes the newlines from a file. + +--- + +## How a message reaches a device + +When Superstack accepts a request, it queues one copy of the message for each device the request names. A device paired with the fleet later does not receive it. + +Superstack then asks each device to collect its messages straight away. A device in [low power mode](/pages/superstack/lua#set-low-power-mode) collects them at its next check-in. + +Each device receives its messages in the order your application sent them. Superstack removes a message from the queue when the device confirms that it received it. A message the device does not confirm stays queued, and Superstack tries again at the next check-in. + +The device confirms a message even when nothing receives it in Lua: + +- If the code is stopped, the device discards the message. +- If the code has not assigned a handler with `network.assign_message_event`, the device discards the message. +- If the code ends, stops or restarts before its handler runs, the device discards the message. + +If the device's confirmation is lost on the network, Superstack sends the message again, so Lua can receive the same message twice. Write a message that has the same effect when it arrives twice, such as `{"led":true}` rather than `toggle`. + +The device has room for one 4096-byte message, or several shorter ones, that Lua has not handled yet. Each message takes 2 bytes more than its length. The device runs one handler at a time, so messages wait on the device while a handler, such as one that makes a web request, is still running. When a message does not fit, the device refuses it. That message and every later one wait in Superstack for a later check-in. + +While the fleet has no [credit](/pages/superstack/credit), Superstack delivers no messages. Messages already queued wait until a top-up or until they expire. + +Superstack discards a message without delivering it in these cases: + +- The device has not confirmed it before `expires_in` runs out. +- The device has refused it, or stopped answering partway through it, three times. +- The device is unpaired from the fleet. Its queued messages are discarded, so a device paired with another fleet never receives them. + +--- + +## Receive a message in Lua + +Assign a handler before the messages arrive, and keep the code running, because the device discards messages while the code is stopped: + +```lua +network.assign_message_event(function(content) + local settings = json.decode(content) + device.digital.set_output("B1", settings.led) + print("Interval is now " .. settings.interval) +end) + +while true do + device.sleep(1) +end +``` + +The [Lua reference](/pages/superstack/lua#assign-an-event-handler-for-messages) describes `network.assign_message_event` and `network.unassign_message_event`. + +--- + +## Message errors + +Superstack refuses the whole request when any part of it fails, and queues nothing. The response body is a plain-text sentence that says what went wrong. Superstack checks the fleet key first, so a request without a valid fleet key gets `401 Unauthorized` whatever else is wrong. The exception is an address that has sent 20 invalid fleet keys. Superstack then refuses its requests with `429 Too Many Requests` before checking the key, and allows one more every 10 seconds. + +| Status | Response body | Cause | +| --- | --- | --- | +| `400 Bad Request` | `enter the 15-digit IMEI of each device` | An `imei` is not 15 digits | +| `400 Bad Request` | `device is not paired with this fleet` | An `imei` names a device that is not paired with the fleet | +| `400 Bad Request` | `expires_in is a whole number of seconds from 30 to 1209600 (14 days)` | `expires_in` is out of range or not a whole number | +| `400 Bad Request` | `the server could not read the message` | The request body could not be read | +| `401 Unauthorized` | `send a fleet key with the request` | The request has no fleet key | +| `401 Unauthorized` | `the fleet key is not valid, create a new one` | The fleet key has been revoked, its fleet has been deleted, or it was never valid | +| `402 Payment Required` | `the fleet has no credit, top it up to send messages` | The fleet has no [credit](/pages/superstack/credit). Top it up, then send the message again | +| `403 Forbidden` | `the fleet key belongs to another fleet` | The fleet key is for another fleet than the one in the path | +| `404 Not Found` | `no such fleet` | The fleet id in the path is not a whole number above 0 | +| `413 Content Too Large` | `the message can be at most 4096 bytes` | The message is longer than 4096 bytes | +| `429 Too Many Requests` | `device already has 100 queued messages, try again after it receives some` | A device the request names already has 100 messages queued | +| `429 Too Many Requests` | `too many requests, try again in s` | The fleet sent more than 100 requests at once, or more than 20 a second, across all of its fleet keys. Wait the number of seconds in the `Retry-After` header, then send again. Only this refusal has a `Retry-After` header | +| `503 Service Unavailable` | `the server could not check the fleet key` or `the server could not queue the message` | Superstack could not reach its database. Try again | + +--- + +## Receive requests from a device + +Lua on the device calls a function such as [`network.post()`](/pages/superstack/lua#send-a-post-put-or-patch-request-to-a-web-service), and Superstack makes the request to your application. Your application receives the method, URL, headers and body that the Lua code set. + +Your application must meet these limits, or Lua receives an error in place of the response: + +- **Public address.** Superstack connects only to public addresses, including after a redirect. It never connects to `localhost` or a private network. Lua receives `connection failed`. +- **8 seconds.** Superstack waits 8 seconds for the whole response, including any redirects. Lua receives `timeout`. +- **4096 bytes.** The response body is at most 4096 bytes. Lua receives `too large`. + +Unless the Lua code sets them, Superstack adds `User-Agent: Go-http-client/2.0`, or `Go-http-client/1.1` for a web service that does not use HTTP/2, and `Accept-Encoding: gzip`. When Superstack adds `Accept-Encoding`, it unzips a gzip response before Lua receives it, and the 4096-byte limit applies to the unzipped body. Superstack sets the `Host` header from the URL, and ignores one that the Lua code sets. + +Superstack follows up to 9 redirects. A request that needs more fails, and Lua receives `connection failed`. Lua receives the status code and body of the final response, but not its headers. A response with any status code, such as `404` or `500`, reaches Lua as a response, not as an error. + +**Note:** A `301`, `302` or `303` redirect turns the request into a `GET` without a body, and a redirect to a host other than the original or one of its subdomains drops the `Authorization` and `Cookie` headers. A `307` or `308` redirect keeps the method and body. To keep the method, body and headers, have Lua call the final URL. + +A request that fails is not retried.