// After the Beep — Arduino UNO R4 WiFi + 16x2 LCD (LCM1602C) + 3 buttons. // // Libraries (Arduino IDE > Library Manager): ArduinoJson (v7), LiquidCrystal. // WiFiS3, EEPROM and Arduino_LED_Matrix come with the UNO R4 board package. // // Copy arduino_secrets.h.example to arduino_secrets.h and fill in your WiFi details. // If the LED matrix shows things upside down, add #define FLIP_MATRIX 1 to that file. // // Wiring // LCD RS D12, E D11, D4 D5, D5 D4, D6 D3, D7 D2, RW + VSS + K to GND, VDD to 5V, // V0 to the middle leg of a 10k pot (outer legs 5V/GND), A to 5V through 220 ohm. // Buttons (each between the pin and GND, no resistors): PREV D6, NEXT D7, SELECT D8. // // Buttons // NEXT / PREV browse messages (newest first) // SELECT open the newest unread message, or go back home // hold SELECT delete the message on screen (asks to confirm) // hold SELECT while powering on: forget this board's pairing and get a new code #include #include #include #include #include "Arduino_LED_Matrix.h" #include "arduino_secrets.h" #ifndef FLIP_MATRIX #define FLIP_MATRIX 0 #endif // Types come before any function: the Arduino IDE puts its generated prototypes there. struct Message { long id; char from[17]; char body[121]; bool read; bool anim; // has an animation for the LED matrix, fetched when opened }; enum Screen { HOME, VIEW, CONFIRM_DELETE, PAIRING, OFFLINE, TOO_LARGE }; enum Press { NONE, SHORT, LONG }; // ---------- hardware ---------- LiquidCrystal lcd(12, 11, 5, 4, 3, 2); ArduinoLEDMatrix matrix; const uint8_t PIN_PREV = 6; const uint8_t PIN_NEXT = 7; const uint8_t PIN_SELECT = 8; const uint32_t ENVELOPE[3] = { 0xFFFC03A0, 0x59098F18, 0x01801FFF }; const uint32_t BLANK[3] = { 0, 0, 0 }; // ---------- timing ---------- const unsigned long POLL_MS = 15000; // check for new messages const unsigned long PAIR_POLL_MS = 5000; // check faster while waiting to be paired const unsigned long SCROLL_MS = 350; // marquee step const unsigned long READ_AFTER_MS = 2000; // a message counts as read after this long on screen const unsigned long IDLE_MS = 45000; // go home after this long without a button press const unsigned long RESTING_SWAP_MS = 5000; // swaps between the message count and the number const unsigned long LONG_PRESS_MS = 800; const unsigned long DEBOUNCE_MS = 25; // ---------- identity (saved in EEPROM) ---------- const int EE_MAGIC = 0, EE_ID = 4, EE_SECRET = 40; const char MAGIC[4] = { 'A', 'M', '0', '1' }; char deviceId[37] = ""; char deviceSecret[37] = ""; bool loadIdentity() { for (int i = 0; i < 4; i++) if (EEPROM.read(EE_MAGIC + i) != MAGIC[i]) return false; for (int i = 0; i < 36; i++) { deviceId[i] = EEPROM.read(EE_ID + i); deviceSecret[i] = EEPROM.read(EE_SECRET + i); } deviceId[36] = deviceSecret[36] = '\0'; return true; } void saveIdentity(const char* id, const char* secret) { strncpy(deviceId, id, 36); strncpy(deviceSecret, secret, 36); deviceId[36] = deviceSecret[36] = '\0'; for (int i = 0; i < 36; i++) { EEPROM.update(EE_ID + i, deviceId[i]); EEPROM.update(EE_SECRET + i, deviceSecret[i]); } for (int i = 0; i < 4; i++) EEPROM.update(EE_MAGIC + i, MAGIC[i]); } void forgetIdentity() { for (int i = 0; i < 4; i++) EEPROM.update(EE_MAGIC + i, 0); deviceId[0] = deviceSecret[0] = '\0'; } // ---------- messages ---------- const int MAX_MESSAGES = 20; Message messages[MAX_MESSAGES]; int messageCount = 0; int unreadCount = 0; bool paired = false; char pairCode[8] = ""; char boxName[33] = ""; char boxNumber[8] = ""; // Messages marked read on the board but not yet told to the server. They go out with the next // poll instead of right away, so the text isn't frozen by a network call while it scrolls. long pendingReads[MAX_MESSAGES]; int pendingReadCount = 0; // ---------- animation for the message on screen ---------- const int MAX_ANIM_FRAMES = 64; uint32_t animFrames[MAX_ANIM_FRAMES][4]; // 3 words of pixels + duration in ms int animCount = 0; long animFor = 0; // message id the frames belong to bool animPlaying = false; uint32_t shownFrame[3] = { 1, 1, 1 }; // last still picture sent to the matrix // ---------- screen state ---------- Screen screen = OFFLINE; int current = 0; // index into messages while viewing unsigned long viewStartedAt = 0; unsigned long lastInputAt = 0; unsigned long lastPollAt = 0; bool pollNow = true; int scrollOffset = 0; unsigned long lastScrollAt = 0; String lastDrawn[2]; // ---------- buttons ---------- struct Button { uint8_t pin; bool down = false; bool lastRaw = false; unsigned long changedAt = 0; unsigned long downAt = 0; bool longFired = false; Press update() { bool raw = digitalRead(pin) == LOW; unsigned long now = millis(); if (raw != lastRaw) { lastRaw = raw; changedAt = now; } if (now - changedAt < DEBOUNCE_MS || raw == down) { if (down && !longFired && now - downAt >= LONG_PRESS_MS) { longFired = true; return LONG; } return NONE; } down = raw; if (down) { downAt = now; longFired = false; return NONE; } return longFired ? NONE : SHORT; // released before the long-press fired } }; Button btnPrev{ PIN_PREV }, btnNext{ PIN_NEXT }, btnSelect{ PIN_SELECT }; // ---------- network ---------- // HTTPS is spoken by hand rather than through ArduinoHttpClient: that library only spots a // "Content-Length" header written in exactly that case, and Vercel sends headers in lowercase // (or chunked), so it waited out a 1 s read timeout after every response and couldn't keep the // connection open. Each TLS handshake through the WiFi chip costs a second or more too. WiFiSSLClient ssl; unsigned long sslUsedAt = 0; const unsigned long KEEP_ALIVE_MS = 4000; // reuse the connection only while the server surely still holds it const unsigned long HTTP_TIMEOUT_MS = 10000; const unsigned int MAX_BODY = 8192; const int TOO_BIG = -2; // request(): the reply didn't fit in MAX_BODY bool bodyOverflow = false; void showStatus(const char* line1, const char* line2) { lcd.clear(); lcd.setCursor(0, 0); lcd.print(line1); lcd.setCursor(0, 1); lcd.print(line2); lastDrawn[0] = lastDrawn[1] = ""; } // One try of up to 10 s per poll, so the buttons are only ever stuck that long while the // WiFi is down; the next poll tries again. Messages already on the board stay readable. bool ensureWifi() { if (WiFi.status() == WL_CONNECTED) return true; if (screen != VIEW && screen != CONFIRM_DELETE) showStatus("Connecting WiFi", SECRET_SSID); WiFi.begin(SECRET_SSID, SECRET_PASS); for (int i = 0; i < 20 && WiFi.status() != WL_CONNECTED; i++) delay(500); return WiFi.status() == WL_CONNECTED; } // Reads one header line (CRLF dropped, cut to `size`). False on timeout or a dropped connection. bool readLine(char* buf, size_t size, unsigned long startedAt) { size_t n = 0; while (millis() - startedAt < HTTP_TIMEOUT_MS) { int c = ssl.read(); if (c < 0) { if (!ssl.connected() && !ssl.available()) return false; continue; } if (c == '\n') { buf[n] = '\0'; return true; } if (c != '\r' && n + 1 < size) buf[n++] = (char)c; } return false; } // Appends exactly `len` body bytes (len < 0: until the server closes). False on timeout. bool readBody(long len, String& body, unsigned long startedAt) { char buf[128]; while (len != 0 && millis() - startedAt < HTTP_TIMEOUT_MS) { int want = len < 0 || len > (long)sizeof(buf) ? sizeof(buf) : len; int got = ssl.read((uint8_t*)buf, want); if (got <= 0) { if (!ssl.connected() && !ssl.available()) return len < 0; continue; } if (body.length() + got <= MAX_BODY) body.concat(buf, got); else bodyOverflow = true; // keep reading so the connection stays usable, but report it if (len > 0) len -= got; } return len == 0; } bool startsWithNoCase(const char* s, const char* prefix) { return strncasecmp(s, prefix, strlen(prefix)) == 0; } bool containsNoCase(const char* s, const char* word) { for (; *s; s++) if (startsWithNoCase(s, word)) return true; return false; } // One request/response over the open connection. Returns the HTTP status, or -1. int exchange(const char* method, const char* path, const char* json, String& body) { // One write for the whole request: every write is a separate trip to the WiFi chip. char head[400]; int n = snprintf(head, sizeof(head), "%s %s HTTP/1.1\r\nHost: " SERVER_HOST "\r\nUser-Agent: AnsweringMachine\r\nConnection: keep-alive\r\n", method, path); if (deviceId[0]) n += snprintf(head + n, sizeof(head) - n, "X-Device-Id: %s\r\nX-Device-Secret: %s\r\n", deviceId, deviceSecret); if (json) n += snprintf(head + n, sizeof(head) - n, "Content-Type: application/json\r\n"); if (json || strcmp(method, "POST") == 0) n += snprintf(head + n, sizeof(head) - n, "Content-Length: %u\r\n", json ? strlen(json) : 0); n += snprintf(head + n, sizeof(head) - n, "\r\n"); if (n >= (int)sizeof(head)) return -1; if (ssl.write((const uint8_t*)head, n) != (size_t)n) return -1; if (json && ssl.write((const uint8_t*)json, strlen(json)) != strlen(json)) return -1; unsigned long startedAt = millis(); bodyOverflow = false; char line[96]; int status = 0; long length = -1; bool chunked = false, closes = false; do { // skip any "100 Continue" if (!readLine(line, sizeof(line), startedAt)) return -1; const char* sp = strchr(line, ' '); status = sp ? atoi(sp + 1) : 0; if (status <= 0) return -1; while (true) { if (!readLine(line, sizeof(line), startedAt)) return -1; if (!line[0]) break; if (startsWithNoCase(line, "content-length:")) length = atol(line + 15); else if (startsWithNoCase(line, "transfer-encoding:") && containsNoCase(line, "chunked")) chunked = true; else if (startsWithNoCase(line, "connection:") && containsNoCase(line, "close")) closes = true; } } while (status >= 100 && status < 200); bool ok; if (strcmp(method, "HEAD") == 0 || status == 204 || status == 304) ok = true; else if (chunked) { ok = false; while (readLine(line, sizeof(line), startedAt)) { long size = strtol(line, nullptr, 16); if (size == 0) { // last chunk, then optional trailers up to a blank line while (readLine(line, sizeof(line), startedAt) && line[0]) {} ok = true; break; } if (!readBody(size, body, startedAt) || !readLine(line, sizeof(line), startedAt)) break; } } else if (length >= 0) ok = readBody(length, body, startedAt); else { ok = readBody(-1, body, startedAt); closes = true; } if (!ok) return -1; if (closes) ssl.stop(); return bodyOverflow ? TOO_BIG : status; } // Sends one request; fills `body` and returns the HTTP status (negative on network errors). // Back-to-back requests share one TLS connection; a stale one is retried on a fresh connection. int request(const char* method, const char* path, const char* json, String& body) { for (int attempt = 0; attempt < 2; attempt++) { body = ""; bool reused = attempt == 0 && millis() - sslUsedAt < KEEP_ALIVE_MS && ssl.connected(); if (!reused) { ssl.stop(); if (!ssl.connect(SERVER_HOST, 443)) return -1; } int status = exchange(method, path, json, body); if (status > 0 || status == TOO_BIG) { sslUsedAt = millis(); return status; } ssl.stop(); sslUsedAt = 0; if (!reused) return status; } return -1; } bool registerDevice() { showStatus("Registering...", ""); String body; if (request("POST", "/api/device/register", nullptr, body) != 200) return false; JsonDocument doc; if (deserializeJson(doc, body)) return false; const char* id = doc["id"]; const char* secret = doc["secret"]; if (!id || !secret || strlen(id) != 36 || strlen(secret) != 36) return false; saveIdentity(id, secret); strncpy(pairCode, doc["code"] | "", sizeof(pairCode) - 1); return true; } void poll() { lastPollAt = millis(); pollNow = false; if (!ensureWifi()) { screen = OFFLINE; return; } if (!deviceId[0] && !registerDevice()) { screen = OFFLINE; return; } flushReads(); String body; int status = request("GET", "/api/device/state", nullptr, body); if (status == 401 && body.indexOf("unknown device") >= 0) { // The owner removed this board in the web app: start over with a new pairing code. Only // our own server's answer counts; a 401 from anything in between keeps the pairing. forgetIdentity(); pendingReadCount = 0; pollNow = true; return; } if (status != 200) { if (screen != VIEW && screen != CONFIRM_DELETE) screen = status == TOO_BIG ? TOO_LARGE : OFFLINE; return; } JsonDocument doc; if (deserializeJson(doc, body)) { if (screen != VIEW && screen != CONFIRM_DELETE) screen = TOO_LARGE; return; } paired = doc["paired"] | false; if (!paired) { strncpy(pairCode, doc["code"] | "", sizeof(pairCode) - 1); screen = PAIRING; messageCount = unreadCount = 0; return; } strncpy(boxName, doc["name"] | "", sizeof(boxName) - 1); strncpy(boxNumber, doc["number"] | "", sizeof(boxNumber) - 1); long viewingId = (screen == VIEW || screen == CONFIRM_DELETE) && current < messageCount ? messages[current].id : 0; JsonArray list = doc["messages"]; messageCount = 0; unreadCount = 0; for (JsonObject m : list) { if (messageCount >= MAX_MESSAGES) break; Message& msg = messages[messageCount]; msg.id = m["id"]; strncpy(msg.from, m["from"] | "", sizeof(msg.from) - 1); msg.from[sizeof(msg.from) - 1] = '\0'; strncpy(msg.body, m["body"] | "", sizeof(msg.body) - 1); msg.body[sizeof(msg.body) - 1] = '\0'; msg.read = (m["read"] | false) || isPendingRead(msg.id); msg.anim = m["anim"] | false; if (!msg.read) unreadCount++; messageCount++; } // Keep showing the same message even if new ones arrived above it. if (viewingId) { int found = -1; for (int i = 0; i < messageCount; i++) if (messages[i].id == viewingId) found = i; if (found < 0) screen = HOME; else current = found; } else if (screen == PAIRING || screen == OFFLINE || screen == TOO_LARGE) { screen = HOME; } prefetchAnim(); } // Returns the HTTP status, or a negative number when the server couldn't be reached. int sendAction(long id, const char* action) { if (WiFi.status() != WL_CONNECTED) return -1; char json[64]; snprintf(json, sizeof(json), "{\"id\":%ld,\"action\":\"%s\"}", id, action); String body; return request("POST", "/api/device/action", json, body); } bool isPendingRead(long id) { for (int i = 0; i < pendingReadCount; i++) if (pendingReads[i] == id) return true; return false; } void queueRead(long id) { if (isPendingRead(id)) return; if (pendingReadCount == MAX_MESSAGES) { // full: drop the oldest memmove(pendingReads, pendingReads + 1, sizeof(pendingReads[0]) * (MAX_MESSAGES - 1)); pendingReadCount--; } pendingReads[pendingReadCount++] = id; } // Did the server take the action? A 4xx won't change on a retry (say, the message was deleted // on the web), so it's dropped too; network errors and 5xx wait for the next poll. bool settled(int status) { return status >= 200 && status < 500; } // Tells the server about queued reads; the ones it couldn't be reached for wait for the next poll. void flushReads() { int sent = 0; while (sent < pendingReadCount && settled(sendAction(pendingReads[sent], "read"))) sent++; memmove(pendingReads, pendingReads + sent, sizeof(pendingReads[0]) * (pendingReadCount - sent)); pendingReadCount -= sent; } // Copies a frame's pixels, turned 180° when FLIP_MATRIX is set. void orient(const uint32_t* in, uint32_t* out) { uint32_t turned[3]; for (int k = 0; k < 3; k++) { turned[k] = FLIP_MATRIX ? __RBIT(in[2 - k]) : in[k]; // reversing all 96 bits rotates the picture 180° } memcpy(out, turned, sizeof(turned)); } // Fetches a message's animation: one "w0 w1 w2 ms" line per frame (hex words). // Returns false when the server couldn't be reached, so a prefetch can be retried later. bool loadAnim(long id) { animFor = id; // even on failure, so a broken animation isn't retried every loop animCount = 0; if (WiFi.status() != WL_CONNECTED) return false; char path[48]; snprintf(path, sizeof(path), "/api/device/anim?id=%ld", id); String body; int status = request("GET", path, nullptr, body); if (status != 200) return status > 0; const char* p = body.c_str(); while (*p && animCount < MAX_ANIM_FRAMES) { char* end; uint32_t* f = animFrames[animCount]; for (int k = 0; k < 3; k++) { f[k] = strtoul(p, &end, 16); p = end; } f[3] = strtoul(p, &end, 10); if (end == p) break; orient(f, f); p = end; while (*p == '\n' || *p == '\r' || *p == ' ') p++; animCount++; } return true; } // On the home screen, fetches the animation of the message SELECT would open, so opening it // starts playing at once instead of waiting on the network. void prefetchAnim() { if (screen != HOME || messageCount == 0 || animPlaying) return; const Message& m = messages[firstUnread()]; if (!m.anim || animFor == m.id) return; if (!loadAnim(m.id)) animFor = 0; // unreachable: try again when it's opened } // Stops the animation before its frames change or the matrix shows something else. void stopAnim() { if (!animPlaying) return; matrix.autoscroll(0); animPlaying = false; shownFrame[0] = ~shownFrame[0]; // force the next still picture to load } // Shows a still picture on the LED matrix; skips repeats. void showMatrix(const uint32_t* frame) { uint32_t out[3]; orient(frame, out); if (memcmp(out, shownFrame, sizeof(out)) == 0) return; memcpy(shownFrame, out, sizeof(out)); matrix.loadFrame(out); } // What the matrix shows: the open message's animation, else an envelope while anything is unread. void renderMatrix() { bool viewing = (screen == VIEW || screen == CONFIRM_DELETE) && current < messageCount; if (viewing && messages[current].anim) { if (animFor != messages[current].id) { stopAnim(); loadAnim(messages[current].id); } if (animCount > 0) { // The matrix's timer advances the frames, so they keep going while the network calls block. if (!animPlaying) { matrix.loadWrapper(animFrames, animCount * sizeof(animFrames[0])); matrix.play(true); animPlaying = true; } return; } } stopAnim(); showMatrix(unreadCount > 0 ? ENVELOPE : BLANK); } // ---------- screens ---------- void draw(const String& a, const String& b) { String lines[2] = { a, b }; for (int r = 0; r < 2; r++) { String line = lines[r].substring(0, 16); while (line.length() < 16) line += ' '; if (line != lastDrawn[r]) { lcd.setCursor(0, r); lcd.print(line); lastDrawn[r] = line; } } } // Scrolls long text through 16 columns, wrapping with a gap. String marquee(const char* text) { String s(text); if (s.length() <= 16) return s; String loop = s + " " + s; int period = s.length() + 4; if (millis() - lastScrollAt >= SCROLL_MS) { lastScrollAt = millis(); scrollOffset = (scrollOffset + 1) % period; } // Pause on the first frame so the start is readable. int start = scrollOffset < 3 ? 0 : scrollOffset - 3; return loop.substring(start, start + 16); } String header(const Message& m, int index) { String pos = String(index + 1) + "/" + String(messageCount) + (m.read ? "" : "*"); String from(m.from); int room = 16 - pos.length() - 1; if ((int)from.length() > room) from = from.substring(0, room); while ((int)from.length() < 16 - (int)pos.length()) from += ' '; return from + pos; } void openMessage(int index) { current = index; screen = VIEW; viewStartedAt = millis(); scrollOffset = 0; lastScrollAt = millis(); } // "Call 555-0142", what the machine shows while it's resting. String callLine() { String number(boxNumber); return "Call " + number.substring(0, 3) + "-" + number.substring(3); } int firstUnread() { for (int i = 0; i < messageCount; i++) if (!messages[i].read) return i; return 0; } void render() { switch (screen) { case OFFLINE: draw("Can't reach the", "server. Retrying"); break; case TOO_LARGE: draw("Reply too long.", "Update sketch"); break; case PAIRING: { String code = String("Pair code ") + pairCode; String hint = String("Enter it at ") + SERVER_HOST + "/inbox"; draw(code, marquee(hint.c_str())); break; } case HOME: if (unreadCount > 0) draw(String(unreadCount) + (unreadCount == 1 ? " new message" : " new messages"), "SELECT to play"); else if (messageCount == 0 || (millis() / RESTING_SWAP_MS) % 2) draw(boxName, callLine()); else draw(String(messageCount) + (messageCount == 1 ? " message" : " messages"), "< > to browse"); break; case VIEW: { Message& m = messages[current]; draw(header(m, current), marquee(m.body)); if (!m.read && millis() - viewStartedAt >= READ_AFTER_MS) { m.read = true; unreadCount--; draw(header(m, current), marquee(m.body)); queueRead(m.id); } break; } case CONFIRM_DELETE: draw("Delete message?", "SELECT=yes <>=no"); break; } renderMatrix(); } void handleButtons() { Press prev = btnPrev.update(), next = btnNext.update(), sel = btnSelect.update(); if (prev == NONE && next == NONE && sel == NONE) return; lastInputAt = millis(); if (messageCount == 0 && screen != CONFIRM_DELETE) return; switch (screen) { case HOME: if (next == SHORT) openMessage(0); else if (prev == SHORT) openMessage(messageCount - 1); else if (sel == SHORT) openMessage(firstUnread()); break; case VIEW: if (next == SHORT) { if (current + 1 < messageCount) openMessage(current + 1); else screen = HOME; } else if (prev == SHORT) { if (current > 0) openMessage(current - 1); else screen = HOME; } else if (sel == SHORT) screen = HOME; else if (sel == LONG) screen = CONFIRM_DELETE; break; case CONFIRM_DELETE: if (sel == SHORT) { long id = messages[current].id; if (!messages[current].read) unreadCount--; for (int i = current; i < messageCount - 1; i++) messages[i] = messages[i + 1]; messageCount--; draw("Deleted", ""); sendAction(id, "delete"); if (messageCount == 0) screen = HOME; else openMessage(min(current, messageCount - 1)); } else if (prev == SHORT || next == SHORT) { openMessage(current); } break; default: break; } } // ---------- main ---------- void setup() { pinMode(PIN_PREV, INPUT_PULLUP); pinMode(PIN_NEXT, INPUT_PULLUP); pinMode(PIN_SELECT, INPUT_PULLUP); lcd.begin(16, 2); matrix.begin(); if (digitalRead(PIN_SELECT) == LOW) { showStatus("Keep holding to", "reset pairing..."); delay(3000); if (digitalRead(PIN_SELECT) == LOW) { forgetIdentity(); showStatus("Pairing reset.", "Release button"); while (digitalRead(PIN_SELECT) == LOW) delay(10); } } showStatus("Answering", "Machine"); loadIdentity(); } void loop() { handleButtons(); unsigned long interval = screen == PAIRING ? PAIR_POLL_MS : POLL_MS; if (pollNow || millis() - lastPollAt >= interval) poll(); if ((screen == VIEW || screen == CONFIRM_DELETE) && millis() - lastInputAt >= IDLE_MS) screen = HOME; render(); delay(5); }