Standard library · Hardware

hw.wifi

Wi-Fi for boards: scan, join a network, read the address and signal, TCP client sockets and a soft access point, with a simulated radio on a computer.

import hw.wifi

hw.wifi connects a board to a Wi-Fi network: scan for networks, join one with a password, ask for the address and signal, open a TCP connection and start a soft access point. It is the station-side API only and every call returns a plain value, so a failure is an answer you check, never an exception.

Where it runsWhat answers the calls
A computerA deterministic fake radio in memory. You fill the air with SimAddNetwork, SimSetPassword and SimSetReply, so programs and tests run anywhere.
An ESP32-C3 through ESP-IDFThe salam_rt_wifi_* hooks implemented in idf_radio.c on top of esp_wifi, esp_netif and lwip. See the ESP32-C3 section of docs/FREESTANDING.md. This path has not been run on a device.
A board without a radioThe runtime's default hooks answer "unsupported", so Init returns false and the program still links.

Things to know:

•

No hidden threads. Scan and Connect block until they finish or time out. Connect takes its timeout in milliseconds and polls the link itself.

•

Codes next to enums. Status and SecurityOf return the State and Security enums. StateCode, SecurityCode and the state_ and security_ constants give the same values as plain numbers for comparisons and printing.

•

Read fields with functions. Ssid, Bssid, Signal, Channel and SecurityOf read a Network; SocketOk and SocketId read a Socket.

•

You own received text. TcpReceive returns a heap string; free it with mem.Free(text as void*) when you are done with it.

•

Join before sockets. TcpOpen fails until Connect has succeeded.

Joining the strongest network

Call Init, scan, pick the entry with the best Signal and connect to it. This example fills the simulated air first, so it runs on a computer.

hw-wifi-guide-join.salam
Try it
import hw.wifi

func main:
    if not wifi.Init():
        println "no radio"
        ret 1
    end
    wifi.SimAddNetwork("Cafe", "aa:bb:cc:00:11:33", -70, 11, wifi.security_open)
    wifi.SimAddNetwork("Home", "aa:bb:cc:00:11:22", -48, 6, wifi.security_wpa2)
    wifi.SimSetPassword("Home", "secret123")
    mut best := ""
    mut best_signal := -127
    each n in wifi.Scan():
        if wifi.Signal(n) > best_signal:
            best = wifi.Ssid(n)
            best_signal = wifi.Signal(n)
        end
    end
    println "strongest:", best, best_signal
    if wifi.Connect(best, "secret123", 10000):
        println "connected with", wifi.Ip(), "at", wifi.Rssi(), "dBm"
    else:
        println "failed, state", wifi.StateCode()
    end
    ret 0
end
Output
strongest: Home -48
connected with 192.168.4.2 at -48 dBm

Talking to a server

After a successful Connect, TcpOpen gives a socket; send with TcpSend, read with TcpReceive and finish with TcpClose.

hw-wifi-guide-http.salam
Try it
import hw.wifi

func main:
    wifi.Init()
    wifi.SimAddNetwork("Home", "aa:bb:cc:00:11:22", -48, 6, wifi.security_open)
    wifi.SimSetReply("example.com", 80, "HTTP/1.0 200 OK")
    wifi.Connect("Home", "", 5000)
    sock := wifi.TcpOpen("example.com", 80)
    if not wifi.SocketOk(sock):
        println "cannot reach the server"
        ret 1
    end
    wifi.TcpSend(sock, "GET / HTTP/1.0\r\n\r\n")
    println "sent:", wifi.SimSent(sock).Len(), "bytes"
    println wifi.TcpReceive(sock, 2000)
    wifi.TcpClose(sock)
    ret 0
end
Output
sent: 18 bytes
HTTP/1.0 200 OK

Types

State

#
enum State

The state of the station link: Disconnected, Connecting, Connected or Failed.

NameTypeDescription
DisconnectedNot joined to any network.
ConnectingA join is in progress.
ConnectedJoined and holding an address.
FailedThe last join did not work: unknown network, wrong password or timeout.
hw-wifi-Connect.salam
Try it
import hw.wifi

