1// Wi-Fi lab W2: phone control.2// uv run pio run -d labs/wifi-lab-w2 -e wifi-lab-w2 -t upload variation 1: control on your Wi-Fi3// uv run pio run -d labs/wifi-lab-w2 -e wifi-lab-w2-remote -t upload variation 2: also from anywhere, through your4// dashboard server and a tunnel (remote.h)5// Everything from W1 (scanner views, join, status) plus a web server: REST API + WebSocket,6// a phone page at http://bench.local, a set-up network for joining without a cable, firmware7// updates over HTTP, and the desktop dashboard in esp-labs/apps/dashboard.8//9// Wiring: the screen from lesson 03. The push button on GPIO 5 is optional: it does exactly what10// BOOT does, and with nothing wired its internal pull-up keeps it quiet.11//12// Views: networks · channels · radar · status · message13// Button or BOOT: click = next view · double-click = scan now · long press = auto-scan on/off14// Serial: scan | view <1-5> | auto on|off | join <n> | forget | reconnect | status | tz <TZ> |15// ping [ip] | setup | token | token new | relay [url|off] | help16//17// Web: http://bench.local (phone page), /api (REST), /ws (live). See web_api.h.18// The saved network is shared with W1 (same NVS namespace), so switching labs keeps it.19#include <Arduino.h>20#include <ArduinoJson.h>21#include <WiFi.h>22#include <esp_heap_caps.h>23 24#include "api_rules.h"25#include "api_token.h"26#include "button.h"27#include "color.h"28#include "commands.h"29#include "connection.h"30#include "display.h"31#include "pinger.h"32#include "pins.h"33#include "remote.h"34#include "scanner.h"35#include "setup_portal.h"36#include "views.h"37#include "web_api.h"38#include "web_views.h"39 40namespace {41 42constexpr uint32_t kAutoScanMs = 10'000; // pause between automatic scans when not joined43// When joined, every scan takes the radio off the router's channel for ~3 s, and web requests44// arriving meanwhile get lost. So scan much less often once we're on a network.45constexpr uint32_t kAutoScanJoinedMs = 60'000;46constexpr uint32_t kPageFlipMs = 4'000; // list view: next page after this long47constexpr uint32_t kStatusPushMs = 1'000; // live status to web clients48constexpr uint32_t kPortalAfterFailMs = 60'000;49constexpr uint32_t kPortalCloseAfterJoinMs = 30'000;50constexpr int kStatusView = 3, kMessageView = 4;51const char *const kViewNames[] = {"networks", "channels", "radar", "status", "message"};52constexpr int kViews = sizeof(kViewNames) / sizeof(kViewNames[0]);53constexpr const char *kFirmware = "wifi-lab-w2";54 55Display display;56Scanner scanner;57Connection connection;58SetupPortal portal;59ApiToken token;60Pinger pinger;61CommandQueue commands;62ApiRules rules(commands, connection, kViewNames, kViews);63WebApi web(rules, commands, token);64Button external(PIN_BUTTON, "button");65Button boot(PIN_BOOT_BTN, "BOOT");66 67struct {68 int view = 0;69 int page = 0;70 bool autoScan = true;71 uint8_t backlight = 255;72 uint8_t r = 0, g = 0, b = 0; // on-board RGB LED73 String message;74 uint32_t pageFlippedAt = 0;75 String pendingSsid; // set by `join <n>`: the next serial line is the password76 bool awaitingPassword = false;77 uint32_t rebootAt = 0; // set by a reboot command; 0 = none78 float tempC = NAN;79} state;80 81// ---- JSON snapshots for the web --------------------------------------------------------82 83const char *wifiStateName(Connection::State s) {84 switch (s) {85 case Connection::State::Connected: return "connected";86 case Connection::State::Connecting: return "connecting";87 case Connection::State::Failed: return "failed";88 default: return "not-set-up";89 }90}91 92String statusJson() {93 JsonDocument doc;94 doc["firmware"] = kFirmware;95 doc["uptimeS"] = millis() / 1000;96 doc["heapFree"] = ESP.getFreeHeap();97 doc["psramFree"] = ESP.getFreePsram();98 if (!isnan(state.tempC)) doc["tempC"] = serialized(String(state.tempC, 1));99 doc["clients"] = web.clients();100 101 JsonObject wifi = doc["wifi"].to<JsonObject>();102 wifi["state"] = wifiStateName(connection.state());103 wifi["ssid"] = connection.ssid();104 wifi["hostname"] = String(Connection::kHostname) + ".local";105 if (connection.state() == Connection::State::Connected) {106 wifi["ip"] = WiFi.localIP().toString();107 wifi["rssi"] = WiFi.RSSI();108 wifi["channel"] = WiFi.channel();109 }110 wifi["reason"] = Connection::reasonHint(connection.lastReason());111 112 JsonObject link = doc["remote"].to<JsonObject>();113 link["state"] = remote::stateName(remote::state());114 115 JsonObject setup = doc["setup"].to<JsonObject>();116 setup["active"] = portal.active();117 setup["ssid"] = SetupPortal::kSsid; // the password is only on the screen, never in the API118 119 JsonObject screen = doc["screen"].to<JsonObject>();120 screen["view"] = kViewNames[state.view];121 JsonArray names = screen["views"].to<JsonArray>();122 for (const char *n : kViewNames) names.add(n);123 screen["autoScan"] = state.autoScan;124 screen["backlight"] = state.backlight;125 screen["message"] = state.message;126 127 JsonObject led = doc["led"].to<JsonObject>();128 led["r"] = state.r, led["g"] = state.g, led["b"] = state.b;129 130 JsonObject scan = doc["scan"].to<JsonObject>();131 scan["running"] = scanner.scanning();132 scan["count"] = scanner.networks().size();133 scan["durationMs"] = scanner.lastScanMs();134 135 String out;136 serializeJson(doc, out);137 return out;138}139 140String networksJson() {141 JsonDocument doc;142 doc["scans"] = scanner.scans();143 doc["durationMs"] = scanner.lastScanMs();144 JsonArray list = doc["networks"].to<JsonArray>();145 for (const ScanResult &n : scanner.networks()) {146 JsonObject o = list.add<JsonObject>();147 o["ssid"] = n.ssid; // hardware addresses (BSSIDs) stay off the web on purpose148 o["rssi"] = n.rssi;149 o["channel"] = n.channel;150 o["auth"] = authName(n.auth);151 }152 String out;153 serializeJson(doc, out);154 return out;155}156 157void pushEvent(const char *source, const char *gesture) {158 JsonDocument doc;159 doc["source"] = source;160 doc["gesture"] = gesture;161 doc["uptimeS"] = millis() / 1000;162 String out;163 serializeJson(doc, out);164 web.publishEvent(out);165 remote::publish("event", out);166}167 168// ---- Serial output ---------------------------------------------------------------------169 170void printResults() {171 const auto &nets = scanner.networks();172 Serial.printf("\n--- scan %lu: %u networks in %lu ms ---\n", static_cast<unsigned long>(scanner.scans()),173 unsigned(nets.size()), static_cast<unsigned long>(scanner.lastScanMs()));174 Serial.println(" # dBm ch security bssid ssid");175 for (size_t i = 0; i < nets.size(); i++) {176 const ScanResult &n = nets[i];177 Serial.printf("%2u %4ld %2u %-10s %s %s\n", unsigned(i + 1), static_cast<long>(n.rssi), n.channel,178 authName(n.auth), n.bssid.c_str(), n.ssid.isEmpty() ? "(hidden)" : n.ssid.c_str());179 }180 Serial.println("To join one: join <#>");181}182 183void printRelay() {184 const String url = remote::url();185 Serial.printf("Remote link: %s%s%s\n", remote::stateName(remote::state()), url.isEmpty() ? "" : " | ", url.c_str());186}187 188void printStatus() {189 using State = Connection::State;190 switch (connection.state()) {191 case State::NoCredentials: Serial.println("Not joined. Scan, then: join <#>"); break;192 case State::Connecting: Serial.printf("Joining '%s'...\n", connection.ssid().c_str()); break;193 case State::Failed: Serial.printf("Could not join '%s': %s\n", connection.ssid().c_str(), Connection::reasonHint(connection.lastReason())); break;194 case State::Connected:195 Serial.printf("Joined '%s' | IP %s | http://%s.local | ch %d | %ld dBm | time %s | web clients %u\n",196 connection.ssid().c_str(), WiFi.localIP().toString().c_str(), Connection::kHostname,197 static_cast<int>(WiFi.channel()), static_cast<long>(WiFi.RSSI()),198 connection.timeSynced() ? "synced" : "not yet", unsigned(web.clients()));199 break;200 }201 if (portal.active()) Serial.printf("Set-up network '%s' is open (password on the screen)\n", SetupPortal::kSsid);202 if (remote::builtIn()) printRelay();203}204 205void printHelp() {206 Serial.println();207 Serial.println("Commands: scan | view <1-5> | auto on|off | join <#> | forget | reconnect | status | tz <TZ>");208 Serial.println(" ping (the router) | ping <ip> (e.g. your computer: can the board reach it?)");209 Serial.println(" setup (open the set-up network) | token (show admin token) | token new | help");210 if (remote::builtIn()) Serial.println(" relay (show) | relay wss://<tunnel host> (save + connect) | relay off");211 Serial.println("Button (GPIO 5) or BOOT: click = next view, double-click = scan now, long press = auto-scan on/off");212}213 214// ---- Actions (shared by the button, serial and web) -------------------------------------215 216uint32_t autoScanInterval() {217 return connection.state() == Connection::State::Connected ? kAutoScanJoinedMs : kAutoScanMs;218}219 220void scanNow(const char *why) {221 if (scanner.start()) log_i("scan started (%s)", why);222}223 224void setView(int v) {225 state.view = (v % kViews + kViews) % kViews;226 state.page = 0;227 state.pageFlippedAt = millis();228 log_i("view %d: %s", state.view + 1, kViewNames[state.view]);229}230 231void setAuto(bool on) {232 state.autoScan = on;233 log_i("auto-scan %s", on ? "on" : "off");234}235 236void setLed(uint8_t r, uint8_t g, uint8_t b) {237 state.r = r, state.g = g, state.b = b;238 rgbLedWrite(PIN_RGB, r, g, b);239}240 241void applyCommand(const Command &c) {242 using T = Command::Type;243 switch (c.type) {244 case T::SetView: setView(c.value); break;245 case T::Scan: scanNow("web"); break;246 case T::SetAutoScan: setAuto(c.value != 0); break;247 case T::SetBacklight:248 state.backlight = uint8_t(c.value);249 display.setBacklight(state.backlight);250 log_i("backlight %u", state.backlight);251 break;252 case T::SetLed: setLed(c.r, c.g, c.b); break;253 case T::ShowMessage:254 state.message = c.text;255 setView(kMessageView);256 log_i("message from the web (%u characters)", unsigned(state.message.length()));257 break;258 case T::SaveWifi:259 connection.save(c.text, c.secret);260 setView(kStatusView);261 break;262 case T::ForgetWifi: connection.forget(); break;263 case T::Reboot:264 log_i("reboot requested");265 state.rebootAt = millis() + 800; // let the HTTP answer go out first266 break;267 }268}269 270void startJoin(long number) {271 const auto &nets = scanner.networks();272 if (number < 1 || number > long(nets.size())) {273 log_w("join needs a number from the last scan table (1-%u)", unsigned(nets.size()));274 return;275 }276 const ScanResult &n = nets[number - 1];277 if (n.ssid.isEmpty()) {278 log_w("That network is hidden; its name is unknown, so it can't be joined from the list.");279 return;280 }281 if (n.auth == WIFI_AUTH_OPEN) {282 log_i("'%s' is open, joining without a password", n.ssid.c_str());283 connection.save(n.ssid, "");284 return;285 }286 state.pendingSsid = n.ssid;287 state.awaitingPassword = true;288 Serial.printf("Password for '%s' (the monitor shows what you type; it is stored on the chip only):\n", n.ssid.c_str());289}290 291// ---- Input -----------------------------------------------------------------------------292 293void handleButton(Button &b) {294 switch (b.poll()) {295 case Button::Event::Click:296 setView(state.view + 1);297 pushEvent(b.name(), "click");298 break;299 case Button::Event::DoubleClick:300 scanNow(b.name());301 pushEvent(b.name(), "double-click");302 break;303 case Button::Event::LongPress:304 setAuto(!state.autoScan);305 pushEvent(b.name(), "long-press");306 break;307 case Button::Event::None: break;308 }309}310 311void handleCommand(String raw) {312 // A password is taken exactly as typed: no lower-casing, no trimming of inner spaces.313 if (state.awaitingPassword) {314 state.awaitingPassword = false;315 connection.save(state.pendingSsid, raw);316 state.pendingSsid = "";317 setView(kStatusView);318 return;319 }320 String line = raw;321 line.trim();322 String lower = line;323 lower.toLowerCase();324 if (lower.isEmpty()) return;325 if (lower == "scan") return scanNow("serial");326 if (lower == "auto on" || lower == "auto off") return setAuto(lower == "auto on");327 if (lower == "forget") return connection.forget();328 if (lower == "reconnect") return connection.connect();329 if (lower == "status") return printStatus();330 if (lower == "ping" || lower.startsWith("ping ")) {331 IPAddress target = WiFi.gatewayIP();332 if (connection.state() != Connection::State::Connected) log_w("ping needs a network: join one first");333 else if (lower.length() > 5 && !target.fromString(line.substring(5))) log_w("not an IP address: %s", line.substring(5).c_str());334 else pinger.start(target);335 return;336 }337 if (lower == "relay" || lower.startsWith("relay ")) {338 if (!remote::builtIn()) log_w("this build has no remote link: flash wifi-lab-w2-remote");339 else if (lower == "relay") printRelay();340 else if (lower == "relay off") remote::setUrl("");341 else remote::setUrl(line.substring(6)); // as typed: host names can be mixed case342 return;343 }344 if (lower == "setup") return portal.start();345 if (lower == "token") {346 Serial.printf("Admin token: %s (put it in esp-labs/apps/dashboard/.env as ESP_TOKEN)\n", token.value().c_str());347 return;348 }349 if (lower == "token new") {350 token.regenerate();351 Serial.printf("New admin token: %s (the old one stops working now)\n", token.value().c_str());352 return;353 }354 if (lower.startsWith("join ")) return startJoin(lower.substring(5).toInt());355 if (lower.startsWith("tz ")) return connection.setTimezone(line.substring(3));356 if (lower.startsWith("view ")) {357 const long v = lower.substring(5).toInt();358 if (v < 1 || v > kViews) {359 log_w("view needs 1-%d, got '%s'", kViews, lower.substring(5).c_str());360 return;361 }362 return setView(v - 1);363 }364 if (lower == "help" || lower == "?") return printHelp();365 log_w("unknown command '%s' (type help)", line.c_str());366}367 368void pollSerial() {369 static String buffer;370 while (Serial.available()) {371 const char c = Serial.read();372 if (c == '\n' || c == '\r') {373 if (!buffer.isEmpty() || state.awaitingPassword) handleCommand(buffer);374 buffer = "";375 } else if (buffer.length() < 96) { // WPA passwords can be 63 characters376 buffer += c;377 }378 }379}380 381// Open the set-up network when there's nothing to join (or joining keeps failing),382// close it a while after we're connected.383void managePortal() {384 using State = Connection::State;385 static uint32_t failingSince = 0;386 const uint32_t now = millis();387 const State s = connection.state();388 if (s == State::NoCredentials) portal.start();389 if (s == State::Failed) {390 if (!failingSince) failingSince = now;391 if (now - failingSince > kPortalAfterFailMs) portal.start();392 } else if (s != State::Connecting) {393 failingSince = 0;394 }395 if (s == State::Connected && portal.activeFor() > kPortalCloseAfterJoinMs) portal.stop();396}397 398} // namespace399 400void setup() {401 Serial.begin(115200);402 delay(1500);403 404 if (!display.begin()) {405 log_e("No memory for the frame buffer. Stopping.");406 return;407 }408 setLed(0, 0, 0);409 external.begin();410 boot.begin();411 commands.begin();412 token.begin();413 scanner.begin();414 portal.begin();415 connection.begin();416 web.begin();417 remote::begin(rules, token);418 log_i("%s: MAC %s. Radio: 2.4 GHz only.", kFirmware, WiFi.macAddress().c_str());419 Serial.printf("Admin token: %s (for the dashboard's .env; serial command 'token' shows it again)\n", token.value().c_str());420 printHelp();421 // A scan can't start while the radio is busy joining; the loop scans once we're settled.422 if (connection.state() != Connection::State::Connecting) scanNow("start-up");423}424 425void loop() {426 FrameBuffer &fb = display.fb();427 if (fb.pixels() == nullptr) {428 delay(1000);429 return;430 }431 const uint32_t now = millis();432 if (state.rebootAt && now >= state.rebootAt) ESP.restart();433 434 pollSerial();435 handleButton(external);436 handleButton(boot);437 for (Command c; commands.pop(c);) applyCommand(c);438 connection.loop();439 portal.loop();440 managePortal();441 web.loop();442 if (connection.takeJustConnected()) setView(kStatusView);443 444 if (scanner.poll()) {445 if (scanner.failed()) log_w("scan failed, will retry");446 else log_i("scan %lu done: %u networks in %lu ms", static_cast<unsigned long>(scanner.scans()),447 unsigned(scanner.networks().size()), static_cast<unsigned long>(scanner.lastScanMs()));448 printResults();449 const String networks = networksJson();450 web.publishNetworks(networks);451 remote::publish("networks", networks);452 }453 // No automatic scans while joining (the radio must stay on the router's channel) or while the454 // set-up network is open (a scan would briefly cut off the phone that's setting us up).455 const bool joining = connection.state() == Connection::State::Connecting;456 // millis() here, not `now`: a scan that finished during poll() above has a finish time later457 // than `now`, and `now - finishedAt` would wrap around to a huge number and scan again at once.458 if (state.autoScan && !joining && !portal.active() && !scanner.scanning() &&459 millis() - scanner.finishedAt() >= autoScanInterval())460 scanNow("auto");461 462 static uint32_t lastPush = 0, lastTemp = 0;463 if (now - lastTemp >= 1000) {464 lastTemp = now;465 state.tempC = temperatureRead();466 }467 if (now - lastPush >= kStatusPushMs) {468 lastPush = now;469 const String status = statusJson();470 web.publishStatus(status);471 remote::publish("status", status);472 }473 474 if (state.view == 0 && now - state.pageFlippedAt >= kPageFlipMs) {475 state.page++;476 state.pageFlippedAt = now;477 }478 479 fb.fillScreen(pal::night);480 const auto &nets = scanner.networks();481 switch (state.view) {482 case 0: views::list(fb, nets, state.page); break;483 case 1: views::channels(fb, nets); break;484 case 2: views::radar(fb, nets, now / 1000.0f, scanner.scanning()); break;485 case kStatusView:486 if (portal.active() && connection.state() != Connection::State::Connected) views::setupScreen(fb, portal);487 else views::status(fb, connection, now / 1000.0f);488 break;489 default: views::message(fb, state.message, pal::amber); break;490 }491 views::header(fb, scanner, state.view, kViews, kViewNames[state.view], connection.state());492 // Remote link: a ring around the Wi-Fi dot, teal when the dashboard server is connected.493 if (remote::state() == remote::State::Online) fb.drawCircle(312, 20, 7, pal::teal);494 else if (remote::state() == remote::State::Connecting) fb.drawCircle(312, 20, 7, pal::amber);495 views::footer(fb, "click: view double: scan hold: auto", state.autoScan, scanner, autoScanInterval() / 1000);496 views::otaOverlay(fb, web.otaPercent());497 display.push();498}
// Wi-Fi lab W2: phone control.
// uv run pio run -d labs/wifi-lab-w2 -e wifi-lab-w2 -t upload variation 1: control on your Wi-Fi
// uv run pio run -d labs/wifi-lab-w2 -e wifi-lab-w2-remote -t upload variation 2: also from anywhere, through your
// dashboard server and a tunnel (remote.h)
// Everything from W1 (scanner views, join, status) plus a web server: REST API + WebSocket,
// a phone page at http://bench.local, a set-up network for joining without a cable, firmware
// updates over HTTP, and the desktop dashboard in esp-labs/apps/dashboard.
//
// Wiring: the screen from lesson 03. The push button on GPIO 5 is optional: it does exactly what
// BOOT does, and with nothing wired its internal pull-up keeps it quiet.
// Views: networks · channels · radar · status · message
// Button or BOOT: click = next view · double-click = scan now · long press = auto-scan on/off
// Serial: scan | view <1-5> | auto on|off | join <n> | forget | reconnect | status | tz <TZ> |
// ping [ip] | setup | token | token new | relay [url|off] | help
// Web: http://bench.local (phone page), /api (REST), /ws (live). See web_api.h.
// The saved network is shared with W1 (same NVS namespace), so switching labs keeps it.
#include <Arduino.h>
#include <ArduinoJson.h>
#include <WiFi.h>
#include <esp_heap_caps.h>
#include "api_rules.h"
#include "api_token.h"
#include "button.h"
#include "color.h"
#include "commands.h"
#include "connection.h"
#include "display.h"
#include "pinger.h"
#include "pins.h"
#include "remote.h"
#include "scanner.h"
#include "setup_portal.h"
#include "views.h"
#include "web_api.h"
#include "web_views.h"
namespace {
constexpr uint32_t kAutoScanMs = 10'000; // pause between automatic scans when not joined
// When joined, every scan takes the radio off the router's channel for ~3 s, and web requests
// arriving meanwhile get lost. So scan much less often once we're on a network.
constexpr uint32_t kAutoScanJoinedMs = 60'000;
constexpr uint32_t kPageFlipMs = 4'000; // list view: next page after this long
constexpr uint32_t kStatusPushMs = 1'000; // live status to web clients
constexpr uint32_t kPortalAfterFailMs = 60'000;
constexpr uint32_t kPortalCloseAfterJoinMs = 30'000;
constexpr int kStatusView = 3, kMessageView = 4;
const char *const kViewNames[] = {"networks", "channels", "radar", "status", "message"};
constexpr int kViews = sizeof(kViewNames) / sizeof(kViewNames[0]);
constexpr const char *kFirmware = "wifi-lab-w2";
Display display;
Scanner scanner;
Connection connection;
SetupPortal portal;
ApiToken token;
Pinger pinger;
CommandQueue commands;
ApiRules rules(commands, connection, kViewNames, kViews);
WebApi web(rules, commands, token);
Button external(PIN_BUTTON, "button");
Button boot(PIN_BOOT_BTN, "BOOT");
struct {
int view = 0;
int page = 0;
bool autoScan = true;
uint8_t backlight = 255;
uint8_t r = 0, g = 0, b = 0; // on-board RGB LED
String message;
uint32_t pageFlippedAt = 0;
String pendingSsid; // set by `join <n>`: the next serial line is the password
bool awaitingPassword = false;
uint32_t rebootAt = 0; // set by a reboot command; 0 = none
float tempC = NAN;
} state;
// ---- JSON snapshots for the web --------------------------------------------------------
const char *wifiStateName(Connection::State s) {
switch (s) {
case Connection::State::Connected: return "connected";
case Connection::State::Connecting: return "connecting";
case Connection::State::Failed: return "failed";
default: return "not-set-up";
}
String statusJson() {
JsonDocument doc;
doc["firmware"] = kFirmware;
doc["uptimeS"] = millis() / 1000;
doc["heapFree"] = ESP.getFreeHeap();
doc["psramFree"] = ESP.getFreePsram();
if (!isnan(state.tempC)) doc["tempC"] = serialized(String(state.tempC, 1));
doc["clients"] = web.clients();
JsonObject wifi = doc["wifi"].to<JsonObject>();
wifi["state"] = wifiStateName(connection.state());
wifi["ssid"] = connection.ssid();
wifi["hostname"] = String(Connection::kHostname) + ".local";
if (connection.state() == Connection::State::Connected) {
wifi["ip"] = WiFi.localIP().toString();
wifi["rssi"] = WiFi.RSSI();
wifi["channel"] = WiFi.channel();
wifi["reason"] = Connection::reasonHint(connection.lastReason());
JsonObject link = doc["remote"].to<JsonObject>();
link["state"] = remote::stateName(remote::state());
JsonObject setup = doc["setup"].to<JsonObject>();
setup["active"] = portal.active();
setup["ssid"] = SetupPortal::kSsid; // the password is only on the screen, never in the API
JsonObject screen = doc["screen"].to<JsonObject>();
screen["view"] = kViewNames[state.view];
JsonArray names = screen["views"].to<JsonArray>();
for (const char *n : kViewNames) names.add(n);
screen["autoScan"] = state.autoScan;
screen["backlight"] = state.backlight;
screen["message"] = state.message;
JsonObject led = doc["led"].to<JsonObject>();
led["r"] = state.r, led["g"] = state.g, led["b"] = state.b;
JsonObject scan = doc["scan"].to<JsonObject>();
scan["running"] = scanner.scanning();
scan["count"] = scanner.networks().size();
scan["durationMs"] = scanner.lastScanMs();
String out;
serializeJson(doc, out);
return out;
String networksJson() {
doc["scans"] = scanner.scans();
doc["durationMs"] = scanner.lastScanMs();
JsonArray list = doc["networks"].to<JsonArray>();
for (const ScanResult &n : scanner.networks()) {
JsonObject o = list.add<JsonObject>();
o["ssid"] = n.ssid; // hardware addresses (BSSIDs) stay off the web on purpose
o["rssi"] = n.rssi;
o["channel"] = n.channel;
o["auth"] = authName(n.auth);
void pushEvent(const char *source, const char *gesture) {
doc["source"] = source;
doc["gesture"] = gesture;
web.publishEvent(out);
remote::publish("event", out);
// ---- Serial output ---------------------------------------------------------------------
void printResults() {
const auto &nets = scanner.networks();
Serial.printf("\n--- scan %lu: %u networks in %lu ms ---\n", static_cast<unsigned long>(scanner.scans()),
unsigned(nets.size()), static_cast<unsigned long>(scanner.lastScanMs()));
Serial.println(" # dBm ch security bssid ssid");
for (size_t i = 0; i < nets.size(); i++) {
const ScanResult &n = nets[i];
Serial.printf("%2u %4ld %2u %-10s %s %s\n", unsigned(i + 1), static_cast<long>(n.rssi), n.channel,
authName(n.auth), n.bssid.c_str(), n.ssid.isEmpty() ? "(hidden)" : n.ssid.c_str());
Serial.println("To join one: join <#>");
void printRelay() {
const String url = remote::url();
Serial.printf("Remote link: %s%s%s\n", remote::stateName(remote::state()), url.isEmpty() ? "" : " | ", url.c_str());
void printStatus() {
using State = Connection::State;
switch (connection.state()) {
case State::NoCredentials: Serial.println("Not joined. Scan, then: join <#>"); break;
case State::Connecting: Serial.printf("Joining '%s'...\n", connection.ssid().c_str()); break;
case State::Failed: Serial.printf("Could not join '%s': %s\n", connection.ssid().c_str(), Connection::reasonHint(connection.lastReason())); break;
case State::Connected:
Serial.printf("Joined '%s' | IP %s | http://%s.local | ch %d | %ld dBm | time %s | web clients %u\n",
connection.ssid().c_str(), WiFi.localIP().toString().c_str(), Connection::kHostname,
static_cast<int>(WiFi.channel()), static_cast<long>(WiFi.RSSI()),
connection.timeSynced() ? "synced" : "not yet", unsigned(web.clients()));
break;
if (portal.active()) Serial.printf("Set-up network '%s' is open (password on the screen)\n", SetupPortal::kSsid);
if (remote::builtIn()) printRelay();
void printHelp() {
Serial.println();
Serial.println("Commands: scan | view <1-5> | auto on|off | join <#> | forget | reconnect | status | tz <TZ>");
Serial.println(" ping (the router) | ping <ip> (e.g. your computer: can the board reach it?)");
Serial.println(" setup (open the set-up network) | token (show admin token) | token new | help");
if (remote::builtIn()) Serial.println(" relay (show) | relay wss://<tunnel host> (save + connect) | relay off");
Serial.println("Button (GPIO 5) or BOOT: click = next view, double-click = scan now, long press = auto-scan on/off");
// ---- Actions (shared by the button, serial and web) -------------------------------------
uint32_t autoScanInterval() {
return connection.state() == Connection::State::Connected ? kAutoScanJoinedMs : kAutoScanMs;
void scanNow(const char *why) {
if (scanner.start()) log_i("scan started (%s)", why);
void setView(int v) {
state.view = (v % kViews + kViews) % kViews;
state.page = 0;
state.pageFlippedAt = millis();
log_i("view %d: %s", state.view + 1, kViewNames[state.view]);
void setAuto(bool on) {
state.autoScan = on;
log_i("auto-scan %s", on ? "on" : "off");
void setLed(uint8_t r, uint8_t g, uint8_t b) {
state.r = r, state.g = g, state.b = b;
rgbLedWrite(PIN_RGB, r, g, b);
void applyCommand(const Command &c) {
using T = Command::Type;
switch (c.type) {
case T::SetView: setView(c.value); break;
case T::Scan: scanNow("web"); break;
case T::SetAutoScan: setAuto(c.value != 0); break;
case T::SetBacklight:
state.backlight = uint8_t(c.value);
display.setBacklight(state.backlight);
log_i("backlight %u", state.backlight);
case T::SetLed: setLed(c.r, c.g, c.b); break;
case T::ShowMessage:
state.message = c.text;
setView(kMessageView);
log_i("message from the web (%u characters)", unsigned(state.message.length()));
case T::SaveWifi:
connection.save(c.text, c.secret);
setView(kStatusView);
case T::ForgetWifi: connection.forget(); break;
case T::Reboot:
log_i("reboot requested");
state.rebootAt = millis() + 800; // let the HTTP answer go out first
void startJoin(long number) {
if (number < 1 || number > long(nets.size())) {
log_w("join needs a number from the last scan table (1-%u)", unsigned(nets.size()));
return;
const ScanResult &n = nets[number - 1];
if (n.ssid.isEmpty()) {
log_w("That network is hidden; its name is unknown, so it can't be joined from the list.");
if (n.auth == WIFI_AUTH_OPEN) {
log_i("'%s' is open, joining without a password", n.ssid.c_str());
connection.save(n.ssid, "");
state.pendingSsid = n.ssid;
state.awaitingPassword = true;
Serial.printf("Password for '%s' (the monitor shows what you type; it is stored on the chip only):\n", n.ssid.c_str());
// ---- Input -----------------------------------------------------------------------------
void handleButton(Button &b) {
switch (b.poll()) {
case Button::Event::Click:
setView(state.view + 1);
pushEvent(b.name(), "click");
case Button::Event::DoubleClick:
scanNow(b.name());
pushEvent(b.name(), "double-click");
case Button::Event::LongPress:
setAuto(!state.autoScan);
pushEvent(b.name(), "long-press");
case Button::Event::None: break;
void handleCommand(String raw) {
// A password is taken exactly as typed: no lower-casing, no trimming of inner spaces.
if (state.awaitingPassword) {
state.awaitingPassword = false;
connection.save(state.pendingSsid, raw);
state.pendingSsid = "";
String line = raw;
line.trim();
String lower = line;
lower.toLowerCase();
if (lower.isEmpty()) return;
if (lower == "scan") return scanNow("serial");
if (lower == "auto on" || lower == "auto off") return setAuto(lower == "auto on");
if (lower == "forget") return connection.forget();
if (lower == "reconnect") return connection.connect();
if (lower == "status") return printStatus();
if (lower == "ping" || lower.startsWith("ping ")) {
IPAddress target = WiFi.gatewayIP();
if (connection.state() != Connection::State::Connected) log_w("ping needs a network: join one first");
else if (lower.length() > 5 && !target.fromString(line.substring(5))) log_w("not an IP address: %s", line.substring(5).c_str());
else pinger.start(target);
if (lower == "relay" || lower.startsWith("relay ")) {
if (!remote::builtIn()) log_w("this build has no remote link: flash wifi-lab-w2-remote");
else if (lower == "relay") printRelay();
else if (lower == "relay off") remote::setUrl("");
else remote::setUrl(line.substring(6)); // as typed: host names can be mixed case
if (lower == "setup") return portal.start();
if (lower == "token") {
Serial.printf("Admin token: %s (put it in esp-labs/apps/dashboard/.env as ESP_TOKEN)\n", token.value().c_str());
if (lower == "token new") {
token.regenerate();
Serial.printf("New admin token: %s (the old one stops working now)\n", token.value().c_str());
if (lower.startsWith("join ")) return startJoin(lower.substring(5).toInt());
if (lower.startsWith("tz ")) return connection.setTimezone(line.substring(3));
if (lower.startsWith("view ")) {
const long v = lower.substring(5).toInt();
if (v < 1 || v > kViews) {
log_w("view needs 1-%d, got '%s'", kViews, lower.substring(5).c_str());
return setView(v - 1);
if (lower == "help" || lower == "?") return printHelp();
log_w("unknown command '%s' (type help)", line.c_str());
void pollSerial() {
static String buffer;
while (Serial.available()) {
const char c = Serial.read();
if (c == '\n' || c == '\r') {
if (!buffer.isEmpty() || state.awaitingPassword) handleCommand(buffer);
buffer = "";
} else if (buffer.length() < 96) { // WPA passwords can be 63 characters
buffer += c;
// Open the set-up network when there's nothing to join (or joining keeps failing),
// close it a while after we're connected.
void managePortal() {
static uint32_t failingSince = 0;
const uint32_t now = millis();
const State s = connection.state();
if (s == State::NoCredentials) portal.start();
if (s == State::Failed) {
if (!failingSince) failingSince = now;
if (now - failingSince > kPortalAfterFailMs) portal.start();
} else if (s != State::Connecting) {
failingSince = 0;
if (s == State::Connected && portal.activeFor() > kPortalCloseAfterJoinMs) portal.stop();
} // namespace
void setup() {
Serial.begin(115200);
delay(1500);
if (!display.begin()) {
log_e("No memory for the frame buffer. Stopping.");
setLed(0, 0, 0);
external.begin();
boot.begin();
commands.begin();
token.begin();
scanner.begin();
portal.begin();
connection.begin();
web.begin();
remote::begin(rules, token);
log_i("%s: MAC %s. Radio: 2.4 GHz only.", kFirmware, WiFi.macAddress().c_str());
Serial.printf("Admin token: %s (for the dashboard's .env; serial command 'token' shows it again)\n", token.value().c_str());
printHelp();
// A scan can't start while the radio is busy joining; the loop scans once we're settled.
if (connection.state() != Connection::State::Connecting) scanNow("start-up");
void loop() {
FrameBuffer &fb = display.fb();
if (fb.pixels() == nullptr) {
delay(1000);
if (state.rebootAt && now >= state.rebootAt) ESP.restart();
pollSerial();
handleButton(external);
handleButton(boot);
for (Command c; commands.pop(c);) applyCommand(c);
connection.loop();
portal.loop();
managePortal();
web.loop();
if (connection.takeJustConnected()) setView(kStatusView);
if (scanner.poll()) {
if (scanner.failed()) log_w("scan failed, will retry");
else log_i("scan %lu done: %u networks in %lu ms", static_cast<unsigned long>(scanner.scans()),
unsigned(scanner.networks().size()), static_cast<unsigned long>(scanner.lastScanMs()));
printResults();
const String networks = networksJson();
web.publishNetworks(networks);
remote::publish("networks", networks);
// No automatic scans while joining (the radio must stay on the router's channel) or while the
// set-up network is open (a scan would briefly cut off the phone that's setting us up).
const bool joining = connection.state() == Connection::State::Connecting;
// millis() here, not `now`: a scan that finished during poll() above has a finish time later
// than `now`, and `now - finishedAt` would wrap around to a huge number and scan again at once.
if (state.autoScan && !joining && !portal.active() && !scanner.scanning() &&
millis() - scanner.finishedAt() >= autoScanInterval())
scanNow("auto");
static uint32_t lastPush = 0, lastTemp = 0;
if (now - lastTemp >= 1000) {
lastTemp = now;
state.tempC = temperatureRead();
if (now - lastPush >= kStatusPushMs) {
lastPush = now;
const String status = statusJson();
web.publishStatus(status);
remote::publish("status", status);
if (state.view == 0 && now - state.pageFlippedAt >= kPageFlipMs) {
state.page++;
state.pageFlippedAt = now;
fb.fillScreen(pal::night);
switch (state.view) {
case 0: views::list(fb, nets, state.page); break;
case 1: views::channels(fb, nets); break;
case 2: views::radar(fb, nets, now / 1000.0f, scanner.scanning()); break;
case kStatusView:
if (portal.active() && connection.state() != Connection::State::Connected) views::setupScreen(fb, portal);
else views::status(fb, connection, now / 1000.0f);
default: views::message(fb, state.message, pal::amber); break;
views::header(fb, scanner, state.view, kViews, kViewNames[state.view], connection.state());
// Remote link: a ring around the Wi-Fi dot, teal when the dashboard server is connected.
if (remote::state() == remote::State::Online) fb.drawCircle(312, 20, 7, pal::teal);
else if (remote::state() == remote::State::Connecting) fb.drawCircle(312, 20, 7, pal::amber);
views::footer(fb, "click: view double: scan hold: auto", state.autoScan, scanner, autoScanInterval() / 1000);
views::otaOverlay(fb, web.otaPercent());
display.push();
New word #include
#include
Pastes another file in here, so this file can use what it declares.
PlatformIO environment wifi-lab-w2 includes C++ source files covering REST API, WebSocket, async web server, captive portal, OTA updates, admin token, React + Node.