API Network and WiFi
WiFi connectivity and HTTP client.
picocalc.wifi
Section titled “picocalc.wifi”WiFi connectivity functions (Pico 2W only).
Functions
Section titled “Functions”picocalc.wifi.isAvailable()
Section titled “picocalc.wifi.isAvailable()”Checks if WiFi hardware is present.
- Parameters: None
- Returns: (boolean)
trueif WiFi is available (Pico 2W),falseotherwise
if picocalc.wifi.isAvailable() then picocalc.wifi.connect("MySSID", "password")endpicocalc.wifi.connect(ssid [, password])
Section titled “picocalc.wifi.connect(ssid [, password])”Connects to a WiFi network (non-blocking).
- Parameters:
ssid(string): Network SSIDpassword(string, optional): Network password (omit for open networks)
- Returns: None
picocalc.wifi.connect("MyWiFi", "password123")picocalc.wifi.disconnect()
Section titled “picocalc.wifi.disconnect()”Disconnects from the current WiFi network.
- Parameters: None
- Returns: None
picocalc.wifi.getStatus()
Section titled “picocalc.wifi.getStatus()”Returns the current WiFi connection status.
- Parameters: None
- Returns: (number) Status code (see constants below)
if picocalc.wifi.getStatus() == picocalc.wifi.STATUS_CONNECTED then print("Connected! IP: " .. picocalc.wifi.getIP())endpicocalc.wifi.getIP()
Section titled “picocalc.wifi.getIP()”Returns the current IP address as a string.
- Parameters: None
- Returns: (string or nil) IP address (e.g.,
"192.168.1.100"), ornilif not connected
picocalc.wifi.getSSID()
Section titled “picocalc.wifi.getSSID()”Returns the SSID of the current connection.
- Parameters: None
- Returns: (string or nil) SSID, or
nilif not connected
picocalc.wifi.hasInternet()
Section titled “picocalc.wifi.hasInternet()”Check if the device has working internet connectivity (beyond just WiFi connection).
- Parameters: None
- Returns: (boolean)
trueif internet is reachable
if picocalc.wifi.hasInternet() then -- Safe to make external requestsendWiFi Status Constants
Section titled “WiFi Status Constants”| Constant | Description |
|---|---|
picocalc.wifi.STATUS_DISCONNECTED | Not connected |
picocalc.wifi.STATUS_CONNECTING | Connection in progress |
picocalc.wifi.STATUS_CONNECTED | Connected successfully |
picocalc.wifi.STATUS_FAILED | Connection failed |
picocalc.wifi.STATUS_ONLINE | Internet connectivity confirmed |
picocalc.network
Section titled “picocalc.network”HTTP client for making network requests. Requires WiFi to be connected first. Up to 8 simultaneous connections are supported. HTTPS (SSL/TLS) is supported via mbedTLS and verifies the server
certificate by default (chain to the OS root bundle, validity dates, host
name). Failures read "TLS: certificate not trusted …", "… expired" or
"… does not match the host name". Because validity needs the wall clock, a
verifying connection is refused with an error starting "clock not set" until
SNTP has set the time; retry a few seconds later.
HTTP connections are objects with method syntax (conn:get(...), conn:read(), etc.). Callbacks are fired automatically — you do not need to poll manually.
picocalc.network functions
Section titled “picocalc.network functions”picocalc.network.getStatus()
Section titled “picocalc.network.getStatus()”Returns the current network status.
- Parameters: None
- Returns: (number) One of the
kStatus*constants
if picocalc.network.getStatus() == picocalc.network.kStatusConnected then -- Safe to make HTTP requestsendpicocalc.network.setEnabled(flag [, callback])
Section titled “picocalc.network.setEnabled(flag [, callback])”Enables or disables WiFi. The optional callback is fired synchronously with nil (reserved for a future async result).
- Parameters:
flag(boolean):trueto enable,falseto disablecallback(function, optional): Called synchronously withnil
- Returns: None
picocalc.network.setEnabled(true, function() print("WiFi enable requested")end)picocalc.network.isHwDisconnected()
Section titled “picocalc.network.isHwDisconnected()”Check if the WiFi hardware has been disabled (e.g. by video playback).
- Parameters: None
- Returns: (boolean)
trueif the WiFi hardware is disconnected
if picocalc.network.isHwDisconnected() then print("WiFi hardware is off")endNetwork Status Constants
Section titled “Network Status Constants”| Constant | Value | Description |
|---|---|---|
picocalc.network.kStatusNotConnected | 0 | WiFi present but not connected |
picocalc.network.kStatusConnected | 1 | Connected and ready |
picocalc.network.kStatusNotAvailable | 2 | No WiFi hardware, or connection failed |
picocalc.network.http — HTTP Connection Objects
Section titled “picocalc.network.http — HTTP Connection Objects”picocalc.network.http.new(server [, port [, usessl]])
Section titled “picocalc.network.http.new(server [, port [, usessl]])”Creates a new HTTP/HTTPS connection object. Does not connect immediately — call conn:get() or conn:post() to start a request.
- Parameters:
server(string): Hostname (e.g.,"api.example.com")port(number, optional): TCP port. Defaults to80for HTTP,443for HTTPS.usessl(boolean, optional):trueto use HTTPS/TLS. Defaults tofalse.
- Returns: (userdata) Connection object, or
nil, errstrif the connection pool is full
-- Plain HTTPlocal conn = picocalc.network.http.new("api.example.com")
-- HTTPS (port 443 is the default when usessl=true)local conn = picocalc.network.http.new("api.example.com", 443, true)
if not conn then print("Pool full")endHTTP Connection Methods
Section titled “HTTP Connection Methods”All methods are called on the connection object with colon syntax.
conn:get(path [, headers])
Section titled “conn:get(path [, headers])”Issues an HTTP GET request.
Returns false (“a request is already in progress”) unless the connection is idle or its last request finished. POST bodies are binary-safe.
- Parameters:
path(string): URL path (e.g.,"/api/data")headers(string or table, optional): Extra headers. Can be a raw"Key: Value "string, a flat array of"Key: Value"strings, or a{key=value}table.
- Returns: (boolean)
trueif request started, orfalse, errstron immediate failure
conn:get("/api/data")conn:post(path [, headers], data)
Section titled “conn:post(path [, headers], data)”Issues an HTTP POST request.
Returns false (“a request is already in progress”) unless the connection is idle or its last request finished. POST bodies are binary-safe.
- Parameters:
path(string): URL pathheaders(string or table, optional): Extra headers (omit to pass data as third arg)data(string): Request body
- Returns: (boolean)
trueif request started, orfalse, errstron immediate failure
conn:post("/submit", '{"value":42}')-- or with headers:conn:post("/submit", {["Content-Type"] = "application/json"}, '{"value":42}')conn:close()
Section titled “conn:close()”Closes the connection and frees the connection pool slot. The object is unusable afterwards.
- Returns: None
conn:setKeepAlive(flag)
Section titled “conn:setKeepAlive(flag)”Enables HTTP keep-alive (Connection: keep-alive). Must be called before get/post.
- Parameters:
flag(boolean)
- Returns: None
conn:setByteRange(from, to)
Section titled “conn:setByteRange(from, to)”Adds a Range: bytes=from-to header to the next request (for partial content / resumable downloads). Must be called before get/post.
- Parameters:
from(number): Start byte (inclusive)to(number): End byte (inclusive)
- Returns: None
conn:setConnectTimeout(seconds)
Section titled “conn:setConnectTimeout(seconds)”Sets the TCP connection timeout. Default is 10 seconds.
- Parameters:
seconds(number): Timeout in seconds (fractions allowed)
- Returns: None
conn:setReadTimeout(seconds)
Section titled “conn:setReadTimeout(seconds)”Sets the timeout waiting for response data after connecting. Default is 30 seconds.
- Parameters:
seconds(number): Timeout in seconds (fractions allowed)
- Returns: None
conn:setReadBufferSize(bytes)
Section titled “conn:setReadBufferSize(bytes)”Resizes the receive ring buffer. Must be called before get/post. Defaults to 4096 bytes. Maximum is 2097152 bytes (2 MiB).
- Parameters:
bytes(number): Buffer size in bytes
- Returns: None
conn:setInsecure(flag)
Section titled “conn:setInsecure(flag)”Before get/post: true skips certificate verification and the clock check
for this connection only (self-signed development servers). Logs a warning.
conn:getError()
Section titled “conn:getError()”Returns the last error string, if any.
- Returns: (string or nil) Error description, or
nilif no error
local err = conn:getError()if err then print("HTTP error: " .. err) endconn:getProgress()
Section titled “conn:getProgress()”Returns download progress.
- Returns: (number, number)
bytesReceived, totalBytes—totalBytesis-1if unknown (noContent-Lengthheader or chunked encoding)
local received, total = conn:getProgress()if total > 0 then print(string.format("%d%%", received * 100 // total))endconn:getBytesAvailable()
Section titled “conn:getBytesAvailable()”Returns the number of bytes currently available to read from the receive buffer.
- Returns: (number) Bytes available
conn:read([length])
Section titled “conn:read([length])”Reads data from the receive buffer.
- Parameters:
length(number, optional): Maximum bytes to read. Defaults to all available. Capped at 131072 bytes per call.
- Returns: (string or nil) Data, or
nilif nothing is available yet
local chunk = conn:read()if chunk then buffer = buffer .. chunk endconn:getResponseStatus()
Section titled “conn:getResponseStatus()”Returns the HTTP response status code.
- Returns: (number or nil) e.g.
200,404—nilif headers not yet received
conn:getResponseHeaders()
Section titled “conn:getResponseHeaders()”Returns the response headers as a key-value table (lowercase keys).
- Returns: (table or nil)
{["content-type"]="text/json", ...}—nilif headers not yet received
local hdrs = conn:getResponseHeaders()if hdrs then print("Content-Type: " .. (hdrs["content-type"] or "unknown"))endResponses
Section titled “Responses”Content-Length, chunked and close-delimited bodies are supported, with keep-alive reuse. A body cut short (reset, early close, out of memory) fails; it never reports complete. Callbacks never nest: a callback that sleeps leaves later events for the outer call. The read timeout runs from the moment the request is sent.
Callbacks
Section titled “Callbacks”Callbacks are fired automatically from within the app’s execution loop — no polling needed.
conn:setRequestCallback(fn)
Section titled “conn:setRequestCallback(fn)”Called each time new body data arrives. fn receives no arguments; use conn:read() to consume data.
conn:setHeadersReadCallback(fn)
Section titled “conn:setHeadersReadCallback(fn)”Called once when all response headers have been received. Use conn:getResponseStatus() and conn:getResponseHeaders() inside this callback.
conn:setRequestCompleteCallback(fn)
Section titled “conn:setRequestCompleteCallback(fn)”Called when the response body is fully received.
conn:setConnectionClosedCallback(fn)
Section titled “conn:setConnectionClosedCallback(fn)”Called when the connection closes, either cleanly or due to an error. Check conn:getError() to distinguish.
HTTP Example
Section titled “HTTP Example”-- Check WiFi is upif picocalc.network.getStatus() ~= picocalc.network.kStatusConnected then print("Not connected") returnend
local conn = picocalc.network.http.new("httpbin.org")local body = ""
conn:setHeadersReadCallback(function() print("Status: " .. conn:getResponseStatus())end)
conn:setRequestCallback(function() local chunk = conn:read() if chunk then body = body .. chunk endend)
conn:setRequestCompleteCallback(function() print("Done. Body length: " .. #body) conn:close()end)
conn:setConnectionClosedCallback(function() local err = conn:getError() if err then print("Error: " .. err) endend)
conn:get("/get")
-- Keep looping until the request completeslocal done = falseconn:setRequestCompleteCallback(function() print("Done. Body length: " .. #body) done = trueend)
while not done do picocalc.input.update() if picocalc.input.getButtonsPressed() & picocalc.input.BTN_ESC ~= 0 then conn:close() return end picocalc.sys.sleep(16)endconn:close()