func main:
    wifi.Init()
    wifi.SimAddNetwork("Home", "aa:bb:cc:00:11:22", -48, 6, wifi.security_wpa2)
    wifi.SimSetPassword("Home", "secret123")
    println wifi.Connect("Home", "wrong", 1000), wifi.StateCode() == wifi.state_failed
    println wifi.Connect("Home", "secret123", 1000), wifi.StateCode() == wifi.state_connected
    println wifi.IsConnected(), wifi.Ip(), wifi.Rssi(), wifi.Mac()
    wifi.SimSetIp("10.0.0.7")
    st := wifi.Status()
    println wifi.Ip(), st == wifi.Status()
    wifi.SimDrop()
    println wifi.IsConnected(), wifi.Ip(), wifi.Rssi()
    wifi.SimSetDelay(5000)
    println wifi.Connect("Home", "secret123", 1000), wifi.StateCode()
    wifi.SimSetDelay(0)
    wifi.Connect("Home", "secret123", 1000)
    wifi.Disconnect()
    println wifi.StateCode() == wifi.state_disconnected, wifi.state_connecting
end
Output
false true
true true
true 192.168.4.2 -48 02:00:00:00:00:01
10.0.0.7 true
false 0.0.0.0 0
false 3
true 1

Security

#
enum Security

The protection of a network: Open, Wep, Wpa, Wpa2 or Wpa3.

NameTypeDescription
OpenNo password.
WepThe old WEP scheme.
WpaWPA with a pre-shared key.
Wpa2WPA2 with a pre-shared key, the common home setup.
Wpa3WPA3, or a WPA2 and WPA3 mix.
hw-wifi-Scan.salam
Try it
import hw.wifi

func main:
    println wifi.Init(), wifi.Ready(), wifi.max_scan
    wifi.SimAddNetwork("Home", "aa:bb:cc:00:11:22", -48, 6, wifi.security_wpa2)
    wifi.SimAddNetwork("Cafe", "aa:bb:cc:00:11:33", -70, 11, wifi.security_open)
    each n in wifi.Scan():
        println wifi.Ssid(n), wifi.Bssid(n), wifi.Signal(n), wifi.Channel(n), wifi.SecurityCode(n)
    end
    first := wifi.Scan().Get(0)
    println wifi.Ssid(first), wifi.SecurityCode(first), wifi.SecurityOf(first) == wifi.SecurityOf(first)
    println wifi.security_open, wifi.security_wep, wifi.security_wpa, wifi.security_wpa2, wifi.security_wpa3
    wifi.SimReset()
    println wifi.Ready(), wifi.Scan().Len()
end
Output
true true 32
Home aa:bb:cc:00:11:22 -48 6 3
Cafe aa:bb:cc:00:11:33 -70 11 0
Home 3 true
0 1 2 3 4
false 0

Network

#
struct Network

One access point found by a scan. Read its parts with Ssid, Bssid, Signal, Channel and SecurityOf.

NameTypeDescription
ssidstr = ""The network name.
bssidstr = ""The hardware address of the access point as six hex pairs, such as aa:bb:cc:00:11:22.
rssiint = 0The signal strength in dBm; closer to 0 is stronger (-40 is strong, -90 is barely usable).
channelint = 0The Wi-Fi channel the access point uses.
securitySecurityHow the network is protected, as a Security value.

The example for this item is shown with the ones above: hw-wifi-Scan.salam

Socket

#
struct Socket

A TCP connection made through the radio. Pass it by value; the id and ok fields are read with SocketId and SocketOk.

NameTypeDescription
idint = -1The connection number, or -1 when the open failed.
okbool = falseTrue when the connection opened.
hw-wifi-Tcp.salam
Try it
import hw.wifi

func main:
    wifi.Init()
    wifi.SimAddNetwork("Home", "aa:bb:cc:00:11:22", -48, 6, wifi.security_open)
    println wifi.SocketOk(wifi.TcpOpen("example.com", 80))
    wifi.Connect("Home", "", 1000)
    wifi.SimSetReply("example.com", 80, "HTTP/1.0 200 OK")
    s := wifi.TcpOpen("example.com", 80)
    println wifi.SocketOk(s), wifi.SocketId(s)
    println wifi.TcpSend(s, "GET / HTTP/1.0"), wifi.SimSent(s)
    println wifi.TcpReceive(s, 200), wifi.TcpReceive(s, 200).Len()
    wifi.TcpClose(s)
    println wifi.TcpSend(s, "late"), wifi.TcpReceive(s, 10).Len()
end
Output
false
true 1
true GET / HTTP/1.0
HTTP/1.0 200 OK 0
false 0

