Mailbox
demo-kit/ is what simulates the device for the demo on the start page. The device itself does not need it.
demo-kit/ is what simulates the device for the demo on the start page. The device itself does not need it.
/*
Mailbox sensor - the far half of the mailbox example: an ESP32 at the mailbox that calls the flag indoors
An ESP32 with a reed switch at a mailbox or a gate, in a network of its own (the Wi-Fi of a mobile router,
for example). When the lid opens, it calls the indicator indoors (../indicator/indicator.ino) itself:
Connectivitizer.link() puts the indicator's web server on a port of this chip, and Connectivitizer.post()
sends POST /event there. It also calls when the lid closes, and every ten minutes, so that the indicator
knows the sensor is alive. An opening that could not be delivered is kept and sent with the next call.
The sensor is a device of its own as well: it serves its state and a small page (page.h, made from
../../ui/sensor.html) that the Connectivitizer app shows.
It stays awake and keeps its Wi-Fi connection all the time. It does not sleep, so it needs a power supply
that is always there; it is not a battery design.
Wiring (ESP32 DevKit, 3.3 V logic; change the pins below for another board):
Reed switch (normally open) GPIO27 -> switch -> GND (the pin's own pull-up is used); the magnet on the
lid, so that it holds the switch closed while the lid is closed
A tilt switch works the same way. If your switch is closed while the lid is open, set LID_OPEN_LEVEL to LOW.
On a bare DevKit board: PIN_LID = 0 and LID_OPEN_LEVEL = LOW make the BOOT button the lid.
What you need (https://connectivitizer.com):
1. a device key - Credentials > Create credential > Device key, with "Its devices may open sessions to
other devices" switched on -> DEVICE_KEY
2. a shared key - Credentials > Generate a shared key -> SHARED_KEY; the same key in the
indicator and in the app
Copy secrets.example.h to secrets.h and fill it in. The Connectivitizer library is the only one to install.
*/
// ---------- the lid ----------
const int PIN_LID = 27;
const int LID_OPEN_LEVEL = HIGH; // what the pin reads while the lid is open
const uint32_t LID_SAMPLE_MS = 20;
const int LID_SAMPLES_NEEDED = 3; // 60 ms the same: the contacts have stopped bouncing
// ---------- the indicator ----------
const uint16_t INDICATOR_PORT = 8081; // the indicator's web server, on this port of this chip
const uint32_t CALL_TIMEOUT_MS = 15000; // opening the session the first time takes a few seconds of that
const uint32_t RETRY_SECONDS = 15; // after a call without an answer
const uint32_t CHECK_IN_SECONDS = 600; // a call without news, so that the indicator knows the sensor is alive
WebServer server(80);
bool lidOpen = false;
uint32_t opens = 0; // openings since the start
uint32_t unsent = 0; // openings the indicator has not confirmed yet
int reportedLid = -1; // the lid as the indicator last heard it: 1 open, 0 closed, -1 nothing yet
bool calling = false;
int lastStatus = 0; // the HTTP status of the last call, -1 without an answer, 0 before the first
bool delivered = false;
uint64_t deliveredMs = 0;
int indicatorFlag = -1; // what the indicator answered: 1 up, 0 down, -1 not known
bool hasFailed = false;
uint64_t failedMs = 0;
// A call to the indicator waits for its answer, up to CALL_TIMEOUT_MS. It runs in a task of its own, so that
// the lid is watched and the web server answers meanwhile. loop() hands the task one call at a time and
// takes the outcome back; nothing else is shared between the two.
struct Call {
uint32_t opened;
bool lidOpen;
int rssi;
};
struct Outcome {
uint32_t opened;
bool lidOpen;
int status;
int flag;
};
QueueHandle_t callQueue = nullptr;
QueueHandle_t outcomeQueue = nullptr;
// Milliseconds since the start, 64 bit: millis() starts again at zero after 49 days.
uint64_t nowMs() {
return (uint64_t)(esp_timer_get_time() / 1000);
}
void callerTask(void *) {
Call call;
for (;;) {
if (xQueueReceive(callQueue, &call, portMAX_DELAY) != pdTRUE) continue;
String body = "{\"from\":\"" DEVICE_NAME "\",\"opened\":";
body += call.opened;
body += ",\"lid\":";
body += call.lidOpen ? "\"open\"" : "\"closed\"";
body += ",\"rssi\":";
body += call.rssi;
body += ",\"checkInSeconds\":";
body += CHECK_IN_SECONDS;
body += "}";
String answer;
Outcome outcome = { call.opened, call.lidOpen, 0, -1 };
outcome.status = Connectivitizer.post(INDICATOR_DEVICE, "/event", body, answer, CALL_TIMEOUT_MS);
if (outcome.status == 200) {
if (answer.indexOf("\"flag\":true") >= 0) outcome.flag = 1;
else if (answer.indexOf("\"flag\":false") >= 0) outcome.flag = 0;
}
xQueueSend(outcomeQueue, &outcome, portMAX_DELAY);
}
}
// Watches the lid. An opening is counted at the moment the lid leaves its closed place.
void watchLid() {
static uint64_t lastSample = 0;
static int inARow = 0;
if (nowMs() - lastSample < LID_SAMPLE_MS) return;
lastSample = nowMs();
bool now = digitalRead(PIN_LID) == LID_OPEN_LEVEL;
inARow = now == lidOpen ? 0 : inARow + 1;
if (inARow < LID_SAMPLES_NEEDED) return;
inARow = 0;
lidOpen = now;
if (lidOpen) {
opens++;
unsent++;
Serial.println("The lid opened.");
} else {
Serial.println("The lid closed.");
}
}
// Calls the indicator when there is something to say: an opening, a lid that moved, or the check-in.
void watchCalls() {
Outcome outcome;
if (calling && xQueueReceive(outcomeQueue, &outcome, 0) == pdTRUE) {
calling = false;
lastStatus = outcome.status;
if (outcome.status == 200) {
unsent -= outcome.opened; // openings counted during the call stay for the next one
reportedLid = outcome.lidOpen ? 1 : 0;
indicatorFlag = outcome.flag;
delivered = true;
deliveredMs = nowMs();
hasFailed = false;
Serial.println("The indicator answered.");
} else {
hasFailed = true;
failedMs = nowMs();
Serial.printf("The indicator did not answer (status %d, %s). Trying again in %u s.\n", outcome.status, Connectivitizer.lastError(), (unsigned)RETRY_SECONDS);
}
}
if (calling || !Connectivitizer.connected()) return;
if (hasFailed && nowMs() - failedMs < (uint64_t)RETRY_SECONDS * 1000) return;
bool news = unsent > 0 || reportedLid != (lidOpen ? 1 : 0);
bool checkIn = !delivered || nowMs() - deliveredMs >= (uint64_t)CHECK_IN_SECONDS * 1000;
if (!news && !checkIn) return;
Call call = { unsent, lidOpen, (int)WiFi.RSSI() };
calling = xQueueSend(callQueue, &call, 0) == pdTRUE;
}
String stateJson() {
String json;
json.reserve(330);
json += "{\"name\":\"" DEVICE_NAME "\",\"indicator\":\"" INDICATOR_DEVICE "\",\"lid\":";
json += lidOpen ? "\"open\"" : "\"closed\"";
json += ",\"opens\":";
json += opens;
json += ",\"unsent\":";
json += unsent;
json += ",\"calling\":";
json += calling ? "true" : "false";
json += ",\"lastDeliveredSecondsAgo\":";
if (delivered) json += (uint32_t)((nowMs() - deliveredMs) / 1000);
else json += "null";
json += ",\"lastStatus\":";
if (lastStatus != 0) json += lastStatus;
else json += "null";
json += ",\"indicatorFlag\":";
json += indicatorFlag < 0 ? "null" : indicatorFlag ? "true" : "false";
json += ",\"checkInSeconds\":";
json += CHECK_IN_SECONDS;
json += ",\"rssi\":";
json += WiFi.RSSI();
json += ",\"uptimeSeconds\":";
json += (uint32_t)(nowMs() / 1000);
json += "}";
return json;
}
void sendJson(int status, const String &json) {
server.sendHeader("Cache-Control", "no-store");
server.send(status, "application/json", json);
}
void setup() {
Serial.begin(115200);
pinMode(PIN_LID, INPUT_PULLUP);
lidOpen = digitalRead(PIN_LID) == LID_OPEN_LEVEL; // a lid that is open at the start is not counted as an opening
callQueue = xQueueCreate(1, sizeof(Call));
outcomeQueue = xQueueCreate(1, sizeof(Outcome));
xTaskCreate(callerTask, "mailbox-caller", 8192, nullptr, 1, nullptr);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
// An ordinary web server. It knows nothing about Connectivitizer.
server.on("/state", HTTP_GET, []() { sendJson(200, stateJson()); });
// The screen of the device: the app asks for the manifest, then for the page it names.
server.on("/.cz/ui.json", HTTP_GET, []() { server.send_P(200, "application/json", MANIFEST_JSON); });
server.on("/.cz/ui.html", HTTP_GET, []() {
server.sendHeader("Cache-Control", "no-cache");
server.send_P(200, "text/html; charset=utf-8", PAGE_HTML, PAGE_HTML_LENGTH);
});
server.onNotFound([]() { sendJson(404, "{\"error\":\"Not found.\"}"); });
server.begin();
Connectivitizer.setLog(Serial);
Connectivitizer.setServer(SERVER_URL);
Connectivitizer.setSharedKey(SHARED_KEY);
Connectivitizer.expose("api", 80); // the web server above, under the name "api"
// The service "api" of the indicator, on port INDICATOR_PORT of this chip. The session to it opens with
// the first request and closes when the port has not been used for half a minute.
Connectivitizer.link(INDICATOR_DEVICE, "api", INDICATOR_PORT);
if (!Connectivitizer.begin(DEVICE_KEY, DEVICE_NAME)) {
Serial.println("Connectivitizer: check DEVICE_KEY, DEVICE_NAME, INDICATOR_DEVICE and SHARED_KEY");
}
}
void loop() {
server.handleClient();
watchLid();
watchCalls();
// On the serial monitor: the address in the Wi-Fi, to open http://<address>/.cz/ui.html in a browser.
static bool hadWifi = false;
bool hasWifi = WiFi.status() == WL_CONNECTED;
if (hasWifi != hadWifi) {
hadWifi = hasWifi;
if (hasWifi) {
Serial.print("Wi-Fi connected: http://");
Serial.print(WiFi.localIP());
Serial.println("/.cz/ui.html");
} else {
Serial.println("Wi-Fi lost.");
}
}
static bool wasConnected = false;
bool isConnected = Connectivitizer.connected();
if (isConnected != wasConnected) {
wasConnected = isConnected;
Serial.println(isConnected ? "Reachable through Connectivitizer." : "Not reachable right now.");
}
if (Connectivitizer.refused()) {
static uint64_t lastComplaint = 0;
if (lastComplaint == 0 || nowMs() - lastComplaint > 10000) { // no delay(): the lid must not wait
lastComplaint = nowMs();
Serial.printf("The platform refused this device: %s\n", Connectivitizer.lastError());
}
}
}