WiFi + HTTP
Connect to a WiFi network and make an HTTP request to a JSON API. Uses the wifi and http/request APIs.
Hardware
- Any ESP32 board with WiFi
- USB cable
- A WiFi network with internet access
Setup
Set your WiFi credentials as environment variables:
pnpm mikro env set WIFI_SSID YourNetworkName --no-secret
pnpm mikro env set WIFI_PASSPHRASEnpx mikro env set WIFI_SSID YourNetworkName --no-secret
npx mikro env set WIFI_PASSPHRASEyarn mikro env set WIFI_SSID YourNetworkName --no-secret
yarn mikro env set WIFI_PASSPHRASEbunx mikro env set WIFI_SSID YourNetworkName --no-secret
bunx mikro env set WIFI_PASSPHRASECode
import {env} from 'mikro/env'
import {request} from 'mikro/http/request'
import {memoryUsage} from 'mikro/sys'
import {wifi} from 'mikro/wifi'
const ssid = env.require('WIFI_SSID')
const passphrase = env.require('WIFI_PASSPHRASE')
// Connect to WiFi
console.log(`Connecting to ${ssid}...`)
const connectResult = await wifi.connect({ssid, passphrase})
if (!connectResult.ok) {
console.error('WiFi connect failed:', connectResult.error)
} else {
console.log('Connected! IP: %s', connectResult.value.ip)
// Request JSON from an API
const result = await request('https://httpbingo.org/json')
if (result.ok) {
if (!result.value.ok) {
console.error(`HTTP error: ${result.value.status}`)
} else {
const data = await result.value.json()
if (!data.ok) {
console.error('Body decode failed:', data.error)
} else {
console.log('Fetched: %o', data.value)
}
}
} else {
console.error('Request failed:', result.error)
}
}
const mem = memoryUsage()
console.log('free heap: %dKB', (mem.heapTotal - mem.heapUsed) / 1000)Walkthrough
Country code.
wifi.countrymust be set before connecting. This configures the regulatory domain for your region's WiFi channels.Environment variables. WiFi credentials come from
env.require(), which panics with a clear message if a variable is missing. Environment variables are stored in NVS on device. Set them withmikro env set.Connect.
wifi.connect()returns aPromise<Result>. The outerResulttells you if the connection succeeded; thevaluecontains your IP address.Request.
request()also returns aPromise<Result>. Two levels of error checking:result.ok: did the network request succeed at all?result.value.ok: was the HTTP status in the 2xx range?
Memory. Prints free heap after the request completes, useful for tracking memory on constrained devices.
Create project
pnpm create mikro --template wifi-fetchnpm create mikro -- --template wifi-fetchyarn create mikro --template wifi-fetchbun create mikro --template wifi-fetchRun it
pnpm install
pnpm mikro flash # only needed once per board
pnpm mikro devnpm install
npx mikro flash # only needed once per board
npx mikro devyarn install
yarn mikro flash # only needed once per board
yarn mikro devbun install
bunx mikro flash # only needed once per board
bunx mikro devThe console output shows the WiFi connection, the fetched JSON data, and memory usage.