// Pair an ESP32 with packeroo: ask for a code, show it, keep the token in flash, and ask // GET /device every 5 seconds until someone enters the code in the app. // Arduino core for ESP32 (2.x or 3.x) and the library ArduinoJson 7. // // Fill in WIFI_SSID and WIFI_PASSWORD. BASE_URL points at the sandbox. This sketch prints to the // serial monitor; for a display, draw the same texts with a library such as TFT_eSPI or U8g2, // and the link as a QR code with a library such as QRCode (ricmoo). #include #include #include #include #include #include #include #include // What the device shows, in the language of the location. const char *TEXT_CODE = "Code am Tisch: %s %s\n"; const char *TEXT_LINK = "QR-Code mit diesem Link: %s/verbinden?code=%s\n"; const char *TEXT_ENTER = "Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen."; const char *TEXT_EXPIRED = "Der Code ist abgelaufen. Ich hole einen neuen."; const char *TEXT_UNPAIRED = "Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code."; const char *TEXT_OFF = "Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s."; const char *TEXT_PAIRED = "Verbunden mit %s\n"; const char *TEXT_ERROR = "Fehler %d %s, neuer Versuch in %lu s\n"; const char *WIFI_SSID = ""; const char *WIFI_PASSWORD = ""; const char *BASE_URL = "https://api.qm.packeroo.com/api/v1"; const char *APP_URL = "https://app.qm.packeroo.com"; // Every request names the device: product and firmware. const char *USER_AGENT = "Kickertisch-ESP32/1.0"; const unsigned long POLL_MS = 5000; // After errors in a row the pause doubles, up to one minute. const unsigned long MAX_PAUSE_MS = 60000; // The roots api.packeroo.com and api.qm.packeroo.com chain up to (Let's Encrypt): ISRG Root X1 // (RSA, valid until 2035) and ISRG Root X2 (ECDSA, valid until 2040). If the chain of the API // changes to a root not listed here, add it and ship a firmware update. const char *ROOT_CERTIFICATES = "-----BEGIN CERTIFICATE-----\n" "MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n" "TzELMAkGA1UEBhMC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aFw00\n" "MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT\n" "ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw\n" "EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW\n" "+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9\n" "ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T\n" "AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI\n" "zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW\n" "tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1\n" "/q4AaOeMSQ+2b1tbFfLn\n" "-----END CERTIFICATE-----\n"; Preferences store; // The token lives in NVS, never in the sketch. String token; unsigned long expiresAtMs = 0; // millis() when the shown code runs out; 0 when no code is waiting bool waitingForCode = false; unsigned long pauseMs = POLL_MS; // the next pause after an error, doubled with every error in a row // Waits after a network error, a 5xx or an unexpected answer, and doubles the next pause up to // MAX_PAUSE_MS. The sketch never asks the API again without a pause. void pauseAfterError(int status, const char *problem) { Serial.printf(TEXT_ERROR, status, problem, pauseMs / 1000); delay(pauseMs); pauseMs = min(pauseMs * 2, MAX_PAUSE_MS); } WiFiClientSecure tls; // One request. Returns the status (negative on a network error), the body in `body`. int call(const char *method, const char *path, const String &json, const String &idempotencyKey, String &body, int &retryAfter) { HTTPClient http; http.begin(tls, String(BASE_URL) + path); http.setUserAgent(USER_AGENT); http.addHeader("Accept", "application/json"); http.addHeader("Accept-Language", "de"); if (token.length() > 0) http.addHeader("Authorization", "Bearer " + token); // A write carries an Idempotency-Key; a retry of the same request sends the same key. if (idempotencyKey.length() > 0) http.addHeader("Idempotency-Key", idempotencyKey); const char *wanted[] = {"Retry-After"}; http.collectHeaders(wanted, 1); int status; if (json.length() > 0) { http.addHeader("Content-Type", "application/json"); status = http.sendRequest(method, json); } else { status = http.sendRequest(method); } body = status > 0 ? http.getString() : ""; // Retry-After in seconds; the API sends seconds, so an HTTP date falls back to 60. retryAfter = http.header("Retry-After").toInt(); if (retryAfter <= 0) retryAfter = 60; http.end(); return status; } String newKey() { uint8_t b[16]; esp_fill_random(b, sizeof b); b[6] = (b[6] & 0x0f) | 0x40; b[8] = (b[8] & 0x3f) | 0x80; char key[37]; snprintf(key, sizeof key, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]); return String(key); } // Show these on the display of the table: the code as two groups of three, and the link as a QR code. void showCode(const String &code) { Serial.println(); Serial.printf(TEXT_CODE, code.substring(0, 3).c_str(), code.substring(3).c_str()); Serial.printf(TEXT_LINK, APP_URL, code.c_str()); Serial.println(TEXT_ENTER); Serial.println(); } // Asks for a code. Returns true when there is a code to wait for or the token is paired already; // false on an answer the sketch cannot act on, after a pause. bool requestCode() { String key = newKey(); for (;;) { String body; int retryAfter; int status = call("POST", "/device-pairings", "{\"model\":\"Kickertisch-ESP32\",\"firmware\":\"1.0\"}", key, body, retryAfter); JsonDocument answer; deserializeJson(answer, body); const char *problem = answer["code"] | ""; if (status == 201) { token = answer["data"]["token"].as(); // Shown only this once: keep it before anything else. store.putString("token", token); // The code is valid for 10 minutes; counted from now with millis(), a few seconds early. expiresAtMs = millis() + 10UL * 60UL * 1000UL - 5000UL; waitingForCode = true; pauseMs = POLL_MS; showCode(answer["data"]["code"].as()); return true; } if (status == 409 && strcmp(problem, "device_already_paired") == 0) { waitingForCode = false; pauseMs = POLL_MS; return true; } if (status == 409 && strcmp(problem, "table_devices_off") == 0) { Serial.println(TEXT_OFF); delay(60000); } else if (status == 429) { delay(retryAfter * 1000UL); } else if (status < 0 || status >= 500) { // No network, or the API is busy or being deployed: the same request with the same key. pauseAfterError(status, problem); } else { pauseAfterError(status, problem); return false; } } } // GET /device: 1 paired, 0 not yet, -1 the code ran out, -2 unpaired (401 with no code waiting), // -3 no network, a 5xx or another answer. Only 401 means "not paired": after -3 the code stays, // someone may be typing it right now. Unattended, the sketch has nobody to stop for: on an answer // it cannot act on it prints the status and its problem code, and asks again after a pause. int checkPaired() { String body; int retryAfter; int status = call("GET", "/device", "", "", body, retryAfter); if (status == 200) { JsonDocument device; deserializeJson(device, body); Serial.printf(TEXT_PAIRED, device["data"]["table"]["name"] | "?"); return 1; } if (status == 429) { delay(retryAfter * 1000UL); return 0; } if (status == 401) { if (!waitingForCode) return -2; if ((long)(millis() - expiresAtMs) >= 0) return -1; return 0; } // No network, a 5xx or another answer: keep the code, ask again after a pause. JsonDocument problem; deserializeJson(problem, body); pauseAfterError(status, problem["code"] | ""); return -3; } bool paired = false; bool needCode = false; // true while a new code has to be asked for void setup() { Serial.begin(115200); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); while (WiFi.status() != WL_CONNECTED) delay(250); // The certificate check needs the right time; take it from NTP before the first request. configTime(0, 0, "pool.ntp.org", "time.nist.gov"); while (time(nullptr) < 1700000000) delay(250); tls.setCACert(ROOT_CERTIFICATES); store.begin("packeroo", false); token = store.getString("token", ""); if (token.length() > 0) paired = checkPaired() == 1; // Not paired, or no answer yet: ask for a code with the stored token; a paired one gets 409. needCode = !paired; } void loop() { if (paired) { // From here the table reports to packeroo; the next operations are planned. delay(60000); return; } if (needCode) { // requestCode() has paused already when it gives up; loop() asks again with a new key. if (!requestCode()) return; needCode = false; } int state = checkPaired(); if (state == 1) { paired = true; } else if (state == -2) { // Paired a moment ago, unpaired now: this token is of no use any more. Serial.println(TEXT_UNPAIRED); token = ""; store.remove("token"); needCode = true; } else if (state == -1) { Serial.println(TEXT_EXPIRED); needCode = true; } else if (state == 0) { pauseMs = POLL_MS; delay(POLL_MS); } // -3: checkPaired() has paused already. }