// Week 14 - Interface & Application Programming // MKR WiFi 1010 + IoT Carrier: HTTP server that // - reports sensor readings (temperature, humidity, pressure, light, acceleration) // - shows a chosen sensor on the carrier display // - runs LED/text scripts (from the SD card or sent by the app) // Libraries: WiFiNINA, Arduino_MKRIoTCarrier (Library Manager). SD comes with the carrier lib. // // Endpoints // GET /sensors JSON with all sensor readings // POST /show?what=X display X on the board: none|temperature|humidity|pressure|light // GET /files list .FAB files on SD (/files?all=1 lists EVERYTHING, for debugging) // GET /file?name=X read a file // POST /run?name=X run a file from SD // POST /runtext run the script sent in the request body (no SD needed) // POST /save?name=X write the request body to SD as X (overwrites) // POST /stop stop // POST /pause toggle pause / resume // POST /brightness?v=N LED brightness 0-100 % // GET /status JSON: state, file, last, sd, paused, brightness, show #include #include #include #include #include "arduino_secrets.h" // SECRET_SSID, SECRET_PASS MKRIoTCarrier carrier; WiFiServer server(80); // ---- script runner state ---- String script; unsigned int pos = 0; bool running = false; bool paused = false; bool sdOk = false; String current = ""; // name of running script ("(memory)" if sent by app) String lastEvent = "none"; // finished / app String lastText = ""; unsigned long waitUntil = 0; unsigned long pausedRemaining = 0; int brightness = 100; // percent int cr = 0, cg = 0, cb = 0; // current LED colour (before brightness scaling) // ---- sensors ---- float temp = 0, hum = 0, pres = 0; // C, %, hPa int lr = 0, lg = 0, lb = 0; // light colour channels float ax = 0, ay = 0, az = 0; // acceleration (g) String showMode = "none"; // which reading the display shows unsigned long lastShow = 0; // ---------- output helpers ---------- void applyLeds() { for (int i = 0; i < 5; i++) carrier.leds.setPixelColor(i, cr * brightness / 100, cg * brightness / 100, cb * brightness / 100); carrier.leds.show(); } void setAll(int r, int g, int b) { cr = r; cg = g; cb = b; applyLeds(); } void setBrightness(int v) { brightness = constrain(v, 0, 100); applyLeds(); } // Centred text; picks size 3 if it fits on one line, else size 2. void showText(const String &t, uint16_t colour = ST77XX_WHITE) { int size = (t.length() * 18 <= 220) ? 3 : 2; int w = t.length() * 6 * size; int x = (w < 240) ? (240 - w) / 2 : 0; carrier.display.fillScreen(ST77XX_BLACK); carrier.display.setTextColor(colour); carrier.display.setTextSize(size); carrier.display.setCursor(x, 100); carrier.display.print(t); } void showReading(const String &label, const String &value) { showText(value, ST77XX_GREEN); int x = (240 - (int)label.length() * 12) / 2; carrier.display.setTextSize(2); carrier.display.setTextColor(ST77XX_CYAN); carrier.display.setCursor(x < 0 ? 0 : x, 140); carrier.display.print(label); } // ---------- sensors ---------- void readSensors() { temp = carrier.Env.readTemperature(); hum = carrier.Env.readHumidity(); pres = carrier.Pressure.readPressure() * 10.0; // kPa -> hPa if (carrier.Light.colorAvailable()) carrier.Light.readColor(lr, lg, lb); if (carrier.IMUmodule.accelerationAvailable()) carrier.IMUmodule.readAcceleration(ax, ay, az); } String sensorsJson() { readSensors(); return String("{\"temperature\":") + String(temp, 1) + ",\"humidity\":" + String(hum, 1) + ",\"pressure\":" + String(pres, 1) + ",\"light\":" + String((lr + lg + lb) / 3) + ",\"ax\":" + String(ax, 2) + ",\"ay\":" + String(ay, 2) + ",\"az\":" + String(az, 2) + "}"; } // Keeps the chosen reading on the display (only while no script is running) void updateDisplay() { if (running || showMode == "none" || millis() - lastShow < 1000) return; lastShow = millis(); readSensors(); if (showMode == "temperature") showReading("Temperature", String(temp, 1) + " C"); else if (showMode == "humidity") showReading("Humidity", String(hum, 0) + " %"); else if (showMode == "pressure") showReading("Pressure", String(pres, 0) + " hPa"); else if (showMode == "light") showReading("Light", String((lr + lg + lb) / 3)); } // ---------- script runner ---------- void startScript(const String &s, const String &name) { script = s; pos = 0; waitUntil = 0; current = name; running = true; paused = false; lastEvent = "none"; } bool startRun(const String &name) { File f = SD.open(name.c_str()); if (!f) return false; String s = ""; while (f.available() && s.length() < 2000) s += (char)f.read(); f.close(); startScript(s, name); return true; } void stopRun(const String &why) { running = false; paused = false; lastEvent = why; setAll(0, 0, 0); showText("Stopped: " + why, ST77XX_RED); lastShow = millis(); // let the message stay for a second before sensor display resumes } void togglePause() { if (!running) return; if (!paused) { paused = true; pausedRemaining = (waitUntil > millis()) ? waitUntil - millis() : 0; showText("Paused", ST77XX_YELLOW); } else { paused = false; waitUntil = millis() + pausedRemaining; if (lastText.length()) showText(lastText); } } void stepScript() { if (!running || paused || millis() < waitUntil) return; while (running) { if (pos >= script.length()) { stopRun("finished"); return; } int e = script.indexOf('\n', pos); if (e < 0) e = script.length(); String line = script.substring(pos, e); pos = e + 1; line.trim(); if (line.length() == 0 || line[0] == '#') continue; if (line.startsWith("TEXT ")) { lastText = line.substring(5); showText(lastText); } else if (line.startsWith("COLOR ")) { int r = 0, g = 0, b = 0; sscanf(line.c_str() + 6, "%d %d %d", &r, &g, &b); setAll(r, g, b); } else if (line.startsWith("WAIT ")) { waitUntil = millis() + line.substring(5).toInt(); return; } else if (line == "LOOP") { pos = 0; return; } // return so the main loop keeps serving } } // ---------- HTTP ---------- void reply(WiFiClient &c, int code, const String &type, const String &body) { c.print("HTTP/1.1 "); c.print(code); c.println(code == 200 ? " OK" : " Error"); c.print("Content-Type: "); c.println(type); c.print("Content-Length: "); c.println(body.length()); c.println("Connection: close"); c.println(); c.print(body); } String queryParam(const String &path, const String &key) { // ?key=value (first match) int i = path.indexOf(key + "="); if (i < 0) return ""; String v = path.substring(i + key.length() + 1); int amp = v.indexOf('&'); if (amp >= 0) v = v.substring(0, amp); return v; } void handleClient() { WiFiClient c = server.available(); if (!c) return; unsigned long t0 = millis(); String req = c.readStringUntil('\n'); // request line int contentLength = 0; while (c.connected() && millis() - t0 < 2000) { // headers String h = c.readStringUntil('\n'); h.trim(); if (h.length() == 0) break; String hl = h; hl.toLowerCase(); if (hl.startsWith("content-length:")) contentLength = h.substring(15).toInt(); } String body = ""; // body (if any) if (contentLength > 2000) contentLength = 2000; while ((int)body.length() < contentLength && millis() - t0 < 3000) { if (c.available()) body += (char)c.read(); } int s1 = req.indexOf(' '), s2 = req.indexOf(' ', s1 + 1); String method = req.substring(0, s1); String path = req.substring(s1 + 1, s2); if (path.startsWith("/sensors")) { reply(c, 200, "application/json", sensorsJson()); } else if (method == "POST" && path.startsWith("/show")) { String w = queryParam(path, "what"); if (w == "none" || w == "temperature" || w == "humidity" || w == "pressure" || w == "light") { showMode = w; lastShow = 0; if (w == "none" && !running) { carrier.display.fillScreen(ST77XX_BLACK); } reply(c, 200, "text/plain", w); } else reply(c, 400, "text/plain", "use none|temperature|humidity|pressure|light"); } else if (path.startsWith("/files")) { bool all = path.indexOf("all=1") >= 0; String out = ""; File root = SD.open("/"); if (!root) { reply(c, 500, "text/plain", "SD not readable"); c.stop(); return; } while (true) { File f = root.openNextFile(); if (!f) break; String n = String(f.name()); String u = n; u.toUpperCase(); if (all) out += n + (f.isDirectory() ? "/" : "") + "\n"; else if (!f.isDirectory() && u.endsWith(".FAB")) out += n + "\n"; f.close(); } root.close(); reply(c, 200, "text/plain", out); } else if (path.startsWith("/file")) { File f = SD.open(queryParam(path, "name").c_str()); if (!f) reply(c, 404, "text/plain", "not found"); else { String out = ""; while (f.available() && out.length() < 2000) out += (char)f.read(); f.close(); reply(c, 200, "text/plain", out); } } else if (method == "POST" && path.startsWith("/runtext")) { // must be before /run startScript(body, "(memory)"); reply(c, 200, "text/plain", "started"); } else if (method == "POST" && path.startsWith("/run")) { if (startRun(queryParam(path, "name"))) reply(c, 200, "text/plain", "started"); else reply(c, 404, "text/plain", "not found on SD"); } else if (method == "POST" && path.startsWith("/save")) { String name = queryParam(path, "name"); if (!sdOk) reply(c, 500, "text/plain", "no SD card"); else if (name.length() == 0 || name.length() > 12) reply(c, 400, "text/plain", "bad name (use 8.3)"); else { SD.remove(name.c_str()); File f = SD.open(name.c_str(), FILE_WRITE); if (!f) reply(c, 500, "text/plain", "could not open file for writing"); else { f.print(body); f.close(); reply(c, 200, "text/plain", "saved"); } } } else if (method == "POST" && path.startsWith("/stop")) { stopRun("app"); reply(c, 200, "text/plain", "stopped"); } else if (method == "POST" && path.startsWith("/pause")) { togglePause(); reply(c, 200, "text/plain", paused ? "paused" : "resumed"); } else if (method == "POST" && path.startsWith("/brightness")) { String v = queryParam(path, "v"); if (v.length() == 0) reply(c, 400, "text/plain", "use ?v=0..100"); else { setBrightness(v.toInt()); reply(c, 200, "text/plain", String(brightness)); } } else if (path.startsWith("/status")) { String j = String("{\"state\":\"") + (running ? "running" : "idle") + "\",\"file\":\"" + current + "\",\"last\":\"" + lastEvent + "\",\"sd\":" + (sdOk ? "true" : "false") + ",\"paused\":" + (paused ? "true" : "false") + ",\"brightness\":" + brightness + ",\"show\":\"" + showMode + "\"}"; reply(c, 200, "application/json", j); } else reply(c, 404, "text/plain", "unknown endpoint"); c.stop(); } // ---------- setup / loop ---------- // Fallback access point: join this WiFi from the laptop, then use IP 192.168.4.1 #define AP_SSID "CarrierRunner" #define AP_PASS "fabacademy" // must be 8+ characters bool connectWiFi() { for (int attempt = 1; attempt <= 4; attempt++) { Serial.print("Attempt "); Serial.print(attempt); Serial.print(" joining '"); Serial.print(SECRET_SSID); Serial.println("'"); showText("WiFi " + String(attempt) + "/4"); WiFi.begin(SECRET_SSID, SECRET_PASS); unsigned long t0 = millis(); while (WiFi.status() != WL_CONNECTED && millis() - t0 < 10000) delay(250); Serial.print(" status = "); Serial.println(WiFi.status()); // 3 = connected if (WiFi.status() == WL_CONNECTED) return true; WiFi.disconnect(); } return false; } void setup() { Serial.begin(115200); unsigned long t = millis(); while (!Serial && millis() - t < 3000) {} // wait up to 3 s for the serial monitor carrier.noCase(); carrier.begin(); carrier.display.fillScreen(ST77XX_BLACK); showText("Starting"); sdOk = SD.begin(SD_CS); Serial.println(sdOk ? "SD ok" : "SD FAILED"); if (WiFi.status() == WL_NO_MODULE) { Serial.println("No WiFi module!"); showText("No WiFi chip", ST77XX_RED); while (true) {} } Serial.print("WiFi firmware: "); Serial.print(WiFi.firmwareVersion()); Serial.print(" (latest: "); Serial.print(WIFI_FIRMWARE_LATEST_VERSION); Serial.println(")"); bool apMode = false; if (!connectWiFi()) { Serial.println("Router connection failed, starting access point"); WiFi.end(); if (WiFi.beginAP(AP_SSID, AP_PASS) != WL_AP_LISTENING) { showText("AP failed", ST77XX_RED); while (true) {} } apMode = true; } server.begin(); IPAddress ip = WiFi.localIP(); Serial.print("IP: "); Serial.println(ip); showText(ip.toString(), ST77XX_GREEN); // type this into the app carrier.display.setTextSize(2); carrier.display.setTextColor(sdOk ? ST77XX_GREEN : ST77XX_RED); carrier.display.setCursor(sdOk ? 90 : 84, 150); carrier.display.print(sdOk ? "SD ok" : "NO SD"); if (apMode) { carrier.display.setTextColor(ST77XX_YELLOW); carrier.display.setCursor(30, 180); carrier.display.print("AP: " AP_SSID); } } void loop() { stepScript(); updateDisplay(); handleClient(); }