Skip to content

Networking

import net; gives a Goose program WiFi, HTTP, MQTT and sockets on the ESP32-S3 and the classic ESP32. It works the same way as import mcu;: lib/net.goose is a list of extern fns, and components/microgoose/mg_net.c and mg_mqtt.c implement them on ESP-IDF's WiFi driver, lwIP, HTTP and MQTT clients. The STM32H743 has no radio, so building a networked program for h7 is an error.

Saving your network

The board joins the network you save once on your PC:

microgoose wifi MyNetwork

It asks for the password and saves it in ~/.microgoose/wifi.json (readable only by you). --name kitchen names the boards on the network (kitchen.local); the default name is microgoose. microgoose wifi alone shows what is saved, --forget deletes it, and --open saves a network with no password.

MG_WIFI_SSID and MG_WIFI_PASSWORD take the place of the saved file, for CI and scripts. The password is built into the firmware only when the program uses the network and is flashed over USB; other programs carry empty settings.

The same file holds the key that signs updates sent over WiFi (see Updates over WiFi). It is made the first time you save a network and kept when you save another one.

A first networked program

examples/web.goose joins the network, sets the clock, fetches a page over HTTPS, and then serves its own page:

microgoose new web --example web
microgoose run web/main.goose --target s3 --seconds 120
I (1234) microgoose: wifi: joined MyNetwork as 192.168.1.23 (microgoose.local)
joined as 192.168.1.23, signal -48 dBm
clock set: 1795900000 seconds since 1970
GET https://example.com/ -> 200, 577 bytes
serving http://192.168.1.23/
GET /

Open http://microgoose.local/ in a browser. Name resolution with .local needs mDNS on the PC: it is built into macOS, Linux and current Windows.

The API

Waits take a timeout in milliseconds, and -1 waits forever. Strings go in as any u8 array or slice; text comes back appended to a builder (u8[>..]), as in the rest of Goose's standard library.

WiFi and time

Function Returns Notes
wifi_connect() bool joins the saved network; true once the board has an address
wifi_join(ssid, password) bool joins this network instead
wifi_connected() bool
wifi_wait(timeout_ms) bool waits for a link that dropped; the board reconnects by itself
wifi_ip(out) — appends the address, 192.168.1.23
wifi_rssi() i32 signal strength, dBm
ntp_sync(timeout_ms) bool sets the clock from pool.ntp.org; then time() is the date

HTTP client

Function Returns
http_get(url, response) the status code, or -1 when nothing answered
http_post(url, content_type, body, response) the same
http_request(method, url, content_type, body, response) the same; any method

https:// URLs are checked against ESP-IDF's bundle of common root certificates. The response body is appended to response.

HTTP server

The program answers the requests itself, one at a time:

http_serve(80);
loop {
    method.clear(); path.clear(); body.clear();
    let id = http_next(method, path, body, -1);
    if id == 0 { continue; }
    http_reply(id, 200, "text/plain", "hello\n");
}
Function Returns Notes
http_serve(port) bool starts listening
http_next(method, path, body, timeout_ms) i32 the next request's id, or 0 when none came in time; the path keeps its query string
http_reply(id, status, content_type, body) bool answers request id

A request the program leaves unanswered for 30 seconds gets a 503 Service Unavailable. Request bodies are cut at 64 KB.

Sockets

Function Returns
tcp_connect(host, port, timeout_ms) a socket, or -1
tcp_listen(port) a listening socket, or -1
tcp_accept(listener, timeout_ms) a connected socket, or -1 (also on a timeout)
udp_open(port) a socket bound to port (0: any), or -1
net_send(sock, data) bytes sent, or -1
udp_send(sock, host, port, data) bytes sent, or -1
net_recv(sock, out, max, timeout_ms) bytes appended to out; 0 when a TCP peer closed, -1 on an error, -2 on a timeout
net_close(sock) —

MQTT

A program talks to one MQTT broker at a time, on ESP-IDF's MQTT client (MQTT 3.1.1). It receives messages as it receives HTTP requests, by asking for the next one:

mqtt_will("kitchen/status", "offline", 1, true);
mqtt_connect("mqtt://192.168.1.10", "", "", "", 10000);
mqtt_publish("kitchen/status", "online", 1, true);
mqtt_subscribe("kitchen/cmd/#", 1);
loop {
    topic.clear(); payload.clear();
    if !mqtt_next(topic, payload, 1000) { continue; }
    print(topic, ": ", payload);
}
Function Returns Notes
mqtt_connect(url, client_id, user, password, timeout_ms) bool true once connected; see below
mqtt_will(topic, payload, qos, retain) — before mqtt_connect: what the broker publishes if the board drops off; topic "" clears it
mqtt_connected() bool
mqtt_publish(topic, payload, qos, retain) bool qos 0, 1 or 2
mqtt_subscribe(topic, qos) bool + and # wildcards; 16 subscriptions at most
mqtt_unsubscribe(topic) bool
mqtt_next(topic, payload, timeout_ms) bool the next message, appended to topic and payload; false when none came in time
mqtt_disconnect() — also forgets the subscriptions
  • URLs. mqtt://host, mqtt://host:1884, mqtts://host (TLS, checked against the same root certificates as https://), ws:// and wss://.
  • Client id. "" makes one from the board's name and the end of its MAC, microgoose-51a9b4.
  • Login. user and password are "" for a broker without one. A broker that refuses the login makes mqtt_connect return false at once, and the log says why.
  • Reconnecting. After the broker or WiFi drops, the board reconnects by itself every 10 seconds and subscribes again, so a program that subscribed once keeps getting its messages. mqtt_connected() says whether it is connected right now. A QoS 0 publish made while it is disconnected is lost, and mqtt_publish returns false.
  • Messages waiting. Up to 16 messages wait for mqtt_next. If the program falls further behind, newer ones are dropped, with a warning in the log. Messages over 64 KB are dropped too.
  • Message size and --reserve. A payload is appended to a Goose builder, which lives on the program's data stack, so a message bigger than the data stack stops the program with a data stack overflow. Raise --reserve to fit the largest message the program subscribes to; the same goes for HTTP response bodies.
  • Ending. mqtt_disconnect tells the broker, which then does not publish the last will. A board that resets or loses power gets its will published.

What a networked board runs

A networked program is one that imports net, or is built with --net. Before its main() starts, the board:

  1. joins the saved network, as NAME.local (the default is microgoose);
  2. starts the network console on TCP port 3233;
  3. starts SSH and SFTP on port 22;
  4. starts the update listener on port 3232.

They keep running beside the program, and after it ends. wifi_connect() in such a program returns at once, because the board is already on the network.

--net makes any program networked, even one that never touches the network, so you can update it over WiFi:

microgoose run blink.goose --net --name lab-bench

Updates over WiFi

Flash a networked program over USB once. From then on, --ota sends programs over WiFi instead:

microgoose run main.goose --target s3            # once, over USB
microgoose run main.goose --target s3 --ota      # from now on, no cable
[mg] sending main.goose (856 KB) to 192.168.1.23, which runs web.goose from ota_0
[mg] sent in 6.0 s; the board restarts into it
[mg] console of 192.168.1.23 over WiFi for up to 30s
hello from Goose on a microcontroller
[microgoose] program exited with code 0 (free heap 8573155)

run --ota builds the program and sends it to the board. The board restarts into it, and you see its output over the network console from its first line. build --ota then flash --ota splits the same steps, and monitor --ota restarts the board and shows its console. The board is found by its .local name; --host takes a name or an address instead.

How it works:

  • Two app slots. The flash holds two app slots (1.9 MB each on the S3, 1.75 MB on the WROOM-32, beside the storage for flash/). An update is written to the slot the board is not running, checked, and only then made the one it boots.
  • Signed. Each update carries an HMAC-SHA256 signature made with the key in ~/.microgoose/wifi.json, over a one-time challenge from the board and the image's SHA-256. The board checks the signature before it writes anything, and the SHA-256 once the image is in. A board flashed with a different key refuses the update with a 403.
  • No secrets on the network. An image sent over WiFi does not hold the WiFi password or the key. A USB flash stores them in the board's NVS, and the board keeps using them.
  • Rollback. A new app that fails before it gets onto the network is replaced by the previous one at the next boot.
  • Crash loops. A program that crashes straight after starting could leave no time to replace it. After a crash, the board waits 15 seconds before it starts the program again, and the host keeps trying for a minute, so run --ota with a fix gets in.
  • USB still works. A USB flash always boots what it wrote, even after updates over WiFi.

A build is for one way of flashing. flash --ota refuses an image built for USB, because that image holds the password. flash refuses one built for WiFi, because that image holds no settings.

The update listener answers anyone on your network who has the key. Keep wifi.json private, and use microgoose wifi --forget then a new microgoose wifi (and a USB flash) if it leaks.

The network console

Everything the board prints goes to the USB console as before, and also to the network console: stdout, stderr in red, and ESP-IDF's log. The board keeps the last 8 KB, so a client that connects late still sees the run from its start. Any TCP client can read it, such as nc on macOS and Linux:

nc microgoose.local 3233

Windows has no nc. There, microgoose ssh log shows the same history and then follows it (see SSH and SFTP).

After a crash, the board keeps that history and adds a note of how the run ended:

goose runtime error: data stack overflow (raise --reserve)
[microgoose] the board crashed: Unhandled debug exception (core 1). Rebooting...
[microgoose] the board restarted after the crash

The full panic dump, with registers and a backtrace, still goes only to USB.

SSH and SFTP

A networked board takes SSH logins on port 22, for the PC's own key only:

microgoose ssh                 # a shell on the board
microgoose ssh log             # what it has printed since boot, then as it comes
microgoose sftp                # its files
microgoose sftp -b cmds.txt    # run the sftp commands in a file

