From 784f36d08bf250924f22919fdbd57b742d836f54 Mon Sep 17 00:00:00 2001 From: Frelsaren Date: Fri, 30 Oct 2026 21:31:14 +0100 Subject: [PATCH 1/5] unor4wifi: add WiFi driver for the Arduino UNO R4 WiFi Talks AT commands over UART to the ESP32-S3 bridge firmware and implements netlink and netdev. Supports STA and AP mode, TCP client and server, UDP and DNS. Adds a netlink probe and enables the small net examples for the arduino_uno_r4_wifi build tag. --- examples/net/ntpclient/main.go | 2 +- examples/net/socket/main.go | 2 +- examples/net/tcpclient/main.go | 2 +- examples/net/tcpecho/main.go | 2 +- examples/net/tlsclient/main.go | 2 +- examples/net/webclient/main.go | 2 +- netlink/probe/unor4wifi.go | 27 ++ smoketest.sh | 4 +- unor4wifi/README.md | 75 ++++ unor4wifi/debug.go | 16 + unor4wifi/modem.go | 225 ++++++++++ unor4wifi/unor4wifi.go | 732 +++++++++++++++++++++++++++++++++ 12 files changed, 1084 insertions(+), 7 deletions(-) create mode 100644 netlink/probe/unor4wifi.go create mode 100644 unor4wifi/README.md create mode 100644 unor4wifi/debug.go create mode 100644 unor4wifi/modem.go create mode 100644 unor4wifi/unor4wifi.go diff --git a/examples/net/ntpclient/main.go b/examples/net/ntpclient/main.go index 9ea079ddb..d37026b1b 100644 --- a/examples/net/ntpclient/main.go +++ b/examples/net/ntpclient/main.go @@ -3,7 +3,7 @@ // It creates a UDP connection to request the current time and parse the // response from a NTP server. The system time is set to NTP time. -//go:build ninafw || wioterminal || challenger_rp2040 || comboat_fw +//go:build ninafw || wioterminal || challenger_rp2040 || comboat_fw || arduino_uno_r4_wifi package main diff --git a/examples/net/socket/main.go b/examples/net/socket/main.go index 2e867fd53..b8af9d9d8 100644 --- a/examples/net/socket/main.go +++ b/examples/net/socket/main.go @@ -4,7 +4,7 @@ // // nc -lk 8080 -//go:build ninafw || wioterminal || challenger_rp2040 || comboat_fw +//go:build ninafw || wioterminal || challenger_rp2040 || comboat_fw || arduino_uno_r4_wifi package main diff --git a/examples/net/tcpclient/main.go b/examples/net/tcpclient/main.go index 24f07750c..ddff73c05 100644 --- a/examples/net/tcpclient/main.go +++ b/examples/net/tcpclient/main.go @@ -5,7 +5,7 @@ // // nc -lk 8080 -//go:build ninafw || wioterminal || challenger_rp2040 || comboat_fw +//go:build ninafw || wioterminal || challenger_rp2040 || comboat_fw || arduino_uno_r4_wifi package main diff --git a/examples/net/tcpecho/main.go b/examples/net/tcpecho/main.go index 274dc04d2..ca58c8d17 100644 --- a/examples/net/tcpecho/main.go +++ b/examples/net/tcpecho/main.go @@ -7,7 +7,7 @@ // // $ nc 10.0.0.2 8080 copy ; cmp file copy -//go:build ninafw || wioterminal +//go:build ninafw || wioterminal || arduino_uno_r4_wifi package main diff --git a/examples/net/tlsclient/main.go b/examples/net/tlsclient/main.go index adef22005..4db4478dc 100644 --- a/examples/net/tlsclient/main.go +++ b/examples/net/tlsclient/main.go @@ -5,7 +5,7 @@ // // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security -//go:build ninafw || wioterminal || comboat_fw +//go:build ninafw || wioterminal || comboat_fw || arduino_uno_r4_wifi package main diff --git a/examples/net/webclient/main.go b/examples/net/webclient/main.go index 6b287839d..8a8fc5d09 100644 --- a/examples/net/webclient/main.go +++ b/examples/net/webclient/main.go @@ -17,7 +17,7 @@ // } // --------------------------------------------------------------------------- -//go:build ninafw || wioterminal || comboat_fw +//go:build ninafw || wioterminal || comboat_fw || arduino_uno_r4_wifi package main diff --git a/netlink/probe/unor4wifi.go b/netlink/probe/unor4wifi.go new file mode 100644 index 000000000..0f87846be --- /dev/null +++ b/netlink/probe/unor4wifi.go @@ -0,0 +1,27 @@ +//go:build arduino_uno_r4_wifi + +package probe + +import ( + "machine" + + "tinygo.org/x/drivers/netdev" + "tinygo.org/x/drivers/netlink" + "tinygo.org/x/drivers/unor4wifi" +) + +func Probe() (netlink.Netlinker, netdev.Netdever) { + + cfg := unor4wifi.Config{ + // UART3 is the SCI1 link to the ESP32-S3 AT interface. + Uart: machine.UART3, + Tx: machine.UART3_TX_PIN, + Rx: machine.UART3_RX_PIN, + BaudRate: 115200, + } + + dev := unor4wifi.New(&cfg) + netdev.UseNetdev(dev) + + return dev, dev +} diff --git a/smoketest.sh b/smoketest.sh index 17034d8d0..bda7e35d9 100755 --- a/smoketest.sh +++ b/smoketest.sh @@ -196,7 +196,9 @@ tinygo build -size short -o ./build/test.hex -target=wioterminal -stack-size 8kb # network examples (comboat) tinygo build -size short -o ./build/test.hex -target=elecrow-rp2040 -stack-size 8kb ./examples/net/tlsclient/ tinygo build -size short -o ./build/test.hex -target=elecrow-rp2350 -stack-size 8kb ./examples/net/ntpclient/ - # Arduino UNO R4 WiFi LED matrix tinygo build -size short -o ./build/test.hex -target=arduino-uno-r4-wifi ./examples/unor4matrix/checkerboard/ tinygo build -size short -o ./build/test.hex -target=arduino-uno-r4-wifi ./examples/unor4matrix/life/ +# network examples (unor4wifi) +tinygo build -size short -o ./build/test.hex -target=arduino-uno-r4-wifi -stack-size 4kb ./examples/net/tcpclient/ +tinygo build -size short -o ./build/test.hex -target=arduino-uno-r4-wifi -stack-size 4kb ./examples/net/ntpclient/ diff --git a/unor4wifi/README.md b/unor4wifi/README.md new file mode 100644 index 000000000..d14aa21b4 --- /dev/null +++ b/unor4wifi/README.md @@ -0,0 +1,75 @@ +# unor4wifi + +WiFi network driver for the Arduino UNO R4 WiFi. + +The board has a Renesas RA4M1 main MCU and an ESP32-S3 WiFi module. The +ESP32-S3 runs the Arduino [uno-r4-wifi-usb-bridge][bridge] firmware. The +RA4M1 talks to it over UART (SCI1, `machine.UART3`) with an AT style +protocol. This driver speaks that protocol and implements the +[netlink](../netlink) and [netdev](../netdev) interfaces, so the standard +`net` package works. + +Keep the stock bridge firmware on the ESP32-S3. Do not flash the ESP32-S3. + +## Supported + +- WiFi station mode (`ConnectModeSTA`) with WPA2 or open networks +- WiFi access point mode (`ConnectModeAP`) +- TCP client and TCP server +- UDP +- DNS lookup + +## Not supported + +- TLS offload in the ESP32-S3. Use the Go `crypto/tls` package instead. +- Socket options (`SetSockOpt` returns `netdev.ErrNotSupported`). +- BLE. The bridge has HCI pass-through commands, but this driver does not + use them. + +## Usage + +```go +import ( + "tinygo.org/x/drivers/netlink" + "tinygo.org/x/drivers/netlink/probe" +) + +link, _ := probe.Probe() +err := link.NetConnect(&netlink.ConnectParams{ + Ssid: "my-ssid", + Passphrase: "my-passphrase", +}) +``` + +Then use `net.Dial`, `net.Listen` and so on. + +The RA4M1 has 256 KB of flash. The `net/http` package does not fit. +Use the `net` package directly, or a small client such as the `ntpclient` +or `tcpclient` examples. + +Build with `-target=arduino-uno-r4-wifi -stack-size 2kb`. The RA4M1 has +32 KB of RAM and each goroutine gets a stack of the given size, so a larger +stack size leaves too little heap. The network examples that fit in flash +(`socket`, `tcpclient`, `tcpecho`, `ntpclient`, `tlsclient`, `webclient`) +carry the `arduino_uno_r4_wifi` build tag. + +Do not use `io.Copy` with a `net.TCPConn` on this board. It allocates a +32 KB buffer. Use a `Read`/`Write` loop with a small buffer instead. + +## Protocol + +Commands and response formats are defined in the bridge firmware: + +- [commands.h][commands] +- [cmds_wifi_netif.h][netif] (TCP client and server) +- [cmds_wifi_udp.h][udp] + +Text responses look like `+CMD:\r\nOK\r\n`. Binary responses from +`+CLIENTRECEIVE` and `+UDPREAD` look like `+CMD:|OK\r\n`. +Payload for `+CLIENTSEND` and `+UDPWRITE` follows the command line as raw +bytes. + +[bridge]: https://github.com/arduino/uno-r4-wifi-usb-bridge +[commands]: https://github.com/arduino/uno-r4-wifi-usb-bridge/blob/main/UNOR4USBBridge/commands.h +[netif]: https://github.com/arduino/uno-r4-wifi-usb-bridge/blob/main/UNOR4USBBridge/cmds_wifi_netif.h +[udp]: https://github.com/arduino/uno-r4-wifi-usb-bridge/blob/main/UNOR4USBBridge/cmds_wifi_udp.h diff --git a/unor4wifi/debug.go b/unor4wifi/debug.go new file mode 100644 index 000000000..7e42405c6 --- /dev/null +++ b/unor4wifi/debug.go @@ -0,0 +1,16 @@ +package unor4wifi + +type debug uint8 + +const ( + debugBasic debug = 1 << iota // show fw version, mac addr, etc + debugNetdev // show netdev entry points + debugCmd // show AT cmds + + debugOff = 0 + debugAll = debugBasic | debugNetdev | debugCmd +) + +func debugging(want debug) bool { + return (_debug & want) != 0 +} diff --git a/unor4wifi/modem.go b/unor4wifi/modem.go new file mode 100644 index 000000000..4a7178642 --- /dev/null +++ b/unor4wifi/modem.go @@ -0,0 +1,225 @@ +package unor4wifi + +import ( + "errors" + "fmt" + "machine" + "runtime" + "strconv" + "strings" + "time" +) + +var ( + errModemError = errors.New("unor4wifi: modem returned ERROR") + errModemTimeout = errors.New("unor4wifi: modem response timeout") + errModemParse = errors.New("unor4wifi: modem response parse error") +) + +const ( + tokenOK = "OK" + tokenError = "ERROR" +) + +// modem is the AT transport to the ESP32-S3 bridge firmware. +// The protocol is defined in uno-r4-wifi-usb-bridge/UNOR4USBBridge/commands.h. +// Responses have the form "+CMD:\r\nOK\r\n" or "ERROR\r\n". +// Binary responses have the form "+CMD:|OK\r\n". +type modem struct { + uart *machine.UART + timeout time.Duration + line []byte +} + +func (m *modem) readByte(deadline time.Time) (byte, error) { + for m.uart.Buffered() == 0 { + if time.Now().After(deadline) { + return 0, errModemTimeout + } + runtime.Gosched() + } + return m.uart.ReadByte() +} + +// readLine reads a line and strips the trailing CR LF. +func (m *modem) readLine(deadline time.Time) (string, error) { + m.line = m.line[:0] + for { + c, err := m.readByte(deadline) + if err != nil { + return "", err + } + if c == '\n' { + n := len(m.line) + if n > 0 && m.line[n-1] == '\r' { + n-- + } + return string(m.line[:n]), nil + } + m.line = append(m.line, c) + } +} + +func (m *modem) writeString(s string) { + m.uart.Write([]byte(s)) +} + +func (m *modem) flushInput() { + for m.uart.Buffered() > 0 { + m.uart.ReadByte() + } +} + +// waitResult reads response lines until OK or ERROR. +// Data lines are collected into a single string. Multiple data lines are +// joined with "\r\n". +func (m *modem) waitResult(deadline time.Time) (string, error) { + var sb strings.Builder + first := true + for { + line, err := m.readLine(deadline) + if err != nil { + return sb.String(), err + } + if debugging(debugCmd) { + fmt.Printf(" [<--] %s\r\n", line) + } + switch { + case line == tokenOK: + return strings.TrimSpace(sb.String()), nil + case line == tokenError: + return strings.TrimSpace(sb.String()), errModemError + case first && len(line) > 0 && line[0] == '+': + if i := strings.IndexAny(line, ":="); i >= 0 { + line = line[i+1:] + } else { + line = "" + } + sb.WriteString(strings.TrimLeft(line, " ")) + first = false + case first && line == "": + // Skip empty lines before the prompt. + default: + if !first { + sb.WriteString("\r\n") + } + sb.WriteString(line) + first = false + } + } +} + +// exec sends a command and returns the response data. +func (m *modem) exec(cmd string) (string, error) { + return m.execTimeout(cmd, m.timeout) +} + +func (m *modem) execTimeout(cmd string, timeout time.Duration) (string, error) { + m.flushInput() + if debugging(debugCmd) { + fmt.Printf(" [-->] %s\r\n", cmd) + } + m.writeString(cmd) + m.writeString("\r\n") + return m.waitResult(time.Now().Add(timeout)) +} + +// execInt sends a command and parses the response as an integer. +func (m *modem) execInt(cmd string) (int, error) { + res, err := m.exec(cmd) + if err != nil { + return 0, err + } + n, err := strconv.Atoi(res) + if err != nil { + return 0, errModemParse + } + return n, nil +} + +// execSend sends a command followed by raw payload bytes and waits for OK. +func (m *modem) execSend(cmd string, payload []byte) error { + m.flushInput() + if debugging(debugCmd) { + fmt.Printf(" [-->] %s, len(payload): %d\r\n", cmd, len(payload)) + } + m.writeString(cmd) + m.writeString("\r\n") + m.uart.Write(payload) + _, err := m.waitResult(time.Now().Add(m.timeout)) + return err +} + +// execSized sends a command whose response carries binary data in the form +// "+CMD:|". The bytes are stored in dst. Returns the count. +func (m *modem) execSized(cmd string, dst []byte) (int, error) { + m.flushInput() + if debugging(debugCmd) { + fmt.Printf(" [-->] %s\r\n", cmd) + } + m.writeString(cmd) + m.writeString("\r\n") + deadline := time.Now().Add(m.timeout) + + // Find the prompt. A bare ERROR line can arrive instead. + for { + c, err := m.readByte(deadline) + if err != nil { + return 0, err + } + if c == '+' { + break + } + if c == 'E' { + line, err := m.readLine(deadline) + if err != nil { + return 0, err + } + if "E"+line == tokenError { + return 0, errModemError + } + return 0, errModemParse + } + } + // Skip the command name up to ':'. + for { + c, err := m.readByte(deadline) + if err != nil { + return 0, err + } + if c == ':' || c == '=' { + break + } + } + // Read the decimal length up to '|'. + size := 0 + for { + c, err := m.readByte(deadline) + if err != nil { + return 0, err + } + if c == '|' { + break + } + if c < '0' || c > '9' { + if c == ' ' { + continue + } + return 0, errModemParse + } + size = size*10 + int(c-'0') + } + n := 0 + for i := 0; i < size; i++ { + c, err := m.readByte(deadline) + if err != nil { + return n, err + } + if i < len(dst) { + dst[i] = c + n++ + } + } + _, err := m.waitResult(deadline) + return n, err +} diff --git a/unor4wifi/unor4wifi.go b/unor4wifi/unor4wifi.go new file mode 100644 index 000000000..68af0dbfe --- /dev/null +++ b/unor4wifi/unor4wifi.go @@ -0,0 +1,732 @@ +// Package unor4wifi implements a WiFi network driver for the Arduino UNO R4 +// WiFi. The on-board ESP32-S3 runs the Arduino "uno-r4-wifi-usb-bridge" +// firmware. This driver talks to that firmware over UART with the same AT +// style protocol that the Arduino WiFiS3 library uses. +// +// Supported: STA and AP mode, TCP client, TCP server, UDP, DNS lookup. +// Not supported: TLS offload (use Go TLS), socket options. +// +// References: +// https://github.com/arduino/uno-r4-wifi-usb-bridge/blob/main/UNOR4USBBridge/commands.h +// https://github.com/arduino/ArduinoCore-renesas/tree/main/libraries/WiFiS3/src +package unor4wifi // import "tinygo.org/x/drivers/unor4wifi" + +import ( + "fmt" + "io" + "machine" + "net" + "net/netip" + "strconv" + "strings" + "sync" + "time" + + "tinygo.org/x/drivers" + "tinygo.org/x/drivers/netdev" + "tinygo.org/x/drivers/netlink" +) + +var _debug debug = debugBasic + +//var _debug debug = debugBasic | debugNetdev +//var _debug debug = debugBasic | debugNetdev | debugCmd + +var ( + driverName = "TinyGo UNO R4 WiFi (ESP32-S3 bridge) network device driver (unor4wifi)" +) + +const ( + defaultBaudRate = 115200 + defaultTimeout = 10 * time.Second + maxSockets = 8 + // The bridge RX path is a UART, so keep transfers small. + maxChunk = 1024 + // Poll interval while a Recv or Accept waits for data. + pollInterval = 5 * time.Millisecond + // TCP connect timeout passed to the firmware. + connectTimeout = 10 * time.Second + + // WiFi status values, see WiFiS3/src/WiFiTypes.h. + wlIdleStatus = 0 + wlConnected = 3 + wlConnectFailed = 4 + wlConnectionLost = 5 + wlDisconnected = 6 + wlAPListening = 7 + + // ip_type values, see commands.h. + ipAddr = 0 + gatewayAddr = 1 + netmaskAddr = 2 + dns1Addr = 3 + + modeSTA = 1 + modeAP = 2 +) + +type Config struct { + Uart *machine.UART + Tx machine.Pin + Rx machine.Pin + BaudRate uint32 + // Timeout for one modem transaction. Default 10 s. + Timeout time.Duration +} + +type socket struct { + protocol int + // Socket number inside the ESP32 firmware, -1 when not yet allocated. + modemSock int + server bool + laddr netip.AddrPort + raddr netip.AddrPort +} + +type device struct { + cfg *Config + modem modem + mu sync.Mutex + notifyCb func(netlink.Event) + + params *netlink.ConnectParams + netConnected bool + mac net.HardwareAddr + ip netip.Addr + gateway netip.Addr + netmask netip.Addr + dns netip.Addr + + sockets [maxSockets]*socket + rxbuf [maxChunk]byte +} + +// New returns a new driver instance. The UART is configured in NetConnect. +func New(cfg *Config) *device { + d := &device{cfg: cfg} + d.modem.timeout = cfg.Timeout + if d.modem.timeout == 0 { + d.modem.timeout = defaultTimeout + } + return d +} + +// escapeArg escapes the characters that the bridge argument parser treats +// as special. See uno-r4-wifi-usb-bridge/UNOR4USBBridge/parser.cpp, +// ATParser::parse, state Argument. +func escapeArg(s string) string { + if !strings.ContainsAny(s, `\",`) { + return s + } + var sb strings.Builder + for i := 0; i < len(s); i++ { + c := s[i] + if c == '\\' || c == '"' || c == ',' { + sb.WriteByte('\\') + } + sb.WriteByte(c) + } + return sb.String() +} + +func (d *device) setupUART() { + baud := d.cfg.BaudRate + if baud == 0 { + baud = defaultBaudRate + } + d.modem.uart = d.cfg.Uart + d.modem.uart.Configure(machine.UARTConfig{ + BaudRate: baud, + TX: d.cfg.Tx, + RX: d.cfg.Rx, + }) +} + +// reset clears all firmware sockets and WiFi state. Retries until the +// firmware answers. +func (d *device) reset() error { + var err error + for i := 0; i < 10; i++ { + _, err = d.modem.execTimeout("AT+SOFTRESETWIFI", 500*time.Millisecond) + if err == nil { + return nil + } + } + return err +} + +func (d *device) firmwareVersion() string { + res, err := d.modem.exec("AT+FWVERSION?") + if err != nil { + return "unknown" + } + return res +} + +func (d *device) readMAC(cmd string) { + res, err := d.modem.exec(cmd) + if err != nil { + return + } + if mac, err := net.ParseMAC(res); err == nil { + d.mac = mac + } +} + +func (d *device) readAddr(cmd string) netip.Addr { + res, err := d.modem.exec(cmd) + if err != nil { + return netip.Addr{} + } + addr, _ := netip.ParseAddr(strings.TrimSpace(res)) + return addr +} + +func (d *device) status() int { + n, err := d.modem.execInt("AT+GETSTATUS?") + if err != nil { + return wlIdleStatus + } + return n +} + +func (d *device) connectSTA() error { + p := d.params + timeout := p.ConnectTimeout + if timeout == 0 { + timeout = netlink.DefaultConnectTimeout + } + + if _, err := d.modem.exec("AT+WIFIMODE=" + strconv.Itoa(modeSTA)); err != nil { + return err + } + if p.Hostname != "" { + d.modem.exec("AT+HOSTNAME=" + escapeArg(p.Hostname)) + } + + cmd := "AT+BEGINSTA=" + escapeArg(p.Ssid) + if p.Passphrase != "" { + cmd += "," + escapeArg(p.Passphrase) + } + if _, err := d.modem.exec(cmd); err != nil { + return netlink.ErrConnectFailed + } + + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + switch d.status() { + case wlConnected: + // The bridge reports WL_CONNECTED before DHCP completes. + d.ip = d.readAddr("AT+IPSTA=" + strconv.Itoa(ipAddr)) + if !d.ip.IsValid() || d.ip.IsUnspecified() { + break + } + d.gateway = d.readAddr("AT+IPSTA=" + strconv.Itoa(gatewayAddr)) + d.netmask = d.readAddr("AT+IPSTA=" + strconv.Itoa(netmaskAddr)) + d.dns = d.readAddr("AT+IPSTA=" + strconv.Itoa(dns1Addr)) + d.readMAC("AT+MACSTA?") + return nil + case wlConnectFailed: + return netlink.ErrConnectFailed + } + time.Sleep(100 * time.Millisecond) + } + return netlink.ErrConnectTimeout +} + +func (d *device) connectAP() error { + p := d.params + if _, err := d.modem.exec("AT+WIFIMODE=" + strconv.Itoa(modeAP)); err != nil { + return err + } + // Channel 1 is the WiFiS3 default. + cmd := "AT+BEGINSOFTAP=" + escapeArg(p.Ssid) + "," + escapeArg(p.Passphrase) + ",1" + n, err := d.modem.execInt(cmd) + if err != nil || n != wlAPListening { + return netlink.ErrConnectFailed + } + d.ip = d.readAddr("AT+IPSOFTAP") + d.gateway = d.ip + d.readMAC("AT+MACSOFTAP?") + return nil +} + +func (d *device) NetConnect(params *netlink.ConnectParams) error { + d.mu.Lock() + defer d.mu.Unlock() + + if d.netConnected { + return netlink.ErrConnected + } + if len(params.Ssid) == 0 { + return netlink.ErrMissingSSID + } + if params.ConnectMode == netlink.ConnectModeSTA && + params.AuthType != netlink.AuthTypeOpen && len(params.Passphrase) < 8 { + return netlink.ErrShortPassphrase + } + d.params = params + + d.setupUART() + + if debugging(debugBasic) { + fmt.Printf("\r\n") + fmt.Printf("%s\r\n\r\n", driverName) + fmt.Printf("Driver version : %s\r\n", drivers.Version) + } + + if err := d.reset(); err != nil { + return err + } + if debugging(debugBasic) { + fmt.Printf("Bridge firmware version : %s\r\n", d.firmwareVersion()) + } + + var err error + switch params.ConnectMode { + case netlink.ConnectModeSTA: + if debugging(debugBasic) { + fmt.Printf("Connecting to Wifi SSID '%s'...", params.Ssid) + } + err = d.connectSTA() + case netlink.ConnectModeAP: + if debugging(debugBasic) { + fmt.Printf("Starting Wifi AP as SSID '%s'...", params.Ssid) + } + err = d.connectAP() + default: + return netlink.ErrConnectModeNoGood + } + if err != nil { + if debugging(debugBasic) { + fmt.Printf("FAILED (%s)\r\n", err.Error()) + } + return err + } + if debugging(debugBasic) { + fmt.Printf("CONNECTED\r\n") + fmt.Printf("\r\n") + fmt.Printf("MAC address : %s\r\n", d.mac.String()) + fmt.Printf("IP address : %s\r\n", d.ip) + fmt.Printf("Gateway : %s\r\n", d.gateway) + if d.dns.IsValid() { + fmt.Printf("DNS server : %s\r\n", d.dns) + } + fmt.Printf("\r\n") + } + + d.netConnected = true + if d.notifyCb != nil { + d.notifyCb(netlink.EventNetUp) + } + return nil +} + +func (d *device) NetDisconnect() { + d.mu.Lock() + defer d.mu.Unlock() + + if !d.netConnected { + return + } + if d.params.ConnectMode == netlink.ConnectModeAP { + d.modem.exec("AT+DISCONNECTSOFTAP") + } else { + d.modem.exec("AT+DISCONNECT") + } + d.netConnected = false + + if debugging(debugBasic) { + fmt.Printf("\r\nDisconnected from Wifi SSID '%s'\r\n\r\n", d.params.Ssid) + } + + if d.notifyCb != nil { + d.notifyCb(netlink.EventNetDown) + } +} + +func (d *device) NetNotify(cb func(netlink.Event)) { + d.notifyCb = cb +} + +func (d *device) GetHardwareAddr() (net.HardwareAddr, error) { + if debugging(debugNetdev) { + fmt.Printf("[GetHardwareAddr]\r\n") + } + + return d.mac, nil +} + +func (d *device) GetHostByName(name string) (netip.Addr, error) { + if debugging(debugNetdev) { + fmt.Printf("[GetHostByName] name: %s\r\n", name) + } + + if ip, err := netip.ParseAddr(name); err == nil { + return ip, nil + } + + d.mu.Lock() + defer d.mu.Unlock() + + res, err := d.modem.exec("AT+HOSTBYNAME=" + name) + if err != nil { + return netip.Addr{}, netdev.ErrHostUnknown + } + ip, err := netip.ParseAddr(strings.TrimSpace(res)) + if err != nil { + return netip.Addr{}, netdev.ErrHostUnknown + } + return ip, nil +} + +func (d *device) Addr() (netip.Addr, error) { + if debugging(debugNetdev) { + fmt.Printf("[GetIPAddr]\r\n") + } + + return d.ip, nil +} + +func (d *device) getSocket(sockfd int) (*socket, error) { + if sockfd < 0 || sockfd >= maxSockets || d.sockets[sockfd] == nil { + return nil, netdev.ErrInvalidSocketFd + } + return d.sockets[sockfd], nil +} + +func (d *device) newSocket(protocol int, modemSock int) (int, *socket, error) { + for fd := range d.sockets { + if d.sockets[fd] == nil { + s := &socket{protocol: protocol, modemSock: modemSock} + d.sockets[fd] = s + return fd, s, nil + } + } + return -1, nil, netdev.ErrNoMoreSockets +} + +func (d *device) Socket(domain int, stype int, protocol int) (int, error) { + if debugging(debugNetdev) { + fmt.Printf("[Socket] domain: %d, type: %d, protocol: %d\r\n", + domain, stype, protocol) + } + + if domain != netdev.AF_INET { + return -1, netdev.ErrFamilyNotSupported + } + switch { + case protocol == netdev.IPPROTO_TCP && stype == netdev.SOCK_STREAM: + case protocol == netdev.IPPROTO_UDP && stype == netdev.SOCK_DGRAM: + default: + return -1, netdev.ErrProtocolNotSupported + } + + d.mu.Lock() + defer d.mu.Unlock() + + fd, _, err := d.newSocket(protocol, -1) + return fd, err +} + +// udpBegin opens the firmware UDP socket on the local port, once. +func (d *device) udpBegin(s *socket) error { + if s.modemSock >= 0 { + return nil + } + n, err := d.modem.execInt("AT+UDPBEGIN=" + strconv.Itoa(int(s.laddr.Port()))) + if err != nil { + return err + } + s.modemSock = n + return nil +} + +func (d *device) Bind(sockfd int, ip netip.AddrPort) error { + if debugging(debugNetdev) { + fmt.Printf("[Bind] sockfd: %d, addr: %s:%d\r\n", sockfd, ip.Addr(), ip.Port()) + } + + d.mu.Lock() + defer d.mu.Unlock() + + s, err := d.getSocket(sockfd) + if err != nil { + return err + } + s.laddr = ip + if s.protocol == netdev.IPPROTO_UDP { + return d.udpBegin(s) + } + return nil +} + +func (d *device) Connect(sockfd int, host string, ip netip.AddrPort) error { + if debugging(debugNetdev) { + fmt.Printf("[Connect] sockfd: %d, host: %s, addr: %s\r\n", sockfd, host, ip) + } + + d.mu.Lock() + defer d.mu.Unlock() + + s, err := d.getSocket(sockfd) + if err != nil { + return err + } + s.raddr = ip + + if s.protocol == netdev.IPPROTO_UDP { + return d.udpBegin(s) + } + + if s.modemSock < 0 { + n, err := d.modem.execInt("AT+BEGINCLIENT") + if err != nil { + return err + } + s.modemSock = n + } + + // The firmware resolves names and dotted addresses through the same + // path, so always use +CLIENTCONNECT like the Arduino WiFiS3 library. + if host == "" { + host = ip.Addr().String() + } + cmd := "AT+CLIENTCONNECT=" + strconv.Itoa(s.modemSock) + "," + host + "," + + strconv.Itoa(int(ip.Port())) + "," + strconv.Itoa(int(connectTimeout/time.Millisecond)) + if _, err := d.modem.execTimeout(cmd, connectTimeout+d.modem.timeout); err != nil { + return netlink.ErrConnectFailed + } + return nil +} + +func (d *device) Listen(sockfd int, backlog int) error { + if debugging(debugNetdev) { + fmt.Printf("[Listen] sockfd: %d\r\n", sockfd) + } + + d.mu.Lock() + defer d.mu.Unlock() + + s, err := d.getSocket(sockfd) + if err != nil { + return err + } + if s.protocol != netdev.IPPROTO_TCP { + return netdev.ErrProtocolNotSupported + } + n, err := d.modem.execInt("AT+BEGINSERVER=" + strconv.Itoa(int(s.laddr.Port()))) + if err != nil { + return err + } + s.modemSock = n + s.server = true + return nil +} + +func (d *device) remoteAddr(sock string) netip.AddrPort { + ipStr, err := d.modem.exec("AT+REMOTEIP=" + sock) + if err != nil { + return netip.AddrPort{} + } + port, err := d.modem.execInt("AT+REMOTEPORT=" + sock) + if err != nil { + return netip.AddrPort{} + } + ip, _ := netip.ParseAddr(strings.TrimSpace(ipStr)) + return netip.AddrPortFrom(ip, uint16(port)) +} + +func (d *device) Accept(sockfd int) (int, netip.AddrPort, error) { + if debugging(debugNetdev) { + fmt.Printf("[Accept] sockfd: %d\r\n", sockfd) + } + + for { + d.mu.Lock() + s, err := d.getSocket(sockfd) + if err != nil { + d.mu.Unlock() + return -1, netip.AddrPort{}, err + } + if !s.server { + d.mu.Unlock() + return -1, netip.AddrPort{}, netdev.ErrNotSupported + } + n, err := d.modem.execInt("AT+SERVERACCEPT=" + strconv.Itoa(s.modemSock)) + if err == nil && n >= 0 { + fd, cs, err := d.newSocket(netdev.IPPROTO_TCP, n) + if err != nil { + d.mu.Unlock() + return -1, netip.AddrPort{}, err + } + cs.laddr = s.laddr + cs.raddr = d.remoteAddr(strconv.Itoa(n)) + d.mu.Unlock() + return fd, cs.raddr, nil + } + d.mu.Unlock() + time.Sleep(pollInterval) + } +} + +func (d *device) sendTCP(s *socket, buf []byte) (int, error) { + sock := strconv.Itoa(s.modemSock) + sent := 0 + for sent < len(buf) { + end := sent + maxChunk + if end > len(buf) { + end = len(buf) + } + chunk := buf[sent:end] + cmd := "AT+CLIENTSEND=" + sock + "," + strconv.Itoa(len(chunk)) + if err := d.modem.execSend(cmd, chunk); err != nil { + return sent, err + } + sent += len(chunk) + } + return sent, nil +} + +func (d *device) sendUDP(s *socket, buf []byte) (int, error) { + sock := strconv.Itoa(s.modemSock) + cmd := "AT+UDPBEGINPACKETIP=" + sock + "," + + strconv.Itoa(int(s.raddr.Port())) + "," + s.raddr.Addr().String() + if _, err := d.modem.exec(cmd); err != nil { + return 0, err + } + cmd = "AT+UDPWRITE=" + sock + "," + strconv.Itoa(len(buf)) + if err := d.modem.execSend(cmd, buf); err != nil { + return 0, err + } + if _, err := d.modem.exec("AT+UDPENDPACKET=" + sock); err != nil { + return 0, err + } + return len(buf), nil +} + +func (d *device) Send(sockfd int, buf []byte, flags int, deadline time.Time) (int, error) { + if debugging(debugNetdev) { + fmt.Printf("[Send] sockfd: %d, len(buf): %d, flags: %d\r\n", + sockfd, len(buf), flags) + } + + d.mu.Lock() + defer d.mu.Unlock() + + s, err := d.getSocket(sockfd) + if err != nil { + return 0, err + } + if s.modemSock < 0 { + return 0, netdev.ErrInvalidSocketFd + } + if s.protocol == netdev.IPPROTO_UDP { + return d.sendUDP(s, buf) + } + return d.sendTCP(s, buf) +} + +// recvOnce performs one receive attempt. Returns 0, nil when no data is +// available yet, and io.EOF when the connection is closed. +func (d *device) recvOnce(s *socket, buf []byte) (int, error) { + sock := strconv.Itoa(s.modemSock) + want := len(buf) + if want > maxChunk { + want = maxChunk + } + + if s.protocol == netdev.IPPROTO_UDP { + n, err := d.modem.execInt("AT+UDPPARSE=" + sock) + if err != nil { + return 0, err + } + if n == 0 { + return 0, nil + } + if n < want { + want = n + } + return d.modem.execSized("AT+UDPREAD="+sock+","+strconv.Itoa(want), buf) + } + + n, err := d.modem.execSized("AT+CLIENTRECEIVE="+sock+","+strconv.Itoa(want), buf) + if err != nil { + return 0, err + } + if n > 0 { + return n, nil + } + connected, err := d.modem.execInt("AT+CLIENTCONNECTED=" + sock) + if err != nil || connected == 0 { + return 0, io.EOF + } + return 0, nil +} + +func (d *device) Recv(sockfd int, buf []byte, flags int, deadline time.Time) (int, error) { + if debugging(debugNetdev) { + fmt.Printf("[Recv] sockfd: %d, len(buf): %d, flags: %d\r\n", + sockfd, len(buf), flags) + } + + for { + d.mu.Lock() + s, err := d.getSocket(sockfd) + if err != nil { + d.mu.Unlock() + return 0, err + } + if s.modemSock < 0 { + d.mu.Unlock() + return 0, netdev.ErrInvalidSocketFd + } + n, err := d.recvOnce(s, buf) + d.mu.Unlock() + if err != nil || n > 0 { + return n, err + } + if !deadline.IsZero() && time.Now().After(deadline) { + return 0, netdev.ErrTimeout + } + time.Sleep(pollInterval) + } +} + +func (d *device) Close(sockfd int) error { + if debugging(debugNetdev) { + fmt.Printf("[Close] sockfd: %d\r\n", sockfd) + } + + d.mu.Lock() + defer d.mu.Unlock() + + s, err := d.getSocket(sockfd) + if err != nil { + return err + } + if s.modemSock >= 0 { + sock := strconv.Itoa(s.modemSock) + switch { + case s.protocol == netdev.IPPROTO_UDP: + _, err = d.modem.exec("AT+UDPSTOP=" + sock) + case s.server: + _, err = d.modem.exec("AT+SERVEREND=" + sock) + default: + _, err = d.modem.exec("AT+CLIENTCLOSE=" + sock) + } + } + d.sockets[sockfd] = nil + if err != nil { + return netdev.ErrClosingSocket + } + return nil +} + +func (d *device) SetSockOpt(sockfd int, level int, opt int, value interface{}) error { + if debugging(debugNetdev) { + fmt.Printf("[SetSockOpt] sockfd: %d\r\n", sockfd) + } + + return netdev.ErrNotSupported +} From eef8051c03460dba43bbca00f04cebcd76765725 Mon Sep 17 00:00:00 2001 From: Frelsaren Date: Thu, 12 Nov 2026 09:47:59 +0100 Subject: [PATCH 2/5] unor4wifi: increase stack size to 4kb for net examples --- unor4wifi/README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/unor4wifi/README.md b/unor4wifi/README.md index d14aa21b4..e22b6cd00 100644 --- a/unor4wifi/README.md +++ b/unor4wifi/README.md @@ -47,9 +47,10 @@ The RA4M1 has 256 KB of flash. The `net/http` package does not fit. Use the `net` package directly, or a small client such as the `ntpclient` or `tcpclient` examples. -Build with `-target=arduino-uno-r4-wifi -stack-size 2kb`. The RA4M1 has -32 KB of RAM and each goroutine gets a stack of the given size, so a larger -stack size leaves too little heap. The network examples that fit in flash +Build with `-target=arduino-uno-r4-wifi -stack-size 4kb`. The RA4M1 has +32 KB of RAM and each goroutine gets a stack of the given size, so a much +larger stack size leaves too little heap. With 2 KB the `ntpclient` example +overflows the stack while connecting. The network examples that fit in flash (`socket`, `tcpclient`, `tcpecho`, `ntpclient`, `tlsclient`, `webclient`) carry the `arduino_uno_r4_wifi` build tag. From d8e46e58d76a449e1351e5de87f4beaef6b90838 Mon Sep 17 00:00:00 2001 From: Frelsaren Date: Thu, 12 Nov 2026 09:49:44 +0100 Subject: [PATCH 3/5] unor4wifi: harden AT I/O and arg handling --- unor4wifi/modem.go | 21 +++++++++--- unor4wifi/unor4wifi.go | 78 ++++++++++++++++++++++++++++++++---------- 2 files changed, 75 insertions(+), 24 deletions(-) diff --git a/unor4wifi/modem.go b/unor4wifi/modem.go index 4a7178642..459b0294d 100644 --- a/unor4wifi/modem.go +++ b/unor4wifi/modem.go @@ -14,11 +14,13 @@ var ( errModemError = errors.New("unor4wifi: modem returned ERROR") errModemTimeout = errors.New("unor4wifi: modem response timeout") errModemParse = errors.New("unor4wifi: modem response parse error") + errInvalidArg = errors.New("unor4wifi: control character in argument") ) const ( tokenOK = "OK" tokenError = "ERROR" + maxLine = 256 ) // modem is the AT transport to the ESP32-S3 bridge firmware. @@ -28,7 +30,7 @@ const ( type modem struct { uart *machine.UART timeout time.Duration - line []byte + line [maxLine]byte } func (m *modem) readByte(deadline time.Time) (byte, error) { @@ -41,22 +43,31 @@ func (m *modem) readByte(deadline time.Time) (byte, error) { return m.uart.ReadByte() } -// readLine reads a line and strips the trailing CR LF. +// readLine reads a line and strips the trailing CR LF. Lines longer than +// maxLine are discarded up to the LF and return errModemParse. func (m *modem) readLine(deadline time.Time) (string, error) { - m.line = m.line[:0] + n := 0 + overflow := false for { c, err := m.readByte(deadline) if err != nil { return "", err } if c == '\n' { - n := len(m.line) + if overflow { + return "", errModemParse + } if n > 0 && m.line[n-1] == '\r' { n-- } return string(m.line[:n]), nil } - m.line = append(m.line, c) + if n < len(m.line) { + m.line[n] = c + n++ + } else { + overflow = true + } } } diff --git a/unor4wifi/unor4wifi.go b/unor4wifi/unor4wifi.go index 68af0dbfe..c555bddb9 100644 --- a/unor4wifi/unor4wifi.go +++ b/unor4wifi/unor4wifi.go @@ -53,7 +53,6 @@ const ( wlConnectFailed = 4 wlConnectionLost = 5 wlDisconnected = 6 - wlAPListening = 7 // ip_type values, see commands.h. ipAddr = 0 @@ -98,7 +97,6 @@ type device struct { dns netip.Addr sockets [maxSockets]*socket - rxbuf [maxChunk]byte } // New returns a new driver instance. The UART is configured in NetConnect. @@ -129,6 +127,17 @@ func escapeArg(s string) string { return sb.String() } +// checkArg rejects control characters. The bridge parser ends a command at +// LF before escape handling, see parser.cpp, ATParser::parse. +func checkArg(s string) error { + for i := 0; i < len(s); i++ { + if s[i] < ' ' || s[i] == 0x7f { + return errInvalidArg + } + } + return nil +} + func (d *device) setupUART() { baud := d.cfg.BaudRate if baud == 0 { @@ -145,6 +154,7 @@ func (d *device) setupUART() { // reset clears all firmware sockets and WiFi state. Retries until the // firmware answers. func (d *device) reset() error { + d.sockets = [maxSockets]*socket{} var err error for i := 0; i < 10; i++ { _, err = d.modem.execTimeout("AT+SOFTRESETWIFI", 500*time.Millisecond) @@ -242,7 +252,7 @@ func (d *device) connectAP() error { // Channel 1 is the WiFiS3 default. cmd := "AT+BEGINSOFTAP=" + escapeArg(p.Ssid) + "," + escapeArg(p.Passphrase) + ",1" n, err := d.modem.execInt(cmd) - if err != nil || n != wlAPListening { + if err != nil || n != 1 { return netlink.ErrConnectFailed } d.ip = d.readAddr("AT+IPSOFTAP") @@ -251,20 +261,40 @@ func (d *device) connectAP() error { return nil } -func (d *device) NetConnect(params *netlink.ConnectParams) error { - d.mu.Lock() - defer d.mu.Unlock() - - if d.netConnected { - return netlink.ErrConnected +func checkParams(params *netlink.ConnectParams) error { + if params.ConnectMode != netlink.ConnectModeSTA && + params.ConnectMode != netlink.ConnectModeAP { + return netlink.ErrConnectModeNoGood } if len(params.Ssid) == 0 { return netlink.ErrMissingSSID } + if err := checkArg(params.Ssid); err != nil { + return err + } + if err := checkArg(params.Passphrase); err != nil { + return err + } + if err := checkArg(params.Hostname); err != nil { + return err + } if params.ConnectMode == netlink.ConnectModeSTA && params.AuthType != netlink.AuthTypeOpen && len(params.Passphrase) < 8 { return netlink.ErrShortPassphrase } + return nil +} + +func (d *device) NetConnect(params *netlink.ConnectParams) error { + d.mu.Lock() + defer d.mu.Unlock() + + if d.netConnected { + return netlink.ErrConnected + } + if err := checkParams(params); err != nil { + return err + } d.params = params d.setupUART() @@ -294,8 +324,6 @@ func (d *device) NetConnect(params *netlink.ConnectParams) error { fmt.Printf("Starting Wifi AP as SSID '%s'...", params.Ssid) } err = d.connectAP() - default: - return netlink.ErrConnectModeNoGood } if err != nil { if debugging(debugBasic) { @@ -365,11 +393,14 @@ func (d *device) GetHostByName(name string) (netip.Addr, error) { if ip, err := netip.ParseAddr(name); err == nil { return ip, nil } + if err := checkArg(name); err != nil { + return netip.Addr{}, err + } d.mu.Lock() defer d.mu.Unlock() - res, err := d.modem.exec("AT+HOSTBYNAME=" + name) + res, err := d.modem.exec("AT+HOSTBYNAME=" + escapeArg(name)) if err != nil { return netip.Addr{}, netdev.ErrHostUnknown } @@ -479,6 +510,13 @@ func (d *device) Connect(sockfd int, host string, ip netip.AddrPort) error { return d.udpBegin(s) } + if host == "" { + host = ip.Addr().String() + } + if err := checkArg(host); err != nil { + return err + } + if s.modemSock < 0 { n, err := d.modem.execInt("AT+BEGINCLIENT") if err != nil { @@ -487,12 +525,9 @@ func (d *device) Connect(sockfd int, host string, ip netip.AddrPort) error { s.modemSock = n } - // The firmware resolves names and dotted addresses through the same - // path, so always use +CLIENTCONNECT like the Arduino WiFiS3 library. - if host == "" { - host = ip.Addr().String() - } - cmd := "AT+CLIENTCONNECT=" + strconv.Itoa(s.modemSock) + "," + host + "," + + // WiFiS3 uses +CLIENTCONNECT only with a timeout, else +CLIENTCONNECTNAME. + // This driver always passes a timeout, which the firmware accepts for names too. + cmd := "AT+CLIENTCONNECT=" + strconv.Itoa(s.modemSock) + "," + escapeArg(host) + "," + strconv.Itoa(int(ip.Port())) + "," + strconv.Itoa(int(connectTimeout/time.Millisecond)) if _, err := d.modem.execTimeout(cmd, connectTimeout+d.modem.timeout); err != nil { return netlink.ErrConnectFailed @@ -554,9 +589,14 @@ func (d *device) Accept(sockfd int) (int, netip.AddrPort, error) { return -1, netip.AddrPort{}, netdev.ErrNotSupported } n, err := d.modem.execInt("AT+SERVERACCEPT=" + strconv.Itoa(s.modemSock)) - if err == nil && n >= 0 { + if err != nil { + d.mu.Unlock() + return -1, netip.AddrPort{}, err + } + if n >= 0 { fd, cs, err := d.newSocket(netdev.IPPROTO_TCP, n) if err != nil { + d.modem.exec("AT+CLIENTCLOSE=" + strconv.Itoa(n)) d.mu.Unlock() return -1, netip.AddrPort{}, err } From fc00e48afe773749a02167ba750b87477622475e Mon Sep 17 00:00:00 2001 From: Frelsaren Date: Sun, 15 Nov 2026 00:42:15 +0100 Subject: [PATCH 4/5] unor4wifi: detect link loss and unknown SSID Add an optional watchdog that reports EventNetDown and EventNetUp and reconnects in station mode. Fail fast with ErrConnectFailed when the SSID is not found. Allow an open AP with an empty passphrase and clear the socket table in NetDisconnect. --- unor4wifi/README.md | 10 +++ unor4wifi/modem.go | 9 +-- unor4wifi/unor4wifi.go | 162 ++++++++++++++++++++++++++++++++--------- 3 files changed, 140 insertions(+), 41 deletions(-) diff --git a/unor4wifi/README.md b/unor4wifi/README.md index e22b6cd00..d876fff5b 100644 --- a/unor4wifi/README.md +++ b/unor4wifi/README.md @@ -43,6 +43,16 @@ err := link.NetConnect(&netlink.ConnectParams{ Then use `net.Dial`, `net.Listen` and so on. +Set `WatchdogTimeout` in `ConnectParams` to detect link loss in station +mode. The driver then polls the link status at that interval, reports +`EventNetDown` and `EventNetUp` through `NetNotify`, and reconnects. The +watchdog runs in its own goroutine. With the default of zero, link loss is +not detected. + +An unknown SSID fails with `ErrConnectFailed` after about 4 s. The bridge +reports a wrong password only after roughly 10 s, so with the default +`ConnectTimeout` it still returns `ErrConnectTimeout`. + The RA4M1 has 256 KB of flash. The `net/http` package does not fit. Use the `net` package directly, or a small client such as the `ntpclient` or `tcpclient` examples. diff --git a/unor4wifi/modem.go b/unor4wifi/modem.go index 459b0294d..14529f4d9 100644 --- a/unor4wifi/modem.go +++ b/unor4wifi/modem.go @@ -2,7 +2,6 @@ package unor4wifi import ( "errors" - "fmt" "machine" "runtime" "strconv" @@ -93,7 +92,7 @@ func (m *modem) waitResult(deadline time.Time) (string, error) { return sb.String(), err } if debugging(debugCmd) { - fmt.Printf(" [<--] %s\r\n", line) + print(" [<--] ", line, "\r\n") } switch { case line == tokenOK: @@ -128,7 +127,7 @@ func (m *modem) exec(cmd string) (string, error) { func (m *modem) execTimeout(cmd string, timeout time.Duration) (string, error) { m.flushInput() if debugging(debugCmd) { - fmt.Printf(" [-->] %s\r\n", cmd) + print(" [-->] ", cmd, "\r\n") } m.writeString(cmd) m.writeString("\r\n") @@ -152,7 +151,7 @@ func (m *modem) execInt(cmd string) (int, error) { func (m *modem) execSend(cmd string, payload []byte) error { m.flushInput() if debugging(debugCmd) { - fmt.Printf(" [-->] %s, len(payload): %d\r\n", cmd, len(payload)) + print(" [-->] ", cmd, ", len(payload): ", len(payload), "\r\n") } m.writeString(cmd) m.writeString("\r\n") @@ -166,7 +165,7 @@ func (m *modem) execSend(cmd string, payload []byte) error { func (m *modem) execSized(cmd string, dst []byte) (int, error) { m.flushInput() if debugging(debugCmd) { - fmt.Printf(" [-->] %s\r\n", cmd) + print(" [-->] ", cmd, "\r\n") } m.writeString(cmd) m.writeString("\r\n") diff --git a/unor4wifi/unor4wifi.go b/unor4wifi/unor4wifi.go index c555bddb9..302b8da70 100644 --- a/unor4wifi/unor4wifi.go +++ b/unor4wifi/unor4wifi.go @@ -12,7 +12,6 @@ package unor4wifi // import "tinygo.org/x/drivers/unor4wifi" import ( - "fmt" "io" "machine" "net" @@ -40,15 +39,21 @@ const ( defaultBaudRate = 115200 defaultTimeout = 10 * time.Second maxSockets = 8 + // Firmware UDP and server pools, see at_handler.h. + maxUDP = 4 + maxServers = 4 // The bridge RX path is a UART, so keep transfers small. maxChunk = 1024 // Poll interval while a Recv or Accept waits for data. pollInterval = 5 * time.Millisecond // TCP connect timeout passed to the firmware. connectTimeout = 10 * time.Second + // Interval between +BEGINSTA status probes while a connect is pending. + probeInterval = 4 * time.Second // WiFi status values, see WiFiS3/src/WiFiTypes.h. wlIdleStatus = 0 + wlNoSSIDAvail = 1 wlConnected = 3 wlConnectFailed = 4 wlConnectionLost = 5 @@ -97,6 +102,9 @@ type device struct { dns netip.Addr sockets [maxSockets]*socket + // +SERVEREND keeps the slot until reset, see cmds_wifi_netif.h. + serversBegun int + watchdogDone chan struct{} } // New returns a new driver instance. The UART is configured in NetConnect. @@ -155,6 +163,7 @@ func (d *device) setupUART() { // firmware answers. func (d *device) reset() error { d.sockets = [maxSockets]*socket{} + d.serversBegun = 0 var err error for i := 0; i < 10; i++ { _, err = d.modem.execTimeout("AT+SOFTRESETWIFI", 500*time.Millisecond) @@ -218,11 +227,14 @@ func (d *device) connectSTA() error { if p.Passphrase != "" { cmd += "," + escapeArg(p.Passphrase) } - if _, err := d.modem.exec(cmd); err != nil { + + before, err := d.modem.execInt(cmd) + if err != nil { return netlink.ErrConnectFailed } deadline := time.Now().Add(timeout) + probe := time.Now().Add(probeInterval) for time.Now().Before(deadline) { switch d.status() { case wlConnected: @@ -236,8 +248,15 @@ func (d *device) connectSTA() error { d.dns = d.readAddr("AT+IPSTA=" + strconv.Itoa(dns1Addr)) d.readMAC("AT+MACSTA?") return nil - case wlConnectFailed: - return netlink.ErrConnectFailed + case wlIdleStatus: + if time.Now().Before(probe) { + break + } + probe = time.Now().Add(probeInterval) + n, err := d.modem.execInt(cmd) + if err == nil && n != before && (n == wlNoSSIDAvail || n == wlConnectFailed) { + return netlink.ErrConnectFailed + } } time.Sleep(100 * time.Millisecond) } @@ -278,13 +297,62 @@ func checkParams(params *netlink.ConnectParams) error { if err := checkArg(params.Hostname); err != nil { return err } - if params.ConnectMode == netlink.ConnectModeSTA && - params.AuthType != netlink.AuthTypeOpen && len(params.Passphrase) < 8 { + if params.ConnectMode == netlink.ConnectModeAP { + // An empty passphrase starts an open AP, see WiFiAP.cpp, WiFiAPClass::softAP. + if len(params.Passphrase) != 0 && len(params.Passphrase) < 8 { + return netlink.ErrShortPassphrase + } + } else if params.AuthType != netlink.AuthTypeOpen && len(params.Passphrase) < 8 { return netlink.ErrShortPassphrase } return nil } +// The bridge reports idle after link loss, see UNOR4USBBridge.ino, onWiFiEvent. +func (d *device) networkDown() bool { + n, err := d.modem.execInt("AT+GETSTATUS?") + return err == nil && n != wlConnected +} + +func (d *device) watchdog(done chan struct{}, timeout time.Duration) { + ticker := time.NewTicker(timeout) + defer ticker.Stop() + up := true + for { + select { + case <-done: + return + case <-ticker.C: + d.mu.Lock() + select { + case <-done: + d.mu.Unlock() + return + default: + } + if up && d.networkDown() { + up = false + if debugging(debugBasic) { + print("Watchdog: Wifi NOT CONNECTED, trying again...\r\n") + } + if d.notifyCb != nil { + d.notifyCb(netlink.EventNetDown) + } + } + if !up && d.connectSTA() == nil { + up = true + if debugging(debugBasic) { + print("Watchdog: Wifi CONNECTED\r\n") + } + if d.notifyCb != nil { + d.notifyCb(netlink.EventNetUp) + } + } + d.mu.Unlock() + } + } +} + func (d *device) NetConnect(params *netlink.ConnectParams) error { d.mu.Lock() defer d.mu.Unlock() @@ -300,53 +368,59 @@ func (d *device) NetConnect(params *netlink.ConnectParams) error { d.setupUART() if debugging(debugBasic) { - fmt.Printf("\r\n") - fmt.Printf("%s\r\n\r\n", driverName) - fmt.Printf("Driver version : %s\r\n", drivers.Version) + print("\r\n") + print(driverName, "\r\n\r\n") + print("Driver version : ", drivers.Version, "\r\n") } if err := d.reset(); err != nil { return err } if debugging(debugBasic) { - fmt.Printf("Bridge firmware version : %s\r\n", d.firmwareVersion()) + print("Bridge firmware version : ", d.firmwareVersion(), "\r\n") } var err error switch params.ConnectMode { case netlink.ConnectModeSTA: if debugging(debugBasic) { - fmt.Printf("Connecting to Wifi SSID '%s'...", params.Ssid) + print("Connecting to Wifi SSID '", params.Ssid, "'...") } err = d.connectSTA() case netlink.ConnectModeAP: if debugging(debugBasic) { - fmt.Printf("Starting Wifi AP as SSID '%s'...", params.Ssid) + print("Starting Wifi AP as SSID '", params.Ssid, "'...") } err = d.connectAP() } if err != nil { if debugging(debugBasic) { - fmt.Printf("FAILED (%s)\r\n", err.Error()) + print("FAILED (", err.Error(), ")\r\n") } return err } if debugging(debugBasic) { - fmt.Printf("CONNECTED\r\n") - fmt.Printf("\r\n") - fmt.Printf("MAC address : %s\r\n", d.mac.String()) - fmt.Printf("IP address : %s\r\n", d.ip) - fmt.Printf("Gateway : %s\r\n", d.gateway) + print("CONNECTED\r\n") + print("\r\n") + print("MAC address : ", d.mac.String(), "\r\n") + print("IP address : ", d.ip.String(), "\r\n") + print("Gateway : ", d.gateway.String(), "\r\n") if d.dns.IsValid() { - fmt.Printf("DNS server : %s\r\n", d.dns) + print("DNS server : ", d.dns.String(), "\r\n") } - fmt.Printf("\r\n") + print("\r\n") } d.netConnected = true if d.notifyCb != nil { d.notifyCb(netlink.EventNetUp) } + + if params.ConnectMode == netlink.ConnectModeSTA && params.WatchdogTimeout != 0 { + d.watchdogDone = make(chan struct{}) + go d.watchdog(d.watchdogDone, params.WatchdogTimeout) + } + return nil } @@ -357,15 +431,21 @@ func (d *device) NetDisconnect() { if !d.netConnected { return } + + if d.watchdogDone != nil { + close(d.watchdogDone) + d.watchdogDone = nil + } if d.params.ConnectMode == netlink.ConnectModeAP { d.modem.exec("AT+DISCONNECTSOFTAP") } else { d.modem.exec("AT+DISCONNECT") } d.netConnected = false + d.sockets = [maxSockets]*socket{} if debugging(debugBasic) { - fmt.Printf("\r\nDisconnected from Wifi SSID '%s'\r\n\r\n", d.params.Ssid) + print("\r\nDisconnected from Wifi SSID '", d.params.Ssid, "'\r\n\r\n") } if d.notifyCb != nil { @@ -379,7 +459,7 @@ func (d *device) NetNotify(cb func(netlink.Event)) { func (d *device) GetHardwareAddr() (net.HardwareAddr, error) { if debugging(debugNetdev) { - fmt.Printf("[GetHardwareAddr]\r\n") + print("[GetHardwareAddr]\r\n") } return d.mac, nil @@ -387,7 +467,7 @@ func (d *device) GetHardwareAddr() (net.HardwareAddr, error) { func (d *device) GetHostByName(name string) (netip.Addr, error) { if debugging(debugNetdev) { - fmt.Printf("[GetHostByName] name: %s\r\n", name) + print("[GetHostByName] name: ", name, "\r\n") } if ip, err := netip.ParseAddr(name); err == nil { @@ -413,7 +493,7 @@ func (d *device) GetHostByName(name string) (netip.Addr, error) { func (d *device) Addr() (netip.Addr, error) { if debugging(debugNetdev) { - fmt.Printf("[GetIPAddr]\r\n") + print("[GetIPAddr]\r\n") } return d.ip, nil @@ -439,8 +519,7 @@ func (d *device) newSocket(protocol int, modemSock int) (int, *socket, error) { func (d *device) Socket(domain int, stype int, protocol int) (int, error) { if debugging(debugNetdev) { - fmt.Printf("[Socket] domain: %d, type: %d, protocol: %d\r\n", - domain, stype, protocol) + print("[Socket] domain: ", domain, ", type: ", stype, ", protocol: ", protocol, "\r\n") } if domain != netdev.AF_INET { @@ -465,6 +544,15 @@ func (d *device) udpBegin(s *socket) error { if s.modemSock >= 0 { return nil } + udp := 0 + for _, o := range d.sockets { + if o != nil && o.protocol == netdev.IPPROTO_UDP && o.modemSock >= 0 { + udp++ + } + } + if udp >= maxUDP { + return netdev.ErrNoMoreSockets + } n, err := d.modem.execInt("AT+UDPBEGIN=" + strconv.Itoa(int(s.laddr.Port()))) if err != nil { return err @@ -475,7 +563,7 @@ func (d *device) udpBegin(s *socket) error { func (d *device) Bind(sockfd int, ip netip.AddrPort) error { if debugging(debugNetdev) { - fmt.Printf("[Bind] sockfd: %d, addr: %s:%d\r\n", sockfd, ip.Addr(), ip.Port()) + print("[Bind] sockfd: ", sockfd, ", addr: ", ip.Addr().String(), ":", ip.Port(), "\r\n") } d.mu.Lock() @@ -494,7 +582,7 @@ func (d *device) Bind(sockfd int, ip netip.AddrPort) error { func (d *device) Connect(sockfd int, host string, ip netip.AddrPort) error { if debugging(debugNetdev) { - fmt.Printf("[Connect] sockfd: %d, host: %s, addr: %s\r\n", sockfd, host, ip) + print("[Connect] sockfd: ", sockfd, ", host: ", host, ", addr: ", ip.String(), "\r\n") } d.mu.Lock() @@ -537,7 +625,7 @@ func (d *device) Connect(sockfd int, host string, ip netip.AddrPort) error { func (d *device) Listen(sockfd int, backlog int) error { if debugging(debugNetdev) { - fmt.Printf("[Listen] sockfd: %d\r\n", sockfd) + print("[Listen] sockfd: ", sockfd, "\r\n") } d.mu.Lock() @@ -550,10 +638,14 @@ func (d *device) Listen(sockfd int, backlog int) error { if s.protocol != netdev.IPPROTO_TCP { return netdev.ErrProtocolNotSupported } + if d.serversBegun >= maxServers { + return netdev.ErrNoMoreSockets + } n, err := d.modem.execInt("AT+BEGINSERVER=" + strconv.Itoa(int(s.laddr.Port()))) if err != nil { return err } + d.serversBegun++ s.modemSock = n s.server = true return nil @@ -574,7 +666,7 @@ func (d *device) remoteAddr(sock string) netip.AddrPort { func (d *device) Accept(sockfd int) (int, netip.AddrPort, error) { if debugging(debugNetdev) { - fmt.Printf("[Accept] sockfd: %d\r\n", sockfd) + print("[Accept] sockfd: ", sockfd, "\r\n") } for { @@ -647,8 +739,7 @@ func (d *device) sendUDP(s *socket, buf []byte) (int, error) { func (d *device) Send(sockfd int, buf []byte, flags int, deadline time.Time) (int, error) { if debugging(debugNetdev) { - fmt.Printf("[Send] sockfd: %d, len(buf): %d, flags: %d\r\n", - sockfd, len(buf), flags) + print("[Send] sockfd: ", sockfd, ", len(buf): ", len(buf), ", flags: ", flags, "\r\n") } d.mu.Lock() @@ -706,8 +797,7 @@ func (d *device) recvOnce(s *socket, buf []byte) (int, error) { func (d *device) Recv(sockfd int, buf []byte, flags int, deadline time.Time) (int, error) { if debugging(debugNetdev) { - fmt.Printf("[Recv] sockfd: %d, len(buf): %d, flags: %d\r\n", - sockfd, len(buf), flags) + print("[Recv] sockfd: ", sockfd, ", len(buf): ", len(buf), ", flags: ", flags, "\r\n") } for { @@ -735,7 +825,7 @@ func (d *device) Recv(sockfd int, buf []byte, flags int, deadline time.Time) (in func (d *device) Close(sockfd int) error { if debugging(debugNetdev) { - fmt.Printf("[Close] sockfd: %d\r\n", sockfd) + print("[Close] sockfd: ", sockfd, "\r\n") } d.mu.Lock() @@ -765,7 +855,7 @@ func (d *device) Close(sockfd int) error { func (d *device) SetSockOpt(sockfd int, level int, opt int, value interface{}) error { if debugging(debugNetdev) { - fmt.Printf("[SetSockOpt] sockfd: %d\r\n", sockfd) + print("[SetSockOpt] sockfd: ", sockfd, "\r\n") } return netdev.ErrNotSupported From 8d1ea5109b07f2c1442856d6bcd0f9fe52708828 Mon Sep 17 00:00:00 2001 From: Frelsaren Date: Sun, 15 Nov 2026 11:02:25 +0100 Subject: [PATCH 5/5] examples/net: note stack size for the Arduino UNO R4 WiFi --- examples/net/ntpclient/main.go | 3 +++ examples/net/socket/main.go | 3 +++ examples/net/tcpclient/main.go | 3 +++ examples/net/tcpecho/main.go | 3 +++ examples/net/tlsclient/main.go | 3 +++ examples/net/webclient/main.go | 3 +++ 6 files changed, 18 insertions(+) diff --git a/examples/net/ntpclient/main.go b/examples/net/ntpclient/main.go index d37026b1b..6894bc630 100644 --- a/examples/net/ntpclient/main.go +++ b/examples/net/ntpclient/main.go @@ -2,6 +2,9 @@ // // It creates a UDP connection to request the current time and parse the // response from a NTP server. The system time is set to NTP time. +// +// Note: The Arduino UNO R4 WiFi hangs without output on the default stack size. +// Use the -stack-size=4KB command line option, see unor4wifi/README.md. //go:build ninafw || wioterminal || challenger_rp2040 || comboat_fw || arduino_uno_r4_wifi diff --git a/examples/net/socket/main.go b/examples/net/socket/main.go index b8af9d9d8..b8eeeb4b6 100644 --- a/examples/net/socket/main.go +++ b/examples/net/socket/main.go @@ -3,6 +3,9 @@ // You can open a server to accept connections from this program using: // // nc -lk 8080 +// +// Note: The Arduino UNO R4 WiFi hangs without output on the default stack size. +// Use the -stack-size=4KB command line option, see unor4wifi/README.md. //go:build ninafw || wioterminal || challenger_rp2040 || comboat_fw || arduino_uno_r4_wifi diff --git a/examples/net/tcpclient/main.go b/examples/net/tcpclient/main.go index ddff73c05..3261ded2c 100644 --- a/examples/net/tcpclient/main.go +++ b/examples/net/tcpclient/main.go @@ -4,6 +4,9 @@ // You can open a server to accept connections from this program using: // // nc -lk 8080 +// +// Note: The Arduino UNO R4 WiFi hangs without output on the default stack size. +// Use the -stack-size=4KB command line option, see unor4wifi/README.md. //go:build ninafw || wioterminal || challenger_rp2040 || comboat_fw || arduino_uno_r4_wifi diff --git a/examples/net/tcpecho/main.go b/examples/net/tcpecho/main.go index ca58c8d17..55588c61a 100644 --- a/examples/net/tcpecho/main.go +++ b/examples/net/tcpecho/main.go @@ -6,6 +6,9 @@ // Example test using nc as client to copy file: // // $ nc 10.0.0.2 8080 copy ; cmp file copy +// +// Note: The Arduino UNO R4 WiFi hangs without output on the default stack size. +// Use the -stack-size=4KB command line option, see unor4wifi/README.md. //go:build ninafw || wioterminal || arduino_uno_r4_wifi diff --git a/examples/net/tlsclient/main.go b/examples/net/tlsclient/main.go index 4db4478dc..c837e143b 100644 --- a/examples/net/tlsclient/main.go +++ b/examples/net/tlsclient/main.go @@ -4,6 +4,9 @@ // this confirms communication is indeed over HTTPS // // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security +// +// Note: The Arduino UNO R4 WiFi hangs without output on the default stack size. +// Use the -stack-size=4KB command line option, see unor4wifi/README.md. //go:build ninafw || wioterminal || comboat_fw || arduino_uno_r4_wifi diff --git a/examples/net/webclient/main.go b/examples/net/webclient/main.go index 8a8fc5d09..96ede530c 100644 --- a/examples/net/webclient/main.go +++ b/examples/net/webclient/main.go @@ -16,6 +16,9 @@ // http.ListenAndServe(":8080", nil) // } // --------------------------------------------------------------------------- +// +// Note: The Arduino UNO R4 WiFi hangs without output on the default stack size. +// Use the -stack-size=4KB command line option, see unor4wifi/README.md. //go:build ninafw || wioterminal || comboat_fw || arduino_uno_r4_wifi