Constants and variables

max_scan

#
const max_scan: i32 = 32

The most networks one Scan returns, 32.

The example for this item is shown with the ones above: hw-wifi-Scan.salam

state_disconnected

#
const state_disconnected: i32 = 0

The number 0 for Disconnected; StateCode returns these numbers.

The example for this item is shown with the ones above: hw-wifi-Connect.salam

state_connecting

#
const state_connecting: i32 = 1

The number 1 for Connecting.

The example for this item is shown with the ones above: hw-wifi-Connect.salam

state_connected

#
const state_connected: i32 = 2

The number 2 for Connected.

The example for this item is shown with the ones above: hw-wifi-Connect.salam

state_failed

#
const state_failed: i32 = 3

The number 3 for Failed.

The example for this item is shown with the ones above: hw-wifi-Connect.salam

security_open

#
const security_open: i32 = 0

The number 0 for an open network; SimAddNetwork and SecurityCode use these codes.

The example for this item is shown with the ones above: hw-wifi-Scan.salam

security_wep

#
const security_wep: i32 = 1

The number 1 for WEP.

The example for this item is shown with the ones above: hw-wifi-Scan.salam

security_wpa

#
const security_wpa: i32 = 2

The number 2 for WPA.

The example for this item is shown with the ones above: hw-wifi-Scan.salam

security_wpa2

#
const security_wpa2: i32 = 3

The number 3 for WPA2.

The example for this item is shown with the ones above: hw-wifi-Scan.salam

security_wpa3

#
const security_wpa3: i32 = 4

The number 4 for WPA3.

The example for this item is shown with the ones above: hw-wifi-Scan.salam

Functions

Init

#
func Init(): bool

Starts the Wi-Fi station. Returns true when the radio is ready and false on a board with no radio. Calling it again is harmless.

The example for this item is shown with the ones above: hw-wifi-Scan.salam

Ready

#
func Ready(): bool

True after a successful Init. Every other call returns an empty or false answer until then.

The example for this item is shown with the ones above: hw-wifi-Scan.salam

Scan

#
func Scan(): Vector<Network>

Looks for networks and returns up to max_scan of them as a Vector of Network. The result is empty before Init. On a board the call blocks until the scan is done.

The example for this item is shown with the ones above: hw-wifi-Scan.salam

Connect

#
func Connect(ssid: str, password: str, timeout_ms: int): bool

Joins a network and waits up to timeout_ms milliseconds for an address. Returns true when connected. On a failure the state is Failed and the radio is left disconnected. An open network ignores the password.

The example for this item is shown with the ones above: hw-wifi-Connect.salam

Disconnect

#
func Disconnect()

Leaves the network. Safe to call when not connected.

The example for this item is shown with the ones above: hw-wifi-Connect.salam

Status

#
func Status(): State

The current State of the link.

The example for this item is shown with the ones above: hw-wifi-Connect.salam

IsConnected

#
func IsConnected(): bool

True when Status is Connected.

The example for this item is shown with the ones above: hw-wifi-Connect.salam

Ip

#
func Ip(): str

The IPv4 address as text such as 192.168.4.2, or 0.0.0.0 when not connected.

The example for this item is shown with the ones above: hw-wifi-Connect.salam

Rssi

#
func Rssi(): int

The signal strength of the joined network in dBm, or 0 when not connected.

The example for this item is shown with the ones above: hw-wifi-Connect.salam

Mac

#
func Mac(): str

The hardware address of the station as six hex pairs.

The example for this item is shown with the ones above: hw-wifi-Connect.salam

StartAccessPoint

#
func StartAccessPoint(ssid: str, password: str, channel: int): bool

Starts a soft access point other devices can join. The name is 1 to 32 bytes, the password is empty (open) or 8 or more characters, and the channel is 1 to 13. Returns true on success.

hw-wifi-AccessPoint.salam
Try it
import hw.wifi

func main:
    println wifi.StartAccessPoint("Salam", "password1", 6)
    wifi.Init()
    println wifi.StartAccessPoint("Salam", "password1", 6), wifi.SimAccessPoint()
    println wifi.StartAccessPoint("Salam", "short", 6), wifi.StartAccessPoint("Salam", "password1", 14)
    println wifi.StartAccessPoint("Guests", "", 1), wifi.SimAccessPoint()