The first microgoose ssh, sftp or networked build makes a key for the PC with ssh-keygen, in ~/.microgoose/ssh/id_ed25519. Every networked image carries its public half, so the board knows it after the next flash, over USB or --ota. Other people's keys go in ~/.microgoose/authorized_keys, one OpenSSH public key per line, as ssh-ed25519 AAAA... name; the board takes eight. There are no passwords.

The board makes its own host key the first time and keeps it in NVS, so it stays the same across updates. It prints the fingerprint at boot:

I (6555) microgoose: ssh: port 22, host key SHA256:arnVpGWa..., 1 key may log in

microgoose ssh remembers that key under the board's name, in ~/.microgoose/known_hosts, and refuses to log in if it ever changes.

A board makes a new key when its flash is erased, and two boards with the same name have different keys. OpenSSH then stops with REMOTE HOST IDENTIFICATION HAS CHANGED. Compare the fingerprint it shows with the one the board prints at boot over USB. If they match, forget the old key and log in again:

ssh-keygen -R microgoose.local -f ~/.microgoose/known_hosts

microgoose ssh prints that line, with the board's name and the file's path filled in, when this is what stopped it. Boards that share a network are better told apart by name: see --name under Saving your network.

The wrappers only add options to OpenSSH's own ssh and sftp, so any SSH client works too:

ssh -i ~/.microgoose/ssh/id_ed25519 goose@microgoose.local info

The user name is ignored; the key is what counts.

The shell

Command What it does
ls [DIR], cat FILE list a folder, print a file
rm, mkdir, rmdir, mv change the file tree
info the program, chip, app slot, uptime, free memory and address
log the network console's history, then the rest as it comes (Ctrl-C stops)
restart restart the board
help, exit

microgoose ssh info runs one command and returns its exit status, so the shell works from scripts too.

SFTP

SFTP sees the same file tree as the program: / is the folder the program runs in, so a file put at /data/x.txt is read_file("data/x.txt") to the program. put, get, ls, rm, mkdir, rmdir and rename work. OpenSSH's scp goes over SFTP too, with the same options as ssh.

Put files in /flash to keep them: that folder is on the board's flash chip and survives restarts and updates (see Files that survive a reset). Everywhere else the tree lives in RAM, so files sent there last until the board restarts, and they take heap, which a board without PSRAM has little of while the program runs (see Memory). Files in /flash take no heap. mv and rename between /flash and the rest copy the file across.

Security

The server is MicroGoose's own, small enough to read: mg_ssh.c for the protocol and mg_sftp.c for files, on Monocypher for the cryptography. It speaks one set of algorithms, the ones OpenSSH prefers short of post-quantum ones: curve25519-sha256 key exchange (with OpenSSH's strict key exchange, which closes the Terrapin attack), Ed25519 keys and chacha20-poly1305. It takes no passwords, opens no port forwards and runs no agent.

OpenSSH 10.1 and later warn that curve25519 is not post-quantum. microgoose ssh turns that warning off; a plain ssh shows it, and -o WarnWeakCrypto=no quiets it.

A board with PSRAM serves two connections at once; a WROOM-32 serves one, with smaller buffers, and turns a login away when memory is short.

Memory

WiFi, lwIP, the HTTP server, the update listener and the network console take their memory from the chip's internal RAM, plus buffers for TLS while an https:// request runs. An SSH session takes about 20 KB on the WROOM-32 (its buffers and a 6 KB stack) while it lasts; on the ESP32-S3 its buffers go to PSRAM, and it takes 6 KB of internal RAM. A networked board reserves the program's data stacks before it joins the network, because WiFi leaves the WROOM-32's RAM in pieces too small for them. On the WROOM-32, which has no PSRAM, examples/web.goose still has 39 KB of heap free while it serves pages after an HTTPS fetch, with the default 16 KB data stacks. Raise --reserve with that budget in mind.

Tested on the ESP32-S3 and the WROOM-32: joining, .local names, NTP, an HTTPS GET, the server answering 30 requests sent at once (they queue and are answered in turn), updates over WiFi (an 856 KB image in 5 to 7 seconds), a wrong key refused, and recovering a board stuck in a crash loop. MQTT: QoS 0, 1 and 2, retained messages, the last will, wildcards, unsubscribing, a refused login, a 20 KB message put back together, a broker restart (reconnected and subscribed again), and six connect and disconnect rounds on the WROOM-32 that end with the heap where it started. SSH and SFTP: OpenSSH 10.2's ssh and sftp against both boards, the shell with and without a terminal, a 300 KB file up and back (2.7 s on the S3, beside a second session following the log), the host key kept across an update over WiFi, and a login on the WROOM-32 while examples/web.goose serves pages. On the WROOM-32 that program leaves about 34 KB free, and a download over SFTP takes nearly all of it while WiFi sends; the board waits for memory to come back rather than drop the connection, and the program goes on serving.

chip_temp_c() reads −273 on the classic ESP32, which has no temperature sensor (see Hardware API).