Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .luarc.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
"json",
"network",
"location",
"storage",
"time"
]
}
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ One plugin, `superstack`, with two skills:

| Skill | What it teaches the agent |
|------------------|---------------------------|
| `s2-lua` | Writing Lua for the S2 Module: pins and ports, I2C, SPI, UART, analog, GPS, power, temporary files, network calls, messages from the user's project, and I2C sensor drivers from datasheets, including the traps the docs don't make obvious. |
| `s2-lua` | Writing Lua for the S2 Module: pins and ports, I2C, SPI, UART, analog, GPS, power, network calls, messages from the user's project, and I2C sensor drivers from datasheets, including the traps the docs don't make obvious. |
| `superstack-cli` | Driving the `superstack` CLI: login, fleets, pairing, uploading code, device state, logs, members, fleet keys and credit, plus messaging a device from the user's own project. |

The `superstack-cli` skill needs the [Superstack CLI](https://github.com/siliconwitchery/superstack-cli#install)
Expand Down
21 changes: 11 additions & 10 deletions plugins/superstack/skills/s2-lua/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ description: >-
Writes and reviews Lua code for the Silicon Witchery S2 Module (nRF9151-based
LTE-M and GNSS cellular module) running on Superstack. Covers digital and
analog IO on PORTA-PORTF, I2C, SPI, UART, PWM, GPS, power and battery,
temporary files, REST calls from the device, messages from the user's own
project, sleep and timing, and writing I2C sensor drivers from datasheets.
REST calls from the device, messages from the user's own project, sleep and
timing, and writing I2C sensor drivers from datasheets.
Use when the user mentions the S2 Module, Superstack device code or Lua,
wiring sensors to an S2, or IoT code for Silicon Witchery hardware.
license: Apache-2.0
Expand All @@ -32,10 +32,10 @@ Superstack. These facts shape all code:
Code files are read-only.
- Standard libraries: basic, `math`, `string`, `table`, `utf8`, `coroutine`,
plus a built-in `json` with `json.encode` and `json.decode`. **There is no
`io`, `os`, `debug` or `package`.** Use `storage.*`, `time.*` and `device.*`
instead.
`io`, `os`, `debug` or `package`,** so Lua has no file access beyond
`require`. Use `time.*` and `device.*` instead.
- New code **starts from the top of `main.lua`**. So does a restart and a
reboot. Globals and temporary files never survive into the next run.
reboot. Globals and tables never survive into the next run.
- There is no debugger. `print()` sends one log, which the user reads with
`superstack tail`. The loop is: edit, upload, read the log. An upload
usually lands within seconds, unless PSM is on (see the traps).
Expand Down Expand Up @@ -100,7 +100,7 @@ in [references/footguns.md](references/footguns.md).
it. Use messages for remote configuration instead of uploading new code.
A message arriving with no handler assigned is discarded.
7. **User data spends credit** at €1 per MB: every log, every network call and
response, every message, and every upload (changed files × target devices).
response, every message, and every upload (whole bundle × target devices).
Batch readings, and strip debug prints before a fleet upload. A fleet with
no credit sends no logs, and network calls return `no credit`.
8. **`print` joins its arguments with tabs into one log.** A log over about
Expand All @@ -110,10 +110,11 @@ in [references/footguns.md](references/footguns.md).
always check it. SPI, UART, analog and digital calls raise on failure, so
wrap risky sections in `pcall`. Handlers cannot yield, and an error inside
one crashes the program.
10. **Temporary files die with the run**: `storage.open()` returns a handle to
a new temporary file, deleted on close and whenever the code starts,
stops, crashes or is replaced. Nothing on the device survives a restart,
so keep durable state on the user's server.
10. **Buffered data dies with the run**: unsent data waits in a Lua table in
RAM, which is lost when the code ends, crashes, stops, restarts or is
replaced, and when the device restarts. A table that outgrows free memory
raises `not enough memory`, so cap it. Keep durable state on the user's
server, or on an SPI flash module driven from Lua.
11. **Power**: ports boot **live at 1.8 V**, so a 3.3 V sensor on an
unconfigured port half-works rather than failing cleanly. Call
`device.power.set_vout(3.3)` in setup. It sets **all** ports at once (1.8 to
Expand Down
28 changes: 15 additions & 13 deletions plugins/superstack/skills/s2-lua/references/examples.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Complete example programs

Full S2 Module Lua programs. The ground rules: code starts from the top of `main.lua` on new code, a restart or a reboot; there is no `io`, `os` or `package`; temporary files and globals never survive into the next run; data leaves through a REST call to the user's own endpoint, and arrives as a message from the user's project.
Full S2 Module Lua programs. The ground rules: code starts from the top of `main.lua` on new code, a restart or a reboot; there is no `io`, `os` or `package`; tables and globals never survive into the next run; data leaves through a REST call to the user's own endpoint, and arrives as a message from the user's project.

## Official examples index (s2-lua-examples repo)

Expand All @@ -27,13 +27,15 @@ Complete applications:

## Example A: Battery-powered environmental logger

An SHT45 logger that posts each reading to the user's own endpoint. It keeps readings in a temporary file while the device is out of coverage, sends them when the connection returns, and accepts a new sample interval as a message.
An SHT45 logger that posts each reading to the user's own endpoint. It keeps the newest 200 readings in a Lua table while the device is out of coverage, sends them when the connection returns, and accepts a new sample interval as a message.

Credit notes:

- Every log, every network call and its response, and every message spend credit. This program prints only on errors and after a backlog drains.
- Draining sends one request per buffered sample so each keeps its own timestamp. Aggregate instead, such as min, mean and max per hour, if credit matters more than per-sample timing.
- The backlog lives only as long as the run. New code, a restart or a reboot deletes it.
- Each body holds one reading, so it stays within the 4096-byte limit. Joining 200 of these readings into one body would not.
- The backlog lives only as long as the run. The code ending, crashing, stopping or restarting, new code or a reboot deletes it.
- The cap keeps the backlog from outgrowing free memory, which raises `not enough memory`. When the backlog is full, each new reading drops the oldest.

```lua
-- Battery-powered SHT45 environmental logger.
Expand Down Expand Up @@ -108,8 +110,7 @@ local function time_is_synced(ts)
return ts > 1000000000000
end

local backlog = storage.open()
local backlog_count = 0
local backlog = {}

-- Returns true once the server accepted the reading
local function post(line)
Expand All @@ -121,14 +122,12 @@ end
local function drain_backlog()
local sent = 0

while backlog_count > 0 do
local line = backlog:read{ line = 1 }
if not post(line) then
while #backlog > 0 do
if not post(backlog[1]) then
break
end

backlog:write(backlog:read{ length = math.maxinteger, offset = #line + 1 })
backlog_count = backlog_count - 1
table.remove(backlog, 1)
sent = sent + 1
end

Expand All @@ -153,9 +152,12 @@ while true do

drain_backlog()

if backlog_count > 0 or not post(line) then
backlog:append(line .. "\n")
backlog_count = backlog_count + 1
if #backlog > 0 or not post(line) then
if #backlog == 200 then
table.remove(backlog, 1)
end

table.insert(backlog, line)
end
else
print("SHT45 read failed (bus error or CRC mismatch)")
Expand Down
69 changes: 34 additions & 35 deletions plugins/superstack/skills/s2-lua/references/footguns.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ bricked. Each item is checked against the firmware source or the S2 datasheet.
- [Messages from the user's project](#messages-from-the-users-project)
- [Error handling differs per bus](#error-handling-differs-per-bus)
- [Handlers cannot yield, and their errors crash the code](#handlers-cannot-yield-and-their-errors-crash-the-code)
- [Temporary files die with the run](#temporary-files-die-with-the-run)
- [Buffered data dies with the run](#buffered-data-dies-with-the-run)
- [Retry pattern for a dropped connection](#retry-pattern-for-a-dropped-connection)
- [Battery charger voltage list has a gap](#battery-charger-voltage-list-has-a-gap)
- [Ports boot at 1.8 V; VOUT applies to all ports at once](#ports-boot-at-18-v-vout-applies-to-all-ports-at-once)
Expand Down Expand Up @@ -109,8 +109,8 @@ Credit costs €1 per MB of user data, counted on the data itself. User data is:
- every log, which includes every `print()`
- every network call and its response
- every message from the user's project
- every upload, which sends only the files that changed, to every target
device
- every upload, including each `superstack dev` save, which sends the whole
bundle to every target device. An upload of identical files sends nothing

Managing the device is free: check-ins, pairing, unpairing, starting,
stopping, restarting and firmware updates.
Expand Down Expand Up @@ -223,24 +223,19 @@ This applies to `device.digital.assign_input_event`,
`pcall` when they parse input from outside, such as a message.
- Any other digital or analog use of a pin cancels its input event.

## Temporary files die with the run

`storage.open()` creates a temporary file and returns its handle. There are no
named files.

- `handle:write(data)` replaces the contents. `handle:append(data)` adds to
them.
- `handle:read()` with no options returns the whole file, and raises
`not enough memory` when the file does not fit in free memory. Use
`handle:read{ line = n }` for line `n` (negative counts from the end), or
`handle:read{ length = n, offset = o }` for bytes, which also reads a large
file in parts.
- `handle:close()` deletes the file.
- **Every temporary file is deleted when the code starts, stops, restarts or
crashes, when new code arrives, and at reboot.** Nothing survives the run
that created it.
- Storage is shared with the code bundle. A write that does not fit raises
`there is not enough storage`.
## Buffered data dies with the run

Lua has no file access beyond `require`, so unsent data waits in a Lua table
in RAM.

- **A table is lost when the code ends, crashes, stops or restarts, when new
code arrives, and when the device restarts.** Nothing survives the run that
created it.
- A table that outgrows free memory raises `not enough memory`. Cap every
buffer, as the [retry pattern](#retry-pattern-for-a-dropped-connection) does.
- The Lua heap is larger than the 96 KB of storage, and storage holds only
code. For larger or durable buffering, connect an SPI flash module and drive
it from Lua with `device.spi.*`.

Code files in the bundle are read-only. Load one with `require("name")`, which
runs `name.lua` once and returns its first value, and later calls return the
Expand All @@ -250,36 +245,40 @@ same value. The name is a path: `require("lib/sensor")` loads
## Retry pattern for a dropped connection

Network calls fail with `no network` while the device is out of coverage.
Keep unsent readings in a temporary file and send them when the connection
returns. The backlog lives only as long as the run.
Keep unsent readings in a Lua table and send them when the connection returns.
The backlog lives only as long as the run. This one keeps the newest 200
readings and sends each in its own request. A joined backlog must stay within
the 4096-byte body limit.

```lua
local backlog = storage.open()
local backlog_lines = 0
local backlog = {}

local function send(reading)
local line = json.encode(reading)
local response, err = network.post(URL, line,
{ headers = { ["Content-Type"] = "application/json" } })

if err then
backlog:append(line .. "\n")
backlog_lines = backlog_lines + 1
if #backlog == 200 then
table.remove(backlog, 1)
end

table.insert(backlog, line)
return false
end
return true
end

local function drain()
while backlog_lines > 0 do
local line = backlog:read{ line = 1 }
local response, err = network.post(URL, line,
while #backlog > 0 do
local response, err = network.post(URL, backlog[1],
{ headers = { ["Content-Type"] = "application/json" } })

if err then
return
end
local rest = backlog:read{ length = math.maxinteger, offset = #line + 1 }
backlog:write(rest or "")
backlog_lines = backlog_lines - 1

table.remove(backlog, 1)
end
end
```
Expand Down Expand Up @@ -361,9 +360,9 @@ Checked against firmware 3.0.0:
| Busy loop | Does not harm the device. Lua runs at the lowest priority, and an instruction hook delivers stops and events. The cost is power, so always sleep in the main loop |
| Event handlers during `device.sleep()` | Run within about 100 ms, then the sleep resumes. Shared state they touch can change across any `sleep()` |
| Lua heap | All the RAM the firmware doesn't use, about 160 KB. Still avoid large tables and long strings |
| Storage | Up to 96 KB of flash, shared by the code bundle and temporary files, in 4 KB blocks |
| Storage | Up to 96 KB of flash in 4 KB blocks, holding only code |
| I2C | 7-bit addresses (0 to 127). `write_read` is a write, a stop, then a read, never a repeated start. A transfer is at most 8191 bytes, and a stuck bus times out after 2 s with `success = false` |
| SPI | Pin options `sclk_pin`, `mosi_pin`, `miso_pin` and `cs_pin` are all or none. At most 8191 bytes per transfer |
| Digital input | `get_input` and `assign_input_event` pull **down** unless `pull` says otherwise. `set_output` needs a boolean, not `1` or `0` |
| PSM timing | Requested as a 900 s periodic update and 30 s active time, hence "up to 15 minutes". The network may grant different values |
| State across new code | Globals do not survive. Code starts from the top of `main.lua`, and temporary files are gone |
| State across new code | Globals and tables do not survive. Code starts from the top of `main.lua` |
12 changes: 7 additions & 5 deletions plugins/superstack/skills/superstack-cli/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,8 @@ person, so run them like this:
dotfiles. A file argument lands at the top of the bundle under its own name.
3. The upload replaces the whole bundle. The server refuses it when:
- `main.lua` is missing.
- A path is `tmp` or starts with `tmp/`.
- A path is `.bundle` or starts with `.bundle/`, a name the device keeps for
itself.
- A path is longer than 255 bytes.
- The bundle does not fit the device's storage.
- The fleet has no credit.
Expand Down Expand Up @@ -134,8 +135,8 @@ A fleet upload reaches the devices paired with the fleet at that moment. A
device paired later needs its own upload.

`superstack dev <imei|fleet_id> <directory>` uploads on every change and
follows the log. Use it when the user is working interactively. It runs until
stopped.
follows the log. Each save spends credit for the bundle's full size. Use it
when the user is working interactively. It runs until stopped.

`superstack download <imei> <directory>` fetches the bundle the server holds
for a device. Nothing is read back from the device itself.
Expand Down Expand Up @@ -164,8 +165,9 @@ device. Stop is the remote kill switch. It always works, even without credit.
responses.
- Managing a device is free: check-ins, pairing, unpairing, starting,
stopping, restarting and firmware updates.
- An upload sends only the files that changed, but it sends them to every
target device. Estimate the cost before uploading to a large fleet.
- An upload sends the whole bundle to every target device, not only the files
that changed. An upload of identical files sends nothing. Estimate the cost
before uploading to a large fleet.
- A fleet with no credit refuses uploads and messages, sends no logs, and its
network calls from Lua return `no credit`. The code keeps running.
- `superstack account balance [fleet_id]` shows the credit left.
Expand Down
Loading