end
Output
false
true Salam
false false
true Guests

TcpOpen

#
func TcpOpen(host: str, port: int): Socket

Opens a TCP connection to a host name or address and a port from 1 to 65535. The station must be connected. A failure returns a Socket for which SocketOk is false.

The example for this item is shown with the ones above: hw-wifi-Tcp.salam

TcpSend

#
func TcpSend(s: Socket, data: str): bool

Sends all of a string and returns true when it was sent. False on a closed or failed socket.

The example for this item is shown with the ones above: hw-wifi-Tcp.salam

TcpReceive

#
func TcpReceive(s: Socket, timeout_ms: int): str

Waits up to timeout_ms for data and returns what has arrived, up to 1024 bytes, or an empty string. The result is a heap string.

The example for this item is shown with the ones above: hw-wifi-Tcp.salam

TcpClose

#
func TcpClose(s: Socket)

Closes the connection. Safe to call twice.

The example for this item is shown with the ones above: hw-wifi-Tcp.salam

Ssid

#
func Ssid(n: Network): str

The name of a scanned network.

The example for this item is shown with the ones above: hw-wifi-Scan.salam

Bssid

#
func Bssid(n: Network): str

The hardware address of a scanned network.

The example for this item is shown with the ones above: hw-wifi-Scan.salam

Signal

#
func Signal(n: Network): int

The signal strength of a scanned network in dBm.

The example for this item is shown with the ones above: hw-wifi-Scan.salam

Channel

#
func Channel(n: Network): int

The channel of a scanned network.

The example for this item is shown with the ones above: hw-wifi-Scan.salam

SecurityOf

#
func SecurityOf(n: Network): Security

The Security value of a scanned network.

The example for this item is shown with the ones above: hw-wifi-Scan.salam

SecurityCode

#
func SecurityCode(n: Network): int

The security of a scanned network as a number, 0 for open up to 4 for WPA3 (see the security_ constants such as security_open).

The example for this item is shown with the ones above: hw-wifi-Scan.salam

StateCode

#
func StateCode(): int

The current state as a number, 0 to 3 (see the state_ constants such as state_connected).

The example for this item is shown with the ones above: hw-wifi-Connect.salam

SocketOk

#
func SocketOk(s: Socket): bool

True when the socket opened and has not been closed by you.

The example for this item is shown with the ones above: hw-wifi-Tcp.salam

SocketId

#
func SocketId(s: Socket): int

The connection number of a socket.

The example for this item is shown with the ones above: hw-wifi-Tcp.salam

SimReset

#
func SimReset()

Forgets everything the simulation holds: networks, passwords, sockets, the access point and the Init state. Does nothing on a board.

The example for this item is shown with the ones above: hw-wifi-Scan.salam

SimAddNetwork

#
func SimAddNetwork(ssid: str, bssid: str, rssi: int, channel: int, security: int)

Adds a fake network to the simulated air. The security argument is one of the security constants such as security_wpa2.

The example for this item is shown with the ones above: hw-wifi-Scan.salam

SimSetPassword

#
func SimSetPassword(ssid: str, password: str)

Sets the password the simulation expects for a network. Non-open networks without one refuse every join.

The example for this item is shown with the ones above: hw-wifi-Connect.salam

SimSetIp

#
func SimSetIp(ip: str)

Sets the address the simulation hands out on the next join.

The example for this item is shown with the ones above: hw-wifi-Connect.salam

SimSetDelay

#
func SimSetDelay(ms: int)

Sets how many milliseconds the simulated join takes. A Connect with a smaller timeout fails.

The example for this item is shown with the ones above: hw-wifi-Connect.salam

SimDrop

#
func SimDrop()

Drops the simulated link, as if the access point went away.

The example for this item is shown with the ones above: hw-wifi-Connect.salam

SimSetReply

#
func SimSetReply(host: str, port: int, data: str)

Sets the bytes a simulated server at host and port sends right after a connection opens.

The example for this item is shown with the ones above: hw-wifi-Tcp.salam

SimSent

#
func SimSent(s: Socket): str

Everything the program has sent on a simulated socket so far.

The example for this item is shown with the ones above: hw-wifi-Tcp.salam

SimAccessPoint

#
func SimAccessPoint(): str

The name of the access point started in the simulation, or an empty string.

The example for this item is shown with the ones above: hw-wifi-AccessPoint.salam