1// Wi-Fi lab W3: internet & AI. uv run pio run -d labs/wifi-lab-w3 -e wifi-lab-w3 -t upload2// The board becomes an internet client: it fetches the weather over HTTPS as JSON (Open-Meteo, no3// key needed), draws it, and asks an AI model to turn the moment into a haiku or to answer your4// questions with the weather in mind. The answer picks the LED colour too. The AI goes through a5// LiteLLM gateway (esp-labs/apps/ai-gateway), so any provider and model works.6//7// Wiring: the screen from lesson 03. The push button on GPIO 5 is optional: it does exactly what8// BOOT does. Wi-Fi: the network saved by W1 or W2 (same NVS namespace); join one there first.9//10// Views: now · forecast · week · oracle · status11// Button or BOOT: click = next view · double-click = refresh weather (oracle view: new haiku)12// long press = ask the oracle from any view13// Serial: city <name> | weather | oracle | ask <question> | ai | ai url <url> | ai key <key> |14// ai key forget | ai model <name> | led off | view <1-5> | status | ping [ip] | tz <TZ> |15// reconnect | forget | help16#include <Arduino.h>17#include <ArduinoJson.h>18#include <WiFi.h>19 20#include "button.h"21#include "color.h"22#include "connection.h"23#include "display.h"24#include "pinger.h"25#include "pins.h"26#include "settings.h"27#include "views.h"28#include "w3_views.h"29#include "worker.h"30 31namespace {32 33constexpr uint32_t kWeatherEveryMs = 15 * 60'000; // Open-Meteo updates its model every 15 min34constexpr uint32_t kRetryMs = 60'000; // after a failed fetch35constexpr uint32_t kOracleGapMs = 10'000; // at most one AI request per 10 s36const char *const kViewNames[] = {"now", "forecast", "week", "oracle", "status"};37constexpr int kViews = sizeof(kViewNames) / sizeof(kViewNames[0]);38constexpr int kOracleView = 3, kStatusView = 4;39 40Display display;41Connection connection;42Pinger pinger;43Worker worker;44Button external(PIN_BUTTON, "button");45Button boot(PIN_BOOT_BTN, "BOOT");46 47struct {48 int view = 0;49 Place place;50 bool aiReady = false; // gateway address and key both saved51 String model;52 Worker::Outcome out; // the latest copy of the worker's results53 uint32_t lastWeatherTry = 0, lastOracle = 0, seenAnswerAt = 0;54} state;55 56// ---- What the oracle gets to know about this moment ---------------------------------------57 58String context() {59 JsonDocument d;60 if (state.place.valid()) d["place"] = state.place.name;61 struct tm lt;62 if (getLocalTime(<, 0)) {63 char when[32];64 strftime(when, sizeof(when), "%A %d %B, %H:%M", <);65 d["local_time"] = when;66 }67 if (state.out.weatherAt) {68 const Weather &w = state.out.weather;69 JsonObject o = d["weather"].to<JsonObject>();70 o["now"] = weather::describe(w.code);71 o["temp_c"] = serialized(String(w.temp, 1));72 o["feels_like_c"] = serialized(String(w.feels, 1));73 o["wind_kmh"] = int(lroundf(w.wind));74 o["humidity_pct"] = w.humidity;75 o["daylight"] = w.day;76 if (w.hours) o["max_rain_chance_next_24h_pct"] = *std::max_element(w.hourRain, w.hourRain + w.hours);77 if (w.days) o["today_min_c"] = int(lroundf(w.dayMin[0])), o["today_max_c"] = int(lroundf(w.dayMax[0]));78 }79 JsonObject b = d["bench"].to<JsonObject>();80 b["board"] = "ESP32-S3 with a 1.9 inch screen";81 b["chip_temp_c"] = serialized(String(temperatureRead(), 1));82 b["uptime_min"] = millis() / 60'000;83 b["wifi_signal_dbm"] = WiFi.RSSI();84 String out;85 serializeJson(d, out);86 return out;87}88 89// ---- Actions ---------------------------------------------------------------------------90 91bool online() { return connection.state() == Connection::State::Connected; }92 93void setView(int v) {94 state.view = (v % kViews + kViews) % kViews;95 log_i("view %d: %s", state.view + 1, kViewNames[state.view]);96}97 98void fetchWeather(const char *why) {99 if (!state.place.valid()) {100 log_w("no city yet: type city <name>");101 return;102 }103 if (!online()) {104 log_w("not on Wi-Fi yet");105 return;106 }107 state.lastWeatherTry = millis();108 Worker::Request r;109 r.job = Worker::Job::Weather;110 r.place = state.place;111 if (worker.submit(r)) log_i("weather for %s (%s)", state.place.name.c_str(), why);112 else log_w("busy with another request, try again in a moment");113}114 115void findCity(const String &name) {116 if (!online()) {117 log_w("not on Wi-Fi yet");118 return;119 }120 Worker::Request r;121 r.job = Worker::Job::Geocode;122 r.text = name;123 if (worker.submit(r)) log_i("looking up '%s'...", name.c_str());124 else log_w("busy with another request, try again in a moment");125}126 127void askOracle(const String &question) {128 if (!state.aiReady) {129 setView(kOracleView);130 log_w("set the gateway first: ai url <url> and ai key <key>");131 return;132 }133 if (!online()) {134 log_w("not on Wi-Fi yet");135 return;136 }137 if (state.lastOracle && millis() - state.lastOracle < kOracleGapMs) {138 log_w("one question per 10 s, please");139 return;140 }141 Worker::Request r;142 r.job = question.isEmpty() ? Worker::Job::Oracle : Worker::Job::Ask;143 r.text = question;144 r.aiUrl = settings::aiUrl();145 r.apiKey = settings::apiKey();146 r.model = state.model;147 r.context = context();148 if (!worker.submit(r)) {149 log_w("busy with another request, try again in a moment");150 return;151 }152 state.lastOracle = millis();153 setView(kOracleView);154 log_i("asking %s%s%s", state.model.c_str(), question.isEmpty() ? " for a haiku" : ": ", question.c_str());155}156 157// ---- Input -----------------------------------------------------------------------------158 159void handleButton(Button &b) {160 switch (b.poll()) {161 case Button::Event::Click: setView(state.view + 1); break;162 case Button::Event::DoubleClick:163 if (state.view == kOracleView) askOracle("");164 else fetchWeather(b.name());165 break;166 case Button::Event::LongPress: askOracle(""); break;167 case Button::Event::None: break;168 }169}170 171void printAi() {172 const String url = settings::aiUrl();173 Serial.printf("AI gateway: %s | key %s | model %s\n", url.isEmpty() ? "not set" : url.c_str(),174 settings::masked(settings::apiKey()).c_str(), state.model.c_str());175}176 177void refreshAiReady() { state.aiReady = !settings::aiUrl().isEmpty() && !settings::apiKey().isEmpty(); }178 179void printStatus() {180 using State = Connection::State;181 switch (connection.state()) {182 case State::NoCredentials: Serial.println("No saved Wi-Fi: flash W1 or W2 once and join there (it's shared)."); break;183 case State::Connecting: Serial.printf("Joining '%s'...\n", connection.ssid().c_str()); break;184 case State::Failed: Serial.printf("Could not join '%s': %s\n", connection.ssid().c_str(), Connection::reasonHint(connection.lastReason())); break;185 case State::Connected:186 Serial.printf("Joined '%s' | IP %s | %ld dBm | time %s\n", connection.ssid().c_str(), WiFi.localIP().toString().c_str(),187 static_cast<long>(WiFi.RSSI()), connection.timeSynced() ? "synced" : "not yet");188 break;189 }190 Serial.printf("City: %s | weather %s\n", state.place.valid() ? state.place.name.c_str() : "not set",191 w3::ago(state.out.weatherAt).c_str());192 printAi();193 if (!state.out.error.isEmpty()) Serial.printf("Last error: %s\n", state.out.error.c_str());194}195 196void printHelp() {197 Serial.println();198 Serial.println("Commands: city <name> | weather | oracle | ask <question> | view <1-5> | status | led off");199 Serial.println(" ai (show) | ai url http://<gateway>:4000 | ai key <key> | ai key forget");200 Serial.println(" ai model <name> (a model_name from ai-gateway/config.yaml, default " + String(oracle::kDefaultModel) + ")");201 Serial.println(" ping [ip] | tz <TZ> | reconnect | forget | help");202 Serial.println("Button (GPIO 5, optional) or BOOT: click = next view, double-click = refresh (oracle view: new haiku),");203 Serial.println(" long press = ask the oracle");204}205 206void handleCommand(const String &raw) {207 String line = raw;208 line.trim();209 String lower = line;210 lower.toLowerCase();211 if (lower.isEmpty()) return;212 if (lower.startsWith("city ")) return findCity(line.substring(5));213 if (lower == "weather") return fetchWeather("serial");214 if (lower == "oracle") return askOracle("");215 if (lower.startsWith("ask ")) return askOracle(line.substring(4, 164));216 if (lower == "ai") return printAi();217 if (lower.startsWith("ai url ")) {218 String url = line.substring(7);219 url.trim();220 if (!url.startsWith("http://") && !url.startsWith("https://")) {221 log_w("the gateway address starts with http:// or https://");222 return;223 }224 settings::saveString("url", url);225 refreshAiReady();226 log_i("AI gateway: %s", url.c_str());227 return;228 }229 if (lower == "ai key forget") {230 settings::saveString("key", "");231 refreshAiReady();232 log_i("AI key erased from the chip");233 return;234 }235 if (lower.startsWith("ai key ")) {236 String key = line.substring(7);237 key.trim();238 settings::saveString("key", key); // as typed: keys are case-sensitive239 refreshAiReady();240 log_i("AI key saved: %s", settings::masked(key).c_str());241 return;242 }243 if (lower.startsWith("ai model ")) {244 state.model = line.substring(9);245 state.model.trim();246 settings::saveString("model", state.model);247 log_i("model: %s", state.model.c_str());248 return;249 }250 if (lower == "led off") return rgbLedWrite(PIN_RGB, 0, 0, 0);251 if (lower == "status") return printStatus();252 if (lower == "forget") return connection.forget();253 if (lower == "reconnect") return connection.connect();254 if (lower.startsWith("tz ")) return connection.setTimezone(line.substring(3));255 if (lower == "ping" || lower.startsWith("ping ")) {256 IPAddress target = WiFi.gatewayIP();257 if (!online()) log_w("ping needs a network");258 else if (lower.length() > 5 && !target.fromString(line.substring(5))) log_w("not an IP address: %s", line.substring(5).c_str());259 else pinger.start(target);260 return;261 }262 if (lower.startsWith("view ")) {263 const long v = lower.substring(5).toInt();264 if (v < 1 || v > kViews) {265 log_w("view needs 1-%d", kViews);266 return;267 }268 return setView(v - 1);269 }270 if (lower == "help" || lower == "?") return printHelp();271 log_w("unknown command '%s' (type help)", line.c_str());272}273 274void pollSerial() {275 static String buffer;276 while (Serial.available()) {277 const char c = Serial.read();278 if (c == '\n' || c == '\r') {279 if (!buffer.isEmpty()) handleCommand(buffer);280 buffer = "";281 } else if (buffer.length() < 240) { // API keys are ~110 characters282 buffer += c;283 }284 }285}286 287// ---- Results from the worker ----------------------------------------------------------------288 289void takeResults() {290 if (!worker.update(state.out)) return;291 if (state.out.placeChanged) {292 state.place = state.out.place;293 settings::savePlace(state.place);294 log_i("city set: %s (%.3f, %.3f)", state.place.name.c_str(), state.place.lat, state.place.lon);295 setView(0);296 fetchWeather("new city");297 }298 if (state.out.answerAt && state.out.answerAt != state.seenAnswerAt) {299 state.seenAnswerAt = state.out.answerAt;300 const OracleAnswer &a = state.out.answer;301 rgbLedWrite(PIN_RGB, a.r / 4, a.g / 4, a.b / 4); // a quarter: the LED is very bright302 log_i("oracle: \"%s\" (%u lines, %lu > %lu tokens)", a.title.c_str(), unsigned(a.lineCount),303 static_cast<unsigned long>(a.inputTokens), static_cast<unsigned long>(a.outputTokens));304 for (int i = 0; i < a.lineCount; i++) Serial.printf(" %s\n", a.lines[i].c_str());305 }306}307 308void drawNoWifi(FrameBuffer &fb) {309 fb.setFont(&FreeSans9pt7b);310 fb.setTextColor(pal::ink);311 fb.setCursor(8, 56);312 fb.print("No saved Wi-Fi network");313 const char *lines[] = {"W3 uses the network W1 or W2 saved.", "Flash one of them, join, then come back:",314 " uv run pio run -d labs/wifi-lab-w1 -e wifi-lab-w1 -t upload"};315 w3::hint(fb, 72, lines, 3);316}317 318} // namespace319 320void setup() {321 Serial.begin(115200);322 delay(1500);323 if (!display.begin()) {324 log_e("No memory for the frame buffer. Stopping.");325 return;326 }327 rgbLedWrite(PIN_RGB, 0, 0, 0);328 external.begin();329 boot.begin();330 WiFi.mode(WIFI_STA);331 state.place = settings::loadPlace();332 refreshAiReady();333 state.model = settings::model();334 worker.begin();335 connection.begin();336 log_i("wifi-lab-w3: city %s, AI gateway %s, model %s", state.place.valid() ? state.place.name.c_str() : "not set",337 state.aiReady ? "set" : "not set", state.model.c_str());338 printHelp();339}340 341void loop() {342 FrameBuffer &fb = display.fb();343 if (fb.pixels() == nullptr) {344 delay(1000);345 return;346 }347 pollSerial();348 handleButton(external);349 handleButton(boot);350 connection.loop();351 if (connection.takeJustConnected()) fetchWeather("joined");352 takeResults();353 354 // Keep the weather fresh; after a failure wait a minute before trying again.355 const uint32_t now = millis();356 const bool stale = !state.out.weatherAt || now - state.out.weatherAt > kWeatherEveryMs;357 if (online() && state.place.valid() && stale && !state.out.busy && now - state.lastWeatherTry > kRetryMs)358 fetchWeather("refresh");359 360 const float t = now / 1000.0f;361 fb.fillScreen(pal::night);362 const bool noWifi = connection.state() == Connection::State::NoCredentials;363 switch (state.view) {364 case 0: noWifi ? drawNoWifi(fb) : w3::now(fb, state.out, state.place.valid(), t); break;365 case 1: w3::forecast(fb, state.out); break;366 case 2: w3::week(fb, state.out); break;367 case kOracleView: w3::oracleView(fb, state.out, state.aiReady, state.model, t); break;368 default: noWifi ? drawNoWifi(fb) : views::status(fb, connection, t); break;369 }370 const char *title = state.view < kOracleView ? "Weather" : state.view == kOracleView ? "Bench" : "Wi-Fi";371 w3::header(fb, title, kViewNames[state.view], state.view, kViews, state.place, connection.state());372 w3::footer(fb, state.view == kOracleView ? "click: view double: new haiku" : "click: view double: refresh hold: oracle",373 state.out);374 display.push();375}
// Wi-Fi lab W3: internet & AI. uv run pio run -d labs/wifi-lab-w3 -e wifi-lab-w3 -t upload
// The board becomes an internet client: it fetches the weather over HTTPS as JSON (Open-Meteo, no
// key needed), draws it, and asks an AI model to turn the moment into a haiku or to answer your
// questions with the weather in mind. The answer picks the LED colour too. The AI goes through a
// LiteLLM gateway (esp-labs/apps/ai-gateway), so any provider and model works.
//
// Wiring: the screen from lesson 03. The push button on GPIO 5 is optional: it does exactly what
// BOOT does. Wi-Fi: the network saved by W1 or W2 (same NVS namespace); join one there first.
// Views: now · forecast · week · oracle · status
// Button or BOOT: click = next view · double-click = refresh weather (oracle view: new haiku)
// long press = ask the oracle from any view
// Serial: city <name> | weather | oracle | ask <question> | ai | ai url <url> | ai key <key> |
// ai key forget | ai model <name> | led off | view <1-5> | status | ping [ip] | tz <TZ> |
// reconnect | forget | help
#include <Arduino.h>
#include <ArduinoJson.h>
#include <WiFi.h>
#include "button.h"
#include "color.h"
#include "connection.h"
#include "display.h"
#include "pinger.h"
#include "pins.h"
#include "settings.h"
#include "views.h"
#include "w3_views.h"
#include "worker.h"
namespace {
constexpr uint32_t kWeatherEveryMs = 15 * 60'000; // Open-Meteo updates its model every 15 min
constexpr uint32_t kRetryMs = 60'000; // after a failed fetch
constexpr uint32_t kOracleGapMs = 10'000; // at most one AI request per 10 s
const char *const kViewNames[] = {"now", "forecast", "week", "oracle", "status"};
constexpr int kViews = sizeof(kViewNames) / sizeof(kViewNames[0]);
constexpr int kOracleView = 3, kStatusView = 4;
Display display;
Connection connection;
Pinger pinger;
Worker worker;
Button external(PIN_BUTTON, "button");
Button boot(PIN_BOOT_BTN, "BOOT");
struct {
int view = 0;
Place place;
bool aiReady = false; // gateway address and key both saved
String model;
Worker::Outcome out; // the latest copy of the worker's results
uint32_t lastWeatherTry = 0, lastOracle = 0, seenAnswerAt = 0;
} state;
// ---- What the oracle gets to know about this moment ---------------------------------------
String context() {
JsonDocument d;
if (state.place.valid()) d["place"] = state.place.name;
struct tm lt;
if (getLocalTime(<, 0)) {
char when[32];
strftime(when, sizeof(when), "%A %d %B, %H:%M", <);
d["local_time"] = when;
}
if (state.out.weatherAt) {
const Weather &w = state.out.weather;
JsonObject o = d["weather"].to<JsonObject>();
o["now"] = weather::describe(w.code);
o["temp_c"] = serialized(String(w.temp, 1));
o["feels_like_c"] = serialized(String(w.feels, 1));
o["wind_kmh"] = int(lroundf(w.wind));
o["humidity_pct"] = w.humidity;
o["daylight"] = w.day;
if (w.hours) o["max_rain_chance_next_24h_pct"] = *std::max_element(w.hourRain, w.hourRain + w.hours);
if (w.days) o["today_min_c"] = int(lroundf(w.dayMin[0])), o["today_max_c"] = int(lroundf(w.dayMax[0]));
JsonObject b = d["bench"].to<JsonObject>();
b["board"] = "ESP32-S3 with a 1.9 inch screen";
b["chip_temp_c"] = serialized(String(temperatureRead(), 1));
b["uptime_min"] = millis() / 60'000;
b["wifi_signal_dbm"] = WiFi.RSSI();
String out;
serializeJson(d, out);
return out;
// ---- Actions ---------------------------------------------------------------------------
bool online() { return connection.state() == Connection::State::Connected; }
void setView(int v) {
state.view = (v % kViews + kViews) % kViews;
log_i("view %d: %s", state.view + 1, kViewNames[state.view]);
void fetchWeather(const char *why) {
if (!state.place.valid()) {
log_w("no city yet: type city <name>");
return;
if (!online()) {
log_w("not on Wi-Fi yet");
state.lastWeatherTry = millis();
Worker::Request r;
r.job = Worker::Job::Weather;
r.place = state.place;
if (worker.submit(r)) log_i("weather for %s (%s)", state.place.name.c_str(), why);
else log_w("busy with another request, try again in a moment");
void findCity(const String &name) {
r.job = Worker::Job::Geocode;
r.text = name;
if (worker.submit(r)) log_i("looking up '%s'...", name.c_str());
void askOracle(const String &question) {
if (!state.aiReady) {
setView(kOracleView);
log_w("set the gateway first: ai url <url> and ai key <key>");
if (state.lastOracle && millis() - state.lastOracle < kOracleGapMs) {
log_w("one question per 10 s, please");
r.job = question.isEmpty() ? Worker::Job::Oracle : Worker::Job::Ask;
r.text = question;
r.aiUrl = settings::aiUrl();
r.apiKey = settings::apiKey();
r.model = state.model;
r.context = context();
if (!worker.submit(r)) {
log_w("busy with another request, try again in a moment");
state.lastOracle = millis();
log_i("asking %s%s%s", state.model.c_str(), question.isEmpty() ? " for a haiku" : ": ", question.c_str());
// ---- Input -----------------------------------------------------------------------------
void handleButton(Button &b) {
switch (b.poll()) {
case Button::Event::Click: setView(state.view + 1); break;
case Button::Event::DoubleClick:
if (state.view == kOracleView) askOracle("");
else fetchWeather(b.name());
break;
case Button::Event::LongPress: askOracle(""); break;
case Button::Event::None: break;
void printAi() {
const String url = settings::aiUrl();
Serial.printf("AI gateway: %s | key %s | model %s\n", url.isEmpty() ? "not set" : url.c_str(),
settings::masked(settings::apiKey()).c_str(), state.model.c_str());
void refreshAiReady() { state.aiReady = !settings::aiUrl().isEmpty() && !settings::apiKey().isEmpty(); }
void printStatus() {
using State = Connection::State;
switch (connection.state()) {
case State::NoCredentials: Serial.println("No saved Wi-Fi: flash W1 or W2 once and join there (it's shared)."); 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 | %ld dBm | time %s\n", connection.ssid().c_str(), WiFi.localIP().toString().c_str(),
static_cast<long>(WiFi.RSSI()), connection.timeSynced() ? "synced" : "not yet");
Serial.printf("City: %s | weather %s\n", state.place.valid() ? state.place.name.c_str() : "not set",
w3::ago(state.out.weatherAt).c_str());
printAi();
if (!state.out.error.isEmpty()) Serial.printf("Last error: %s\n", state.out.error.c_str());
void printHelp() {
Serial.println();
Serial.println("Commands: city <name> | weather | oracle | ask <question> | view <1-5> | status | led off");
Serial.println(" ai (show) | ai url http://<gateway>:4000 | ai key <key> | ai key forget");
Serial.println(" ai model <name> (a model_name from ai-gateway/config.yaml, default " + String(oracle::kDefaultModel) + ")");
Serial.println(" ping [ip] | tz <TZ> | reconnect | forget | help");
Serial.println("Button (GPIO 5, optional) or BOOT: click = next view, double-click = refresh (oracle view: new haiku),");
Serial.println(" long press = ask the oracle");
void handleCommand(const String &raw) {
String line = raw;
line.trim();
String lower = line;
lower.toLowerCase();
if (lower.isEmpty()) return;
if (lower.startsWith("city ")) return findCity(line.substring(5));
if (lower == "weather") return fetchWeather("serial");
if (lower == "oracle") return askOracle("");
if (lower.startsWith("ask ")) return askOracle(line.substring(4, 164));
if (lower == "ai") return printAi();
if (lower.startsWith("ai url ")) {
String url = line.substring(7);
url.trim();
if (!url.startsWith("http://") && !url.startsWith("https://")) {
log_w("the gateway address starts with http:// or https://");
settings::saveString("url", url);
refreshAiReady();
log_i("AI gateway: %s", url.c_str());
if (lower == "ai key forget") {
settings::saveString("key", "");
log_i("AI key erased from the chip");
if (lower.startsWith("ai key ")) {
String key = line.substring(7);
key.trim();
settings::saveString("key", key); // as typed: keys are case-sensitive
log_i("AI key saved: %s", settings::masked(key).c_str());
if (lower.startsWith("ai model ")) {
state.model = line.substring(9);
state.model.trim();
settings::saveString("model", state.model);
log_i("model: %s", state.model.c_str());
if (lower == "led off") return rgbLedWrite(PIN_RGB, 0, 0, 0);
if (lower == "status") return printStatus();
if (lower == "forget") return connection.forget();
if (lower == "reconnect") return connection.connect();
if (lower.startsWith("tz ")) return connection.setTimezone(line.substring(3));
if (lower == "ping" || lower.startsWith("ping ")) {
IPAddress target = WiFi.gatewayIP();
if (!online()) log_w("ping needs a network");
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.startsWith("view ")) {
const long v = lower.substring(5).toInt();
if (v < 1 || v > kViews) {
log_w("view needs 1-%d", kViews);
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()) handleCommand(buffer);
buffer = "";
} else if (buffer.length() < 240) { // API keys are ~110 characters
buffer += c;
// ---- Results from the worker ----------------------------------------------------------------
void takeResults() {
if (!worker.update(state.out)) return;
if (state.out.placeChanged) {
state.place = state.out.place;
settings::savePlace(state.place);
log_i("city set: %s (%.3f, %.3f)", state.place.name.c_str(), state.place.lat, state.place.lon);
setView(0);
fetchWeather("new city");
if (state.out.answerAt && state.out.answerAt != state.seenAnswerAt) {
state.seenAnswerAt = state.out.answerAt;
const OracleAnswer &a = state.out.answer;
rgbLedWrite(PIN_RGB, a.r / 4, a.g / 4, a.b / 4); // a quarter: the LED is very bright
log_i("oracle: \"%s\" (%u lines, %lu > %lu tokens)", a.title.c_str(), unsigned(a.lineCount),
static_cast<unsigned long>(a.inputTokens), static_cast<unsigned long>(a.outputTokens));
for (int i = 0; i < a.lineCount; i++) Serial.printf(" %s\n", a.lines[i].c_str());
void drawNoWifi(FrameBuffer &fb) {
fb.setFont(&FreeSans9pt7b);
fb.setTextColor(pal::ink);
fb.setCursor(8, 56);
fb.print("No saved Wi-Fi network");
const char *lines[] = {"W3 uses the network W1 or W2 saved.", "Flash one of them, join, then come back:",
" uv run pio run -d labs/wifi-lab-w1 -e wifi-lab-w1 -t upload"};
w3::hint(fb, 72, lines, 3);
} // namespace
void setup() {
Serial.begin(115200);
delay(1500);
if (!display.begin()) {
log_e("No memory for the frame buffer. Stopping.");
rgbLedWrite(PIN_RGB, 0, 0, 0);
external.begin();
boot.begin();
WiFi.mode(WIFI_STA);
state.place = settings::loadPlace();
state.model = settings::model();
worker.begin();
connection.begin();
log_i("wifi-lab-w3: city %s, AI gateway %s, model %s", state.place.valid() ? state.place.name.c_str() : "not set",
state.aiReady ? "set" : "not set", state.model.c_str());
printHelp();
void loop() {
FrameBuffer &fb = display.fb();
if (fb.pixels() == nullptr) {
delay(1000);
pollSerial();
handleButton(external);
handleButton(boot);
connection.loop();
if (connection.takeJustConnected()) fetchWeather("joined");
takeResults();
// Keep the weather fresh; after a failure wait a minute before trying again.
const uint32_t now = millis();
const bool stale = !state.out.weatherAt || now - state.out.weatherAt > kWeatherEveryMs;
if (online() && state.place.valid() && stale && !state.out.busy && now - state.lastWeatherTry > kRetryMs)
fetchWeather("refresh");
const float t = now / 1000.0f;
fb.fillScreen(pal::night);
const bool noWifi = connection.state() == Connection::State::NoCredentials;
switch (state.view) {
case 0: noWifi ? drawNoWifi(fb) : w3::now(fb, state.out, state.place.valid(), t); break;
case 1: w3::forecast(fb, state.out); break;
case 2: w3::week(fb, state.out); break;
case kOracleView: w3::oracleView(fb, state.out, state.aiReady, state.model, t); break;
default: noWifi ? drawNoWifi(fb) : views::status(fb, connection, t); break;
const char *title = state.view < kOracleView ? "Weather" : state.view == kOracleView ? "Bench" : "Wi-Fi";
w3::header(fb, title, kViewNames[state.view], state.view, kViews, state.place, connection.state());
w3::footer(fb, state.view == kOracleView ? "click: view double: new haiku" : "click: view double: refresh hold: oracle",
state.out);
display.push();
New word #include
#include
Pastes another file in here, so this file can use what it declares.
PlatformIO environment wifi-lab-w3 includes C++ source files covering HTTPS client, TLS certificates, JSON + filters, REST APIs, AI function calling, LLM gateway (LiteLLM), worker tasks.