Programming Gogo
A book about gogo: a tiny actor VM for microcontrollers, programmed in a subset of Go, with Erlang-style actors, supervisors and ports.
It is written for programmers who know some Go or another C-like language, and assumes no knowledge of embedded programming or Erlang.
Contents
- Preface: what gogo is, what it is good for, and what it is not
- Getting Started:
gogo setup, build the tools, run a program, flash a board - Language Basics: the Go subset, what it leaves out, and what to write instead
- Actors: Spawn, Send, Receive, type switches, Call/Reply, names, timers, actors on other boards (with chapter 20)
- Failure and Recovery: exit reasons, links, monitors, TrapExit, supervisors, “let it crash”
- Memory Model: per-actor heaps and limits, copied messages, mailbox quotas, Bytes and Buffer
- Ports and Peripherals: ports, GPIO, events, debouncing, owners, Handoff
- Keyboard and Power: the
kbdandpowerports - Storage:
/flashand/sd,gogo/fs,gogo/kv,gogo/ringlog - Networking: DHCP, DNS, UDP, TCP, the HTTP client and server, the wall clock (
gogo/sys,gogo/sntp) - Configuration and Devices:
gogo config,sys.Config, Wi-Fi, the two boards - Toolchain Reference:
gogo build,run,dis,flash,monitor,firmware,config,setup - Appendices: library quick reference, exit reasons, error codes, limits, differences from Go, requirement names
- Hot Loading: loading code at run time, modules, supervised upgrades
- IMU and IR: the motion sensor, infrared send and receive, streams (
Chunk,Out,Done) - Audio: the microphone and speaker, recording to WAV files, playing them back
- HTTPS: https URLs, the clock, the keep-alive
http.Client, streaming uploads, the"tls"port - Embedding gogo: running gogo images inside a C program:
libgogo.a, the host table and the latched wake, stepping, posts, host ports, a sandboxed/flash - Text UI: the
"screen"port,gogo/tui: frames, windows, colours, menus, progress bars, status lines, a line editor, keys on both boards - Distributed Actors:
gogo/node: a server node and boards, remote PIDs, names, what a message may hold, lost nodes, security - Best Practices: actors as small machines, messages and
Bytes, backpressure, shared state, Call discipline, restarts, receive order, C or gogo, high-bandwidth streams (audio, sensors, cameras), streaming TCP and HTTP, a checklist - Extending gogo with C: why there is no FFI, port drivers in C (the driver table, events, memory, requirements, optional features, host simulation), a tested driver with generic types, host ports, pitfalls
- Bluetooth LE: the
"ble"port, a peripheral a phone app talks to: services and characteristics, events, values a phone reads, notifications with flow control, nRF Connect, the host simulation, memory and Wi-Fi
Known issues lists gogo’s open limitations, with workarounds.
Examples
Every program in the book is a complete, runnable example in
examples/, one directory per program, named after its
chapter (04-call, 09-kv-boot, …). The output printed in the book is
the real output of the host VM, kept next to each program in
expected.out and expected.err. To run them all and check that the
book is still right:
make vm
go build -o build/gogo ./cmd/gogo
docs/book/examples/run.sh
Chapter 23’s programs need a phone: each has a phone script that
tests/ble plays over gogovm’s Bluetooth socket
(go test ./tests/ble/, part of make test), and run.sh skips them.
Chapter 20’s programs need several VMs: they are the server and boards
of tests/dist/progs, run as separate host
VMs over real TCP by go test ./tests/dist/.
Chapter 18’s C programs are in examples/embed-c/;
make example-embed builds them, runs them and checks that every C
snippet in the chapter is cut from them. Chapter 22’s driver is in
examples/dice-driver/; make example-driver runs it on its test board and checks the chapter’s
snippets against the tree.
1. Preface
What gogo is
gogo is a small virtual machine for microcontrollers, plus a compiler for a
subset of Go. You write your program in Go syntax, the gogo tool on your
computer compiles it to a compact bytecode image, and the VM runs that image
on the board: today the M5StickS3 and the Cardputer ADV (both ESP32-S3), with
RP2040 boards planned. The same VM also runs on macOS and Linux, so you can
develop and test on your computer before you touch hardware.
A gogo program is not structured the way an ordinary Go program is. There are no goroutines, no channels and no shared memory. Instead a program is a set of actors, in the style of Erlang: small, isolated processes that each have their own memory and talk to each other only by sending messages. Peripherals (buttons, the keyboard, the battery gauge, files, network sockets) appear as ports: special actors that you send commands to and that send you typed event messages.
Here is the flavour of it. This actor counts button presses:
for {
switch m := actor.Receive().(type) {
case gpio.Edge: // the button was pressed
count++
case actor.Request: // someone asks for the count
actor.Reply(m, count)
}
}
Why it works the way it does
gogo makes a few choices that will feel unusual if you come from Go. They all follow from one goal: one failing part must never take the whole device down.
- Isolation. Every actor has its own heap. No pointer, slice or map can be shared between two actors, so no actor can corrupt another’s data. There are no locks because there is nothing to lock.
- Messages are copied.
actor.Sendmakes a deep copy of the message (slices, nested structs and all). The receiver gets its own copy. The one exception is frozenbytes.Bytes, which are immutable and so can be shared safely. - Per-actor memory limits. Each actor has a memory limit. An actor that goes over it (with a runaway loop, a leak, or a flood of incoming messages) is stopped. Other actors keep running.
- Let it crash. Instead of defensive error handling everywhere, an actor that hits something unexpected (division by zero, an index out of range, bad input) simply exits. Other actors are told through links and monitors, and a supervisor restarts the failed actor in a clean state. Resources the actor held, such as open pins and files, are released automatically when it exits.
- Small and readable. The VM is plain C99 with no third-party libraries and a 64 KB code budget. An idle actor costs about 150 bytes, so a board with 160 KB for actors can hold a thousand of them. The whole system is meant to be small enough for one person to read.
What gogo is good for
- Firmware for small devices built from several independent activities: a button handler, a sensor poller, a display updater, a little web server, a logger. Each becomes an actor, and a bug in one does not freeze the others.
- Devices that must keep running unattended: supervisors restart what fails.
- Learning and experimenting: the language, VM and network stack are small enough to study end to end, and every program also runs on your laptop.
What gogo is not good for
- Existing Go code. gogo compiles a subset of Go: no channels or
goroutines (actors instead), no generics, no
recover, nounsafeor reflection, package-level variables are read-only, and pointers, maps andfmtbehave a little differently (copied when sent, maps in key order, no reflection infmt). Most Go libraries will not compile as they are. Chapter 3 lists exactly what is in and what is out. - Number crunching. The VM is an interpreter, and every float is a
small heap object:
float32andfloat64work, but heavy maths belongs in C drivers. - Hard real-time work. The scheduler is preemptive but not real-time, and storage calls stall all actors while they run (a flash erase takes tens of milliseconds).
- General-purpose secure networking. There is an HTTPS client (TLS 1.2, one connection at a time), but no TLS server, no client certificates and no HTTP/2.
- Big data on a board. Each actor is limited to 16 KB by default on a board, and a single actor can never use more than 256 KB there (on a computer, 1 MB by default and up to 1 GB).
Where gogo is going
This book describes what is on gogo’s main branch.
The next steps, in order:
- Embed mode (in progress): embedding the VM in other programs, the way Lua is embedded, for desktop and server programs, phone apps and test tools. The C library and its API are in place (chapter 18); the network and the board peripherals are not in it yet.
- Language completeness: more of Go. Methods, interfaces,
error,panicand type assertions are in; pointers, maps, arrays, sized integers and floats are next (chapter 3 lists what is missing today). - Bluetooth (BLE): talking to a phone app, and setting up Wi-Fi from the phone.
HTTPS (TLS, chapter 17) is done. RP2040 boards are planned, with the
board and the timing still open. The design document,
docs/design.md, describes how the VM works.
How to read this book
The chapters build on each other:
| Chapter | What you learn |
|---|---|
| 2. Getting Started | Build the tools, run a program on your computer, flash a board |
| 3. Language Basics | The Go subset: what works, what does not, and what to do instead |
| 4. Actors | Spawn, Send, Receive, Call/Reply, names, timers |
| 5. Failure and Recovery | Exit reasons, links, monitors, supervisors, “let it crash” |
| 6. Memory Model | Per-actor heaps and limits, message copying, Bytes and Buffer |
| 7. Ports and Peripherals | GPIO, events, owners, Handoff |
| 8. Keyboard and Power | The kbd and power ports |
| 9. Storage | Files on /flash and /sd, kv, ringlog |
| 10. Networking | DHCP, DNS, UDP, TCP, HTTP client and server, the date (SNTP) |
| 11. Configuration and Devices | gogo config, Wi-Fi, the two boards |
| 12. Toolchain Reference | Every gogo command |
| 13. Appendices | Library quick reference, exit reasons, error codes, limits, differences from Go, requirement names |
| 14. Hot Loading | Loading code at run time: gogo/code, modules, supervised upgrades |
| 15. IMU and IR | The motion sensor, infrared send and receive, streams |
| 16. Audio | The microphone and speaker, WAV files |
| 17. HTTPS | https:// URLs, the clock, keep-alive http.Client, streaming uploads, the "tls" port |
| 18. Embedding gogo | Running images inside a C program: libgogo.a, the host table, stepping, posts, host ports |
Actors need not share a board: chapter 20, Distributed Actors, lets a PID name an actor on another board or a server, with the same Send, Call, links and monitors.
Every example in the book is a complete program in
docs/book/examples/, and the output shown is the real output
of running it on the host VM. You can run all of them with
docs/book/examples/run.sh, which also checks the output against the
book. Where the behaviour is likely to surprise you, the book says so in
a Note box; the open limitations are collected in
docs/known-issues.md.
You should know some Go, or at least one C-like language. You do not need to know Erlang or embedded programming; the book explains the ideas as they come up.
2. Getting Started
This chapter puts gogo on a board with one command, then builds the tools from source, runs a first program on your computer, and shows the manual way to flash a board.
2.1 The quick way: gogo setup
gogo setup takes a new M5StickS3 or Cardputer ADV to a running program:
it identifies the board, downloads the matching firmware, flashes it, sets
up Wi-Fi and runs a first program. You need:
- the board and a USB-C data cable (some cables only charge);
- the
gogocommand, prebuilt for your system; - esptool 5 or newer, the ESP32 flashing tool:
pip install esptoolorbrew install esptool.
You do not need Go, a C compiler or ESP-IDF.
Install gogo
On macOS and Linux, one command installs it:
curl -fsSL https://raw.githubusercontent.com/c4pt0r/gogo/main/install.sh | sh
gogo version
The script (install.sh in the repository) picks the file for your
system and CPU (amd64 or arm64), checks it against the release’s
SHA256SUMS, and installs gogo in /usr/local/bin, or in ~/.local/bin
when /usr/local/bin is not writable (it tells you if that directory is
not on your PATH). It also installs gogovm when the release has one.
GOGO_VERSION=v0.1.0 installs a given release and GOGO_INSTALL_DIR=dir
chooses the directory, for example
curl -fsSL .../install.sh | GOGO_INSTALL_DIR=~/bin sh.
Each release on GitHub has the command for macOS, Linux and Windows, on
amd64 and arm64: gogo-darwin-arm64, gogo-darwin-amd64,
gogo-linux-amd64, gogo-linux-arm64, gogo-windows-amd64.exe and
gogo-windows-arm64.exe. On Windows, or to install by hand, download the
file for your system from the release page and put it on your PATH as
gogo (gogo.exe on Windows). By hand on an Apple silicon Mac:
curl -L -o gogo https://github.com/c4pt0r/gogo/releases/latest/download/gogo-darwin-arm64
chmod +x gogo
sudo mv gogo /usr/local/bin/
A file downloaded with a browser on macOS may need
xattr -d com.apple.quarantine gogo before it runs.
Run it
Connect the board and run:
gogo setup
It works in six steps, says what each one does, and asks before it writes to the board:
[1/6] Checking the environment
esptool 5.6.0 (/usr/local/bin/esptool)
port /dev/cu.usbmodem5101
[2/6] Identifying the board
$ esptool --port /dev/cu.usbmodem5101 --after watchdog-reset read-flash 0x8000 3072 ...
chip: ESP32-S3-PICO-1 (LGA56) (revision v0.2), embedded PSRAM
This looks like the M5StickS3. Right? [Y/n]
[3/6] Getting the firmware
release: https://github.com/c4pt0r/gogo/releases/latest/download
sticks3-flasher_args.json (899 bytes, sha256 ok)
sticks3-bootloader.bin (18880 bytes, sha256 ok)
sticks3-partition-table.bin (3072 bytes, sha256 ok)
sticks3-gogo.bin (1093072 bytes, sha256 ok)
[4/6] Flashing the firmware
board firmware unknown (no answer on its console); flashing it
0x00000000 bootloader.bin (18880 bytes)
0x00008000 partition-table.bin (3072 bytes)
0x00010000 gogo.bin (1093072 bytes)
not written: NVS 0x9000..0xf000 (settings such as Wi-Fi stay)
Flash this firmware to the M5StickS3 on /dev/cu.usbmodem5101? [Y/n]
[5/6] Setting up Wi-Fi
Set up Wi-Fi now? [Y/n]
scanning for networks on the board...
1) Home Net ch 6 -50 dBm
2) another network (type its name)
Which network? [1]
Wi-Fi password (not shown):
saved on the board: wifi.ssid=Home Net, wifi.password=(set)
waiting for the board to join...
| gogo: wifi connected (Home Net, ch 6, -50 dBm)
Wi-Fi works
[6/6] Running a first program
hello program: 1552 bytes, to the image partition at 0x210000
...
| gogo <version>: image 1552 bytes, arena 163840 bytes, free RAM <F> (largest <L>)
| hello from gogo on the M5StickS3!
- Environment. It finds esptool and the board’s serial port
(
/dev/cu.usbmodem*on macOS,/dev/ttyACM*on Linux). With several ports it asks which one. On Windows, pass-port COM5; there setup flashes the firmware and the first program but skips the Wi-Fi step and does not watch the board’s console (gogo cannot use the serial console on Windows). - Board. esptool reports the chip. Both boards are ESP32-S3s; the StickS3 has embedded PSRAM and the Cardputer ADV has none, so that is the guess, which you confirm (if esptool does not say, setup asks). Any other chip is refused.
- Firmware. It downloads the board’s firmware from the gogo release
that matches your
gogo(or the latest one), checks every file against the release’sSHA256SUMS, and keeps them in your user cache directory (~/Library/Caches/gogoon macOS,~/.cache/gogoon Linux), so a second run downloads onlySHA256SUMSagain. - Flash. First it asks the firmware already on the board which
version it is (
gogo device info, chapter 12). If that is exactly the version about to be flashed, built for the same board, and the board’s app is that very build (its SHA256, read from the board’s flash, the same as the firmware’s) with the same partition table, it saysthe board already runs gogo <version> (<board>, app <sha>); not reflashingand moves on;-reflashflashes anyway. Otherwise (another version, a new board, a firmware too old to answer, a development build) it says why in one line and writes the bootloader, the partition table and the firmware at the offsets the firmware build lists. It never erases the chip and never writes the NVS partition, where the board keeps its settings, so a Wi-Fi setup from before survives. If the firmware now on the board keeps its settings somewhere else (a board straight from the factory may), or its partition table cannot be read, setup stops and says so;-new-layoutflashes anyway, still without writing either settings area. The old settings are then not used, and later firmware or programs may reuse the space where they were. - Wi-Fi. The board scans for networks and you pick one. The
password is read without echo and sent only to the board; gogo never
prints or stores it. You can skip this step and use
gogo configlater (chapter 11). - First program. A small program is flashed to the program
partition; the board shows its greeting on the screen and on the
console, where
gogo setupwaits for it.
When something fails, gogo setup prints what went wrong and a line
starting fix: that says what to do, then stops. Running it again is
always safe.
Options
| Option | Effect |
|---|---|
-port P | the board’s serial port |
-board sticks3|cardputer | skip the board question |
-version vX.Y.Z | that release instead of the one matching gogo |
-release-url URL|DIR | the files of one release from another place: an http(s) URL or a local directory (also GOGO_RELEASE_URL) |
-offline | build the firmware locally instead of downloading it |
-skip-wifi | leave the Wi-Fi settings as they are |
-reflash | flash the firmware even when the board already runs the same version |
-new-layout | flash even though the board keeps its settings elsewhere than the new firmware, or its partition table cannot be read (the old settings are then not used, and their space may be reused later) |
-yes | accept every default without asking (Wi-Fi is then skipped) |
-dry-run | read the board and download, but only print the commands that would write to it (and whether the firmware would be flashed at all) |
-esptool path | the esptool to run |
-no-usb-reset | do not reset the board’s USB device when it stops answering (section 2.5, Troubleshooting) |
Without a release to download (no network, or no such release),
gogo setup offers to build the firmware with ESP-IDF instead, if it is
installed (idf.py on PATH, $IDF_PATH or ~/esp/esp-idf) and you run
it inside the gogo source tree. Section 2.6 has the manual commands.
The prebuilt gogo also compiles and flashes your own programs (section
2.5). To run programs on your computer, as most of this book does, you
also need the host VM, gogovm. Each release has it for macOS and Linux:
gogovm-darwin-arm64, gogovm-darwin-amd64, gogovm-linux-amd64 and
gogovm-linux-arm64. Put it next to gogo, named gogovm (the asset
name works too):
curl -L -o gogovm https://github.com/c4pt0r/gogo/releases/latest/download/gogovm-darwin-arm64
chmod +x gogovm
sudo mv gogovm /usr/local/bin/ # the directory where gogo is
gogo env # shows the gogovm it found
The release VM has no tls port (HTTPS on the host, chapter 17); for
that, build gogo from source (section 2.2).
Set up Wi-Fi from your phone
A board can also get its Wi-Fi network from a phone, over Bluetooth, with no computer attached. The board’s firmware does it, before any program runs, so the program never sees the password. It uses Espressif’s standard provisioning protocol, so the phone app is Espressif’s own ESP BLE Provisioning (free, for Android and iOS); gogo has no app of its own.
The firmware does this with its bleprov feature, which is on in the
default firmware of both boards, beside the program’s own Bluetooth port
(ble, chapter 23): both use the one radio, never at once. A release
older than the first with Bluetooth lacks it; build and flash the
firmware from the gogo source tree as in section 2.6. Like gogo setup,
this leaves the board’s settings and program alone. gogo firmware
(chapter 12) keeps bleprov in a trimmed firmware whenever it has ble
and net (the setup key is read without the keyboard driver, so the
Cardputer’s works without kbd), and -without bleprov leaves the
setup mode out.
Then:
-
Hold the setup key and start the board. On the M5StickS3 that is button A (KEY1, the big front button); on the Cardputer ADV it is W (for Wi-Fi). Hold it while you switch the board on or press its reset button; the screen says
gogo: keep holding button A for Wi-Fi setup; keep holding for about a second, until it shows the setup. Nothing else opens provisioning: an unconfigured board does not start it on its own, and a board that restarts by itself (after a crash, a watchdog, a low battery, or the end of a setup session) does not even look at the key, so a program that uses button A is never taken over. -
The screen shows the session:
gogo: Wi-Fi setup over Bluetooth, 120 s gogo: app: ESP BLE Provisioning gogo: device PROV_gogo_9B56 gogo: PIN 639615 gogo: press button A again to cancelThe device name ends in four hex digits of the board’s Bluetooth address. The PIN is new at every session. A line repeats the PIN with the time left every 15 seconds. The same lines go to the serial console.
-
In the app, choose to provision a new device over BLE. When it offers to scan a QR code, choose to continue without one (the board shows none), then pick
PROV_gogo_...from the list. The app asks for the proof of possession (on some versions the “PIN” or “password”): type the PIN from the screen. If the app asks for a username, it iswifiprov, the app’s default. -
Type the network name and password. The board does not scan for networks, so the app asks for the name instead of listing them. The password is the network’s passphrase, up to 63 characters (as for
gogo setup); a 64-digit hexadecimal key is not accepted. -
The board joins that network to check the password, and the app shows the result.
What happens next:
- Success. The app says the device is connected. The board writes
the network into
wifi.ssidandwifi.password, exactly asgogo setupandgogo configdo (chapter 11), saysgogo: Wi-Fi settings saved (...)and restarts. It boots normally and joins the new network:gogo monitor -resetshowsgogo: wifi connected (<name>, ...), andgogo config get wifi.ssidthe name. - Wrong password or no such network. After three tries the app shows
the failure (
could not joinornetwork not foundon the board’s screen). Nothing is saved; send the settings again from the app within the same session. - Wrong PIN. The app cannot open a session (
session refusedon the screen). Try again with the right PIN; after five refused sessions the board closes the setup. - Cancel. Let go of the key and press it again: the board says
gogo: Wi-Fi setup cancelled, nothing changedand restarts as before. - Timeout. After 120 seconds without success the board says
gogo: Wi-Fi setup timed out, nothing changed, restarts and runs as before with its old settings. A join already under way at the end gets up to 30 seconds more, and if it succeeds the settings are saved as above, even past the 120 seconds. A key still held at that restart does not start another session. - A phone that connects and does not open a session (the PIN typed and checked) within 60 seconds is dropped, so a stranger cannot hold the setup for the whole window. Once the PIN is accepted, the app may stay connected until the end of the 120 seconds while you type the network name and password.
Every session ends with a restart, so the program starts afresh with the radio and its memory in the normal state.
The security: the session is Espressif’s security 2, a password authenticated key exchange (SRP6a) with the PIN, then AES-GCM for every message, so someone nearby who does not see the screen cannot join or read the password, and a recording of the radio traffic does not reveal the PIN. The window is open only while you hold the key at boot and for two minutes at most. Section 5.4.11 of the design has the details.
2.2 Building the tools from source
To change gogo itself, run its tests, or have a host VM with HTTPS, build the tools from source.
What you need
On your computer (macOS or Linux):
- Go 1.27 or newer, to build the
gogocommand (the compiler and board tools). It uses only Go’s standard library. - A C compiler and
make, to buildgogovm, the VM that runs programs on your computer. Any C99 compiler works (cc,clang,gcc). - The gogo source tree.
To flash firmware by hand you also need ESP-IDF, covered in section 2.6. You do not need it to follow most of this book: every example runs on your computer.
Building
From the root of the gogo source tree:
make vm # builds build/gogovm, the host VM
go build -o build/gogo ./cmd/gogo
build/gogo is the only command you use directly. When it runs a program it
looks for the VM in this order: $GOGO_VM; gogovm in the directory of
the gogo command itself (build/gogovm here, or wherever a release put
it); build/gogovm in the gogo tree around gogo or your current
directory. gogo env prints the one it would use.
Run it without arguments to see what it can do:
$ build/gogo
usage: gogo build [-path dirs] [-o out.ggb] <dir|file.gg>
gogo run [--key c=pin]... [--fs-root DIR] [--actor-memory SIZE] [--memory SIZE] [--max-actors N] [--max-ports N] [--max-links N] [--bytes-handles N[/M]] [-path dirs] <dir|file.gg|file.ggb> [args...]
gogo env [-path dirs]
gogo dis <file.ggb>
gogo info [-path dirs] <file.ggb|dir|file.gg>
gogo flash [-port P] [-esptool path] [-path dirs] [-no-usb-reset] <app.ggb|dir|file.gg>
gogo push [-port P] [-timeout seconds] [-no-usb-reset] <file.ggb> [/flash/path]
gogo monitor [-port P] [-timeout seconds] [-until text] [-reset] [-no-usb-reset]
gogo firmware (-board sticks3|cardputer | -port P [-esptool path] [-no-usb-reset]) [-o dir] [-build] [-with list] [-without list] [-component dir]... files...
gogo config [-port P | -local] [-no-usb-reset] set <key> <value|-> | get <key> | list | rm <key> | import [-n] <file|-> | export | keys | scan | stats
gogo device [-port P] [-yes] [-no-usb-reset] info | scan | stats | format-flash | usb-reset
gogo setup [-port P] [-board sticks3|cardputer] [-version vX.Y.Z] [-release-url URL|DIR] [-esptool path] [-offline] [-skip-wifi] [-new-layout] [-reflash] [-yes] [-dry-run] [-no-usb-reset]
gogo version
The rest of this book writes gogo for build/gogo. Put it on your PATH
if you like.
2.3 Your first program
A gogo program is a directory holding one package main (in one or more
.gg files: gogo source, Go syntax) with a func main():
// The smallest gogo program: package main, func main, println.
package main
func main() {
println("hello, gogo", 42, true)
}
Run it with gogo run and the directory:
$ gogo run docs/book/examples/02-hello
hello, gogo 42 true
gogo run compiles the directory to a temporary image and runs it on the
host VM. println is the only printing function: it prints its arguments
separated by spaces, followed by a newline, on standard output. (There is no
fmt package.)
When the program has nothing left to do (no actor can run, no timer is
pending, no input can arrive) the VM exits. The exit status says how
main ended: 0 when it returned, 4 when it crashed, or the code it
passed to actor.Exit (chapter 12 has the table). Crashes of other
actors are reported on standard error, as you will see in chapter 5,
and do not change it.
Scripts
gogo run also takes a single .gg file, and compiles that file alone:
$ gogo run hello.gg
A file whose first line starts with #! is an executable script: the
compiler reads that line as an empty one (line numbers in errors stay
right), so with
#!/usr/bin/env -S gogo run
package main
func main() {
println("hello from a script")
}
and chmod +x hello.gg, ./hello.gg runs it (gogo must be on your
PATH). env -S, which splits gogo run into two words, is in macOS and
in GNU coreutils 8.30 and newer, but not in BusyBox (Alpine) or older
coreutils. There, name gogo by its absolute path instead, which needs no
env: #!/usr/local/bin/gogo run (the kernel passes run as one
argument).
The name need not end in .gg: gogo run reads any file starting with
#! as source. Arguments after the script are the program’s: it reads
them with sys.Args() (chapter 12).
A single file and a directory differ: gogo run dir compiles every .gg
file in dir as one package main, so a directory of scripts, each with
its own func main, only runs file by file. A script can still import
packages from its directory (import "scripts/calc" for scripts/calc/
next to a script in scripts/) and from the search path, as below.
Packages and GOGOPATH
A program can be split into packages of its own (section 3.1.1):
import "app/shapes" in a program in app/ is the directory
app/shapes/. Packages that several programs share live in a directory
on the search path, by default $HOME/gogo:
mkdir -p ~/gogo/lib/ring # import "lib/ring"
export GOGOPATH=$HOME/gogo:$HOME/work/gogo-pkgs # optional: several directories
gogo env # prints the search path
gogo build -path dirs and gogo run -path dirs use dirs instead of
GOGOPATH for one build.
2.4 A first actor
The main function runs in the first actor. It can start more with
actor.Spawn, which takes a function to run, and talk to them with
actor.Send and actor.Receive:
// A first actor: main spawns a greeter, sends it a name, and waits for the
// greeting to come back.
package main
import "gogo/actor"
// Greet asks the greeter to greet Name and answer to From.
type Greet struct {
From actor.PID
Name string
}
func greeter() {
for {
switch m := actor.Receive().(type) {
case Greet:
actor.Send(m.From, "hello, "+m.Name)
}
}
}
func main() {
g := actor.Spawn(greeter)
actor.Send(g, Greet{From: actor.Self(), Name: "world"})
println(actor.Receive())
}
hello, world
Read it in order:
actor.Spawn(greeter)starts a new actor runninggreeterand returns its PID (process identifier).actor.Send(g, Greet{...})puts aGreetmessage in the greeter’s mailbox. The message carriesactor.Self(), main’s own PID, so the greeter knows where to answer.- The greeter’s
actor.Receive()returns the message as anany; the type switch finds out it is aGreet. - The greeter sends a string back, and main’s
actor.Receive()returns it.
Chapter 4 covers all of this in detail. Notice already that greeter is
still waiting in Receive when main returns. That is fine: nothing can
ever reach it again, so the VM exits.
Editor support
gogo source files end in .gg, and compiled images in .ggb. A .gg
file is Go syntax. The repository’s editors/
directory has ready-made support that gives .gg a gogo file type (Go
highlighting and indentation, plus the //gogo: directives and #!
scripts) and a black and white color scheme, gogo mono:
-
VS Code: link the extension and restart VS Code,
ln -s "$PWD/editors/vscode" ~/.vscode/extensions/gogo-lang -
Vim / Neovim: add
editors/vimto the runtime path,set runtimepath^=/path/to/gogo/editors/vimand optionally
colorscheme gogo-mono. -
Emacs: with
go-modeinstalled, loadeditors/emacs/gogo-mode.el((require 'gogo-mode)after adding the directory toload-path).
In any other editor, map the extension to Go: in VS Code without the
extension that is "files.associations": { "*.gg": "go" }, in Vim
autocmd BufRead,BufNewFile *.gg setfiletype go.
That is syntax only. gopls and go vet do not apply: the Go toolchain
does not read .gg files, and gogo is a subset of Go with its own
packages (gogo/actor, gogo/net, …), which exist only inside the gogo
compiler. Programs are only ever compiled and run by gogo, never by go run; gogo build is the judge of what is valid. Their sources are in
lib/ of the gogo tree (one directory per package) if you want to read
an API.
2.5 Running on a board
Programs and firmware are separate on the board. The firmware (the VM,
drivers, Wi-Fi, file systems and the screen console) is flashed once, by
gogo setup (section 2.1) or by hand (section 2.6). Your program
image goes into its own flash partition and can be replaced in a
second, without touching the firmware.
Build, flash and watch a program
gogo build docs/book/examples/02-hello -o hello.ggb
gogo flash hello.ggb
gogo monitor -reset -timeout 5 -until "gogo: vm exited"
gogo buildcompiles the directory to an image file (.ggb; without-oit writes<directory name>.ggbin the current directory).gogo flashwrites the image to the board’s program partition. It needsesptoolon yourPATH(the one you installed forgogo setup, or ESP-IDF’s, which itsexport.shputs there) and uses the only board port it finds (/dev/cu.usbmodem*on macOS,/dev/ttyACM*on Linux); pass-portif there are several. It also takes a directory, and builds it first:gogo flash docs/book/examples/02-hellodoes both steps.gogo monitorcopies the board’s console to your terminal.-resetrestarts the board first, so you see the program from the beginning;-timeout 5stops after 5 seconds;-untilstops at the first line containing that text.
The board prints a boot line, runs the program, and prints a line when the VM exits:
gogo <version>: image <N> bytes, arena <cap> bytes, free RAM <F> (largest <L>)
hello, gogo 42 true
gogo: vm exited (<code>), arena used <bytes>
Everything the program prints also appears on the board’s screen; crash reports (standard error) are shown in red.
Note. Only one program can use the serial port at a time. Close
gogo monitor(or any other serial terminal) beforegogo flashorgogo config.
Note. The image format has a version. When you update gogo and the version changes, reflash the firmware too (run
gogo setupagain, or section 2.6): an older firmware refuses a newer image withgogo: bad image (unsupported version).
Troubleshooting
no answer from the board, or esptool’sNo serial data received. The board’s USB serial link sometimes goes silent while the program keeps running.gogorecovers it on its own on macOS and Linux: when the board’s USB device fails a descriptor request too (a board that runs other firmware does not), it bus-resets the device (the chip is not restarted), retries once and printsgogo: the board's USB link was silent; reset it (USB bus reset).gogo device usb-resetdoes the same by hand. On Linux the reset needs a udev rule (gogoprints it when it is missing;docs/known-issues.mdhas it); on Windows, or if the board still does not answer, unplug it and plug it in again.- The port is busy. Another program has it open: close
gogo monitoror the serial terminal.gogodoes not reset a board’s USB device while another of your programs has the port open; it cannot see programs run as root or by other users, so close those yourself. gogo: bad image (unsupported version). The firmware is older than the image format: update it (note above).
You now have the whole loop: edit, gogo run on the computer, then gogo build and gogo flash for the board. The next chapter looks at the
language itself.
2.6 Flashing the firmware by hand
gogo setup is the easy way to flash the firmware. To build it yourself,
for example after changing the firmware, install ESP-IDF and use
idf.py from the gogo tree. gogo uses ESP-IDF v6.1.1:
mkdir -p ~/esp && cd ~/esp
git clone -b v6.1.1 --recursive --shallow-submodules --depth 1 https://github.com/espressif/esp-idf.git
cd esp-idf && ./install.sh esp32s3
Then, from the gogo tree, for the M5StickS3:
. ~/esp/esp-idf/export.sh
idf.py -C platform/esp32s3 build
idf.py -C platform/esp32s3 -p /dev/cu.usbmodemXXXX flash
The Cardputer ADV firmware is built in its own directory with its own settings:
idf.py -C platform/esp32s3 -B platform/esp32s3/build-cardputer -DGOGO_BOARD=cardputer \
-DSDKCONFIG=build-cardputer/sdkconfig \
-DSDKCONFIG_DEFAULTS="sdkconfig.defaults;sdkconfig.ble;sdkconfig.cardputer" build
idf.py -C platform/esp32s3 -B platform/esp32s3/build-cardputer -p /dev/cu.usbmodemXXXX flash
Make sure you flash the right firmware to the right board (esptool chip-id reports embedded PSRAM on the StickS3 and none on the Cardputer
ADV). Chapter 11 says more about the two boards.
idf.py flash writes the same three files as gogo setup and, like it,
leaves the NVS partition (and so the Wi-Fi settings) alone.
gogo firmware (chapter 12) builds a firmware with only the parts your
programs need.
3. Language Basics
gogo programs are written in Go syntax and type-checked by Go’s own type checker, so everything that compiles means what it means in Go, with one deliberate exception (messages are copied, chapter 6). But gogo accepts only a subset of Go. The subset is small on purpose: every feature costs code in a VM that must fit in 64 KB, and some Go features (shared memory, goroutines) would break the isolation between actors.
This chapter walks through what you can use, then lists what you cannot and what to write instead. The compiler checks the subset with an allow-list: anything it does not know is rejected with an error of the form
main.gg:LINE:COL: gogo: <what> not supported
so you will never get a program that silently behaves differently from Go.
3.1 Programs and packages
A program is a directory with package main and func main(), the
build root. package main can be split over several .gg files (gogo
source files; other files in the directory, .go files included, are not
read). A program can import gogo’s own packages, all under the gogo/
path, and packages of your own (section 3.1.1):
| Package | What it is |
|---|---|
gogo/actor | spawn, send, receive, links, monitors, timers, names |
gogo/supervisor | restart a failing actor |
gogo/port, gogo/gpio | open and close ports, the stream protocol; GPIO pins |
gogo/bytes | Bytes (immutable, shareable) and Buffer |
gogo/strings, gogo/strconv | string and number helpers |
gogo/kbd, gogo/power | keyboard and battery |
gogo/fs, gogo/kv, gogo/ringlog | storage |
gogo/net, gogo/dhcp, gogo/dns, gogo/http | networking |
gogo/sys | the wall clock, randomness, settings from the device’s configuration store |
gogo/errors | New, Is, Unwrap, and the error codes every package shares (errors.NotFound, …) |
Go’s standard library is not available. Importing fmt looks for a
package of your own called fmt, finds none and says where it looked:
main.gg:2:8: gogo: import "fmt": package not found; searched:
. (build root: serves only imports starting with "app/")
/home/you/gogo/fmt (search path: no such directory)
Renamed imports (import s "gogo/strings") are rejected.
3.1.1 Packages of your own
Any import that does not start with gogo/ is a package of your own: a
directory of .gg files, all with the same package clause. Inside the
build root, the import path starts with the root directory’s name. For a
program in app/:
app/
main.gg package main: import "app/shapes", "app/text/banner"
shapes/
shapes.gg package shapes
square.gg package shapes
text/banner/
banner.gg package banner
// A program of three packages: package main here, app/shapes and the
// nested app/text/banner. The imports start with app/, the name of this
// directory (the build root).
package main
import (
"app/shapes"
"app/text/banner"
)
func main() {
r := shapes.Rect{W: 3, H: 4}
println(banner.Title("shapes"))
println("area", shapes.Area(r), "perimeter", shapes.Perimeter(r))
sq := shapes.Square(5)
println("square", sq.W, sq.H, shapes.Area(sq))
}
// Package shapes measures rectangles. Its name is its directory's name.
package shapes
// Rect is a W by H rectangle.
type Rect struct{ W, H int }
// Area is W times H.
func Area(r Rect) int { return r.W * r.H }
// Perimeter is the length around r.
func Perimeter(r Rect) int { return 2 * (r.W + r.H) }
$ gogo run docs/book/examples/03-packages/app
----------
| shapes |
----------
area 12 perimeter 14
square 5 5 25
An import is looked up in this order, and the first directory that holds
.gg files wins:
- The build root.
import "app/shapes"in a program built fromapp/isapp/shapes/;app/text/bannerisapp/text/banner/. - The search path, for packages shared between programs: each
directory of
$GOGOPATHin turn (separated by:,;on Windows), whereimport "lib/ring"is<dir>/lib/ring/. WhenGOGOPATHis unset the search path is$HOME/gogo.gogo build -path dirsandgogo run -path dirsreplace it for one build, andgogo envprints it (chapter 12).
examples/packages in the repository uses both: a package of its own
(app/sensors) and shared packages from a GOGOPATH directory
(units/temp, units/stats, one importing the other, with a struct type
passed between packages), plus a #! script that imports a shared
package. Its README has the commands and what gogo env prints.
If the same import path is found in more than one place, the first is used and the build warns, naming them all:
gogo: warning: package "lib/ring" is in 2 places; using the first: /home/you/gogo/lib/ring, /home/you/work/pkgs/lib/ring
A program kept inside a search path directory (~/gogo/app, the GOPATH
habit) finds its packages once, through the root: the same directory is
one place.
There is no go.mod and no version: a package is whatever is in its
directory when you build. The rules, as in Go:
- A package’s name (its
packageclause) is its directory’s name, the last element of its import path, so the name you use in code is always the last element of the import.package utilsinapp/util/is an error, and so the directory’s name must be a Go identifier:my-lib/cannot hold a package (mylib/ormy_lib/can). - An import path matches the directory names letter for letter, case
included, even on a file system that ignores case (macOS by default):
import "app/Util"forapp/util/is an error, so a program that builds on a Mac also builds on Linux. Two import paths that name the same directory (through a symlink) are an error too. import "strings"looks for a package of your own; the error suggestsgogo/strings. A build root namedgogocannot have packages of its own, since everygogo/...import is gogo’s.- Only the build root is
package main; apackage mainbelow it is an error. The root itself cannot be imported. - Imports must not form a cycle; the error shows it:
b/b.gg:3:8: gogo: import cycle app/a -> app/b -> app/a. - A package that cannot be found is an error listing every place searched.
- Your packages may import
gogo/packages and each other. They follow the same subset rules aspackage main, and are compiled into the image like thegogo/libraries: there is no separate linking step, and importing a package compiles all of it. - A package’s struct types are the image’s own, like those of
package main. A module loaded withcode.Load(chapter 14) compiles its own copy of every package it imports, so even when the program and the module import the same package, its struct types cannot be sent from one to the other (the send fails withBadMsg). Each package’s//gogo:optionalcovers its own opens only, and the image requires the drivers your packages open (chapter 12). - In crash reports,
gogo disandactor.Reason.Func, a function of your package is named by its import path,app/shapes.Area; a gogo library’s by its package name,strings.Index.
A module built for hot loading (chapter 14) finds its packages the same
way, from its own directory. gogo run file.gg builds a single file, with
its directory as the build root (chapter 2, Scripts).
Note.
printlnprints any value;gogo/fmtformats as Go’sfmtdoes (section 3.7). Errors are reported as shown in section 3.10.
3.2 Types and values
The supported types are:
int: always 32 bits, on the board and on your computer. Overflow wraps around, as in Go. Constants that do not fit are compile errors.int64: 64 bits.actor.Now()returns one.byte(uint8): arithmetic is cut to 8 bits after every operation.- The other sized integers, as in Go:
int8,int16,int32(rune),uint8,uint16,uint32,uint64anduint(32 bits, likeint). See Sized integers below. float64andfloat32: IEEE 754 floating point, as in Go (see Floating point below).boolandstring. A string is an immutable sequence of bytes.rune(int32) is the type of character literals and of the value inrangeover a string (which gives bytes, not decoded runes).- Slices (
[]T), arrays ([N]T), maps (map[K]V, section 3.6), structs, pointers (*T, section 3.5), function values andany. - Named types whose underlying type is an integer or float type,
boolorstring(type Weekday int,type Reg uint32), and named structs. - Type aliases, another name for a type of the subset (
type Millis = int64,type Err = errors.Code): the two names are interchangeable. constwithiota.- The gogo types
actor.PID,actor.Ref,bytes.Bytes,bytes.Bufferand the struct types of the gogo packages.
There are no channels, complex numbers or uintptr.
// The basic types of the subset: int (32 bits), int64, byte, bool, string,
// named basic types, constants and iota.
package main
// Weekday is a named int type. Its constants come from iota.
type Weekday int
const (
Sunday Weekday = iota
Monday
Tuesday
)
const kilo = 1024
func main() {
// int is always 32 bits and wraps around on overflow, as in Go.
big := 2147483647
big++
println("int wraps:", big)
// int64 for larger numbers; actor.Now() returns one too.
var t int64 = 1 << 40
println("int64:", t*3)
// byte arithmetic wraps at 256.
b := byte(250)
b += 10
println("byte:", b)
println("bool:", 3 > 2, !true)
println("string:", "gogo"+"!", len("gogo"))
println("named:", Monday, Tuesday, int(Tuesday)*kilo)
// Integer division truncates toward zero; % has the dividend's sign.
println("div:", -7/2, -7%2, 7/2)
// Conversions between the integer types are explicit.
var n int = 300
println("convert:", int64(n)*1000000, byte(n), int(int64(5)))
}
int wraps: -2147483648
int64: 3298534883328
byte: 4
bool: true false
string: gogo! 4
named: 1 2 2048
div: -3 -1 3
convert: 300000000 44 5
Conversions between the integer types must be written out, as in Go, and
so must a conversion to a named type built on one (Weekday(n),
errors.Code(n)). string(b) and
[]byte(s) convert between strings and byte slices (each copies). Other
conversions are rejected.
Floating point
float64 and float32 behave as in Go: + - * /, comparisons,
negation, ++ and the compound assignments, with IEEE 754 rounding. An
untyped constant such as 1.5 is a float64 unless its context says
otherwise, and constant expressions (1.0/3, math.Pi * 2) are computed
exactly by the compiler. Division by zero gives +Inf, -Inf or NaN
instead of ending the actor, and NaN equals nothing, itself included.
// float64 and float32: Go semantics, printed as Go's println prints them.
package main
import (
"gogo/math"
"gogo/strconv"
)
// Celsius is a named float type.
type Celsius float64
func fahrenheit(c Celsius) float64 { return float64(c)*9/5 + 32 }
func main() {
x := 1.5 // untyped float constants default to float64
var f float32 = 0.1
println("values:", x, x/3, f, 1e21, 1e-7)
// float32 rounds every result to float32 (24 bits), float64 to 53
// bits: println shows the shortest digits that read back exactly.
println("0.1+0.2:", f+0.2, x/15+0.2)
// Division by zero is not a crash: it gives an infinity or NaN.
var zero float64
nan := zero / zero
println("special:", 1/zero, -1/zero, nan, nan == nan, -zero)
// Conversions are explicit; to an integer they truncate toward zero.
n := 7
println("convert:", float64(n)/2, int(-2.9*x), int64(x*1e12), float64(f))
println("named:", fahrenheit(21.5))
println("math:", math.Sqrt(2), math.Floor(-x), math.Round(2.5), math.Pi)
s := strconv.FormatFloat(math.Pi, 'f', 3, 64)
v, err := strconv.ParseFloat("6.02e23", 64)
println("strconv:", s, v, err == nil)
}
values: 1.5 0.5 0.1 1e+21 1e-07
0.1+0.2: 0.3 0.30000000000000004
special: +Inf -Inf NaN false -0
convert: 3.5 -4 1500000000000 0.10000000149011612
named: 70.7
math: 1.4142135623730951 -2 3 3.141592653589793
strconv: 3.142 6.02e+23 true
printlnprints a float the way Go’sprintlndoes (Go 1.27): the shortest digits that read back as the same value, as%efor large and small exponents (1e+21,1e-07),-0,NaN,+Inf. Afloat32prints at its own precision (0.1, not0.10000000149011612). Older Go releases printed+1.500000e+000.- Conversions are explicit.
int(f),int64(f)andbyte(f)truncate toward zero. Go leaves NaN and out-of-range values to the implementation; gogo gives 0 for NaN and the nearest end of the range otherwise (int(1e10)is 2147483647, sinceintis 32 bits);byte(f)keeps the low 8 bits of thatint(byte(300.7)is 44). float32andfloat64values can go intoany(a type switch tells them apart), into structs and slices, and into messages, which copy them like any value. A named float type cannot go intoany, like a named int.gogo/mathhasSqrt,Floor,Ceil,Trunc,Round,RoundToEven,Abs,Copysign,Signbit,Inf,NaN,IsNaN,IsInf,Max,Minand Go’s constants (Pi,E,MaxFloat64, …);Pow,Exp,Logand the trigonometric functions are not there yet.strconv.FormatFloatandstrconv.ParseFloatwork as in Go, except thatParseFloat’s error iserrors.BadFormatorerrors.Overflow(with±Inf, when the value is out of range) andFormatFloathas no'x'format. Both are exact, on the board as on your computer.- Cost. Every float is a small heap object (8 or 12 bytes), so each
arithmetic result allocates; keep tight loops on integers where you
can. On the ESP32-S3,
float32arithmetic runs on the FPU andfloat64in software; with the interpreter’s own cost on top, afloat64operation takes about twice as long as afloat32one (20000 multiply-adds: 313 ms infloat32, 409 ms infloat64, 226 ms onints): preferfloat32for sensor maths. On a chip without an FPU (the RP2040) both are software. - Firmware. Floats are a firmware option (
GOGO_FLOAT, requirementfloat): an image that uses them needs firmware built with it, and image format 15.2 (chapter 12).gogo firmwareturns it on when an image needs it. A program that only importsgogo/strconvforAtoiorItoadoes not need it.
Sized integers
int8, int16, int32, int64, uint8 (byte), uint16, uint32,
uint64 and uint follow Go: arithmetic wraps around at the type’s
width after every operation, / truncates toward zero and % takes the
dividend’s sign (for the signed types), the unsigned types divide,
compare and shift right as unsigned numbers, and a shift by the width or
more gives 0 (or -1 for a negative signed value shifted right). Division
by zero ends the actor with divzero, as for int. A constant that does
not fit its type is a compile error. uint is 32 bits, like int.
// Sized integers: Go's int8 .. uint64, with wraparound at each type's
// width, unsigned division, comparison and shifts, and explicit
// conversions.
package main
import "gogo/strconv"
// Reg is a named uint32 with methods, like a hardware register.
type Reg uint32
func (r Reg) Bit(n int) bool { return r>>n&1 != 0 }
// crc32 is the IEEE CRC-32 (the one zip and Ethernet use).
func crc32(s string) uint32 {
crc := ^uint32(0)
for i := 0; i < len(s); i++ {
crc ^= uint32(s[i])
for k := 0; k < 8; k++ {
if crc&1 != 0 {
crc = crc>>1 ^ 0xEDB88320
} else {
crc >>= 1
}
}
}
return ^crc
}
// fnv1a is the 64-bit FNV-1a hash.
func fnv1a(s string) uint64 {
h := uint64(14695981039346656037)
for i := 0; i < len(s); i++ {
h ^= uint64(s[i])
h *= 1099511628211
}
return h
}
func main() {
// Each type wraps at its own width.
var a int8 = 127
var b uint16 = 65535
var c uint32 = 0
a++
b++
c--
println("wrap:", a, b, c)
// Unsigned values print, divide, compare and shift as unsigned.
var big uint64 = 1<<64 - 1
println("unsigned:", big, big/3, c > 1<<31, c>>28)
// uint and int are 32 bits, as everywhere in gogo.
var u uint = 1 << 31
println("uint:", u, u*2, int(u))
// Conversions are explicit; they keep the low bits or extend.
n := -1
w := 200
println("convert:", uint8(n), uint32(n), uint64(n), int8(w), int64(c))
r := Reg(0x80000001)
println("register:", r.Bit(31), r.Bit(1), uint32(r))
println("crc32:", crc32("hello"), strconv.FormatUint(uint64(crc32("hello")), 16))
println("fnv1a:", fnv1a("gogo"))
v, err := strconv.ParseUint("18446744073709551615", 10, 64)
println("parse:", v, err == nil)
}
wrap: -128 0 4294967295
unsigned: 18446744073709551615 6148914691236517205 true 15
uint: 2147483648 0 -2147483648
convert: 255 4294967295 18446744073709551615 -56 4294967295
register: true false 2147483649
crc32: 907060870 3610a686
fnv1a: 11313272551757906769
parse: 18446744073709551615 true
- Conversions follow Go: to a narrower type they keep the low bits
(
uint8(n)of anint-1 is 255,int8(w)of 200 is -56), to a wider one they extend by the source’s sign (int64(c)of auint32is never negative). From a float they truncate toward zero; where Go leaves the result to the implementation (NaN, out of range), gogo does what Go does on arm64, as forint(forf := -1.0,uint32(f)is 4294967295 anduint64(f)is 0). - They work everywhere an
intdoes: struct fields, slices, arrays,switch, indexes (any integer of up to 32 bits; notint64oruint64),rangeover a sized count,anyand messages. In an interface a sized value keeps its type, as in Go:any(uint32(1))is notany(1), and a type switch tells them apart. printlnprints an unsigned value as unsigned. A struct, slice or array holding auint32,uintoruint64cannot be printed whole (println of main.P not supported): print its fields one by one.gogo/strconvhasFormatUint,ParseUintandParseIntwith a bit size (0 means 32 bits, the size ofintanduintin gogo).- Cost.
int8,int16,uint8,uint16andint32are as cheap asint(a narrow result costs one extra instruction to cut it back);uint64as cheap asint64.uint32(anduint)+ - * & | ^ <<cost whatint’s do, but its/,%,<,<=,>,>=and>>widen both operands to 64 bits first: three or four instructions instead of one, and values from 2^30 up are heap objects, as largeints are. - Firmware. Programs that use the unsigned 64-bit operations or the
narrow conversions need image format 15.3 (chapter 12);
byte,int32anduint32addition alone do not.
Package-level variables
A package-level var is read-only: it is set when the program is
built, and the value lives in the image, in flash, so it takes no RAM in
any actor. Tables, lookup maps and sentinel errors are what it is for;
state that changes belongs in an actor.
// Package-level variables: read-only, set when the program is built,
// kept in flash.
package main
import "gogo/errors"
type Note struct {
Name string
Hz int
}
var (
scale = []Note{{"A", 440}, {"B", 494}, {"C", 523}}
ErrNoNote = errors.New("no such note")
sizes = map[string]int{"S": 1, "M": 2, "L": 3}
greeting = "hello"
)
func find(name string) (Note, error) {
for _, n := range scale {
if n.Name == name {
return n, nil
}
}
return Note{}, ErrNoNote
}
func main() {
n, err := find("B")
println(n.Hz, err == nil)
_, err = find("H")
println(err == ErrNoNote, err.Error())
println(sizes["M"], len(scale), greeting)
// A copy is yours to change; the variable itself is read-only.
mine := append([]Note{}, scale...)
mine[0].Hz = 432
println(mine[0].Hz, scale[0].Hz)
}
494 true
true no such note
2 3 hello
432 440
The initializer must be something the compiler can work out: constants,
literals of structs, slices, arrays and maps (a map’s keys constants of
an integer, float, bool or string type), conversions, other package-level
variables and calls of functions whose body is a single return (as
errors.New is). make, &T{} and a function that computes are
rejected (package-level variable x: ... is not static). Every write is
a compile error (package-level variable scale is read-only): an
assignment, ++, scale[0].Hz = 1, copy into it. A slice of one still
shares its array, which is in flash: t := scale; t[0] = n ends the actor
with badcode at run time. Copy it first, as mine above does.
3.3 Control flow
if/else, for in all its forms, range over slices, strings and
integers, switch, break and continue (also with labels) and return
work as in Go.
// Control flow: if/else chains, the three for forms, range over slices and
// strings, break and continue. Switches, labels and range over an integer
// follow in their own sections.
package main
func classify(n int) string {
if n < 0 {
return "negative"
} else if n == 0 {
return "zero"
} else if n < 10 {
return "small"
}
return "large"
}
func main() {
for _, n := range []int{-5, 0, 7, 42} {
println(n, classify(n))
}
// The C-style loop, the while-style loop and the endless loop.
sum := 0
for i := 1; i <= 10; i++ {
if i%2 == 0 {
continue
}
sum += i
}
println("odd sum", sum)
n := 27
steps := 0
for n != 1 {
if n%2 == 0 {
n = n / 2
} else {
n = 3*n + 1
}
steps++
}
println("collatz steps", steps)
i := 0
for {
i++
if i == 5 {
break
}
}
println("broke at", i)
// range over a string gives byte indexes and byte values.
for i, c := range "gogo" {
if c == 'o' {
println("o at", i)
}
}
// An if statement may start with a short declaration.
if half := sum / 2; half > 10 {
println("half", half)
}
}
-5 negative
0 zero
7 small
42 large
odd sum 25
collatz steps 111
broke at 5
o at 1
o at 3
half 12
range over a string gives bytes, not runes: the subset never decodes
UTF-8.
Switch
switch compares a value with each case in order and runs the first
that matches. A case may list several values, a switch without a value
runs the first case whose condition is true, an init statement can come
before the value, and fallthrough at the end of a clause runs the next
clause without testing it. As in Go, there is no implicit fall through, and
a plain break leaves the switch.
// Expression switch: a tag compared with each case, several values per
// case, a switch with no tag, an init statement and fallthrough.
package main
type Code int
const (
Ok Code = iota
Busy
Gone
)
func describe(c Code) string {
switch c {
case Ok:
return "ok"
case Busy, Gone:
return "try later"
default:
return "unknown"
}
}
func size(n int) string {
switch { // no tag: the first true case runs
case n < 0:
return "negative"
case n < 10:
return "small"
}
return "large"
}
func main() {
println(describe(Ok), describe(Gone), describe(7))
println(size(-1), size(3), size(50))
for _, cmd := range []string{"start", "stop", "jump"} {
switch s := cmd + "!"; s { // strings compare by content
case "start!":
println("starting")
case "stop!":
println("stopping")
default:
println("unknown", s)
}
}
// fallthrough runs the next clause's body without testing it.
switch level := 2; level {
case 2:
println("level 2")
fallthrough
case 1:
println("level 1")
}
}
ok try later unknown
negative small large
starting
stopping
unknown jump!
level 2
level 1
- The value can be of any type
==works on (section 3.5): anint,int64,byte,bool,string, a named type of one of them (type Code int), a float, anactor.PID, anactor.Ref, a struct, an array, or an interface value such as anany, whose cases may be values of different types (case 1, "one", nil:). To ask which type ananyholds, use a type switch, `switch v - = x.(type)`, which is how actors look at what they receive (chapter 4).
Labeled break and continue
A label on a for, range, switch or type switch statement lets
break and continue name it: break search leaves the labeled loop
from inside an inner one, and continue rows starts its next pass.
// Labeled break and continue: leave or restart an outer loop from an
// inner one, or leave a loop from inside a switch.
package main
func main() {
grid := [][]int{{1, 3, 5}, {4, 5, 6}, {7, 9, 11}}
// break L leaves both loops at the first match.
found := false
search:
for i, row := range grid {
for j, v := range row {
if v == 5 {
println("5 at", i, j)
found = true
break search
}
}
}
println("found", found)
// continue L goes on with the next row.
rows:
for i, row := range grid {
for _, v := range row {
if v%2 == 0 {
println("row", i, "has an even number:", v)
continue rows
}
}
println("row", i, "is all odd")
}
// A plain break inside a switch leaves only the switch; break L
// leaves the loop.
n := 0
loop:
for {
switch {
case n == 3:
break loop
default:
n++
}
}
println("n", n)
}
5 at 0 2
found true
row 0 is all odd
row 1 has an even number: 4
row 2 is all odd
n 3
goto is not supported (goto statement not supported), and neither is a
label on any other statement.
range over an integer
for i := range n runs i from 0 to n-1, as in Go 1.22. n is
evaluated once, i has n’s type, and when n is zero or negative the
body does not run.
// range over an integer: for i := range n runs i from 0 to n-1.
package main
func main() {
for i := range 3 {
println("pass", i)
}
// No variable: just repeat.
dots := ""
for range 4 {
dots += "."
}
println(dots)
// n is evaluated once; zero or a negative n runs no pass.
n := 0
for range n {
println("never")
}
for i := range -2 {
println("never", i)
}
// i has n's type.
var big int64 = 3
var total int64
for i := range big {
total += i << 32
}
println(total)
}
pass 0
pass 1
pass 2
....
12884901888
3.4 Functions and closures
Functions can take and return any number of values, have named results and bare returns, be passed around as values and be written as literals (closures).
// Functions: several results, named results, function values and
// closures.
package main
func divmod(a, b int) (int, int) {
return a / b, a % b
}
// minmax has named results and a bare return.
func minmax(xs []int) (lo, hi int) {
lo, hi = xs[0], xs[0]
for _, x := range xs {
if x < lo {
lo = x
}
if x > hi {
hi = x
}
}
return
}
// apply takes a function value.
func apply(f func(int) int, xs []int) []int {
out := make([]int, 0, len(xs))
for _, x := range xs {
out = append(out, f(x))
}
return out
}
// adder returns a closure that captures step.
func adder(step int) func(int) int {
return func(x int) int { return x + step }
}
func double(x int) int { return x * 2 }
func show(xs []int) {
s := ""
for i, x := range xs {
if i > 0 {
s = s + " "
}
s = s + itoa(x)
}
println(s)
}
// itoa is a small decimal formatter (gogo/strconv.Itoa does the same).
func itoa(n int) string {
if n == 0 {
return "0"
}
neg := n < 0
if neg {
n = -n
}
b := []byte{}
for n > 0 {
b = append([]byte{byte('0' + n%10)}, b...)
n /= 10
}
if neg {
return "-" + string(b)
}
return string(b)
}
func main() {
q, r := divmod(17, 5)
println("divmod", q, r)
lo, hi := minmax([]int{4, -2, 9, 3})
println("minmax", lo, hi)
xs := []int{1, 2, 3}
show(apply(double, xs))
show(apply(adder(10), xs))
show(apply(func(x int) int { return x * x }, xs))
// A closure that changes a variable it captures.
total := 0
count := func(s string) { total += len(s) }
for _, w := range []string{"go", "gogo", "actor"} {
count(w)
}
println("letters", total)
}
divmod 3 2
minmax -2 9
2 4 6
11 12 13
1 4 9
letters 11
Closures share what they capture
As in Go, a closure refers to the variables it captures: when the variable changes later, inside or outside the closure, the other side sees the change.
// Closures share the variables they capture, as in Go: a counter kept in
// a closure, and a loop variable that is the iteration's own.
package main
func counter() (func() int, func()) {
n := 0
return func() int { return n }, func() { n++ }
}
func main() {
get, inc := counter()
inc()
inc()
println(get())
x := 1
show := func() { println(x) }
x = 5
show()
var fs []func()
for i := 0; i < 3; i++ {
fs = append(fs, func() { println(i) })
}
for _, f := range fs {
f()
}
}
$ gogo run docs/book/examples/03-capture
2
5
0
1
2
Each iteration of a loop has its own loop variable, as in Go 1.22: the
three closures print 0, 1 and 2, not 3 three times. A deferred func
literal can set a named result (defer func() { err = wrap(err) }()).
How it works: a closure copies the values it captures when it is made.
A captured variable that is assigned after its declaration is kept in a
box instead (the same box &x gives, section 3.5), and the closure
copies the box, so both sides share it; a variable that is never
assigned after its declaration needs no box. The difference shows when a
closure goes to another actor: actor.Spawn(func() { ... }) copies what
the closure captures, boxes included, into the new actor, so a variable
the new actor changes is its own (chapter 4).
Function values have a few more limits: they cannot be compared (not even
with nil) and cannot be put into any. Calling a nil function value
crashes the calling actor with badcode.
Variadic functions
A function’s last parameter can be ...T: inside the function it is a
[]T. Callers pass any number of T values, which go into a new slice,
or none (the parameter is then a nil slice), or an existing slice with
s..., which the function receives as it is, sharing its array, as in Go.
Func literals and func values can be variadic too.
// Variadic functions: a final ...T parameter is a []T; callers pass
// separate values, none at all, or a slice with s...
package main
func sum(xs ...int) int {
t := 0
for _, x := range xs {
t += x
}
return t
}
func join(sep string, parts ...string) string {
s := ""
for i, p := range parts {
if i > 0 {
s += sep
}
s += p
}
return s
}
func main() {
println(sum(), sum(1, 2, 3))
nums := []int{10, 20, 30}
println(sum(nums...))
println(join(", ", "a", "b", "c"))
println(join(", ") == "")
// With no values the parameter is a nil slice.
count := func(xs ...int) bool { return xs == nil }
println(count(), count(1))
// s... passes the slice itself: the function sees the same array.
zero := func(xs ...int) { xs[0] = 0 }
zero(nums...)
println(nums[0])
}
0 6
60
a, b, c
true
true false
0
Defer
defer f(args) runs the call when the function returns, as in Go:
deferred calls run last deferred first, at every return and at the end
of the function, and the function value, the receiver and the arguments
are evaluated at the defer statement. A method value (defer c.Close())
and a func literal (defer func() { ... }()) work too:
// defer: the deferred calls run when the function returns, last deferred
// first; their arguments are evaluated at the defer statement.
package main
type Conn struct{ Name string }
func (c Conn) Close() { println("close", c.Name) }
func open(name string) Conn {
println("open", name)
return Conn{name}
}
// copyAll returns early on a bad item: every return runs the deferred
// calls registered before it.
func copyAll(items []int) (n int) {
src := open("src")
defer src.Close()
dst := open("dst")
defer dst.Close()
for _, it := range items {
if it < 0 {
println("bad item", it)
return n
}
n++
}
return n
}
func count() {
x := 1
defer println("deferred x =", x) // x is evaluated now: 1
x = 2
if x > 1 {
defer println("only when x > 1")
}
defer func() {
println("func literal, last deferred, runs first")
}()
println("x =", x)
}
func main() {
println("copied", copyAll([]int{1, 2, 3}))
println("copied", copyAll([]int{1, -2, 3}))
count()
}
open src
open dst
close dst
close src
copied 3
open src
open dst
bad item -2
close dst
close src
copied 1
x = 2
func literal, last deferred, runs first
only when x > 1
deferred x = 1
gogo’s defer is static: a defer statement may not be inside a
loop (defer inside a loop not supported), so each one runs at most once
per call and the compiler knows them all. It compiles the deferred calls
at each return, in order; there is no run-time list of deferred calls and
no cost when none was registered. A defer inside an if or a switch
clause is fine (a flag records whether it ran). To defer in a loop, move
the loop body into a function (a func literal is a function of its own,
so a defer in a literal called in a loop is allowed).
Two differences from Go:
- Deferred calls run on normal returns only. A crash (division by
zero, an index out of range,
badcode), apanic(also one inside a deferred call) andactor.Exitend the actor without running them, so Go’sdefer mu.Unlock()habit does not carry over to panics. There is norecover: the actor ends, and its ports and files are closed for it (section 5.7), sodefer f.Close()is for actors that live on, not a safety net. - A deferred func literal sees variables, as in Go.
x := 1; defer func() { println(x) }(); x = 2prints 2, anddefer func() { err = wrap(err) }()changes the result: with named results,return xsets them before the deferred calls run, and the caller gets what the deferred calls left in them.
A deferred call whose single argument is a call with several results,
defer f(g()), is rejected; assign the results to variables first.
3.5 Structs and methods
Structs work as in Go: literals with or without field names, nested
structs, value semantics (assignment copies) and field assignment:
p.X = v, r.Max.X++, pts[i].Y += 2, m.Items[i].Name = "a", and
fields in multi-assignments (p.X, p.Y = p.Y, p.X). Index expressions and
right-hand sides are evaluated first, then the assignments happen left to
right, as in Go.
// Structs are values: assignment copies, and assigning a field changes only
// the variable (or slice element) written, never an earlier copy.
package main
type Point struct{ X, Y int }
type Rect struct {
Min, Max Point
Name string
}
// move returns a moved copy: p is the function's own copy.
func move(p Point, dx, dy int) Point {
p.X += dx
p.Y += dy
return p
}
func area(r Rect) int {
return (r.Max.X - r.Min.X) * (r.Max.Y - r.Min.Y)
}
func main() {
p := Point{1, 2}
q := move(p, 10, 0)
println(p.X, q.X, q) // p is unchanged: structs are values
r := Rect{Min: Point{0, 0}, Max: Point{3, 4}, Name: "box"}
println(r.Name, area(r))
old := r
r.Max.X++ // a nested field
r.Max.Y++
r.Name += "!"
println(r.Name, area(r), r)
println(old.Name, area(old)) // the copy made before is unchanged
// A slice element's fields, in place: the slice shares its array.
pts := []Point{{0, 0}, {5, 5}}
for i := range pts {
pts[i].X, pts[i].Y = pts[i].Y, pts[i].X+1 // swap and bump
}
println(pts[0], pts[1])
// The zero value of a struct has every field zero.
var z Rect
println(z.Max.X, z.Name == "")
// == compares structs field by field.
println(p == Point{1, 2}, q != p)
}
1 11 {11 2}
box 12
box! 20 {{0 0} {4 5} box!}
box 12
{0 1} {5 6}
0 true
true true
Writing a field changes only the variable or slice element written:
old keeps the value it had when it was copied, and a function or a
method that writes a field of its parameter changes only its own copy.
A slice element is written in place, because a slice shares its array
(pts[i].X = v is seen through every slice of that array, as in Go).
What a field write costs. Inside the VM a struct never changes. p.X = v builds a new struct with X replaced, copies the other fields into it,
and stores it back into p (or into the slice element); for a path such
as r.Max.X++ it builds every struct on the path, here a new Point and
a new Rect. So each write allocates one struct per level (2 words plus
one per field), and the old one becomes garbage for the collector. This
is exactly what rebuilding the struct with a literal by hand
(p = Point{p.X + 1, p.Y}) costs, so prefer the clearer field write.
In a tight loop it is noticeable: on the host, p.X++ on a 3-field
struct takes about twice as long as x++ on an int. In a hot loop
over a big struct, keep the changing values in local variables and
write them back once at the end.
A field of a variable that a closure captures can be written on either side; the closure sees the change (section 3.4).
== and != work on int, int64, byte, floats, bool, string
and named types of those, actor.PID, actor.Ref, structs (field by
field; a bytes.Bytes field by its contents), arrays (element by
element) and interface values (section 3.9). A struct with a
bytes.Buffer field does not compare. For slices only s == nil works.
Methods
A named struct type, or a named int, int64, bool or string type
(type Celsius int), can have methods with a value receiver, as in
Go: func (p Point) Add(q Point) Point. You call them as x.M(args),
also on expressions and in chains (p.Moved(1, 0).Moved(0, 1)), and they
can be variadic. A package’s methods are used from other packages like
its functions, and two types can have methods of the same name.
// Methods with value receivers: on a struct and on a named int. A method
// gets a copy of its receiver, so it returns the new value instead of
// changing the old one.
package main
import "gogo/actor"
type Point struct{ X, Y int }
func (p Point) Add(q Point) Point { return Point{p.X + q.X, p.Y + q.Y} }
func (p Point) Moved(dx, dy int) Point { return p.Add(Point{dx, dy}) }
// Reset changes only its own copy of p.
func (p Point) Reset() {
p.X, p.Y = 0, 0
println("inside", p.X, p.Y)
}
type Celsius int
func (c Celsius) Fahrenheit() int { return int(c)*9/5 + 32 }
// Sum is variadic, like a function.
func (p Point) Sum(more ...Point) Point {
for _, q := range more {
p = p.Add(q)
}
return p
}
func (p Point) Show() { println("show", p.X, p.Y) }
func main() {
p := Point{1, 2}
p.Reset()
println(p.X, p.Y) // unchanged
p = p.Moved(10, 0).Moved(0, 10)
println(p)
println(Celsius(100).Fahrenheit(), p.Sum(), p.Sum(Point{1, 1}, Point{2, 2}))
// A method value remembers its receiver as it was.
show := p.Show
p = Point{}
show()
// It can be spawned like any func(): the receiver goes with it.
done := actor.Self()
actor.Spawn(func() {
show()
actor.Send(done, true)
})
actor.Receive()
// A method expression takes the receiver as its first argument.
f := Celsius.Fahrenheit
println(f(-40))
}
inside 0 0
1 2
{11 12}
212 {11 12} {14 15}
show 11 12
show 11 12
-40
A few things to know:
- A value receiver works on a copy. Like a parameter, the receiver is
the method’s own copy: assigning to it or to its fields changes nothing
for the caller (a slice field still shares its array, as in Go). A
pointer receiver,
func (p *Point) Move(dx int), changes the caller’s value: see Pointers below. - A method value
f := x.Mis a func value that captured a copy ofxwhen it was made. Like any func value it can be spawned, stored in a struct field, and sent inside a struct to another actor, which gets its own copy of the receiver. - A method expression
T.Mis the method as a function whose first parameter is the receiver:Celsius.Fahrenheit(-40). - Names. In
gogo dis, in crash reports and inactor.Reason.Func, a method isType.Method, with its package’s prefix outsidemain(app/geom.Point.Add); a func literal inside it ismain.Type.Method.func1. - Calls are static. The compiler knows each call’s method, so a call costs the same as a function call; a call through an interface value (section 3.9) adds a type check per candidate type.
Embedded fields
A struct can embed another named type: a field without a name, named
after its type. The embedded struct’s fields and methods are promoted:
s.X means s.Point.X and s.Dist() means s.Point.Dist(), for reading,
for field assignment and for method values, as in Go:
// Embedded fields: the fields and methods of an embedded struct are
// promoted to the outer one, and a shallower name hides a deeper one.
package main
type Point struct{ X, Y int }
func (p Point) Dist() int { return abs(p.X) + abs(p.Y) }
func (p Point) Moved(dx, dy int) Point { return Point{p.X + dx, p.Y + dy} }
// Sprite embeds a Point: s.X is s.Point.X, s.Dist() is s.Point.Dist().
type Sprite struct {
Point
Name string
}
// Label is the outer type's own method.
func (s Sprite) Label() string { return s.Name }
// Player embeds a Sprite and has its own X, which hides Sprite's (depth 1
// beats depth 2); the promoted one is still reachable by its full path.
type Player struct {
Sprite
X int
Lives int
}
func abs(n int) int {
if n < 0 {
return -n
}
return n
}
func main() {
s := Sprite{Point{3, -4}, "ship"}
println(s.X, s.Y, s.Dist(), s.Label())
// Promoted fields can be assigned, like any field.
s.X = 10
s.Point.Y++
println(s.X, s.Y, s.Moved(1, 1).X)
p := Player{Sprite: s, X: 99, Lives: 3}
p.Y = 0 // p.Sprite.Point.Y
println(p.X, p.Sprite.X, p.Y, p.Dist(), p.Label(), p.Lives)
// A method value of a promoted method keeps its receiver.
dist := p.Dist
p.Sprite.X = 0
println(dist(), p.Dist())
}
3 -4 7 ship
10 -3 11
99 10 0 10 ship 3
10 0
Go’s rules decide which name a selector means: the shallowest one wins
(p.X is Player’s own X, not the promoted p.Sprite.X), and two at the
same depth make the selector ambiguous, a compile error (ambiguous selector c.X) unless you write the path. An embedded field is an
ordinary field underneath: a literal sets it by its type’s name
(Player{Sprite: s}), and a promoted field costs one GETFIELD per
level. A type can embed a named struct, a named basic type
(type Celsius int) or an interface, from any package; not a pointer. A method
expression of a promoted method (Sprite.Dist) is rejected: write a
method value or call it on the embedded field. The methods of an
embedded gogo type (bytes.Buffer, bytes.Bytes, fs.File) are not
promoted either (method WriteByte of an embedded gogo/bytes type not supported): call them on the field, w.Buffer.WriteByte(b). Promoted
methods count toward implementing an interface (section 3.9), and the
methods of an embedded interface are promoted too: struct { Namer; K int } is a Namer, and its Name() calls the field’s.
Pointers
&T{...}, new(T) and &x make pointers; *p reads and writes what
one points to, and p.X its fields, as in Go. Two pointers to one value
see each other’s writes:
// Pointers: &T{}, new, *p, fields through a pointer, pointer receivers,
// a linked list, and *T in an interface.
package main
type Counter struct {
name string
n int
}
// Inc has a pointer receiver: it changes the caller's Counter.
func (c *Counter) Inc() { c.n++ }
// Get has a value receiver: it works on a copy, as before.
func (c Counter) Get() int { return c.n }
type Getter interface{ Get() int }
type Node struct {
Val int
Next *Node
}
func main() {
p := &Counter{name: "hits"}
q := p // q and p point to one Counter
q.Inc()
p.Inc()
println(p.n, q.Get())
var c Counter // a variable: c.Inc() takes &c
c.Inc()
snapshot := c // a copy: a value, as always
c.Inc()
println(c.n, snapshot.n)
var g Getter = p // *Counter has Get too
println(g.Get())
var list *Node
for i := 1; i <= 3; i++ {
list = &Node{i, list}
}
for n := list; n != nil; n = n.Next {
println(n.Val)
}
x := new(int)
*x += 41
*x++
println(*x)
}
2 2
2 1
2
3
2
1
42
Method sets are Go’s: a pointer receiver method can be called on a
variable (c.Inc() takes &c) or a pointer, a value receiver method on
either, and *T has both kinds in an interface. == compares pointers,
not what they point to. Reading through a nil pointer ends the actor with
the reason actor.Nil (crash kind nil, chapter 5).
What differs from Go:
- No pointers into slices or fields.
&s[i]and&v.Fare rejected (interior pointer &s[i] not supported), and so is calling a pointer method on a slice element or a field (s[i].Inc()). Keep pointers in the slice ([]*Counter), or write the field directly,s[i].n++. - A send copies. A pointer sent to another actor (in a message, or captured by a spawned closure) arrives with a copy of what it points to, as a slice’s array does (chapter 6): the receiver’s writes stay its own.
- No pointers to arrays, and no embedded pointer fields.
println(p)prints whatppoints to after&(&{1 2}), not an address.
A pointer to a struct is one heap object laid out like the struct, so
p.X = v writes in place without allocating; *p makes a copy (one
allocation). A variable whose address is taken lives in a box for its
whole life (one allocation at its declaration).
3.6 Slices, arrays and maps
make, append (also append(a, b...)), copy, len, cap and slice
expressions s[i:j] behave as in Go, including sharing: two slices of one
array see each other’s writes:
// Slices: literals, make, append, copy, slicing and sharing, nil slices.
package main
func main() {
var s []int // nil
println(s == nil, len(s))
for i := 0; i < 5; i++ {
s = append(s, i*i)
}
println(len(s), s[4])
// Slicing shares the array: a write through one view shows in the other.
mid := s[1:3]
mid[0] = 100
println(s[1], len(mid), cap(mid))
// copy copies; make sets the length and capacity.
c := make([]int, 2, 8)
n := copy(c, s)
println(n, c[0], c[1], cap(c))
// []byte and string convert both ways (each conversion copies).
b := []byte("gogo")
b[0] = 'G'
println(string(b))
// Swapping elements with a tuple assignment works.
s[0], s[4] = s[4], s[0]
println(s[0], s[4])
}
true 0
5 16
100 2 7
2 0 100 8
Gogo
apples 4 true 2
plums false
16 0
Indexing out of range crashes the actor with badcode (chapter 5); it
never reads or writes outside the slice. Slice literals cannot use keys
([]int{2: 5}), and three-index slices (s[a:b:c]) are not supported.
Index assignment works on slices (s[i] = v), including through a struct
field (m.Items[i] = v); strings are immutable, as in Go.
Printing slices
println prints a slice as its elements in brackets, the way it prints a
struct’s fields in braces. A nil or empty slice prints as [], and a
[]byte prints its bytes as numbers.
// println prints a slice's elements, like a struct's fields. Go's println
// prints a slice as [len/cap]address instead.
package main
type Point struct{ X, Y int }
func main() {
println([]int{1, 2, 3})
var none []string
println(none, len(none))
println([]string{"a", "b"}, []bool{true})
println([]byte("hi")) // bytes print as numbers
println([]Point{{1, 2}, {3, 4}})
println([][]int{{1}, {2, 3}})
}
true 0
5 16
100 2 7
2 0 100 8
Gogo
16 0
This differs from Go: Go’s println prints any slice as its length,
capacity and the address of its array, [3/3]0xc000014090; only
fmt.Println prints the elements. gogo has no addresses to show, so it
prints what fmt.Println would.
Arrays
An array [N]T has a fixed length that is part of its type, and it is a
value, as in Go: assigning it, passing it, returning it or storing it
in a field or an element copies it. Indexing (checked, like a slice’s),
len, cap, range, element and field assignment through it
(a[i] = v, pts[i].X = v, b.Cells[r][c] = v), literals with [...]
and index keys, arrays of structs and arrays in struct fields all work as
in Go:
// Arrays are values: assigning, passing or returning one copies it. A
// slice of an array variable shares it, as in Go.
package main
type Point struct{ X, Y int }
// Board holds its cells in an array field: copying a Board copies them.
type Board struct {
Cells [3][3]byte
Moves int
}
// play returns the board with one more move: b is play's own copy.
func play(b Board, row, col int, who byte) Board {
b.Cells[row][col] = who
b.Moves++
return b
}
func sum(a [4]int) int {
t := 0
for _, v := range a {
t += v
}
return t
}
func main() {
var a [4]int // the zero value: four zeros
a[1] = 5
a[3] += 2
b := a // a copy
b[0] = 9
println(a[0], b[0], len(a), sum(a))
// Literals: [...] counts the elements; keys set given indices.
primes := [...]int{2, 3, 5, 7, 11}
flags := [8]bool{1: true, 6: true}
println(len(primes), primes[4], flags[1], flags[2])
// a[:] shares the variable's array; a = b copies b into it.
s := a[:]
s[0] = -1
println(a[0])
a = b
println(s[0])
// Arrays of structs, and arrays in struct fields.
pts := [2]Point{{1, 2}, {3, 4}}
pts[1].X = 30
var empty Board
game := play(empty, 1, 1, 'x')
game = play(game, 0, 2, 'o')
println(pts[1].X, empty.Moves, game.Moves, game.Cells[1][1], game.Cells[0][2])
}
0 9 4 7
5 11 true false
-1
9
30 0 2 120 111
Inside the VM an array is a slice of length and capacity N, so it prints
like one (println(a) gives [0 5 0 2]) and a[:] is an ordinary slice
of it. Some things to know:
- Copies are real copies.
b := a,f(a),return aandp.Cells = ceach allocate a new array of N elements (an array literal or a call result is not copied again). Pass a slice,a[:], when a function only reads or should write the caller’s array. - Only an array variable can be sliced.
a[:]sharesa, anda = bcopiesb’s elements into that shared array, as in Go. An array in a field or an element is not changed in place (a write through it copies it), sop.Cells[:]is rejected (slice of an array that is not a variable not supported): copy it first,c := p.Cells; c[:]. ==compares the elements, as in Go:a == band aswitchon an array hold when every element is equal.- Not in
any. An array cannot go into an interface, so it cannot be a message on its own (array in interface not supported): send a slice, or a struct with the array as a field, which is copied with the message. - A closure that captures an array variable shares its elements with the
variable, as in Go. Named array types (
type Grid [9]int) are not supported.
Maps
map[K]V works as in Go: make, literals, m[k] (the value type’s
zero value for a missing key), v, ok := m[k], assignment, m[k]++,
delete, len, clear and range. A map is a reference: assigning it
shares it.
// Maps: make, literals, lookups with comma-ok, delete, len and range,
// which goes in key order.
package main
func main() {
stock := map[string]int{"pears": 5, "apples": 3}
stock["plums"] = 7
stock["apples"]++
delete(stock, "pears")
n, ok := stock["pears"]
println(n, ok, len(stock))
for fruit, count := range stock {
println(fruit, count)
}
// Counting words: a missing key reads as 0.
counts := make(map[string]int)
for _, w := range []string{"go", "gogo", "go"} {
counts[w]++
}
println(counts["go"], counts["gogo"], counts["rust"])
// A map is a reference: both names see one map.
alias := counts
alias["rust"] = 1
println(len(counts))
println(counts)
}
0 false 2
apples 4
plums 7
2 1 0
3
map[go:2 gogo:1 rust:1]
What differs from Go:
rangegoes in key order (numbers by value, strings byte by byte), not Go’s random order, so a program prints the same thing every run. Deleting during arangeis fine, as in Go.- It is a sorted slice. A lookup is a binary search; an insert or a delete moves the entries after it, so it costs O(n). Maps of a few hundred entries are fine; a large map that changes often is slower than Go’s.
- Keys cannot hold pointers, maps or funcs (
map with key type ...: a pointer key). Structs, arrays, strings, numbers, bools and interfaces are fine. - A send copies the map with its entries (chapter 6).
- Writing to a nil map ends the actor with
actor.Nil; reading one gives the zero value, as in Go.
println(m) prints map[k:v ...], as Go’s fmt does.
3.7 Strings, strconv and strings
Strings can be indexed (a byte), sliced (a new string), concatenated with
+ and compared with ==, < and friends. Two small libraries, written in
the gogo subset and compiled into your image when you import them, cover the
rest:
gogo/strings:Index,IndexByte,Cut,HasPrefix,HasSuffix,TrimSpace,ToLower,EqualFold,Split.gogo/strconv:Itoa,Atoi,FormatInt64,ParseInt64,FormatUint,ParseUint,ParseInt(with a bit size).
All of them work on bytes. ToLower, EqualFold and TrimSpace know only
ASCII. Atoi has Go’s signature, (int, error), the error
errors.BadFormat or errors.Overflow; ParseInt64, gogo’s own, returns
(value, ok bool).
// Strings are immutable byte sequences. gogo/strings and gogo/strconv
// cover the common needs; both work on bytes, not runes.
package main
import (
"gogo/strconv"
"gogo/strings"
)
func main() {
line := " GET /index.html HTTP/1.0 "
t := strings.TrimSpace(line)
parts := strings.Split(t, " ")
println(len(parts), parts[0], parts[1])
method, rest, found := strings.Cut(t, " ")
println(method, found, strings.HasPrefix(rest, "/"), strings.HasSuffix(t, "1.0"))
println(strings.Index(t, "HTTP"), strings.IndexByte(t, '/'), strings.ToLower(method))
println(strings.EqualFold("Content-Length", "content-length"))
// Numbers and strings.
n, err := strconv.Atoi("-1234")
println(n, err == nil)
_, err = strconv.Atoi("12x")
println(err.Error())
println(strconv.Itoa(99) + " bottles")
println(strconv.FormatInt64(255, 16), strconv.FormatInt64(-5, 2))
big, ok := strconv.ParseInt64("9000000000", 10)
println(big, ok)
// Indexing gives a byte; slicing gives a new string; < compares.
s := "héllo"
println(len(s), s[0], s[3:], "abc" < "abd")
}
3 GET /index.html
GET true true true
16 4 get
true
-1234 true
bad format
99 bottles
ff -101
9000000000 true
6 104 llo true
Note the last line: "héllo" is 6 bytes long, because é is two bytes
in UTF-8.
To turn a byte into a one-character string, convert a one-element slice:
string([]byte{c}). (string(rune(c)) is a conversion the subset
rejects.) Another common trick is to slice a constant string: with const digits = "0123456789", digits[d:d+1] is the digit d, and no slice is
allocated. Chapter 8 uses it for keyboard characters.
Formatting: gogo/fmt
gogo/fmt has Go’s Sprint, Sprintln, Sprintf, Print, Println,
Printf and Errorf, with the usual verbs (%v %d %s %q %x %X %o %b %c %U %t %e %f %g), flags, widths and precisions. A value with an Error
or String method prints through it:
// gogo/fmt: Println, Printf with verbs, widths and precisions, Sprintf,
// Stringer and error operands, and Errorf with %w.
package main
import (
"gogo/errors"
"gogo/fmt"
)
type Celsius int
// String makes Celsius a fmt.Stringer.
func (c Celsius) String() string { return fmt.Sprintf("%d°C", int(c)) }
type Point struct{ X, Y int }
var errClosed = errors.New("closed")
func main() {
fmt.Println("temp", Celsius(21), true, 2.5)
fmt.Println(Point{1, 2}, []int{1, 2}, map[string]int{"b": 2, "a": 1})
fmt.Printf("%-6s|%5d|%05.1f|%x|%q\n", "go", 42, 3.14159, 255, "hi")
s := fmt.Sprintf("%v and %v", Celsius(-3), &Point{3, 4})
fmt.Println(s, len(s))
err := fmt.Errorf("read %s: %w", "sensor", errClosed)
fmt.Println(err, errors.Is(err, errClosed))
}
temp 21°C true 2.5
{1 2} [1 2] map[a:1 b:2]
go | 42|003.1|ff|"hi"
-3°C and &{3 4} 16
read sensor: closed true
%v of a struct, slice, map or pointer prints what println prints. Go
calls the String method of a field inside a struct; gogo does not (no
reflection), and %T and %p are not supported. Only the functions you
call are compiled into the image, but Sprintf alone brings the whole
formatter, about 19 KB of image: use println and strconv where image
size matters.
3.8 Bit operations
&, |, ^, &^, <<, >>, unary ^ and their assignment forms work on
every integer type, with Go’s rules: a shift count of the type width or
more gives 0 (or -1 when shifting a negative number right), >> keeps the
sign of a signed type and shifts zeros into an unsigned one, and a
negative shift count crashes the actor with badshift.
// Bit operations on int, int64 and byte.
package main
const (
FlagRead = 1 << iota // 1
FlagWrite // 2
FlagExec // 4
)
func main() {
perm := FlagRead | FlagWrite
println(perm&FlagWrite != 0, perm&FlagExec != 0)
perm |= FlagExec
perm &^= FlagWrite // clear a bit
println(perm)
// >> is an arithmetic shift: the sign is kept. A shift by the width
// or more gives 0 (or -1 for a negative value shifted right).
x := -16
one := 1
println(x>>2, one<<30, x>>40, one<<40)
println(^0, 0xF0^0xFF)
// byte results are cut to 8 bits after every operation.
var b byte = 0x81
println(b<<1, b>>1, ^b)
// int64 has the full 64 bits.
var w int64 = 1
w = w<<62 | 5
println(w, w>>60, w&0xFF)
// Pack and unpack an IPv4 address held in an int, as gogo/net does.
// Addresses from 128.0.0.0 up are negative ints.
ip := ipv4(192, 168, 1, 42)
println(ip, ip>>24&0xFF, ip>>16&0xFF, ip>>8&0xFF, ip&0xFF)
}
func ipv4(a, b, c, d int) int { return a<<24 | b<<16 | c<<8 | d }
true false
5
-4 1073741824 -1 0
-1 15
2 64 126
4611686018427387909 4 5
-1062731478 192 168 1 42
gogo stores IPv4 addresses in an int, which is why 192.168.1.42 prints
as a negative number. Chapter 10 shows how to format one.
3.9 Interfaces
An interface is a set of methods. Any type that has those methods satisfies it, a struct or a named basic type alike, without saying so, and a value of an interface type holds a value of any such type. Calling a method on it calls the method of the type it holds:
// Interfaces: a method set any type can satisfy (structs and named basic
// types alike), interface values that hold one of them, type switches and
// assertions on them, and == between them.
package main
type Shape interface {
Area() int
Name() string
}
type Rect struct{ W, H int }
type Square int
func (r Rect) Area() int { return r.W * r.H }
func (r Rect) Name() string { return "rect" }
func (s Square) Area() int { return int(s) * int(s) }
func (s Square) Name() string { return "square" }
// Stringer is a smaller interface; every Shape that has String is one.
type Stringer interface{ String() string }
func (s Square) String() string { return "a square" }
func total(shapes []Shape) int {
t := 0
for _, s := range shapes {
t += s.Area() // calls Rect.Area or Square.Area
}
return t
}
func describe(x any) string {
switch v := x.(type) {
case nil:
return "nothing"
case Stringer:
return v.String()
case Shape:
return v.Name()
case int:
return "an int"
}
return "something else"
}
func main() {
shapes := []Shape{Rect{2, 3}, Square(4)}
println(total(shapes))
for _, s := range shapes {
println(s.Name(), describe(s))
}
println(describe(nil), describe(7), describe("x"))
// x.(T) takes the value out (a panic if it holds another type);
// with ok it reports instead.
sq := shapes[1].(Square)
r, ok := shapes[1].(Rect)
println(int(sq), r.W, ok)
// Interface values are equal when they hold equal values of the
// same type.
var a, b Shape = Rect{2, 3}, Rect{2, 3}
println(a == b, a == shapes[0], a == Shape(Square(6)))
var none Shape
println(none == nil)
}
22
rect rect
square a square
nothing an int something else
4 0 false
true true false
true
- Satisfying an interface needs the methods, with value receivers,
a type’s own or promoted from an embedded field (an embedded
interface’s included). Interfaces can embed other interfaces (
type ReadWriter interface { Reader; Writer }), and one interface value can be assigned to another interface whose methods it has. The methods of gogo’s own types (bytes.Bytes,bytes.Buffer,fs.File) are builtins of the VM and do not count:var s Stringer = bfor aBytesb is a compile error; wrap it in a struct of your own. any(the empty interface) holds any value. Inside one, a value keeps its type: anint64is not anint, aCelsius(type Celsius int) is neither, and abyteor auint32is not aninteither.- Type switches take interface types as cases too (
case Stringer:matches every value whose type hasString() string), andcase nilmatches the nil interface value. - Type assertions:
v := x.(T)gives the value as aTand panics (interface conversion: ...) ifxholds another type;v, ok := x.(T)setsokto false instead.Tmay be an interface type. ==compares interface values by the type and the value they hold (structs field by field).x == nilis true only for the nil interface value. A method call on a nil interface value panics, as in Go.erroris the predefined interfaceinterface{ Error() string }(section 3.10).
How it works: gogo knows every type in your program when it compiles it,
so a method call on an interface value is a call of a small function the
compiler writes, which checks the value’s type against the types of your
program that have that method and calls the right one. A value goes into
an interface as it is; a named basic value (and a byte) is wrapped in a
small box so that its type can be told apart, which costs an allocation
unless the value is a constant.
Interface values cross actors in messages like any other value. A type of your program is your module’s own (chapter 14): a value of it, in an interface or not, cannot be sent to a hot-loaded module, and the module’s types cannot be sent to you.
3.10 Errors
As in Go, a function that can fail returns an error as its last result,
nil for success. error is the predefined interface interface{ Error() string }, so any type with that method is one (section 3.9), and
gogo/errors has what Go’s errors has (but As):
errors.New(text)makes an error whoseError()istext;errors.Is(err, target)reports whethererr, or an error it wraps (throughUnwrap() errormethods), istarget;errors.Unwrap(err)takes one layer off;errors.Codeis gogo’s one set of error codes, shared by every package (errors.NotFound,errors.Busy, …; appendix C). ACodeis anerror: itsError()says what it means ("not found"), anderr == errors.NotFoundworks whichever package returnederr.
// Errors are values of the interface error. gogo/errors has Go's New, Is
// and Unwrap, and Code, the shared error codes, which are errors too.
package main
import (
"gogo/errors"
"gogo/strconv"
)
// ErrEmpty is a sentinel error, compared with ==.
const ErrEmpty = errors.BadArg
// RangeError is an error type of our own, with the details.
type RangeError struct {
N int
Err error // what it wraps
}
func (e RangeError) Error() string { return strconv.Itoa(e.N) + " is out of range" }
func (e RangeError) Unwrap() error { return e.Err }
// parsePercent parses "0".."100".
func parsePercent(s string) (int, error) {
if s == "" {
return 0, ErrEmpty
}
n, err := strconv.Atoi(s)
if err != nil {
return 0, errors.New("not a number: " + s)
}
if n < 0 || n > 100 {
return 0, RangeError{n, errors.Overflow}
}
return n, nil
}
func main() {
for _, s := range []string{"42", "", "x1", "250"} {
n, err := parsePercent(s)
switch {
case err == nil:
println("["+s+"]", "=", n)
case err == ErrEmpty:
println("["+s+"]", "empty:", err.Error())
case errors.Is(err, errors.Overflow):
println("["+s+"]", "too big:", err.Error())
default:
println("["+s+"]", "error:", err.Error())
}
}
}
[42] = 42
[] empty: bad argument
[x1] error: not a number: x1
[250] too big: 250 is out of range
Compare an error with a sentinel by == (err == errors.NotFound), or
with errors.Is when it may be wrapped; a type switch or err.(T) gets
at an error type’s details. Unlike Go, two errors from errors.New with
the same text are equal: an error is a value, compared by what it holds.
Warning.
gogo/fsandgogo/codestill return anerrors.Code(fs.Err,code.Err), not anerror, and their success iserrors.OK, the code 0. Put into anerror,errors.OKis a non-nil error, like a typed nil pointer in Go:return fs.WriteFile(p, b)in a function that returnserrorwould report every success as a failure. The compiler rejects that form, and the same in avaror an assignment (errors.Code result used as an error); passing the result to compare it (errors.Is(fs.Remove(p), errors.NotFound)) and an expliciterror(...)conversion are allowed. Check the code first:func save(p string, b bytes.Bytes) error { if c := fs.WriteFile(p, b); c != fs.OK { return c } return nil }The functions that return
error(port.Open,strconv.Atoi,http.Get, …) return a truenilon success.
For failures you do not expect and cannot handle, gogo’s answer is
different: let the actor crash, and let a supervisor restart it. That is
the subject of chapter 5. panic(v) crashes the current actor on
purpose: it prints panic: and v on standard error and ends the actor
with the reason actor.Panic. There is no recover. To stop the current
actor with a code of your own instead, call actor.Exit(code) with a
code of 100 or more.
3.11 What is not supported
Here is a program that uses many of the features gogo leaves out:
// This program does NOT compile: it collects the Go features the gogo
// subset rejects, so you can see the compiler's messages.
package main
var counter = 0 // fine: package-level variables are read-only
type Shape interface{ Area() int } // fine: interfaces are supported
type Sq struct{ S int }
func (s *Sq) Area() int { return s.S * s.S } // fine: pointer receivers are supported
func Max[T int | int64](a, b T) T { // generics
if a > b {
return a
}
return b
}
func main() {
ch := make(chan int) // channel
go func() { ch <- 1 }()
sq := []Sq{{2}}
defer recover() // recover
m := map[*Sq]int{} // a map with pointer keys
p := &sq[0] // a pointer into a slice
x := 1.5i // complex
if counter > 0 {
goto done // goto
}
counter++ // a write to a package-level variable
done:
var a any = [4]int{} // array in an interface
y := any(1).(int) // fine: type assertions are supported
_ = y
println(m, p, x, a)
println(recover())
}
gogo build reports each one:
main.gg:13:1: gogo: generic function not supported
main.gg:21:8: gogo: channel not supported
main.gg:22:2: gogo: go statement not supported
main.gg:24:8: gogo: recover (a panic ends the actor: let its supervisor restart it) not supported
main.gg:25:7: gogo: map with key type *main.Sq: a pointer key (no pointer keys: pointers move) not supported
main.gg:26:7: gogo: interior pointer &sq[0] not supported: gogo has no pointers into a slice element or a struct field; use a []*T or a *T field, or s[i].F = v
main.gg:27:7: gogo: complex not supported
main.gg:29:3: gogo: goto statement not supported
main.gg:31:2: gogo: package-level variable counter is read-only
main.gg:32:1: gogo: label on a statement other than for or switch not supported
main.gg:33:14: gogo: array in interface not supported: use a slice or a struct with an array field
main.gg:36:10: gogo: map with key type *main.Sq: a pointer key (no pointer keys: pointers move) not supported
main.gg:36:16: gogo: complex not supported
main.gg:37:10: gogo: recover (a panic ends the actor: let its supervisor restart it) not supported
The full list, with what to do instead:
| Go feature | Error | gogo way |
|---|---|---|
go f() | go statement not supported | actor.Spawn(f) |
channels, select, <- | channel not supported, operator <- not supported | messages: actor.Send, actor.Receive |
defer in a loop | defer inside a loop not supported: deferred calls are static (move the loop body into a function) | a function per iteration |
recover() | recover (a panic ends the actor: let its supervisor restart it) not supported | let the actor exit; a supervisor restarts it (chapter 5); ports and files close automatically |
writing a package-level var | package-level variable counter is read-only | state in an actor |
| a map with pointer keys | map with key type *T: a pointer key (no pointer keys: pointers move) not supported | a key the pointer’s target identifies |
a pointer into a slice element or a field, &s[i], &v.F | interior pointer &s[i] not supported | a []*T or a *T field, or s[i].F = v |
goto | goto statement not supported | labeled break/continue, or a function and return |
complex64/128 | complex not supported | two floats |
uintptr | uintptr not supported | uint32 |
| generics | generic function not supported | write the function per type |
| Go’s std packages by their Go paths | import "fmt": package not found | the gogo ones: gogo/fmt, gogo/strings, gogo/strconv, gogo/errors, gogo/math |
an array in any | array in interface not supported | a slice, or a struct holding the array |
func init() | func init not supported | call it from main |
Small surprises
printlnaccepts any number of integer, float,bool,string, PID, Ref, struct and slice arguments (structs print as{1 2}, slices as[1 2], unlike Go), but notBytesorBuffer(use.String()), not a struct or slice holdinguint32oruint64values, and not a multi-result call (println(divmod(7, 2))ismultiple values not supported). An interface value prints the value it holds (Go prints two addresses), a pointer what it points to (&{1 2}), a mapmap[k:v]; a sized integer or a named basic value inside one prints in its box,{5}, unless the program uses pointers, maps orgogo/fmt(then5: older firmware cannot print it so, and a program without them still runs there).- A multi-result call can be a statement on its own or deferred, as in
Go, a gogo builtin’s included:
actor.ReceiveTimeout(0)on a line by itself drops whatever message it takes. Its results are discarded. - The zero PID is
actor.PID{}, equal to avar p actor.PIDthat was never set. It names no actor (chapter 4). - Unary
+is rejected (operator + not supported).
With the language in hand, we can turn to what gogo is really about: actors.
4. Actors
An actor is a lightweight process with three things of its own: a heap (its memory), a mailbox (a queue of incoming messages) and a PID (its address). Actors share nothing. The only way one actor affects another is to send it a message.
If you know Go, think of an actor as a goroutine that owns all its data and
has exactly one channel, its mailbox, that anyone with its PID can send
to. If you know Erlang, this is the Erlang process model with Go syntax:
spawn is actor.Spawn, ! is actor.Send, and receive is
actor.Receive plus a type switch.
Everything in this chapter is in the gogo/actor package.
4.1 Spawn, Send, Receive
func Spawn(f func()) PID
func Send(to PID, msg any)
func Receive() any
func Self() PID
Spawn starts a new actor running f and returns its PID at once; the
new actor runs when the scheduler gets to it. Send puts a copy of msg
in the mailbox of to and returns immediately; it never blocks and never
fails (a message to an actor that no longer exists is dropped). Receive
takes the oldest message from your own mailbox, waiting if there is none.
An actor ends when its function returns. The typical actor is a loop
around Receive that keeps its state in local variables:
// An actor that owns state: a counter. Other actors change it and read it
// only by sending messages.
package main
import "gogo/actor"
type Add struct{ N int }
type Get struct{ From actor.PID }
type Value struct{ N int }
type Stop struct{}
func counter() {
total := 0
for {
switch m := actor.Receive().(type) {
case Add:
total += m.N
case Get:
actor.Send(m.From, Value{total})
case Stop:
println("counter stopping at", total)
return // returning from the entry function ends the actor
default:
println("counter: unknown message dropped")
}
}
}
func main() {
c := actor.Spawn(counter)
for i := 1; i <= 10; i++ {
actor.Send(c, Add{i})
}
actor.Send(c, "hello?") // any value can be sent; the counter drops it
actor.Send(c, Get{actor.Self()})
switch v := actor.Receive().(type) {
case Value:
println("total", v.N)
}
actor.Send(c, Stop{})
}
counter: unknown message dropped
total 55
counter stopping at 55
Points to notice:
- The state (
total) is an ordinary local variable. No other actor can touch it, so there is no locking. Other actors change it by sendingAddand read it by sendingGet. - Each message type is its own struct. Using a struct per kind of message (instead of, say, strings) lets the type switch pick them apart, and lets the Go type checker catch typos.
- A request that needs an answer carries the PID to answer to (
Get{From}). Section 4.3 shows a more convenient way. - The
defaultcase drops messages the actor does not understand. Without it, unknown messages would be dropped too (Receivealready took them out of the mailbox); thedefaultjust makes it visible. - Messages from one sender arrive in the order they were sent.
Every message is copied into the receiver’s memory. Chapter 6 explains why and what it costs; for now just remember that the receiver can never change the sender’s data.
Main is an actor too
main runs in the first actor. When main returns, only that actor ends;
other actors keep running. The VM exits when no actor can run any more, no
timer is pending and no port can deliver an event. On a board the VM then
prints gogo: vm exited and idles.
Scheduling
The VM runs one actor at a time on a single scheduler. An actor runs until
it waits (in Receive, Sleep, Call …) or until it has used up its
time slice: every function call and every loop iteration costs one
reduction, and after 1000 the actor is put at the back of the queue. So a
busy loop cannot freeze the other actors, even for { n++ }.
The zero PID
A PID variable that was never set holds the zero PID. You can also write
it as actor.PID{} or actor.NoPID (a read-only package-level
variable). It names no actor, so it is a safe “nobody yet” value: compare
with it (if w == actor.NoPID) to see whether a PID was set. Each actor
builtin treats it as an actor that has exited:
| Function | With the zero PID |
|---|---|
Send(p, m), SendAfter(p, m, ms) | the message is dropped (SendAfter still returns a Ref) |
Call(p, req, ms) | fails at once with errors.NoProc (4.3) |
Register(name, p) | fails with errors.NoProc (4.4) |
Monitor(p) | a DownMsg with reason actor.NoProc arrives at once (chapter 5) |
Link(p) | the exit signal actor.NoProc arrives at once: it ends the caller unless the caller traps exits, and then it is an ExitMsg (chapter 5) |
Unlink(p), Kill(p, code) | nothing |
Info(p), Limit(p) | Memory 0; 0 |
Whereis of an unknown name and a failed port.Open return it. It
prints as <pid 0>, which is also how println shows the main actor’s
PID (println shows only a PID’s slot, chapter 5); compare with ==,
which tells them apart.
4.2 Type switches: reading messages
Receive returns any, and a type switch finds out what it holds. The
case types can be any of your struct types, int, int64, float32,
float64, bool, string, actor.PID, actor.Ref and bytes.Bytes, and the struct types
of the gogo packages (actor.ExitMsg, gpio.Edge, kbd.Key, …):
// The type switch is how an actor tells messages apart. Cases can be
// struct types, int, int64, bool, string, actor.PID, actor.Ref and
// bytes.Bytes; default catches the rest.
package main
import "gogo/actor"
type Celsius struct{ Deg int }
type Reset struct{}
func describe(m any) {
switch v := m.(type) {
case Celsius:
println("temperature", v.Deg)
case Reset:
println("reset")
case int:
println("int", v)
case int64:
println("int64", v)
case string:
println("string", v)
case bool:
println("bool", v)
case actor.PID:
println("a pid")
default:
println("something else")
}
}
func main() {
me := actor.Self()
for _, m := range []any{Celsius{21}, Reset{}, 7, int64(7), "hi", true, me, []int{1}} {
describe(m)
}
}
temperature 21
reset
int 7
int64 7
string hi
bool true
a pid
something else
int and int64 are different cases: an int64 put into any stays an
int64. So do a byte and a value of a named basic type such as type Celsius int: each keeps its own type in an any (it is boxed), so case Celsius matches a Celsius and not an int. Slices can be sent but cannot
be a case; put them in a struct.
When only one type is expected, a type assertion is shorter: t := m.(Celsius) takes the value out, and crashes the actor with a panic if m
holds another type; t, ok := m.(Celsius) does not crash but sets ok to
false (and t to the zero value).
Note. Erlang’s
receivecan wait for a message matching a pattern and leave the others in the mailbox. gogo’sReceivealways takes the oldest message. The one exception isCall(next section), which waits for its own reply and leaves everything else in place. This keeps the VM simple and receiving cheap.
4.3 Call and Reply
Asking a question and waiting for the answer is so common that gogo has it built in:
func Call(to PID, req any, timeoutMs int) (reply any, err error)
func Reply(req Request, reply any)
type Request struct{ From PID; Ref Ref; Body any }
Call wraps req in an actor.Request with a fresh unique Ref, sends
it, and waits for a reply carrying that Ref, at most timeoutMs
milliseconds. Other messages that arrive meanwhile stay in the mailbox.
err is nil when the reply came; otherwise reply is nil and err
is a gogo/errors code that says why:
err | Why | When |
|---|---|---|
errors.Timeout | no reply within timeoutMs | after the timeout (at once for timeoutMs <= 0 with no reply yet) |
errors.NoProc | to is no live actor: it has exited, never existed, is the zero PID or a port | at once |
errors.NoConnection | to is on another node that is not connected, or went away while you waited (4.8, chapter 20) | at once |
Compare with == (err == errors.Timeout) or print err.Error(). The
req of a failed Call is still checked as a Send’s message is, so one
that cannot be sent (a closure, a port’s PID to another node, …) stops
the caller with actor.BadMsg.
The server receives an actor.Request, looks at its Body, and answers
with actor.Reply:
// Call and Reply: a request-reply server holding a small key-value table.
package main
import (
"gogo/actor"
"gogo/errors"
)
type Put struct {
Key string
Value int
}
type Lookup struct{ Key string }
type Found struct {
Value int
OK bool
}
type entry struct {
Key string
Value int
}
func store() {
var tbl []entry
for {
switch r := actor.Receive().(type) {
case actor.Request:
switch b := r.Body.(type) {
case Put:
tbl = put(tbl, b.Key, b.Value)
actor.Reply(r, true)
case Lookup:
v, ok := get(tbl, b.Key)
actor.Reply(r, Found{v, ok})
}
}
}
}
func put(tbl []entry, k string, v int) []entry {
for i, e := range tbl {
if e.Key == k {
tbl[i] = entry{k, v}
return tbl
}
}
return append(tbl, entry{k, v})
}
func get(tbl []entry, k string) (int, bool) {
for _, e := range tbl {
if e.Key == k {
return e.Value, true
}
}
return 0, false
}
// lookup wraps the Call in a function with a typed result.
func lookup(s actor.PID, k string) (value int, found bool, err error) {
reply, err := actor.Call(s, Lookup{k}, 100)
if err != nil {
return 0, false, err // errors.Timeout, errors.NoProc, ...
}
f, _ := reply.(Found)
return f.Value, f.OK, nil
}
func main() {
s := actor.Spawn(store)
if _, err := actor.Call(s, Put{"led", 1}, 100); err != nil {
println("put led:", err.Error())
}
if _, err := actor.Call(s, Put{"fan", 0}, 100); err != nil {
println("put fan:", err.Error())
}
v, found, _ := lookup(s, "led")
println("led", v, found)
v, found, _ = lookup(s, "door")
println("door", v, found)
// A message sent to main before a Call stays in the mailbox: Call
// waits only for its own reply.
actor.Send(actor.Self(), "kept for later")
v, found, _ = lookup(s, "fan")
println("fan", v, found)
println(actor.Receive())
// A Call to an actor that never answers times out.
silent := actor.Spawn(func() { actor.Receive() })
_, err := actor.Call(silent, Lookup{"x"}, 50)
println("silent:", err.Error())
// A Call to an actor that has exited fails at once.
actor.Kill(silent, actor.Killed)
_, _, err = lookup(silent, "x")
println("killed:", err == errors.NoProc, err.Error())
}
led 1 true
door 0 false
fan 0 true
kept for later
silent: timed out
killed: true no such actor
It is good style to hide each Call behind a small function with a typed
result, like lookup here, so that the rest of the program never sees
any.
Note. If the server dies while you wait,
Calldoes not return early: it waits until the timeout and fails witherrors.Timeout. Monitor the server (chapter 5) if you need to know sooner. (For a server on another board, see 4.8 and 20.5: a Call fails at once witherrors.NoConnectionwhen the server’s node goes away.)
4.4 Registered names
Passing PIDs around works, but some actors are services that many others need: a logger, a display, the DNS resolver. Give them a name:
func Register(name string, p PID) error // errors.NoProc or errors.Exists
func Whereis(name string) (PID, bool)
func Unregister(name string)
Register fails with errors.NoProc if p is not a live actor of this
VM (it has exited, is the zero PID, a port or a remote PID; this is
checked first), and with errors.Exists if another actor has the name.
Whereis has no error, only ok: it looks the name up in this VM’s own
table, as v, ok := m[k] looks in a map, and either the name is there or
it is not. node.Whereis (chapter 20), which finds a name on another
node, returns an error instead, because it asks over the network and
can fail for the network’s reasons (errors.Timeout,
errors.NoConnection).
// Registered names: find a service by name instead of passing its PID.
package main
import "gogo/actor"
type Log struct{ Line string }
type Flush struct{ From actor.PID }
func logger() {
n := 0
for {
switch m := actor.Receive().(type) {
case Log:
n++
println("log", n, m.Line)
case Flush:
actor.Send(m.From, n)
}
}
}
// logf sends to the "log" service if it runs.
func logf(line string) {
if p, ok := actor.Whereis("log"); ok {
actor.Send(p, Log{line})
}
}
func main() {
logf("lost: nobody is registered yet")
l := actor.Spawn(logger)
if err := actor.Register("log", l); err != nil {
println("register:", err.Error())
}
err := actor.Register("log", actor.Self())
println("again:", err.Error()) // errors.Exists: the name is taken
done := actor.Self()
for i := 0; i < 2; i++ {
actor.Spawn(func() {
logf("from a worker")
actor.Send(done, true)
})
actor.Receive()
}
logf("from main")
actor.Send(l, Flush{actor.Self()})
println("lines logged:", actor.Receive())
actor.Unregister("log")
_, ok := actor.Whereis("log")
println("after unregister:", ok)
}
again: exists already
log 1 from a worker
log 2 from a worker
log 3 from main
lines logged: 3
after unregister: false
A name belongs to the actor until it exits or the name is unregistered;
then the name is free again. Only the actor that registered a name can
unregister it; Unregister from any other actor does nothing.
A supervisor that restarts a named service can
have the new instance register the same name, so clients that look the
name up each time always find the live one. One actor can hold several
names.
4.5 Time
func Now() int64 // ms since the VM started
func Sleep(ms int)
func ReceiveTimeout(ms int) (msg any, ok bool) // ms == 0: only look
func SendAfter(to PID, msg any, ms int) Ref // Send's arguments, then the delay
func CancelTimer(r Ref) bool // false if it already fired
Sleep pauses only the calling actor. ReceiveTimeout is Receive with
a deadline; ok is false if nothing came. SendAfter arranges for a
message to be delivered later, which is how you build periodic work: on
each tick, arm the next one.
// Time: Now, Sleep, ReceiveTimeout, SendAfter and CancelTimer.
package main
import "gogo/actor"
type Tick struct{ N int }
func main() {
start := actor.Now()
actor.Sleep(30)
println("slept at least 30 ms:", actor.Now()-start >= 30)
// ReceiveTimeout: wait at most 20 ms. 0 only looks.
_, ok := actor.ReceiveTimeout(20)
println("got a message:", ok)
// SendAfter delivers a message later; timers fire in deadline order.
me := actor.Self()
actor.SendAfter(me, "late", 40)
actor.SendAfter(me, "early", 10)
t := actor.SendAfter(me, "cancelled", 20)
println("cancel:", actor.CancelTimer(t))
println(actor.Receive())
println(actor.Receive())
// A periodic tick: re-arm the timer each time it fires.
actor.SendAfter(me, Tick{1}, 10)
last := 0
for last < 3 {
switch m := actor.Receive().(type) {
case Tick:
println("tick", m.N)
last = m.N
if m.N < 3 {
actor.SendAfter(me, Tick{m.N + 1}, 10)
}
}
}
println("done")
}
slept at least 30 ms: true
got a message: false
cancel: true
early
late
tick 1
tick 2
tick 3
done
4.6 What a spawned closure takes with it
Spawn takes a function value, so you can pass a closure that captures
arguments for the new actor: actor.Spawn(func() { worker(me, 3) }). The
captured values are copied into the new actor’s heap when it starts.
Changing them in the child does not change them in the parent:
// A spawned closure gets copies of what it captures: the new actor shares
// no memory with its parent.
package main
import "gogo/actor"
func main() {
me := actor.Self()
data := []int{1, 2, 3}
actor.Spawn(func() {
data[0] = 100 // changes the child's copy only
actor.Send(me, data[0])
})
println("child saw", actor.Receive())
println("parent still has", data[0])
// Each actor has its own PID; Self tells an actor its own.
child := actor.Spawn(func() {
actor.Send(me, actor.Self())
})
switch p := actor.Receive().(type) {
case actor.PID:
println("same pid:", p == child, p == me)
}
}
child saw 100
parent still has 1
same pid: true false
A captured variable that the closure and its maker both change (chapter 3) is shared within one actor; a spawned closure takes a copy of it with it, so from then on the child’s variable is its own.
SpawnLink and SpawnOpt are variants of Spawn that link the new actor
to the caller and set its memory limit; they come up in the next two
chapters.
4.7 Designing with actors
A few habits make actor programs easy to follow:
- One actor per resource or activity. The actor that opened a pin handles that pin; the actor that owns the screen draws on it. Others send it messages.
- Messages are structs with exported, meaningful names, one per kind
of request or event. Put the reply-to PID in the message, or use
Call. - Wrap the protocol in functions. Callers should call
lookup(s, k), not buildRequests. - Keep handlers short. While an actor handles one message, its mailbox fills. Give slow work to another actor.
- Do not handle every error. If an actor gets into a state it does not understand, let it exit and let a supervisor start a fresh one. The next chapter shows how.
4.8 Actors on other boards
Everything in this chapter also works between boards. With gogo/node
(chapter 20), a PID can name an actor on another board or on a server, and
Send, Call/Reply, Monitor and Link work on it unchanged. A
message to a remote actor is copied over the network as a local one is
copied into the receiver’s heap, with a few limits on what may cross
(20.4): no func values, pointers, maps or bytes.Buffer, and at most
about 4 KB encoded. When an actor’s whole node goes away, its links and
monitors fire with the reason actor.NoConnection (chapter 5, 20.5).
This is the client of examples/nodehello joining a server node, finding its exported counter and calling it:
if err := node.Connect(addr, "client"); err != nil {
println("connect:", err.Error())
return
}
counter, err := node.Whereis("server", "counter", 2000)
if err != nil {
println("whereis:", err.Error())
return
}
println("client: found counter", counter)
ref := actor.Monitor(counter)
for i := 1; i <= 5; i++ {
total, err := actor.Call(counter, Add{N: i}, 2000)
The counter on the server is an ordinary Call server like the one in
4.3; tests/dist runs the program as a server and clients on separate
host VMs. Chapter 20 shows how to set up the server node and the shared
token, and covers delivery, limits and security.
5. Failure and Recovery
Programs fail. A sensor returns garbage, a parser meets input nobody thought of, a counter overflows into an index. In most embedded systems a fault like that resets the whole device, or worse, corrupts memory and carries on.
gogo takes Erlang’s approach: make failure small, visible and recoverable. A fault ends only the actor it happened in. The actors that care are told why. A supervisor starts a fresh copy. Because the failed actor’s memory, pins and files are released when it ends, the fresh copy starts from a clean state. This is “let it crash”: instead of guarding against every possible error inside an actor, you arrange for the system around it to recover.
5.1 A crash ends one actor
// A crash ends only the actor that crashed. Its neighbours keep running.
package main
import "gogo/actor"
func divide(a, b int) int { return a / b }
func main() {
me := actor.Self()
for _, d := range []int{2, 0, 5} {
actor.Spawn(func() {
actor.Send(me, divide(100, d)) // d == 0 crashes this actor only
})
}
// Two answers arrive; the third worker crashed instead of answering.
for i := 0; i < 2; i++ {
println("answer", actor.Receive())
}
_, ok := actor.ReceiveTimeout(50)
println("third answer:", ok)
println("main is fine")
}
Standard output:
answer 50
answer 20
third answer: false
main is fine
Standard error:
gogo: actor <pid 2> crashed: divzero in divide
The worker that divided by zero ended; the other two answered; main
carried on. The VM printed a crash report on standard error (on a board,
in red on the screen):
gogo: actor <pid N> crashed: <kind>[ in <function>]
<pid N> is the actor’s slot number. Slots are reused, so two different
actors over time can show the same number, and the zero PID and the main
actor both print as <pid 0>. <function> is where a runtime error
happened; closures are named main.main.func1 and so on.
5.2 Exit reasons
Every actor ends with a reason:
type Reason struct {
Code int // a reason code
Func string // function a runtime error happened in, else ""
}
| Code | Constant | Cause | Crash report |
|---|---|---|---|
| 0 | actor.Normal | the entry function returned | none |
| 1 | actor.Killed | actor.Kill(p, actor.Killed) | killed |
| 2 | actor.OutOfMemory | over its memory limit (chapter 6), or the whole VM ran out | oom |
| 3 | actor.MailboxOverflow | queued messages took it over its limit | mailbox_overflow |
| 4 | actor.NoProc | linked to an actor that did not exist | noproc |
| 5 | actor.DivZero | integer division or % by zero | divzero |
| 6 | actor.BadCode | index or slice out of range, nil function call, unusable zero Buffer, … | badcode |
| 7 | actor.Shutdown | asked to stop (supervisors use this) | none |
| 8 | actor.BadShift | a negative shift count | badshift |
| 9 | actor.BadMsg | sent a module’s own value to another module (chapter 14) | badmsg |
| 10 | actor.Panic | panic(v), a failed type assertion, a method call on a nil interface | panic, after panic: v |
| 11 | actor.NoConnection | linked to an actor on another node that became unreachable (20.5) | noconnection |
| 12 | actor.Nil | a nil pointer dereference, a write to a nil map | nil |
| 64..99 | actor.Fail(code) | a failure a shared error code describes: actor.Failed (64) + the code (appendix C), as http.ListenFailed is actor.Fail(errors.Busy), 69 | exit(<code>) |
| ≥ 100 | your own | actor.Exit(code) or actor.Kill(p, code) | exit(<code>) |
Normal and Shutdown are the two “expected” endings; everything else
counts as abnormal. Here is how each one is produced and what a monitor
(section 5.4) sees:
// Every way an actor can end, and the reason code a monitor sees for it.
package main
import "gogo/actor"
func watch(name string, f func()) {
p := actor.Spawn(f)
actor.Monitor(p)
switch m := actor.Receive().(type) {
case actor.DownMsg:
println(name, "-> code", m.Reason.Code, "func ["+m.Reason.Func+"]")
}
}
func deep(n int) int { return deep(n+1) + 1 }
func main() {
watch("return", func() {})
watch("exit(150)", func() { actor.Exit(150) })
watch("divide by zero", func() {
zero := 0
println(1 / zero)
})
watch("index out of range", func() {
xs := []int{1, 2, 3}
i := 3
println(xs[i])
})
watch("negative shift", func() {
n := -1
println(1 << n)
})
watch("nil func", func() {
var f func()
f()
})
watch("endless recursion", func() { println(deep(0)) })
watch("panic", func() { panic("boom") })
watch("killed", func() {
actor.Kill(actor.Self(), actor.Killed)
})
}
return -> code 0 func []
exit(150) -> code 150 func []
divide by zero -> code 5 func [main.main.func3]
index out of range -> code 6 func [main.main.func4]
negative shift -> code 8 func [main.main.func5]
nil func -> code 6 func [main.main.func6]
endless recursion -> code 2 func [deep]
panic -> code 10 func [main.main.func8]
killed -> code 1 func []
Standard error:
gogo: actor <pid 1> crashed: exit(150)
gogo: actor <pid 1> crashed: divzero in main.main.func3
gogo: actor <pid 1> crashed: badcode in main.main.func4
gogo: actor <pid 1> crashed: badshift in main.main.func5
gogo: actor <pid 1> crashed: badcode in main.main.func6
gogo: actor <pid 1> crashed: oom in deep
panic: boom
gogo: actor <pid 1> crashed: panic in main.main.func8
gogo: actor <pid 1> crashed: killed
Note that endless recursion is not a special error: the stack lives in the
actor’s memory, so it simply runs into the memory limit (oom).
panic(v) is Go’s: it prints panic: and the value on standard error
and ends the actor, here with the reason actor.Panic. There is no
recover. A panic is a crash like the others, so the links, monitors and
supervisors of the next sections handle it; that is gogo’s answer to
“something that should never happen just did”.
5.3 Links
A link joins two actors’ fates. When one exits with an abnormal reason, the other receives an exit signal and, unless it traps exits, exits too with the same reason. Links are two-way.
func SpawnLink(f func()) PID // spawn and link in one step
func Link(p PID)
func Unlink(p PID)
Use links for actors that only make sense together: a connection handler and the parser it started, a worker and its helper. If one fails, both should be restarted together.
// Links tie actors' fates together: when one exits abnormally, the actors
// linked to it exit too, with the same reason.
package main
import "gogo/actor"
type Hello struct{ Who string }
func part(name string, boss actor.PID, crash bool) {
actor.Send(boss, Hello{name})
if crash {
zero := 0
println(1 / zero)
}
for {
actor.Receive()
}
}
func main() {
me := actor.Self()
// a and b are linked: SpawnLink inside a links b to a.
a := actor.Spawn(func() {
actor.SpawnLink(func() { part("b", me, true) })
part("a", me, false)
})
ref := actor.Monitor(a)
for i := 0; i < 2; i++ {
switch m := actor.Receive().(type) {
case Hello:
println("started", m.Who)
}
}
// b crashed; a, linked to it and not trapping exits, went down too.
switch m := actor.Receive().(type) {
case actor.DownMsg:
println("a went down with b:", m.Ref == ref, m.Reason.Code == actor.DivZero)
}
// A normal exit does not take linked actors down.
c := actor.Spawn(func() {
actor.SpawnLink(func() {}) // returns at once: Normal
actor.Sleep(20)
actor.Send(me, "c survived its partner's normal exit")
})
_ = c
println(actor.Receive())
}
started a
started b
a went down with b: true true
c survived its partner's normal exit
Standard error (actor a is reported too, with the reason it inherited):
gogo: actor <pid 2> crashed: divzero in part
gogo: actor <pid 1> crashed: divzero in part
A Normal exit sends a signal as well, but a non-trapping actor ignores it,
which is why c survives. SpawnLink links before the child runs, so
there is no window in which the child could die unnoticed; Spawn followed
by Link has such a window. Linking to an actor that has already exited
delivers a NoProc signal at once.
Links (and the monitors of 5.5) work the same on an actor on another
board (4.8). If that actor’s whole node becomes unreachable, the signal
carries the reason actor.NoConnection (11) instead of the actor’s own;
see 20.5.
5.4 Trapping exits
An actor that calls actor.TrapExit(true) is not taken down by exit
signals. Instead each signal arrives as a message:
type ExitMsg struct {
From PID
Reason Reason
}
This is how a supervisor watches its children. actor.Kill(p, code) sends
an exit signal on purpose; a trapping actor receives it as an ExitMsg
like any other, with one exception: Kill(p, actor.Killed) cannot be
trapped and always ends the target.
// TrapExit turns exit signals from linked actors into ExitMsg messages, so
// an actor can react to a partner's death instead of dying with it.
package main
import "gogo/actor"
func flaky(n int) {
if n%2 == 1 {
zero := 0
println(1 / zero)
}
actor.Exit(100 + n)
}
func main() {
actor.TrapExit(true)
var pids []actor.PID
for i := 0; i < 3; i++ {
pids = append(pids, actor.SpawnLink(func() { flaky(i) })) // each iteration has its own i
}
for i := 0; i < 3; i++ {
switch m := actor.Receive().(type) {
case actor.ExitMsg:
who := -1
for j, p := range pids {
if p == m.From {
who = j
}
}
println("worker", who, "exited with", m.Reason.Code)
}
}
// Kill with Shutdown is trapped like any other signal; Killed cannot be.
t := actor.SpawnLink(func() {
actor.TrapExit(true)
for {
switch m := actor.Receive().(type) {
case actor.ExitMsg:
println("target trapped code", m.Reason.Code)
}
}
})
actor.Sleep(10)
actor.Kill(t, actor.Shutdown)
actor.Sleep(10)
actor.Kill(t, actor.Killed)
switch m := actor.Receive().(type) {
case actor.ExitMsg:
println("target gone, code", m.Reason.Code)
}
}
worker 0 exited with 100
worker 1 exited with 5
worker 2 exited with 102
target trapped code 7
target gone, code 1
Standard error:
gogo: actor <pid 1> crashed: exit(100)
gogo: actor <pid 2> crashed: divzero in flaky
gogo: actor <pid 3> crashed: exit(102)
gogo: actor <pid 1> crashed: killed
Each closure gets its own i: as in Go 1.22, every iteration of the loop
has its own loop variable (chapter 3).
5.5 Monitors
A monitor is a one-way link that never kills anybody. The watcher gets a message when the watched actor exits, for any reason:
func Monitor(p PID) Ref
func Demonitor(r Ref)
type DownMsg struct {
Ref Ref // the Ref Monitor returned
From PID
Reason Reason
}
Use a monitor when you depend on an actor but should not die with it: a
client watching a server, a manager watching jobs. Combined with Call it
tells you when a server is gone:
// Monitors watch an actor one way: the watcher gets a DownMsg and is never
// taken down itself. Pair Call with a monitor to notice a dead server early.
package main
import "gogo/actor"
type Work struct{ N int }
func server() {
for {
switch r := actor.Receive().(type) {
case actor.Request:
switch w := r.Body.(type) {
case Work:
actor.Reply(r, 100/w.N) // N == 0 crashes the server
}
}
}
}
func main() {
s := actor.Spawn(server)
ref := actor.Monitor(s)
reply, err := actor.Call(s, Work{4}, 1000)
println("reply", reply, err == nil)
// This request crashes the server. Call does not return early when the
// server dies: it waits out its timeout.
start := actor.Now()
_, err = actor.Call(s, Work{0}, 200)
println(err.Error(), "after the full timeout:", actor.Now()-start >= 200)
// The DownMsg was queued meanwhile.
switch m := actor.Receive().(type) {
case actor.DownMsg:
println("server down:", m.Ref == ref, m.Reason.Code)
}
// Monitoring an actor that is already gone gives a DownMsg at once,
// with reason NoProc.
actor.Monitor(s)
switch m := actor.Receive().(type) {
case actor.DownMsg:
println("late monitor:", m.Reason.Code == actor.NoProc)
}
}
reply 25 true
timed out after the full timeout: true
server down: true 5
late monitor: true
Standard error:
gogo: actor <pid 1> crashed: divzero in server
Monitoring an actor that does not exist (any more) delivers a DownMsg
with NoProc straight away, so there is no race between looking up a PID
and monitoring it. Demonitor cancels a monitor; no DownMsg arrives
afterwards. A monitor of an actor on another board delivers a DownMsg
with actor.NoConnection when that board, or the server between, goes
away (20.5).
Good to know. The
ExitMsgorDownMsgan exit will need is reserved when you create the link or monitor, and charged to the actor that created it. When an actor exits, the notifications are delivered without allocating memory, so they arrive even when memory is short.
5.6 Supervisors
A supervisor is an actor whose only job is to start a child, watch it,
and restart it when it fails. gogo/supervisor provides one, written in the
gogo subset with the pieces from this chapter (it is about 120 lines; read
lib/supervisor/supervisor.gg to see exactly what it does).
func Supervise(child func(), spec Spec) actor.PID
type Spec struct {
Restart int // supervisor.Permanent or supervisor.Transient
MaxRestarts int // restarts allowed within one window
PeriodMs int // window length in ms; <= 0: never expires
}
Supervisestarts a supervisor linked to the caller, which startschildlinked to itself.- Permanent: restart the child however it ends, even
Normal. - Transient: restart only after an abnormal exit; when the child ends
with
NormalorShutdown, the supervisor exitsNormal. - Restart intensity: if the child needs more than
MaxRestartsrestarts withinPeriodMs, something is seriously wrong; the supervisor gives up and exits withShutdown. Its own supervisor, if any, then decides what to do. The window opens at the first restart and the count starts over oncePeriodMshas passed. - When the actor that called
Superviseexits (even normally), the supervisor stops the child (asking withShutdown, then after 1 s withKilled) and exits too. Somainmust not return while the tree should keep running.
Here is “let it crash” in full. The worker does no error checking at all: on bad input it just exits. The supervisor brings it back, and the service keeps answering:
// Let it crash: a worker parses commands and crashes on bad ones. A
// supervisor restarts it, so the service keeps working.
package main
import (
"gogo/actor"
"gogo/strconv"
"gogo/supervisor"
)
type Ready struct{ From actor.PID }
// parse turns "n" into n, and crashes on anything else: no error handling
// at all, the supervisor takes care of failure.
func parse(s string) int {
n, err := strconv.Atoi(s)
if err != nil {
actor.Exit(100) // "bad input"
}
return n
}
func worker(boss actor.PID) {
actor.Send(boss, Ready{actor.Self()})
for {
switch r := actor.Receive().(type) {
case actor.Request:
switch s := r.Body.(type) {
case string:
actor.Reply(r, parse(s)*2)
}
}
}
}
func main() {
me := actor.Self()
supervisor.Supervise(func() { worker(me) }, supervisor.Spec{
Restart: supervisor.Permanent,
MaxRestarts: 3,
PeriodMs: 1000,
})
var none, w actor.PID // zero PIDs
for _, in := range []string{"21", "oops", "50", "x", "4"} {
// Every new instance says Ready first; take the newest PID.
for {
m, ok := actor.ReceiveTimeout(0)
if !ok {
break
}
switch r := m.(type) {
case Ready:
w = r.From
}
}
if w == none {
switch r := actor.Receive().(type) {
case Ready:
w = r.From
}
}
reply, err := actor.Call(w, in, 100)
if err != nil {
println(in, "-> no answer (the worker crashed):", err.Error())
w = none
continue
}
println(in, "->", reply)
}
// main returns: the supervisor shuts the worker down and exits too.
}
21 -> 42
oops -> no answer (the worker crashed): timed out
50 -> 100
x -> no answer (the worker crashed): timed out
4 -> 8
Standard error:
gogo: actor <pid 2> crashed: exit(100)
gogo: actor <pid 2> crashed: exit(100)
The request that caused the crash got no answer (main’s Call failed with errors.Timeout),
but the next request found a fresh worker. In a real program the client
would report “bad input”, retry, or move on.
A new child instance has a new PID. That is why this worker announces
itself with Ready. A worker that offers a service to many clients would
actor.Register a name when it starts instead (section 4.4).
When restarts do not help, the supervisor gives up:
// Restart intensity: a child that keeps crashing makes its supervisor give
// up (exit Shutdown) after MaxRestarts restarts within PeriodMs. The
// supervisor is linked to its caller; trapping exits lets main see it.
package main
import (
"gogo/actor"
"gogo/supervisor"
)
func main() {
actor.TrapExit(true)
me := actor.Self()
sup := supervisor.Supervise(func() {
actor.Send(me, "child started")
zero := 0
println(1 / zero)
}, supervisor.Spec{Restart: supervisor.Permanent, MaxRestarts: 2, PeriodMs: 5000})
for {
switch m := actor.Receive().(type) {
case string:
println(m)
case actor.ExitMsg:
if m.From == sup {
println("supervisor gave up, code", m.Reason.Code)
return
}
}
}
}
child started
child started
child started
supervisor gave up, code 7
Standard error:
gogo: actor <pid 2> crashed: divzero in main.main.func1
gogo: actor <pid 2> crashed: divzero in main.main.func1
gogo: actor <pid 2> crashed: divzero in main.main.func1
With MaxRestarts: 2 the child ran three times (the first start and two
restarts); the third crash was one too many and the supervisor exited with
code 7, Shutdown.
Supervision trees
A supervisor’s child can itself start supervisors, giving a tree: a
top-level supervisor restarts a subsystem, whose own supervisor restarts
the workers inside it. If an inner supervisor gives up, it exits, its parent
child (linked to it) exits too, and the outer supervisor restarts the whole
subsystem. tests/golden/sup_tree in the gogo tree is a two-level example.
The current supervisor handles one child. To supervise several independent workers, give each its own supervisor; for workers that must restart together, start them from one child function and link them.
examples/sticks3_demo in the gogo tree runs this on a real M5StickS3:
pressing KEY1 makes a worker divide by zero, the supervisor restarts it, and
the demo stops when crashes come too fast.
5.7 What gets cleaned up
When an actor exits, for any reason, the VM:
- frees its heap and its mailbox;
- closes every port it owns: GPIO pins, files (committing what was written), network sockets, the keyboard and battery ports (chapter 7);
- removes its registered names, its monitors, and the timers that would
deliver to it (a
SendAfterit set up for another actor still fires); - sends exit signals to linked actors and
DownMsgto monitors.
This is why cleanup in gogo does not depend on defer: there is nothing
you could forget to release when an actor ends. gogo’s defer (section
3.4) runs on normal returns only, for actors that live on and must
release something before they continue; a crash skips it, and this
cleanup takes over.
6. Memory Model
A microcontroller has little memory: the ESP32-S3 boards give gogo about 160 KB for all actors together. How that memory is divided decides whether one misbehaving actor can bring down the rest. gogo’s answer is simple to state: every actor has its own memory with its own limit, and nothing is ever shared that could be changed.
6.1 One heap per actor
Each actor owns one block of memory holding both its heap (slices,
strings, structs, closures) and its stack. When the block fills up, the VM
collects garbage for that actor only, by copying its live data to a new
block, which can also grow or shrink the block. Other actors are not
stopped or touched. An actor waiting in Receive with little live data is
shrunk back to a small block automatically.
Because of this, a gogo actor is cheap. An idle actor (blocked in
Receive, nothing in its mailbox) costs about 150 bytes in total: a
48-byte control block, a small memory block for its stack frame, and a
4-byte slot in the actor table. Links, monitors and names are kept outside
the control block and cost nothing until used.
// Actors are cheap: an idle actor waiting in Receive costs about 150
// bytes. Spawn a thousand, measure one, then stop them all.
package main
import "gogo/actor"
type Quit struct{}
func idle() {
for {
switch actor.Receive().(type) {
case Quit:
return
}
}
}
func main() {
var pids []actor.PID
for i := 0; i < 1000; i++ {
pids = append(pids, actor.Spawn(idle))
}
actor.Sleep(10) // let them all reach Receive
m := actor.Info(pids[500]).Memory
println("1000 idle actors; one uses", m, "bytes, under 256:", m <= 256)
for _, p := range pids {
actor.Send(p, Quit{})
}
println("all asked to quit")
}
1000 idle actors; one uses 152 bytes, under 256: true
all asked to quit
actor.Info(p).Memory reports everything an actor is charged for: its
control block, its memory block, its link and monitor records, and the
messages waiting in its mailbox.
6.2 Memory limits
Every actor has a memory limit: its heap, its stack and its mailbox together. The limits are the VM’s parameters, with a default per platform:
| Limit | ESP32-S3 boards | host VM (gogo run, gogovm, libgogo) | Config key | gogovm flag |
|---|---|---|---|---|
| memory per actor (default) | 16 KB, at most 256 KB | 1 MB, at most 1 GB | vm.actor_memory | --actor-memory |
| memory for all actors | 160 KB (the arena; its ceiling) | no limit | vm.memory | --memory |
| live actors | 1024 | 16384, at most 61440 (65520 in libgogo) | vm.max_actors | --max-actors |
| open ports | 16 | 1024, at most 2048 | vm.max_ports | --max-ports |
| node links | 8 | 512, at most 2048 and the open ports | node.max_links | --max-links |
| loaded module code | 64 KB | 16 MB | code.mem | |
off-heap Bytes, VM-wide / per actor | 64 / 16, at most 1024 | 4096 / 256, at most 65535 | vm.handles | --bytes-handles |
Raising a limit. The VM reads them once, when it starts, in this
order: a gogovm flag (or, in an embedding host, a field of its
gogo_config, section 18.3) beats the config key, and the key beats the
platform default. On a board, set the key and restart it:
gogo config set vm.actor_memory 24K # every actor may now use 24 KB
gogo device info # limits actor_memory=24K memory=160K ...
On your computer, a flag for one run or the key for every run:
gogo run --actor-memory 4M myprog # or: gogovm --actor-memory 4M myprog.ggb
gogo config -local set vm.actor_memory 4M
gogovm --info # actor_memory=4M memory=unlimited ...
Sizes take a K, M or G suffix. A value past the platform’s ceiling is
cut to it, with one line on the console (gogo: vm.actor_memory 2M is over this VM's 262140; using 262140 on a board, where an actor holds at most
65535 words), and one that is not a number is ignored with a line; gogo config set refuses one that is not a number or past the most of any
platform before writing, and on a board also one past that board’s own
ceilings or that could not boot (an actor table larger than half of
vm.memory, a vm.memory under 32 KB); gogo config import to a
board checks the same before writing any key (the file’s vm.memory
and vm.max_actors together). If the keys still leave a VM
that does not fit, it says gogo: out of memory with vm.max_actors as set; starting with the defaults and starts with the defaults, so a
board stays reachable for gogo config rm. A board’s ceilings come from its
RAM: raising vm.actor_memory lets one actor take more of the 160 KB, it
does not make more. Chapter 12 lists the flags, chapter 11.3 the keys.
SpawnOpt sets a different limit for one actor, up to the ceiling, and
actor.Limit(p) reports an actor’s limit, so a program can check its
budget instead of guessing (image format 15.8):
func SpawnOpt(f func(), opts Options) PID
type Options struct{ MaxMemory int } // bytes; 0 = the platform default
An actor that needs more than its limit, even after a garbage collection,
exits with OutOfMemory. Nobody else is affected:
// Every actor has a memory limit (the platform default, or Options.
// MaxMemory with SpawnOpt). Going over it ends that actor with
// OutOfMemory; nobody else is affected. actor.Info reports usage.
package main
import "gogo/actor"
func grow() {
var xs []int
for {
xs = append(xs, len(xs))
if len(xs)%1000 == 0 {
println(" holding", len(xs), "ints, memory", actor.Info(actor.Self()).Memory >= len(xs)*4)
}
}
}
func main() {
me := actor.Self()
println("main uses", actor.Info(me).Memory, "bytes")
p := actor.SpawnOpt(func() { grow() }, actor.Options{MaxMemory: 16384})
actor.Monitor(p)
switch m := actor.Receive().(type) {
case actor.DownMsg:
println("grower exited, OutOfMemory:", m.Reason.Code == actor.OutOfMemory)
}
println("main still runs")
}
main uses 168 bytes
holding 1000 ints, memory true
holding 2000 ints, memory true
grower exited, OutOfMemory: true
main still runs
Standard error:
gogo: actor <pid 1> crashed: oom in grow
A limit smaller than the actor’s starting block is raised to fit it, and a
huge one is cut to the platform’s ceiling (256 KB on a board, 1 GB on the
host). One value is smaller still: a slice, byte slice or string holds at
most 2^26 - 1 words, 256 MB (its object header’s size field); asking for
more is OutOfMemory, whatever the actor’s limit.
Tip. Programs are usually tested with
gogo run, where the default limit is 64 times larger than on the board. An actor that works on your computer can run out of memory on the board. Give memory-hungry actors an explicitSpawnOptlimit during development, or run with all of the board’s numbers, so the host behaves like the board:gogo run --actor-memory 16K --memory 160K --max-actors 1024 --max-ports 16 --max-links 8 --bytes-handles 64/16 progAll of them: the host’s tables are sized from these parameters, and its actor table alone (16384 actors) would take most of 160 KB. The host’s records are a little larger (64-bit pointers), so a program at the very edge of the 160 KB can still differ;
build/gogovm_mcu(make test-go), the board build of the VM, is the exact model.
If the whole VM runs out of memory (all actors together are using the
160 KB, or vm.memory), the actor that is trying to allocate is ended with OutOfMemory.
The VM keeps a small emergency reserve so that it can still finish that
exit and deliver the notifications.
6.3 Messages are copied
actor.Send copies the message into the receiver’s memory: the struct, the
slices it points to, the strings, the closures, everything reachable from
it. The receiver gets an independent copy. Inside the message, sharing is
kept: if two fields refer to the same slice, the copy’s two fields refer to
the same copied slice.
// Send copies the whole message, including slices and nested structs. The
// receiver's copy keeps the sharing inside the message (two views of one
// slice stay one slice), but nothing is shared between the two actors.
package main
import "gogo/actor"
type Batch struct {
Name string
All []int
First []int // a view into All
}
func main() {
me := actor.Self()
nums := []int{1, 2, 3, 4}
b := Batch{Name: "b1", All: nums, First: nums[:2]}
w := actor.Spawn(func() {
switch m := actor.Receive().(type) {
case Batch:
m.First[0] = 99 // First and All share one array in the copy too
println("receiver:", m.All[0], m.First[0])
actor.Send(me, true)
}
})
actor.Send(w, b)
nums[1] = -2 // after the send: the receiver never sees this
actor.Receive()
println("sender:", nums[0], nums[1], b.First[1])
}
receiver: 99 99
sender: 1 -2 -2
The receiver’s write to First[0] showed up in its own All[0] (shared
inside the copy), and the sender’s later write to nums[1] did not reach
the receiver at all.
Note. This is the one place where gogo and Go mean different things by the same code. In Go, sending a slice over a channel shares the underlying array. In gogo the receiver gets a copy, always. The price is the copying; the gain is that no actor can ever see another one’s data change under it.
Some values are not copied because they cannot change: PIDs, Refs, ports,
string constants from your program (they stay in flash), and large frozen
bytes.Bytes (next section).
Closures can be sent in messages too: the function and its captured values travel together.
6.4 Mailboxes count against the receiver
A message waiting in a mailbox has already been copied, so it uses memory.
That memory is charged to the receiver. If a receiver falls behind and
its queued messages take it over its limit, the receiver exits with
MailboxOverflow. The sender is never blocked or harmed:
// Queued messages count against the RECEIVER's memory limit. A receiver
// that falls behind exits with MailboxOverflow; the sender is never
// slowed down or killed.
package main
import "gogo/actor"
type Sample struct{ N, Value int }
func main() {
slow := actor.SpawnOpt(func() {
actor.Sleep(1000) // never reads in time
}, actor.Options{MaxMemory: 4096})
actor.Monitor(slow)
for i := 0; i < 1000; i++ {
actor.Send(slow, Sample{i, i * i})
}
println("sender sent 1000 messages")
switch m := actor.Receive().(type) {
case actor.DownMsg:
println("receiver exited, MailboxOverflow:", m.Reason.Code == actor.MailboxOverflow)
}
}
sender sent 1000 messages
receiver exited, MailboxOverflow: true
Standard error:
gogo: actor <pid 1> crashed: mailbox_overflow
This rule protects the system from the most common actor bug, a fast producer feeding a slow consumer. The consumer fails, visibly, and its supervisor restarts it with an empty mailbox; the producer carries on. Messages sent to it after it exited are dropped.
Port events differ. GPIO edges are ordinary messages: an owner that never reads them overflows like any receiver. Keyboard, battery and UDP events that do not fit the owner’s limit are dropped instead (the owner is not killed), and TCP data waits until the owner has room. See chapters 7 to 10.
6.5 Bytes and Buffer: big data without copies
Copying is fine for small messages. For a 4 KB file chunk or a screen
frame it is not. gogo/bytes has two types for byte data:
bytes.Bufferis a growable, writable buffer that belongs to one actor. Make one withbytes.NewBuffer(capacity)and append withWriteString,Write,WriteByteandWriteBytes. ABufferis a reference type:b2 := brefers to the same buffer.bytes.Bytesis an immutable sequence of bytes.buf.Freeze()turns the buffer’s contents into aBytesand empties the buffer for reuse.bytes.FromStringandbytes.FromSlicecopy into one.
A Bytes larger than 64 bytes made by Freeze lives outside the actor’s
heap, with a reference count. Sending it passes a reference: no copy, no
matter the size. Since nobody can change it, sharing is safe.
// bytes.Buffer builds data; Freeze turns it into an immutable bytes.Bytes.
// A frozen Bytes over 64 bytes lives outside the actor heap and is shared,
// not copied, when sent.
package main
import (
"gogo/actor"
"gogo/bytes"
)
type Frame struct {
Seq int
Data bytes.Bytes
}
func main() {
buf := bytes.NewBuffer(256)
for i := 0; i < 200; i++ {
buf.WriteByte(byte('a' + i%26))
}
buf.WriteString("!")
frame := buf.Freeze() // buf is empty again and can be reused
println("frozen", frame.Len(), "bytes; buffer now", buf.Len())
println("first", frame.Slice(0, 5).String(), "last", frame.At(frame.Len()-1))
me := actor.Self()
sink := actor.Spawn(func() {
switch m := actor.Receive().(type) {
case Frame:
// The receiver holds the same 201 bytes, charged to it too.
println("sink got frame", m.Seq, m.Data.Len(), m.Data.Slice(26, 29).String())
actor.Send(me, actor.Info(actor.Self()).Memory > 201)
}
})
actor.Send(sink, Frame{1, frame})
println("sink charged for it:", actor.Receive())
// Small helpers: from strings and slices, compare, copy out.
a := bytes.FromString("ping")
b := bytes.FromSlice([]byte{'p', 'i', 'n', 'g'})
println(a.Equal(b), a.String())
out := make([]byte, 2)
println(a.CopyTo(out), string(out))
}
frozen 201 bytes; buffer now 0
first abcde last 33
sink got frame 1 201 abc
sink charged for it: true
true ping
2 pi
Reading a Bytes: Len(), At(i), Slice(lo, hi), String() (a copy),
Equal(other) (== is not allowed), CopyTo(p []byte). A Slice of a
large Bytes shares it (and keeps all of it alive). Out-of-range indexes
crash the actor with badcode.
The rules that keep this honest:
- Every actor that holds a shared
Bytesis charged its full size, including a receiver that has it waiting in its mailbox. Sharing saves the copy, not the accounting, so a limit still means what it says. - An actor can hold at most 16 off-heap
Bytesat a time, and the whole VM at most 64. Going over ends the actor withOutOfMemory. - A
Bytesis freed when no actor can reach it any more (at the holder’s next garbage collection or exit). A local variable keeps itsBytesalive until the end of its block, so drop a big one early by using it in an inner block or reassigning the variable. - The zero
Bufferis not usable. The compiler rejectsvar b bytes.Bufferandbytes.Buffer{}(zero value of bytes.Buffer not supported: use bytes.NewBuffer); a zeroBufferit cannot see (a field of a zero struct) crashes withbadcodewhen used. - A
Buffersent in a message is copied like other data.
The file, network and HTTP APIs all take and return bytes.Bytes.
6.6 Constants live in flash
The program image stays in flash and runs in place. String constants and other constant data are read from flash and never copied into RAM, and sending a constant string sends a reference. Package-level variables live there too (chapter 3): they are read-only, set when the program is built, so data that is the same for every actor costs no RAM, and data that changes belongs to an actor. A slice or map of one stays read-only wherever it goes, sent in a message included.
6.7 Summary
| Question | Answer |
|---|---|
| Who owns a value? | The actor whose heap it is in. Nobody else can reach it. |
What does Send do? | Copies the message into the receiver’s mailbox (except PIDs, Refs, constants and large frozen Bytes). |
| Who pays for a queued message? | The receiver. |
| What happens over the limit? | That actor exits: OutOfMemory or MailboxOverflow. |
| How do I move big data? | Build it in a Buffer, Freeze it, send the Bytes. |
| How do I free memory? | Let values go out of scope; each actor collects its own garbage. When an actor exits, all of its memory goes at once. |
7. Ports and Peripherals
A microcontroller is there to talk to hardware. In gogo, every piece of hardware an actor uses (a pin, the keyboard, the battery gauge, a file, a network socket) is a port: a special actor, implemented in C by a driver, that has a PID like any other actor.
- You open a port with
port.Open(driver, config)and become its owner. - Anyone holding the port’s PID can send it commands with
actor.Send, like any message. - The port sends events (typed messages) to its owner only.
- The port closes when its owner exits, also when the owner crashes.
So hardware fits the actor model with no new concepts: you receive button presses in the same type switch as everything else, and a crashed actor cannot leave a pin claimed forever.
7.1 The port API
package port
func Open(driver string, cfg any) (p actor.PID, err error)
func Close(p actor.PID)
func Handoff(p actor.PID, to actor.PID) (ok bool)
gogo/port holds only what every port shares: these three functions,
the stream messages (section 7.6) and the host-port types (chapter 18).
Each device’s configuration, commands and events live in a package of its
own (gogo/gpio, gogo/kbd, gogo/power, gogo/imu, …).
Open fails with an errors.Code (and p is the zero PID):
errors.NotFound if the driver is unknown or not on this board,
errors.BadArg if the configuration is invalid, errors.Busy if the
resource is already taken, errors.TooMany if the port table is full, or
errors.NoMemory if memory runs out. Close closes a port;
closing one that is already closed is ignored. actor.Kill on a port PID
also closes it.
Drivers and their configuration types:
| Driver | Config | Chapter |
|---|---|---|
"gpio" | gpio.Config | this one |
"kbd" | kbd.Config | 8 |
"power" | power.Config | 8 |
| files | fs.Open (not port.Open) | 9 |
"netif", "udp", "tcp", "tcp_listen" | net.IfConfig, net.UDP, net.Dial, net.Listen | 10 |
"tls" | net.DialTLS | 17 |
"imu" | imu.Config | 15 |
"ir_tx", "ir_rx" | ir.TX, ir.RX | 15 |
"mic", "speaker" | audio.Mic, audio.Speaker | 16 |
"screen" | screen.Config | 19 |
| ports a host program registers | port.Host | 18 |
At most 16 ports can be open at once in the whole VM on a board, 1024 in
the host VM; the config key vm.max_ports (up to 2048) changes it.
7.2 GPIO
A "gpio" port is one pin. Its types and constants are in gogo/gpio:
package gpio
type Config struct {
Pin int
Mode int // gpio.Input, InputPullUp, InputPullDown, Output
Edge int // gpio.None, Rising, Falling, Both (inputs only)
DebounceMs int // input debounce; <= 0 means the default, 20 ms
}
type Write struct{ Value int } // command: drive an output to 0 or 1
type Edge struct{ Pin, Value int } // event: the level changed; Value is the new level
Output
Open the pin with Mode: gpio.Output and send it gpio.Write commands:
// Drive an output pin: blink an LED three times. On the host a Write
// prints "gpio: pin N = V" on stderr instead of touching hardware.
package main
import (
"gogo/actor"
"gogo/gpio"
"gogo/port"
)
const ledPin = 5
func main() {
led, err := port.Open("gpio", gpio.Config{Pin: ledPin, Mode: gpio.Output})
if err != nil {
println("cannot open the LED pin")
return
}
for i := 0; i < 3; i++ {
actor.Send(led, gpio.Write{Value: 1})
actor.Sleep(100)
actor.Send(led, gpio.Write{Value: 0})
actor.Sleep(100)
}
port.Close(led)
println("blinked 3 times")
}
On the host there is no LED, so the simulated driver reports each write on standard error:
gpio: pin 5 = 1
gpio: pin 5 = 0
gpio: pin 5 = 1
gpio: pin 5 = 0
gpio: pin 5 = 1
gpio: pin 5 = 0
Standard output:
blinked 3 times
Input and edges
An input pin reports level changes as gpio.Edge events, filtered by
Edge: Rising (0 to 1), Falling (1 to 0) or Both. The buttons on the
M5StickS3 (KEY1 on G11, KEY2 on G12) connect the pin to ground when
pressed, so they are opened with InputPullUp and Falling: one event per
press.
// Count button presses. KEY1 on the M5StickS3 is G11, active low: open it
// with a pull-up and ask for falling edges. Each press arrives as a
// gpio.Edge message. On the host the presses come from the stdin script
// in the file "input" ("11 0" = pin 11 goes low).
package main
import (
"gogo/actor"
"gogo/gpio"
"gogo/port"
)
const key1 = 11
func main() {
_, err := port.Open("gpio", gpio.Config{Pin: key1, Mode: gpio.InputPullUp, Edge: gpio.Falling})
if err != nil {
println("cannot open KEY1")
return
}
presses := 0
for presses < 3 {
switch e := actor.Receive().(type) {
case gpio.Edge:
presses++
println("press", presses, "pin", e.Pin, "level", e.Value)
}
}
println("three presses, bye")
}
On the host, input comes from standard input. This example’s input file:
11 0
11 1
sleep 50
11 0
11 1
11 0
11 1
Run it with the script on standard input:
$ gogo run docs/book/examples/07-button < docs/book/examples/07-button/input
press 1 pin 11 level 0
press 2 pin 11 level 0
press 3 pin 11 level 0
three presses, bye
The script lines for GPIO are <pin> <level> and sleep <ms>. The VM
reads one line each time it has nothing else to do, so the output depends
only on the order of events, not on timing. After the end of the script
no more input can arrive, and the VM exits once the program is idle.
You can also drive pins from the keyboard: in a terminal, gogo run --key a=11 --key s=12 <dir> turns a key press of a into a press of pin 11 (the
level goes to 0 and back to 1). End the input with Ctrl-D, or stop the
program with Ctrl-C.
Debouncing
A mechanical button does not switch cleanly: one press can bounce between
0 and 1 several times within a few milliseconds. The GPIO driver treats an
edge that comes less than DebounceMs milliseconds (20 ms by default)
after the previous level change as bounce and drops it; on a single-edge
pin (Rising or Falling) this is what removes the bounce of a key
release. Set DebounceMs higher for noisy switches. In the host’s script
mode debouncing is off, so scripts are exact; in the host’s terminal mode
(--key) it is on.
Which pins
Pins the board itself uses cannot be opened: on the M5StickS3 the USB
pins, the flash and PSRAM, the LCD and the power-management I2C bus; on
the Cardputer ADV the USB pins, flash, LCD, SD card, keyboard I2C bus and
interrupt and the battery ADC. platform/esp32s3/README.md lists them.
Free ones include KEY1 (G11) and KEY2 (G12) on the StickS3 and the G0
button on the Cardputer ADV (active low).
7.3 Owners, commands and events
Commands can come from any actor that has the PID. You can hand an
LED’s PID to several actors and let each of them Send it gpio.Writes.
Events go only to the owner, as ordinary messages in its mailbox, and
count against its memory limit like any message. An owner that does not
read its events will eventually exit with MailboxOverflow.
You cannot link to or monitor a port; a SendAfter to a port is ignored,
and a Call to one fails at once with errors.NoProc.
Ports close with their owner
// A port belongs to the actor that opened it, and closes when that actor
// exits, also when it crashes. So a restarted worker can open the same pin
// again: no leaked handles, no cleanup code.
package main
import (
"gogo/actor"
"gogo/gpio"
"gogo/port"
)
func worker(boss actor.PID, crash bool) {
_, err := port.Open("gpio", gpio.Config{Pin: 5, Mode: gpio.Output})
actor.Send(boss, err == nil)
if crash {
zero := 0
println(1 / zero)
}
}
func main() {
me := actor.Self()
actor.Spawn(func() { worker(me, true) })
println("first worker opened pin 5:", actor.Receive())
actor.Sleep(10)
actor.Spawn(func() { worker(me, false) })
println("second worker opened pin 5:", actor.Receive())
// While someone owns it, nobody else can open it.
_, err := port.Open("gpio", gpio.Config{Pin: 7, Mode: gpio.Output})
_, again := port.Open("gpio", gpio.Config{Pin: 7, Mode: gpio.Output})
println("pin 7 first open:", err == nil, "second open:", again == nil)
}
first worker opened pin 5: true
second worker opened pin 5: true
pin 7 first open: true second open: false
Standard error:
gogo: actor <pid 1> crashed: divzero in worker
The first worker crashed while holding pin 5, and the VM closed the pin for it, so the second worker could open it. This is what makes supervisor restarts work with hardware: the restarted actor opens its pins again from scratch. When the VM itself exits, it closes every port still open.
7.4 Handoff
Sometimes the actor that opens a port is not the one that should handle
its events. A web server’s listener accepts connections and hands each to a
new actor; a setup actor opens the buttons and hands them to the UI actor.
port.Handoff(p, to) makes to the owner:
// A port's events go to its owner. port.Handoff gives the port to another
// actor: main opens the button and hands it to a dedicated key handler.
package main
import (
"gogo/actor"
"gogo/gpio"
"gogo/port"
)
func keyHandler(boss actor.PID) {
n := 0
for n < 2 {
switch e := actor.Receive().(type) {
case gpio.Edge:
n++
println("handler: edge on pin", e.Pin)
}
}
actor.Send(boss, "handler done")
}
func main() {
btn, err := port.Open("gpio", gpio.Config{Pin: 12, Mode: gpio.InputPullUp, Edge: gpio.Falling})
println("open", err == nil)
me := actor.Self()
h := actor.Spawn(func() { keyHandler(me) })
println("handoff", port.Handoff(btn, h))
println("handoff again (main is no longer the owner)", port.Handoff(btn, me))
println(actor.Receive())
}
input:
12 0
12 1
12 0
12 1
open true
handoff true
handoff again (main is no longer the owner) false
handler: edge on pin 12
handler: edge on pin 12
handler done
After a handoff, later events go to the new owner, the port closes when
it exits, and the memory charged for the port moves to it. Only the
current owner can hand a port off. Handoff returns false, and nothing
changes, if the caller is not the owner, the port is closed, to is not a
live actor, or to cannot take the port’s memory charge within its limit.
7.5 Peripherals that are not ports
On the boards, everything a program prints (standard output in white,
standard error in red) appears on the LCD as a scrolling text console,
with Chinese characters supported. The console itself is not a port; the
"screen" port (chapter 19) takes the LCD over as a grid of character
cells while it is open, and gives it back to the console when it closes.
uart, i2c and spi ports are planned.
7.6 How ports work inside
You never need this section to use ports, but it explains why they behave the way the earlier sections describe: why a slow actor cannot stall a driver, why a crash frees everything, and why every peripheral looks the same.
owner actor VM (scheduler thread) hardware / host
┌──────────────────┐ port.Open(name,cfg) ┌───────────────────────────────┐
│ │ ───────────────────► │ find driver by name │
│ p := PID │ ◄─────────────────── │ board drivers, host ports │
│ │ (PID, err) │ charge memory to the owner │
│ │ │ port table: slot + generation │
│ actor.Send(p,cmd)│ ───────────────────► │ driver command │ ──► registers,
│ │ │ │ frames, DMA
│ │ │ ┌─────────────────────────┐ │
│ receive event ◄─┼── mailbox (quota) ◄──┼──│ event delivery │◄─┼─┐
│ (typed struct) │ │ │ driver hook (debounce) │ │ │
└──────────────────┘ │ └─────────────────────────┘ │ │
│ ▲ ▲ │ │
│ │ drain │ drain │ │
│ ┌────┴──────┐ ┌──────┴─────┐ │ │
│ │ event ring│ │ source │ │ │
│ │ (SPSC) │ │ pending │ │ │
│ └────▲──────┘ │ deadline │ │ │
└──────┼─────────┴──────▲─────┴─┘ │
│ interrupt │ poll │
gpio, kbd INT net RX, IMU FIFO,
audio DMA, TLS
Opening. port.Open looks the driver up by name: first the board’s
drivers, then any ports the host program registered (chapter 18). The
memory a port needs is charged to the caller; if the caller’s limit cannot
hold the port’s state plus one event, Open fails at once (errors.NoMemory)
rather than opening a port whose events would all be dropped. Each VM has
a table of 16 port slots. A port’s PID is its slot number plus a
generation, so a PID kept after its port closed never reaches a later port
in the same slot.
Drivers. Each kind of peripheral is a C driver with a small set of callbacks: open, command, close, and a few helpers for handoff and backpressure. A driver turns commands into hardware actions and hardware state into events. It never runs actors or allocates in their heaps.
One driver, many boards. The drivers for GPIO, the keyboard, the
battery, the motion sensor, infrared and audio are written once, in the
runtime. A board does not copy them: it describes its hardware in a small
table of functions (for GPIO: how many pins, which ones it keeps for
itself, and how to configure, write, read and release a pin; for the
keyboard: its key table and how to read the chip), and lists a driver
instance that points at that table. So the rules you met in 7.2 (which
pins are refused, the bounce filter, the 20 ms default) behave the same
on every board, and the simulator runs the very code the device does. The
file systems work the same way: LittleFS and FatFs run over a board’s
block device or SD card, and the board’s table of mounts says which
prefixes (/flash, /sd) it serves.
Two ways in for events. A driver that is told about hardware by an interrupt (a GPIO edge, the keyboard’s INT line) pushes a small record into an event ring from the interrupt handler and wakes the VM; the ring has exactly one writer and one reader, so the handler never takes a lock and never calls into the VM. A driver that has to look at hardware (the network’s received frames, the IMU’s FIFO, audio DMA buffers, a TLS handshake step) is an event source with three questions the scheduler asks: is there work now, do the work, and when is the next time there might be. The scheduler never sleeps while a source has work due, and work that only depends on time waits for its deadline instead of spinning.
Delivery and backpressure. Events are typed structs (kbd.Key,
imu.Gesture, port.Chunk, …) delivered to the owner’s mailbox under
its mailbox quota. When the owner falls behind, a driver drops or merges
events and counts what it dropped (a debounced pin keeps only its latest
level; a Chunk reports Dropped), so a slow actor costs itself data but
never stalls the driver or other actors.
Streams. Every port that moves bytes speaks one protocol, four
messages in gogo/port:
type Chunk struct { // event: the next block of input
From actor.PID
Seq, TimeMs, Dropped int
Data bytes.Bytes
}
type Out struct{ Data bytes.Bytes } // command: send Data
type Done struct{ From actor.PID; Seq int } // event: an Out finished
type Closed struct{ From actor.PID; Reason int } // event: the port ended by itself
- Writes are
Out{Data}messages, each answered withDone{Seq}when it has been sent or played. At most two may be in flight; a third is answered at once withDone{-1}, and the port carries on.Seqcounts the Outs that went out, from 1;-1means this one did not (refused, bad data, or the hardware or connection failed before it went out). - A
Donethe owner has no mailbox room for is owed and delivered later, in order; an Out whose Done is still owed keeps its place among the two in flight. Every accepted Out gets exactly one Done, in the Outs’ order; a refusal is answered at once, so itsDone{-1}may come before the Dones of Outs still in flight. Count Dones;Seqnumbers only the Outs that went out. - Input arrives as
Chunk{Seq, TimeMs, Dropped, Data}. A gap inSeqmeans chunks were lost, andDroppedsays how many; a port that loses nothing (TCP and TLS make the peer resend instead) always says 0. Closed{Reason}says the port ended by itself: the peer closed or reset a connection, a timeout, a failure. TCP and TLS send it (chapter 10); their reasons are thenetconstants, which are shared codes fromgogo/errors(net.Timeoutiserrors.Timeout). A host port sends it when the program embedding the VM ends the port (chapter 18), with whatever shared code that program gives. After aClosedother thanNormalthe port does nothing more: close it.- Every event carries
From, the port’s PID, so one actor can own several stream ports and still tell their events apart.
TCP and TLS (chapters 10 and 17), IR (chapter 15), the microphone and the
speaker (chapter 16) all use it. The "screen" port (chapter 19) takes
Outs and answers with Dones too, with one difference: it draws each
Out at once, so none waits in flight; a Done its owner has no room for
is owed (up to 8, retried until delivered), and an Out arriving with 8
owed is not drawn and gets Done{-1}.
Shapes. The messages of every port follow the same conventions, so a
new port reads like the old ones: the config type is named for its driver
("speaker" takes audio.Speaker); commands are imperative nouns (Out,
Write, Read); events are past participles or nouns (Done, Chunk,
Closed, Key); every acknowledgement is a Done and every terminal
event a Closed; quantities carry their unit (RateHz, VolumePct,
TimeoutMs).
Ownership. A port belongs to the actor that opened it until it is handed off (section 7.4). When the owner exits or crashes, the VM closes every port it owns and frees what they hold, which is why gogo programs need no cleanup code for hardware.
Requirements. The compiler records which drivers a program opens by a
constant name, and an image that needs a driver the firmware lacks is
refused when it is loaded, not halfway through running. A library can
mark a driver it can live without with //gogo:optional (chapter 12); its
Open then simply fails on boards without that hardware.
8. Keyboard and Power
Two more ports give programs the keyboard and the battery: "kbd" (package
gogo/kbd) and "power" (package gogo/power). They work like the GPIO
port of the last chapter: open them with port.Open, receive typed events
in your type switch, and they close when your actor exits.
Both are the same on every board and on the host. A board without the
hardware simply refuses to open the port (errors.NotFound): the M5StickS3
has no keyboard, so port.Open("kbd", ...) fails there. Write programs
that check the error and carry on with what the board has.
Each of these ports has one owner at a time in the whole VM; a second
Open fails while the first is open. If several actors need key presses,
have the owner forward them.
8.1 The keyboard
package kbd
type Config struct{ RepeatDelayMs, RepeatMs int }
type Key struct {
Code, Char, Mods int
Down bool
}
Open the port with port.Open("kbd", kbd.Config{RepeatDelayMs: 400, RepeatMs: 60}). RepeatDelayMs is how long a key must be held before it
repeats (0 turns repeat off); RepeatMs is the interval between repeats
(0 or less means 50).
Every press, repeat and release is a kbd.Key message:
Codesays which key: its USB HID usage code, the same on every board. Letters are 0x04 to 0x1D, digits 0x1E to 0x27; the package has constants for the rest:kbd.Enter,Esc,Backspace,Tab,Space,Delete,Up,Down,Left,Right,F1toF12, and the modifier keysLeftCtrl,LeftShift,LeftAlt,OptandFn(0xF0, which has no HID code).Charis the ASCII character the key types with the current modifiers (US layout), or 0. Shift gives the shifted character; Ctrl with a letter gives a control character (Ctrl-C is 3); Enter is 10, Tab 9, Backspace 8, Esc 27, Delete 127.Modsis a bit set of the modifiers held:kbd.ModCtrl,ModShift,ModAlt,ModOpt,ModFn.Downis true for a press or a repeat, false for a release.
The Cardputer’s keyboard is small, so the Fn key gives a second layer:
with Fn held, ; is Up, . is Down, , is Left, / is Right and `
is Esc, Backspace is Delete, the digit keys 1 to 0 are F1 to F10, and
- and = are F11 and F12. The event then carries the Fn
layer’s Code and Char. A key without an Fn meaning reports its normal
code, with ModFn set. A release always carries the same Code as its
press, even if you let go of Fn first, so keys never get stuck.
Modifier keys produce their own Key events too (with Char 0). Only the
last non-modifier key held repeats. There is no Caps Lock.
Here is a small line editor:
// A line editor on the Cardputer keyboard: type characters, Backspace
// deletes, Enter prints the line, Esc quits. On the host the keys come
// from the stdin script in "input".
package main
import (
"gogo/actor"
"gogo/kbd"
"gogo/port"
)
// printable holds ASCII 32..126, so character c is printable[c-32 : c-31]
// (string([]byte{byte(c)}) works too, but allocates a slice per key).
const printable = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
func main() {
_, err := port.Open("kbd", kbd.Config{RepeatDelayMs: 400, RepeatMs: 60})
if err != nil {
println("no keyboard on this board")
return
}
line := ""
for {
switch k := actor.Receive().(type) {
case kbd.Key:
if !k.Down {
continue // ignore releases
}
if k.Code == kbd.Esc {
println("bye")
return
} else if k.Code == kbd.Enter {
println("line:", line)
line = ""
} else if k.Code == kbd.Backspace {
if len(line) > 0 {
line = line[:len(line)-1]
}
} else if k.Mods&kbd.ModCtrl != 0 && k.Char == 3 {
println("^C: line cleared")
line = ""
} else if k.Char >= 32 && k.Char <= 126 {
line = line + printable[k.Char-32:k.Char-31]
}
}
}
}
On the host the keys come from a script on standard input, with lines
key <name> (press and release), keydown <name> and keyup <name>:
key h
key i
key space
keydown shift
key g
keyup shift
key o
key x
key backspace
key enter
key a
key b
keydown ctrl
key c
keyup ctrl
key o
key k
key 1
key enter
key esc
line: hi Go
^C: line cleared
line: ok1
bye
Key names in scripts are a-z, 0-9, enter, esc, backspace,
tab, space, delete, up, down, left, right, f1-f12,
ctrl, shift, alt, opt, fn and the punctuation characters - = [ ] \ ; ' , . /. Run gogo run` in a terminal without a script and your
computer’s keyboard becomes the Cardputer’s keyboard: printable characters,
Enter, Backspace, Tab, Esc and the arrow keys are passed through.
examples/kbddemo in the gogo tree prints every event with its name and
modifiers; it is a handy way to see what each key sends.
A key event that would take the owner over its memory limit is dropped; the owner is not killed. A key held when the port opens never got a press event, so you may see a release without a press; ignore it.
Note. The keyboard and battery have been checked on both boards (every key, the Fn layer, modifiers, fast typing, battery and charging readings). Auto-repeat has not been exercised on a board yet, and the Cardputer’s battery reading has not been compared with the vendor firmware’s; see
docs/known-issues.md.
8.2 The battery
package power
type Config struct{ PeriodMs int }
type Battery struct{ MilliVolts, Pct, Charging, External int }
type Read struct{}
Open with port.Open("power", power.Config{PeriodMs: 5000}). PeriodMs
is how often the board samples the battery chip (0 or less means 10000,
the minimum is 1000). The owner receives a power.Battery:
- once when the port opens (the first good sample);
- after every
power.Read{}command you send to the port; - at once when
ChargingorExternalchanges; - when
Pcthas moved by 2 or more since the last one sent.
Nothing is sent while nothing changes; there is no heartbeat.
The fields:
MilliVolts: the cell voltage, as the average of the last 4 samples.Pct: 0 to 100, computed linearly fromMilliVolts: 3300 mV or less is 0 %, 4100 mV or more is 100 %.Charging,External: 1 (yes), 0 (no) or -1 (the board cannot tell). On the M5StickS3 both are read from its power chip. The Cardputer ADV cannot see either and always reports -1.
// Watch the battery. The power port sends a Battery message when it opens,
// on every Read, when charging or external power changes, and when the
// charge moves by 2 % or more. On the host the samples come from the
// "battery <mV> <charging> <external>" lines of the stdin script.
package main
import (
"gogo/actor"
"gogo/port"
"gogo/power"
)
func main() {
p, err := port.Open("power", power.Config{PeriodMs: 5000})
if err != nil {
println("no battery monitor on this board")
return
}
actor.Send(p, power.Read{}) // ask for a reading now
n := 0
for n < 3 {
switch b := actor.Receive().(type) {
case power.Battery:
n++
state := "on battery"
if b.External == 1 {
state = "on external power"
} else if b.External < 0 {
state = "power source unknown"
}
if b.Charging == 1 {
state = state + ", charging"
}
println(b.MilliVolts, "mV", b.Pct, "%", state)
if b.Pct < 20 && b.External != 1 {
println(" low battery!")
}
}
}
}
The host’s battery is simulated with battery <mV> <charging> <external>
lines:
battery 4100 1 1
battery 4095 1 1
battery 4000 0 0
battery 3550 0 0
4100 mV 100 % on external power, charging
4073 mV 96 % on battery
3936 mV 79 % on battery
Follow the numbers to see the rules at work. The first line arrived with
the Read (4100 mV, 100 %). The second line (4095 mV) moved the average
by too little to report. The third changed Charging and External, so
it was reported at once, and its voltage is the average of the samples so
far, 4073 mV, not 4000. The fourth moved the percentage enough to be
reported, again averaged.
Note. The package documentation calls
MilliVolts“the cell voltage”, but it is a moving average of the last 4 samples (seeruntime/input/power.c). After a sudden change it takes 4 samples to settle.
There is no power-button event: the StickS3’s power chip handles its button by itself (click to restart, double click to power off).
9. Storage
gogo gives programs a small file system API, gogo/fs, over two media:
/flash: part of the board’s internal flash (about 5 MB, LittleFS). Every board has it. It survives reboots and reflashing of firmware or program./sd: the SD card, on boards with a slot (the Cardputer ADV). FAT12, FAT16, FAT32 and exFAT cards work. The card is mounted on first use; a card inserted later works from the next call on.
On top of gogo/fs there are two small libraries: gogo/kv, a key-value
store, and gogo/ringlog, a size-bounded log.
On your computer, storage is a directory: gogo run --fs-root DIR maps
/flash to DIR/flash (created if needed) and /sd to DIR/sd (only if
that directory exists). Without --fs-root there is no storage at all and
every call fails with NotMounted. Programs stay inside those
directories: a symlink in them is not followed (it is listed as a file,
and opening it is BadPath). The examples in this chapter are run that
way.
9.1 Paths
Paths are absolute and start with /flash or /sd. The rules are strict,
so that a path means the same thing on both media and on your computer:
- a name is 1 to 32 bytes of
A-Z a-z 0-9 . _ -; - a whole path is at most 96 bytes;
- no empty segments (
/flash//a), no trailing/, and no name ending in.(so no.or..).
Anything else is fs.BadPath. Prefer lower-case names: /sd is FAT and
ignores case (A.TXT is a.txt), while /flash does not. A name made on a
PC that breaks the rules is still listed by ReadDir, but cannot be opened.
Where the media are
| Path | On a board | gogo run / gogovm on a computer | A program that embeds gogo (chapter 18) |
|---|---|---|---|
/flash | the board’s flash (LittleFS) | DIR/flash with --fs-root DIR (created if missing); without it, every call is NotMounted | the host’s fs_root directory; without it, NotMounted |
/sd | the SD card (FAT), when one is inserted (Cardputer ADV) | DIR/sd, only if that directory exists | never mounted |
anything else (/, /tmp, /data, …) | BadPath | BadPath | BadPath |
On a computer a program stays inside those directories: symlinks, FIFOs
and devices in them are not followed (BadPath), a file with other hard
links cannot be opened for writing, and on a file system that ignores case
(macOS by default) /flash ignores case too.
Reserved names
The file system itself reserves no names beyond the rules above, but these
libraries and tools use names of their own. Keep your files out of their
way: put a program’s data in a directory of its own (/flash/myapp/...).
| Name | Used by | What happens |
|---|---|---|
<name>.tmp | fs.WriteFile | the new content is written to <name>.tmp beside the file, then renamed over it (section 9.3). Do not keep data in names ending in .tmp: a WriteFile of the same base name replaces it, and on /sd a power cut can leave one behind |
/flash/kv/ | gogo/kv (section 9.5) | one file per key. Keys may not end in .tmp; any other file put there shows up in kv.Keys() |
0.log, 1.log | gogo/ringlog (section 9.6) | the two halves of a log, in the directory you pass to ringlog.Append and ringlog.Read |
.gogo-push | gogo push (chapter 12) | the upload is written to this name in the target directory, checked, then renamed; an interrupted push can leave it |
/flash/<name>.ggb | gogo push | where an image goes by default; code.Load loads images from any path (chapter 14) |
9.2 Errors
Every call returns an fs.Err; fs.OK (0) means success. Storage errors
never crash the caller. fs.Err is another name for errors.Code, the
shared codes of gogo/errors (appendix C): fs.NotFound is
errors.NotFound, the code gogo/code and the other packages use for it,
and an fs.Err is an error too (e.Error() is "not found").
| Value | Name | Meaning |
|---|---|---|
| 0 | OK | success |
| 1 | NotFound | no such file or directory |
| 2 | Exists | the target of Mkdir or Rename exists |
| 3 | NoMemory | the result does not fit the caller’s memory limit (it is not killed) |
| 4 | TooMany | 4 files are open already |
| 5 | Busy | the path is in use (see 9.4) |
| 7 | Closed | the file is closed, or not owned by the caller |
| 8 | IO | a medium error (card removed, …) |
| 11 | NoSpace | the medium is full |
| 12 | BadPath | the path breaks the rules |
| 13 | IsDir | a file operation on a directory |
| 14 | NotDir | a segment before the last is not a directory (/sd says NotFound) |
| 15 | NotEmpty | Remove of a directory with entries |
| 16 | NotMounted | unknown prefix, or /sd has no working card |
// Storage errors are values, never crashes: every call returns an fs.Err.
// And a File is a port: it closes when its owner exits, even by a crash.
package main
import (
"gogo/actor"
"gogo/fs"
)
func main() {
_, e := fs.ReadFile("/flash/missing.txt", 100)
println("missing file:", int(e), e == fs.NotFound)
println("bad name:", int(fs.WriteFile("/flash/bad name.txt", "x")))
println("relative path:", int(fs.WriteFile("notes.txt", "x")))
println("no such mount:", int(fs.WriteFile("/usb/a.txt", "x")))
println("no card (/sd):", int(fs.WriteFile("/sd/a.txt", "x")))
fs.Mkdir("/flash/d")
fs.WriteFile("/flash/d/a", "x")
println("remove non-empty dir:", int(fs.Remove("/flash/d")))
// Too big for the caller's quota: NoMemory, and nothing is read.
_, e = fs.ReadFile("/flash/d/a", 0)
println("max 0:", int(e))
// A writer that crashes still closes (and commits) its file.
me := actor.Self()
w := actor.Spawn(func() {
f, _ := fs.Open("/flash/crash.txt", fs.Write)
f.Write("written before the crash\n")
actor.Send(me, "wrote")
actor.Receive()
zero := 0
println(1 / zero)
})
println(actor.Receive())
// While the writer holds the file open, removing it is Busy.
println("remove while open:", int(fs.Remove("/flash/crash.txt")))
ref := actor.Monitor(w)
actor.Send(w, "crash now")
switch m := actor.Receive().(type) {
case actor.DownMsg:
println("writer down:", m.Ref == ref)
}
b, e := fs.ReadFile("/flash/crash.txt", 100)
println("after the crash:", int(e), b.Len(), "bytes")
println("remove now:", int(fs.Remove("/flash/crash.txt")))
}
missing file: 1 true
bad name: 12
relative path: 12
no such mount: 16
no card (/sd): 16
remove non-empty dir: 15
max 0: 3
wrote
remove while open: 5
writer down: true
after the crash: 0 25 bytes
remove now: 0
Standard error:
gogo: actor <pid 1> crashed: divzero in main.main.func1
9.3 Reading and writing files
The simplest calls work on whole files:
func ReadFile(path string, max int) (bytes.Bytes, Err) // NoMemory if larger than max
func WriteFile(path string, data any) Err // string, bytes.Bytes or []byte
WriteFile replaces the file: it writes <name>.tmp first and then
renames it over the old file, so on /flash a power loss leaves either the
old or the new content. (On /sd the replacement is not atomic: a power
loss at the wrong moment leaves <name>.tmp.)
For more control, open a file:
func Open(path string, mode int) (File, Err) // fs.Read, fs.Write (create or truncate), fs.Append
func (f File) Read(max int) (bytes.Bytes, Err) // at most 4096 bytes; empty with OK = end of file
func (f File) Write(data any) Err // string, bytes.Bytes or []byte
func (f File) WriteAt(off int, data any) Err // overwrite inside a Write-mode file, never extends it
func (f File) Sync() Err // commit without closing
func (f File) Size() (int, Err)
func (f File) Close()
and for directories and the rest:
func Stat(path string) (Info, Err) // Info{Size int; IsDir bool}
func ReadDir(path string) ([]string, Err) // directories end in "/", order not defined
func Mkdir(path string) Err // one level, not recursive
func Remove(path string) Err // a file or an empty directory
func Rename(from, to string) Err // within one medium
func Usage(prefix string) (Space, Err) // Space{Used, Total int}, "/flash" or "/sd"
// Files on /flash: whole-file helpers, an open File, directories.
// Run on the host with: gogo run --fs-root /tmp/somedir .
package main
import (
"gogo/bytes"
"gogo/fs"
)
func check(what string, e fs.Err) {
if e != fs.OK {
println(what, "failed, error", int(e))
}
}
func main() {
// WriteFile replaces the whole file (atomically on /flash).
check("write", fs.WriteFile("/flash/hello.txt", "hello, flash\n"))
b, e := fs.ReadFile("/flash/hello.txt", 1024)
check("read", e)
print1("hello.txt:", b)
// An open File: write in pieces, then read back in chunks.
check("mkdir", fs.Mkdir("/flash/data"))
f, e := fs.Open("/flash/data/log.txt", fs.Write)
check("open", e)
for i := 0; i < 3; i++ {
check("write", f.Write("line "+string([]byte{byte('1' + i)})+"\n"))
}
n, _ := f.Size()
println("written", n, "bytes")
f.Close()
f, e = fs.Open("/flash/data/log.txt", fs.Append)
check("append", e)
f.Write(bytes.FromString("line 4\n"))
f.Close()
f, _ = fs.Open("/flash/data/log.txt", fs.Read)
for {
chunk, e := f.Read(10) // at most 10 bytes per call
if e != fs.OK || chunk.Len() == 0 {
break // an empty chunk with OK is the end of the file
}
println("chunk of", chunk.Len(), "bytes")
}
f.Close()
all, _ := fs.ReadFile("/flash/data/log.txt", 1024)
print1("log.txt:", all)
info, _ := fs.Stat("/flash/data/log.txt")
println("size", info.Size, "dir?", info.IsDir)
names, _ := fs.ReadDir("/flash")
println("entries in /flash:", len(names)) // order is not defined
check("rename", fs.Rename("/flash/hello.txt", "/flash/data/hello.txt"))
check("remove", fs.Remove("/flash/data/hello.txt"))
_, e = fs.Stat("/flash/data/hello.txt")
println("after remove, NotFound:", e == fs.NotFound)
}
// print1 prints a Bytes as text without its trailing newline.
func print1(label string, b bytes.Bytes) {
s := b.String()
if len(s) > 0 && s[len(s)-1] == '\n' {
s = s[:len(s)-1]
}
println(label, "["+s+"]")
}
hello.txt: [hello, flash]
written 21 bytes
chunk of 10 bytes
chunk of 10 bytes
chunk of 8 bytes
log.txt: [line 1
line 2
line 3
line 4]
size 28 dir? false
entries in /flash: 2
after remove, NotFound: true
A File is a port
fs.File is the PID of a file port, so files follow the port rules of
chapter 7: the actor that opened the file owns it, and the file is closed
(and what was written is committed) when the owner exits, even by a crash,
as 09-fs-errors above showed. Only the owner can read, write, sync or
size it; anyone else gets Closed. port.Handoff(actor.PID(f), other)
gives a file to another actor.
Close has no result, so it cannot report a failed commit. If you need to
know that the data reached the medium, call Sync before Close.
A file opened for writing cannot be read and vice versa (Closed).
WriteAt(off, data) overwrites bytes that are already in a file opened with
fs.Write, for fixing up what was written (a length field in a header, as
gogo/wav does). It never extends the file: off + len(data) must be at
most Size, else the result is BadPath and nothing is written. A file
opened Read or Append gives Closed. It does not move the position
of the next Write, which still appends at the end. On /sd it needs no
free space, so it works on a full card; on /flash it needs a free block.
Note.
fs.Filecannot be a case in a type switch (type switch case fs.File not supported; wrap it in a struct), because at run time it is indistinguishable from anactor.PID. To send a file to another actor, put it in a struct field.
9.4 Limits and rules
- At most 4 files are open at once in the whole VM (
TooMany).ReadFile,WriteFileand thekvcalls use one of those 4 slots while they run. - One writer per path. A second
WriteorAppendopen of the same path isBusy. While any file is open on a path,Remove,Renameand the final step ofWriteFileon it areBusytoo. Readers can open a file that is being written, but what they see of unclosed data is not guaranteed. - Renaming a directory while any file is open on the same medium is
Busy. Renaming into its own subtree (/flash/dto/flash/d/x) and across media areBadPath. Renaming onto an existing name isExists. - Operations on
/, andMkdir,RemoveorRenameof/flashor/sdthemselves, areBadPath. - Sizes are reported up to 2 GB - 1; larger files or cards read as that.
- Every storage call is synchronous and stops all actors while it runs. Erasing flash takes tens of milliseconds, and an SD card occasionally hundreds. Write in large pieces, and keep storage out of actors that must react quickly.
Copying between media takes a read and a write, since Rename cannot
cross them:
// /sd works like /flash, on boards with a card slot (the Cardputer ADV).
// Copy a file from /flash to /sd: Rename cannot cross mounts, so read and
// write. On the host, --fs-root DIR gives /sd only if DIR/sd exists.
package main
import "gogo/fs"
func copyFile(from, to string) fs.Err {
b, e := fs.ReadFile(from, 4096)
if e != fs.OK {
return e
}
return fs.WriteFile(to, b)
}
func main() {
fs.WriteFile("/flash/settings.txt", "volume=3\n")
println("rename across mounts:", int(fs.Rename("/flash/settings.txt", "/sd/settings.txt")) == int(fs.BadPath))
e := copyFile("/flash/settings.txt", "/sd/settings.txt")
if e == fs.NotMounted {
println("no SD card")
return
}
b, _ := fs.ReadFile("/sd/settings.txt", 100)
println("copied:", b.Len(), "bytes")
sp, e := fs.Usage("/sd")
println("usage ok:", e == fs.OK, sp.Total > 0, sp.Used <= sp.Total)
}
With --fs-root on a directory that has an sd subdirectory:
rename across mounts: true
copied: 9 bytes
usage ok: true true true
On a board without a card the program prints no SD card.
9.5 gogo/kv: a key-value store
gogo/kv stores small values under names, one file per key in
/flash/kv/:
func Get(key string) (bytes.Bytes, fs.Err) // fs.NotFound if there is none
func Put(key string, v any) fs.Err // a string or a bytes.Bytes, at most 4096 bytes
func Delete(key string) fs.Err
func Keys() ([]string, fs.Err)
A key follows the file name rules (and must not end in .tmp); a bad
key is fs.BadPath. Put replaces the value atomically. A value over
4096 bytes is the shared code errors.Overflow and a value of another
type errors.BadArg (compare with errors.Overflow). A []byte must
go through
bytes.FromSlice first.
The classic use is a boot counter:
// A boot counter in gogo/kv: read, increment, store. Each run of the
// program (each boot, on a board) adds one. The example counts three
// "boots" in one run by calling boot three times.
package main
import (
"gogo/fs"
"gogo/kv"
"gogo/strconv"
)
func boot() int {
n := 0
v, e := kv.Get("boots")
if e == fs.OK {
n, _ = strconv.Atoi(v.String())
} else if e != fs.NotFound {
println("cannot read the counter, error", int(e))
return -1
}
n++
if e := kv.Put("boots", strconv.Itoa(n)); e != fs.OK {
println("cannot store the counter, error", int(e))
}
return n
}
func main() {
for i := 0; i < 3; i++ {
println("boot number", boot())
}
kv.Put("owner", "dev board 7")
keys, _ := kv.Keys()
println("keys stored:", len(keys))
v, _ := kv.Get("owner")
println("owner:", v.String())
println("delete:", int(kv.Delete("owner")), "again:", int(kv.Delete("owner")))
println("bad key:", kv.Put("a/b", "x") == fs.BadPath)
}
boot number 1
boot number 2
boot number 3
keys stored: 2
owner: dev board 7
delete: 0 again: 1
bad key: true
Only fs.NotFound means “no such key”. Any other error from Get is a real
failure (the medium, or NoMemory when the value does not fit your
actor’s limit), and should not be treated as “use the default and
overwrite”: that would destroy a value you merely failed to read.
9.6 gogo/ringlog: a bounded log
Logs on a device must not fill the flash. gogo/ringlog keeps a log in two
files, dir/0.log (newest) and dir/1.log, and keeps the total within a
size you choose:
func Append(dir string, maxBytes int, line any) fs.Err
func Read(dir string, max int) (bytes.Bytes, fs.Err) // the newest max bytes, oldest first
When 0.log passes maxBytes/2, 1.log is deleted and 0.log becomes
1.log. So the log holds between half of maxBytes and maxBytes (plus
one line) of the most recent lines. Append writes the line exactly as
given, so include the newline yourself. Each Append opens, writes, syncs
and closes, so a power loss costs at most the line being written.
// gogo/ringlog keeps a log on flash that never grows past a size bound:
// two files, the older one dropped when the newer one is half full.
package main
import (
"gogo/fs"
"gogo/ringlog"
"gogo/strconv"
)
func main() {
for i := 1; i <= 30; i++ {
e := ringlog.Append("/flash/events", 100, "event "+strconv.Itoa(i)+"\n")
if e != fs.OK {
println("append", i, "error", int(e))
}
}
// Read returns the newest bytes, oldest first.
b, _ := ringlog.Read("/flash/events", 1000)
println("kept", b.Len(), "bytes:")
println(b.String())
tail, _ := ringlog.Read("/flash/events", 9)
println("last 9 bytes: [" + tail.String() + "]")
}
kept 99 bytes:
event 20
event 21
event 22
event 23
event 24
event 25
event 26
event 27
event 28
event 29
event 30
last 9 bytes: [event 30
]
One actor should write each log directory: while a file holds 0.log
open for writing, Append returns Busy and the line is not written.
9.7 /flash size and formatting
By default /flash uses the whole storage partition (5056 KB). The first
boot formats it. Two settings in the configuration store (chapter 11)
change that:
gogo config set fs.flash.size 1M # bytes, K or M suffix; at least 64K
gogo config rm fs.flash.size # back to the whole partition
A larger size grows the file system in place at the next boot, keeping
files. A smaller one needs a format, which erases everything on /flash:
gogo device format-flash # asks first; restarts the board and formats /flash
It formats the /flash partition only: the configuration store, the
program and the firmware stay. (It was gogo config set fs.flash.format yes before, which still works in this release.) Reflashing firmware or a
program does not touch /flash; only idf.py erase-flash wipes it.
To put a file on a board’s /flash from your computer, gogo push
copies an image there (chapter 14); other files go through a program
(over HTTP, chapter 10) or the SD card.
examples/fsdemo (a boot counter, button presses logged to a ringlog,
Usage on the screen) and examples/sddemo in the gogo tree exercise
storage on real boards.
10. Networking
The boards have Wi-Fi, and gogo has its own small TCP/IP stack written in C (Ethernet, ARP, IPv4, ICMP echo, UDP and TCP), sized for a microcontroller: its fixed state is under 4 KB. On top of it, libraries written in the gogo subset give you DHCP, DNS, SNTP (the date) and an HTTP client (HTTP/1.0, and HTTP/1.1 keep-alive) and server.
Networking follows the same model as everything else:
- The network interface, each UDP socket and each TCP connection is a port, owned by one actor, with typed events.
- Libraries such as DHCP and DNS are actors you talk to by message.
- A crashed connection handler takes only its own connection with it.
HTTPS (the "tls" port, keep-alive and file upload) has a chapter of its
own: chapter 17.
10.1 Running network programs
Before a board can join your network, store the Wi-Fi name and password in its configuration store (chapter 11; once per board, the settings survive reflashing):
gogo config set wifi.ssid MyNetwork
gogo config set wifi.password - # type the password; it is not echoed back
The firmware connects to Wi-Fi by itself, reconnects when the link drops,
and shows gogo: wifi connected (...) and later gogo: ip <address> on the
screen. Only 2.4 GHz networks work.
On your computer, gogo run has no network. The network ports refuse
to open, net.Subscribe returns false, and dhcp.Start fails at
once. The examples in this chapter check for that and say no network,
which is what you see when you run them on the host. gogo’s own tests run
network programs against a simulated network (tests/net); the HTTP
server, UDP echo and TCP echo examples below were checked that way too,
and the results are shown with them.
Note. With
GOGO_NET=hostin the environment (orgogovm --host-net), the host VM’stcpandtcp_listenports use your computer’s real sockets instead: a program can dial and accept TCP connections (numeric addresses;netif,udpand so DHCP and DNS stay unavailable). That is how a server node of distributed actors runs (chapter 20). The simulator intests/netis driven from Go test code, not fromgogo run.
10.2 Getting an address: gogo/dhcp
func Start(cfg dhcp.Config) error // Config{TimeoutMs int}; <= 0 means 10000
dhcp.Start starts the DHCP client actor, linked to the caller, and waits
until the interface has an address (it returns nil) or the timeout has
passed (errors.Timeout; the client keeps trying in the background). It
fails at once when there is no network (port.Open’s error for
"netif"). The client renews the lease, rebinds,
and starts over if the lease runs out. It owns the "netif" port, so keep
it alive (do not let the caller exit) while you use the network.
For a fixed address, set it in the configuration store and DHCP is skipped:
gogo config set net.ip 192.168.1.50
gogo config set net.mask 255.255.255.0 # the default
gogo config set net.gw 192.168.1.1
gogo config set net.dns 192.168.1.1
Watching the link
net.Subscribe() makes the caller receive net.Up{IP, Gateway, DNS}
whenever the interface gets (or changes) its address, and net.Down{}
when it loses it. It returns false if there is no network or 4 actors are
subscribed already.
IPv4 addresses are ints: a.b.c.d is a<<24 | b<<16 | c<<8 | d, so
addresses from 128.0.0.0 up are negative. Format them through int64:
// net.Subscribe delivers net.Up when the interface gets an address and
// net.Down when it loses it. IP addresses are ints; format them yourself.
package main
import (
"gogo/actor"
"gogo/dhcp"
"gogo/net"
"gogo/strconv"
)
// ipString formats a.b.c.d held in an int (addresses from 128.0.0.0 up are
// negative ints, so work in int64).
func ipString(ip int) string {
v := int64(ip)
if v < 0 {
v += 4294967296
}
s := ""
for shift := 24; shift >= 0; shift -= 8 {
if s != "" {
s = s + "."
}
s = s + strconv.FormatInt64(v>>shift&255, 10)
}
return s
}
// ipv4 packs a.b.c.d into an int (wrapping past 2^31, as int does).
func ipv4(a, b, c, d int) int { return a<<24 | b<<16 | c<<8 | d }
func main() {
println(ipString(ipv4(192, 168, 1, 42)), ipString(ipv4(10, 0, 0, 1)))
if !net.Subscribe() {
println("no network to watch")
return
}
dhcp.Start(dhcp.Config{TimeoutMs: 1000}) // keeps trying in the background
for {
switch m := actor.Receive().(type) {
case net.Up:
println("up: ip", ipString(m.IP), "gateway", ipString(m.Gateway), "dns", ipString(m.DNS))
case net.Down:
println("down")
}
}
}
On the host:
192.168.1.42 10.0.0.1
no network to watch
10.3 Names: gogo/dns
func Lookup(name string, timeoutMs int) (int, error) // timeoutMs <= 0: 5000
dns.Lookup returns the IPv4 address of a name (an A record), asking the
DNS server learned from DHCP. A dotted address like "10.0.0.1" is returned
as is. Behind it is a resolver actor registered as "dns", started by the
first lookup; it sends one query at a time, retries twice, and caches 4
answers by their time-to-live. You rarely call it directly: http.Get does.
To set the date from the network, see section 10.8.
10.4 HTTP client
func Get(url string, timeoutMs int) (http.Response, error)
func Post(url, contentType string, body bytes.Bytes, timeoutMs int) (http.Response, error)
func Do(method, url, contentType string, body bytes.Bytes, maxBody, timeoutMs int) (http.Response, error)
func HeaderValue(h []http.Header, name string) (string, bool) // case-insensitive
type Response struct {
Status int
Headers []Header // Header{Name, Value string}
Body bytes.Bytes
Truncated bool
}
The client speaks HTTP/1.0 with Connection: close to http:// URLs, and
HTTP/1.1 with Connection: close to https:// URLs (chapter 17 covers https, the keep-alive http.Client and
http.Upload). Each request runs in a temporary actor; the caller waits for it the way
actor.Call waits, and on timeout the request is abandoned. The temporary
actor follows its caller: if the caller exits or is killed meanwhile, the
request stops and its connection is reset. The error is an
errors.Code: errors.BadURL for a URL (or method or content type) that
cannot be sent, errors.Timeout when the timeout runs out,
errors.IO when DNS or the connection fails or the response is
malformed; an HTTP error status such as 404 is a response (nil error)
with that Status. dns.Lookup says more about a name: errors.NotFound
(no such name, no A record), errors.NoRoute (no network or DNS
server), errors.Timeout.
// Fetch a page with http.Get. The URL comes from the config store
// (gogo config set fetch.url http://...); for https:// see chapter 17.
package main
import (
"gogo/dhcp"
"gogo/http"
"gogo/sys"
)
func main() {
url, ok := sys.Config("fetch.url")
if !ok {
url = "http://example.com/"
}
if dhcp.Start(dhcp.Config{}) != nil {
println("no network")
return
}
r, err := http.Get(url, 8000)
if err != nil {
println("GET", url, "failed:", err.Error())
return
}
ct, _ := http.HeaderValue(r.Headers, "content-type")
println("GET", url, "->", r.Status, ct, r.Body.Len(), "bytes", "truncated:", r.Truncated)
}
On the host:
no network
Response size. The body is cut at http.MaxBody (8 KB) and marked
Truncated. Do takes a different limit, up to 64 KB. The whole body is
charged to the caller’s memory, and the default limit on a board is 16 KB,
so a caller that wants big responses needs a larger SpawnOpt limit (or a
small maxBody). Over http, responses using chunked transfer encoding
fail (an HTTP/1.0 request must not get one); https requests and the
keep-alive client of chapter 17 decode them.
10.5 HTTP server
func Serve(port int, handler func(http.Request) http.Response) actor.PID
type Request struct {
Method, Path string
Headers []Header
Body bytes.Bytes
}
http.Serve starts a listener actor, linked to the caller. For every
connection it starts a new actor that reads one request, calls your
handler, sends the response with Content-Length and Connection: close,
and exits. So the handler runs in its own actor: a handler that crashes
loses only that one connection, and the server carries on. Status 0
means 200.
Limits: the request line and headers at most 2 KB, the body at most 8 KB
(by Content-Length; chunked bodies are not supported). Bad requests get
400 and too-large bodies 413 without calling the handler. A connection
that does not send a complete request within 10 s is closed. If the
listener cannot listen (the port is taken), it exits with code 69,
http.ListenFailed (actor.Fail(errors.Busy): library failures are
exit codes 64..99, appendix B); trap exits to see that.
Since the handler is an ordinary function, you can call it directly to test it, which is what this example does on the host:
// A small web server: GET / shows a hit counter kept by its own actor;
// anything else is 404. On a board it serves on port 80 once DHCP (or the
// static net.ip setting) gives it an address. On the host there is no
// network, so it tests its handler by calling it directly instead.
package main
import (
"gogo/actor"
"gogo/bytes"
"gogo/dhcp"
"gogo/http"
"gogo/strconv"
)
type hit struct{}
// hits counts requests; it is registered as "hits".
func hits() {
n := 0
for {
switch r := actor.Receive().(type) {
case actor.Request:
n++
actor.Reply(r, n)
}
}
}
// count asks the hits actor for the next number (0 if it is not there).
func count() int {
p, ok := actor.Whereis("hits")
if !ok {
return 0
}
v, err := actor.Call(p, hit{}, 500)
if err != nil {
return 0
}
n, _ := v.(int)
return n
}
// handle runs in a fresh actor for every connection.
func handle(r http.Request) http.Response {
text := []http.Header{{"Content-Type", "text/plain"}}
if r.Method != "GET" || r.Path != "/" {
return http.Response{Status: 404, Headers: text, Body: bytes.FromString("not found\n")}
}
n := count()
return http.Response{Headers: text, Body: bytes.FromString("hello from gogo, visitor " + strconv.Itoa(n) + "\n")}
}
func show(r http.Response) {
status := r.Status
if status == 0 {
status = 200
}
body := r.Body.String()
println(status, body[:len(body)-1]) // without the newline
}
func main() {
actor.Register("hits", actor.Spawn(hits))
if dhcp.Start(dhcp.Config{TimeoutMs: 10000}) != nil {
println("no network: testing the handler directly")
show(handle(http.Request{Method: "GET", Path: "/"}))
show(handle(http.Request{Method: "GET", Path: "/"}))
show(handle(http.Request{Method: "GET", Path: "/secret"}))
return
}
actor.TrapExit(true) // Serve's listener is linked to us
http.Serve(80, handle)
println("serving on port 80")
for {
switch m := actor.Receive().(type) {
case actor.ExitMsg:
if m.Reason.Code == http.ListenFailed {
println("port 80 is taken")
}
}
}
}
On the host:
no network: testing the handler directly
200 hello from gogo, visitor 1
200 hello from gogo, visitor 2
404 not found
On the simulated network (with net.ip set), three requests to the server
got these responses:
GET / HTTP/1.0 -> HTTP/1.0 200 OK
Content-Length: 27
Connection: close
Content-Type: text/plain
hello from gogo, visitor 1
GET / HTTP/1.0 -> ... hello from gogo, visitor 2
GET /x HTTP/1.0 -> HTTP/1.0 404 Not Found ... not found
and the program printed serving on port 80.
Note how the counter works: handlers run in separate, short-lived actors
and cannot share a variable, so the count lives in a hits actor that
handlers ask with Call. That is the actor way to share state.
examples/netdemo in the gogo tree is a fuller program for the M5StickS3:
a bilingual page showing button presses and uptime, plus a periodic
http.Get.
10.6 UDP
port.Open("udp", net.UDP{Port: 7}) // Port 0: pick a free one
actor.Send(u, net.SendTo{Addr: a, Data: data}) // command
// event to the owner:
type Datagram struct{ From net.Addr; Data bytes.Bytes } // Addr{IP, Port int}
// A UDP echo server on port 7, straight on the "udp" port. The DHCP actor
// owns the network interface; this actor owns the UDP port.
package main
import (
"gogo/actor"
"gogo/dhcp"
"gogo/net"
"gogo/port"
)
func main() {
if dhcp.Start(dhcp.Config{}) != nil {
println("no network")
return
}
u, err := port.Open("udp", net.UDP{Port: 7})
if err != nil {
println("udp port 7 is taken")
return
}
println("echoing on udp port 7")
for i := 0; i < 3; i++ {
switch d := actor.Receive().(type) {
case net.Datagram:
println("echo", d.Data.Len(), "bytes to port", d.From.Port)
actor.Send(u, net.SendTo{Addr: d.From, Data: d.Data})
}
}
println("done")
}
On the host:
no network
On the simulated network, three datagrams of hello came back to their
sender, and the program printed:
echoing on udp port 7
echo 5 bytes to port 5000
echo 5 bytes to port 5000
echo 5 bytes to port 5000
done
UDP has no flow control: a datagram that would take its owner over its memory limit is dropped (the owner is not killed). A datagram to a host whose hardware address is not known yet is dropped while the stack asks for it with ARP; send again.
10.7 TCP
TCP connections are ports too, and they speak the stream protocol every
byte port shares (section 7.6): bytes in are port.Chunk, bytes out are
port.Out, each answered by port.Done, and the end is port.Closed.
| Port | Config | Commands | Events to the owner |
|---|---|---|---|
"tcp" | net.Dial{IP, Port, TimeoutMs} | port.Out{Data}, net.Shutdown{} | net.Connected{}, port.Chunk{From, Seq, ..., Data}, port.Done{From, Seq}, port.Closed{From, Reason} |
"tcp_listen" | net.Listen{Port} | net.Accepted{Conn} |
- Dialing.
port.Open("tcp", net.Dial{...})starts connecting; you getConnected, orClosedwithnet.Refused,net.Timeoutornet.NoRoute. - Accepting. A listener’s owner gets
Accepted{Conn}for each new connection.Connis a"tcp"port owned by the listener’s owner and paused until youport.Handoffit to the actor that will handle it (or send itnet.Resume{}to keep it). - Receiving. Each
Chunkis the next segment from the peer, in order;Droppedis always 0. A segment is acknowledged only once itsChunkis in your mailbox, so a slow reader slows the sender down instead of being killed or losing data. - Sending.
Out{Data}sends aBytes;Done{Seq}follows when the peer has acknowledged all of it. OneOutmay wait behind the one in progress; a thirdOutbefore aDoneis refused withDone{Seq: -1}and not sent; the connection carries on. An emptyOut, one afterShutdown, or one on a connection that has ended getsDone{-1}too. - Closing.
Closed{Normal}means the peer has finished sending (you may still send). Any other reason means the connection is gone;Outs still in flight then getDone{-1}before theClosed. SendShutdown{}to finish your side, then close the port: the stack completes the close on its own. Closing the port withoutShutdown(or exiting) resets the connection. - From. Every event carries the connection’s PID in
From, so an actor that owns several connections can tell them apart.
The write rule matters in practice. This echo server queues data in a
Buffer while two Outs are in flight:
// A TCP echo server on port 7: the listener accepts connections and hands
// each one to its own actor, which echoes until the peer closes.
package main
import (
"gogo/actor"
"gogo/bytes"
"gogo/dhcp"
"gogo/net"
"gogo/port"
)
// echo owns one connection. A tcp port takes at most two Outs in flight
// (a third is refused with Done{Seq: -1} and not sent), so data that
// arrives while two are in flight waits in a Buffer.
func echo(conn actor.PID) {
inFlight := 0
waiting := bytes.NewBuffer(256)
for {
switch m := actor.Receive().(type) {
case port.Chunk:
if inFlight < 2 {
actor.Send(conn, port.Out{Data: m.Data})
inFlight++
} else {
waiting.WriteBytes(m.Data)
}
case port.Done:
inFlight--
if waiting.Len() > 0 {
actor.Send(conn, port.Out{Data: waiting.Freeze()})
inFlight++
}
case port.Closed:
if m.Reason == net.Normal {
// The peer has finished sending: finish our side too.
actor.Send(conn, net.Shutdown{})
}
port.Close(conn) // after Shutdown the stack completes the close
return
}
}
}
func main() {
if dhcp.Start(dhcp.Config{}) != nil {
println("no network")
return
}
_, err := port.Open("tcp_listen", net.Listen{Port: 7})
if err != nil {
println("port 7 is taken")
return
}
for {
switch m := actor.Receive().(type) {
case net.Accepted:
conn := m.Conn
h := actor.Spawn(func() { echo(conn) })
if !port.Handoff(conn, h) {
port.Close(conn)
}
}
}
}
On the host:
no network
On the simulated network a client sent five segments without
acknowledging the echoes, and got one two three four five back in full,
followed by the server’s FIN. A naive echo (one Out per Chunk) would
lose data in the same exchange: the third Out arrives before the first
Done and is refused.
The stack is deliberately small: one segment in flight in each direction
(1460 bytes), in-order segments only, retransmission after 1 s doubling to
8 s, and giving up after 6 retransmissions (Closed{Timeout}); a peer
that closes its window but answers the stack’s probes keeps the connection
however long it stays closed. There are
4 connection slots in all, and incoming connections never take the last
one, so the device can always dial out.
A connection with no traffic stays open as long as the peer is alive,
however long that is: after 2 minutes in which nothing arrived from the
peer the stack sends it a keepalive probe, an empty segment any live TCP
answers, and repeats it every 10 s. If 3 probes in a row go unanswered
(the peer was switched off, unplugged, or dropped by a NAT without a
reset) the connection is reset and its owner gets Closed{Timeout}, so
a dead peer frees its slot about 2.5 minutes after it went silent; you
do not need your own timer for that, only for an application-level
timeout. An owner that stops reading does not lose the connection: when
its mailbox has no room for another segment the stack closes the TCP
window, the peer stops sending and only probes, and when the owner reads
again the stack reopens the window at once and the data flows on, however
long the pause was. A dead peer is still found by the keepalive meanwhile. A
connection whose peer has already finished (you got Closed{Normal})
can still end this way, with a second Closed, if you keep it open
after the peer vanished. With --host-net the operating system’s TCP
keepalive probes idle connections at the same timings, and a full
mailbox there likewise only stops the sender.
All connections end with Closed{NoRoute} when the interface loses its
address, or when the "netif" owner (the DHCP actor) exits.
10.8 The date: gogo/sys and gogo/sntp
// gogo/sys
func Time() int64 // Unix time in ms (UTC), or 0 if unknown
func SetTime(ms int64) bool
func Random() int // 30 random bits: 0 <= n < 1<<30
// gogo/sntp
func Sync(server string, timeoutMs int) error // timeoutMs <= 0: 5000
func Now() int64 // sys.Time()
The boards have no battery-backed clock, so after boot nothing knows the
date. actor.Now only counts milliseconds since the VM started. The
wall clock in gogo/sys is separate: sys.Time() returns the Unix
time in milliseconds, or 0 while it is unknown. Once set, it keeps
advancing by itself.
sys.SetTime(ms) sets it and returns true, with one exception: a time
earlier than the moment the firmware (or the host VM) was built is
refused, SetTime returns false and the clock is unchanged. That floor is
the only protection the clock has. Any code may set it, so nothing can move
it back to before the build. SetTime with 0 or less forgets the time, and
Time returns 0 again.
sntp.Sync(server, timeoutMs) asks an SNTP server (a name, resolved with
gogo/dns, or a dotted address; UDP port 123) for the time and sets the
wall clock. It runs the exchange in a helper actor, so your mailbox is not
touched, sends the request up to 3 times within the timeout, and corrects
for half the round trip. It returns an error, leaving the clock alone, if
the name does not resolve (dns.Lookup’s error), no valid reply comes in
time (errors.Timeout), or the floor refuses the answer
(errors.BadArg). SNTP is not authenticated, so a reply could come from anyone on
the network path. Sync once at startup, and again every few hours if the
date matters; the clock drifts with the board’s crystal in between.
sys.Random() returns 30 bits from the platform’s entropy source (the
chip’s hardware generator on the board, getentropy on the host). It is
meant for protocol nonces and IDs; gogo/sntp uses it for its request.
// The wall clock and randomness: gogo/sys, set from the network with
// gogo/sntp. The server comes from the config store
// (gogo config set clock.server pool.ntp.org).
package main
import (
"gogo/dhcp"
"gogo/sntp"
"gogo/strconv"
"gogo/sys"
)
// pad2 formats 0..99 with two digits.
func pad2(n int) string {
if n < 10 {
return "0" + strconv.Itoa(n)
}
return strconv.Itoa(n)
}
// date formats Unix time ms (UTC) as "YYYY-MM-DD hh:mm"
// (the days-to-civil algorithm, for dates after 1970).
func date(ms int64) string {
mins := ms / 60000
days := int(mins / 1440)
hm := int(mins % 1440)
z := days + 719468
era := z / 146097
doe := z - era*146097
yoe := (doe - doe/1460 + doe/36524 - doe/146096) / 365
doy := doe - (365*yoe + yoe/4 - yoe/100)
mp := (5*doy + 2) / 153
d := doy - (153*mp+2)/5 + 1
m := mp + 3
if m > 12 {
m -= 12
}
y := yoe + era*400
if m <= 2 {
y++
}
return strconv.Itoa(y) + "-" + pad2(m) + "-" + pad2(d) + " " + pad2(hm/60) + ":" + pad2(hm%60)
}
func main() {
server, ok := sys.Config("clock.server")
if !ok {
server = "pool.ntp.org"
}
if dhcp.Start(dhcp.Config{}) == nil && sntp.Sync(server, 5000) == nil {
println("synced with", server, "->", date(sys.Time()), "UTC")
} else {
println("not synced: no network or no answer")
}
// Forget the time, then set it by hand.
sys.SetTime(0)
println("known:", sys.Time() != 0)
noon := int64(4102488000000) // 2100-01-01 12:00 UTC
println("set 2100:", sys.SetTime(noon))
println("now:", date(sys.Time()))
// Earlier than the build: refused, the clock is unchanged.
println("set 1970:", sys.SetTime(1000))
println("still:", date(sys.Time()))
// 30 random bits.
a, b := sys.Random(), sys.Random()
println("random in range:", a >= 0 && a < 1<<30, "differ:", a != b)
}
On the host there is no network, so Sync fails, and the rest runs as on
a board:
not synced: no network or no answer
known: false
set 2100: true
now: 2100-01-01 12:00
set 1970: false
still: 2100-01-01 12:00
random in range: true differ: true
On a board with Wi-Fi the first line is synced with pool.ntp.org -> <the date> UTC instead. On the host the wall clock starts from the
computer’s clock (or from $GOGO_UNIX_TIME_MS, in ms; 0 means unknown), so
sys.Time() is known from the start. The example forgets it first to show
the board’s behaviour. On a board it starts unknown at every boot and reset.
gogo has no time zones and no date formatting. date above is the usual
days-to-civil arithmetic, valid for dates after 1970.
10.9 Memory on the board
On the M5StickS3 the Wi-Fi driver takes about 30 KB of heap and 31 KB of
static memory, gogo’s stack under 4 KB, and each HTTP connection a handler
actor of about 3 KB plus its body buffers (handler and client actors are
started with a limit of 2 x body limit + 6 KB, 22 KB by default). Running
examples/netdemo leaves about 173 KB of internal RAM free.
11. Configuration and Devices
A device needs settings that are not part of the program: the Wi-Fi
network, a fixed IP address, the URL of a server, a calibration value.
gogo keeps them in a configuration store of string keys and values,
edited from your computer with gogo config and read by programs with
sys.Config.
11.1 Reading settings: sys.Config
package sys
func Config(key string) (value string, ok bool) // ok is false if the key is not set
Values are strings; convert them with gogo/strconv. Always have a
default, so the program also runs where the key is not set:
// Read settings from the config store. Set them with "gogo config set
// blink.ms 250" (on the board when one is connected, else in
// ~/.gogo/config). Keys that start with "wifi." are never visible to
// programs.
package main
import (
"gogo/strconv"
"gogo/sys"
)
// intSetting returns the key's value as an int, or def.
func intSetting(key string, def int) int {
v, ok := sys.Config(key)
if !ok {
return def
}
n, err := strconv.Atoi(v)
if err != nil {
println("config:", key, "is not a number:", v)
return def
}
return n
}
func main() {
println("blink.ms =", intSetting("blink.ms", 500))
println("retries =", intSetting("retries", 3))
name, ok := sys.Config("device.name")
println("device.name =", name, ok)
_, ok = sys.Config("wifi.ssid")
println("wifi.ssid visible:", ok)
}
With this store (on the host, the file named by $GOGO_CONFIG):
blink.ms=250
retries=lots
device.name=kitchen sensor
wifi.ssid=home
blink.ms = 250
config: retries is not a number: lots
retries = 3
device.name = kitchen sensor true
wifi.ssid visible: false
Keys starting with wifi. belong to the firmware: programs never see them,
whatever is stored.
A program started on your computer has one more input, its command-line
arguments: sys.Args() returns the words after the program in gogo run prog a b as a []string (a, b), without the program’s own name, and
an empty slice when there are none, always the case on a board (chapter
12).
11.2 Editing settings: gogo config
gogo config [-port P | -local] set <key> <value|->
gogo config [-port P | -local] get <key>
gogo config [-port P | -local] list
gogo config [-port P | -local] rm <key>
gogo config [-port P | -local] import [-n] <file|-> # many keys at once
gogo config [-port P | -local] export # the store as a file for import
gogo config keys # the keys gogo itself reads (section 11.3)
Three board commands go with it (chapter 12):
gogo device [-port P] info # the firmware the board runs: version, board, image format
gogo device [-port P] scan # Wi-Fi networks the board sees (2.4 GHz)
gogo device [-port P] stats # network counters and free memory on the board
Keys are 1 to 15 characters of a-z 0-9 . _ (15 is the limit of the
board’s storage); values are at most 1000 bytes, without newlines. A value
of - reads the value from standard input, which is how you enter a
password without leaving it in your shell history.
set checks what it writes. Keys under the prefixes wifi., net.,
fs., code. and gogo. belong to gogo: such a key must be one of the
keys in section 11.3, and its value must have the key’s type, so a typo
is caught when you type it rather than at the next boot:
$ gogo config set fs.flash.size 64KB
gogo config: bad value for fs.flash.size (size): want bytes, with an optional K or M suffix, like 65536, 64K or 1M
$ gogo config set net.adress 10.0.0.9
gogo config: net.adress is not a key gogo knows, and net.* keys belong to gogo (pick another prefix for your own)
Any other key is yours, with any value. Keys written before this check
existed may hold upper case letters or -: get and rm still take
them, set no longer does.
Where the store is. On a board, it is the firmware’s non-volatile
storage (NVS); it survives reflashing the firmware and the program. On
your computer it is a text file of key=value lines: $GOGO_CONFIG, or
~/.gogo/config by default. gogo config picks one this way:
-port P: the board on that serial port.-local: the local file.- Neither: the local file if
$GOGO_CONFIGis set (naming the file counts as choosing it); otherwise the board, if exactly one is connected (a line on standard error says so). - Otherwise it stops with an error and writes nothing:
$ gogo config set wifi.ssid home # no board plugged in (macOS)
gogo config: no board found (/dev/cu.usbmodem*); connect one, pass -port, or -local for this computer's store
$ gogo config set wifi.ssid home # two boards plugged in
gogo config: several boards found (/dev/cu.usbmodem1101, /dev/cu.usbmodem1201); pick one with -port, or -local for this computer's store
So with one board plugged in, gogo config set ... configures that
board, and a setting never lands somewhere you did not mean. This
applies to every operation that uses a store; gogo config keys needs
none.
A session against the local file:
$ export GOGO_CONFIG=/tmp/demo-config
$ gogo config set blink.ms 250
$ gogo config set device.name "kitchen sensor"
$ gogo config list
blink.ms=250
device.name=kitchen sensor
$ gogo config get blink.ms
250
$ gogo config get nope
gogo config: nope is not set
$ gogo config rm blink.ms
$ gogo config list
device.name=kitchen sensor
$ gogo device scan
gogo: no board found (/dev/cu.usbmodem*); connect it or pass -port
get and list never print the Wi-Fi password or node.token, only
(set).
Note. On your computer the store is a plain text file (readable by you only), and
gogo config -local set wifi.password -writes the password into it unencrypted. The tool writes a secret (wifi.password,node.token) there only when you chose the local store (-localor$GOGO_CONFIG), and then warns:gogo config: warning: wifi.password is kept in plain text in .... Set Wi-Fi credentials on the board (with it connected, or-port).
Many settings at once: import and export. Keep the settings in a
file of the store’s own format, one key=value per line; lines starting
with # and blank lines are skipped, and a value runs to the end of the
line (spaces and = included):
# kitchen.cfg: the kitchen sensor
wifi.ssid=home
net.ip=192.168.1.20
net.gw=192.168.1.1
demo.url=http://192.168.1.10:8080/ingest?board=kitchen
device.name=kitchen sensor
import sets every key of the file on the store set would use (the
same rules, -port and -local included), in file order:
$ gogo config import kitchen.cfg
gogo config: board on /dev/cu.usbmodem1101 (-local for this computer's store)
set wifi.ssid
set net.ip
set net.gw
set demo.url
set device.name
imported 5 keys to board /dev/cu.usbmodem1101
Every line is checked as set checks it first, and a key may appear
only once; if any line is wrong, nothing is written and every bad line
is named:
$ gogo config import kitchen.cfg
gogo config: nothing imported:
kitchen.cfg:3: bad value for net.gw (ip): want a dotted IPv4 address like 192.168.1.20
kitchen.cfg:6: demo.url is set again (first on line 4)
-n (or -dry-run) checks the file and prints what would be set,
writing nothing; import - reads the file from standard input. A
secret in the file is shown as set wifi.password (set), never with its
value. On a board, the keys its limits bound (vm.memory,
vm.max_actors, vm.actor_memory, vm.handles) are first checked
against them, as set does, also with -n; one that does not fit stops
the import before anything is written. A board takes the keys one by one: if it refuses one (its storage
full, say), the import stops there and the error lists the keys written
and those not written. The local store is written in one go.
export prints the store as such a file, so one board’s settings can be
copied to another. Secrets are not exported (the board never sends the
Wi-Fi password back); they appear as comments to fill in by hand:
$ gogo config -port /dev/cu.usbmodem1101 export > kitchen.cfg
$ cat kitchen.cfg
# gogo config export from the board /dev/cu.usbmodem1101
demo.url=http://192.168.1.10:8080/ingest?board=kitchen
device.name=kitchen sensor
net.gw=192.168.1.1
net.ip=192.168.1.20
# wifi.password=(set, not exported)
wifi.ssid=home
$ gogo config -port /dev/cu.usbmodem1201 import kitchen.cfg
The board talks to gogo config over the USB serial console, so close
gogo monitor first. Program output cannot fake the board’s answers.
11.3 Keys gogo uses
| Key | Type | Used by | Meaning |
|---|---|---|---|
wifi.ssid, wifi.password | string (at most 32 and 64 bytes) | firmware | the Wi-Fi network; the board reconnects at once when they change; also written by Wi-Fi setup from a phone (section 2.1) |
net.ip, net.mask, net.gw, net.dns | ip (a.b.c.d) | gogo/dhcp | a static address instead of DHCP (net.mask defaults to 255.255.255.0) |
fs.flash.size | size | firmware | size of /flash (chapter 9) |
fs.flash.format | yes | firmware | deprecated: format /flash once at the next boot; use gogo device format-flash |
ports.postbytes | size | firmware, gogovm, at boot | the bytes the board ports’ posts (book 22.7) may queue at once: 16 KB on a board, 1 MB on the host; 1 KB to 64 MB (0: the default; a smaller value is raised to 1 KB, with a line at boot); a post with no room left is GOGO_EFULL, one larger than the budget GOGO_E2BIG |
code.mem | size | VM (gogo/code), at boot | budget for loaded module code: 64 KB on a board, 16 MB on the host (chapter 14) |
node.token | string (at most 200 bytes) | gogo/node | the shared secret of distributed actors (chapter 20); never printed |
node.name | string (at most 32 bytes) | gogo/node | this node’s name when a program gives none |
vm.actor_memory | size | VM, at boot | an actor’s default memory limit (heap, stack and mailbox; SpawnOpt sets one actor’s): 16 KB on a board, at most 256 KB; 1 MB on the host, at most 1 GB (gogovm --actor-memory); at least 1 KB |
vm.memory | size | VM, at boot | memory for all actors together: on a board the 160 KB arena, which is also its most; no limit on the host (gogovm --memory); 0 is no limit |
vm.max_actors | int | VM, at boot | most live actors: 1024 on a board, 16384 on the host (gogovm --max-actors), at most 61440 (the PIDs above are node links’ remote ones) |
vm.max_ports | int | VM, at boot | most ports open at once: 16 on a board, 1024 on the host (gogovm --max-ports), at most 2048; the table grows as ports open |
node.max_links | int | node port, at boot | most node links: 8 on a board, 512 on the host (gogovm --max-links), at most 2048 and vm.max_ports (a link takes a port); on a board also what fits a quarter of its memory. A larger value is cut, with a line on the console |
vm.handles | N or N/M | VM, at boot | off-heap Bytes handles in the whole VM, and (M) for one actor: 64/16 on a board (at most 1024), 4096/256 on the host (at most 65535; gogovm --bytes-handles); without M, the default’s, at most N |
A size is a number of bytes with an optional K or M suffix (65536,
64K, 1M); the VM’s keys (vm.*, code.mem) also take G. The VM
reads its keys once, when it starts (restart the board after a change): a
gogovm flag, or a field of an embedding host’s gogo_config, beats the
key, and the key beats the platform’s default. A value past the
platform’s most is cut to it with one line on the console, and one that
is not a number is ignored with a line; gogo config set checks the
ranges above before writing, and gogo device info (or gogovm --info)
shows what the VM runs with (section 6.2 has the table per platform).
gogo config keys prints this table. The wifi., net.,
fs., code., gogo., node. and vm. prefixes are reserved for keys gogo adds
later; anything else is yours. A dotted prefix per program (demo.url,
fsdemo.mode) keeps keys apart.
11.4 The two boards
| M5StickS3 | Cardputer ADV | |
|---|---|---|
| Chip | ESP32-S3 (PICO-1-N8R8, 8 MB PSRAM) | ESP32-S3 (Stamp S3A, no PSRAM) |
| Flash | 8 MB | 8 MB |
| Screen | 240 x 135 LCD (console) | 240 x 135 LCD (console) |
| Buttons | KEY1 = G11, KEY2 = G12 (gpio) | G0 button (gpio) |
Keyboard (kbd) | none | 56 keys |
Battery (power) | voltage, charging, external power | voltage only (charging and external are -1) |
| Storage | /flash | /flash, /sd |
| Firmware build | GOGO_BOARD=sticks3 (default) | GOGO_BOARD=cardputer |
Both boards have the same flash layout, so gogo flash writes a program to
either without a board option. Their firmware differs; build the one for
your board (chapter 2).
On both boards the VM gets 160 KB of internal RAM for actors (16 KB per actor by default) and runs on the second CPU core, while Wi-Fi and the screen run on the first.
Flash layout
| Partition | Offset | Size | Holds |
|---|---|---|---|
nvs | 0x9000 | 24 KB | the configuration store |
factory | 0x10000 | 2 MB | the firmware |
gogo | 0x210000 | 1 MB | your program image |
gogofs | 0x310000 | about 5 MB | /flash |
gogo flash writes only the gogo partition, idf.py flash only the
firmware. Neither touches the configuration store or /flash.
Console messages
At boot the firmware checks the program image and prints one of:
gogo <version> (image format 15.<minor>): image <N> bytes, arena <cap> bytes, free RAM <F> (largest <L>): all is well; the program runs.gogo: no image: nothing was flashed withgogo flash.gogo: bad image (<reason>): a damaged image.gogo: unsupported image format 16.0 (this firmware runs 15.0 to 15.3): the image was built for another major, or a newer minor than the firmware’s: update the firmware (or build with a matchinggogo).gogo: image requires kbd, which this VM lacks: the program opens a driver (or uses a mount such as/sd) this firmware was built without (gogo firmware, chapter 12).
When the program ends: gogo: vm exited (<code>), arena used <bytes>, and
the board idles until reset. Wi-Fi status lines (gogo: wifi connected,
gogo: ip ..., gogo: network down) appear on the screen too.
12. Toolchain Reference
Everything is done with one command, gogo: prebuilt in each release
(gogo-<os>-<arch>, chapter 2), or built with go build -o build/gogo ./cmd/gogo. gogo run also needs the host VM, gogovm (released as
gogovm-<os>-<arch> for macOS and Linux, or built with make vm). It runs on macOS and Linux; on Windows, setup flashes the
firmware and programs, but the serial console commands (monitor,
config on a board, and the Wi-Fi and first-program steps of setup)
are not supported.
gogo build [-path dirs] [-o out.ggb] <dir|file.gg>
gogo run [--key c=pin]... [--fs-root DIR] [VM parameter flags] [-path dirs] <dir|file.gg|file.ggb>
gogo env [-path dirs]
gogo dis <file.ggb>
gogo info [-path dirs] <file.ggb|dir|file.gg>
gogo flash [-port P] [-esptool path] [-path dirs] [-no-usb-reset] <app.ggb|dir|file.gg>
gogo push [-port P] [-timeout seconds] [-no-usb-reset] <file.ggb> [/flash/path]
gogo monitor [-port P] [-timeout seconds] [-until text] [-reset] [-no-usb-reset]
gogo firmware (-board sticks3|cardputer | -port P [-esptool path] [-no-usb-reset]) [-o dir] [-build] [-with list] [-without list] [-component dir]... files...
gogo config [-port P | -local] [-no-usb-reset] set <key> <value|-> | get <key> | list | rm <key> | import [-n] <file|-> | export | keys | scan | stats
gogo device [-port P] [-yes] [-no-usb-reset] info | scan | stats | format-flash | usb-reset
gogo setup [-port P] [-board sticks3|cardputer] [-version vX.Y.Z] [-release-url URL|DIR] [-esptool path] [-offline] [-skip-wifi] [-new-layout] [-reflash] [-yes] [-dry-run] [-no-usb-reset]
gogo version
Flags work the same in every command:
- A flag is spelt with one dash or two (
-port P,--port P), and its value follows as the next argument or after=(-o=app.ggb). - Flags may come before or after the other arguments:
gogo build app -o app.ggbandgogo build -o app.ggb appare the same.--ends the flags, so an argument after it that starts with-is not one; a lone-is an ordinary argument.gogo runis the exception, asgo runis: its flags come before the program, and what follows the program belongs to the program (refused for now). - The names are the same everywhere:
-port(the board’s serial port),-board,-o(where the output goes),-timeout(seconds),-esptool,-path,-yes,-no-usb-reset(below). -h(or-help) prints the command’s usage and exits 0. A mistake (an unknown flag, a missing value or argument) prints what is wrong and the usage, and exits 1.
A board that stops answering over USB. The boards’ USB serial link
sometimes goes silent while the program keeps running
(docs/known-issues.md, “ESP32-S3 boards”). The commands that
talk to a board (flash, push, monitor, config on a board,
device, setup, and firmware -port) then recover it themselves on
macOS and Linux. When the board does not answer, or esptool fails (for
gogo monitor: when nothing at all arrived), they ask the board’s USB
device for its string descriptor 0.
Only when that request times out or comes back empty, the signature of
the silent link, do they bus-reset the device once (the chip keeps
running), wait for the port to come back, retry once, and print
gogo: the board's USB link was silent; reset it (USB bus reset)
A device that answers the request (a board without gogo firmware, one
restarting, a quiet program) is never reset, and the original error is
reported as it is. If the retry fails too, the error says so and to
replug the board. esptool keeps the terminal as before (its progress bar
redraws in place). A retried flash is the same command again, which
rewrites every region from its start, so nothing is left half-written
by the first try; if the retry fails too, the firmware refuses the
half-written program as after any failed flash. Only an
Espressif USB device (vendor id 0x303a) is reset, never while another
of your programs has the port open (gogo cannot see programs of root or
other users; if it cannot tell, it does not reset). -no-usb-reset (or GOGO_NO_USB_RESET=1 in
the environment) turns this off; gogo device usb-reset resets by hand.
On Linux the reset needs a udev rule (gogo prints it; known issues has
it too); on Windows gogo cannot reset a USB device, so replug the board.
Where no reset can happen (turned off, or Windows), an esptool failure
is reported alone, and a board that did not answer gets a line on what
to do about a silent link.
gogo build
gogo build [-path dirs] [-o out.ggb] <dir|file.gg>
Compiles the package main in <dir> (all its .gg files), the gogo
libraries and the packages of your own it imports into one image file.
Without -o the image is named after the directory, <dir>.ggb, in the
current directory. Given a .gg file instead (or a file starting with
#!), it compiles that file alone as package main, into <name>.ggb. The image contains bytecode and constants and runs unchanged on
the host VM and on any board.
Errors are printed as file:line:col: message and the exit status is 1
(every gogo command exits 1 on an error; gogo run has its own
statuses, below).
Messages from Go’s type checker look like Go’s (declared and not used: x);
messages about the subset start with gogo::
main.gg:9:7: gogo: interior pointer &s[0] not supported: gogo has no pointers into a slice element or a struct field; use a []*T or a *T field, or s[i].F = v
Type errors are reported first; subset errors appear once the program type-checks. Chapter 3 lists the subset errors.
Packages and the search path
An import that does not start with gogo/ names a package of your own
(section 3.1.1). <dir> (or the directory of the single file) is the
build root, and the import is looked up, first match wins:
- in the build root, when its first element is the root directory’s
name:
import "app/util"while buildingapp/isapp/util/; - in each directory of the search path, in order:
import "lib/ring"is<dir>/lib/ring/.
A match is a directory holding .gg files. The search path is -path dirs if given, else $GOGOPATH (directories separated by :, or ;
on Windows; empty elements are skipped, relative ones are taken from the
current directory), else $HOME/gogo when GOGOPATH is unset. A
build root inside a search path directory counts once (the same directory
is one place). A path found in more than one place is a warning
naming every location; a path found nowhere is an error listing them:
main.gg:3:8: gogo: import "app/nope": package not found; searched:
app/nope (build root: no such directory)
/home/you/gogo/app/nope (search path: no such directory)
A package’s name must be its directory’s name (so a Go identifier), only
the build root may be package main, an import path must match the
directory names on disk letter case included, and import cycles are
errors that show the chain. Functions of your packages are named by their
import path (app/util.Sum) in crash reports and gogo dis. A module
built for hot loading resolves its packages in the same way, from its own
directory.
Only .gg files are read: .go files in the directory are ignored, and a
directory with .go files but no .gg file is an error that says to
rename them (no .gg files, only .go files: ...). gogo sources were .go
files before; .gg is Go syntax, so map it to Go in your editor for
highlighting (chapter 2, Editor support); gopls does not apply.
Requirements and //gogo:optional
The image also records, by name, what it needs from the board (its
requirements, appendix F): the driver of every port.Open with a constant
driver name ("kbd", "tcp", a host port’s "ui"), and the mount /sd
for constant /sd paths, in package main and in every library compiled
in. An image that can make a float (a float constant, a conversion of an
integer to a float, math.Inf, math.NaN, strconv.ParseFloat) also
requires float, the firmware option GOGO_FLOAT; code that only handles
floats it is given (gogo/fmt’s formatting, a float case of a type
switch) requires nothing, since without a source no float can reach it. An
import by itself requires nothing. A firmware that lacks a required
driver or mount refuses the image at boot, naming it:
gogo: image requires kbd, which this VM lacks
and code.Load returns Unsupported with code.Missing naming it
(chapter 14). A driver name the compiler cannot see (a variable, a
function call) is a loophole: it requires nothing, so it escapes this
check, and the open simply fails at run time on a board without the
driver. The build warns at each such call, with its position:
gogo: warning: main.gg:12:9: port.Open with a non-constant driver name: the image does not require it and the load does not check it; name the driver and mark it //gogo:optional if the program handles its absence
To open a driver that may be absent, name it and mark it soft with
//gogo:optional (below), which works in package main too.
The image format itself has a version, major.minor (major 15; gogo version prints the full one). A firmware runs images of its major whose
minor is at most its own, and the compiler stamps each image with the
lowest minor its program needs, so after a firmware update every module
already on /flash keeps loading. An image of another major, or of a newer minor than the
firmware’s, is refused (unsupported image format 15.4 (this VM runs 15.0 to 15.3); code.Load returns BadVersion). The minors so far: 15.1
added screen.Config, 15.2 floating point, 15.3 sized integers (only a
program that divides, compares or shifts uint32/uint64 values, uses
int8/int16/uint16 arithmetic or prints an unsigned value needs it),
15.4 panic, interfaces and == on structs and interfaces, 15.5 the
node port’s types (gogo/node), 15.6 pointers, maps, read-only
package-level variables and gogo/fmt, 15.7 the errors of actor.Call
and actor.Register (new builtins: a program that calls either,
directly or through a library call that does, such as any gogo/node
call, dns.Lookup, http.Get or supervisor.SuperviseModule, needs
15.7 firmware; supervisor.Supervise, http.Serve or sound.Play alone
do not).
A package, a library or package main, can declare that it uses some
drivers only softly: it opens them only when a call asks for that at run
time, and handles their absence (port.Open returns an error) as an
ordinary failure. It says so with a directive line in any of its files,
conventionally the last line of the package doc comment, after an empty
// line (where gofmt puts directives):
// Package http is a small HTTP/1.x client and server...
//
//gogo:optional tls
package http
-
The listed drivers add no requirement for that package’s own
port.Opencalls. The same driver opened by another package still counts: a program that callsport.Open("tls", ...)itself requirestls, unlesspackage mainnames it in its own directive. A program that runs on several boards can so probe for a driver one of them lacks:// Program keys uses the keyboard when the board has one. // //gogo:optional kbd package main -
Any driver name is accepted, a board’s or a host port’s. An empty list or a misspelt
//gogo:directive is a compile error, for examplea.gg:3:1: gogo: unknown directive //gogo:optinal (want //gogo:optional, //gogo:builtin or //gogo:reserved). The other two mark declarations of the standard library’s system packages (a function the VM implements, a struct type with a fixed type index;lib/README.md); a program cannot use them. -
gogo/httpdeclarestls(an http-only program runs on a firmware without TLS, where an https request fails), andgogo/sounddeclaresmic speaker(Recordreturns false without a microphone,Playwithout a speaker). -
The directive is a promise the compiler does not check. A library can still hand
maina function that opens the driver; that open then fails cleanly at run time (an error) on a firmware without the driver. -
gogo firmware(below) chooses features from the requirements, so it does not turn a soft driver on by itself;tls,micandspeakerare on by default, and-withoutmakes those calls fail at run time instead.
gogo run
gogo run [--key c=pin]... [--fs-root DIR] [--actor-memory SIZE] [--memory SIZE] [--max-actors N]
[--max-ports N] [--max-links N] [--bytes-handles N[/M]] [-path dirs] <dir|file.gg|file.ggb> [args...]
Runs a program on the host VM. Given a directory it builds it first (to a
temporary image), all of its .gg files together; given a .gg file, or
any file starting with #!, it builds that file alone, with its directory
as the build root for packages (an executable script with the first line
#!/usr/bin/env -S gogo run runs this way, chapter 2); given a .ggb
file it runs that image. -path dirs is the search path of the build, as
for gogo build.
Program arguments. Everything after the program is the program’s, as
for go run: flags come before the program, and what follows it is passed
on untouched (gogo run tool.gg -v "a b" gives tool.gg the two arguments
-v and a b; -- and empty words are passed too). The program reads
them with sys.Args(), a []string of the arguments only: unlike Go’s
os.Args there is no element 0 for the program’s own name, so with no
arguments the slice is empty (and not nil). A #! script gets the
arguments of its own command line the same way (./tool.gg -v runs
gogo run ./tool.gg -v). gogovm takes them after the image,
gogovm [flags] prog.ggb [args...]. Every call to
sys.Args() copies the arguments into the actor’s heap, so call it once
and keep the result; a very large command line (hundreds of KB) can run
the actor out of memory (a crash, oom, not an empty slice). On a board
nothing starts a program with arguments, so sys.Args() is empty there; a host
that embeds the VM can provide them (chapter 18).
Exit status. gogo run exits with the VM’s status, which says how the
main actor ended:
| Status | Meaning |
|---|---|
| 0 | main exited Normal (or Shutdown) |
| 1 | a usage, toolchain or build error, or the VM was not found |
| 2 | the image could not be loaded: not an image, damaged, or a format this VM does not run |
| 3 | the image requires a driver or mount the VM lacks (for example tls in a VM built without mbedTLS) |
| 4 | main crashed: a VM reason such as divzero, oom or killed (appendix B), or a code below 64 or negative given to actor.Exit |
| 64..99 | main exited with a library failure, actor.Failed plus a shared code (appendix B), as it is: http.ListenFailed is 69 |
| 100..255 | main exited with your code, actor.Exit(code) with code from 100; a code above 255 is 255 |
Only main counts: other actors’ crashes are reported on standard
error but leave the status alone, so a program whose main ends
normally exits 0. To fail a script, end main with a code:
if !ok {
println("check failed")
actor.Exit(100) // gogo run exits 100
}
When a linked actor’s exit takes main down, main exits with that
actor’s own reason: 4 if it crashed, but 150 if it called
actor.Exit(150), 69 for a library failure.
If the VM itself is killed by a signal, gogo run exits 128 plus the
signal’s number, as a shell does (130 for Ctrl-C, 137 for kill -9).
Those statuses overlap the user range 100..255, so a script that must
tell them apart should keep its own codes below 128. The host VM
build/gogovm exits with the same statuses (it is where they come
from).
Options:
--fs-root DIR: back/flashwithDIR/flash(created if missing) and/sdwithDIR/sd(only if it exists). Without it there is no storage. Programs stay inside those directories: symlinks in them are not followed (opening one, or a path through one, isBadPath;ReadDirlists it as a file), and neither are FIFOs or devices. On a host file system that ignores case (macOS by default) the media ignore case too. The VM programbuild/gogovmalso takes--fs-quota BYTES(tests only): each medium may then hold that many bytes of files, counting what is already there; deletes give room back, andfs.Usagereports (used, quota). See section 16.5. And it takes--without NAME,...(tests only): the named drivers and mounts (kbd,tls,/sd, …) are left out of the host board, as on a firmware built without them.--host-net(orGOGO_NET=hostin the environment, whichgogo runpasses on) makes thetcpandtcp_listenports use the host’s real sockets (chapters 10.1 and 20).--key c=pin: in a terminal, pressing the charactercpresses the simulated GPIO inputpin(the level goes to 0, then back to 1). Up to 16 keys.--actor-memory,--memory,--max-actors,--max-ports,--max-links,--bytes-handles: the VM’s limits, passed togogovmas they are (the next section).gogo run --actor-memory 16K --memory 160K --max-actors 1024 --max-ports 16 --max-links 8 --bytes-handles 64/16 progrunsprogwith a board’s limits (tests/golden/board_limitschecks it against the board build,build/gogovm_mcu); all six, since the host’s tables are sized from them.
Standard input feeds the simulated hardware:
-
If it is not a terminal (a file or a pipe), it is a script, read one line at a time whenever the VM is idle and a port that can produce events is open:
Line Meaning <pin> <0|1>a GPIO input changes level key <name>a key press and release ( kbdport)keydown <name>,keyup <name>press or release only, for modifiers battery <mV> <charging> <external>a battery sample ( powerport)imu sample <gx> <gy> <gz> <ax> <ay> <az>,imu gesture <kind> [value]IMU data ( imuport, chapter 15)ir rx <us> <us> ...a received infrared frame ( ir_rxport, chapter 15)mic tone <hz> <ms>,mic silence <ms>microphone input ( micport, chapter 16)sleep <ms>pause before the next line Unknown lines are reported on standard error and skipped. Key lines are dropped while no
kbdport is open. At the end of the script no more input can arrive, so an idle program can end. -
If it is a terminal,
--keycharacters drive GPIO pins and, while akbdport is open, other keys become key presses. Ctrl-D ends the input; Ctrl-C stops the program (and restores the terminal).
Output. println writes to standard output. Crash reports and the
simulated GPIO outputs (gpio: pin 5 = 1) go to standard error.
The VM. gogo run uses the first of: $GOGO_VM; gogovm (or the
release asset name gogovm-<os>-<arch>) in the directory of the gogo
executable, symlinks resolved; build/gogovm in the gogo source tree
around the gogo executable or the current directory. If none is found
it says so and what to do. gogo env prints the one it would use.
Environment. GOGO_VM names the VM to use (above). GOGOPATH is the
package search path of the build. GOGO_CONFIG names the configuration file that
sys.Config reads (default ~/.gogo/config). GOGO_UNIX_TIME_MS starts
the wall clock (sys.Time, chapter 10.8) at that Unix time in ms instead of
the computer’s clock; 0, or a time earlier than the VM’s build, starts it
unknown, as on a board.
There is no network on the host (chapter 10).
gogovm
The host VM: it runs one image, as gogo run does after building it
(gogo run finds it and passes it its flags), and is what a script or a
server runs directly.
gogovm [flags] <file.ggb> [args...] run an image; args are the program's (sys.Args)
gogovm [flags] --info print the VM's parameters as this run would resolve them
gogovm -h | --help list the flags
gogovm --sizeof-actor | --sizeof-net | --has-tls build facts (alone)
Flags come before the image; everything after it is the program’s. An unknown flag is a usage error (exit 1).
The VM’s parameters. Each is also a config key (chapter 11.3) and a
field of an embedding host’s gogo_config (chapter 18.3); the flag beats
the key, the key beats the default, the same rule on every platform. A
value past the most is cut to it with one line on standard error (gogo: vm.actor_memory 2G is over this VM's 1G; using 1G); a flag that is not
a number, or has no value, is a usage error. SIZE is bytes, with an
optional K, M or G; --memory 0 is no limit (it undoes a
vm.memory key). gogovm answers its parameter flags in its config store,
as typed: a program’s sys.Config("vm.actor_memory") sees what was asked
(8G), not what the VM clamped it to (1G; actor.Limit tells that).
Ports and actors share the 65536 PID slots: ports past what the actors
leave are cut, with a line when you gave them. If the VM cannot start
with the parameters (out of memory), it names the config keys that
changed them and starts without them (the flags kept); a flag that
cannot fit is an error (exit 1).
| Flag | Key | Default (a board’s) | Most | Bounds |
|---|---|---|---|---|
--actor-memory SIZE | vm.actor_memory | 1M (16K) | 1G (256K) | an actor’s memory (heap, stack, mailbox) unless SpawnOpt sets it; at least 1K |
--memory SIZE | vm.memory | no limit (160K) | none (160K) | all actors together |
--max-actors N | vm.max_actors | 16384 (1024) | 61440 | live actors at once (the PIDs above are node links’ remote ones) |
--max-ports N | vm.max_ports | 1024 (16) | 2048 | ports open at once; actors + ports at most 65536 |
--max-links N | node.max_links | 512 (8) | 2048 | node links of distributed actors (chapter 20); at most the ports, and on a board what fits a quarter of its memory |
--bytes-handles N[/M] | vm.handles | 4096/256 (64/16) | 65535 (1024) | off-heap Bytes, in the VM and (M) per actor |
code.mem | 16M (64K) | 4G - 1 | loaded module code (chapter 14) |
gogovm --info prints them as the run would have them, one line of
name=value fields, the format of gogo device info’s limits line:
$ gogovm --info
actor_memory=1M memory=unlimited max_actors=16384 max_ports=1024 max_links=512 code_mem=16M bytes_handles=4096/256
$ GOGO_CONFIG=my.cfg gogovm --actor-memory 4M --info
actor_memory=4M memory=2G max_actors=16384 max_ports=1024 max_links=512 code_mem=16M bytes_handles=4096/256
(the second with vm.memory=2G in my.cfg).
Other flags.
| Flag | Meaning |
|---|---|
--fs-root DIR | /flash from DIR/flash (created), /sd from DIR/sd if it exists (above) |
--key C=PIN | in a terminal, the character C presses the simulated GPIO input PIN (0..63; repeatable) |
--screen ansi|text|none | how the screen port shows its grid: ANSI on the terminal, a text dump of every frame, or nothing (default: ansi on a terminal, else text) |
--host-net | the tcp and tcp_listen ports use the host’s sockets (GOGO_NET=host likewise): a real network peer, such as a server node (chapter 20) |
--net-fd N | file descriptor N (inherited, a socketpair end) is the simulated network link; not with --host-net |
--sim-clock | time moves only when the network simulator says so (needs --net-fd) |
--without NAME,... | tests: leave the named drivers (kbd, tls, …) and mounts (/sd) out of the board |
--fs-quota BYTES | tests: each medium may hold BYTES of files (section 16.5) |
Environment.
| Variable | Meaning |
|---|---|
GOGO_CONFIG | the config store, one key=value a line (default ~/.gogo/config): sys.Config, and the VM’s keys above |
GOGO_NET=host | as --host-net |
GOGO_UNIX_TIME_MS | start the wall clock at that Unix time in ms (0: unknown, as on a board) |
GOGO_TLS_CA_FILE | the PEM file of trusted certificates for the tls port (default the system bundle; chapter 17.6) |
GOGO_TLS_BUNDLE_FILE | tests: trust anchors from an ESP-IDF certificate bundle, with the firmware’s rule |
GOGO_TLS_STATS | when set, one tls-stats ... line on standard error at exit |
Exit status is gogo run’s (above): 0 when main ends normally, 1
for a usage error or no memory at boot, 2 for a bad image, 3 for an image
that requires what this VM lacks, 4 when main crashes, and main’s own
code from 64.
gogo env
gogo env [-path dirs]
Prints the version, the package search path (where it comes from:
$GOGOPATH, $HOME/gogo when GOGOPATH is unset, or -path) and the VM
gogo run would use, with where it was found:
$ gogo env
version v0.4.0 (image format 15.4)
GOGOPATH /home/you/gogo ($HOME/gogo, GOGOPATH is unset)
search 1. the build root (imports starting with its directory's name)
2. /home/you/gogo
gogovm /usr/local/bin/gogovm (next to gogo)
A VM that cannot be found is reported on the gogovm line, and the exit
status is still 0.
gogo dis
gogo dis <file.ggb>
Prints the bytecode of an image, function by function. Useful to see what the compiler made of your code, or to compare two builds:
$ gogo build docs/book/examples/02-hello -o hello.ggb
$ gogo dis hello.ggb
func main (params=0 regs=4):
0000 LOADK r1, "hello, gogo"
0002 LOADK r2, 42
0004 LOADK r3, true
0006 BUILTIN r0, r1, 3, PRINTLN
0008 LOADK r0, nil
0010 RET r0
The VM is register based: each function has a fixed number of registers, which live in a stack frame in the actor’s memory.
gogo info
gogo info [-path dirs] <file.ggb|dir|file.gg>
Says what an image is and what it needs, read from the image file: its
format version (major.minor, the lowest the program needs, so the
oldest firmware that runs it), its size, the drivers and mounts it
requires (what a firmware must have to boot it, or to code.Load it as
a module), and its entries (the exported functions code.Spawn starts by
name; (boot) marks the one a board starts):
$ gogo info examples/netdemo
format 15.0
size 46112 bytes: 94 functions, 58 types, 9605 code words, 1462 constant words
requires gpio, netif, tcp, tcp_listen, udp
optional tls (gogo/http)
entries main (boot)
Given a directory or a .gg file, it builds it in memory first (-path
as for gogo build) and adds the optional line: the drivers the
program’s packages mark //gogo:optional (with the packages that do),
which the image does not record because a firmware without them runs it
anyway. A file that is not a gogo image, is damaged, or has a format
this gogo does not know is an error.
gogo flash
gogo flash [-port P] [-esptool path] [-path dirs] [-no-usb-reset] <app.ggb|dir|file.gg>
Writes an image to the board’s program partition at 0x210000, with a
header and a CRC that the firmware checks at boot. Given a directory or a
.gg file it builds it first, as gogo run does (to a temporary image;
-path as for gogo build), so gogo flash ./app is gogo build and
gogo flash in one step. Needs the board’s gogo firmware to be installed
already (chapter 2).
-port P: the serial port. Default: the only board port, a/dev/cu.usbmodem*on macOS, a/dev/ttyACM*on Linux (one whose USB device sysfs shows is not Espressif’s, vendor id 303a, is left out); with none or several,gogo flashstops and asks for-port. Windows has no default: pass-port COM5.-esptool path: the esptool to run. Default:esptooloresptool.pyfromPATH(. ~/esp/esp-idf/export.shputs it there).-no-usb-reset: no automatic USB reset when esptool fails on a silent board (above).
gogo flash refuses files that are not gogo images, images of another
format version (rebuild it with gogo build) and images over the 1 MB
partition.
gogo push
gogo push [-port P] [-timeout seconds] [-no-usb-reset] <file.ggb> [/flash/path]
Copies an image (a module, chapter 14) to the board’s /flash, over the
serial console while the board runs: to /flash/<file name>, or to the
path given (its directory must exist; names as in chapter 9). The board
writes it under a temporary name, reads it back, checks its length and
CRC-32, and only then renames it over the target, so the target is
either the old file or the whole new one. Any failure, a refused chunk,
a mismatch, the cable pulled, leaves the target as it was. The temporary
file is .gogo-push in the target’s directory (which is why that name
cannot be a target); a push cut off by a pulled cable leaves it there,
taking space and listed by fs.ReadDir, until the next push into that
directory.
-port P: as forgogo flash.-timeout seconds: how long to wait for each answer of the board (default 5). A board that does not answer is reset (above) and the push starts over once.
It refuses a file that is not an image of a format this gogo knows,
and a path outside /flash. A firmware older than gogo push answers
that it has no push. Only one program can have the serial port open:
close gogo monitor first.
gogo monitor
gogo monitor [-port P] [-timeout seconds] [-until text] [-reset] [-no-usb-reset]
Copies the board’s console to standard output.
-timeout seconds: stop after this long (default 10; fractions such as0.5are fine).-tis its old name: it still works in this release, with a note on standard error, and goes away in the next.-until text: stop after the first line containingtext, e.g.-until "gogo: vm exited".-reset: reset the board first, so the capture starts at boot. Without it, opening the port never resets the board.-port P: as forgogo flash.-no-usb-reset: when nothing arrived, do not check the USB link and reset it (above).
It is not interactive. Only one program can have the serial port open, so
stop gogo monitor before gogo flash or gogo config.
gogo firmware
gogo firmware (-board sticks3|cardputer | -port P [-esptool path] [-no-usb-reset]) [-o dir] [-build] [-with list] [-without list] [-component dir]... files...
Chooses which optional parts the firmware needs to contain for a set of
images and modules, so a build does not carry a network stack or an SD
driver nobody uses. It reads the requirement names each file carries
(what gogo build writes), maps each to the feature that builds it, and writes
<dir>/sdkconfig.gogo, a list of CONFIG_GOGO_* lines, then prints the
idf.py command that builds with it. It never flashes.
- Feature names:
net kbd power sd exfat cjk imu irtx irrx mic speaker tls screen node float ble bleprov. The requirement names they build:netthe driversnetif,udp,tcpandtcp_listen;kbd,power,imu,mic,speaker,tls,screen,node(distributed actors, chapter 20) andble(Bluetooth LE, chapter 23) the driver of the same name;irtxandirrxthe driversir_txandir_rx;sdthe mount/sd(appendix F);floatthe requirementfloat(floating point in the VM andgogo/math).gpioand/flashare in every firmware; any other name is an error unless a driver component given with-componentprovides it.net,kbd,powerandfloatare on only when a file requires them (or-withadds them). The others are on by default on boards that have them:sd,imu,irtx/irrx(the infrared sender and receiver),mic/speaker,tls(the TLS client, chapter 17),nodeandblecan be required too, so a file that needs one keeps it on, whileexfat(exFAT media) andcjk(the Chinese font) are not.irtxandirrxshare one firmware switch, as domicandspeaker, so they go on and off together.blealso brings its ESP-IDF settings (Bluetooth and NimBLE,sdkconfig.ble);-without bleleaves Bluetooth out of the firmware altogether.bleprov(Wi-Fi setup from a phone over Bluetooth, section 2.1) is on by default withblewhenevernetis on; no program requires it, and it needs bothbleandnet(notkbd: the Cardputer’s setup key is read without the keyboard driver).-without bleprovkeeps thebleport and drops the setup mode. -with a,badds features.-without a,bremoves them; a feature that a file requires cannot be removed (error).exfatgoes off withsd,tls,nodeandbleprovwithnet, andbleprovwithble.- A required feature the board lacks is an error that names it, for example
kbdorsdon thesticks3. -boardnames the board. Instead,-port Pasks the board on that port: one read-only esptool command (chip-id;-esptoolas forgogo flash) reads its chip, and an ESP32-S3 with embedded PSRAM is the M5StickS3, one without is the Cardputer ADV (asgogo setupdecides). The board resets afterwards and runs its program again.-no-usb-resetas forgogo flash.-component dir(repeatable) builds an ESP-IDF component of your own into the firmware: a driver ongogo.hthat registers itself withGOGO_BOARD_PORT(chapter 22). The directory has the component’sCMakeLists.txtand agogo-driver.jsonnaming the requirement names it provides,{"format": 1, "ports": ["acme.dice"]}, which then satisfy the images’ requirements. The tool turns onCONFIG_GOGO_BOARD_PORTS(the firmware’s host-port layer) and passes the directories toidf.pyasEXTRA_COMPONENT_DIRS; without-componentboth are off again. A component’s name is its directory’s, so two components may not share one, and none may be calledmain,driveror like one of gogo’s or ESP-IDF’s components (a list built into the tool, plus the components of an ESP-IDF at$IDF_PATHor~/esp/esp-idf, so the check holds without ESP-IDF exported); the name takes letters, digits,_and-(acme_dice), and a path may not contain;, a space or$. The json’s names go intoCONFIG_GOGO_BOARD_PORT_NAMES, and the firmware says at boot each one it did not register; with-buildthe tool also checks the linker map and fails for a component that put noGOGO_BOARD_PORTin the firmware (one not linked whole). A name of a built-in driver, or one two components give, is an error.gogo device infolists the registered ports amongprovides.-o dir: the build directory and wheresdkconfig.gogogoes (defaultbuild-fw-<board>).-buildruns the printed command (from the gogo repository root, with ESP-IDF exported, chapter 2).
The tool owns the build directory. ESP-IDF would let an existing
<dir>/sdkconfig override a changed sdkconfig.gogo, so if that file exists
and any CONFIG_GOGO_* value in it differs from the new features, the tool
deletes it and prints a line saying so. If nothing differs it is kept and the
next build stays incremental. A lone - argument is an error.
gogo config
gogo config [-port P | -local] set <key> <value|->
gogo config [-port P | -local] get <key>
gogo config [-port P | -local] list
gogo config [-port P | -local] rm <key>
gogo config [-port P | -local] import [-n | -dry-run] <file|->
gogo config [-port P | -local] export
gogo config keys
gogo config [-port P] scan # deprecated: gogo device scan
gogo config [-port P] stats # deprecated: gogo device stats
Edits the configuration store on the board or in the local file. See
chapter 11 for how the store is chosen, the key rules and the keys gogo
uses (keys prints them; set checks a key under a gogo prefix, and its
value, against that table). scan and stats are gogo device scan and
gogo device stats (below), kept here for this release.
-port P: the board on that serial port.-local: the local file ($GOGO_CONFIG, default~/.gogo/config); setting$GOGO_CONFIGchooses it too. Writing a secret (wifi.password,node.token) there prints a warning that the file is plain text.- Neither: the one board connected. With no board, or several, the
command fails (every operation but
keys), naming the ports found. import <file|->sets every key of akey=valuefile (#comments and blank lines skipped, the value to the end of the line;-is standard input) after checking every line assetdoes; a bad line or a repeated key is reported asfile:lineand nothing is written. It printsset <key>per key (a secret as(set)) andimported N keys to .... On a board, a refused key stops the import and the error names the keys written and not written.-n,-dry-run(import only): check and print what would be set, writing nothing.exportprints the store as a fileimportreads, sorted; secrets are comment lines without their values (# wifi.password=(set, not exported)).
gogo device
gogo device [-port P] info
gogo device [-port P] scan
gogo device [-port P] stats
gogo device [-port P] [-yes] format-flash
gogo device [-port P] usb-reset
Operations on the board itself, over its serial console (usb-reset
excepted):
-
infoshows the firmware the board runs: its version (thegit describeit was built from,devwithout git,-dirtyfor uncommitted changes), the board it was built for, the image format it runs (gogo versionshows the onegogowrites), the VM’s limits as it runs with them (its parameters: the config keys over the board’s defaults, section 6.2; a firmware before them has nolimitsline) and the requirement names it provides (the drivers and mounts an image may require, asgogo infolists them for an image):$ gogo device info firmware gogo v0.3.0 board sticks3 (M5StickS3) image format 15.8 (runs images 15.0 to 15.8) limits actor_memory=16K memory=160K max_actors=1024 max_ports=16 max_links=8 code_mem=64K bytes_handles=64/16 provides gpio netif udp tcp tcp_listen tls node power imu ir_tx ir_rx mic speaker screen /flash floatA firmware older than
info(v0.1.0) says so; its boot line (gogo monitor -reset) has its version. -
scanlists the 2.4 GHz networks the board sees. -
statsprints the board’s network counters, free memory and how full the VM’s fixed tables are, as used/capacity:bytes=N/64(off-heapbytes.Byteshandles, ofvm.handles),ports=N/16(open ports, ofvm.max_ports) andsubs=N/4(net.Subscribeslots). When a port open fails or a tcp write getsDone{-1}, these show whether a table is full. A firmware built withoutnetprints no network counters and nosubs.console_stack_free=N/4096is the least stack the console task (which answers these commands and writesgogo pushfiles) has had free. -
format-flasherases every file on/flash: the board restarts and formats its/flashpartition at the sizefs.flash.sizesets (chapter 9). Nothing else is touched: not the configuration store (Wi-Fi settings stay), not the program, not the firmware; the chip is never erased. It asks you to typeyesfirst;-yesskips the question. -
usb-resetbus-resets the board’s USB device, which brings back a USB link that went silent without restarting the chip or its program (the other operations do it on their own when the board does not answer, unless-no-usb-resetis given; see the start of this chapter). It finds the device from the serial port, refuses any device that is not Espressif’s (vendor id 0x303a) and a port another of your programs has open (programs of root or other users cannot be seen), and waits for the port to come back:$ gogo device -port /dev/cu.usbmodem5101 usb-reset reset USB device 303a:1001 at location 0x05100000 (USB bus reset; the chip keeps running) /dev/cu.usbmodem5101 is backOn macOS it re-enumerates the device through IOKit; on Linux it is the
USBDEVFS_RESETioctl on/dev/bus/usb/BBB/DDD, which needs the udev rule of the known issues; Windows has nousb-reset(replug the board).
-port as for gogo flash. scan and stats were gogo config scan
and gogo config stats, and format-flash was gogo config set fs.flash.format yes and a restart; the old forms still work in this
release, with a note, and go away in the next.
gogo setup
gogo setup [-port P] [-board sticks3|cardputer] [-version vX.Y.Z] [-release-url URL|DIR]
[-esptool path] [-offline] [-skip-wifi] [-new-layout] [-reflash] [-yes] [-dry-run]
[-no-usb-reset]
Takes a board from new to running a program, in six steps (chapter 2 shows a run):
- finds esptool (version 5 or newer) and the board’s serial port
(
/dev/cu.usbmodem*on macOS,/dev/ttyACM*on Linux; with several, it asks); - identifies the board with esptool (letting it detect the chip, and reading the partition table now on the board): an ESP32-S3 with embedded PSRAM is the M5StickS3, one without is the Cardputer ADV; you confirm, and any other chip is refused;
- gets the board’s firmware: downloads it from a release, checks every
file against the release’s
SHA256SUMS(a mismatch stops setup), and caches it in the user cache directory (gogo/release/<sha256>); without a release it builds the firmware locally (below); - asks the firmware on the board for its
info(asgogo device info) and reads the version of the firmware about to be flashed from its app image (gogo.bin’s ESP-IDF app descriptor, which carries the samegit describe). When both are the same release or clean commit and the board matches, it reads the app’s descriptor from the board’s flash too (read-flashof 4 KB at the app’s offset, read-only;infohas no build id) and compares itsapp_elf_sha256with the firmware’s: the same version may be another build (-with,-without,-component). Only for the same build and partition table does it skip the flash:the board already runs gogo <version> (<board>, app <first 4 bytes of the SHA256>); not reflashing (-reflash to flash it anyway). The bootloader is not compared. Otherwise it says why in one line (board firmware unknown (...): no answer, a firmware older thaninfo, adevor-dirtybuild on the board;board runs gogo <x> (<board>), flashing ...; orboard runs gogo <x> (<board>), but another build of it (...)) and flashes the bootloader, partition table and app at the offsets in the firmware’sflasher_args.json, then resets the board with a watchdog reset (the Cardputer ADV does not come back from esptool’s default reset). A local build of uncommitted changes (-dirty) is always flashed; - scans for Wi-Fi networks on the board, and writes the chosen network
and the password (read without echo) like
gogo config set; - flashes a small hello program like
gogo flashand watches the console until it prints.
What it never does. It never erases the chip and never writes a merged
image: esptool only ever runs read-flash, write-flash and version.
The partition table must be at 0x8000. Every write must lie in the
bootloader area (below 0x8000), on the partition table sector or inside an
app partition of the partition table being written, and no write, rounded
out to whole 4 KB flash sectors, may touch a protected range: the NVS
partition (where the board keeps its settings, Wi-Fi included) of the
table being written, of the table now on the board, and of the gogo
partition table (0x9000..0xF000), all three. Setup checks this before it
runs esptool. If the board’s table puts NVS elsewhere than the new one,
or the partition table sector holds data that is not a readable table
(blank flash is fine), setup stops unless -new-layout is given. The Wi-Fi password is never
printed, logged or stored on the computer.
Which release. -release-url (or $GOGO_RELEASE_URL) names the files
of one release: an http(s) URL or a local directory, such as one filled
by gh release download or tools/release.sh. Otherwise -version vX.Y.Z
picks a GitHub release of c4pt0r/gogo; otherwise the release matching
this gogo (gogo version) if that is a release tag (vX.Y.Z, or with
-rcN, -beta.N, -alpha.N), else the latest, pinned to its tag on the
first request so every file comes from one release. Drafts are not
visible to setup until published (platform/esp32s3/README.md).
The assets setup reads are:
| Asset | What |
|---|---|
SHA256SUMS | the SHA-256 of every other asset |
<board>-flasher_args.json | ESP-IDF’s list of files and offsets for the board (sticks3, cardputer) |
<board>-bootloader.bin, <board>-partition-table.bin, <board>-gogo.bin | the files it lists, named <board>-<file name> |
gogo-<os>-<arch>[.exe] | the gogo command, for darwin, linux, windows on amd64, arm64 |
LICENSE, THIRD_PARTY_NOTICES.md, font-licenses.zip, LICENSE-APACHE-2.0.txt | the licenses that go with the binaries (setup does not read them) |
A release’s version is also the C embedding API’s: the tag’s X.Y.Z
(v0.2.0, or v0.2.0-rc1) must equal GOGO_VERSION_MAJOR, _MINOR and
_PATCH in runtime/include/gogo.h (what gogo_version() reports, book
chapter 18), and tools/release.sh refuses the tag otherwise. So every
release bumps them, a firmware-only patch release included.
To try a release layout before publishing it, point setup at the directory, or serve it over HTTP:
tools/release.sh v0.1.0 # build/release/v0.1.0/
gogo setup -release-url build/release/v0.1.0
python3 -m http.server -d build/release 8765 &
gogo setup -release-url http://127.0.0.1:8765/v0.1.0
Local firmware build. With -offline, or when the release cannot be
downloaded (and you agree), setup builds the board’s default firmware
with gogo firmware -build and every feature the board has, into
build/setup-<board> of the gogo source tree. It needs to run inside the
gogo source tree and ESP-IDF v6.1.1 (idf.py on PATH, else
$IDF_PATH/export.sh or ~/esp/esp-idf/export.sh, which it sources).
Options:
-port P,-esptool path: as forgogo flash.-board sticks3|cardputer: skip the board question.-skip-wifi: leave the board’s Wi-Fi settings as they are.-new-layout: flash although the board’s partition table keeps NVS elsewhere than the new firmware’s, or cannot be read. Neither NVS area is written, but the old settings are then not used, and the new firmware (or a later one) may reuse the space where they were.-reflash: flash the firmware even when the board already runs the same version (step 4), without asking the board.-yes: take the default answer to every question, without asking; the Wi-Fi step is then skipped, and a board esptool cannot tell apart needs-board.-dry-run: run only what reads (esptool’s chip check, the download, the board’sinfo, the Wi-Fi scan) and print the esptool commands and settings that would be written, or that the firmware would not be reflashed, without writing anything.-no-usb-reset: no automatic USB reset when esptool cannot reach the chip or the board does not answer itsinfo(start of this chapter; only a device that fails the USB descriptor check is reset, so a new board, whose firmware never answers, is left alone).
On failure setup prints the problem and a fix: line, and stops; it is
safe to run again.
gogo version
Prints the version of gogo (dev unless built by tools/release.sh)
and the image format version it writes.
Building the firmware
The firmware is an ESP-IDF project in platform/esp32s3, built with
idf.py (ESP-IDF v6.1.1). See chapter 2 for the commands and
platform/esp32s3/README.md for build options (GOGO_BOARD,
GOGO_CONSOLE=0, and the CONFIG_GOGO_* feature switches NET, KBD,
BATTERY, SD, FS_EXFAT, FONT_CJK, IMU, IR, AUDIO, TLS) and hardware
details. To choose the
switches from what your programs need, use gogo firmware (above).
gogo setup flashes a prebuilt firmware from a release instead.
Running the book’s examples
make vm && go build -o build/gogo ./cmd/gogo
docs/book/examples/run.sh # all examples
docs/book/examples/run.sh 04-call # one
make test-book does the same. run.sh runs each example the way the book shows (with its input,
fsroot and config files) and compares the output with the
expected.out and expected.err files next to it. An example of several
packages keeps its program in app/ (the build root, so its imports
start with app/); run.sh runs it from there, with an empty search
path.
Checking a change to gogo
make test is the full check before a commit. Besides the C and Go
tests, it runs:
make lint:gofmton every.gofile and on every.ggfile (gogo source is Go syntax, butgofmtreads only.go, sotools/lint.shchecks a.gocopy of each),go vet ./..., andshellcheckontools/*.shwhen it is installed. To format a.ggfile, format a.gocopy (or usegofmton standard input:gofmt < f.gg > f.tmp && mv f.tmp f.gg).make test-examples: every program inexamples/andplatform/esp32s3/examples/must build (the board-only ones too: building needs no board), and the ones with anexpected.outrun withgogo runand must print it (tools/examples.sh, which reads the sameinput,config,fsroot,mods/andexpected.errfiles as the golden tests). A new example without anexpected.outis still built on every run. An example of several packages keeps its program inapp/(withapp/expected.out); a.ggfile besideapp/is a script, run when a<name>.expected.outis beside it; and a filegogopathnames the example’sGOGOPATH, relative to the example (examples/packagesuses all three).make test-book: every example in this book, throughdocs/book/examples/run.sh(above).make site-check: builds the website (make site: this book through mdBook, and the landing pagesite/index.html, intobuild/site) and checks that every link and anchor in it resolves (tools/sitecheck); skipped whenmdbookis not installed.make vmsize(andnetsize,vfssize,screensize,floatlibsize): the code size of the VM core and of each runtime part as linked into the ESP32-S3 firmware (the firmware’s flags, a relaxed--gc-sectionslink from the part’s API), against their budgets (skipped without the ESP-IDF compiler);tools/vmsize.sh --objectsgives the older, unlinked sum.vmsizealso prints the VM core’s lines of C;tools/vmsize.sh --recordappends the size and the line count todocs/vmsize-history.csv, andtools/vmsize.sh --no-floatmeasures the core without floating point.
Outside make test: make test-lib (the standard library on the host
Go toolchain, also part of go test ./...) and make test-tls-asan
(the network and TLS tests under AddressSanitizer). The test workflow,
.github/workflows/test.yml, runs all three on macOS and Linux
(x86-64) once a day and when started by hand (Actions > test > Run
workflow). The TLS tests need mbedTLS’s
source (ESP-IDF’s components/mbedtls/mbedtls; MBEDTLS_DIR names
another copy) and are skipped without it; the workflow fetches the
commit ESP-IDF v6.1.1 pins.
13. Appendices
A. Library quick reference
The authoritative definitions are the package sources in the gogo tree,
one directory per package under lib/ (lib/actor/, lib/port/,
lib/bytes/, lib/net/ for gogo/net, and so on; lib/README.md lists
them all); their comments give every detail.
gogo/actor
type PID struct{ /* opaque; comparable */ }
type Ref struct{ /* opaque; comparable */ }
type Reason struct{ Code int; Func string }
type Options struct{ MaxMemory int } // bytes; 0 = platform default
type ProcInfo struct{ Memory int }
type ExitMsg struct{ From PID; Reason Reason }
type DownMsg struct{ Ref Ref; From PID; Reason Reason }
type Request struct{ From PID; Ref Ref; Body any }
var NoPID PID // the zero PID, also actor.PID{}: names no actor (read-only)
func Spawn(f func()) PID
func SpawnLink(f func()) PID
func SpawnOpt(f func(), opts Options) PID
func Self() PID
func Send(to PID, msg any)
func Receive() any
func ReceiveTimeout(ms int) (msg any, ok bool)
func Call(to PID, req any, timeoutMs int) (reply any, err error) // Timeout, NoProc, NoConnection
func Reply(req Request, reply any)
func Link(p PID)
func Unlink(p PID)
func Monitor(p PID) Ref
func Demonitor(r Ref)
func TrapExit(on bool)
func Exit(code int)
func Kill(p PID, code int)
func MakeRef() Ref
func Register(name string, p PID) error // NoProc (p not alive), Exists (name taken)
func Whereis(name string) (PID, bool) // a local table lookup: ok, no error
func Unregister(name string)
func SendAfter(to PID, msg any, ms int) Ref
func CancelTimer(r Ref) bool
func Sleep(ms int)
func Now() int64
func Info(p PID) ProcInfo
func Limit(p PID) int // p's memory limit in bytes (image format 15.8)
func Fail(code errors.Code) int // the exit reason Failed + int(code)
gogo/supervisor
const (Permanent = 0; Transient = 1)
type Spec struct{ Restart, MaxRestarts, PeriodMs int }
func Supervise(child func(), spec Spec) actor.PID
func SuperviseModule(m code.Module, entry string, arg any, spec Spec) actor.PID
type Upgrade struct{ Module code.Module } // actor.Call(sup, Upgrade{m}, ms): 0 is ok
gogo/code
type Module struct{ H int; missing string } // H == 0: none
type Err int // OK, BadImage, Unsupported, NoMemory, NotFound, BadArg, TooMany, BadVersion
func Load(b bytes.Bytes) (Module, Err)
func Spawn(m Module, entry string, arg any) (actor.PID, Err)
func SpawnLink(m Module, entry string, arg any) (actor.PID, Err)
func SpawnOpt(m Module, entry string, arg any, opts actor.Options) (actor.PID, Err)
func Hold(m Module) Err
func Release(m Module)
func Missing(m Module) string // after Unsupported: the missing driver or mount
func MemUsed() int
Chapter 14 describes them.
gogo/port
// the stream protocol of every byte port (tcp, tls, imu, ir, mic, speaker, screen)
type Chunk struct{ From actor.PID; Seq, TimeMs, Dropped int; Data bytes.Bytes } // event: input
type Out struct{ Data bytes.Bytes } // command: send Data (2 in flight)
type Done struct{ From actor.PID; Seq int } // event: an Out finished (Seq -1: not sent)
type Closed struct{ From actor.PID; Reason int } // event: the port ended by itself
// embed mode
type Host struct{ Arg int; Data bytes.Bytes } // cfg of a host-defined port
type Post struct{ From actor.PID; Kind int; Data bytes.Bytes } // a message from the embedding host
func Open(driver string, cfg any) (p actor.PID, err error)
func Close(p actor.PID)
func Handoff(p actor.PID, to actor.PID) (ok bool)
gogo/gpio
type Config struct{ Pin, Mode, Edge, DebounceMs int } // cfg of "gpio"
type Write struct{ Value int } // command
type Edge struct{ Pin, Value int } // event
const (Input = 0; InputPullUp = 1; InputPullDown = 2; Output = 3)
const (None = 0; Rising = 1; Falling = 2; Both = 3)
gogo/errors
type Code int // OK (0), a shared code (1..35), or a package's own (>= 100)
const (OK = 0; NotFound = 1; Exists = 2; NoMemory = 3; TooMany = 4; Busy = 5; BadArg = 6;
Closed = 7; IO = 8; Timeout = 9; Unsupported = 10; NoSpace = 11; BadPath = 12; IsDir = 13;
NotDir = 14; NotEmpty = 15; NotMounted = 16; BadImage = 17; Refused = 18; Reset = 19;
NoRoute = 20; BadCert = 21; NoTime = 22; TLS = 23; Overflow = 24; BadURL = 25;
BadFormat = 26; BadVersion = 27; NoProc = 28; NoConnection = 29)
Appendix C lists who uses which. gogo/http’s Upload and
ClientUpload and gogo/sound’s Recorded.Err and Played.Err are
errors.Code.
gogo/bytes
func NewBuffer(capacity int) Buffer
func FromString(s string) Bytes
func FromSlice(p []byte) Bytes
func (b Buffer) WriteString(s string)
func (b Buffer) Write(p []byte)
func (b Buffer) WriteByte(c byte)
func (b Buffer) WriteBytes(x Bytes)
func (b Buffer) Len() int
func (b Buffer) Freeze() Bytes
func (x Bytes) Len() int
func (x Bytes) At(i int) byte
func (x Bytes) Slice(lo, hi int) Bytes
func (x Bytes) String() string
func (x Bytes) Equal(y Bytes) bool
func (x Bytes) CopyTo(p []byte) int
(These are the only methods in the subset: the compiler turns them into VM builtins.)
gogo/strings and gogo/strconv
func strings.Index(s, sub string) int
func strings.IndexByte(s string, c byte) int
func strings.Cut(s, sep string) (before, after string, found bool)
func strings.HasPrefix(s, prefix string) bool
func strings.HasSuffix(s, suffix string) bool
func strings.TrimSpace(s string) string // ASCII white space
func strings.ToLower(s string) string // ASCII letters
func strings.EqualFold(s, t string) bool // ASCII letters
func strings.Split(s, sep string) []string // sep "" splits into bytes
func strconv.Itoa(i int) string
func strconv.Atoi(s string) (n int, err error) // errors.BadFormat, errors.Overflow (n clamped)
func strconv.FormatInt64(i int64, base int) string // "" for a bad base
func strconv.ParseInt64(s string, base int) (n int64, ok bool) // no base 0, no _
func strconv.FormatUint(i uint64, base int) string // "" for a bad base
func strconv.ParseUint(s string, base, bitSize int) (n uint64, err error) // bitSize 0: 32
func strconv.ParseInt(s string, base, bitSize int) (n int64, err error) // bitSize 0: 32
gogo/kbd and gogo/power
type kbd.Config struct{ RepeatDelayMs, RepeatMs int }
type kbd.Key struct{ Code, Char, Mods int; Down bool }
const (kbd.ModCtrl = 1; ModShift = 2; ModAlt = 4; ModOpt = 8; ModFn = 16)
// key codes: Enter 0x28, Esc 0x29, Backspace 0x2A, Tab 0x2B, Space 0x2C,
// F1..F12 0x3A..0x45, Delete 0x4C, Right 0x4F, Left 0x50, Down 0x51,
// Up 0x52, LeftCtrl 0xE0, LeftShift 0xE1, LeftAlt 0xE2, Opt 0xE3, Fn 0xF0
type power.Config struct{ PeriodMs int }
type power.Battery struct{ MilliVolts, Pct, Charging, External int }
type power.Read struct{}
gogo/fs, gogo/kv, gogo/ringlog
type fs.File actor.PID
type fs.Err = errors.Code
type fs.Info struct{ Size int; IsDir bool }
type fs.Space struct{ Used, Total int }
const (fs.Read = 0; fs.Write = 1; fs.Append = 2)
func fs.Open(path string, mode int) (File, Err)
func (f File) Read(max int) (bytes.Bytes, Err)
func (f File) Write(data any) Err // string, bytes.Bytes or []byte
func (f File) WriteAt(off int, data any) Err // Write-mode files, inside the file only
func (f File) Sync() Err
func (f File) Size() (int, Err)
func (f File) Close()
func fs.ReadFile(path string, max int) (bytes.Bytes, Err)
func fs.WriteFile(path string, data any) Err
func fs.Stat(path string) (Info, Err)
func fs.ReadDir(path string) ([]string, Err)
func fs.Mkdir(path string) Err
func fs.Remove(path string) Err
func fs.Rename(from, to string) Err
func fs.Usage(prefix string) (Space, Err)
const kv.MaxValue = 4096
func kv.Get(key string) (bytes.Bytes, fs.Err)
func kv.Put(key string, v any) fs.Err // string or bytes.Bytes
func kv.Delete(key string) fs.Err
func kv.Keys() ([]string, fs.Err)
func ringlog.Append(dir string, maxBytes int, line any) fs.Err
func ringlog.Read(dir string, max int) (bytes.Bytes, fs.Err)
gogo/net, gogo/dhcp, gogo/dns, gogo/http
// port configs
type net.IfConfig struct{}
type net.UDP struct{ Port int }
type net.Dial struct{ IP, Port, TimeoutMs int }
type net.DialTLS struct{ IP, Port, TimeoutMs int; Host string } // "tls"
type net.Listen struct{ Port int }
// commands
type net.SetAddr struct{ IP, Mask, Gateway, DNS int } // to "netif", owner only
type net.SendTo struct{ Addr Addr; Data bytes.Bytes } // to "udp"
// to "tcp" or "tls": port.Out{Data}, answered by port.Done
type net.Shutdown struct{}
type net.Resume struct{}
// events
type net.Up struct{ IP, Gateway, DNS int }
type net.Down struct{}
type net.Datagram struct{ From Addr; Data bytes.Bytes }
type net.Connected struct{}
// from "tcp" or "tls": port.Chunk, port.Done, port.Closed{From, Reason}
type net.Accepted struct{ Conn actor.PID }
type net.Addr struct{ IP, Port int }
func net.Subscribe() (ok bool)
type dhcp.Config struct{ TimeoutMs int }
func dhcp.Start(cfg Config) error
func dns.Lookup(name string, timeoutMs int) (int, error)
type http.Header struct{ Name, Value string }
type http.Request struct{ Method, Path string; Headers []Header; Body bytes.Bytes }
type http.Response struct{ Status int; Headers []Header; Body bytes.Bytes; Truncated bool }
const (http.MaxBody = 8192; MaxBodyLimit = 65536; MaxHead = 2048;
ReadTimeoutMs = 10000; DefaultTimeoutMs = 10000; ListenFailed = 69) // actor.Fail(errors.Busy)
func http.Get(url string, timeoutMs int) (Response, error)
func http.Post(url, contentType string, body bytes.Bytes, timeoutMs int) (Response, error)
func http.Do(method, url, contentType string, body bytes.Bytes, maxBody, timeoutMs int) (Response, error)
func http.HeaderValue(h []Header, name string) (string, bool)
func http.Serve(port int, handler func(Request) Response) actor.PID
// chapter 17: https://, keep-alive, upload
type http.Client struct{ PID actor.PID }
const (http.BadURL = errors.BadURL; TLSMemory = 26624;
UploadChunk = 4096; LingerMs = 1000; MaxQueued = 4)
func http.NewClient() Client
func http.ClientDo(c Client, method, url, contentType string, body bytes.Bytes, timeoutMs int) (Response, error)
func http.ClientUpload(c Client, url, path, contentType, token string) (status int, err errors.Code)
func http.CloseClient(c Client)
func http.Upload(url, path, contentType, token string) (status int, err errors.Code)
gogo/node
type Options struct{ Name, Token string; TimeoutMs int }
type Up struct{ Node string } // to Subscribe-rs
type Down struct{ Node string }
const DefaultPort = 4370
func node.Listen(port int, name string) error // the server node (host VM: GOGO_NET=host)
func node.ListenOpt(port int, opts Options) error
func node.Connect(addr, name string) error // "a.b.c.d[:port]"; token: config node.token
func node.ConnectOpt(addr string, opts Options) error
func node.Disconnect()
func node.Register(name string, p actor.PID) error // reachable from other nodes; errors.Exists
func node.Unregister(name string)
func node.Whereis(node, name string, timeoutMs int) (actor.PID, error) // NotFound, Closed, Timeout
func node.Nodes() []string
func node.Self() string
func node.Subscribe()
Chapter 20 describes it.
gogo/ble
type UUID string // "180f" (UUID16) or "6e400001-b5a3-f393-e0a9-e50e24dcca9e"
type Characteristic struct{ UUID UUID; Flags int } // Read | Write | WriteNoResp | Notify
type Service struct{ UUID UUID; Chars []Characteristic }
type Config struct{ Name string; Services []Service }
type Connected struct{ Peer string; MTU int } // events: ble.Event(post)
type Disconnected struct{ Reason int }
type Written struct{ Char int; Data bytes.Bytes }
type Subscribed struct{ Char int; On bool }
type MTUChanged struct{ MTU int }
func ble.UUID16(v int) UUID
func ble.Open(cfg Config) (actor.PID, error) // BadArg, TooMany, Busy, NotFound
func ble.SetValue(p actor.PID, char int, data bytes.Bytes) // what a phone's read returns
func ble.SendNotify(p actor.PID, char int, data bytes.Bytes) // answered with port.Done
func ble.Event(m port.Post) (ev any, ok bool)
func ble.MaxNotify(mtu int) int // mtu - 3
Chapter 23 describes it.
gogo/sys and gogo/sntp
func sys.Config(key string) (value string, ok bool) // the configuration store
func sys.Args() []string // the program's arguments, without its name; empty on a board
func sys.Time() int64 // Unix time in ms (UTC); 0: unknown
func sys.SetTime(ms int64) bool // false: earlier than the build, refused; ms <= 0 forgets
func sys.Random() int // 30 random bits
func sntp.Sync(server string, timeoutMs int) error // sets sys's clock; timeoutMs <= 0: 5000
func sntp.Now() int64 // sys.Time()
Chapter 10.8 describes them. The packages for the motion sensor, infrared
and audio (gogo/imu, gogo/ir, gogo/audio and the libraries built on
them) are described in chapters 15 and 16.
B. Exit reasons
| Code | Constant | Crash report | Cause |
|---|---|---|---|
| 0 | actor.Normal | (none) | the entry function returned |
| 1 | actor.Killed | killed | actor.Kill(p, actor.Killed); cannot be trapped |
| 2 | actor.OutOfMemory | oom | over the actor’s limit (also deep recursion), or the VM is out of memory |
| 3 | actor.MailboxOverflow | mailbox_overflow | queued messages took the receiver over its limit |
| 4 | actor.NoProc | noproc | linked to an actor that does not exist |
| 5 | actor.DivZero | divzero | / or % by zero |
| 6 | actor.BadCode | badcode | index or slice out of range, nil function value called, unusable zero Buffer, a bad image |
| 7 | actor.Shutdown | (none) | asked to stop; supervisors use it |
| 8 | actor.BadShift | badshift | negative shift count |
| 9 | actor.BadMsg | badmsg | sent a message holding a module’s own struct or closure to an actor of another module (the sender exits; chapter 14) |
| 10 | actor.Panic | panic | panic(v) (which first prints panic: v on standard error) |
| 11 | actor.NoConnection | noconnection | the node of a linked or monitored remote actor became unreachable (chapter 20) |
| 12 | actor.Nil | nil | a nil pointer dereference: a field read or write, or *p, of a nil pointer; a write to a nil map |
| 13..63 | kept for the VM | ||
| 64..99 | actor.Failed + a shared code | exit(<code>) | a library’s failure: actor.Failed (64) plus a shared code, 1..35 (appendix C); actor.Fail(code) gives it; http.ListenFailed is 69, actor.Fail(errors.Busy) |
| 100+ | (yours) | exit(<code>) | actor.Exit(code) or actor.Kill(p, code) |
The crash report is gogo: actor <pid N> crashed: <kind>[ in <function>],
on standard error. The reason main exits with is also the exit status of
gogo run and gogovm: 0 for Normal and Shutdown, 4 for a VM reason
(1..63) or a negative code, the code itself for 64..255, and 255 above
that (chapter 12).
C. Error codes
The shared codes (gogo/errors, GOGO_E_* in
runtime/include/gogo_errors.h on the C side): one numbering for every
meaning the packages share. An errors.Code is an error; its Error()
is the text gogo_strerror gives the same code on the C side ("not found", "busy", …), and "error N" for a code without one.
| Range | Codes |
|---|---|
| 0 | OK |
| 1..29 | NotFound=1 Exists=2 NoMemory=3 TooMany=4 Busy=5 BadArg=6 Closed=7 IO=8 Timeout=9 Unsupported=10 NoSpace=11 BadPath=12 IsDir=13 NotDir=14 NotEmpty=15 NotMounted=16 BadImage=17 Refused=18 Reset=19 NoRoute=20 BadCert=21 NoTime=22 TLS=23 Overflow=24 BadURL=25 BadFormat=26 BadVersion=27 NoProc=28 NoConnection=29 |
| 30..35 | free for later shared meanings; shared codes stop at 35 so that actor.Failed + a shared code stays below 100 (appendix B) |
| 36..99 | reserved, never shared codes |
| 100 and up | one block of 20 per package that needs its own codes: gogo/http 100..119, gogo/sound 120..139 (neither uses its block yet) |
fs.Err (also returned by kv, ringlog, imulog and wav):
errors.Code under another name, and these codes under the same names.
kv.Put also returns errors.Overflow (24) for a value over 4096 bytes
and errors.BadArg (6) for one that is neither a string nor Bytes;
imulog.Append returns errors.Overflow for a payload over 65535
bytes.
| 0 | 1 | 2 | 3 | 4 | 5 | 7 | 8 | 11 | 12 | 13 | 14 | 15 | 16 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
OK | NotFound | Exists | NoMemory | TooMany | Busy | Closed | IO | NoSpace | BadPath | IsDir | NotDir | NotEmpty | NotMounted |
port.Closed reasons of "tcp" and "tls" (the net constants, plain
ints): the shared codes, with Normal = OK.
| 0 | 9 | 18 | 19 | 20 | 21 | 22 | 23 |
|---|---|---|---|---|---|---|---|
Normal (peer finished sending) | Timeout | Refused | Reset | NoRoute (address or link lost) | BadCert (the certificate failed verification) | NoTime (the wall clock is not set) | TLS (any other TLS failure) |
code.Err (the result of every gogo/code call): errors.Code
under another name, and these codes under the same names.
| 0 | 1 | 3 | 4 | 6 | 10 | 17 | 27 |
|---|---|---|---|---|---|---|---|
OK | NotFound | NoMemory (over code.mem) | TooMany (module table or holders full) | BadArg | Unsupported (firmware lacks a driver or mount: see Missing) | BadImage | BadVersion (another image format) |
actor.Call’s error (chapter 4.3; remote PIDs, chapter 20.5):
| 9 | 28 | 29 |
|---|---|---|
Timeout (no reply in time) | NoProc (no live local actor: exited, never existed, the zero PID, a port) | NoConnection (a remote PID this node cannot reach: its node is gone, or the PID names nothing here any more) |
actor.Register’s error (chapter 4.4): NoProc (28) if the PID is
not a live local actor (checked first), Exists (2) if the name is
taken.
D. Limits
| Limit | Board (ESP32-S3) | Host |
|---|---|---|
| memory for all actors | 160 KB (vm.memory, at most that) | the computer’s (vm.memory, gogovm --memory) |
| default memory limit per actor | 16 KB (vm.actor_memory) | 1 MB (vm.actor_memory, gogovm --actor-memory) |
| largest memory limit per actor | 256 KB | 1 GB |
| actors at once | 1024 (vm.max_actors) | 16384 (vm.max_actors, gogovm --max-actors; at most 61440, 65520 in libgogo) |
| idle actor | about 150 bytes | about 150 bytes (152 on a 64-bit computer) |
| reductions per time slice | 1000 | 1000 |
| open ports | 16 (vm.max_ports, up to 2048) | 1024 (vm.max_ports or gogovm --max-ports, up to 2048) |
| open files | 4 | 4 |
off-heap Bytes per actor / in the VM | 16 / 64 (vm.handles, up to 1024 in the VM) | 256 / 4096 (vm.handles, gogovm --bytes-handles, up to 65535) |
| loaded module code | 64 KB (code.mem) | 16 MB (code.mem) |
Bytes shared instead of copied | over 64 bytes, from Freeze | same |
| TCP connections | 4 | (no network; GOGO_NET=host: the host’s sockets, up to the ports) |
net.Subscribe subscribers | 4 | (no network) |
| HTTP head / body | 2 KB / 8 KB (client body up to 64 KB with Do) | (no network) |
| TLS connections | 1 (about 23 KB charged to its owner) | (no network) |
| Bluetooth LE | one ble port per board, one phone; 4 services, 16 characteristics (8 per service); values and writes up to 512 bytes; 2 notifications in flight | the same, over a local socket ($GOGO_BLE) |
| distributed actors: frame, links, remote PIDs, remote links and monitors | 4096 bytes, 8, 64, 32 | 4096 bytes, 512, 1072, 1040 (GOGO_NET=host; node.max_links, chapter 20.9) |
| config key / value | 15 chars / 1000 bytes | same |
| file name / path | 32 / 96 bytes | same |
kv value | 4096 bytes | same |
| program image | 1 MB | |
| modules loaded at once (the main program included) | 8 | 8 |
holders per module (code.Hold, the loader) | 4 | 4 |
module code in memory (code.mem) | 64 KB (config key code.mem, K/M suffix) | 64 KB |
E. Differences from Go at a glance
| Go | gogo |
|---|---|
goroutines, channels, select | actors: actor.Spawn, Send, Receive |
| shared memory between goroutines | none; every actor has its own heap |
| sending a slice shares it | Send deep-copies (large frozen Bytes are shared, read-only) |
| closures capture variables by reference | the same within an actor; a spawned closure takes copies of them |
int is 64 bits on most machines | int is always 32 bits |
uint is 64 bits on most machines | uint is 32 bits, like int; int8 .. uint64 as in Go, but not in an any |
complex, uintptr | none |
| maps, random iteration order | maps in key order; sorted slices underneath (O(n) insert); copied when sent |
pointers, &s[i] | pointers copied (with what they point to) when sent; no pointers into slices or fields |
goto | labeled break/continue |
| generics | none |
error, panic, recover | bool/code results; actor.Exit; supervisors; automatic cleanup |
defer anywhere, run on panics too | defer outside loops only, run on normal returns only |
package-level var, init | read-only package-level vars, set at build time; state in actors; no init |
| multiple packages, the standard library | one package main; gogo/... packages only |
fmt.Println | println (prints slices’ elements; Go’s println prints an address) |
UTF-8 aware range over strings | bytes |
go run | gogo run; gogo build + gogo flash |
| runtime panics crash the program | runtime errors end only the actor |
F. Requirement names
The compiler records in every image and module, by name, the drivers and
mounts it needs from the firmware, and float when it uses floating
point (its requirements); a firmware that
lacks one refuses the image at boot, naming it, and code.Load returns
Unsupported with code.Missing naming it (chapter 14). gogo firmware
(chapter 12) picks the firmware switches from the names.
| Name | Required by | gogo firmware feature | Firmware switch |
|---|---|---|---|
gpio | the gpio port | (always built) | |
/flash | (never inferred: every firmware has it) | (always built) | |
netif, udp, tcp, tcp_listen | the network ports, opened by gogo/dhcp, dns, http, sntp or directly with gogo/net | net | CONFIG_GOGO_NET |
kbd | the kbd port (gogo/kbd); gogo/tui opens it but does not require it | kbd | CONFIG_GOGO_KBD |
power | the power port (gogo/power) | power | CONFIG_GOGO_BATTERY |
/sd | a constant /sd path in a gogo/fs call | sd | CONFIG_GOGO_SD |
imu | the imu port (gogo/imu, gogo/imulog) | imu | CONFIG_GOGO_IMU |
ir_tx | the ir_tx port | irtx | CONFIG_GOGO_IR |
ir_rx | the ir_rx port | irrx | CONFIG_GOGO_IR |
mic | the mic port opened directly; gogo/sound opens it for Record but does not require it (//gogo:optional, chapter 12) | mic | CONFIG_GOGO_AUDIO |
speaker | the speaker port opened directly; gogo/sound opens it for Play but does not require it | speaker | CONFIG_GOGO_AUDIO |
tls | the tls port opened directly (net.DialTLS); gogo/http opens it for https:// URLs but does not require it (//gogo:optional, chapters 12 and 17) | tls | CONFIG_GOGO_TLS (needs CONFIG_GOGO_NET) |
screen | the screen port (gogo/screen, gogo/tui; chapter 19) | screen | CONFIG_GOGO_SCREEN |
float | floating point anywhere in the image: a float value, operation or constant, a float32 / float64 type switch case, gogo/math, strconv.FormatFloat / ParseFloat (not the rest of gogo/strconv) | float | CONFIG_GOGO_FLOAT |
node | the node port opened directly; gogo/node opens it (and tcp, tcp_listen) but does not require it (chapter 20) | (with net) | CONFIG_GOGO_DIST (needs CONFIG_GOGO_NET) |
ble | the ble port: any program that imports gogo/ble (its Open, chapter 23) | ble | CONFIG_GOGO_BLE (needs NimBLE: sdkconfig.ble) |
| a host port’s name | port.Open of a port the embedding program defines (chapter 18) | (none: an embedded VM only) |
An import of a system package alone requires nothing: gogo/sys (the wall clock and Random
work on every firmware), gogo/fs on /flash, and the type-only use of
gogo/net or gogo/kbd need no name. A port opened by a name known only
at run time requires nothing (with a compiler warning); the open just
fails on a firmware without the driver.
G. Bytecode reference
For the instruction set itself (every opcode with its number, operands and
effect, the builtins table, the reserved types and the image file layout) see
the generated bytecode reference. gogo dis file.ggb
prints the bytecode of a program, and the design behind it is in
design.md section 5.6.
14. Hot Loading
Until now a board has run the one program you flashed. Hot loading lets a running program load more code while it runs: an actor gets a compiled module (from a file, from the network, or in a message), asks the VM to load it, and starts one of its entry functions in a new actor.
Running code is never changed in place. To upgrade, the old actor exits and its supervisor restarts it with the newly loaded code. The unit of replacement is an actor, and replacement is just a supervised restart.
The package is gogo/code. Its full reference is in
docs/design.md section 5.4.4; its open limitations are in
docs/known-issues.md.
14.1 Modules
Every image is a module. The main program and a loaded module use the same format and are built the same way:
gogo build ./greeter -o greeter.ggb # a module is a .ggb image like any other
A module is an ordinary gogo package main, and may have packages of its
own: built from greeter/, import "greeter/words" is greeter/words/,
then the search path, exactly as for a program (section 3.1.1); they are
compiled into the module, and their struct types are the module’s own
(section 14.6). Its entries are the
exported functions with the signature func() or func(arg any), found by
name (case-sensitive). func main() is exported as the entry main. At
boot the firmware loads the flashed image as module 0 and starts its
main the same way code.Spawn would. gogo info lists a module’s
entries, its format version and what it requires (chapter 12):
$ gogo info greeter.ggb
format 15.0
size 1088 bytes: 2 functions, 0 types, 18 code words, 226 constant words
requires none
entries Greet, main (boot)
// mods/greeter/main.gg
package main
import "gogo/actor"
// Greet is an entry: it tells the PID it was started with who it is.
func Greet(arg any) {
switch host := arg.(type) {
case actor.PID:
actor.Send(host, "hello from a module")
}
}
func main() {}
14.2 Loading and starting
func Load(b bytes.Bytes) (Module, Err)
func Spawn(m Module, entry string, arg any) (actor.PID, Err)
func SpawnLink(m Module, entry string, arg any) (actor.PID, Err)
func SpawnOpt(m Module, entry string, arg any, opts actor.Options) (actor.PID, Err)
func Hold(m Module) Err
func Release(m Module)
func Missing(m Module) string // after Unsupported: the driver or mount the firmware lacks
func MemUsed() int // bytes of module code in use (counted against code.mem)
Err is OK (0), BadImage, Unsupported, NoMemory, NotFound,
BadArg, TooMany or BadVersion, with the numbers of the shared codes
in gogo/errors (appendix C): code.NotFound is 1, as fs.NotFound is. arg is copied into the new actor like a message.
A Module is a plain value you can send to other actors, which can spawn
from it too.
The example examples/14-load reads a module from /flash, loads it,
starts Greet, and then shows the errors and the unload:
b, e := fs.ReadFile("/flash/greeter.ggb", 8192)
m, err := code.Load(b)
println("load:", int(err), "code mem in use:", code.MemUsed() > 0)
p, err := code.Spawn(m, "Greet", actor.Self())
...
Its output (run.sh builds mods/greeter into /flash/greeter.ggb before
running it; section 14.3 puts a module on a board’s /flash):
load: 0 code mem in use: true
spawn Greet: 0 true
hello from a module
spawn greet: 1 NotFound is 1
code mem in use after release: 0
spawn after unload: 1
A wrong entry name (greet is not Greet) is NotFound, not a crash. A
bad or malicious module makes Load return an error; the host is
unaffected.
14.3 Putting a module on the board
On the host, /flash is a directory (gogo run --fs-root, chapter 9),
so a module is copied there like any file. On a board, gogo push
copies it over the USB cable, while the board runs, into the board’s
/flash:
gogo build ./greeter -o greeter.ggb
gogo push greeter.ggb # to /flash/greeter.ggb
gogo push worker_v2.ggb /flash/mods/w.ggb # to another path (the directory must exist)
pushed greeter.ggb to /flash/greeter.ggb (1088 bytes, 0.2 s)
The board writes the file under a temporary name beside the target,
reads it back and checks its length and CRC-32 against what gogo push
announced, and only then renames it over the target, so a program never
reads half a module, and an interrupted or damaged push leaves the old
file as it was. gogo push takes images only (it checks the format
version against its own, so push with the gogo that matches the
firmware). Close gogo monitor first: only one program can use the
serial port. The running program is not told; it finds the new file the
next time it reads it, for example when it next loads the module.
14.4 Lifetime
A module stays loaded while an actor running its code is alive, or while
some actor holds it. code.Load holds it for the caller; other actors
can code.Hold(m) (at most four holders). code.Release(m) or the
holder’s exit ends a hold. When there is neither a live actor nor a hold,
the module is unloaded: its code memory is freed and its handle is
stale. Spawn with a stale handle returns NotFound, also after a new
module took the same slot, and a value that still points into the unloaded
module (a constant string, a function value, a struct of its own type) makes
the actor that uses it exit with BadCode.
The VM holds at most 8 modules, the main program included; a ninth Load
is TooMany.
14.5 Supervised upgrades
gogo/supervisor has a supervisor whose child is a module entry:
sup := supervisor.SuperviseModule(m, "Work", arg, spec)
It holds the module and restarts the child with code.SpawnLink(m, "Work", arg) after a crash. If it cannot start (not loaded, no such entry) it
returns the zero PID. To upgrade, send it supervisor.Upgrade{Module: m2}
with actor.Call; the reply is an int, a code.Err: the supervisor holds
the new module, stops the old child, starts the new one with the same entry
and argument, and releases the old module, which unloads once its last
actor is gone. If anything fails, the old module keeps running and the
reply says why. Messages sent to the old child between its stop and the
new start are lost.
The example examples/14-upgrade: worker_v1 crashes on its third
message, the supervisor restarts it from the module, then the host loads
worker_v2 and upgrades without stopping.
v1 := load("/flash/worker_v1.ggb")
sup := supervisor.SuperviseModule(v1, "Work", actor.Self(),
supervisor.Spec{Restart: supervisor.Permanent, MaxRestarts: 3})
...
v2 := load("/flash/worker_v2.ggb")
code.Release(v1) // the supervisor's hold keeps v1 until the upgrade
r, _ := actor.Call(sup, supervisor.Upgrade{Module: v2}, 2000)
println("upgrade result (0 is ok):", r)
loaded v1: true
worker started
worker v1: message 1
worker v1: message 2
worker v1: crashing
worker restarted from the module
worker v1: message 1
loaded v2, both resident: true
upgrade result (0 is ok): 0
upgraded to v2
v1 unloaded, only v2 resident: true
worker v2: message 1
worker v2: message 2
14.6 Messages between modules
Code never runs across modules, and modules do not share types. When the sender and the receiver belong to different modules (an actor belongs to the module it was spawned from, and so do the actors it spawns), a message may carry only:
- basic values, strings and
Bytes(constants are copied to the heap, so the receiver never points into the sender’s code), - PIDs, Refs and
Modulehandles, - the reserved struct types of the system packages (
actor.Request,net.Up,fs.Info, …), which have the same type index in every image.
A module’s own structs and function values may not cross. That
includes the struct types of every package compiled into the module: your
own packages and the gogo/ libraries written in gogo (gogo/http,
gogo/tui, …). Two modules that import the same package each compile
their own copy, so its T in one module is not its T in the other:
a shared “message types” package does not make a struct sendable between
modules, and sending one fails with BadMsg at run time. Send basic
values, strings or Bytes across instead, and rebuild the struct on the
other side. The sender
that tries exits with the reason BadMsg (whichever module it belongs
to; the main program has no special case), and its supervisor handles that
like any crash. code.Spawn with such an arg returns BadArg instead of
crashing. Messages inside one module are unaffected.
The same holds inside interface values: a value of a module’s own type in
an any or an error is still the module’s own, so it cannot cross
either. That is what lets each image call interface methods by checking
its own types only (section 3.9). A module’s interface types and the
types that implement them work inside the module exactly as in a
program.
14.7 What a module may do, and what the firmware offers
-
Requirements. The compiler records, by name, the drivers and mounts an image needs: the driver of every constant
port.Open(tcp,kbd,imu,tls, …) and/sdfor constant/sdpaths (appendix F). Drivers that a library marks//gogo:optionaldo not count for that library’s own opens (chapter 12). A firmware has exactly the drivers and mounts it was built with.code.Loadof a module that requires one it lacks returnsUnsupported, andcode.Missing(m)names the first missing one:m, e := code.Load(b) if e == code.Unsupported { println("this firmware has no", code.Missing(m)) // e.g. "kbd" or "/sd" }The main image is checked the same way at boot (
gogo: image requires kbd, which this VM lacks). -
Format versions. A module records the image format it was built for (
major.minor;gogo versionprints the current one). A firmware loads every module of its major up to its own minor, so modules stored on/flashkeep working after a firmware update; a module built for a newer minor, or for another major, isBadVersion. Rebuild it with agogothat matches the firmware, or update the firmware. -
Rights. This version has no permissions: a module can do everything the main program can (ports, files, network, configuration). Signing and permissions are not built yet; they were meant to come with HTTPS, which does not add them (chapter 17).
-
Memory. All loaded module code together is limited by the configuration key
code.mem(default 64 KB on a board, 16 MB on the host):gogo config set code.mem 128KOver it,
LoadreturnsNoMemory. Code memory is not charged to any actor, and the main program does not count. Module code runs from RAM: from the receivedBytesdirectly when they are a whole off-heapBytesat a 4-byte aligned address, otherwise from a copy. On the M5StickS3 the copy goes into its 8 MB of PSRAM, so module code does not use up the small internal RAM; the Cardputer ADV has no PSRAM and keeps the code in RAM. Nothing is written to flash, so loading is fast, and a loaded module is gone after a reboot: store it as a file (gogo push, section 14.3, orfs.WriteFile) and load it at boot if you need it again.
14.8 Fetching a module over the network
Load only modules you trust, over a channel that proves where they come from. A loaded module runs with the same rights as the main program: every port the firmware has, the config store, the files, the network. Its requirement names say what it needs from the firmware, not what it is allowed to do, and modules are not signed: nothing in the image says who built it. Fetched over plain
http://, anyone on the path can replace it with their own code. Fetch modules overhttps://from a server you control, keep the people who can write to that server as few as the people who can flash the board, and never load bytes that came from an unauthenticated source (a plain HTTP download, a message from the network, a file anyone can write).
examples/hotload_net in the repository does it on a board: it joins
Wi-Fi, sets the clock (gogo/sntp; chapter 17), downloads
worker_v1.ggb with http.Do from the https:// base URL in the config
key demo.modurl (it refuses an http:// one), loads it, runs it under
SuperviseModule, waits, downloads worker_v2.ggb and upgrades. The
body of an HTTP response is charged to the actor that asked, whose default
limit on a board is 16 KB, so the example limits the module to 4 KB
(modBody, passed as maxBody); for bigger modules raise it, up to http.MaxBodyLimit, in an actor started with a larger
MaxMemory. The server needs a certificate the board trusts (chapter 17);
the example’s README serves the modules from your computer through
Tailscale Funnel, with the exact commands.
(The host has no network, so only the refusal of an http:// URL is
checked there, by make test-examples.)
14.9 Not in this version
Loading modules from flash automatically at boot, replacing the whole
firmware image, changing
code inside a running actor (Erlang-style code upgrade), calling functions
or sharing types across modules, signing, and per-module permissions.
Signed modules are planned (see docs/known-issues.md).
15. IMU and IR
Both boards have a six-axis motion sensor (an IMU: three accelerometer axes
and three gyroscope axes) and an infrared LED; the M5StickS3 also has an
infrared receiver. Three ports give programs this hardware: "imu"
(package gogo/imu), "ir_tx" and "ir_rx" (package gogo/ir), with
gogo/irproto for the common NEC remote-control protocol.
These ports move more data than a key press, so they speak gogo’s
stream protocol (section 7.6), defined in gogo/port and shared by
every port that moves bytes (TCP and TLS, the microphone and speaker, the
screen):
type Chunk struct {
From actor.PID
Seq, TimeMs, Dropped int
Data bytes.Bytes
}
type Out struct{ Data bytes.Bytes }
type Done struct {
From actor.PID
Seq int
}
From is the port that sent the event, so an actor that owns several
stream ports (the IR transmitter and the speaker, say) can tell their
events apart.
- An input stream sends the owner
port.Chunkmessages.Seqcounts from 1, including Chunks that were lost, so a gap in the numbers means something was dropped.Droppedis how many were lost since the last one that arrived.TimeMsis when the data began (the low 31 bits of the clockactor.Nowreads). - An output stream takes
port.Outcommands. EveryOutis answered with oneport.Done, in order:Seqnumbers the Outs that were sent (1, 2, …), andDone{Seq: -1}means this one was refused or could not be sent. A port holds at most two Outs at a time (one being sent, one waiting); a third is refused at once. Send the nextOutwhen aDonecomes back, and you never lose one. (One caveat: a refusal is itself aDone{-1}, and when 8 Dones are already owed and unread, an owner that reads nothing while someone floods it with Outs, further refusals are dropped. Accepted Outs always get theirs.)
A stream never kills its owner: when the owner’s mailbox is over its quota
a Chunk is dropped (and counted in the next one’s Dropped), and a Done
waits until there is room.
Like the keyboard, each of these ports has one owner at a time, and a board
without the hardware refuses to open it. The firmware can also be built
without them (section 15.4); then port.Open fails the same way.
15.1 The motion sensor
package imu
type Config struct{ RateHz, Gestures, BatchMs int }
type Gesture struct{ Kind, Value int }
const (
Tap = 1; DoubleTap = 2; TripleTap = 4; Orientation = 8
Flat = 16; AnyMotion = 32; NoMotion = 64; Step = 128
)
The port does two independent things: it samples the sensor, and it reports gestures that the sensor recognises by itself.
Samples. RateHz is 25, 50, 100 or 200 samples per second, or 0 for
no samples at all (any other value makes Open fail). Samples are gathered
for BatchMs milliseconds (default 200, clamped to 50..1000) and arrive as
one port.Chunk. Each sample is 12 bytes, six little-endian int16
values:
gx gy gz ax ay az
The ranges are fixed: acceleration is +-8 g over +-32768 (4096 per g), and rotation +-2000 degrees per second over +-32768. The axes are the sensor chip’s own; they differ between the two boards, so a program that cares about “up” should find gravity rather than assume an axis.
Here is a spirit level that averages each batch:
// A spirit level: sample the motion sensor at 25 Hz in batches of 200 ms,
// average the acceleration of each batch and print it in milli-g, with
// the axis that gravity pulls on. On the host the samples come from the
// "imu sample gx gy gz ax ay az" lines of the stdin script.
package main
import (
"gogo/actor"
"gogo/imu"
"gogo/port"
)
// s16 is the little-endian int16 at byte i of b.
func s16(b []byte, i int) int {
v := int(b[i]) | int(b[i+1])<<8
if v >= 32768 {
v = v - 65536
}
return v
}
// mg converts a raw acceleration (+-8 g over +-32768) to milli-g.
func mg(raw int) int { return raw * 8000 / 32768 }
func abs(v int) int {
if v < 0 {
return -v
}
return v
}
func main() {
_, err := port.Open("imu", imu.Config{RateHz: 25, BatchMs: 200})
if err != nil {
println("no motion sensor on this board")
return
}
buf := make([]byte, 0, 240) // one batch: 200 ms at 25 Hz = 5 samples of 12 bytes
for batches := 0; batches < 3; {
switch c := actor.Receive().(type) {
case port.Chunk:
batches++
n := c.Data.Len() / 12
buf = buf[:c.Data.Len()]
c.Data.CopyTo(buf)
ax, ay, az := 0, 0, 0
for i := 0; i < n; i++ {
ax += s16(buf, 12*i+6) // a sample is gx gy gz ax ay az
ay += s16(buf, 12*i+8)
az += s16(buf, 12*i+10)
}
ax, ay, az = mg(ax/n), mg(ay/n), mg(az/n)
down := "z"
if abs(ax) > abs(ay) && abs(ax) > abs(az) {
down = "x"
} else if abs(ay) > abs(az) {
down = "y"
}
println("batch", c.Seq, "samples", n, "accel mg", ax, ay, az, "gravity on", down)
}
}
}
On the host, with the script in examples/15-imu-level/input, it prints:
batch 1 samples 3 accel mg 9 -4 999 gravity on z
batch 2 samples 2 accel mg 1000 2 -6 gravity on x
batch 3 samples 1 accel mg -2 -1000 12 gravity on y
A board at rest shows about 1000 mg on one axis and close to 0 on the others: that is gravity.
Three things to know about batches:
- Memory. The batch buffer is
BatchMs * RateHz * 12 / 1000bytes (at most 2400) and is charged to the owner while the port is open, like any other memory it holds (chapter 6). 200 Hz with the default 200 ms is 480 bytes; if the owner’s limit cannot take it,Openfails. - TimeMs of a Chunk is the start of its batch window (the open, or the previous Chunk), within one polling period (50 ms) of its first sample.
- Closing discards the partial last batch. To lose nothing, close the port right after a Chunk arrives.
Gestures. Gestures is a mask of the gesture kinds you want; each one
the sensor sees arrives as an imu.Gesture whose Kind is that bit. Two
kinds carry a Value:
Orientation: the new orientation. The low two bits are 0 portrait upright, 1 landscape left, 2 portrait upside down, 3 landscape right; 4 is added when the board is face down.Step: the step count so far (cumulative; it is not reset by closing the port).
Gestures work with RateHz: 0, which keeps only the accelerometer
running. The sensor is polled about every 50 ms (sooner with a shorter
BatchMs), so a gesture reaches the program up to about 50 ms late, and
gestures seen in the same poll arrive in bit order (Tap first, Step last).
This example starts and stops a “recording” with a double tap:
// Gestures only (RateHz 0: no samples): a double tap starts and stops a
// "recording", a change of orientation is reported, and the program ends
// after the step counter passes 10. On the host the gestures come from the
// "imu gesture <kind> [value]" lines of the stdin script.
package main
import (
"gogo/actor"
"gogo/imu"
"gogo/port"
)
// side names the orientation number's low two bits.
func side(v int) string {
if v == 0 {
return "upright"
}
if v == 1 {
return "on its left side"
}
if v == 2 {
return "upside down"
}
return "on its right side"
}
func main() {
_, err := port.Open("imu", imu.Config{Gestures: imu.DoubleTap | imu.Orientation | imu.Step})
if err != nil {
println("no motion sensor on this board")
return
}
recording := false
for {
switch g := actor.Receive().(type) {
case imu.Gesture:
if g.Kind == imu.DoubleTap {
recording = !recording
if recording {
println("double tap: recording")
} else {
println("double tap: stopped")
}
} else if g.Kind == imu.Orientation {
face := "face up"
if g.Value&4 != 0 {
face = "face down"
}
println("orientation:", side(g.Value&3)+",", face)
} else if g.Kind == imu.Step {
println("steps:", g.Value)
if g.Value > 10 {
return
}
}
}
}
}
double tap: recording
orientation: on its left side, face up
steps: 4
double tap: stopped
orientation: upside down, face down
steps: 12
The script also has an imu gesture tap line; it is not printed because
Tap is not in the mask.
To record motion in the background, use gogo/imulog. It owns the port in
an actor of its own and appends every Chunk and every gesture to files, so
the rest of the program need not read them:
l, ok := imulog.Start(imu.Config{RateHz: 50, Gestures: imu.Tap, BatchMs: 500}, "/flash/imu", 32768)
// ... later, or after a reboot:
for _, r := range imulog.Read("/flash/imu", 100) { // the newest 100, oldest first
if r.Kind == imulog.ChunkRec { /* r.A Seq, r.B Dropped, r.TimeMs, r.Data samples */ }
else { /* r.A gesture kind, r.B its value */ }
}
actor.Kill(l, actor.Shutdown) // stops the log and closes the port
The log is two files, 0.imu (newest) and 1.imu, rotated like ringlog
(chapter 9), so it never takes more than maxBytes plus one record. A
record is a 15-byte header plus the Chunk’s data; lib/imulog/imulog.gg
documents the layout. Every record is synced, so a power loss costs at most
the last one. examples/imulogdemo shows it on the host.
15.2 Infrared
An infrared remote sends bursts of light flickering at a carrier
frequency (usually 38 kHz). gogo describes a frame as timings: a
bytes.Bytes of little-endian uint16 microseconds, alternately “mark”
(carrier on) and “space” (off), starting with a mark. Each value is 1 to
32767 and a frame has at most 256 of them. The receiver produces exactly
the format the transmitter takes, so a frame can be learned and sent back
unchanged.
package ir
type TX struct{ CarrierHz, DutyPct int }
type RX struct{ GapUs int }
Sending. port.Open("ir_tx", ir.TX{CarrierHz: 38000, DutyPct: 33})
opens the transmitter (0 means the defaults shown; the carrier may be
10000 to 500000 Hz, the duty at most 99 %). Send a frame with
port.Out{Data: timings}; its Done comes back when the frame has been
sent. An Out with bad timings or more than 256 values is refused with
Done{Seq: -1}. Closing the port forgets an Out still waiting (no
Done); a frame already being sent is finished if it ends within about
100 ms (an NEC frame does), else cut short.
Receiving. port.Open("ir_rx", ir.RX{GapUs: 10000}) opens the
receiver. Silence longer than GapUs microseconds (default 10000, at most
32767) ends a frame, and each frame arrives as one port.Chunk whose
Data holds its timings, ending with a mark. A frame longer than 256
values is cut there and counts 1 in that Chunk’s Dropped. TimeMs is
when the frame began. The receive buffer (512 bytes) is charged to the
owner while the port is open.
NEC. gogo/irproto builds and reads the NEC protocol that most
consumer remotes use: irproto.EncodeNEC(addr, cmd) returns the 67
timings of a frame, and irproto.DecodeNEC(data) returns addr, cmd, ok.
Anything else (air conditioners, for instance) is sent and received as raw
timings.
This program learns a button and plays it back:
// Learn a remote control button and send it back. The first frame the
// receiver hears is kept; if it is an NEC code it is also decoded. Then the
// learned frame is sent twice, followed by an NEC code built from scratch.
// A transmitter takes at most two Outs at a time, so the third is sent
// when the first Done comes back. On the host the frames come from the
// "ir rx <us> ..." lines of the stdin script, and every frame sent prints
// "ir tx: <n> values" on stderr.
package main
import (
"gogo/actor"
"gogo/bytes"
"gogo/ir"
"gogo/irproto"
"gogo/port"
)
func main() {
rx, err := port.Open("ir_rx", ir.RX{GapUs: 10000})
if err != nil {
println("no IR receiver on this board")
return
}
var learned bytes.Bytes
for got := false; !got; {
switch c := actor.Receive().(type) {
case port.Chunk:
learned = c.Data
got = true
}
}
port.Close(rx)
println("learned a frame of", learned.Len()/2, "timings")
addr, cmd, nec := irproto.DecodeNEC(learned)
if nec {
println("it is NEC: address", addr, "command", cmd)
}
tx, err := port.Open("ir_tx", ir.TX{CarrierHz: 38000, DutyPct: 33})
if err != nil {
println("no IR transmitter on this board")
return
}
actor.Send(tx, port.Out{Data: learned})
actor.Send(tx, port.Out{Data: learned})
for sent := 0; sent < 3; {
switch d := actor.Receive().(type) {
case port.Done:
sent++
println("sent", d.Seq)
if d.Seq == 1 {
actor.Send(tx, port.Out{Data: irproto.EncodeNEC(4, 9)})
}
}
}
}
learned a frame of 67 timings
it is NEC: address 4 command 8
sent 1
sent 2
sent 3
The learned frame came from a real remote, so its timings are not the
textbook ones (a 9630 us leader instead of 9000); DecodeNEC allows for
that, and sending it back reproduces what the remote sent. Keep the
receiver and the LED at least 30 cm apart when you try this on a board.
15.3 On the boards
| M5StickS3 | Cardputer ADV | |
|---|---|---|
imu | BMI270 | BMI270 |
ir_tx | LED on G46 | LED on G44 |
ir_rx | receiver on G42 | none: Open fails |
- The motion sensor is a Bosch BMI270 on the board’s internal I2C bus. Its
tap, orientation, flat, motion and step detection run inside the chip
(the firmware loads Bosch’s 8 KB “legacy” feature configuration into it
at the first
Open, which takes about a quarter of a second). Neither board wires the sensor’s interrupt to the processor, which is why the port polls. - On the StickS3, the IR LED and receiver are powered from the 5 V output
that also feeds the Grove and Hat connectors. The firmware turns it on
while any IR port is open and off again when the last one closes (unless
it was already on). While an IR port is open, the Grove and Hat 5 V pins
are outputs: do not feed 5 V into them then. While
ir_rxis open the speaker amplifier is held off, because the receiver does not work with it on: opening"speaker"then fails, and a speaker already playing goes silent untilir_rxcloses. - The G42, G44 and G46 pins are reserved for IR: the
gpioport refuses them.
15.4 Requirements and firmware
The compiler records which of these ports a program opens (imu, ir_tx,
ir_rx) in the image as requirements, as it does for the network and the
keyboard (chapter 14). A firmware built without them refuses such an image
at boot, naming the missing driver.
The switches are GOGO_IMU and GOGO_IR (gogo firmware names them
imu, irtx and irrx; one switch builds both IR ports). Turning
GOGO_IR off removes the IDF’s RMT driver from the firmware; turning
GOGO_IMU off removes the sensor driver and its 8 KB configuration.
15.5 On the host
On the host VM the hardware is simulated from the stdin script, like the keyboard and battery:
| line | effect |
|---|---|
imu sample gx gy gz ax ay az | one sample (added to the current batch) |
imu gesture <kind> [value] | one gesture: tap doubletap tripletap orientation flat anymotion nomotion step |
ir rx <us> <us> ... | one received frame |
sleep <ms> | wait before the next line |
Every frame the program sends prints ir tx: <n> values on stderr. Put a
sleep after sample lines that is at least 100 ms longer than BatchMs,
and after each ir rx line, so the output does not depend on timing.
16. Audio
Both boards have a microphone and a speaker, on one codec and one I2S bus.
Two ports give programs this hardware, "mic" and "speaker" (types in
package gogo/audio), and two small libraries built on them record to
WAV files and play WAV files back: gogo/wav and gogo/sound.
The ports speak the stream protocol (section 7.6, chapter 15): the
microphone sends port.Chunk messages, the speaker takes port.Out
commands and answers each with port.Done; both name themselves in the
events’ From. The sound is 16-bit little-endian mono PCM at 8000 or 16000
samples per second.
16.1 The ports
type Mic struct{ RateHz, FrameMs, GainDb int }
type Speaker struct{ RateHz, VolumePct int }
mic, err := port.Open("mic", audio.Mic{RateHz: 16000, FrameMs: 100})
spk, err := port.Open("speaker", audio.Speaker{RateHz: 16000, VolumePct: 60})
Mic.RateHzis 8000 or 16000.FrameMsis how much sound oneChunkholds (0 means 100; 20 to 500).GainDbis extra gain, 0 to 24 dB in steps of 6, above the board’s normal microphone level: 0 is normal (speech at arm’s length is clearly above the noise floor and does not clip). Each platform maps it to its own codec gain. Frames are whole: a half frame left when you close the port is dropped.Speaker.VolumePctis 0 (mute) to 100: 1 to 100 runs from 40 dB below the board’s loudest level up to it. Sendport.Out{Data: pcm}(an even, non-empty number of bytes). EachOutis answered withDoneonce it has played. Keep twoOuts in flight: send two, then one more for eachDone. The driver writes the second right after the first, so the speaker never runs dry between them; with oneOutat a time you hear a click at every seam.- The ports are half duplex: while one is open the other refuses to
open (
errors.Busy). You cannot record and play at the same time. - A mic that cannot keep up does not stop the program: a
Chunkthat does not fit the owner’s memory quota, or sound the hardware lost, is counted in the nextChunk’sDropped(whole frames).
Memory for a recorder
The mic port charges its owner for its frame buffer (F words, where
F = RateHz * FrameMs / 2000; a word is 4 bytes) and for every Chunk
waiting in the mailbox (F + 11 words). An actor that stalls for 300 ms
on an SD write finds 3 more frames waiting. At 16 kHz and 100 ms frames
that is about 4000 words, which a board’s default per-actor limit (4096
words, chapter 6) does not leave room for. A program that writes
sound to the SD card therefore spawns its recorder with
actor.Options{MaxMemory}, and lets the recorder open the mic itself:
the open checks the charge (and room for one Chunk) against the
opener’s limit, so a long frame opened in a small actor and then handed
over fails. gogo/sound does this for you.
16.2 Recording: gogo/sound
func Record(dir string, cfg audio.Mic, maxSec int) (actor.PID, bool)
type Stop struct{}
type Recorded struct {
Path string
Ms int
Dropped int
Err errors.Code
}
Record starts a recorder actor, which opens the mic with cfg and owns
it; Record waits for that open, so ok still says whether the mic opened.
It writes every Chunk to dir/NNNN.wav, where NNNN is four digits: the
numbering continues from the highest NNNN.wav already in dir, so a
reboot does not overwrite anything. dir is created (one level) if it does
not exist. After maxSec seconds of sound (0 means 600) the file is
closed and the next Chunk starts the next file, so a long recording is
a series of files of at most ten minutes. A file always holds a whole
number of frames.
Every finished file is reported to the actor that called Record as one
sound.Recorded: Ms is the sound in the file, Dropped the frames the mic
lost while it was written (their time is missing from the file). Send
sound.Stop{} to the recorder to finish the current file and end it.
A Stop always gets exactly one final Recorded: if it comes while no
file is open (right after a file filled up, or before the first Chunk),
that Recorded has Path == "" and Ms == 0, meaning nothing was written
since the last one. ok
is false if the mic does not open (no microphone, the speaker is open,
a bad cfg) or dir cannot be used.
// recorddemo: records the microphone to /flash/rec with gogo/sound and reads
// the files back. On unix the sound comes from the stdin script (`mic tone`
// lines of 250 ms, 300 ms apart; run with --fs-root). The directory already
// holds 0007.wav and notes.txt, so the numbering continues at 0008. With
// maxSec 1 the recording rotates after 1000 ms into a second file, which a
// Stop ends at 500 ms (its header is patched in place with the true size).
// Right after that report the program plays that file: the recorder has
// given the microphone back by then. Nothing depends on real-time pacing
// but the Stop: it comes about 300 ms after the last tone line (more than
// the 100 ms margin the 50 ms mic poll needs). Everything is read in pieces
// of 1000 bytes, so it also runs under the 4096-word limit of a board.
package main
import (
"gogo/actor"
"gogo/audio"
"gogo/fs"
"gogo/sound"
"gogo/wav"
)
func main() {
fs.Mkdir("/flash/rec")
fs.WriteFile("/flash/rec/0007.wav", "x")
fs.WriteFile("/flash/rec/notes.txt", "x")
r, ok := sound.Record("/flash/rec", audio.Mic{RateHz: 8000, FrameMs: 100}, 1)
if !ok {
println("no mic")
return
}
n := 0
for n < 1 { // wait for the first file: it is full after 1 s of sound
switch m := actor.Receive().(type) {
case sound.Recorded:
show(m)
n++
}
}
actor.Sleep(900) // the first file closes at about 900 ms into the script; the last tone line is read at 1500 ms: Stop at about 1800 ms
actor.Send(r, sound.Stop{})
last := ""
switch m := actor.Receive().(type) {
case sound.Recorded:
show(m)
last = m.Path
}
_, ok = sound.Play(last) // the mic is already closed
println("play", ok)
switch m := actor.Receive().(type) {
case sound.Played:
println("played", m.Bytes, "dones", m.Dones, "err", int(m.Err))
}
names, _ := fs.ReadDir("/flash/rec")
println("files", len(names))
}
func show(m sound.Recorded) {
println("recorded", m.Path, "ms", m.Ms, "dropped", m.Dropped, "err", int(m.Err))
i, _ := fs.Stat(m.Path)
f, _ := fs.Open(m.Path, fs.Read)
h, _ := f.Read(wav.HeaderLen)
hd, ok := wav.Info(h)
peak := 0
for {
b, _ := f.Read(1000)
if b.Len() == 0 {
break
}
for k := 0; k+1 < b.Len(); k += 2 {
v := int(b.At(k)) | int(b.At(k+1))<<8
if v >= 32768 {
v = 65536 - v
}
if v > peak {
peak = v
}
}
}
f.Close()
println(" size", i.Size, "header ok", ok, "rate", hd.Rate, "data", hd.Data, "samples", (i.Size-wav.HeaderLen)/2, "peak", peak)
}
The script is mic tone <hz> <ms> lines (section 16.5). The output:
recorded /flash/rec/0008.wav ms 1000 dropped 0 err 0
size 16044 header ok true rate 8000 data 16000 samples 8000 peak 999
recorded /flash/rec/0009.wav ms 500 dropped 0 err 0
size 8044 header ok true rate 8000 data 8000 samples 4000 peak 999
play true
played 8000 dones 2 err 0
files 4
The directory already held 0007.wav and notes.txt, so the numbering
continues at 0008. The first file holds 1000 ms (8000 samples, 16000
bytes of PCM plus the 44-byte header); the second was stopped after 500 ms
and its header patched, then played back. The programs read files in
pieces of 1000 bytes: they also run under the 4096-word actor limit of a
board.
Errors: a full card
A failed write, a full card or a removed card stops the recorder. It
finishes the file (the header covers the whole frames written before the
failure), gives the microphone back, sends a Recorded whose Err is the
storage error as a shared errors.Code (errors.NoSpace, errors.IO,
…: the same numbers as fs.NoSpace, fs.IO) and exits normally. It never
deletes anything to make room: that is the program’s decision (it can
remove old files and call Record again, and the numbering carries on).
Monitor the recorder (actor.Monitor) if you want to see it end. After a
Stop or an error the microphone is already closed when Recorded
arrives, so the program may call sound.Play at once (the example does);
the player likewise closes the speaker before it sends Played. The
recording length is capped at one hour per file (sound.MaxMaxSec).
The WAV header and wav.Close
A WAV header holds the size of the data, which a recorder only knows at
the end. gogo/wav writes the header first, with the size you expect
(a recorder’s file is a fixed number of frames), and wav.Close makes it
true: when the file ends as planned it only commits, and when it ends early
(a Stop, a failed write) it patches the 44 header bytes in place with
File.WriteAt (chapter 9). That is 44 bytes of I/O however long the
recording is, needs no copy, and does not need free space on an SD card, so
the header is right even when the card is full. On /flash
(copy-on-write) the patch needs one free block; if it fails, Close
returns the error and the header keeps the planned size. Players and
sound.Play trust the file size, so such a file still plays.
16.3 Playing: gogo/sound
func Play(path string) (actor.PID, bool)
type Played struct {
Path string
Bytes int
Dones int
Err errors.Code
}
Play opens the WAV file, opens the speaker at the file’s rate and starts
a player actor, which reads the file in 4096-byte pieces and keeps two
Outs in flight (section 16.1). When it is over (or after sound.Stop{})
the caller gets one sound.Played: Bytes of PCM handed to the speaker,
Dones the Outs that completed, Err is errors.OK, a read error or
errors.IO (the speaker refused or failed an Out). ok is false, and nothing starts, if the file is
missing, is not a canonical 16-bit mono PCM WAV at 8000 or 16000 Hz (the
files Record writes are), or the speaker does not open (the mic is open,
no speaker). The size of the file is the truth, not the header: the file
Record could not finish plays to its end.
// playdemo: makes a 10000-byte WAV (5000 samples at 8 kHz, 625 ms) with
// gogo/wav and plays it with gogo/sound. Play sends 4096-byte Outs, two in
// flight, so 10000 bytes are 3 Outs (4096, 4096, 1808) and 3 Dones; the
// unix speaker prints `spk: <n> bytes` on stderr for each write. The player
// plays in real time, but nothing here depends on it: the program waits
// for Played.
package main
import (
"gogo/actor"
"gogo/bytes"
"gogo/fs"
"gogo/sound"
"gogo/wav"
)
func main() {
w, e := wav.Create("/flash/ramp.wav", 8000, 10000)
println("create", int(e))
b := bytes.NewBuffer(10000)
for i := 0; i < 5000; i++ {
v := (i % 100) * 300
b.WriteByte(byte(v))
b.WriteByte(byte(v >> 8))
}
w, e = wav.Write(w, b.Freeze())
println("write", int(e), w.N)
println("close", int(wav.Close(w)))
_, ok := sound.Play("/flash/none.wav")
println("missing file", ok)
fs.WriteFile("/flash/bad.wav", "this is not a wav file, it is far too short to be one")
_, ok = sound.Play("/flash/bad.wav")
println("bad file", ok)
_, ok = sound.Play("/flash/ramp.wav")
println("play", ok)
switch m := actor.Receive().(type) {
case sound.Played:
println("played", m.Path, "bytes", m.Bytes, "dones", m.Dones, "err", int(m.Err))
}
}
create 0
write 0 10000
close 0
missing file false
bad file false
play true
played /flash/ramp.wav bytes 10000 dones 3 err 0
and on stderr, one line from the simulated speaker for each write:
spk: 4096 bytes
spk: 4096 bytes
spk: 1808 bytes
10000 bytes are three Outs (4096, 4096, 1808) and three Dones.
16.4 gogo/wav
wav is the file format on its own, for programs that make sound
themselves (a synthesiser, a recorder with other rules). Close patches the header
through File.WriteAt:
func Create(path string, rate, planned int) (Writer, fs.Err)
func Write(w Writer, pcm bytes.Bytes) (Writer, fs.Err)
func Close(w Writer) fs.Err
func Info(header bytes.Bytes) (Header, bool)
A Writer is a value (the package was written before gogo had
pointers), and each call returns the new one: w, e = wav.Write(w, pcm). planned is the
number of PCM bytes you expect (0 if you do not know: Close then always
patches the header). Info parses the 44-byte header (ok is false for anything
but canonical RIFF/WAVE, PCM, mono, 16-bit); Header.Data is the size
the header declares, which may be more than the file holds.
16.5 On the host
On the host VM the microphone and speaker are simulated, like the keyboard:
| line | effect |
|---|---|
mic tone <hz> <ms> | a sine wave (amplitude 1000, doubled every 6 dB of GainDb) |
mic silence <ms> | zeros |
sleep <ms> | wait before the next line |
Sound arrives as a burst at the next poll (every min(FrameMs, 50) ms),
not in real time, so a long mic tone line is delivered at once and can
fill a recorder’s mailbox: write tones of a few hundred milliseconds with a
sleep after each, as the example does, and keep a margin of at least
100 ms between script lines and anything that depends on them.
The speaker prints spk: <n> bytes on stderr for every write (at most 4096
bytes) and plays in real time, so Done arrives as late as on the board.
--fs-root gives /flash a directory on the host; for testing a full
medium gogovm has the flag --fs-quota <bytes> (not in gogo run).
Each medium (/flash, and /sd if present) then holds at most that many
bytes of files: what is already in its directory counts from the start,
deleting or truncating a file gives its bytes back, a write that does not
fit stores what does and fails with fs.NoSpace, and fs.Usage reports
the bytes used and the quota. --fs-quota 0 is a full medium. The golden
test tests/golden/sound_diskfull uses it.
16.6 Requirements and firmware
The compiler records in the image that a program opens "mic" or "speaker"
itself (a requirement, like the other ports); a firmware built without them
refuses that image at boot. Importing gogo/sound does not require them: the library
declares //gogo:optional mic speaker (chapter 12), and Record and Play
return false when the hardware is absent. A program that opens "mic" or
"speaker" with port.Open itself still requires them. Both are on by default and share one switch, GOGO_AUDIO (gogo firmware names them mic and speaker). A board without the hardware
refuses port.Open (errors.NotFound). The codec’s I2S pins are reserved: the
gpio port refuses G14 to G18 on the StickS3 and G41, G42, G43 and G46 on
the Cardputer ADV.
On both boards the microphone and speaker are an ES8311 codec on I2S:
GainDb0 is 54 dB of codec gain (30 dB analog, 24 dB in the ADC);GainDbadds digital gain on top.VolumePct1 to 100 is the codec’s DAC volume from 40 dB below the ceiling to the ceiling, in 0.4 dB steps. The ceiling is 0 dB on the Cardputer ADV and -4 dB on the StickS3: at full codec level its USB console once stopped answering (probably a supply dip from the amplifier).- The codec’s analog reference is switched on by the first
micorspeakeropen and stays on until the board resets. Powering it down at every close made each later open start with about a second of silence. The firstmicopen after power-up still has that silence: a first recording after a cold boot starts with about 1 s of zeros.
17. HTTPS
Chapter 10’s HTTP client also speaks HTTPS. Give http.Get, http.Post
or http.Do an https:// URL and the request goes over TLS. On top of
that, gogo/http has two things a device that talks to a server all day
needs:
- a keep-alive client,
http.Client, which keeps one connection open between requests, so a poll once a second does not pay for a TLS handshake every time; http.Upload, which streams a file (a recording, a log) from storage as a request body, a few KB at a time, so a file of any size fits in a small actor.
What there is not: a TLS server, client certificates, HTTP/2, TLS 1.3 (the client speaks TLS 1.2, which every mainstream server accepts), and more than one TLS connection at a time on a board.
17.1 Before the first request: the clock
TLS checks the server’s certificate: that a trusted authority signed it,
that it is for the name in the URL, and that it is valid now. The board
has no battery-backed clock, so after boot it does not know the date, and
until it does every https request fails. Set the clock once the network is
up, with gogo/sntp (chapter 10):
if sntp.Sync("pool.ntp.org", 5000) != nil {
println("no time: https would fail")
return
}
You do not need to sync again for TLS: the clock keeps running from there.
The authorities a board trusts are the usual public ones (the ESP-IDF certificate bundle, in flash). A server with a certificate from Let’s Encrypt or another public CA works as it is; this includes a server published with Tailscale Funnel. A self-signed certificate does not, and there is no switch to turn the checks off.
17.2 https with Get, Post and Do
Nothing changes in the calls; the URL decides:
// Fetch a page over HTTPS. The clock comes first: TLS checks the
// certificate's dates, and the board does not know the date after boot.
// The URL comes from the config store (gogo config set fetch.url
// https://...).
package main
import (
"gogo/dhcp"
"gogo/http"
"gogo/sntp"
"gogo/sys"
)
func main() {
url, ok := sys.Config("fetch.url")
if !ok {
url = "https://example.com/"
}
if dhcp.Start(dhcp.Config{}) != nil {
println("no network")
return
}
if sntp.Sync("pool.ntp.org", 5000) != nil {
println("no time: https would fail")
return
}
// The request runs in an actor of its own with room for the TLS
// state (about 23 KB); this actor only needs room for the body.
r, err := http.Get(url, 15000)
if err != nil {
println("GET", url, "failed:", err.Error())
return
}
println("GET", url, "->", r.Status, r.Body.Len(), "bytes")
}
On the host:
no network
The port is 443 unless the URL names another. A failed certificate check is an ordinary failure, an error, as for a refused connection or a timeout. The TLS handshake takes a while on a microcontroller (the signature checks are spread over many short slices, so other actors keep running), so give an https request a longer timeout than a plain one.
Memory. TLS needs about 23 KB for one connection: two record buffers
(16 KB in, 4 KB out) and the connection state. That memory is charged to
the actor that opens the connection, like any port’s state, so it does not
fit the 16 KB default of a board. You do not have to do anything about
it: every request already runs in an actor that gogo/http spawns with the
limit it needs (the body limit as before, plus http.TLSMemory for https).
Your own actor still needs room for the response body it gets back
(chapter 10).
Only one at a time. A board has one TLS connection at most. While one
is open (another request in progress, or a Client holding its kept
connection), a second https request fails at once. Plain http requests are
not affected.
Cut-short responses are errors. Over TLS, a server’s connection close
can be faked by anyone on the path at the right moment, and it then looks
like a normal close. So over https a response must say how long it is: a
Content-Length, or chunked encoding, and a body that ends early is a
failure, never a short success. A response that just runs until the
server closes, which plain http accepts, fails over https. That is why an
https Get asks in HTTP/1.1 (with Connection: close), where a plain one
asks in HTTP/1.0: some servers, Cloudflare among them, answer an HTTP/1.0
request with exactly such a body, and in HTTP/1.1 they frame it.
17.3 Keep-alive: http.Client
type Client struct{ PID actor.PID }
func NewClient() Client
func ClientDo(c Client, method, url, contentType string, body bytes.Bytes, timeoutMs int) (Response, error)
func ClientUpload(c Client, url, path, contentType, token string) (status int, err errors.Code)
func CloseClient(c Client)
NewClient starts an actor that makes requests for you over HTTP/1.1 and
keeps the connection open after each response. The next request to the
same scheme, host and port reuses it: no new TCP connection, no new TLS
handshake. ClientDo is like Do, with the body limit fixed at
http.MaxBody.
// Poll a server once a second over one kept HTTPS connection: one TLS
// handshake for all the requests, not one each. The URL comes from the
// config store (gogo config set poll.url https://...).
package main
import (
"gogo/actor"
"gogo/bytes"
"gogo/dhcp"
"gogo/http"
"gogo/sntp"
"gogo/sys"
)
func main() {
url, ok := sys.Config("poll.url")
if !ok {
url = "https://example.com/status"
}
if dhcp.Start(dhcp.Config{}) != nil || sntp.Sync("pool.ntp.org", 5000) != nil {
println("no network")
return
}
c := http.NewClient()
var none bytes.Bytes
for i := 0; i < 5; i++ {
r, err := http.ClientDo(c, "GET", url, "", none, 5000)
// A failed request (the server went away mid-request) is not
// retried for you; the next one reconnects.
println(i, err == nil, r.Status, r.Body.Len())
actor.Sleep(1000)
}
http.CloseClient(c)
}
On the host:
no network
The rules:
- One connection. The client keeps at most one. A request to another host (or port, or scheme) closes the current connection and opens a new one. For two servers, start two clients (only one of them can hold an https connection, though).
- Servers close idle connections, after a few seconds or minutes. The client notices that while it waits and opens a new connection for the next request, transparently.
- No automatic retry. If the connection ends after a request was sent
on it,
ClientDofails. The server may already have acted on the request (a POST that created something), so sending it again is your decision, not the library’s. The next call opens a new connection. There is a short window where the server closes an idle connection just as a request goes out; a GET that fails like that is safe to repeat. - Responses are framed by
Content-Lengthor by chunked transfer encoding (which the client decodes); a response the server marksConnection: closecloses the connection after it. - One request at a time. The client is an actor: requests from several
actors are answered one after the other, in order. A request whose
caller gave up while it waited (its timeout passed) is dropped without
being sent. At most
http.MaxQueued(4) requests wait at once; one more fails at once. - It follows its creator. When the actor that called
NewClientexits or crashes withoutCloseClient, the client closes its connection and ends too: a request in progress then (even another actor’s) fails at once, its connection reset, and the requests queued behind it fail at once without being sent. A client does not outlive its owner by more than that abort, so a dead owner never keeps the one TLS connection. - Responses of type 1xx (
103 Early Hints) are interim: the client skips them and reads the real response that follows. - Memory. The client actor is spawned with the limit an https connection and an upload need (60 KB), whatever URL you use. That is a limit, not a reservation: it costs memory only while used. Requests waiting for it (their bodies too) count against it.
CloseClientcloses the connection cleanly and ends the actor; requests still waiting for it fail. Close a client you no longer need: while it holds an https connection, no other https request can open one.
17.4 Uploading a file: http.Upload
func Upload(url, path, contentType, token string) (status int, err errors.Code)
Upload sends the file at path as the body of a POST, with its
Content-Length and Content-Type: contentType. The file is read with
fs.File.Read, http.UploadChunk (4 KB) at a time, with at most two
writes in flight, so the whole file is never in memory: a 1 MB recording
goes up with the same memory as a 16 KB one. Like Get, it runs in an
actor of its own with the limit it needs (46 KB for https), so it
can be called from any actor.
If token is not empty, the request carries Authorization: Bearer <token>. Keep the token out of your source code: store it on the
device with gogo config and read it with sys.Config. gogo/http never
prints it, and neither should you. A token goes over https only: with
an http:// URL, Upload refuses at once with http.BadURL, so a mistyped
URL cannot send the token in the clear.
gogo config set upload.url https://myhost.example.ts.net/upload
gogo config set upload.token - # type it; it is not echoed back
The error is an errors.Code, the shared codes of gogo/errors
(appendix C). The result is the server’s status with errors.OK when the
server answered, whatever the status (201, 401, 413…); check it.
Otherwise status is 0 and err says why:
err | meaning |
|---|---|
| a storage error | the file, with the same number as in gogo/fs: errors.NotFound, errors.IsDir, errors.IO (also: the file got shorter while it was sent) |
a connection’s Closed reason | the connection ended while the request was sent: errors.Timeout (9, a host that does not answer), Refused, Reset, NoRoute, BadCert (21, the certificate failed), NoTime, TLS |
errors.Timeout (9) | no usable answer in time: a wait or the whole upload ran out |
errors.IO (8) | no usable answer otherwise: DNS, the peer closed, or a malformed or cut-short response |
http.BadURL (25, errors.BadURL) | not an http:// or https:// URL, a content type or token that cannot go in a header, or a token with an http:// URL |
A server that answers before it has read the whole body (a 401 for a bad
token, a 413 for a file too large) stops the upload, and you get its status
without the rest of the file being sent. Each wait (connecting, a write
being acknowledged, the response) has http.DefaultTimeoutMs, and the
upload as a whole 30 s plus 1 ms per byte: about 17 minutes for 1 MB, so
only a link slower than about 1 KB/s fails for being slow. A file that grows while it is sent (a recording still
being written) is sent up to the size it had when the upload started.
// Upload a recording with http.Upload: the file is streamed from storage
// 4 KB at a time, never held in memory whole. The URL and the token come
// from the config store, never from the source:
//
// gogo config set upload.url https://myhost.example.ts.net/upload
// gogo config set upload.token - (typed, not echoed)
//
// On the host there is no network, so this shows the error cases.
package main
import (
"gogo/bytes"
"gogo/errors"
"gogo/fs"
"gogo/http"
"gogo/sys"
)
func main() {
url, _ := sys.Config("upload.url")
token, _ := sys.Config("upload.token") // sent as "Authorization: Bearer <token>"; never print it
// A 10 KB file to send.
b := bytes.NewBuffer(10240)
for i := 0; i < 10240; i++ {
b.WriteByte(byte(i))
}
println("write:", int(fs.WriteFile("/flash/rec.bin", b.Freeze())))
status, err := http.Upload(url, "/flash/missing.bin", "audio/wav", token)
println("missing file:", status, int(err), err == errors.NotFound)
status, err = http.Upload("ftp://myhost/upload", "/flash/rec.bin", "audio/wav", token)
println("bad URL:", status, int(err), err == http.BadURL)
// No network on the host: IO. On a board, the server's status
// (201, 401, ...) with errors.OK.
status, err = http.Upload(url, "/flash/rec.bin", "audio/wav", token)
println("upload:", status, int(err), err == errors.IO)
}
On the host (the example’s config file sets upload.url and a dummy
upload.token; the dns: line is the resolver saying there is no
network):
write: 0
missing file: 0 1 true
bad URL: 0 25 true
dns: net.Subscribe failed (no network or 4 subscribers): retrying on each lookup
upload: 0 8 true
Upload runs in an actor of its own that follows the caller: if the
caller crashes or a supervisor kills it mid-upload, the upload stops and
its connection is reset at once, so the restarted caller’s retry finds
the TLS connection free (and the server never gets a duplicate finished
behind its back).
Upload uses a connection of its own (HTTP/1.1, Connection: close). On
a board that means it needs the one TLS connection: while an https
Client holds it, the upload fails. If the program has a client to the
same server anyway (a status poll once a second), upload through it:
http.ClientUpload(c, url, path, contentType, token) sends the same
request on the client’s kept connection, with the same results, and keeps
the connection for the next request.
17.5 The "tls" port
gogo/http sits on a port you can also use directly, for a protocol of
your own over TLS. It is the "tcp" port with TLS in between, and has the
same messages (Connected, Shutdown and the stream protocol’s
port.Out, Done, Chunk and Closed, section 7.6); only its config
differs:
c, err := port.Open("tls", net.DialTLS{IP: ip, Port: 443, TimeoutMs: 15000, Host: "myhost.example.ts.net"})
Host is the name the certificate must be for (it is also sent to the
server, SNI). Connected comes after the handshake. Closed has three
more reasons: net.NoTime (the clock is not set; nothing was sent),
net.BadCert (the certificate is untrusted, expired or for another name)
and net.TLS (any other TLS failure). The owner needs about 23 KB plus
room for one Chunk beyond its own heap, or the open fails: spawn it with
actor.SpawnOpt and a larger MaxMemory, as gogo/http does. And frame
what you read (a length, a terminator): a close at a record boundary looks
normal, so “read until the close” cannot tell a whole stream from a cut
one. The full contract is in the DialTLS comment in lib/net/net.gg.
17.6 On the host, and requirements
gogovm built with mbedTLS (the Makefile does it when it finds the
ESP-IDF source) has the "tls" port. It trusts the host’s CA bundle, or
the certificates in the file named by $GOGO_TLS_CA_FILE. The tests in
tests/net use that to run gogo/http against real Go TLS servers with a
test CA, through the network simulator: https, wrong names, keep-alive,
idle closes, cut-short responses and a 1 MB upload.
A program that opens "tls" itself requires the tls driver, and a
firmware built without it (gogo firmware feature tls, on by default)
refuses the image. Importing gogo/http does not require it: the library
opens "tls" only for an https URL, and without it that request just
fails (one-shot and on a Client alike). It says so with the directive
//gogo:optional tls (chapter 12), which any library can use for its own
soft drivers. So an http-only program runs on any firmware with
networking.
17.7 On the board
examples/httpsdemo is the whole chapter on a StickS3: DHCP, sntp.Sync,
one http.Get of https://example.com/, three requests through a
Client, and a connection with the wrong name that must be refused. A
run on the board printed this (the reason on the wrong.example line is
edited to today’s number, 23 for TLS; it was captured as 8, before the
codes were shared):
sntp: ok, 50 ms unix ms 1795628156793
httpsdemo: 15 s 后开始 / TLS in 15 s
Get HTTP 200 body 577 B, 2790 ms
Client 1 HTTP 200 body 577 B, 2887 ms
Client 2 HTTP 200 body 577 B, 316 ms
Client 3 HTTP 200 body 577 B, 312 ms
wrong.example: closed 23 , 1085 ms
httpsdemo: done
What the numbers say:
- A handshake takes about 2.5 s. Almost all of it is elliptic-curve arithmetic in software: checking the certificate chain (example.com’s has a P-384 root) takes about 1.8 s, the server’s key-exchange signature about 0.35 s. These checks are cut into slices of about 10 to 25 ms (a few that cannot be cut, near 50 ms), so other actors keep running. Give https requests a timeout of 10 s or more.
- Keep-alive pays once.
Client 1includes the handshake;Client 2andClient 3reuse the connection and take about 0.3 s, the network round trip. - One step is not sliced. The key exchange (X25519, the faster curve
here) is a single step of about 200 ms. For that long nothing else runs:
no other actor, no timer. A program that must not pause that long (audio
to SD, say) should not start an https request while it is busy. Making
this step sliced too is on the list (
docs/known-issues.md). - The wrong name is refused. Here the server itself refuses a name it
does not serve (
Closed{TLS}, reason 23); a server that answers with its certificate anyway getsClosed{BadCert}(21) from the name check.
The TLS memory comes from PSRAM on the StickS3 (about 35 KB at its peak,
during the handshake), so the internal RAM the VM uses is not touched;
on the Cardputer ADV, which has no PSRAM, it comes from internal RAM. The
board keeps the trust anchors in flash: ESP-IDF’s certificate bundle.
gogo device stats shows the TLS counters (tls_*), the longest slice
(tls_max_step_us) and the TLS memory (mbedtls_mem_peak).
17.8 Limits
| board | host | |
|---|---|---|
| TLS connections at once | 1 | 1 |
| TLS version | 1.2 | 1.2 |
| memory charged per TLS connection | about 23 KB (+ one Data) | same |
Client connections | 1 per client | same |
Client / Upload actor limit (https) | 60 KB / 46 KB | same |
requests waiting for a Client | 4 (http.MaxQueued) | same |
| upload chunk, writes in flight | 4 KB, 2 | same |
| response body | http.MaxBody (8 KB; up to 64 KB with Do) | same |
Responses are still read into memory whole, up to the body limit; downloading a large file to storage in a stream is not there yet.
18. Embedding gogo
So far a gogo program has run on a board or under gogovm. Embed mode
puts the same VM inside a program of your own, the way Lua is embedded: a
desktop or server program, a phone app, a test tool. The program (the
host) loads an image that gogo build made, runs it, sends its actors
messages, and gives it ports of its own. Any number of VMs can live in one
process, on any threads; they share nothing.
The API is one C header, runtime/include/gogo.h
(C99, no threads), with
gogo_posix.h for the POSIX host
and a VM on a thread of its own, and one library, libgogo.a. This
chapter walks through it with the
programs in examples/embed-c/; Go programs
use the binding gogotools/embed (section 18.12), and a host can
compile source itself (section 18.13). Every C and Go snippet
here is cut from the examples, and make example-embed builds them and checks
their output.
What an embedded VM does not have in this version: the board peripherals
(GPIO, keyboard, power, IMU, IR, audio), the
network and TLS. It has actors, timers, Bytes, host ports, posts,
/flash on a host directory, and hot loading if the host allows it.
18.1 Building
make lib # build/libgogo.a
make example-embed # builds and tests examples/embed-c
libgogo.a is the VM core, the file system layer, streams and the
embedding layer, compiled as strict C99. Link it with -pthread:
cc -std=c99 -Iruntime/include -o host host.c build/libgogo.a -pthread
The examples include gogo_posix.h, which includes gogo.h; a host
with a table of its own needs only gogo.h. That split is in the headers
only: libgogo.a is one prelinked object, and it needs
POSIX threads (pthread_create, pthread_join, mutexes and condition
variables), getentropy, clock_gettime, the *at file calls with
open, fdopendir, readdir, fstatvfs and fsync (for /flash on a
host directory), and the C library (malloc, snprintf, string
functions), whichever header the host includes. A library build for an
RTOS without POSIX is still to come. The library exports only the gogo_* functions: everything
else in it is local, so your program may use any other names. make lib also builds
build/libgogo-debug.a, the same code as separate objects, for debugging
on a machine other than the one that built it
(runtime/include/README.md explains
the difference).
18.2 The smallest host
examples/embed-c/main.c runs one image. It reads the file, makes a VM on
the POSIX host and loads the image:
gogo_vm *vm;
int rc = h ? gogo_new(h, ctx, cfg, &vm) : gogo_new_posix(cfg, &vm);
if (rc != GOGO_OK) { fprintf(stderr, "gogo_new: %s\n", gogo_strerror(rc)); free(img); return NULL; }
rc = gogo_load(vm, img, len, GOGO_LOAD_COPY); /* copied: img can go */
free(img);
if (rc != GOGO_OK) {
fprintf(stderr, "gogo_load %s: %s (%d)\n", path, gogo_strerror(rc), rc);
gogo_free(vm);
return NULL;
}
return vm;
then runs it to the end:
static int run_one(const char *path, const gogo_config *cfg) {
gogo_vm *vm = load_vm(NULL, NULL, cfg, path);
if (!vm) return 1;
int rc = gogo_run(vm); /* starts main, runs until every actor is done */
gogo_free(vm);
return rc == GOGO_OK ? 0 : 1;
}
The life of a VM is always the same four steps:
gogo_new(orgogo_new_posix) makes it, from a host table and a configuration;gogo_loadgives it its image, once. WithGOGO_LOAD_COPYthe VM copies the image; without it the image is borrowed and must stay valid, unchanged and 4-byte aligned untilgogo_free;gogo_startstarts the image’smain, and the host runs the VM: withgogo_runas here (it startsmainitself if needed), or by stepping it (section 18.5);gogo_freecloses its ports and gives back every byte it took.
gogo build examples/many_idle -o many_idle.ggb
build/embed-c/main many_idle.ggb
spawned 1000
idle memory total: 148000 B
The program is done when every actor has exited or is blocked for good,
as on a board: many_idle’s 1000 actors wait in Receive forever, so the
run ends when main returns. Every call returns a negative GOGO_E* on
error, and gogo_strerror describes one; gogo_load’s reasons (a bad
image, an unsupported image format, a missing driver) are also written to
the host’s error stream, with the names involved.
The error codes are the shared codes of gogo programs (gogo/errors,
appendix C; GOGO_E_* in gogo_errors.h, which gogo.h includes),
negated: GOGO_EINVAL is -GOGO_E_BADARG, GOGO_ENOMEM is
-GOGO_E_NOMEMORY, GOGO_EREQUIRES is -GOGO_E_UNSUPPORTED, as
code.Load says for the same refusal. One table of meanings covers both
sides, so gogo_strerror also describes a code a program hands the host
(a port.Closed reason, say), negated: gogo_strerror(-reason).
gogo_step’s GOGO_IDLE and GOGO_DONE are not errors, and it says so. Only GOGO_ESTATE, a call
out of order, is the API’s own (-36; 36 to 99 are never shared codes).
| result | from | |
|---|---|---|
GOGO_EINVAL | a bad argument, table or configuration | every call |
GOGO_ENOMEM | out of memory, or over mem_limit | every call that allocates |
GOGO_ESTATE | out of order: no image, loaded twice, started twice | gogo_load, gogo_start, gogo_step, … |
GOGO_EBUSY | called from a hook while the VM steps | gogo_step, gogo_run, gogo_load, gogo_start, … |
GOGO_EIMAGE | not an image | gogo_load |
GOGO_EVERSION | an image format this library does not run | gogo_load |
GOGO_EREQUIRES | the image requires a driver or mount the VM lacks | gogo_load |
GOGO_ENOTFOUND | the image has no main | gogo_start |
GOGO_EFULL, GOGO_E2BIG | a queue or table is full; a name or data is too long | posts, host ports |
GOGO_ECLOSED, GOGO_EEXIST | posts are closed or the VM is gone; a name is taken | posts, host ports |
Versions. gogo_version() is the library’s version,
(major << 16) | (minor << 8) | patch, and GOGO_VERSION the header’s
(0.2.0 here). A host checks at start that it runs on a library at least
as new as the header it was compiled with, of the same major (during
0.x, the same minor). gogo_image_format() says which images the
library loads, (major << 16) | newest minor.
gogo_new_posix is the ready-made host for POSIX systems: malloc,
CLOCK_MONOTONIC, the system’s wall clock (which the program may not
set), getentropy, stdout and stderr, and a latched wait. The VM owns
that host’s state and frees it with the VM.
Functions that make something return a result code and hand the new
object back through their last argument: gogo_new(h, ctx, cfg, &vm)
is GOGO_OK, or an error with vm set to NULL, so a host can say why
it failed.
18.3 The configuration
The third argument of gogo_new (or the first of gogo_new_posix) is a
gogo_config. Start it from GOGO_CONFIG_INIT: that is a VM that
grants every name it has, with no memory cap, no storage and no hot
loading (a NULL config is the same). main.c fills in three fields
from its options:
if (strcmp(argv[i], "--flash") == 0 && i + 1 < argc - 1) cfg.fs_root = argv[++i];
else if (strcmp(argv[i], "--quota") == 0 && i + 1 < argc - 1) cfg.fs_quota = strtoll(argv[++i], NULL, 10);
else if (strcmp(argv[i], "--allow-load") == 0) cfg.flags |= GOGO_CONFIG_CODE_LOAD;
| field | meaning |
|---|---|
size | the struct’s size, set by GOGO_CONFIG_INIT (section 18.4 explains why) |
flags | GOGO_CONFIG_CODE_LOAD lets code.Load load modules (section 18.10) |
mem_limit | bytes the whole VM may allocate, on top of each actor’s own limit; 0 = no cap (the parameter vm.memory) |
max_actors | live actors at once; 0 = the build’s default (16384), at most 65520 (vm.max_actors; gogovm and boards stop at 61440, below the remote PIDs of node links, which an embedded VM does not have) |
grant | the requirement names the VM may serve, a NULL-terminated list; NULL = all it has (section 18.9) |
fs_root | a host directory served as /flash, or NULL for no storage (section 18.8) |
fs_quota | bytes the files under fs_root may hold; 0 = no quota |
max_ports | ports open at once (the table grows as they open); 0 = 1024, or fewer when max_actors leaves less room (actor and port PIDs share 65536 slots); at most 2048 |
max_links | node links at once (chapter 20; an embedded VM has no node port yet); 0 = 8; at most 2048 |
actor_memory | an actor’s default memory limit in bytes, unless SpawnOpt sets one; 0 = 1 MB; at least 1 KB, at most 1 GB (vm.actor_memory) |
bytes_handles | off-heap Bytes handles in the whole VM; 0 = 4096; at most 65535 (vm.handles) |
bytes_per_actor | of those, how many one actor may hold; 0 = 256, at most bytes_handles |
These are the VM’s parameters, the same on every platform (chapter 6.2,
the keys in 11.3, gogovm’s flags in 12): a field set here beats the host’s
config key of the same parameter (read through its config_get, when it
has one), which beats the library’s default, and a value past the most is
cut to it with one line on stream 2. code.mem has no field: its key or
16 MB. The VM’s config_get answers the fields that are set before
asking the host’s store, so sys.Config("vm.actor_memory") in a program
sees them. So whoever can edit the host’s config store can raise any
parameter the configuration leaves 0: a host that serves sys.Config
from settings its users or tenants edit sets these fields, or filters
the keys of this section (vm.*, node.max_links, code.mem) out of
its config_get. The last three fields were appended after v0.2.0 (the struct is
size-first: a host compiled against an older header passes a smaller
size, and they read as 0).
Changed after v0.2.0 for a host that sets none of these: an actor’s
default limit is 1 MB (was 256 KB), the off-heap Bytes caps 4096 / 256
(were 64 / 16; the table and the lists grow as they are used), and with
GOGO_CONFIG_CODE_LOAD module code may take 16 MB (was 64 KB); and
gogo_new asks the host’s config_get, if it has one, for the vm.*,
node.max_links and code.mem keys.
Over mem_limit, the VM’s allocations fail and the actor that asked is
stopped with oom, as when an actor goes over its own limit
(chapter 6). gogo_new returns GOGO_EINVAL for a configuration it
cannot honour: no size, a flag it does not know, too many actors, a
negative quota, an fs_root that is not a directory.
18.4 The host table and the latched wake
gogo_new takes a gogo_host: the hooks through which the VM reaches the
outside world, and a ctx pointer that every hook gets back. main.c’s
--two mode has a table of its own:
/* No wait hook: this loop sleeps in poll() itself. */
static const gogo_host pipe_host = {
.size = sizeof(gogo_host),
.write = w_write,
.alloc = w_alloc,
.free = w_free,
.now_ms = w_now,
.wake = w_wake,
};
The table, like the configuration, begins with its own size; name the
hooks you set, and leave the rest out (they are NULL). A table filled
at run time starts from GOGO_HOST_INIT:
gogo_host h = GOGO_HOST_INIT;
h.write = my_write;
...
The size is what lets the library grow without breaking a host built
against an older header. Fields are only ever added at the end. A newer
library reads a smaller table’s missing hooks as NULL (and a smaller
configuration’s missing fields as 0); an older library ignores the
fields it does not know. gogo_new copies the table, so it may live on
the stack; the ctx must stay valid until the VM is gone. The structs
the library fills in (gogo_stats, gogo_image_info) work the other way
round: the caller sets size, and the library writes back how much of
it it filled, so a host built against a newer header can tell a field
this library lacks from one that is 0. A size smaller than the v0.2
struct’s (no host has an older one), in or out, or a reserved word that
is not 0, is refused with GOGO_EINVAL, so both can be given a meaning later.
| hook | |
|---|---|
write(ctx, stream, s, n) | output: stream 1 is println, stream 2 crash reports and refusals. Required |
alloc(ctx, n), free(ctx, p, n) | raw memory; NULL from alloc is out of memory. Required, and thread-safe if other threads post |
now_ms(ctx) | a monotonic clock in milliseconds, any epoch. Required |
wake(ctx) | wakes the host’s wait, from any thread |
wait(ctx, timeout_ms) | the idle wait gogo_run uses; NULL if the host steps the VM itself |
unix_time_ms, set_unix_time_ms | a wall clock (an RTC); NULL: the VM keeps its own, unknown until a program sets it |
random(ctx) | 32 random bits; NULL: the VM’s own clock-seeded mixer (not for secrets) |
config_get | the values sys.Config reads; NULL: nothing is set |
config_get (key "\0args") | also how sys.Args gets the program’s arguments: answer the 5-byte key \0args with every argument followed by a NUL byte (so a, empty, b is a\0\0b\0); unset: no arguments; the value is split at NUL bytes, so an argument that holds one would become two |
code_alloc, code_free | special memory for hot-loaded code; NULL: ordinary memory |
destroy(ctx) | called once when the VM is gone, to free the host’s context; NULL: nothing |
A hook that can fail returns 0 for success and a negative GOGO_E* for
failure (set_unix_time_ms refusing a time, a host port’s open
refusing it); hooks that return a value, a length or a time, say what
they return. destroy runs after the VM’s last reference is dropped
(gogo_free, or the last posting thread’s), on that thread, and never
if gogo_new failed.
The hooks run on the VM’s thread, inside gogo_step, except wake (and
alloc/free for posts). gogo_new runs some before it returns, on
its caller’s thread: alloc and free, config_get for the VM’s
parameters (the keys of section 18.3 the configuration leaves unset),
and write for a line about one it clamped; so the ctx must be ready
when gogo_new is called. A hook must not call gogo_step, gogo_run,
gogo_load or gogo_start (they return GOGO_EBUSY), nor gogo_free.
The one rule that matters is the latched wake. A VM that has nothing
to do returns GOGO_IDLE, and the host sleeps until the next timer or
until something wakes it: a post from another thread, an event from a
host port. Such a wake can come at any moment, including just after the
step returned GOGO_IDLE and just before the host goes to sleep. If the
host’s sleep missed it, the VM would sleep through work that is already
there. So:
wakemust latch: a wake while the host is not waiting makes the next wait return at once;- the host consumes the latch before it steps, never between an idle step and its wait.
main.c’s latch is a byte in a pipe. wake writes one; the loop drains
the pipe before it steps the VMs and then sleeps in poll(), which returns
at once if a byte arrived after the drain:
static void w_wake(void *c) {
char b = 1;
ssize_t r = write(((Ctx *)c)->wake_fd, &b, 1); /* full pipe: already latched */
(void)r;
}
A condition variable with a flag works the same way, which is what
gogo_host_posix does: wake sets the flag and signals, wait returns
at once while the flag is set and clears it on the way out.
wake is required with wait, and whenever the host sleeps between steps
in a wait of its own. It may be NULL only for a host that never sleeps
(it steps the VM in a busy loop), or one where nothing can make work while
it sleeps (no posts, no host ports, no other threads).
18.5 Stepping the VM yourself
gogo_run is the simple way: it steps the VM, waits in the host’s wait
while the VM is idle, and returns when the program is done.
gogo_run_thread does the same on a new thread; the VM then belongs to
that thread, the host only posts to it (through posters, section 18.6),
and gogo_join returns the result (gogo_free stops the thread and
joins it first).
A host with its own event loop (a GUI, a game, a server) steps the VM itself:
gogo_step(vm, budget)runs at mostbudgetscheduler passes (0: until idle or done) and returnsGOGO_RUNNABLE(work remains),GOGO_IDLE(nothing to do until a deadline or a wake) orGOGO_DONE;gogo_next_deadline(vm)says when the next timer is due, as anow_msvalue, orGOGO_NEVER.
main.c --two steps two VMs from one loop on one thread, a slice of each
in turn, and sleeps when both are idle:
while (live) {
/* Consume the latch before stepping, never between an idle
* result and the poll below. */
char buf[64];
while (read(fds[0], buf, sizeof buf) > 0) {}
int busy = 0;
int64_t next = GOGO_NEVER;
for (int i = 0; i < 2; i++) {
if (!(live & 1 << i)) continue;
int r = gogo_step(vm[i], 64); /* a slice of work, then the other VM */
if (r == GOGO_DONE || r < 0) { live &= ~(1 << i); if (r < 0) rc = 1; continue; }
if (r == GOGO_RUNNABLE) { busy = 1; continue; }
int64_t d = gogo_next_deadline(vm[i]); /* GOGO_IDLE */
if (d != GOGO_NEVER && (next == GOGO_NEVER || d < next)) next = d;
}
if (busy || !live) continue;
int timeout = -1; /* no deadline: only a wake ends the wait */
if (next != GOGO_NEVER) {
int64_t now = (int64_t)w_now(NULL);
timeout = next <= now ? 0 : next - now > 60000 ? 60000 : (int)(next - now);
}
struct pollfd p = { fds[0], POLLIN, 0 };
if (poll(&p, 1, timeout) < 0 && errno != EINTR) { rc = 1; break; }
}
build/embed-c/main --two httpparse.ggb many_idle.ggb
a| GET /index.html
a| Host = [example.org]
...
a| malformed request, 40 bytes
b| spawned 1000
b| idle memory total: 148000 B
A VM is single-threaded: every call that takes a gogo_vm happens on the
thread that owns it. Other threads get a gogo_poster (section 18.6),
whose calls any thread may make: the type says which is which. Different VMs
may run on different threads at once; the embed tests run 8 VMs on 4
threads, each thread stepping two of them as above
(runtime/embed/test/test_multi.c). In --two nothing wakes the loop
from another thread; the embed tests do (runtime/embed/test/test_embed.c
posts from other threads at the worst moment, just before the wait, many
thousands of times), and so does post.c in the next section.
18.6 Posts: messages from the host
The host sends an actor a message with gogo_post(vm, name, name_len, kind, data, len). The actor must have registered name
(actor.Register, chapter 4), and gets a port.Post{From, Kind, Data}
(From is the zero PID; a host port’s events carry the port’s PID there
instead). Like every name the API takes, name is a pointer and a
length, and need not end in a NUL:
func main() {
actor.Register("greeter", actor.Self())
println("greeter ready")
for {
switch p := actor.Receive().(type) {
case port.Post:
println("hello,", p.Data.String(), "( kind", p.Kind, ")")
}
}
}
examples/embed-c/post.c starts this program, steps it until it is idle
(by then it has registered its name), and posts three names:
while (gogo_step(vm, 0) == GOGO_RUNNABLE) {}
greet(vm, "Ada");
greet(vm, "Grace");
gogo_post(vm, "greeter", 7, 2, "Alan", 4);
gogo_post belongs to the VM’s own thread, like every call on a
gogo_vm. Another thread posts through a poster: a handle made on the
owner’s thread with gogo_poster_new and handed over. Here a second
thread posts two more names and closes posts, while the main thread
runs the VM with gogo_run:
gogo_poster *p = gogo_poster_new(vm); /* made here, used and freed there */
int started = p && pthread_create(&t, NULL, poster, p) == 0;
static void *poster(void *arg) {
gogo_poster *p = arg;
gogo_poster_post(p, "greeter", 7, 1, "Edsger", 6);
gogo_poster_post(p, "greeter", 7, 1, "Barbara", 7);
gogo_poster_close_posts(p); /* no more posts: the VM ends when its actors do */
gogo_poster_free(p);
return NULL;
}
greeter ready
hello, Ada ( kind 1 )
hello, Grace ( kind 1 )
hello, Alan ( kind 2 )
hello, Edsger ( kind 1 )
hello, Barbara ( kind 1 )
posts delivered: 5, dropped: 0
The rules:
- Posts are queued, in a lock-free inbox, and delivered at the VM’s
next step, in order per posting thread. A post copies the data and
wakes the host. At most
GOGO_POST_MAX(256) wait at once (GOGO_EFULLbeyond). - A post to a name nobody holds is dropped when it is delivered, and
counted (
gogo_get_stats). That includes posts sent before the program registered the name, which is whypost.csteps the program first. A post over the receiver’s mailbox quota is dropped too. - Posts keep the VM alive. While posts are open and an actor holds a
registered name, the VM is not done: it can still get posts, so
gogo_runwaits.gogo_close_postsends that: later posts returnGOGO_ECLOSED, and the VM is done once its actors are, as on a board. Without the close,post.c’sgogo_runwould never return. - A poster is a small object of its own.
gogo_poster_newcan fail (NULL: out of memory), and each poster is freed exactly once. Using one after its free, a second free included, is undefined behaviour, which a debug build (GOGO_DEBUG) often catches. - A poster outlives the free. It holds a reference to the VM, so a
thread may post while (or after) the owner calls
gogo_free: its posts then returnGOGO_ECLOSEDinstead of touching freed memory. The VM’s last bytes go back, and the host’sdestroyruns, at the last ofgogo_freeand thegogo_poster_frees. In Rust terms, agogo_vmisSendbut notSync, and agogo_posteris both.
18.7 Host ports
A host can define ports of its own, which Go code opens by name like any
port (chapter 7). This is gogo’s one driver API: the same
gogo_port_driver table, compiled into a firmware or gogovm and
registered with GOGO_BOARD_PORT instead of gogo_register_port, is a
driver of a board (chapter 22, which builds one driver all three ways).
examples/embed-c/port.c defines one called "echo":
/* port.Open("echo", port.Host{Arg, Data}). Events emitted here reach the
* owner once the open succeeds. */
static int echo_open(void *ctx, gogo_vm *vm, gogo_port p, int32_t arg, const uint8_t *data, size_t len) {
(void)ctx;
if (arg < 0) return GOGO_EINVAL; /* refused: port.Open fails with errors.BadArg */
gogo_port_emit(vm, p, arg, data, len);
return 0;
}
/* actor.Send(p, port.Post{Kind, Data}) */
static void echo_command(void *ctx, gogo_vm *vm, gogo_port p, int32_t kind, const uint8_t *data, size_t len) {
int *commands = ctx;
++*commands;
if (kind == 100) {
gogo_port_close(vm, p, GOGO_E_IO); /* the owner gets port.Closed{p, errors.IO} */
return;
}
gogo_port_emit(vm, p, kind + 1, data, len);
}
static const gogo_port_driver echo_driver = {
.size = sizeof(gogo_port_driver),
.open = echo_open,
.command = echo_command,
};
and registers it before the program starts:
if (rc == GOGO_OK && requires(img, len, "echo"))
rc = gogo_register_port(vm, "echo", 4, &echo_driver, &commands); /* before load */
(requires reads the image’s requirements, section 18.9.)
The gogo side (examples/hostecho) opens
it with a port.Host config, sends it port.Post commands and receives
port.Post events:
p, err := port.Open("echo", port.Host{Arg: 7, Data: bytes.FromString("config")})
println("open:", err == nil)
e := event()
println("hello", e.Kind, e.Data.String())
open with Arg -1: false
open an unknown port: false
open: true
hello 7 config
echo 2 4 true
echo -4 0 true
echo 2000000001 12 true
echo 4 300 true
closed
ended by the host: true true
A driver, like the host table, begins with its size; it has three
callbacks, each optional: open (0 accepts, nonzero refuses; NULL
accepts all), command (a port.Post sent to the port)
and close (the port closed, for any reason: the owner exited,
port.Close, actor.Kill, gogo_port_close, gogo_free). They run on
the VM’s thread inside gogo_step, and get the port as a gogo_port: a
nonzero 32-bit value that names that one open port, and no later one in
its slot until 4096 more closes there. The host sends the port’s owner
an event with gogo_port_emit from a callback or between steps, or with
gogo_poster_port_post from any thread (queued like a post). A VM takes
a few host ports (4 in this version; GOGO_EFULL beyond), registered
before gogo_load: an image that opens a host port by a constant name
requires it (section 18.9), and a registration after the load returns
GOGO_ESTATE.
Refusing an open. What open returns is what the program sees. A
negative GOGO_E* that is a shared code negated (gogo_errors.h: from
GOGO_ENOTFOUND, -1, to -GOGO_E_SHARED_LAST) is the error
port.Open returns: GOGO_EINVAL is errors.BadArg, GOGO_ENOMEM
errors.NoMemory, GOGO_EBUSY errors.Busy, -GOGO_E_UNSUPPORTED
errors.Unsupported. Any other nonzero value (GOGO_ESTATE, a positive
number) refuses as errors.Busy. So echo above refuses a negative
Arg with bad argument. Mind that -1 is GOGO_ENOTFOUND, “not
found”: a driver that means “taken” returns GOGO_EBUSY. The Go
binding’s Open does the same with an Errno (section 18.12).
A port can end on the host’s side, when the device behind it goes
away, say. gogo_port_close(vm, port, reason) sends the owner
port.Closed{From, Reason} (chapter 7’s stream event: the port does
nothing more), with a shared code as the reason (GOGO_E_IO is
errors.IO; it must be positive, as 0 is a stream’s Normal half-close),
and closes the port: the driver’s close runs, and the program’s own
port.Close of it later finds a stale PID and does nothing. Every post
already queued is delivered first (the whole inbox, as the next step
would, so the port’s own events come before the end), and the
Closed is never dropped, not even over the owner’s mailbox quota: it
is made when the port opens, as a stream port keeps room for its own. port.c ends its port when it gets a command of Kind 100, and
hostecho waits for the Closed:
actor.Send(q, port.Post{Kind: 100}) // the host ends the port
for ended := false; !ended; {
switch c := actor.Receive().(type) {
case port.Closed:
println("ended by the host:", c.From == q, c.Reason == int(errors.IO))
ended = true
}
}
What a host port may do is the host’s business. They keep the usual port rules: one owner, closed when the
owner exits, port.Handoff gives one away, a stale PID is ignored. While
posts are open an open host port keeps the VM alive, since it can still
get events; gogo_close_posts ends that too.
Names. gogo’s own port drivers have names without a ., and they
are reserved on every board and host, whether or not it has the driver:
gogo_register_port refuses them with GOGO_EEXIST, as it does a
driver of the board’s. In this version the reserved names are:
gpio, netif, udp, tcp, tcp_listen, tls, kbd, power,
imu, ir_tx, ir_rx, mic, speaker, screen, node, ble,
file (gogo/fs’s open files) and float (a requirement, not a driver).
A new driver may add a name to this list in any minor release (ble
came in v0.3). A dotted name with a prefix of your own (acme.ui) is
never reserved, so a host port that must keep working on later releases
takes one; a board port must (chapter 22). An undotted name such as this
section’s echo keeps working until a release reserves it: from then
gogo_register_port returns GOGO_EEXIST for it, so the host finds out
when it starts, never by its program opening gogo’s driver instead of
its own.
18.8 Storage: /flash on a host directory
fs_root names an existing host directory, which the program sees as
/flash (chapter 9). /sd is never mounted. Without fs_root, every
gogo/fs call returns NotMounted.
The program is confined to the directory. Paths are walked from it one
name at a time without following symlinks: a symlink, FIFO or device
inside it is BadPath, and so is opening a file that has other hard links
for writing. A . or .. in a path is BadPath, as on a board. On a host file
system that ignores case (macOS by default), /flash ignores case too.
Two rules are the host’s to keep: the directory must not be writable by
other users (they could link their files in), and VMs running at the same
time must not have nested roots.
fs_quota caps the bytes that the regular files under fs_root may hold.
The VM counts what is there when it is made, then tracks how much each
write grows a file and what truncation, removal and replacement give back.
A write past the quota stores what fits and returns NoSpace, and
fs.Usage reports (used, fs_quota). Two things it does not see:
- only file bytes count. Empty files and directories cost nothing, so a program can create any number of them;
- only the VM’s own changes count. Files the host or another VM adds to the same directory meanwhile make the count approximate.
With fs_quota 0 there is no quota (the host file system’s own limits
apply). The quota belongs to the VM: two VMs on two directories each have
their own.
18.9 Requirements and grant
An image records, by name, what it needs (gogo build infers it; chapter
13 lists the names): the driver of every constant port.Open and /sd
for constant /sd paths. On an embedded VM the drivers are the host ports
registered before gogo_load, and the one mount is /flash when
fs_root serves it. gogo_load refuses an image that requires anything
else with GOGO_EREQUIRES (-10) and names the first missing name on the
error stream. Basic I/O (println, actors, timers, posts) needs nothing.
This version’s library has no board peripherals, so an image that uses
the network, say, is refused. The first missing name in sorted order is
reported, here gpio (netdemo opens buttons too) rather than a network
driver:
build/embed-c/main netdemo.ggb
gogo: image requires gpio, which this VM lacks
gogo_load netdemo.ggb: unsupported: a driver or mount is missing (-10)
A host can read an image’s requirements before it loads it, without a
VM: gogo_image_info_get gives the image’s format and the number of its
requirements and exports, and gogo_image_requires their names, as
gogo_name pairs (pointer and length).
port.c registers its port only for an image that needs it:
static int requires(const void *img, size_t len, const char *want) {
gogo_name names[16];
uint32_t n;
int found = 0;
if (gogo_image_requires(img, len, names, 16, &n) != GOGO_OK) return 0;
for (uint32_t i = 0; i < n && i < 16; i++) {
fprintf(stderr, "requires %.*s\n", (int)names[i].len, names[i].ptr);
if (names[i].len == strlen(want) && memcmp(names[i].ptr, want, names[i].len) == 0) found = 1;
}
return found;
}
The names point into the image and are not NUL-terminated. Each call
validates the whole image once, as gogo_load does, and returns its
errors (GOGO_EIMAGE, GOGO_EVERSION, with the format still filled
in), so they also tell a host whether an image will load at all.
grant narrows what the VM has: a NULL-terminated list of names, and
whatever is not listed is absent for this VM (an image requiring it is
refused, port.Open of it fails, and /flash is not mounted unless
"/flash" is listed). NULL grants everything. The list and its strings
must stay valid while the VM exists.
static const char *const grant[] = { "acme.ui", "/flash", NULL };
gogo_config cfg = GOGO_CONFIG_INIT;
cfg.grant = grant; /* a host port "acme.sensor" registered later stays hidden */
An image whose format is another major, or a newer minor than this
library’s, is refused with GOGO_EVERSION (-27), and both formats are
named (gogo: unsupported image format 15.5 (this VM runs 15.0 to 15.4)).
18.10 Hot loading: GOGO_CONFIG_CODE_LOAD
code.Load (chapter 14) turns bytes into running code, so whether a
program may use it is the host’s decision. Without the flag, the
default, code.Load refuses every module, and the refusal reads as
NoMemory (3): the program cannot tell it from running out of code
memory. Bundled code (the image itself) is unaffected.
examples/hotload loads its worker from /flash, so it needs both
fs_root and GOGO_CONFIG_CODE_LOAD:
build/embed-c/main --flash dir --allow-load hotload.ggb # runs as under gogovm
build/embed-c/main --flash dir hotload.ggb
load /flash/worker_v1.ggb 3
loaded v1: false
18.11 Many VMs
Everything a VM has is its own: its memory and memory cap, actors,
timers and clock, Bytes handles, ports, posts, /flash and quota. The
library has no global state (make lib checks its objects with
tools/globals.sh --objects), so VMs can run side by side on one thread,
as in main.c --two, or on many threads, as in the stress test.
18.12 Hosts in Go: gogotools/embed
A Go program embeds gogo through the package gogotools/embed, a cgo
binding over libgogo.a. It is built with the build tag libgogo:
make lib
CGO_LDFLAGS="-L$PWD/build" go run -tags libgogo ./examples/embed-go
CGO_LDFLAGS names the directory of libgogo.a. go does not notice when
make lib rebuilds the archive, so after that build with -a (make example-embed and make test-gobind relink by themselves). Without the
tag, or without cgo, the package holds only the compiler (section 18.13),
so a plain go build ./... needs neither a C compiler nor the library.
The binding maps the C API one to one: embed.New (with a Config whose
Host holds Go functions for the output, the clocks, random numbers and
sys.Config; zero fields take the OS’s), Load, Start, Step,
NextDeadline, Post, ClosePosts, Stats, Close, and the
image inspection functions GetImageInfo and ImageRequires. Errors are
embed.Errno values, gogo.h’s codes with gogo_strerror’s messages,
wrapped with the call that failed: errors.Is(err, embed.ErrRequires).
Messages are embed.Message{Kind, Data}, a port.Post on the gogo side.
embed.Config holds gogo_config’s fields under Go names; every zero
field takes the default of section 18.3:
embed.Config | gogo_config | meaning |
|---|---|---|
Host | (the gogo_host) | output, clocks, random numbers, sys.Config |
MemLimit | mem_limit | bytes the whole VM may allocate; 0 = no cap |
MaxActors | max_actors | live actors at once; 0 = 16384 |
MaxPorts | max_ports | ports open at once; 0 = 1024, or what MaxActors leaves; at most 2048 |
MaxLinks | max_links | node links at once; 0 = 8; at most 2048 |
ActorMemory | actor_memory | an actor’s default memory limit in bytes; 0 = 1 MB; 1 KB to 1 GB |
BytesHandles | bytes_handles | off-heap Bytes handles in the VM; 0 = 4096; at most 65535 |
BytesPerActor | bytes_per_actor | of those, how many one actor may hold; 0 = 256; at most BytesHandles |
Grant | grant | the requirement names the VM may serve; nil = all it has, an empty slice none |
FSRoot, FSQuota | fs_root, fs_quota | a host directory served as /flash, and its quota |
CodeLoad | GOGO_CONFIG_CODE_LOAD | code.Load may load modules |
As in C, a field that is set beats the Host.Config key of its
parameter (vm.actor_memory, vm.max_ports, …). ActorMemory,
BytesHandles and BytesPerActor past their range are clamped to the
nearer end, with one line on the host’s Stderr (gogo: vm.actor_memory 100 is under 1K; using 1K); MaxActors, MaxPorts and MaxLinks past
theirs, or MaxActors + MaxPorts over 65536, make New fail with
embed.ErrInval. The library does not report the values a VM ends up
with: a program sees the fields that are set, as given, through
sys.Config under their keys, and its own limit through actor.Limit.
examples/embed-go/main.go compiles its program, defines a host port in
Go and runs the VM. A host port is a PortDriver, or a PortFuncs of
the methods it needs; its Port emits events to the port’s owner:
upper := embed.PortFuncs{
OpenFunc: func(p embed.Port, arg int32, data []byte) error {
close(ready) // the program has registered "words"
return nil
},
CommandFunc: func(p embed.Port, m embed.Message) {
p.Emit(embed.Message{Kind: m.Kind, Data: bytes.ToUpper(m.Data)})
},
}
OpenFunc refuses an open by returning an error: an embed.Errno of
a shared code (embed.ErrInval, embed.ErrNoMem, also wrapped) is the
error port.Open gets (errors.BadArg, errors.NoMemory), any other
error errors.Busy, as in C (section 18.7).
A VM is single-threaded, as in C: its methods are not safe for
concurrent use, and its hooks and drivers run inside Step on the
goroutine that calls it (which may move between OS threads: the library
only needs calls not to overlap). Hooks and drivers must not block: a
driver with slow work (a network request, a device read) does it on a
goroutine of its own and delivers the result with Poster.PortPost.
Run checks its context between steps, so a blocked driver delays its
return. Run(ctx) is the loop of section 18.5
in Go: it steps the VM, waits on its Wake channel (the latch) or its
next deadline while it is idle, and returns when the program has finished
or the context ends. Other goroutines post through a Poster, which is
safe for concurrent use. The example runs the VM on a goroutine of its
own and posts from five more:
// Posters are made on the VM's goroutine, before Run takes it over.
posters := make([]*embed.Poster, 5)
for i := range posters {
if posters[i], err = vm.NewPoster(); err != nil {
log.Fatal(err)
}
}
done := make(chan error, 1)
go func() { done <- vm.Run(context.Background()) }()
The Go values the C hooks reach cross as cgo.Handle numbers, so no Go
pointer is kept by C; memory comes from C’s malloc, counted, and the
binding’s tests check that every byte comes back when a VM is closed. A
panic in a hook or driver is caught at the C boundary and raised again
when the call that ran it (Step, Load, …) returns; New too runs
Host.Config and Host.Stderr, and a panic there comes out of New,
which leaves no VM behind. make test-gobind runs the binding’s tests, also under the race detector.
18.13 Compiling in process
A host can also compile source at run time, without the gogo command.
In Go, embed.Compile takes the source files (a map of paths to
contents; CompileFS takes an fs.FS, CompileDir a path) and
returns the image gogo build would make:
img, err := embed.Compile(map[string][]byte{"main.gg": program}, nil)
if err != nil {
log.Fatal(err)
}
Files at the top level are package main; a subdirectory is a user
package, imported under CompileOptions.Root ("app" serves import "app/util"). Errors name the files by their keys (main.gg:3:5: ...).
The search path is empty unless CompileOptions.Path gives one, so a
build reads only its sources and the gogo libraries. Compile writes the
files into a temporary directory, which the compiler reads, and removes
it; calls may run on many goroutines at once.
A C host links libgogoc.a (make libgogoc), the same compiler built
as a Go c-archive, with the header
embed/gogoc/gogoc.h. gogoc_compile
takes a path (a directory or a .gg file) or, with GOGOC_SOURCE, the
text of one file; examples/embed-c/compile.c compiles and runs:
if (gogoc_compile(in, strlen(in), source ? GOGOC_SOURCE : 0, &img, &len, &msg) != 0) {
fprintf(stderr, "%s\n", msg); /* "main.gg:3:5: ..." */
gogoc_free(msg);
return 1;
}
cc -std=c99 -Iembed/gogoc -Iruntime/include -o compile compile.c build/libgogoc.a build/libgogo.a -pthread
./compile -e 'package main
func main() { println("hi", 1+2) }'
On success the image comes with the warnings in msg (or NULL); both
are freed with gogoc_free. The call is thread-safe.
libgogoc.a carries the Go runtime: a 6 MB archive that adds about
5 MB to a program, and a few threads that start with the
program. A process can hold only one Go runtime, so it links at most one
Go c-archive, and a Go program does not link libgogoc.a at all: it
calls embed.Compile. As with libgogo.a, the archive’s objects are
prelinked so that only the gogoc_* functions are global; the Go
runtime’s C symbols (crosscall2, x_cgo_init, …) are local, and
make test-gogoc links a host that defines functions of those names. A
host that only runs precompiled images needs none of this.
18.14 What is stable
From v0.2 the API has a compatibility promise: within a major version
(during 0.x, within a minor) functions keep their signatures and
meaning, and the size-first structs only grow at the end. From v0.3 the
driver API is part of it: host ports here and board ports (chapter 22)
lost their GOGO_EXPERIMENTAL mark, so a driver built against the 0.3
header runs on every 0.3.x. A minor release may still reserve a new
port name (section 18.7); a dotted name is never taken. A part still
taking shape is marked GOGO_EXPERIMENTAL in the headers and may change
in any minor release:
| stable | experimental |
|---|---|
gogo_new, gogo_load, gogo_start, gogo_step, gogo_next_deadline, gogo_run, gogo_free | the flag GOGO_CONFIG_CODE_LOAD; the configuration’s grant, fs_root, fs_quota, max_ports, max_links, actor_memory, bytes_handles and bytes_per_actor |
the host table, gogo_host_posix, gogo_new_posix | gogo_get_stats and its fields |
the configuration’s size, flags, mem_limit, max_actors | gogo_image_info_get, gogo_image_requires |
the error codes, gogo_strerror, gogo_version, gogo_image_format | gogo_run_thread, gogo_join |
gogo_post, gogo_close_posts and the poster (gogo_poster_new, _post, _close_posts, _free) | |
host ports: gogo_register_port, gogo_port_emit, gogo_port_close, gogo_poster_port_post, gogo_port_driver (from v0.3) | |
board ports: gogo_board_port, GOGO_BOARD_PORT (from v0.3, book 22.8) |
GOGO_EXPERIMENTAL expands to nothing. To see every place a program
leans on the experimental part, define it before the include as a
deprecation:
#define GOGO_EXPERIMENTAL __attribute__((deprecated("experimental")))
#include "gogo_posix.h"
The compiler then warns at each use (make test-libgogo builds its
host this way with -Werror, to keep it on the stable part).
The Go binding (gogotools/embed) and libgogoc.a (gogoc.h) are
outside the promise: they may change in any minor release. Their
experimental parts are the C API’s (Grant, FSRoot, FSQuota,
CodeLoad, the VM parameters, Stats, image inspection).
18.15 Limits
- No network, TLS or board peripherals in the library yet; host ports are the way to give a program access to the host’s own devices.
- At most 4 host ports per VM, 256 queued posts, and 255 bytes of name and 262,080 bytes of data per post. A post must also fit the receiver’s memory limit beside its heap and mailbox.
gogo_port_closebelongs to the VM’s thread; a host whose device goes away on another thread hands the news to that thread first (a flag it checks between steps, say).- The
fs_quotacounts regular-file bytes only (section 18.8). libgogoc.abrings the Go runtime, and only one Go runtime fits in a process (section 18.13).
19. Text UI
Both boards have a small colour LCD. So far it has only shown the console:
whatever a program prints scrolls up, in white (red for errors). This
chapter turns the display into a real user interface: a grid of character
cells you can draw anywhere on, in 16 colours, with menus, progress bars and
a status line. It works like ncurses on a terminal, and the same program
runs on the Cardputer, on the StickS3 and on the host, where it draws in
your terminal.
There are two layers:
- The
"screen"port (packagegogo/screen) owns the grid. A program sends it frames of compact drawing operations, and it draws on the LCD the rows that changed. - The
gogo/tuilibrary, written in gogo on top of the port, gives you frames and windows, a few widgets, and keys that work on both boards.
Most programs only need gogo/tui.
19.1 A first screen
package main
import (
"gogo/screen"
"gogo/tui"
)
func main() {
s, ok := tui.Open(screen.Config{Cols: 24, Rows: 5})
if !ok {
println("no screen")
return
}
f := tui.NewFrame(s)
tui.Box(f, 0, 0, 24, 5, "Hello")
tui.Color(f, screen.BrightYellow, screen.Black)
tui.PrintAt(f, 2, 1, "gogo on a screen")
tui.Color(f, screen.BrightGreen, screen.Black)
tui.DrawProgress(f, 2, 2, 15, 2, 3)
tui.Color(f, screen.White, screen.Black)
tui.PrintAt(f, 18, 2, tui.Percent(2, 3))
tui.DrawStatus(tui.Window(f, 1, 1, 22, 3), "status", "ok")
tui.Flush(s)
tui.Close(s)
println("back to the console")
}
tui.Open takes the display. screen.Config{} asks for the whole display:
40 columns by 11 rows on both boards (6 x 12 pixel cells, the console’s
font), and the same by default on the host. This example asks for a
smaller grid so that its output is short. s.Cols and s.Rows give the
size you got. While the screen is open, the console is hidden. It still
takes everything the program prints, and it comes back, whole, when the
screen closes (tui.Close, or the owner’s exit).
Drawing goes into a frame. tui.NewFrame(s) starts one over the whole
screen. Every drawing call adds a few bytes of operations to the screen’s
buffer, and nothing reaches the display until tui.Flush(s) sends them as
one message. The port then draws the whole frame at once, so a half-drawn
frame is never seen.
On the host, when standard output is not a terminal (as in the book’s tests), the VM prints the grid after every frame instead of drawing it:
screen 1 24x5
+------------------------+
|┌ Hello ───────────────┐|
|│ gogo on a screen │| ..bbbbbbbbbbbbbbbb
|│ ██████████░░░░░ 66% │| ..aaaaaaaaaaaaaaa
|│status ok│| .RRRRRRRRRRRRRRRRRRRRRR
|└──────────────────────┘|
+------------------------+
back to the console
The characters after a row show the style of each of its cells:
| Character | Style of the cell |
|---|---|
. | default (White on Black) |
R | reverse |
U | underline |
B | bold |
# | a background other than Black |
| a hex digit | the foreground colour (b is BrightYellow) |
In a terminal, gogo run draws the grid in place, with colours, on the
terminal’s alternate screen. build/gogovm --screen ansi|text|none
chooses explicitly.
19.2 Cells, colours and the drawing calls
Each cell holds one character, a foreground colour, a background colour and three attributes:
- Colours:
screen.Black,Red,Green,Yellow,Blue,Magenta,Cyan,White, then their bright versionsGray,BrightRed… up toBrightWhite(0 to 15). On the LCD they are the VGA palette in RGB565; in a terminal they are the 16 ANSI colours. - Attributes:
screen.Bold(each glyph thickened by one pixel),screen.Underline(the bottom pixel row) andscreen.Reverse(the two colours swapped).
A Chinese character, or any other wide character, takes two cells. The
box-drawing characters (─ │ ┌ ┐ └ ┘ ├ ┤ ┬ ┴ ┼) and the blocks
(█ ░ ▒ ▓ ▀ ▄ ▌ ▐) take one cell each. The LCD draws them as lines and
fills, so they work even with the ASCII-only font (GOGO_FONT_CJK off).
The calls, all on a tui.Frame:
| Call | What it does |
|---|---|
Clear(f) | blanks the frame in the current colours |
Move(f, x, y) | moves the cursor |
Print(f, s) | draws s at the cursor, which moves on; text does not wrap |
PrintAt(f, x, y, s) | Move then Print |
Fill(f, x, y, w, h, ch) | fills a rectangle with one character |
Box(f, x, y, w, h, title) | a frame of lines, with an optional title |
Color(f, fg, bg), Attr(f, a), Style(f, fg, bg, a) | set the colours and attributes for what follows (they stay set across frames) |
Cursor(f, x, y, on) | shows the cursor (a reversed cell) at x, y, or hides it |
Scroll(f, x, y, w, h, n) | moves a rectangle up n rows (down if n is negative) |
Every frame starts with the cursor hidden. The frame remembers which colours, attributes and clip the port already has, and only sends what changes.
Windows. tui.Window(f, x, y, w, h) is a frame over a sub-rectangle.
It has its own origin: 0, 0 is its top-left cell. Everything drawn
through it is clipped to it, and to its parent. Drawing partly or wholly
outside it is fine: that part is dropped. In the example, the status line
belongs to a window inside the box, so it stays within the box’s walls.
tui.Size(w) gives a window’s width and height.
Redraw everything. The simplest way to keep a screen right is to redraw the whole interface after every event: clear, then draw it all. That costs little. The port compares each row at the end of a frame with what it was before, and the LCD only redraws the rows that really changed.
19.3 Widgets
gogo/tui predates methods, so each widget is a plain struct and some
functions. The doc comments in lib/tui give the method form each will
take when the package moves to methods (tui.ListKey(l, k) becomes
l.Key(k), and so on). A widget’s key function returns the updated
struct, which is also how a method with a value receiver would return it.
Label(f, x, y, w, text, align)draws text inwcolumns,tui.Left,CenterorRight. It cuts the text to fit and pads it with spaces, so it also erases what was there before.tui.Width(s)counts columns (wide characters count 2) andtui.Cut(s, w)cuts a string to a width.Box(f, x, y, w, h, title)is listed above.Listis a menu.tui.NewList(items, rows)showsrowsitems at a time.tui.ListKey(l, k)moves the selection with Up and Down, wrapping around at both ends, and returns the item chosen with Enter (-1 for none).tui.DrawList(f, l, x, y, w)draws the selected item in reverse video with a>, and puts^orvin the last column when more items are hidden above or below.DrawProgress(f, x, y, w, value, max)draws a progress bar of full blocks and light shade;tui.Percent(value, max)formats it as"66%".DrawStatus(f, left, right)draws a status line on the frame’s last row, in reverse video, withleftat the start andrightat the end.Editis a one-line text editor for boards with a keyboard.tui.NewEdit(text, max)makes one.tui.EditKey(e, k)inserts characters and handles Backspace, Delete, Left and Right. It returnstui.EditDoneon Enter andtui.EditCancelon Esc.tui.DrawEdit(f, e, x, y, w, focus)draws the text underlined, scrolled so that the cursor shows, and puts the screen’s cursor at the edit position whenfocusis true. It returns the editor with its scroll position; keep that one.
19.4 Keys on both boards
The Cardputer has a keyboard; the StickS3 has two buttons. tui.OpenKeys
opens whichever the board has, and tui.Event turns their messages into
one kind of key, tui.Key{Code, Char}:
-
Keyboard:
KeyUp,KeyDown,KeyLeft,KeyRight(on the Cardputer Fn with;.,/),KeyEnter,KeyEsc(Fn+`),KeyTab,KeyBackspace,KeyDelete, andKeyCharwith the character inCharfor the printable keys. Key releases are dropped. -
Buttons (
tui.Buttons{A: tui.ButtonA, B: tui.ButtonB}: KEY1 on G11 and KEY2 on G12):- pressing A is
KeyEnter; - releasing B is
KeyDown; - releasing B after holding it for
tui.LongPressMs(600 ms) isKeyEsc.
Since lists wrap around, Down alone reaches every item.
- pressing A is
gogo/tui declares kbd optional, so importing it does not make an image
need a keyboard: one image runs on both boards. (Importing gogo/kbd for
its types alone does not require a keyboard either; a constant
port.Open("kbd", ...) in your own code still does.)
Nothing in gogo/tui waits for a message on its own. Your actor keeps its
receive loop and hands each message to tui.Event(s, keys, msg), which
returns the updated key state, the key (KeyNone if the message meant
none) and whether the message was the UI’s at all. A UI message is a key,
a button edge, or a port.Done answering one of the screen’s frames.
Everything else is yours to handle: timers, network events, messages from
other actors. A UI never blocks the rest of a program.
Every port.Done names the port that sent it in From. Event takes
exactly the Dones whose From is the screen’s port (s.Port) and hands
every other one back, so a program that also drives another stream port,
the speaker or a TCP connection, gets each of its own Dones, with its
Seq, untouched.
func main() {
s, ok := tui.Open(screen.Config{Cols: 14, Rows: 4})
keys, kok := tui.OpenKeys(tui.Buttons{A: tui.ButtonA, B: tui.ButtonB})
if !ok || !kok {
println("open failed")
return
}
items := []string{"Tea", "Coffee", "Water"}
l := tui.NewList(items, 3)
draw(s, l)
for {
msg := actor.Receive()
k2, k, ui := tui.Event(s, keys, msg)
keys = k2
if !ui {
continue // not the UI's: a real program handles it here
}
l2, chosen := tui.ListKey(l, k)
l = l2
if chosen >= 0 {
println("chose", items[chosen])
break
}
if k.Code != tui.KeyNone {
draw(s, l)
}
}
tui.CloseKeys(keys)
tui.Close(s)
}
func draw(s tui.Screen, l tui.List) {
f := tui.NewFrame(s)
tui.DrawList(f, l, 0, 0, 14)
tui.DrawStatus(f, "Enter: pick", "")
tui.Flush(s)
}
With the input script key down and key enter it prints two frames, then
chose Coffee.
tui.Run is a ready-made loop for an actor that does nothing but its
UI. You give it three callbacks in a tui.Handlers:
Keygets every key;Msggets every other message (usetui.Ignoreto drop them);Drawredraws the interface.
Key or Msg returns false to end the loop. Run draws and flushes
before the first message and after every call to Key or Msg. The
callbacks share the variables they capture, so they can keep their state
in a local variable of the function that calls Run.
examples/tuidemo is built this way. It is a menu, a job with a progress
bar driven by a timer, a status line, a rename dialog and an About box, and
the same image runs on both boards.
examples/clock is another: a big-digit clock in the spirit of tty-clock,
drawn with tui.Fill blocks, woken every whole second by actor.SendAfter
and set from the network by a second actor with gogo/sntp (config keys
clock.ntp and clock.tz, e.g. gogo config set clock.tz +8).
examples/snake keeps its own receive loop instead: a game whose steps
come from a timer, with a second actor, the autopilot, that plays it.
19.5 The screen port underneath
gogo/tui is plain gogo over a port you can use directly:
package main
import (
"gogo/actor"
"gogo/bytes"
"gogo/port"
"gogo/screen"
)
// waitDone waits up to a second for the port's Done and returns its Seq
// (0: none came). A Done can come late when memory is short: never wait
// for one without a timeout.
func waitDone() int {
for {
msg, ok := actor.ReceiveTimeout(1000)
if !ok {
return 0
}
switch m := msg.(type) {
case port.Done:
return m.Seq
}
}
}
func main() {
p, err := port.Open("screen", screen.Config{Cols: 12, Rows: 2})
if err != nil {
println("no screen")
return
}
switch m := actor.Receive().(type) {
case port.Chunk: // the grid: cols, rows, colours, attributes
println("grid", m.Data.At(0), "x", m.Data.At(1), "colours", m.Data.At(2))
}
b := bytes.NewBuffer(32)
b.Write([]byte{screen.OpMove, 1, 0, screen.OpAttr, screen.Reverse, screen.OpText, 5})
b.WriteString("hello")
b.Write([]byte{screen.OpAttr, 0, screen.OpFill, 0, 1, 12, 1, 0x00, 0x25}) // ─ is U+2500
actor.Send(p, port.Out{Data: b.Freeze()})
println("done", waitDone())
actor.Send(p, port.Out{Data: bytes.FromSlice([]byte{42})}) // not an operation
println("done", waitDone())
port.Close(p)
}
grid 12 x 2 colours 16
screen 1 12x2
+------------+
| hello | .RRRRR
|────────────|
+------------+
done 1
done -1
-
Opening.
port.Open("screen", screen.Config{Cols, Rows}). Zeros mean the whole display. A board refuses a grid larger than its display; the host takes up to 255 x 32. Opening also fails if another actor has the screen. The port’s first message to its owner is aport.ChunkwhoseDatais the grid’s columns, rows, colour count and attribute mask, one byte each. (tui.Openreads it in a helper actor, so your mailbox is not touched.) -
Drawing. Each
port.Outis a frame: a sequence of operations, each an op byte followed by its arguments, coordinates in cells:Operation Arguments What it does OpClearblanks the clip rectangle OpMovex ymoves the cursor OpTextn, then n bytes of UTF-8draws text at the cursor OpColorfg<<4 | bgsets the colours OpAttrmask sets the attributes OpFillx y w h lo hifills with the character lo | hi<<8OpClipx y w hsets the clip rectangle OpScrollx y w h nscrolls a rectangle by the signed byte nOpCursor0or1hides the cursor, or shows it at the current position The package comment of
gogo/screenhas the details. -
Done. The port checks the whole frame first. A malformed frame is drawn not at all and answered with
port.Done{Seq: -1}; a good one is drawn and answered with the nextSeq. EveryOutgets itsDone, in order, but not always at once: when the owner’s memory is too full to take the message, the port tries again every 10 ms, and theDonearrives once the owner has room (waiting inReceiveusually frees it). With 8Dones waiting, a furtherOutis not drawn and getsDone{-1}. So, aswaitDoneabove does, never wait for aDonewithout a timeout. ItsFromis the screen port’s PID. -
Memory. The grid is 4 bytes a cell (1760 bytes for 40 x 11). It is allocated when the port opens and charged to the owner. The frame’s data is read in place, never copied. A frame that changes nothing draws nothing.
On the boards, the console’s render task draws the screen’s rows on the
LCD. While the screen is open the console keeps everything that is printed
and shows it again when the screen closes. The port is a firmware feature:
the GOGO_SCREEN switch, on by default; gogo firmware’s feature is
screen (chapter 12). An image that opens "screen" requires the driver
screen (appendix F), and uses image format 15.1 (screen.Config), so it
needs a firmware of 15.1 or later.
19.6 Limits
- One screen per VM, and one owner at a time.
- No mouse or touch, no pixels: only cells. Characters outside the Basic Multilingual Plane are shown as a box.
- On the host, in a terminal,
printlnoutput lands on top of the grid. Use the text dump, or print nothing while the screen is open. - The StickS3 has no way to move up: lists wrap around instead. Esc (holding B) fires when B is released, with no sign on the screen when the 600 ms have passed.
- While the screen is open on a board, the console is hidden: crash
reports of other actors (and anything printed) show only when the
screen closes, or on the serial console. Watch the serial console
(
gogo monitor) while developing a UI.
See Known issues for the rest.
20. Distributed Actors
An actor on one board can talk to an actor on another board, or on a
server, with the same actor.Send, actor.Call, actor.Monitor and
actor.Link it uses at home. The library is gogo/node. This chapter
builds on chapter 4 (actors, Call) and chapter 5 (links, monitors, exit
reasons).
The shape is a star: one server node (a gogo VM on a computer, with real sockets) and any number of boards that connect to it over TCP. The server relays messages between boards, so a board needs one connection whatever it talks to.
board "cardputer" ---\ /--- board "sticks3"
>--- server node ----<
board "kitchen" -----/ (gogovm --host-net)
20.1 Remote PIDs
A remote actor’s PID is an ordinary actor.PID. You get one from
node.Whereis, or in a message (a Request’s From, a struct field),
and then use it like any other:
| Operation | On a remote PID |
|---|---|
actor.Send(p, m) | the message is encoded, sent over the link and delivered to p’s mailbox |
actor.Call(p, req, ms) / actor.Reply | work unchanged (the reply comes back over the link); a lost node is errors.NoConnection (20.5) |
actor.Monitor(p) | DownMsg when p exits (its reason code), or actor.NoConnection when its node becomes unreachable |
actor.Link(p) / Unlink | exit signals both ways; NoConnection when the node is lost |
==, type switches | as for local PIDs: one remote actor has one PID value on this node |
println(p) | <pid 5@2>: actor slot 5 on node 2 |
actor.Kill(p, code) | an exit signal on p’s node, as for a local actor (p must have been given out by its node; a node’s door cannot be killed, nor linked to) |
actor.SendAfter(p, m, ms) | not across nodes: the sender exits with actor.BadMsg |
actor.Info, actor.Limit, actor.Register | Info and Limit report 0; Register refuses a remote PID (errors.NoProc: names are per node, see node.Register) |
A PID of this node that comes back from another node is the local PID
again, so actor.Self() sent away and back is == actor.Self().
20.2 A server node
The server is a gogo program on a host VM that uses the host’s sockets:
gogovm --host-net, or GOGO_NET=host in the environment, which also
works through gogo run. (Without it the host VM’s tcp port is the
simulated network of the tests, chapter 12.) With it, a program gets the
host’s real network: tcp_listen listens on every interface of the
computer, and tcp may connect anywhere. Do not export GOGO_NET=host
in a shell profile: every gogo run would get real sockets.
func main() {
if err := node.Listen(4370, "server"); err != nil {
println("cannot listen:", err.Error())
return
}
node.Register("echo", actor.Spawn(echo))
...
}
printf 'node.token=<a long random string>\n' >> ~/.gogo/config
GOGO_NET=host build/gogo run server/
node.Listen(port, name) starts the node and returns at once; boards may
join from then on. Its error tells why not, in the codes of gogo/errors
(3.10, appendix C): errors.BadArg without a token, errors.Unsupported
without the host network, errors.Busy if the port is taken or the VM is
a node already. node.Register(name, pid) makes an actor reachable
from other nodes under a name. Names registered with actor.Register stay
local: another node can find only what you node.Register (which
returns errors.Exists for a name already taken).
20.3 Joining from a board
A board needs an address first (gogo/dhcp), then joins:
dhcp.Start(dhcp.Config{})
if err := node.Connect("192.168.1.10:4370", "kitchen"); err != nil {
println("no server:", err.Error())
return
}
echo, err := node.Whereis("server", "echo", 2000)
if err != nil {
return
}
r, err := actor.Call(echo, "hi", 2000)
node.Connect(addr, name) dials the server (a numeric a.b.c.d:port; the
port defaults to node.DefaultPort, 4370), proves the shared token, and
returns nil once the board is a node. Otherwise its error says why:
| Error | Why |
|---|---|
errors.BadArg | no token or name, or addr is not a.b.c.d[:port] |
errors.Busy | the server is at its handshake limit (below): try again later; or this VM is a node already |
errors.Unsupported | the firmware has no network |
errors.Refused, errors.NoRoute, errors.Timeout, … | the TCP connection failed (the tcp port’s reason): the server is not up, or not reachable |
errors.Refused | the server rejected the handshake (another token), or it is full (20.9) |
errors.Timeout | the handshake did not finish in time |
Retry with backoff. Connect makes one attempt. A server takes only
a few connections into their handshake at once (16 on a host with the
default caps, 2 on a board; 20.9) and answers the others busy before
closing them, so when many boards start together (a room of them after a
power cut) most first see errors.Busy. A board may also boot before its
server does and see Refused or Timeout. Write the join as a loop that
waits longer after each failure, with some randomness so that boards
which failed together do not all come back together:
// join tries Connect a few times, waiting 0.2, 0.4, 0.8, 1.6 s (plus up
// to as much again, at random) in between.
func join(addr, name string) error {
wait := 200
for i := 1; ; i++ {
err := node.Connect(addr, name)
if err == nil || i == 5 {
return err // nil, or the last reason: print it
}
actor.Sleep(wait + sys.Random()%wait)
wait *= 2
}
}
A board that must stay joined loops for ever instead, with a cap on the
wait (examples/snake’s joiner: 0.5 s doubling to 3 s, starting over after
each loss of the server). A wrong token is Refused every time; a few
tries then a message that names the error tell it apart from a busy or
missing server. Retrying is the caller’s choice, not Connect’s: only the
program knows how long to keep trying and what to show meanwhile, and a
loop like this one covers the server that is not up yet as well as the
busy one.
node.Whereis(node, name, timeoutMs) asks that node for an exported
name; it works for the server, for other boards (through the relay), and
for the board itself. It fails with errors.NotFound (no such node or
name), errors.Closed (this VM is not a node), errors.Timeout or
errors.NoConnection (the node went away during the lookup).
Both ends need the same token: the config key node.token (gogo config set node.token ...), or node.Options{Token: ...} with
ConnectOpt / ListenOpt. Without one, Connect and Listen return
errors.BadArg. node.name in the config can give the node’s name too.
examples/nodehello is the smallest
complete pair: one program that runs as server or client on the
host, finds a counter, calls it five times and notices the server going
away. Run both with GOGO_NET=host on one computer.
node.Nodes() lists the nodes this one can reach and node.Self() is its
own name. node.Disconnect() drops a board’s link.
20.4 What a message may hold
A message to a remote PID is encoded on the sender’s node and rebuilt on the receiver’s. What may cross:
| Value | Crosses |
|---|---|
int, int64, float32, float64, bool, string, bytes.Bytes, []byte, slices, nil | yes (floats bit for bit) |
| actor PIDs, Refs | yes |
the system structs (actor.Request, port.Chunk, net.Addr, …) | yes |
| your own structs | yes, by name: the receiver must have a struct of the same qualified name (snake/board.View, main.Ping), the same number of fields and the same field kinds (int, string, PID, a slice of int, …); otherwise the receiver drops the message |
your own named non-struct types in an interface (any(Dir(3)) for type Dir int) | yes, by name, as your own structs |
func values, bytes.Buffer, pointers and maps, a port’s PID | no: the sender exits with actor.BadMsg |
| a Ref made by the receiving node itself | no: the receiver drops the message (a peer could otherwise forge a reply or a DownMsg) |
| a value nested deeper than 16, or more than about 4 KB encoded | no: actor.BadMsg |
The simplest way to share message types is a package that both programs
import (chapter 3.1), or one program that plays both parts, as the snake
does (20.8). Two programs that both declare type Ping struct{ From actor.PID; N int } in package main share main.Ping too.
Two differences from a local send: values that share a slice inside one
message arrive as separate copies (local sends keep the sharing), and a
[]any holding itself fails with BadMsg instead of being copied.
20.5 When a node goes away
Links and monitors cover remote actors exactly as local ones, with one
new reason, actor.NoConnection (11): the node holding the actor became
unreachable (its TCP connection ended, or the server reported it gone).
ref := actor.Monitor(remote)
...
case actor.DownMsg:
if m.Ref == ref && m.Reason.Code == actor.NoConnection {
// the server is gone: carry on locally
}
A board that loses the server loses every node at once. Monitoring or
linking a PID whose node is already gone gets the DownMsg or exit
signal at once, as for a dead local actor (with NoConnection). A
Killed exit reaches a linked actor that traps exits as an ExitMsg,
as locally.
A remote actor.Call says why it failed, as a local one does (4.3):
err | When |
|---|---|
errors.NoConnection | at once: the PID’s node is gone, or goes while the Call waits; the PID names nothing here any more (see below); or the node’s table of remote Calls in flight is full (20.9), rather than risk waiting out the timeout |
errors.Timeout | the request or the reply was lost (20.6), or the remote actor had exited |
A Call to a remote actor that has exited on a node that is still up waits
for its timeout the first time (its node answers that the PID is gone,
which removes it here); the Calls after it fail at once with
errors.NoConnection, as a Monitor of that PID reports
NoConnection. Monitor a remote actor whose end you want to hear of at
once.
node.Subscribe() makes the caller receive node.Up{Node} and
node.Down{Node} for every node that joins or goes. Up comes as soon as
the server has the node, possibly before that node’s own Connect has
returned: names it registers afterwards may not be there yet, so
node.Register before Connect what others should find at once. A board that wants
to stay joined connects again after a Down of the server:
node.Subscribe()
for {
if node.Connect(addr, "kitchen") == nil {
waitForServerDown()
}
actor.Sleep(3000)
}
If the node itself dies. gogo/node runs the node in one actor, its
agent (registered locally as node). If it dies for any reason (a bug,
actor.Kill), the node ends as if every link were lost: the links and
the listener end with it, monitors and links of remote PIDs fire with
NoConnection, other nodes see this one go, and the VM is no node any
more (node.Self() is ""; PIDs it gave out reach nothing). gogo/node
does not restart it: call Listen or Connect again, from your own
supervisor as for any other failure, and a fresh node starts.
20.6 Delivery
- At most once. A message is never duplicated. It may be lost: when
the link is full, when the receiver does not have its struct type, or
when it would take the receiver over its memory limit. A
Callwhose request or reply is lost that way waits for its timeout and fails witherrors.Timeout(a Call to a node that is gone fails at once witherrors.NoConnection, 20.5). - In order between one sender and one receiver, relayed or not.
- Backpressure. Each connection’s link actor sends frames to TCP at
TCP’s pace (the stream protocol’s
OutandDone, chapter 10.7) and queues up to 8 KB more; beyond that, messages are dropped and the link stays up. On a host VM the node port writes the socket itself (20.9) and queues up to 256 KB per link in the host’s memory, outside the VM’s limits, before it drops. Senders never block. Unlike a local send, a remote message that would take its receiver over its memory limit is dropped: a peer cannot end a local actor by sending it data.
20.7 Security
- Authentication. Both ends prove the token with a challenge and HMAC-SHA-256; the token itself never crosses the network. A node with the wrong token is refused.
- What a peer can reach. A node’s zero PID is its door, which only
answers
node.Whereisfor names exported withnode.Register; the node’s agent, which keeps the names and the node table, is never reachable from outside. Besides the door, a peer can send to the PIDs this node gave out in a message to any peer (aRequest’sFrom, a field): the list is per node, not per peer, and a PID once seen by one peer may be passed to another. A PID the node never gave out reaches nothing; link, monitor and kill signals need a PID given out, and exit and down signals are accepted only for links and monitors that exist. - Integrity. Both ends derive a session key from the token and the handshake, and every frame carries its number and a MAC (HMAC-SHA-256) over both: a frame changed or injected on the way ends the link, and a replayed or reordered one is refused.
- Not encrypted. The messages travel in plain TCP; someone on the network can read them. Use a trusted network and a long random token (a captured handshake allows guessing a weak one offline). TLS for node links is not there yet (known issues).
- Unauthenticated connections may hold only a few handshakes at a time on a server (its link cap / 32, at least 2 and at most 64: 16 on a host by default, 2 on a board); more are answered busy and closed at once, and a handshake that does not finish within its timeout (5 s) ends. A peer that keeps every slot busy delays other boards’ joins, but holds no more than that many link actors and twice as many ports.
- All nodes with the token are trusted alike.
20.8 Example: the snake’s autopilot on a server
examples/snake runs its autopilot on a
server node when the config key snake.server is set: the game on the
board sends the server’s autopilot a board.View after every step and
gets a board.Move back, one request and one reply per step over Wi-Fi.
The game monitors the remote autopilot; when the link drops, the
DownMsg (reason NoConnection) makes it start a local autopilot at
once, and a joiner actor connects again when the server is back. The
server is the same program with snake.serve on a host VM.
On a StickS3 over Wi-Fi to a Mac on the same network, a View and its
Move took 7 ms at best and 51 ms on average (50 round trips; Wi-Fi
delays a few by several hundred ms).
20.9 Limits
| Limit | Value |
|---|---|
| frame (one message, encoded) | 4096 bytes |
| node links per VM, L | 8 on a board, 512 on a host VM; set with the config key node.max_links or gogovm --max-links (at most 2048 and the open ports, vm.max_ports; on a board also what fits a quarter of its memory; about 1380 boards serve well, below) |
| the node agent’s memory limit | 256 KB on a board; on a host VM the most of that, vm.actor_memory (1 MB) and 64 KB + 320 bytes × L |
| ports per VM | 16 on a board, 1024 on a host VM; vm.max_ports or gogovm --max-ports (at most 2048) |
| ports per link | 1 on a host VM (the node port takes the TCP connection over), 2 on a board (TCP and node port) |
| remote PIDs known at once | 48 + 2L (64 on a board; also at most 4096 minus the port cap) |
| local PIDs given out | 48 + 2L (dead ones are reused) |
| remote links and monitors | 16 + 2L (a full table answers with NoConnection) |
| remote Calls in flight | 8 + L (a Call beyond that fails at once with errors.NoConnection) |
| nesting of a message | 16 |
| queued frames per link | 8 KB on a board (the link actor); 256 KB on a host VM (the node port, host memory) |
| connections in their handshake on a server | L / 32, at least 2, at most 64 (2 on a board, 16 on a host VM); more get errors.Busy |
How many boards a server serves. A host VM serves 512 boards with
the default caps (1024 ports, 512 links), each costing it one port and
one link; tests/dist fills a server to 512 and checks that the 513th is
refused. Raising the caps serves more, up to the link cap: the server’s
node agent, which keeps one entry per board, has a memory limit that
follows the link cap and vm.actor_memory (the most of 256 KB, the
actor default and 320 bytes a link plus 64 KB: 1 MB on a host VM), and
it refuses new boards with errors.Refused only past three quarters of
it, far beyond any link cap (until v0.2 it had a fixed 256 KB and
stopped near 930 boards). What bounds a server now is its 65536 PID
slots: each board takes a port, and the remote PIDs (each board’s door,
the actors that call the server) share the 4096 minus the port cap above
the actors. make test-dist-scale measures it: with 1390 ports and 1380
links (gogovm --max-ports 1390 --max-links 1380), 1380 boards join and
every one of them looks a name up through the server; the 1381st is
refused by the link cap, and the server and its boards carry on. With
more ports there are fewer remote PIDs: at 1410 ports and 1400 links the
boards join but some of their calls go unanswered. The process also
needs a file descriptor per board: raise ulimit -n (often 256 by
default) for a big server. The
tables above are allocated at the first link, about 100 bytes per link of
the cap (some 50 KB at 512), plus about 300 bytes per open link and its
link actor’s heap (at most 40 KB, usually a few).
Many boards at once. A server takes L / 32 connections into their
handshake at a time (16 by default on a host) and answers the others
busy: their Connect fails at once with errors.Busy. A handshake takes
a round trip and two HMACs, a few milliseconds on a LAN, so the slots
admit hundreds of boards a second; boards that retry with backoff (20.3)
all join soon after a power cut, however many start together.
tests/dist starts 24 boards at the same moment on a host server, and
12 on one with 2 slots, and checks that all join. The slots cost the
server a port each, and a busy answer one more for a moment: leave
vm.max_ports at least L + 2 × L / 32 + 1 (the host defaults, 1024
and 512, do). A connection the server cannot even give a port is closed
at once, which a board sees as Busy too.
A board in a big star. A board’s 8 links are enough whatever the size
of the star: it joins one server. Its 64 remote PIDs hold the PIDs it
uses, not one per node: a node’s door is made when node.Whereis first
needs it and may be evicted like any other. tests/dist runs a board,
with the board’s caps and memory, in a star of 300 nodes. Its node agent
keeps a short entry per node (some 100 bytes).
Full tables. When the remote-PID table is full, the least recently
used entry that no link or monitor names makes room. A remote PID that an
actor kept without monitoring it can so go stale: sends to it are
dropped, and it is no longer == a fresh copy of the same PID from a new
message. Monitor the remote PIDs you keep (a subscriber list on the
server, say): a monitored PID is never evicted. When the link’s queue is
full, the message is dropped (counted), and the link stays up: frames
carry their number, and the receiver accepts gaps (20.6).
The VM core gains only the hooks; the rest is the "node" port
(runtime/dist/) and the gogo/node library. The programs of this
chapter are tested as separate VMs on one machine by tests/dist
(go test ./tests/dist/).
21. Best Practices
The earlier chapters say what gogo does. This one says how to use it well. Each section states a problem, the rule that avoids it, and why the rule follows from how gogo works. It assumes chapters 4 to 7, and refers to the chapters on streams (15), audio (16) and HTTPS (17) where they matter.
The short version: every actor is a small machine with its own memory
budget; messages are copies, so keep them small and move bulk data as
bytes.Bytes; never let a producer outrun a consumer; and keep the
per-byte work in C drivers, where the data plane belongs.
21.1 Treat each actor as a small machine
Problem. A program passes under gogo run and fails on the board with
oom.
Rule. Give every actor that does real work an explicit memory limit
with actor.SpawnOpt, sized from a measurement, and test with board
limits.
Why. Every actor has its own memory limit (section 6.2): its heap, its
stack and the messages waiting in its mailbox count against it. The
default is 16 KB on a board and 1 MB on the host, 64 times
more (the config key vm.actor_memory changes both, section 6.2). On top of that, all actors on an ESP32-S3 board share about
160 KB, so ten actors at their full default already take it all. An
idle actor, by contrast, costs about 150 bytes (section 6.1): many
small actors are cheap, a few big ones are not.
func SpawnOpt(f func(), opts Options) PID
type Options struct{ MaxMemory int } // bytes; 0 = the platform default
func Info(p PID) ProcInfo // ProcInfo{Memory int}: bytes charged now
func Limit(p PID) int // the most it may be charged (format 15.8)
This program runs the same job (a table of 5000 ints) three times, with three limits:
// table builds a lookup table of n entries and reports its own memory.
func table(boss actor.PID, n int) {
t := make([]int, 0, n)
for i := 0; i < n; i++ {
t = append(t, i*i)
}
actor.Send(boss, Result{actor.Info(actor.Self()).Memory})
}
// run starts table with the given limit (0: the platform default) and
// says how it ended.
func run(label string, limit int) {
me := actor.Self()
p := actor.SpawnOpt(func() { table(me, 5000) }, actor.Options{MaxMemory: limit})
actor.Monitor(p)
for {
switch m := actor.Receive().(type) {
case Result:
println(label, "ok, uses more than 16 KB:", m.Peak > 16384)
case actor.DownMsg:
if m.Reason.Code == actor.OutOfMemory {
println(label, "OutOfMemory")
}
return
}
}
}
func main() {
run("default limit:", 0) // 1 MB under gogo run, 16 KB on a board
run("board-sized limit:", 16384) // what a board gives by default
run("sized for the job:", 32768) // measured, with room to spare
}
Under gogo run:
default limit: ok, uses more than 16 KB: true
board-sized limit: OutOfMemory
sized for the job: ok, uses more than 16 KB: true
Standard error:
gogo: actor <pid 1> crashed: oom in table
The first line is the trap: with the default limit the job passes on the
host, and on a board it would fail like the second. make test-go also
builds build/gogovm_mcu, a host VM with the board’s limits (16 KB per
actor, 160 KB in all, 1024 actors); GOGO_VM=build/gogovm_mcu gogo run .
runs a program with them, and there the first line says OutOfMemory
too. The third run, with a limit chosen from actor.Info, works on both.
Habits that follow:
- Measure with
actor.Info(p).Memoryat the actor’s busiest moment (a full mailbox, the largest message it handles), then setMaxMemorywith a margin. - Add up the limits of the actors that can be busy at the same time. If the sum is far above 160 KB, the design does not fit the board, whatever the host says.
- Prefer several small actors to one big one: a big actor costs memory and, as section 21.8 shows, time for everyone else.
21.2 Keep messages small; move bulk data as bytes.Bytes
Problem. Passing large values between actors is slow and uses memory twice.
Rule. Messages are small structs. Bulk data (a file chunk, a sound
frame, a screen) travels as a bytes.Bytes, built in a bytes.Buffer and
frozen, and is released as soon as it is not needed.
Why. actor.Send deep-copies the message into the receiver’s memory
(section 6.3). Copying is proportional to the size, it cannot be
preempted (section 21.8), and for a while both actors hold the data. A
frozen Bytes larger than 64 bytes is different: it lives outside the
actor heaps with a reference count, and sending it passes a reference
(section 6.5). It costs the copy once, at Freeze.
What a shared Bytes does not save is accounting:
- Every holder is charged its full size, including a receiver that still has it waiting in its mailbox. Two actors holding the same 4 KB frame are charged 4 KB each.
- At most 16 off-heap
Bytesper actor and 64 in the whole VM on a board (256 and 4096 on the host; the config keyvm.handleschanges both). One more ends the actor withOutOfMemory. - A local variable keeps its
Bytesalive to the end of its block, and aSliceof a largeByteskeeps all of it alive. An actor that keeps the last frame in a variable while it waits inReceiveholds that frame, its charge and its handle for as long as it waits. ABytesnobody reaches any more is freed at its holder’s next garbage collection.
// holder sleeps first, so a frame sent to it waits in its mailbox.
func holder() {
actor.Sleep(50)
for {
actor.Receive()
}
}
// hoarder keeps every frame it makes, until it runs out of handles.
func hoarder(boss actor.PID) {
var kept []bytes.Bytes
for {
kept = append(kept, frame(1000))
actor.Send(boss, len(kept))
}
}
func main() {
f := frame(4000)
a := actor.Spawn(holder)
b := actor.Spawn(holder)
actor.Sleep(10) // both are asleep now
before := actor.Info(a).Memory
actor.Send(a, Frame{1, f})
actor.Send(b, Frame{1, f})
println("queued frame charged to a:", actor.Info(a).Memory-before >= 4000)
println("and to b as well:", actor.Info(b).Memory-before >= 4000)
Then main starts a hoarder under a monitor and waits for it to die.
(frame(n) fills a Buffer with n bytes and freezes it; the whole
program is the book example 21-bytes-cost.)
queued frame charged to a: true
and to b as well: true
hoarder held 256 frames, then: true
Not every Bytes is off-heap. The off-heap ones are mainly the results
of Buffer.Freeze, fs.File.Read and fs.ReadFile over 64 bytes, and
large slices of those. The Data of a stream port’s port.Chunk is built
inside the message and lands on the receiver’s heap, like a small
Bytes: forwarding a Chunk’s data to another actor copies it. For one hop that is the same copy Freeze would make;
when one frame goes to several actors, or through several stages, copy it
into a Buffer and Freeze it once, then pass the frozen one.
21.3 Backpressure
Problem. A producer sends faster than its consumer handles messages.
Rule. Never let a producer run ahead of its consumer without a bound.
Use Call or acknowledgements to keep a fixed number of messages in
flight, let the consumer pull, or reduce the data at the source.
Why. Send never blocks (section 4.1), and queued messages count
against the receiver’s limit (section 6.4). A consumer that falls
behind is not slowed down: its mailbox grows until it exits with
MailboxOverflow, and what is sent to it afterwards is dropped. Section
6.4 shows exactly that: 1000 Samples to a 4 KB consumer that never
reads. This
protects the rest of the system, but the data is lost and the consumer
restarts empty.
The patterns:
- Acknowledgements (a window). The producer keeps at most N messages unacknowledged; the consumer answers each (or each batch) with an ack. The consumer’s mailbox then never holds more than N, so its memory need is known.
Call. A window of one: the producer waits for each answer. Simple, and slower, since nothing overlaps.- Pull. The consumer asks for the next item when it is ready (“give me more”), and the producer keeps what is not asked for, or drops it.
- Reduce at the source. Average, downsample, batch or drop before
sending: one message with the mean of 100 samples instead of 100
messages. Ports do this themselves: the IMU sends one
ChunkperBatchMs, and stream ports drop and count rather than overflow (section 21.9).
Here is section 6.4’s producer and consumer again, with a window of 4:
const Window = 4
type Sample struct {
From actor.PID
N, Value int
}
type Ack struct{}
type Total struct{ N, Sum int }
func consumer(boss actor.PID) {
n, sum := 0, 0
for n < 1000 {
switch m := actor.Receive().(type) {
case Sample:
if n%100 == 0 {
actor.Sleep(1) // slow work
}
n++
sum += m.Value
actor.Send(m.From, Ack{})
}
}
actor.Send(boss, Total{n, sum})
}
func main() {
me := actor.Self()
c := actor.SpawnOpt(func() { consumer(me) }, actor.Options{MaxMemory: 4096})
actor.Monitor(c)
inFlight := 0
for i := 0; i < 1000; i++ {
for inFlight == Window { // wait for room
switch m := actor.Receive().(type) {
case Ack:
inFlight--
case actor.DownMsg:
println("consumer died, reason", m.Reason.Code)
return
}
}
actor.Send(c, Sample{me, i, i % 10})
inFlight++
}
consumer got 1000 samples, sum 4500
The consumer has the same 4 KB limit as in section 6.4 and gets all 1000
samples. The producer runs at the consumer’s pace. The window is also the
memory rule: a consumer’s limit must hold its heap plus Window messages.
21.4 Shared state lives in an actor
Problem. Several actors need the same changing data: settings, a count, a cache.
Rule. One actor owns each piece of state and is the only one that
changes it. Others ask it (Call), tell it (Send), or subscribe to
snapshots it pushes. When one owner becomes a bottleneck, split the state
by key over several owners.
Why. There is nothing else. Package-level variables are read-only (section 3.2, they live in flash), and actors share no memory. The owner’s mailbox serializes every change, so there are no locks and no races: two updates are simply two messages, handled one after the other. A snapshot sent to a reader is a copy, so the reader cannot change the owner’s data, and it is up to date only until the next change.
func owner(shard int) {
var counts []Count
var subs []actor.PID
for {
switch m := actor.Receive().(type) {
case Incr:
counts = incr(counts, m.Key)
for _, s := range subs {
actor.Send(s, Snapshot{shard, counts}) // a copy: readers cannot change it
}
case Subscribe:
subs = append(subs, m.To)
case actor.Request:
switch g := m.Body.(type) {
case Get:
actor.Reply(m, find(counts, g.Key))
}
}
}
}
// shardFor picks the owner of a key: the same key always goes to the same
// shard.
func shardFor(key string, shards []actor.PID) actor.PID {
h := 0
for i := 0; i < len(key); i++ {
h = (h*31 + int(key[i])) % 1024
}
return shards[h%len(shards)]
}
func main() {
shards := []actor.PID{actor.Spawn(func() { owner(0) }), actor.Spawn(func() { owner(1) })}
d := actor.Spawn(display)
for _, s := range shards {
actor.Send(s, Subscribe{d})
}
for _, k := range []string{"door", "fan", "door", "window", "door"} {
actor.Send(shardFor(k, shards), Incr{k})
}
n, err := get("door", shards)
println("door:", n, err == nil)
}
The display actor prints each snapshot it gets:
shard 0: door=1
shard 0: door=2
shard 0: door=2 window=1
shard 0: door=3 window=1
shard 1: fan=1
door: 3 true
Push snapshots when readers need the state often and it changes rarely
(a reader then answers from its own copy, without a round trip); answer
Calls when it changes often and is read rarely. Snapshots are copies, so
keep them small, or send only what changed. Sharding helps only when the
keys are independent: an operation that needs two shards at once is a
sign the split is wrong. Section 10.5’s web server keeps its hit counter
the same way: handlers live for one request, the count lives in an actor.
21.5 Call discipline
Problem. An actor waits forever, or two actors wait for each other.
Rule. Every Call has a timeout, and the caller checks its error:
r, err := actor.Call(p, req, ms); if err != nil { ... }. Requests flow
in one direction: if A calls B, B never calls A.
Why. Call waits only for its own reply and leaves every other
message in the mailbox (section 4.3). Its error says why no reply came:
errors.NoProc (the server was already gone: it fails at once),
errors.NoConnection (the server’s node is gone: at once too), or
errors.Timeout. A server that dies while you wait is not noticed: the
Call waits out the whole timeout and says errors.Timeout (monitor the
server to know sooner). A reply that comes after the timeout stays in
the caller’s mailbox, counted against its limit, until the next
Receive or Call scans past it. So treat errors.Timeout as “no
answer, maybe dead”, and keep timeouts short enough that a dead server
costs little. A server on another board adds lost messages; sections
20.5 and
20.6 say when such a Call fails at once
and when it waits out its timeout.
A cycle is worse. If A calls B and B, while handling that request, calls
A, then A is waiting in Call for B’s reply, and B’s request sits in A’s
mailbox behind it. Neither can go on until a timeout fires:
func sensor(boss actor.PID) {
for {
switch r := actor.Receive().(type) {
case actor.Request:
switch b := r.Body.(type) {
case Read:
// Calls up the hierarchy: a cycle with the controller.
scale, err := actor.Call(boss, GetScale{}, 200)
if err != nil {
println(" sensor: GetScale:", err.Error())
scale = 0
}
actor.Reply(r, 42*scale.(int))
case ReadWith:
actor.Reply(r, 42*b.Scale)
}
}
}
}
The controller calls the sensor with a Read (in the first run) or a
ReadWith{Scale: 10} (in the second); the program measures each:
sensor: GetScale: timed out
cycle: 0 true slow: true
fixed: 420 true slow: false
With the cycle the answer is wrong (0, not 420) and late (200 ms), and the
controller still holds the sensor’s GetScale in its mailbox; when it
answers it, the reply goes to a Call that has given up. The fix is a
one-directional request hierarchy: the controller sends what the
sensor needs with the request (ReadWith), and the sensor never calls
up. When a lower actor must tell a higher one something, it uses Send
(an event), never Call, and the higher one handles it like any other
message. If the higher one must answer, it answers with another Send,
and the lower one waits for that reply message in its own receive loop,
where it can also handle everything else that arrives.
21.6 Be ready to restart
Problem. After a supervisor restarts an actor, its data is gone.
Rule. Keep what must survive a crash in storage (gogo/kv for small
values, files for larger ones) and reload it when the actor starts. Make
everything else cheap to rebuild.
Why. A restarted actor is a new actor: a new PID, an empty heap, an empty mailbox (section 5.6). Its ports were closed with the old one, its names freed, its links gone. That is the point of “let it crash”: the new instance starts from a known state. Whatever the program cannot afford to lose must be outside the actor when it crashes.
// load reads the stored count: 0 if there is none yet.
func load() int {
v, e := kv.Get("count")
if e != fs.OK {
return 0 // fs.NotFound on the first start
}
n, err := strconv.Atoi(v.String())
if err != nil {
return 0
}
return n
}
func counter() {
n := load()
println("counter starts at", n)
actor.Register("counter", actor.Self())
for {
switch r := actor.Receive().(type) {
case actor.Request:
switch r.Body.(type) {
case Incr:
n++
kv.Put("count", strconv.Itoa(n)) // persist before answering
actor.Reply(r, n)
case Get:
actor.Reply(r, n)
case Crash:
zero := 0
println(n / zero)
}
}
}
}
main supervises counter, counts to 3, makes it crash, and counts once
more; its helper finds the counter by name each time, so it reaches the
restarted instance:
counter starts at 0
counter starts at 3
after the crash: 4 true
Standard error:
gogo: actor <pid 2> crashed: divzero in counter
The snake game (examples/snake in the gogo tree) keeps its high score the same way: it
reads snake.hi with kv.Get at start and writes it with kv.Put when a
game beats it. Habits:
- Persist before acknowledging. The counter writes before it replies, so a client that got an answer knows the value is stored.
- Treat only
fs.NotFoundas “no value yet” (section 9.5). Another error is a real failure; replacing the value with a default would destroy data you merely failed to read. - Keep startup cheap. An actor that takes seconds to rebuild its state makes every crash cost seconds. Store compact state, not logs to replay.
- Write rarely.
/flashwears and its writes pause every actor (section 21.8). Save on change, not on a timer, and not for every sample. - Re-register names and re-open ports at start, so clients that look services up by name find the new instance. Clients should not keep a PID across a restart.
21.7 Receive takes the oldest message
Problem. An actor gets a message it did not expect at that moment.
Rule. Handle every message type the actor can receive, in every state. Tag requests with an ID and drop answers to requests you gave up on.
Why. Receive always returns the oldest message in the mailbox,
whatever it is. There is no selective receive: an actor cannot wait for
one kind of message and leave the others queued. The only exception is
Call’s wait for its own reply, which is internal to Call (section
4.3). And messages from one sender arrive in order, but messages from
different senders interleave in any order.
So a state machine must cope with messages that arrive “early” (a Data
before the Start it belongs to, from another sender) and “late” (the
answer to a request that already timed out, an event from a port closed a
moment ago). For each state decide what to do with each type: handle it,
keep it for later, answer “not now”, or drop it on purpose.
// ask sends query id and waits at most timeoutMs for its answer.
func ask(s actor.PID, id, delayMs, timeoutMs int) (int, bool) {
actor.Send(s, Query{id, delayMs, actor.Self()})
deadline := actor.Now() + int64(timeoutMs)
for {
left := int(deadline - actor.Now())
if left <= 0 {
return 0, false
}
m, ok := actor.ReceiveTimeout(left)
if !ok {
return 0, false
}
switch a := m.(type) {
case Answer:
if a.ID == id {
return a.Value, true
}
println(" dropped the late answer to query", a.ID)
default:
println(" dropped a message of an unexpected type")
}
}
}
func main() {
s := actor.Spawn(server)
v, ok := ask(s, 1, 100, 50) // the server needs 100 ms: give up after 50
println("query 1:", v, ok)
actor.Send(actor.Self(), "noise")
v, ok = ask(s, 2, 0, 500)
println("query 2:", v, ok)
}
query 1: 0 false
dropped a message of an unexpected type
dropped the late answer to query 1
query 2: 200 true
Without the ID check, ask(s, 2, ...) would have returned the answer to
query 1. Note that this loop drops whatever else arrives while it waits;
an actor that must not lose those messages keeps them in a slice and
handles them after the wait, or, better, does not wait at all: it sends
the query, returns to its main loop, and handles the answer there as one
more message type. A default case in the main loop makes unexpected
messages visible instead of silently dropped.
21.8 What belongs in C and what in gogo
Problem. One busy actor makes everything else late.
Rule. Loops over thousands of elements per second belong in C, in a driver or port. Decisions made a few to a few hundred times per second belong in actors.
Why. One VM thread runs every actor. Actors are preempted by
reductions (every call and loop iteration costs one; an actor is switched
out after 1000, section 4.1), so a long loop in gogo does not freeze the
others. But it does use the one thread, and gogo code is interpreted:
every byte touched in a loop costs many machine instructions. Some
operations are not preempted at all and stall every actor while they run
(docs/known-issues.md):
- copying a large message, and the mailbox scan of
Call; - garbage collection. An actor’s heap is collected by copying its live data to a new block. A big actor with a lot of live data takes a long collection, and nothing else runs meanwhile;
- storage calls: tens of milliseconds on
/flash(an erase), sometimes hundreds on/sd; - the TLS key exchange: one step of about 200 ms in every handshake (the rest of the 2.5 s handshake is sliced, chapter 17);
- the IMU’s first open after boot, about 250 ms.
So the split is by rate. A driver moves samples with DMA, fills buffers
and hands the VM whole frames; an actor decides what to do with each
frame. Ports are built this way: the IMU driver gathers samples for
BatchMs and sends one Chunk, so the spirit level of section 15.1 runs
its loop over 5 samples five times a second, not 25 times a second over
one:
_, err := port.Open("imu", imu.Config{RateHz: 25, BatchMs: 200})
if err != nil {
println("no motion sensor on this board")
return
}
buf := make([]byte, 0, 240) // one batch: 200 ms at 25 Hz = 5 samples of 12 bytes
for batches := 0; batches < 3; {
switch c := actor.Receive().(type) {
case port.Chunk:
batches++
n := c.Data.Len() / 12
buf = buf[:c.Data.Len()]
c.Data.CopyTo(buf)
At 25 Hz that is fine in gogo. Filtering 16 000 audio samples a second, compressing an image or computing an FFT is not: there is no port for those today, and they would be C functions behind a port (chapter 22 shows how to write one). In gogo, pass such data through without touching each byte (write it to a file, send it on a socket) and keep the per-byte loops for small things: a peak over a short frame, the line parser of section 21.10.
Habits that follow:
- Keep the heap of busy actors small: big state means long collections.
Large data belongs in off-heap
Bytes, which a collection does not copy. - Do slow storage and HTTPS work in actors whose latency does not matter, and do not start an https request while something real-time (recording to a card) is running.
- When a gogo loop shows up as a problem, move it into a driver: that is what ports are for.
21.9 High-bandwidth data: audio, sensors, (future) cameras
Audio, fast sensors and, one day, cameras produce data continuously, at rates where the rules above stop being style and decide whether a design works at all.
Two layers
Split the work in two:
- The data plane is the C driver or port: DMA, the codec, timing, the buffers the hardware fills. It runs at the hardware’s rate and keeps its buffers outside the actors’ heaps. The microphone driver keeps 11 DMA buffers of 30 ms on a board, enough to ride out a 300 ms stall of the VM.
- The control plane is actors: open and close, start and stop, what to do with each frame, where to send it, what to do on failure.
Actors see the data only in whole frames, a few to a few dozen times per second.
The stream protocol
Every port that moves bytes speaks the same four messages (section 7.6, and the exact rules at the start of chapter 15):
- Input is
port.Chunk{From, Seq, TimeMs, Dropped, Data}.Seqcounts from 1, dropped chunks included, so a gap means loss;Droppedsays how many were lost since the last one that arrived;TimeMsis when the data began. - Output is
port.Out{Data}, answered by oneport.Doneeach. At most twoOuts are in flight; a third is refused withDone{Seq: -1}. Send two, then one more for eachDone, and the device never runs dry between them (the speaker plays the second right after the first, section 16.1). - A stream never kills its owner. A
Chunkthat does not fit the owner’s memory is dropped and counted in the next one’sDropped; aDonethat does not fit waits until there is room.
That last rule shapes everything else: when a recorder falls behind, it
loses frames, visibly, and keeps running. Note that a loss is reported by
the next Chunk; frames lost just before the port closes are never
reported.
A pipeline of actors
A recorder that captures sound and writes it to storage is a pipeline:
mic port ──Chunk──► capture ──Frame──► writer ──► /sd (or the network)
◄────Written────
Each stage is its own actor with its own limit, and each can fail and be restarted without taking the others with it: a full card stops the writer, not the capture. The stages pass frames with the window of section 21.3, so no stage can drown the next one.
Here is such a pipeline, runnable on the host with the simulated
microphone (section 16.5; the stdin script is the one chapter 16’s
recorder uses: six mic tone 440 250 lines, each followed by sleep 300). The capture actor opens the mic itself, so the port’s memory
charge falls on its own MaxMemory (section 16.1), keeps at most 2 frames
unacknowledged at the writer and at most 4 waiting, and drops the oldest
waiting frame when the writer falls further behind:
func capture(w actor.PID) {
var mic actor.PID
switch req := actor.Receive().(type) {
case actor.Request: // the opener's Call: open the mic here, under this actor's limit
p, err := port.Open("mic", audio.Mic{RateHz: RateHz, FrameMs: FrameMs})
actor.Reply(req, err == nil)
if err != nil {
return
}
mic = p
}
me := actor.Self()
var queue []Frame
var boss actor.PID
seq, inFlight, micDropped, queueDropped := 0, 0, 0, 0
stopping := false
for {
switch m := actor.Receive().(type) {
case port.Chunk:
micDropped += m.Dropped
seq++
if len(queue) == MaxQueued {
queue = pop(queue) // the writer is behind: drop the oldest
queueDropped++
}
queue = append(queue, Frame{me, seq, m.Data})
case Written:
inFlight--
case actor.Request:
if _, count := m.Body.(Count); count {
actor.Reply(m, seq) // how many frames have come in
break
}
port.Close(mic) // Stop: no more Chunks; finish what is queued
boss = m.From
stopping = true
actor.Reply(m, true)
}
for inFlight < MaxInFlight && len(queue) > 0 {
actor.Send(w, queue[0])
queue = pop(queue)
inFlight++
}
if stopping && inFlight == 0 && len(queue) == 0 {
actor.Send(w, Finish{boss, micDropped, queueDropped})
return
}
}
}
The writer appends each frame to a file and acknowledges it:
func writer(path string) {
f, e := fs.Open(path, fs.Write)
if e != fs.OK {
actor.Exit(actor.Fail(e))
}
frames, n := 0, 0
for {
switch m := actor.Receive().(type) {
case Frame:
if e := f.Write(m.Data); e != fs.OK {
actor.Exit(actor.Fail(e)) // a supervisor decides what next
}
frames++
n += m.Data.Len()
actor.Send(m.From, Written{m.Seq})
case Finish:
f.Close()
actor.Send(m.Boss, Stats{frames, n, m.MicDropped, m.QueueDropped})
return
}
}
}
main spawns both with the limits computed below, records for 1.9 s,
stops the capture with a Call and prints what arrived (the whole
program is the book example 21-pipeline):
capture MaxMemory 18800 writer MaxMemory 9016
frames 15 bytes 24000 mic dropped 0 queue dropped 0
file size 24000
1500 ms of sound at 8000 samples a second is 15 frames of 100 ms, 1600 bytes each, and all of them arrived. Two details matter:
popclears the slot it frees (q[len(q)-1] = Frame{}), so the queue’s array does not keep a frame alive after it was sent.- The writer is where failures happen (a full card, a removed card). It
exits with
actor.Failof the storage error; under a supervisor it restarts with a new file, and the capture should monitor it and treat frames still in flight as lost.gogo/sound(section 16.2) is a one-actor recorder that stops cleanly on a storage error instead.
Memory arithmetic for frames
Section 16.1 gives the microphone’s charge. With F = RateHz * FrameMs / 2000 words per frame (a word is 4 bytes), the owner pays F for the
port’s frame buffer and F + 11 for every Chunk waiting in its mailbox.
To ride out a stall of S ms, during which ceil(S / FrameMs) more frames
arrive, the owner needs:
heap + F + (ceil(S / FrameMs) + 1) * (F + 11) words
A stall is not only the owner’s own slowness: a storage call in any
actor pauses the whole VM (section 21.8), and when it ends the driver
delivers the frames it buffered all at once. At 16 kHz and 100 ms frames
(F = 800), a 300 ms stall needs heap + 4044 words, about 16 KB plus the
heap: more than a board’s default limit by itself. That is why
gogo/sound spawns its recorder with MaxMemory, and why the capture
actor above does too:
// captureMemory, in bytes: the mic's buffer and the Chunks that pile up
// in a stall of StallMs (section 16.1), plus the frames capture keeps
// queued (F words each, plus 8 for the Frame, the Bytes header and the
// queue slot).
func captureMemory() int {
f := frameWords()
stall := (StallMs+FrameMs-1)/FrameMs + 1
return (HeapWords + f + stall*(f+11) + MaxQueued*(f+8)) * 4
}
// writerMemory, in bytes: the frames in flight in its mailbox and the one
// it holds (F words each, plus 10 for the Frame and the message block).
func writerMemory() int {
return (HeapWords + (MaxInFlight+1)*(frameWords()+10)) * 4
}
With 8 kHz, 100 ms frames (F = 400), a 300 ms stall, 1024 words of heap
and 4 queued frames, that is 18 800 bytes for capture and 9016 for the
writer: about 28 KB of the board’s 160 KB for 8 kHz sound. At 16 kHz,
double the frame terms. The numbers are estimates; check them with
actor.Info under load and leave a margin.
What a big frame costs
A frame in flight is charged, in full, to every actor that holds it, the ones that have it waiting in their mailbox included (section 21.2). So each place a frame can be (the port’s buffer, a mailbox, a queue, a file write in progress) is a term in the sum, and each extra stage or extra frame in flight adds a whole frame. When the sum does not fit:
- A
Chunkthat does not fit its owner is dropped by the port and counted in the nextChunk’sDropped. The owner keeps running. - Frames forwarded by actors pile up in the next actor’s mailbox.
That is ordinary messaging: over its limit the receiver exits with
MailboxOverflow, and its supervisor restarts it empty. The window of section 21.3 prevents it. - Too many frozen frames held at once: an actor holding a 17th
off-heap
Bytes, or a VM with all 64 in use, fails the allocation withOutOfMemory(and a streamOutthat needs a handle getsDone{-1}).
Latest frame wins
For live data, a new frame is worth more than an old one. Design so that when something falls behind, old frames are dropped, not queued:
- Keep few frames in flight: two at a stage is enough to overlap work. More only adds latency and memory.
- Release each frame early: write or send it, then drop the reference; do not keep “the last frame” in a variable while waiting.
- Let the driver drop. A port drops and counts when its owner is full; that is the cheapest place to lose data, since nothing was copied. An actor that hoards frames to avoid loss runs out of memory instead, and then loses everything.
- Count and report drops (
Dropped, your own counters), so a slow stage shows up in the logs instead of as a mysterious gap.
Cameras
gogo has no camera port today. A camera driver would follow the same
stream protocol: each frame (a JPEG, say) a Chunk, with Seq, TimeMs
and Dropped, and frames over the owner’s quota dropped and counted.
The arithmetic is harder than for audio. A 10 to 30 KB JPEG frame is
larger than a board’s default per-actor limit of 16 KB by itself, and is
a large share of the 160 KB all actors share. Every holder is charged the
whole frame, so a design with one frame in the port’s buffer, one waiting
and one being sent already needs 30 to 90 KB. Such a design needs very
few frames in flight (one or two), raised MaxMemory limits for the
actors that touch frames, and as few stages as possible.
Keeping frames in driver memory (the StickS3’s PSRAM) and handing actors only a handle to them is a possible future design. It does not exist.
On a board
The same pipeline runs on a board with these changes: /sd/... instead of
/flash/... for long recordings on the Cardputer ADV; 16 kHz for speech;
the limits recomputed for that rate. Timing differs: the host’s simulated
microphone delivers each script line’s sound as a burst at the next poll
(section 16.5), while a board delivers 10 frames a second, in a burst only
after a stall. Run it with build/gogovm_mcu to check the memory limits,
and on the board to check the timing.
21.10 Streaming TCP and HTTP
Network connections are stream ports too, with the same rules, and a few of their own.
TCP as a stream port
A "tcp" connection (section 10.7) speaks the stream protocol:
- Bytes in are
port.Chunks, in order, andDroppedis always 0: instead of dropping, the stack acknowledges a segment only once itsChunkis in the owner’s mailbox, so a slow reader slows the sender down. The owner is never killed by its own connection. - Bytes out are
port.Outs, each answered by aport.Doneonce the peer has acknowledged all of it. At most twoOuts may be in flight (anOutwhoseDoneis still owed counts). A third is refused withDone{Seq: -1}and not sent; the connection carries on. (Older versions closed the connection instead; that changed with the stream protocol.) So countDones, and keep what you could not send yet in aBuffer. An emptyOut, one afterShutdown, and one on a connection that has ended getDone{-1}too. port.Closed{Reason}ends the stream.net.Normal(0) means only that the peer has finished sending: you may still send, thenShutdown. Any other reason means the connection is gone:net.Timeout,net.Refused,net.Reset,net.NoRoute, and for TLSnet.BadCert,net.NoTimeandnet.TLS. They are the shared codes ofgogo/errors(net.Timeoutiserrors.Timeout), the same numbershttp.Uploadreturns.Outs still in flight getDone{-1}before such aClosed. After it, close the port.- One owner per socket. A connection’s events go to the actor that
owns it, and the connection dies with that actor. An accepted connection
is paused until
port.Handoffgives it to the actor that will serve it (section 7.4).
TCP is a byte stream. A Chunk holds whatever the network delivered: half
a line, two lines and a bit, one byte. Never treat a Chunk as a
message. Join the bytes, parse complete frames (a line, a length-prefixed
record) and keep the rest for the next Chunk. Bound the rest: a peer
that never sends the end of a frame must not grow your memory without
limit.
The server pattern
The listener accepts and hands off; one actor per connection does the work. A client that sends garbage crashes only its own actor, and a supervisor keeps the listener alive:
// listener accepts connections and gives each to a new handler actor.
func listener(portNum int) {
_, err := port.Open("tcp_listen", net.Listen{Port: portNum})
if err != nil {
actor.Exit(actor.Fail(errors.Busy)) // the supervisor retries
}
live := 0
for {
switch m := actor.Receive().(type) {
case net.Accepted:
conn := m.Conn
if live >= MaxConns {
port.Close(conn) // refuse: reset
continue
}
h := actor.SpawnOpt(func() { serveConn(conn) }, actor.Options{MaxMemory: ConnMemory})
if !port.Handoff(conn, h) {
port.Close(conn)
actor.Kill(h, actor.Killed)
continue
}
actor.Monitor(h)
live++
case actor.DownMsg:
live-- // a handler ended, however it ended
}
}
}
The handler joins Chunks, answers complete lines, and keeps at most two
Outs in flight:
// flush sends what waits in out while fewer than two Outs are in flight,
// and returns the new count.
func flush(conn actor.PID, out bytes.Buffer, inFlight int) int {
if inFlight < 2 && out.Len() > 0 {
actor.Send(conn, port.Out{Data: out.Freeze()})
inFlight++
}
return inFlight
}
// serveConn owns one connection.
func serveConn(conn actor.PID) {
var partial bytes.Bytes // the start of a line not finished yet
in := bytes.NewBuffer(256)
out := bytes.NewBuffer(256)
inFlight := 0
peerDone := false
for {
switch m := actor.Receive().(type) {
case port.Chunk:
in.WriteBytes(partial)
in.WriteBytes(m.Data)
data := in.Freeze()
start := 0
for i := 0; i < data.Len(); i++ {
if data.At(i) == '\n' {
out.WriteString(answer(data.Slice(start, i).String()))
start = i + 1
}
}
partial = data.Slice(start, data.Len())
if partial.Len() > MaxLine {
port.Close(conn) // no Shutdown: the connection is reset
return
}
case port.Done:
inFlight--
case port.Closed:
if m.Reason != net.Normal { // reset, timeout, link lost
port.Close(conn)
return
}
peerDone = true // the peer finished sending; answer what we have
}
inFlight = flush(conn, out, inFlight)
if peerDone && inFlight == 0 && out.Len() == 0 {
actor.Send(conn, net.Shutdown{})
port.Close(conn) // after Shutdown the stack completes the close
return
}
}
}
gogo run has no network (section 10.1), so on the host the example’s
main plays one connection itself: a stand-in actor sends the handler
the messages a "tcp" port would (Chunks splitting the lines in odd
places: "pi", "ng\nhello wor", "ld\nping\n", "bye", then
Closed{Normal}), answers each Out with a Done, and prints what it
was sent:
no network: one connection through a stand-in
sent: pong
sent: echo: hello world
sent: pong
shutdown after 2 Outs
handler ended, reason 0
The three answers went out in two Outs (the second carried two lines);
the unfinished bye was never answered, because no newline ended it. On a
board, main starts the listener under a supervisor instead. The real
listener and port path is tested too: tests/net runs this example on the
simulated network (TestBookLineServer), with two clients at once, lines
split over segments, the close, and a line over MaxLine that resets only
its own connection.
Limits that shape a server:
- Connections are few. The stack has 4 TCP connection slots, and incoming connections never take the last one, so at most 3 clients are served at once (and the device can always dial out). Each VM also has only 16 port slots in all, shared with files, pins and the rest.
- Give each handler a limit (
ConnMemoryabove) and size it: its heap, theChunks the stack may deliver before it reads them, and what it buffers. The cap times the limit is the server’s memory budget. - Bound everything a client controls: line length (
MaxLine), request size, the time a connection may stay idle. - Close properly.
Shutdownthenport.Closelets the stack finish the close on its own;port.Closealone (or the handler’s exit) resets the connection.
http.Serve (section 10.5) is this pattern already: a listener and one
actor per request, with the head limited to 2 KB, the body to 8 KB and the
wait to 10 s.
HTTP bodies
In gogo/http, bodies are single bytes.Bytes values with fixed limits,
not streams: a response body is read into memory whole, up to
http.MaxBody (8 KB; up to 64 KB with http.Do), and marked Truncated
beyond it; the server takes request bodies up to 8 KB. The whole body is
charged to the actor that gets it, so a caller that wants a 64 KB
response needs a limit to match (section 10.4). There is no streaming
download yet; for a large download, use the "tcp" or "tls" port and a
framing of your own (chapter 17’s warning applies: over TLS, frame the
data, never “read until close”).
Uploads do stream. http.Upload (section 17.4) reads a file 4 KB at
a time and keeps at most two writes in flight, so a 1 MB recording on
/sd goes up with the same memory as a 16 KB one, and is never loaded
whole. Upload recordings that way, never with http.Post of a file read
into memory. Section 17.4’s example shows the calls and the error cases.
Keep-alive and TLS cost
TLS is the most expensive thing a board does on the network:
- A handshake takes about 2.5 s on the StickS3, most of it sliced so other actors keep running, but one step of about 200 ms pauses the whole VM (section 21.8).
- A TLS connection charges its owner about 23 KB (peak about 34 KB
during the handshake), more than a board’s default actor limit; that is
why
gogo/httpruns requests in actors of its own with a larger limit. - A board has one TLS connection at a time. A second https request fails at once while one is open.
So: talk to a server you poll often through one keep-alive http.Client
(section 17.3), which pays for the handshake once; upload through the same
client (http.ClientUpload) when you have one, since a separate Upload
needs the one TLS connection; close a client you no longer need
(http.CloseClient), since while it holds its connection no other https
request can open one; and do not start https work while something
real-time is running.
Timeouts, retries and partial failure
- Every network wait has a timeout:
http.GetandClientDotake one, anet.DialhasTimeoutMs,Calls to network actors have theirs. Give https requests 10 s or more: the handshake alone takes seconds. - A transfer can fail in the middle. A connection ends with
Closed{Reason};http.Uploadreturns that reason as its error, andClientDofails without retrying, because the server may already have acted on the request. Retrying is the program’s decision. - Retry what may pass, with backoff. A timeout, a reset, no route or no answer may pass; a missing file, a bad URL or a bad certificate will not. Wait between attempts, doubling the wait, and give up after a few.
- Add jitter when many devices retry together. Boards that boot
together after a power cut fail together, and with the same waits they
come back together. A random share on top of each wait
(
wait + sys.Random()%wait) spreads them out.node.Connectis the usual case: a server answers the connections beyond its handshake slots witherrors.Busy, which passes once the crowd is in (section 20.3 has the loop). - Restart rather than repair. An upload actor that fails can simply
exit; its supervisor (or its caller) starts a new one, which begins the
upload again from the file.
http.Uploadfollows its caller: if the caller dies, the upload is reset at once, so the next attempt finds the TLS connection free. - Set the clock before TLS. Certificate checks need the date, and a
board does not know it after boot: call
sntp.Synconce the network is up, or every https request fails (net.NoTime, section 17.1).
// transient says whether trying again later may help.
func transient(e errors.Code) bool {
return e == errors.Timeout || e == errors.IO || e == errors.Reset ||
e == errors.Refused || e == errors.NoRoute
}
// uploadWithRetry tries up to attempts times; waitMs doubles after each
// failure. It returns the server's status, or 0 and the last error.
func uploadWithRetry(url, path, token string, attempts, waitMs int) (int, errors.Code) {
for i := 1; ; i++ {
status, err := http.Upload(url, path, "audio/wav", token)
if err == errors.OK && status < 500 {
return status, err // 2xx, or a 4xx that retrying will not fix
}
if err != errors.OK && !transient(err) {
return 0, err
}
if i == attempts {
return status, err
}
println("attempt", i, "failed, error", int(err), "status", status, "- retry in", waitMs, "ms")
actor.Sleep(waitMs)
waitMs *= 2
}
}
On the host there is no network, so every real attempt fails with
errors.IO (8), and the missing file fails at once with
errors.NotFound (1) without a retry (the dns: line is the resolver
saying there is no network):
missing file: 0 1 (not retried)
dns: net.Subscribe failed (no network or 4 subscribers): retrying on each lookup
attempt 1 failed, error 8 status 0 - retry in 100 ms
attempt 2 failed, error 8 status 0 - retry in 200 ms
attempt 3 failed, error 8 status 0 - retry in 400 ms
upload: 0 8 gave up after 700 ms of waits: true
A retried upload may reach the server twice (the first attempt may have arrived before the connection broke), so make uploads safe to repeat: name the file in the URL, so a second copy replaces the first.
21.11 Checklist
Review a design against these:
Memory
- Does every working actor have a
MaxMemory, measured withactor.Info? Does the program run withbuild/gogovm_mcu? - Do the limits of actors busy at the same time fit in 160 KB?
- Are messages small, and is bulk data a frozen
bytes.Bytes? - Does any actor hold many large
Bytesat once (16 per actor, 64 per VM on a board;vm.handles), or keep one alive in a variable while it waits?
Flow
- Can any producer outrun its consumer? Is there a window, a
Call, a pull, or a reduction at the source? - Does every
Callhave a timeout, and is its error handled? - Do requests flow one way, with no
Callcycles? - Does each actor handle every message type it can receive, in every state, including late answers and messages from other senders?
Failure
- Is every long-lived actor under a supervisor, or monitored?
- Is state that must survive a restart in
gogo/kvor a file, written before it is acknowledged, and reloaded at start? - Do restarted services re-register their names and re-open their ports?
Time
- Do loops over thousands of elements per second run in C, not in gogo?
- Are big heaps, storage calls and https requests kept away from real-time work?
Streams
- Does the data plane stay in the driver, with actors seeing whole frames?
- Is
MaxMemorysized for the longest stall, with section 16.1’s formula? - Are few frames in flight (two per stage), released early, with drops counted and reported?
- Are
Outs limited to two in flight, with the rest buffered?
Network
- Are frames parsed from joined
Chunks, never from oneChunk, with bounded partial data? - Does each connection have its own actor, a memory limit, and a cap on how many run at once (at most 3 inbound)?
- Is every
Closedreason handled,Normal(the peer is done) apart from the rest (the connection is gone)? - Are large files uploaded with
http.Upload, not read into memory? - Is there one keep-alive
http.Clientper server, closed when done, and only one TLS connection at a time? - Does every network wait have a timeout, are only transient failures retried, with backoff, and is the clock set before TLS?
22. Extending gogo with C
Sooner or later a program needs something gogo does not have: a sensor on I2C, a codec, a checksum that must run at a million bytes a second, a library that exists only in C. This chapter answers the question “can I link C into my gogo program?”
The short answer is no, not directly, and that is deliberate. gogo has no
foreign function interface (FFI): gogo code never calls a C function. The
one bridge between gogo and C is the port (chapter 7). C code becomes
a port driver, gogo code opens it with port.Open and talks to it with
messages.
There is one driver API for that, runtime/include/gogo.h, the same
header a program that embeds gogo uses (chapter 18). A driver written
against it is a table of three callbacks, and the same table, unchanged,
runs in three places:
- in a firmware, as an ESP-IDF component of your own that registers
itself with
GOGO_BOARD_PORTand is built withgogo firmware -component: no fork of gogo, no gogo source file changed; - in
gogovm, built with the same component (make vm DRIVERS=...), so the driver can be tested on a computer; - in a program that embeds gogo, registered with
gogo_register_port(a host port, section 18.7).
Sections 22.2 to 22.8 are about that API, with a small driver, dice,
built all three ways. The runtime’s own drivers (gpio, kbd, tcp, …)
are written against an internal table instead, PortDriver, which can do
more and promises nothing; sections 22.9 to 22.16 describe it for work on
gogo itself, and 22.17 lists what is still missing.
22.1 No FFI, on purpose
An FFI would let gogo code call crc32(buf, len) the way Go code calls
into cgo. gogo leaves it out because each of the VM’s guarantees would
break at the first such call.
-
Isolation. Every actor has its own heap, and nothing can reach into another actor’s memory (chapter 6). That is what makes “let it crash” safe: a crash ends one actor and frees exactly its memory. C code has no such boundary. A stray write in a C function called from an actor can corrupt any actor’s heap, or the VM’s own tables, and no supervisor can recover from that. A driver is C too, but it never touches actor heaps directly: it reads commands in place and delivers events through the VM, which copies them into the owner’s mailbox under its quota.
-
Preemption. One thread runs every actor, and the VM switches actors after a budget of reductions (section 4.1). A C function cannot be preempted: while it runs, no other actor runs, no timer fires and no event is delivered. A port turns that around: a command returns at once, slow work happens in hardware (DMA, interrupts) or on another task, and the result comes back later as a message.
-
Portability. One image runs on the StickS3, the Cardputer,
gogovmon a laptop and inside any program that embedslibgogo, and it can be hot-loaded over the network (chapter 14). An image is bytecode and constants; it cannot bind to a C symbol, because there is no linker on the device and no symbol table that would be the same on two platforms. A port name is a string, the same everywhere. -
Checked at load. An image lists, by name, the drivers it opens: the compiler records the name of every constant
port.Openas a requirement (docs/design.mdsection 5.4.4). The loader checks each name against the VM’s driver list and refuses an image that needs a driver the firmware lacks, before any of its code runs:gogo: image requires example.dice, which this VM lacksWith FFI there would be nothing to check: a missing or different C function would be found only when it was called, or would crash.
So the question “how do I call C?” becomes “how do I write a port?”. The
answer costs more than an extern declaration, but the result keeps every
property above.
22.2 Two APIs
The driver API, gogo.h (22.2 to 22.8) | The internal table, PortDriver (22.9 to 22.16) | |
|---|---|---|
| Header | runtime/include/gogo.h: versioned, the rules of section 22.8 | runtime/vm/port.h and the VM’s headers: change in any release |
| Lives in | your own code: an ESP-IDF component, a source of a gogovm build, your embedding program | this tree (runtime/, platform/) |
| Runs on | the boards, gogovm, embedding hosts: one table for all | the boards and gogovm |
| Registered by | GOGO_BOARD_PORT (firmware, gogovm), gogo_register_port (a host) | the board’s driver list (esp_ports, unix_ports_all) |
| Message types | port.Host to open, port.Post commands and events | any reserved types, plus the generic ones |
| From an interrupt or another task | a task or thread posts through a gogo_poster (22.7) | the event ring, one writer (22.11) |
| Choose it for | a product’s own hardware, anything outside this tree | gogo’s own drivers |
Both speak to gogo code the same way: a name for port.Open, which is
also the image’s requirement (an image that needs example.dice is refused at
load by a VM without it), commands as messages to the port, events as
messages to its owner. Only the C side differs. Write a third-party
driver on gogo.h.
22.3 A driver on gogo.h: dice
examples/dice-driver is a complete driver
written the way someone outside the project would write one. The
protocol:
port.Open("example.dice", port.Host{Arg: seed}): seed must be positive, else the open fails witherrors.BadArg;actor.Send(p, port.Post{Kind: n}): roll n dice (1 to 10);- one event
port.Post{From: p, Kind: face}per die.
Its directory dice/ is an ESP-IDF component, and its C files include
gogo.h and nothing else of gogo (make example-driver checks that):
examples/dice-driver/
main.gg the gogo program
driver.out its output
host.c an embedding host with the driver (22.5)
dice/ the driver, an ESP-IDF component
CMakeLists.txt
gogo-driver.json the ports it provides (22.4)
dice.h the driver's table and state
dice.c the driver
dice_port.c GOGO_BOARD_PORT: the board's registration (22.4)
The table
A driver is a gogo_port_driver: its size first, then three callbacks,
each optional:
typedef struct gogo_port_driver {
uint32_t size; /* sizeof(gogo_port_driver) as the host was compiled (GOGO_PORT_DRIVER_INIT) */
uint32_t reserved; /* 0 */
open(ctx, vm, port, arg, data, len)isport.Openwith aport.Host{Arg, Data}:argand the bytes ofData. 0 accepts it; a nonzero value refuses it (section 22.6).command(ctx, vm, port, kind, data, len)is aport.Post{Kind, Data}sent to the port by any actor. Anything else sent to it is ignored before the driver sees it.close(ctx, vm, port)says the port has closed, for any reason:port.Close, the owner’s exit,actor.Kill, the end of the VM.
ctx is the pointer given at registration, the driver’s state. port
is a gogo_port, a 32-bit value naming that one open port (a later port
in the same slot gets another value), which the driver uses as the key
of its own per-port state. vm is a handle to give back to the calls
of the API. The dice table:
const gogo_port_driver dice_driver = {
.size = sizeof(gogo_port_driver),
.open = dice_open,
.command = dice_command,
.close = dice_close,
};
and its state, one table per VM, with a slot per open port:
typedef struct DiceTable {
struct {
gogo_port port; /* 0: free */
uint32_t seed;
} slot[DICE_PORTS];
} DiceTable;
Open, command, close
static int dice_open(void *ctx, gogo_vm *vm, gogo_port port, int32_t arg, const uint8_t *data, size_t len) {
DiceTable *t = ctx;
(void)vm, (void)data, (void)len;
if (arg <= 0) return GOGO_EINVAL;
int i = slot_of(t, 0);
if (i < 0) return GOGO_EFULL; /* errors.TooMany */
t->slot[i].port = port;
t->slot[i].seed = (uint32_t)arg;
return 0;
}
GOGO_EINVAL refuses seed 0 with errors.BadArg, and a full table with
errors.TooMany (section 22.6). A command rolls, sending each face to
the port’s owner with gogo_port_emit:
static void dice_command(void *ctx, gogo_vm *vm, gogo_port port, int32_t kind, const uint8_t *data, size_t len) {
DiceTable *t = ctx;
int i = slot_of(t, port);
(void)data, (void)len;
if (i < 0 || kind < 1 || kind > 10) return;
while (kind-- > 0) {
if (gogo_port_emit(vm, port, next_face(&t->slot[i].seed), NULL, 0) != 0) return; /* the owner cannot take more now */
}
}
gogo_port_emit(vm, port, kind, data, len) queues port.Post{From: the port, Kind, Data} (the data copied) on the port’s owner, whoever that
is now: after port.Handoff the events follow the new owner, and the
driver does nothing for it. It never kills anyone: over the owner’s
mailbox quota it returns GOGO_EFULL and the event is dropped, so the
driver stops rolling. A command the driver does not understand (a
Kind out of range) is ignored: any actor holding the port’s PID may
send it anything. close frees the slot:
static void dice_close(void *ctx, gogo_vm *vm, gogo_port port) {
DiceTable *t = ctx;
int i = slot_of(t, port);
(void)vm;
if (i >= 0) t->slot[i].port = 0;
}
Every callback runs on the VM’s thread (the VM task on a board), inside
the scheduler, never at the same time as an actor: it must return
quickly (section 22.7). Besides gogo_port_emit a driver may end its
port from its side with gogo_port_close(vm, port, reason): the owner
gets port.Closed{From, Reason}, which is never dropped, and the port
closes (section 18.7). A close may close other ports this way, as the
two ends of a pipe close each other: closes nest, and a port whose close
has begun answers gogo_port_emit and gogo_port_close with
GOGO_ECLOSED, so the second end’s attempt to close the first is
harmless.
22.4 Into a firmware or gogovm: GOGO_BOARD_PORT
A board registers drivers of its build at boot. One line, in a file of the driver’s own, does it:
static DiceTable dice_table; /* a board runs one VM */
GOGO_BOARD_PORT("example.dice", &dice_driver, &dice_table);
The name. A board port’s name has a vendor prefix: at least one
., as in example.dice or acme.sensor, then letters, digits, _
and -, at most 31 bytes. gogo’s own drivers never have a . in their
names (a test keeps it so), so a third-party port can never be shadowed
by a driver a later gogo adds (a ble of yours would be, the day gogo
gets its own). An embedding host’s ports may do without the prefix (the
names hosts registered before this rule keep working), but should have
one too.
GOGO_BOARD_PORT(name, &driver, ctx) puts a constant entry in a linker
section; no code runs to register it, and no gogo file names it. At
boot, after the VM is made and before the image loads, the firmware (and
gogovm) walks the section and registers every entry as
gogo_register_port would, so an image’s requirement example.dice is
satisfied. Entries are registered in name order. One the board refuses,
because its name is a runtime driver’s (gpio, tcp, …) or the
board’s, or it is longer than 31 bytes, or a board has more than 8, is
named on the serial log at boot and left out. Two entries with one name
are both refused: which one should win would be the link order’s, which
no driver controls, so neither does, and an image that needs the name is
refused loudly instead of talking to the wrong driver:
gogo: board port "alpha" not registered: two board ports have this name (none of them is registered)
The registered ones join the board’s requirement names: gogo device info lists them in provides, and gogovm --provides prints them.
The component
On the ESP32-S3 the driver is an ESP-IDF component:
idf_component_register(SRCS dice.c dice_port.c
INCLUDE_DIRS "."
REQUIRES gogo_api
WHOLE_ARCHIVE)
gogo_api (platform/esp32s3/components/gogo_api) gives it
runtime/include and nothing else. WHOLE_ARCHIVE matters: nothing
calls into dice_port.c, so without it the linker would leave that file
out and the port with it, and the build would still succeed. Two checks
make that loud: gogo firmware -build reads the linker map and fails if
a component put no entry in the firmware (“component dice put no
GOGO_BOARD_PORT in the firmware: register it with WHOLE_ARCHIVE …”),
and the firmware itself knows the names the components’ json files
promised (CONFIG_GOGO_BOARD_PORT_NAMES, which gogo firmware writes)
and says at boot each one it did not register (gogo: board port "example.dice" expected but not registered: ...), for a build made with
idf.py directly or a json that spells the name otherwise than the code.
Beside it, gogo-driver.json tells gogo firmware which requirement
names the component provides:
{"format": 1, "ports": ["example.dice"]}
format is 1, the format of this gogo; a key the tool does not know
is an error, not ignored, so a later format can add keys a build must
understand, and so is a key given twice. At most 8 ports, each named as
above and listed once.
Then one command builds a firmware with it, for the images that need it:
$ gogo build examples/dice-driver -o dice.ggb
$ gogo firmware -board sticks3 -component examples/dice-driver/dice -build dice.ggb
board ports: dice
...
gogo firmware accepts the images’ requirement example.dice because the
component provides it (without -component it stops: “the images
require “example.dice”, which no gogo firmware provides“), turns on the
firmware’s host-port layer (CONFIG_GOGO_BOARD_PORTS) and passes the
directory to idf.py as EXTRA_COMPONENT_DIRS (chapter 12). Flash it
as any firmware (idf.py flash, or gogo setup -release-url with the
build’s files), and the program runs:
$ gogo device info
... provides=gpio,netif,...,/flash,float,example.dice
$ gogo flash dice.ggb
The layer costs about 3.5 KB of flash (the StickS3 firmware with dice
is 4.1 KB larger than the same one without it; posters add a few hundred
bytes more to a driver that uses them) and is linked only into a
firmware built with a board port. A
GOGO_BOARD_PORT of a component linked whole in a build without it
fails to link, naming gogo_board_ports_enabled: turn on
CONFIG_GOGO_BOARD_PORTS.
On gogovm
gogovm always has the layer. make vm DRIVERS=examples/dice-driver/dice
builds it with the component’s *.c files (but *_esp.c, the
ESP-only hardware files of a component, by convention; an entry with no
source is an error), and then:
$ build/gogovm --provides | tail -1
example.dice
$ gogo run examples/dice-driver
open with seed 0: bad argument
...
A driver with hardware puts it behind a small table of its own and gives
gogovm a simulated backend in a host-only file, as the runtime’s own
drivers do (section 22.13): the driver’s logic is tested on the
computer, the board adds the real hardware.
22.5 Into an embedding host
The same table is a host port of a program that embeds gogo. host.c
registers it before the load, and the image runs as on a board that has
the driver:
static DiceTable table;
gogo_vm *vm = NULL;
int rc = gogo_new_posix(NULL, &vm);
if (rc == GOGO_OK) rc = gogo_register_port(vm, "example.dice", 12, &dice_driver, &table); /* before the load */
if (rc == GOGO_OK) rc = gogo_load(vm, img, len, GOGO_LOAD_COPY);
if (rc == GOGO_OK) rc = gogo_run(vm);
dice.c is compiled in unchanged; dice_port.c, the board’s
registration, is not (in a build without a board it would not link).
Chapter 18 covers the rest of the embedding API: section 18.7 the host
ports, 18.12 the same in Go.
The program
main.gg is ordinary gogo. It rolls, hands the port to another actor
(no driver code is involved), and opens a second port with the same seed:
// roll asks the dice port p for n dice and prints the faces.
func roll(who string, p actor.PID, n int) {
actor.Send(p, port.Post{Kind: n})
faces := ""
for got := 0; got < n; {
switch e := actor.Receive().(type) {
case port.Post:
if e.From == p {
faces += " " + strconv.Itoa(e.Kind)
got++
}
}
}
println(who, "rolls"+faces)
}
func main() {
_, err := port.Open("example.dice", port.Host{Arg: 0})
println("open with seed 0:", err.Error())
p, err := port.Open("example.dice", port.Host{Arg: 42})
println("open with seed 42:", err == nil)
roll("main", p, 3)
roll("main", p, 5)
The output is the same on gogovm with the driver, in host.c and on
the StickS3.
Its output:
open with seed 0: bad argument
open with seed 42: true
main rolls 1 5 4
main rolls 3 1 1 1 5
handoff: true
player rolls 2 6 5 2
done
a second port, same seed: true
main rolls 1 5 4
Seed 0 is refused with bad argument, the code the driver returned. The
second port starts the same sequence again, since each port has its own
slot. On a plain gogovm the image does not start at all:
$ gogo run examples/dice-driver
gogo: image requires example.dice, which this VM lacks
make example-driver (part of make test) runs the program on a
gogovm built with the component and in host.c, compares both with
driver.out, checks that a plain gogovm refuses the image and that
dice/ includes only gogo.h, and checks that every C and Go block in
this chapter is cut verbatim from the tree.
22.6 Opening, refusing and owners
port.Open(name, cfg) returns (actor.PID, error). The VM decides most
errors before or after the driver:
| Error | When |
|---|---|
errors.NotFound | no driver of that name in this VM |
errors.BadArg | cfg is not a struct of the driver’s type (port.Host for a gogo.h driver) |
errors.TooMany | the VM’s port table is at its cap (section 22.9) |
errors.NoMemory | the owner cannot take the port |
| the driver’s code | its open refused with a code: a gogo.h driver returns a negative GOGO_E* (the shared code negated), a PortDriver a positive shared code |
errors.Busy | its open refused with any other nonzero value |
A gogo.h driver refuses an open by returning nonzero from open. A
negative GOGO_E* whose code is a shared one (gogo_errors.h, the same
numbers as gogo/errors, negated: GOGO_EINVAL is -GOGO_E_BADARG) is
exactly the error port.Open returns; any other nonzero value
(GOGO_ESTATE, a positive number) means errors.Busy, the generic “the
resource is taken”. Pick the code a caller can act on:
| Return | port.Open gets | For |
|---|---|---|
GOGO_EINVAL | errors.BadArg | a config value the driver will never accept |
GOGO_EBUSY | errors.Busy | a resource someone else holds now |
GOGO_EFULL | errors.TooMany | a table of the driver’s is full |
GOGO_ENOMEM | errors.NoMemory | a buffer that does not fit |
-GOGO_E_UNSUPPORTED | errors.Unsupported | hardware this board lacks |
-GOGO_E_IO | errors.IO | the device did not answer |
Mind that -1 is GOGO_ENOTFOUND (“not found”), not a generic refusal.
Events a driver emits during its own open reach the owner once the
open succeeds; if it refuses, they are discarded. A driver that did set
up hardware before refusing undoes it before it returns.
Owners. The actor that opened the port owns it. Its events go only to
the owner; the owner’s exit closes the port; port.Handoff(p, to) makes
another actor the owner. The driver keeps nothing about the owner: it
emits to the port, and the VM delivers to whoever owns it, so a handoff
needs no driver code, as the dice example shows.
22.7 Events from tasks and threads
A callback must return quickly: while it runs, no actor runs. Slow work
(a bus transfer, a network request, waiting for a sensor) goes to a task
or thread of the driver’s own, and the result comes back as an event
through a poster: gogo_poster_new(vm) (in a callback) makes a
handle that any thread may use, and gogo_poster_port_post(poster, port, kind, data, len) queues port.Post{Kind, Data} for the port’s owner and
wakes the VM. Posts from one thread arrive in the order made; one for a
port that has closed since is dropped. On a board the wake is the VM
task’s latched notification (section 18.4), so a post made while the VM
sleeps is never lost. make test-board-ports has a driver,
runtime/board/test/ports/ticker.c, whose thread posts 2000 events to
its port this way and the program checks each arrives, in order.
The rules:
- Post from a task or a thread, never from an interrupt handler. A post allocates its message (from the heap, which may block), so an ISR hands its data to a task first (a FreeRTOS queue or a task notification), and the task posts.
- The VM’s calls belong to its thread.
gogo_port_emitandgogo_port_closerun only in a callback; from elsewhere the driver posts. On a board thegogo_vmhandle a callback gets takesgogo_port_emit,gogo_port_close,gogo_postandgogo_poster_new, and nothing else of the header (gogo_step,gogo_get_stats, … are libgogo’s).gogo_close_postsandgogo_poster_close_postsdo nothing there: the posts are every driver’s of the board, and close when the program ends; in an embedding host they still close the host’s posts. - A post can fail.
GOGO_EFULLwith 256 posts queued, or with the board’s budget of queued bytes used up (the keyports.postbytes: 16 KB on a board, whose internal RAM Wi-Fi and TLS need too, 1 MB ingogovm, at least 1 KB; a post’s data plus a few dozen bytes count): wait and try again, as the VM frees room when it takes the posts.GOGO_E2BIGfor a post larger than the whole budget, which never fits, so do not retry it: send big data in pieces.GOGO_ECLOSEDonce the VM has finished. So a thread retries onGOGO_EFULLalone, asticker.cdoes. Free the poster (gogo_poster_free) when the thread is done with it. - Never block in
closeon a thread that may be posting.closeruns on the VM’s thread, the only one that drains posts: a driver thread waiting for room (GOGO_EFULL) waits for that very thread, so aclosethat joins it, or waits on a semaphore it gives, deadlocks.closeonly tells the thread to stop (an atomic flag, a task notification); the thread checks the flag before each post and while it waits for room, frees its own poster and ends; thenclosemay join it. Wait for room with a pause (vTaskDelay,nanosleep), not a yield: a driver task of higher priority than the VM task that yields never lets the VM run. A post to a port that has closed is not an error (it is dropped when delivered), so the flag is the thread’s one sign to stop.ticker.cfollows this, andmake test-board-portscloses one with 100,000 posts still to make. - An open port keeps the VM alive, as it may still get events: a program waiting for a sensor’s next reading does not end. Its owner’s exit closes it.
These events do not use the VM’s event ring or an event-source slot, which stay the runtime’s own drivers’ business (section 22.11).
22.8 The stability rules
gogo.h follows the rules written at its top. Within a major version
(during 0.x, within a minor) a function keeps its signature and meaning,
and a struct that starts with its size only grows at the end: a driver
compiled against an older header keeps working with a newer gogo (the
fields it lacks take their defaults), and one compiled against a newer
header works with an older gogo as far as the fields it knows. The
driver part of the header (gogo_port_driver, gogo_board_port,
GOGO_BOARD_PORT, gogo_register_port, gogo_port_emit,
gogo_port_close, gogo_poster_port_post; a driver also uses
gogo_poster_new, gogo_poster_free and gogo_post, stable since
v0.2) joined the promise in v0.3, when it lost its GOGO_EXPERIMENTAL
mark: a driver built against the 0.3 header runs on every 0.3.x. What a
minor release may still add is a reserved port name, never a dotted one
(section 18.7), which is why a board port’s name must have a dot. The
contract the promise freezes includes the parts a driver may trip on:
open’s result (0 accepts, a negated shared code is that error, any
other nonzero value is errors.Busy), closes that nest (section 22.3),
and a post’s results (GOGO_EFULL to retry, GOGO_E2BIG never fits,
section 22.7). The image side needs no rule of its
own: a driver on gogo.h uses only port.Host, port.Post and the
shared error codes, which every image format since they came has, so an
image that opens it runs on any firmware of its format that has the
driver.
What is not promised: everything under runtime/ but runtime/include.
A driver that includes a VM header (port.h, heap.h) is an in-tree
driver, and can break with any release.
Each GOGO_BOARD_PORT entry records the GOGO_VERSION of the header it
was compiled against (gogo_board_port.api), and the board refuses an
entry of another major or, during 0.x, another minor, with a boot line
that names both versions: a driver prebuilt against 0.3 is not run by
0.4 by accident. A driver may also ask gogo_version(), which a board
links as libgogo does.
22.9 The internal driver table
The rest of the chapter is about gogo’s own drivers, for work on gogo
itself. They are written against the VM’s internal headers, which can
change in any release: a driver outside this tree uses gogo.h
(sections 22.2 to 22.8) instead.
An in-tree driver is a PortDriver (runtime/vm/port.h), a table of C
functions with a name:
typedef struct PortDriver {
const char *name;
uint32_t cfg_type; /* reserved type index the cfg struct must have */
uint32_t event_type; /* reserved type of event messages: struct of 2 ints (a, b) */
/* cfg: the cfg struct's int fields in order. 0 = ok; a GOGO_E_* code
* (> 0) refuses for that reason, anything else (< 0) as busy. */
int (*open)(struct Vm *vm, Port *p, uint16_t index, const int32_t *cfg, uint32_t n);
/* A command struct of reserved type `type` whose fields are all int. */
void (*command)(struct Vm *vm, Port *p, uint32_t type, const int32_t *f, uint32_t n);
void (*close)(struct Vm *vm, Port *p);
bool (*can_event)(const struct Vm *vm, const Port *p); /* may still produce events */
followed by five optional fields: handoff, command_term, open_term,
hw and event. Every callback may be NULL. What each field is for:
nameis what gogo code passes toport.Open, and the requirement name the compiler records.cfg_typeis the reserved type the config must have:port.Openwith any other struct fails witherrors.BadArgbefore the driver sees it.opengets the config’s fields, decoded to anint32_tarray (at mostPORT_MAX_FIELDS, 8, and all of them ints). It returns 0 to accept the open, or refuses it with an error code (section 22.6).open_termreplaces it for a config with other fields (a string,Bytes): it gets the config struct itself, read in place on the owner’s heap.commandgets every message sent to the port whose fields are all ints, with its type, so the driver dispatches on the type and ignores the rest.command_termreplaces it for commands with other fields (aport.Out’sBytes): it gets the message itself, read in place on the sender’s heap. Any actor that holds the port’s PID may send it commands; the driver does not see who the owner is unless it asks (port_owner).closeruns when the port closes for any reason:port.Close, the owner’s exit,actor.Killon the port, the end of the VM, and after an open that the VM refuses after the driver accepted it (the charge did not fit, section 22.11).can_eventsays whether the port can still produce events by itself. While any open port says yes, the VM keeps running even when every actor is waiting; a port that only answers commands says no.handoffruns afterport.Handoffgave the port to a new owner (the TCP driver uses it to resume an accepted connection).hwis the driver instance’s hardware layer, a table the board fills. The VM never reads it; the driver finds it atp->drv->hw.eventtakes the driver’s events from the event ring (section 22.11) instead of the VM delivering each one as it is; the driver delivers withport_deliverwhen it wants (gpiodebounces there).
Each open port is a Port in the VM’s port table. Besides its driver
and owner, it has four words of driver-private state (p->state) and
the memory the driver charges to the owner (section 22.11). A driver whose per-port state fits
in 16 bytes needs nothing else. The table has a cap per VM: 16 ports by
default on a board (GOGO_MAX_PORTS), 1024 on gogovm and in an
embedded VM, changed with the config key vm.max_ports or the embedding
config’s max_ports, at most 2048. The first 16 Ports live in the
Vm itself, so opening them takes no memory from the actors’ arena; a
larger table grows in chunks of 16 that never move, so a driver may keep
a Port * for as long as the port is open.
Every callback runs on the VM’s thread, inside the scheduler, never at the same time as an actor. It must return quickly (section 22.16).
22.10 A real driver: gpio
The gpio driver (runtime/gpio/gpio.c, 211 lines) is the smallest driver
that has a config, a command and events from an interrupt; about half of
it is the debounce of its events (below). It is written
once, in the runtime, and each board gives it a hardware layer.
The gogo side
The types are in lib/gpio/gpio.gg, each with a fixed index in every image
(//gogo:reserved N, section 22.14):
// Config configures a "gpio" port: one pin.
//
//gogo:reserved 6
type Config struct {
Pin int
Mode int // Input, InputPullUp, InputPullDown, Output
Edge int // None, Rising, Falling, Both (inputs only)
DebounceMs int // input debounce; <= 0 means the default, 20 ms
}
// Write is a command: drive an output pin to Value (0 or 1).
//
//gogo:reserved 7
type Write struct{ Value int }
// Edge is an event: the pin's level changed; Value is the level after it.
//
//gogo:reserved 8
type Edge struct{ Pin, Value int }
On the C side the same indices are TYPE_GPIO_CONFIG, TYPE_GPIO_WRITE
and TYPE_GPIO_EDGE in runtime/vm/opcodes.h.
The table
runtime/gpio/gpio.h builds the table with a macro, so a board can make an
instance over its own hardware layer in one line:
/* A board's gpio driver instance over its HAL:
* const PortDriver my_gpio_driver = GPIO_DRIVER(&my_gpio_hal); */
#define GPIO_DRIVER(hal) \
{ .name = PORT_NAME_GPIO, .cfg_type = TYPE_GPIO_CONFIG, .event_type = TYPE_GPIO_EDGE, .open = gpio_open, \
.command = gpio_command, .close = gpio_close, .can_event = gpio_can_event, .hw = (hal), \
.event = gpio_event }
The name comes from runtime/vm/port_names.h, the list of every runtime
driver’s name (section 22.12).
Open
gpio_open gets gpio.Config’s four fields as cfg[0..3]. It checks
them, asks the hardware layer to configure the pin, and keeps what it
needs in the port’s state words:
int gpio_open(struct Vm *vm, Port *p, uint16_t index, const int32_t *cfg, uint32_t n) {
const GpioHal *h = hal_of(p);
if (!h || n != 4) return -1;
int32_t pin = cfg[0], mode = cfg[1], edge = cfg[2];
if (pin < 0 || (uint32_t)pin >= h->npins || mode < GPIO_INPUT || mode > GPIO_OUTPUT ||
edge < GPIO_EDGE_NONE || edge > GPIO_BOTH) return -1;
GpioPin *s = &h->pins[pin];
if (reserved(h, (uint32_t)pin) || s->open) return -1;
bool watch = watched((uint32_t)mode, (uint32_t)edge);
uint16_t deb = (uint16_t)(cfg[3] > 0 ? (cfg[3] > 65535 ? 65535 : cfg[3]) : 20);
if (h->config(h->ctx, (uint32_t)pin, mode, watch, &deb) != 0) return -1;
/* A debounced input needs the driver's event source in this VM (it
* may hold a value): refused with TooMany if no source slot is free. */
if (watch && deb && !src_slot(vm) && !port_add_source(vm, &gpio_source, NULL)) {
h->release(h->ctx, (uint32_t)pin, mode, watch);
return GOGO_E_TOOMANY;
}
p->state[0] = (uint32_t)pin;
p->state[1] = (uint32_t)mode << 4 | (uint32_t)edge << 6 | (uint32_t)deb << 16; /* deb: gpio_event */
s->vm = vm;
s->index = index;
s->gen = p->gen;
s->debounce_ms = h->raw_edges ? 0 : deb; /* the bounce filter's window */
s->mode = (uint8_t)mode;
s->edge = (uint8_t)edge;
s->level = (uint8_t)(h->read(h->ctx, (uint32_t)pin) != 0);
s->settled = 1;
vm_barrier(); /* the slot is whole before gpio_edge sees it open */
s->open = 1;
return 0;
}
Three things to notice. Every refusal but one is return -1, which
port.Open reports as errors.Busy (section 22.6): a pin out of range,
a reserved pin, a pin already open; a debounced input that finds no free
event-source slot returns GOGO_E_TOOMANY (the debounce, below). The
port’s state words keep the pin, mode and edge (PIN(p), MODE(p),
EDGE(p) read them back) and the debounce window (below). And the
per-pin slot s is shared with the interrupt handler, so the driver
fills it completely, then publishes it with vm_barrier() before
setting open.
Command and close
void gpio_command(struct Vm *vm, Port *p, uint32_t type, const int32_t *f, uint32_t n) {
(void)vm;
const GpioHal *h = hal_of(p);
if (type != TYPE_GPIO_WRITE || n != 1 || MODE(p) != GPIO_OUTPUT) return;
h->write(h->ctx, PIN(p), f[0] != 0);
}
void gpio_close(struct Vm *vm, Port *p) {
const GpioHal *h = hal_of(p);
uint32_t pin = PIN(p);
GpioPin *s = &h->pins[pin];
s->open = 0;
vm_barrier();
h->release(h->ctx, pin, (int)MODE(p), watched(MODE(p), EDGE(p)));
bool gpio_can_event(const struct Vm *vm, const Port *p) {
(void)vm;
const GpioHal *h = hal_of(p);
return watched(MODE(p), EDGE(p)) && (!h->live || h->live(h->ctx));
}
A command of the wrong type, or a Write to an input pin, is ignored: a
driver never crashes the sender. gpio_close goes on with the debounce’s
bookkeeping (below): a value held for the port is dropped. gpio_can_event is true for a watched
input while the hardware can still produce edges, so a program waiting
for a button press keeps the VM alive.
Events from an interrupt
The board’s interrupt handler reads the pin and calls gpio_edge, which
pushes a PortEvent to the event ring of the VM that opened the pin:
bool gpio_edge(const GpioHal *hal, uint32_t pin, int level, uint32_t now_ms) {
if (pin >= hal->npins) return false;
GpioPin *s = &hal->pins[pin];
if (!s->open || s->mode == GPIO_OUTPUT) return false;
uint8_t lv = level != 0;
if (lv == s->level) return false;
s->level = lv;
uint32_t since = s->settled ? UINT32_MAX : now_ms - s->changed_ms;
s->settled = 0;
s->changed_ms = now_ms;
if (!(s->edge == GPIO_BOTH || s->edge == (lv ? GPIO_RISING : GPIO_FALLING))) return false;
if (s->edge != GPIO_BOTH && since < s->debounce_ms) return false;
PortEvent e;
e.port = s->index;
e.gen = s->gen;
e.a = (int32_t)pin;
e.b = lv;
e.time_ms = now_ms;
evq_push(s->vm, &e);
return true;
}
It never locks and never allocates, so it is safe in an interrupt handler.
The event names the port by index and generation: if the port was closed
in the meantime, the VM finds a stale generation and drops the event. The
scheduler turns each event into the driver’s event_type struct with the
two ints {a, b}, here gpio.Edge{Pin: a, Value: b}, and queues it on the
owner; but gpio has an event hook, so the scheduler hands it each
event first.
Debounce
A button bounces: one press can be a burst of edges within a few
milliseconds. gpio_edge already drops, on a single-edge pin, an edge
that follows the last level change too closely. The rest is done on the
VM thread, in the driver’s event hook, per port, with the DebounceMs
of its config: an edge that comes at least that long after the last
delivery is delivered at once; one inside the window is held (the latest
wins), and when the window ends the held level is delivered if it
differs from the last one delivered:
void gpio_event(struct Vm *vm, Port *p, const PortEvent *e, uint64_t now) {
uint32_t deb = DEB(p);
if (!deb) {
port_deliver(vm, p, e->a, e->b);
return;
}
uint64_t t = event_time(e->time_ms - (uint32_t)vm->t0, now);
flush_due(vm, p, t);
if (!(p->state[1] & DB_DELIVERED) || t >= last_t(p) + deb) {
deliver_at(vm, p, e->b, t);
return;
}
port_deliver is what the scheduler does for a driver without the hook.
The end of a window is a deadline, so the driver registers an event
source (section 22.11) when a VM first opens a debounced input: its
next_deadline is the earliest window end, its pending is true once
that time has come, and its drain delivers what is due. The source’s
context is the number of ports holding a value (no memory to allocate or
free), so a VM with nothing held pays one test per scheduler pass, and
the source stays registered for the VM’s life. If every source slot is
taken, gpio_open refuses the debounced input with
GOGO_E_TOOMANY (port.Open fails with errors.TooMany) rather than
open a pin whose debounce could not work; an output, an input without an
edge or one whose debounce the hardware layer lowered to 0 needs no
slot.
Two hardware layers
On the ESP32-S3 (platform/esp32s3/main/gpio_esp.c) the interrupt handler
is four lines, and the board’s instance is one:
static void gpio_isr(void *arg) {
uint32_t pin = (uint32_t)(uintptr_t)arg;
int level = gpio_get_level((gpio_num_t)pin);
if (gpio_edge(&gpio_esp_hal, pin, level, (uint32_t)platform_esp_ms())) platform_notify();
}
const PortDriver gpio_esp_driver = GPIO_DRIVER(&gpio_esp_hal);
platform_notify wakes the VM task (the latched wake: no wakeup is lost,
section 18.4). On gogovm (platform/unix/gpio_unix.c) the “interrupt” is
a line 12 0 in the stdin script, which the input reader turns into the
same call:
void gpio_unix_set_level(int pin, int level) {
if (gpio_edge(&gpio_unix_hal, (uint32_t)pin, level, (uint32_t)platform_now_ms())) platform_notify();
}
So the simulator runs the very driver the board runs; only the hardware
layer differs. That is the pattern to copy for a new device: the logic
once in runtime/, a small table of hardware hooks per board (design
section 5.11.1).
22.11 Events and memory
There are three ways for a driver to send its owner a message. They differ in where they may be called from and in what happens when the owner’s mailbox is full.
The event ring (evq_push, runtime/vm/evq.h), as gpio does. It is
the only way in from an interrupt handler. Its events are two ints, made
into the driver’s event_type struct (which must therefore be a struct
of two ints), unless the driver takes them itself through its event
hook (as gpio does to debounce, section 22.10). The ring holds
GOGO_EVQ_CAP (64) events per VM; when it is full, new events are
dropped and counted. The ring has one writer: on the ESP32-S3 every
GPIO interrupt runs on the VM’s core, so they never overlap. A second
interrupt that could preempt them, or run on the other core, must not push
to the same ring. Be aware that a ring event is queued like an ordinary
message: one that would take the owner past its memory limit ends the
owner with mailbox_overflow (chapter 6).
Direct delivery (port_deliver_ints, runtime/vm/port.h), on the VM
thread only: from a callback, or from an event source’s drain (below). It
builds a struct of up to 8 fields of any reserved type, ints or immediate
terms (a PID, a bool, the empty Bytes), and queues it. It never kills
anyone: when the owner is gone, out of memory or over its quota, it
returns false and the message is not sent. The power driver delivers a
power.Battery this way and simply tries again at the next sample:
int32_t v[4] = { (int32_t)avg, pct, ch, ext };
if (!port_deliver_ints(vm, w->port, TYPE_POWER_BATTERY, v, 4, 0)) {
dropped_inc(vm); /* not reported: the next sample tries again */
An event source (PortSource, port_add_source) is how a driver
polls. It is not a delivery path of its own but the place to call
port_deliver_ints or the stream helpers from: a set of callbacks the
scheduler asks “is there work now?” (pending), “do it” (drain), and
“when is the next deadline?” (next_deadline). The scheduler never
sleeps while a source has work pending, so pending must turn false once
drain has done what it can; work that waits for time belongs in the
deadline. The keyboard driver is the pattern for interrupt-driven hardware
that must be read over a bus: its interrupt only sets a flag, and the
source reads the chip on the VM thread when the flag is up. The input
drivers (kbd, power, imu, ir, mic, speaker) share one source,
runtime/input/source.c.
Charging the owner
Memory a driver keeps for a port is the owner’s, so it counts against the owner’s limit like its heap does:
p->charge_words, set inopen: the words of state the driver keeps outside thePortfor this port (a TCP control block, say). The VM charges them to the owner afteropenreturns 0; if they do not fit, it calls the driver’scloseandport.Openfails witherrors.NoMemory. The charge moves withport.Handoffand is given back at close.p->room_64w, set inopen: how much more the owner must have free (in 64-word units) for the driver’s largest event, checked once at open and not charged. A port whose every event would be over the owner’s quota is refused at once instead of dropping everything silently.port_bytes_new/port_bytes_retain: off-heapBytesthe port holds for its owner (at most 2), charged to the owner, released at close, moved byHandoff.
A driver does not malloc per event. Event messages are allocated by the
VM and charged to the receiver when queued; a driver’s own buffers are
fixed (static storage on the board, Port.state, or a charged table).
Streams
A driver that moves bytes uses the stream protocol (section 7.6, and
lib/port/port.gg): port.Chunk events bring input, port.Out commands
send output, each Out is answered by one port.Done, and port.Closed
says the port ended by itself. runtime/stream/stream.h implements the
rules once, for every byte port (IMU, IR, audio, TCP, TLS, the screen):
bool stream_deliver_chunk(struct Vm *vm, const Port *p, StreamIn *s, uint32_t time_ms,
const uint8_t *data, uint32_t len);
int stream_out_accept(struct Vm *vm, const struct Actor *from, Port *p, StreamOut *o,
term msg, StreamCheck check);
bool stream_out_done(struct Vm *vm, Port *p, StreamOut *o);
stream_deliver_chunk copies the data into a Chunk and queues it,
dropping and counting it (in the next Chunk’s Dropped) when the owner
has no room. A driver’s command_term hands each message to
stream_out_accept, which keeps at most two Outs in flight (the data
pinned for the port) and answers a third with Done{Seq: -1}; when the
hardware has finished the head, the driver calls stream_out_done (or
stream_out_fail), and a Done the owner has no room for is owed and
sent later by stream_out_flush. A StreamOut is 16 bytes: it fits
Port.state exactly.
Closed{From, Reason} is sent with port_deliver_ints, the reason a
shared error code (runtime/include/gogo_errors.h, the same numbers as
gogo/errors), as the TCP driver does:
static bool post(Vm *vm, const Port *p, uint32_t type, int32_t reason) {
int32_t v[2] = { (int32_t)p->id, reason };
return port_deliver_ints(vm, p, type, v, type == TYPE_CLOSED ? 2u : 0u, PORT_RAW(0));
}
PORT_RAW(0) says that field 0 is a term (the port’s PID, p->id), not an
int. Reason 0 (errors.OK) is reserved for a stream’s half-close (“the
peer finished sending”); a port that is finished for good sends a
positive code such as GOGO_E_IO, and does nothing more.
22.12 Requirement names and optional features
The driver’s name is the requirement name. The compiler records it for
every constant port.Open("name", ...) in the program and its packages,
and the loader refuses an image whose names the VM does not have; a
driver opened by a name computed at run time requires nothing (the build
warns), and a name listed in a package’s //gogo:optional directive is
left out for programs that handle its absence. There is no separate
capability table: a board’s capabilities are exactly the drivers in its
list. So adding a driver to the tree means:
-
The name goes in
runtime/vm/port_names.has aPORT_NAME_*macro, and the driver uses the macro.tests/portnames_test.gofailsmake testfor a driver name spelled as a literal inruntime/orplatform/, and for aPORT_NAME_*that nogogo/...package opens and no firmware feature provides. The list is also what the embedding layer refuses as host port names, so no host can shadow a runtime driver. -
The board lists it. On the ESP32-S3,
esp_portsinplatform/esp32s3/main/platform_esp.clists the drivers a build has, each behind its switches:static const struct PortDriver *const esp_ports[] = { &gpio_esp_driver, #if CONFIG_GOGO_NET &net_netif_driver, &net_udp_driver, &net_tcp_driver, &net_tcp_listen_driver, #endifOn
gogovm,unix_ports_allinplatform/unix/main.clists them, andgogovm --without NAME,...(for tests) leaves names out to model a firmware without them. -
A compile-time switch, to make the driver optional like the existing features (design section 5.4.5): a
config GOGO_Xinplatform/esp32s3/main/Kconfig.projbuild,#if CONFIG_GOGO_Xaround its entry inesp_ports(andHAS_Xfromboard.hif only some boards have the hardware), its sources added conditionally inplatform/esp32s3/main/CMakeLists.txt, and a row infwFeaturesincmd/gogo/firmware.go, so thatgogo firmwareturns the feature on when an image requires the name:{name: "power", kconf: "CONFIG_GOGO_BATTERY", provides: []string{"power"}},TestFirmwareTableMatchesSourceschecks that table againstboard.handKconfig.projbuild. A switched-off driver is simply not in the list:port.Openreturnserrors.NotFound, and an image that requires it is refused, exactly as on a board without the hardware.
gogo firmware knows the names in its table, and those that a
-component’s gogo-driver.json provides (section 22.4): for any other
name it stops with “the images require “x”, which no gogo firmware
provides“.
22.13 Simulating the driver on the host VM
A driver that exists only on the board can be tested only on the board.
The existing devices avoid that by having a second hardware layer in
platform/unix, so gogovm runs the same driver code on a computer, fed
by a script on stdin (the input file next to a book example):
gpio:gpio_unix.c, script lines<pin> <0|1>, andgogo run --key c=pinin a terminal;kbd,power,imu,ir_rx,mic:input_unix.c, lines such askey enter,battery 3900 1 1,imu gesture tap,ir rx 9000 4500 ...andmic tone 440 200;ir_txandspeakerprint what they would send on stderr and stay busy for as long as the real hardware would.
input_unix.c is the only reader of stdin, so a new device adds its script
lines there and its hardware layer next to it (platform/unix/x_unix.c),
lists its instance in unix_ports_all, and adds the file to the Makefile’s
gogovm sources. Then a golden test or a book example can run programs
that use it under make test, and --without x covers the “board without
it” case.
22.14 The gogo side: types
The gpio driver needs three struct types, and the VM must know them by
number: it checks a config’s type, decodes commands by type and builds
gpio.Edge events itself. Such types are reserved: each has a fixed
index in every image (//gogo:reserved 6 in the .gg source, TYPE_GPIO_CONFIG
in C). A new driver with types of its own needs:
- a system package in
lib/with the types, each marked//gogo:reserved N(onlygogo/...packages may reserve types), with a row inlib/README.md; - the types appended to
reservedTypesincompiler/codegen.go(andreservedName, and the package path incompiler/load.go); TYPE_*constants,TYPE_RESERVED_COUNTandTYPE_NFIELDSinruntime/vm/opcodes.h, whichcompiler/asm_test.gochecks against the compiler’s table;- a new image format minor: reserved types are append-only and a new
one is a format change (
IMAGE_MINORinruntime/vm/image.h, the type intypeMinorincompiler/image.go), so an image that uses the new types runs only on firmware of that format or later.
That is a lot of the VM to touch for one peripheral, and a firmware
update for every user. A driver can avoid all of it by using only the
generic types that already exist in gogo/port:
//gogo:reserved 42
type Host struct {
Arg int
Data bytes.Bytes
}
//gogo:reserved 43
type Post struct {
From actor.PID
Kind int
Data bytes.Bytes
}
They are what every gogo.h driver speaks (sections 22.2 to 22.8), and
an in-tree PortDriver may use them too: cfg_type = TYPE_HOST,
port.Post as its commands and events, and port.Chunk / Out / Done
/ Closed if it moves bytes. Such a driver needs no change to the
compiler, the image format or lib/, and its images run on any firmware
of the current format that has the driver. The price is that the gogo
side reads e.Kind instead of a field with a name; a small gogo package
that wraps the port can give it names again.
22.15 Checklist: the files a new driver touches
For a driver in the tree, in the order you write them:
- The driver, chip-independent C99 in
runtime/<name>/(orruntime/input/for an input device): the callbacks, a hardware-layer table if more than one board will have it, and a*_DRIVER(hal)macro. No mutable globals (make globals). - The name:
PORT_NAME_*inruntime/vm/port_names.h. - The types: generic
gogo/porttypes (nothing to do), or alib/package and the reserved-type changes of section 22.14 with a format minor. - The ESP32-S3: the hardware layer in
platform/esp32s3/main/(with its board storage), the instance inesp_ports, the sources inmain/CMakeLists.txt, and for an optional featureKconfig.projbuild,board.h(HAS_*) andfwFeaturesincmd/gogo/firmware.go. - The host VM: a hardware layer in
platform/unix/, script lines ininput_unix.c, the instance inunix_ports_allinplatform/unix/main.c, the sources in theMakefile. - Tests: C tests of the driver over a fake hardware layer (as
runtime/gpio/test/test_gpio.candruntime/input/test/do), and a golden test or example run bygogovmwith aninputscript. - Documentation: the book (a chapter or section),
docs/design.md,docs/FAQ.mdanddocs/known-issues.mdwhere they apply, and the requirement names in chapter 13.
22.16 Pitfalls
- Never block in a callback. A callback runs on the one thread that
runs every actor; while it waits, nothing else runs. Start slow work and
return: let DMA or an interrupt do it, or a task of the platform’s (the
ESP’s Wi-Fi and LCD tasks), and deliver the result later from an event
source or the event ring. If the hardware must be polled, poll from a
source with a deadline, not in a loop. A few operations still block
today (storage calls, the TLS key exchange), and
docs/known-issues.mdlists them as a cost every actor pays. - Know your thread. Driver callbacks and source callbacks run on the VM
thread. From an interrupt handler or another thread, only two of the
VM’s functions are safe:
evq_push(one writer per VM) and the host’s wake (platform_notify,vm_wake). Everything else,port_deliver_ints, the stream helpers,port_bytes_*, readingPortfields, belongs on the VM thread. State shared with an interrupt handler is filled first and published last, withvm_barrier()between, asgpio_openandgpio_closedo; the handler must not run whileclosereleases the hardware (runtime/gpio/gpio.hexplains the two-core case). - A source must make progress. The scheduler never sleeps while a
source’s
pendingis true. Apendingthat stays true whiledraindoes nothing (a stuck hardware flag, an error retried at once) spins the CPU at 100%: count those passes and back off, askbddoes. - Charge the owner, do not allocate per event. Memory the driver keeps
for a port goes in
charge_wordsor heldBytes; event messages come from the VM. Prefer delivery that drops (port_deliver_ints, the stream helpers) over the event ring when events can come faster than an actor reads them, or thin them out in aneventhook (asgpio’s debounce does): a flood of ring events ends a slow owner withmailbox_overflow. - Keep state per VM. Several VMs can run in one process (chapter 18), so
runtime/has no mutable globals;make globals(tools/globals.sh) fails on any new one. Per-port state goes inPort.stateor behind the hardware layer’sctx; state that must outlive a port is board storage, declared by the platform and passed in through the hardware layer, likegpio’sGpioPin pins[]. Do not size a table by port index for 16 ports: the cap is per VM, 1024 by default ongogovmand in embedded VMs, up to 2048 (section 22.9). Index such state by the device (a pin, a channel), asgpiodoes, or keep it in thePort. - Validate everything. A command can come from any actor and any module, with any type and any values. Check the type, the field count and the ranges, and ignore what you do not understand.
22.17 What is still missing
The driver API of sections 22.2 to 22.8 closes most of what used to
stand between a third party and a firmware driver: there is a stable
header, a registration that needs no fork, gogo firmware builds the
component in, and a refusal names its error. What remains, plainly:
- Additions wait for later minors. A context per port, a flags word
in
gogo_port_driver(a port that does not keep the VM alive), an interrupt-safe post and a way for a board driver to read a config key are all additive (appended fields, new functions), so they can come without breaking a 0.3 driver. - No byte streams. A
gogo.hdriver hasport.Postevents and commands of up to 262,080 bytes each, but not the stream protocol of the runtime’s byte ports (port.Chunk,Out,Donewith flow control, section 22.11); a helper for it can follow. - No interrupt-safe post. An interrupt handler hands its data to a task, which posts (section 22.7). The event ring, which an ISR can push to, is the runtime’s own and holds two-int events only.
- A few ports per board. A board registers at most 8 board ports; a
VM has
GOGO_MAX_SOURCESevent sources, one more of them taken by the post inbox in a firmware with board ports. - No hardware access through gogo. A component’s driver talks to its hardware through ESP-IDF directly (its own I2C device, GPIO, task); the runtime’s shared I2C bus and pin reservations are internal. Pick pins and buses the board’s own drivers do not use.
- C only, compiled in. No driver is loaded at run time (no FFI and no native modules, by design), and there is no package manager for components.
23. Bluetooth LE
Both boards have a Bluetooth Low Energy radio. The "ble" port makes the
board a peripheral: a small GATT server that a phone, a tablet or a
computer connects to. The program declares what the server offers when it
opens the port (services, each a set of characteristics), and from then
on a phone can read values the program has set, write values the program
receives as messages, and subscribe to notifications the program pushes.
That is enough for the usual reason to put Bluetooth on a device: a phone app that talks to it, to read its status, list what it recorded, or tell it to upload something. Setting up the board’s Wi-Fi from a phone is a separate thing, done by the firmware itself, not by a program; while it runs, the port cannot open.
The port lives in package gogo/ble, a small library over gogo/port.
Its messages are the generic host-port ones (port.Post for events and
commands, chapter 22), so it needs no new image format: a program that
imports gogo/ble runs on every firmware of its format that has the
ble driver, which is both boards’ default firmware.
23.1 Declaring a server
p, err := ble.Open(ble.Config{
Name: "gogo-demo",
Services: []ble.Service{
{UUID: ble.UUID16(0x180F), Chars: []ble.Characteristic{
{UUID: ble.UUID16(0x2A19), Flags: ble.Read | ble.Notify},
}},
{UUID: ble.UUID("6e400001-b5a3-f393-e0a9-e50e24dcca9e"), Chars: []ble.Characteristic{
{UUID: ble.UUID("6e400002-b5a3-f393-e0a9-e50e24dcca9e"), Flags: ble.Write | ble.WriteNoResp},
{UUID: ble.UUID("6e400003-b5a3-f393-e0a9-e50e24dcca9e"), Flags: ble.Notify},
}},
},
})
Nameis what a phone’s scan shows, 1 to 26 bytes (it travels in the 31-byte advertisement).- A service is a UUID and 1 to 8 characteristics. A characteristic
is a UUID and flags saying what a phone may do with it:
ble.Read,ble.Write(with a response),ble.WriteNoResp(without one, faster) andble.Notify(the phone may subscribe; the program pushes). At most 4 services and 16 characteristics in all; more iserrors.TooMany. - A UUID is
ble.UUID16(n)for the 16-bit ones the Bluetooth SIG assigns (0x180F is the Battery Service, 0x2A19 its Battery Level, which phone apps recognise; annoutside 0 to 0xFFFF gives an empty UUID, whichOpenrefuses witherrors.BadArg), or the 36-character form for your own, written as a conversion:ble.UUID("6e40..."). Make up a 128-bit UUID for an app of your own (any UUID generator); the ones above are the “Nordic UART” service that many generic phone apps know. - Characteristics are numbered in declaration order, across all services, from 0: in the example the battery level is 0, the command characteristic 1 and the reply characteristic 2. Every event and command names a characteristic by that number.
Open starts advertising at once and makes the caller the port’s owner.
It fails with errors.BadArg for a Config it cannot use (an empty or long
name, a malformed UUID, a characteristic without flags, a service without
characteristics), errors.NoMemory on a board with too little internal
RAM to start Bluetooth (23.7), errors.Busy if the radio is taken (one ble port per
board; or the firmware’s Wi-Fi setup from a phone, section 2.1, holds the
radio: it runs only at boot, before any program, so a program does not
meet it in practice), and
errors.NotFound on a firmware built without ble. On a board the open
waits while the Bluetooth controller and stack start: no actor runs
meanwhile.
One phone is connected at a time. While it is, the board does not advertise, so no other central can connect; when it leaves, advertising starts again by itself. Closing the port, or the owner’s exit, ends the connection and the advertising.
23.2 Events
The port’s events arrive as port.Post messages from the port, and
ble.Event decodes one into a typed value:
type Connected struct {
Peer string
MTU int
}
type Disconnected struct{ Reason int }
type Written struct {
Char int
Data bytes.Bytes
}
type Subscribed struct {
Char int
On bool
}
type MTUChanged struct{ MTU int }
type NotifyFailed struct {
Char int
Reason errors.Code
}
Connected: a phone connected.Peeris its address as the board sees it (phones show a random one that changes),MTUthe ATT MTU so far: on a board always the default 23, since the phone’s MTU request comes after the connection (MTUChanged);gogovm’s test phone may say another number.Disconnected: the phone went away.Reasonis the Bluetooth reason code: 0x13 (19) the phone ended the connection, 0x08 the link timed out (the phone walked out of range), 0x16 the board ended it.Written: the phone wroteDatato characteristicChar, up to 512 bytes (after an MTU exchange, which phones and computers make: at the 23-byte default a long write takes about 30 prepared pieces, more than the board’s Bluetooth buffers hold). A write with a response is acknowledged to the phone when the driver has queued it, before the program reads it.Subscribed: the phone turned notifications ofCharon or off. Every connection starts with all of them off.NotifyFailed: aSendNotifyofCharwas not delivered, andReasonsays why; itsDone{Seq: -1}comes right after (23.3).MTUChanged: the phone negotiated a larger ATT MTU; a notification may now carryMTU - 3bytes (ble.MaxNotify(mtu)). Phones usually ask right after connecting (iPhones and Macs for 185 or more, Android for up to 517); the board answers with at most 256, so a notification carries at most 253 bytes.
A phone’s read never reaches the program. The driver answers it with
the value the program last set with ble.SetValue (empty until then), so
reading a status costs no message and works while the program is busy.
Set the value whenever it changes, and the first time right after Open
(a phone that connects in between reads an empty value):
func SetValue(p actor.PID, char int, data bytes.Bytes)
SetValue sends no reply: a bad Char, more than 512 bytes, or a board
out of memory for the copy leaves the old value, silently.
Events the owner has no room for are held in the driver, not dropped, and delivered when the mailbox has room again; meanwhile a phone’s writes are answered with an error, so the phone retries. A write without a response that arrives while the driver’s queue is full is lost (as it would be over the air).
23.3 Notifications
func SendNotify(p actor.PID, char int, data bytes.Bytes)
SendNotify pushes data to the phone, which must have subscribed to
char. Like a stream’s port.Out (chapter 15), every one is answered
with a port.Done from the port:
Done{Seq: n}once the Bluetooth stack has taken it (counting from 1);Done{Seq: -1}if it could not be delivered: refused (a characteristic withoutNotify, nobody subscribed, empty data, more thanMaxNotify(mtu)bytes, two already in flight), or the phone left before it went out.
Every Done{Seq: -1} is announced by a NotifyFailed event just
before it, whose Reason says why:
Reason | why |
|---|---|
errors.BadArg | no such characteristic, one without Notify, empty data, more than MaxNotify(mtu) bytes |
errors.Closed | no phone connected, or it went away while the notification waited |
errors.Refused | the phone has not subscribed to that characteristic |
errors.TooMany | two already in flight |
errors.IO | the Bluetooth stack refused it |
NotifyFailed is a hint: it is dropped when the owner’s mailbox is full,
while the Done never is. A refusal’s Done{-1} comes at once, so it
may arrive before the Done of an earlier notification still in flight.
Two notifications may be in flight. When the stack has no buffer for one,
the driver waits and tries again, for as long as the connection lasts,
and the Done comes later: a sender that waits for each Done (or keeps
at most two in flight) never runs ahead of the radio. A notification is
never failed for being slow: a slow phone (a long connection interval,
an app in the background) only makes the Done late, and a link that
dies ends in a Disconnected, which fails every notification still
waiting with errors.Closed. Keep to two in flight: beyond that, a
refusal’s Done can be lost when the mailbox is full. There is no hidden fragmentation: data longer than one notification
is the program’s to split, as in this example
(examples/23-ble-chunks):
// sendChunked pushes data to characteristic char in pieces of
// MaxNotify(mtu) bytes, one at a time; ok is false if one was not
// delivered (the phone unsubscribed or went away). The port.Posts that
// arrive meanwhile (a phone's write, a new MTU) come back in held, in
// order, for the caller to handle.
func sendChunked(p actor.PID, char int, data bytes.Bytes, mtu int) (pieces int, ok bool, held []port.Post) {
size := ble.MaxNotify(mtu)
for at := 0; at < data.Len(); at += size {
end := at + size
if end > data.Len() {
end = data.Len()
}
ble.SendNotify(p, char, data.Slice(at, end))
pieces++
var seq int
seq, held = waitDone(p, held)
if seq < 0 {
return pieces, false, held
}
}
return pieces, true, held
}
// waitDone returns the Seq of the next port.Done from p. A port.Post that
// arrives first is appended to held, not dropped: it may be the phone's
// next write.
func waitDone(p actor.PID, held []port.Post) (int, []port.Post) {
for {
switch m := actor.Receive().(type) {
case port.Done:
if m.From == p {
return m.Seq, held
}
case port.Post:
held = append(held, m)
}
}
}
A port.Post that arrives while waitDone waits (the phone’s next
write, a new MTU, a Disconnected) is kept in held, not dropped: the
main loop handles those before it receives again. Dropping them is an
easy mistake, and it loses a phone’s write without a trace.
The program keeps the MTU from Connected and MTUChanged; with a
phone at the default MTU of 23 the 100-byte text goes in 5 pieces, at 50
in 3:
advertising as gogo-log
mtu 23 -> 5 pieces of up to 20 bytes, ok: true
mtu 50 -> 3 pieces of up to 47 bytes, ok: true
phone gone
One notification at a time is the simplest; for throughput keep two in
flight (send the next on each Done, as examples/ble-echo does), and
use the largest MTU the phone offers. tools/ble_central.py (23.6)
measures what a board reaches with a computer as the central.
How fast notifications go depends mostly on the phone (the central): it picks the connection interval, and how many packets it takes in each connection event. The board asks for 251-byte link-layer packets and a 15 ms interval when a central connects (the interval also from a central without the longer packets); a central may refuse. Measured on a StickS3, 200 notifications each:
| Central | 20 bytes each | 253 bytes each |
|---|---|---|
| Raspberry Pi 5 (Linux, BlueZ): took 15 ms | 5 KB/s | 32 KB/s |
| macOS: kept 30 ms, skips most connection events | 0.4 KB/s | 1.2 KB/s |
So send few large notifications rather than many small ones, and do not judge a phone app by a Mac: iOS and Android phones usually take the shorter interval (iOS may keep its own when asked for a fixed 15 ms).
23.4 A complete peripheral
examples/23-ble-status serves the
battery level (a value a phone reads and subscribes to) and a command
characteristic, answered on a third:
pct := 87
ble.SetValue(p, level, bytes.FromSlice([]byte{byte(pct)}))
println("advertising as gogo-demo")
for {
post, ok := actor.Receive().(port.Post)
if !ok {
continue // the port.Done of a SendNotify
}
ev, _ := ble.Event(post)
switch e := ev.(type) {
case ble.Connected:
println("connected:", e.Peer, "mtu", e.MTU)
case ble.MTUChanged:
println("mtu", e.MTU)
case ble.Subscribed:
println("subscribed", e.Char, e.On)
case ble.Disconnected:
println("disconnected, reason", e.Reason)
case ble.Written:
cmd := e.Data.String()
println("command:", cmd)
switch cmd {
case "ping":
ble.SendNotify(p, reply, bytes.FromString("pong"))
case "drain":
pct -= 10
v := bytes.FromSlice([]byte{byte(pct)})
ble.SetValue(p, level, v) // what a read returns from now on
ble.SendNotify(p, level, v) // and a push to a subscribed phone
case "bye":
return // the port closes with its owner: the phone is disconnected
}
}
}
With a phone that connects, reads the level, subscribes to both
notifying characteristics and writes ping, drain and bye, it prints:
advertising as gogo-demo
connected: 4c:2a:91:07:5e:d3 mtu 23
mtu 185
subscribed 0 true
subscribed 2 true
command: ping
command: drain
command: bye
The two reads of the level (87, then 77 after drain) do not appear: the
driver answered them.
23.5 With a phone: nRF Connect
Any generic BLE app works; Nordic’s free nRF Connect for Mobile (Android and iOS) shows everything the port does. Flash the example and open the app:
$ gogo build docs/book/examples/23-ble-status -o status.ggb
$ gogo flash status.ggb
$ gogo monitor
advertising as gogo-demo
- Scan. On the Scanner tab,
gogo-demoappears (filter by name if the room is busy). The board’s address is the radio’s own and stays the same. - Connect. Tap Connect. The monitor prints
connected: ...and, a moment later,mtu ...(the app asks for a larger MTU). - Read. Under Battery Service, the Battery Level characteristic
has a read arrow (the down arrow): tap it, and the value shows as
87%. The program printed nothing: reads never reach it. - Subscribe. Tap the triple-arrow icon of Battery Level and of the
third characteristic (
6E400003-..., under the Nordic UART Service if the app names it). The monitor printssubscribed 0 trueandsubscribed 2 true. - Write. On the write characteristic (
6E400002-...) tap the up arrow, choose UTF-8, typepingand send. The monitor printscommand: pingand the app showspongas the third characteristic’s value. Senddrain: the battery level drops to77%by itself (a notification). - Disconnect. Tap Disconnect: the monitor prints
disconnected, reason 19, andgogo-demoshows up in the scanner again. Sendbyeinstead and the program ends: the app sees the connection close.
On iOS, the system caches what a device offers by its address: after you change a program’s services, turn Bluetooth off and on (or forget the device) before connecting again, or the app may show the old ones.
23.6 On the host
gogovm has the ble port too, so programs that use it run and are
tested without a radio. The radio is a Unix-domain socket that exists
while the port is open, at $GOGO_BLE, or by default
$TMPDIR/gogo-ble-<pid>.sock, one per gogovm, whose path gogovm prints
on stderr when the port opens. A client that connects to it plays the
phone with a small line protocol, documented at the top of
platform/unix/ble_unix.c:
$ GOGO_BLE=/tmp/demo.sock gogo run docs/book/examples/23-ble-status &
advertising as gogo-demo
$ nc -U /tmp/demo.sock
adv gogo-demo
svc 180f
chr 0 2a19 9
...
end
connect 11:22:33:44:55:66 23
connected: 11:22:33:44:55:66 mtu 23
read 0
value 0 57
ble.Open on gogovm fails with errors.BadPath if the path is longer
than a socket’s path may be (103 bytes; a long $TMPDIR can do it: set
$GOGO_BLE) or $GOGO_BLE names a file that is not a socket (the file
is left alone), errors.Busy if another gogovm listens there, and
errors.IO if the directory does not exist. A socket left behind by a
gogovm that was killed is replaced.
Each example in this chapter has a phone script next to it, which
tests/ble plays over the socket (it runs in make test); the tests there
are the place to copy from for a program of your own. On a board, the
same checks with a computer as the phone are tools/ble_central.py
(Python and bleak), which drives examples/ble-echo through scan,
connect, read, write, subscribe, notifications, a throughput figure and
disconnect.
23.7 Memory, Wi-Fi and the radio
- Memory. BLE is in the default firmware of both boards. The firmware
is about 136 KB larger with it (170 KB with the Wi-Fi setup from a
phone, section 2.1), and the Bluetooth controller keeps
about 22 KB of internal RAM even while no port is open. An open port
costs about 65 KB more of internal RAM (the NimBLE
host and the controller’s connection state, freed when the port closes).
ble.Openchecks first: with less than 80 KB of internal RAM free (or no free block of 16 KB) it fails witherrors.NoMemoryand starts nothing, rather than letting the Bluetooth stack run out halfway (which would crash the board). On the Cardputer (no PSRAM) open the port before a TLS connection, or close the connection first. The driver’s own state is fixed (about 3 KB). A firmware for a program that never uses Bluetooth can leave it out:gogo firmware -without ble(chapter 12). - Wi-Fi. Bluetooth and Wi-Fi share one 2.4 GHz radio and antenna; the ESP32-S3 switches between them in time slices (coexistence). Both work at once, Wi-Fi and TLS included, but each is slower while the other is busy, and a phone may see the first connection attempt fail while Wi-Fi is joining a network.
- Range. About 10 m indoors, through a wall or two, with the boards’ small antennas; a body between the board and the phone halves it.
- Security. The port does no pairing or encryption: anyone nearby can connect, read what the program has set, and write. Keep secrets out of readable values, and check what a write asks for as you would check a network request. (The firmware’s own Wi-Fi setup from a phone, section 2.1, is a different service, entered only with a key held at boot, and encrypted.)
23.8 What is not there
- The central role: scanning for other devices and connecting to them (a heart-rate strap, another board). The port is a peripheral only; a central can come later if programs need it.
- More than one connection, indications (notifications the phone acknowledges), descriptors of your own (a characteristic’s user description), pairing and bonding.
- Long values in one notification: split them (23.3).