Caixa de correio
demo-kit/ é o que simula o dispositivo para a demo na página inicial. O próprio dispositivo não precisa dele.
demo-kit/ é o que simula o dispositivo para a demo na página inicial. O próprio dispositivo não precisa dele.
/*
Mailbox flag - the indoor half of the mailbox example: a light that says the mailbox was opened
An ESP32 indoors with a light and a button. The sensor at the mailbox (../sensor/sensor.ino), in another
network, calls it when the mailbox opens: POST /event. The light then glows until someone clears the flag,
with the button here or from the phone. The device serves that as a small web API, and one HTML page
(page.h, made from ../../ui/mailbox.html) that the Connectivitizer app shows full screen.
This device is only called: by the sensor and by the phone. The web server knows nothing about
Connectivitizer; the library makes it reachable, encrypted end to end with the shared key.
Wiring (ESP32 DevKit, 3.3 V logic; change the pins below for another board):
Flag light, an LED GPIO25 -> 220 Ohm -> LED -> GND
Clear button GPIO27 -> button -> GND (the pin's own pull-up is used)
On a bare DevKit board: PIN_FLAG = 2 is the on-board LED of most boards and PIN_BUTTON = 0 its BOOT button.
What you need (https://connectivitizer.com):
1. a device key - Credentials > Create credential > Device key -> DEVICE_KEY
2. a shared key - Credentials > Generate a shared key -> SHARED_KEY; the same key in the
sensor and in the app
Copy secrets.example.h to secrets.h and fill it in. The Connectivitizer library is the only one to install;
Preferences comes with the ESP32 board package.
*/
// ---------- pins ----------
const int PIN_FLAG = 25; // the flag light
const int PIN_BUTTON = 27; // LOW while pressed
const bool FLAG_ACTIVE_HIGH = true; // false when the light is on with the pin LOW
// ---------- the flag light ----------
const uint32_t FLAG_PWM_HZ = 1000;
const uint8_t FLAG_PWM_BITS = 10;
const uint8_t FLAG_CHANNEL = 0;
const float BREATH_SECONDS = 3.0f; // the light swells and fades once in this time while the flag is up
// The sensor counts as late when it has not called for this many of its own check-in intervals.
const float LATE_AFTER_INTERVALS = 2.5f;
const int HISTORY_ENTRIES = 30;
WebServer server(80);
Preferences settings;
bool flag = false; // kept in flash: a power cut does not lose the news
uint32_t opened = 0; // openings since the flag was cleared; kept in flash with it
bool flagTimeKnown = false; // false after a restart with the flag up
uint64_t flagSinceMs = 0;
// What the sensor said in its last call.
bool sensorSeen = false;
uint64_t sensorSeenMs = 0;
int sensorLid = -1; // 1 open, 0 closed, -1 not known
bool sensorHasRssi = false;
int sensorRssi = 0;
uint32_t sensorCheckInSeconds = 0; // 0: not known
struct Entry {
uint32_t id;
uint64_t atMs;
bool cleared; // false: the mailbox was opened
uint8_t via; // 0 the sensor, 1 the button, 2 a phone
uint16_t count; // openings in this call
};
Entry entries[HISTORY_ENTRIES]; // kept in memory only
int entryCount = 0;
int entryNext = 0;
uint32_t nextEntryId = 1;
uint32_t changes = 0; // goes up with every change the page shows from /history or the lid
// 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);
}
// ---------- the flag light ----------
void pwmStart(int pin, uint8_t channel, uint32_t hertz, uint8_t bits) {
ledcAttachChannel(pin, hertz, bits, channel);
ledcSetup(channel, hertz, bits);
ledcAttachPin(pin, channel);
}
void pwmWrite(int pin, uint8_t channel, uint32_t duty) {
(void)channel;
ledcWrite(pin, duty);
(void)pin;
ledcWrite(channel, duty);
}
void showFlag() {
static uint64_t lastStep = 0;
if (nowMs() - lastStep < 20) return;
lastStep = nowMs();
const uint32_t full = (1u << FLAG_PWM_BITS) - 1;
uint32_t duty = 0;
if (flag) {
// Between a tenth and full brightness, never dark: the flag is seen at any moment.
float phase = fmodf((float)nowMs() / 1000.0f, BREATH_SECONDS) / BREATH_SECONDS;
float level = 0.1f + 0.9f * (0.5f - 0.5f * cosf(2.0f * PI * phase));
duty = (uint32_t)lroundf(level * level * (float)full);
}
pwmWrite(PIN_FLAG, FLAG_CHANNEL, FLAG_ACTIVE_HIGH ? duty : full - duty);
}
// ---------- the flag and its history ----------
void addEntry(bool cleared, uint8_t via, uint16_t count) {
Entry &entry = entries[entryNext];
entryNext = (entryNext + 1) % HISTORY_ENTRIES;
if (entryCount < HISTORY_ENTRIES) entryCount++;
entry.id = nextEntryId++;
entry.atMs = nowMs();
entry.cleared = cleared;
entry.via = via;
entry.count = count;
changes++;
}
void saveFlag() {
settings.putBool("flag", flag);
settings.putUInt("opened", opened);
}
void raiseFlag(uint16_t count) {
if (!flag) {
flagTimeKnown = true;
flagSinceMs = nowMs();
}
flag = true;
opened += count;
addEntry(false, 0, count);
saveFlag();
}
// `via`: 1 the button, 2 a phone. Does nothing while the flag is down.
void clearFlag(uint8_t via) {
if (!flag) return;
flag = false;
opened = 0;
flagTimeKnown = false;
addEntry(true, via, 0);
saveFlag();
}
// True once for every press of the button.
bool buttonPressed() {
static uint64_t lastSample = 0;
static int inARow = 0;
static bool down = false;
if (nowMs() - lastSample < 20) return false;
lastSample = nowMs();
bool now = digitalRead(PIN_BUTTON) == LOW;
inARow = now == down ? 0 : inARow + 1;
if (inARow < 3) return false; // 60 ms the same: the contacts have stopped bouncing
inARow = 0;
down = now;
return down;
}
// ---------- JSON ----------
// Just enough JSON reading for the body of /event: a flat object with texts and numbers. Returns where the
// value of a key starts, or -1.
int jsonValueAt(const String &body, const char *key) {
String quoted = String("\"") + key + "\"";
int at = body.indexOf(quoted);
if (at < 0) return -1;
at = body.indexOf(':', at + quoted.length());
if (at < 0) return -1;
at++;
while (at < (int)body.length() && isspace((unsigned char)body[at])) at++;
return at < (int)body.length() ? at : -1;
}
bool jsonText(const String &body, const char *key, String &text) {
int at = jsonValueAt(body, key);
if (at < 0 || body[at] != '"') return false;
int end = body.indexOf('"', at + 1);
if (end < 0) return false;
text = body.substring(at + 1, end);
return true;
}
bool jsonNumber(const String &body, const char *key, float &value) {
int at = jsonValueAt(body, key);
if (at < 0) return false;
char first = body[at];
if (!isdigit((unsigned char)first) && first != '-') return false;
value = body.substring(at).toFloat();
return true;
}
bool sensorLate() {
if (!sensorSeen || sensorCheckInSeconds == 0) return false;
return (float)(nowMs() - sensorSeenMs) / 1000.0f > LATE_AFTER_INTERVALS * (float)sensorCheckInSeconds;
}
String stateJson() {
String json;
json.reserve(360);
json += "{\"name\":\"" DEVICE_NAME "\",\"flag\":";
json += flag ? "true" : "false";
json += ",\"flagSecondsAgo\":";
if (flag && flagTimeKnown) json += (uint32_t)((nowMs() - flagSinceMs) / 1000);
else json += "null"; // when the flag went up is not kept over a restart
json += ",\"opened\":";
json += opened;
json += ",\"sensor\":{\"name\":\"" SENSOR_DEVICE "\",\"lastSeenSecondsAgo\":";
if (sensorSeen) json += (uint32_t)((nowMs() - sensorSeenMs) / 1000);
else json += "null";
json += ",\"lid\":";
json += sensorLid < 0 ? "null" : sensorLid ? "\"open\"" : "\"closed\"";
json += ",\"rssi\":";
if (sensorHasRssi) json += sensorRssi;
else json += "null";
json += ",\"checkInSeconds\":";
if (sensorCheckInSeconds > 0) json += sensorCheckInSeconds;
else json += "null";
json += ",\"late\":";
json += sensorLate() ? "true" : "false";
json += "},\"changes\":";
json += changes;
json += ",\"rssi\":";
json += WiFi.RSSI();
json += ",\"uptimeSeconds\":";
json += (uint32_t)(nowMs() / 1000);
json += "}";
return json;
}
String historyJson() {
static const char *const VIA[] = { "sensor", "button", "phone" };
String json;
json.reserve(40 + entryCount * 90);
json += "{\"entries\":[";
for (int i = 0; i < entryCount; i++) { // newest first
const Entry &entry = entries[(entryNext - 1 - i + 2 * HISTORY_ENTRIES) % HISTORY_ENTRIES];
if (i > 0) json += ",";
json += "{\"id\":";
json += entry.id;
json += ",\"secondsAgo\":";
json += (uint32_t)((nowMs() - entry.atMs) / 1000);
json += ",\"kind\":";
json += entry.cleared ? "\"cleared\"" : "\"opened\"";
json += ",\"via\":\"";
json += VIA[entry.via];
json += "\",\"count\":";
json += entry.count;
json += "}";
}
json += "]}";
return json;
}
// ---------- the web server ----------
void sendJson(int status, const String &json) {
server.sendHeader("Cache-Control", "no-store");
server.send(status, "application/json", json);
}
void sendError(int status, const char *message) {
String json = "{\"error\":\"";
json += message; // only fixed texts without quotes are passed here
json += "\"}";
sendJson(status, json);
}
// The sensor's call: how often the mailbox was opened since its last delivered call (0 for a check-in or
// a lid that closed), and how the sensor is.
void handleEvent() {
String body = server.arg("plain");
String from, lid;
// Keeps a misconfigured sensor out; it is not a second lock. Whoever holds the shared key and may open
// sessions to this device in the workspace can send this request.
if (!jsonText(body, "from", from) || from != SENSOR_DEVICE) {
sendError(400, "from is not the sensor of this flag.");
return;
}
float number = 0;
uint16_t count = 0;
if (jsonNumber(body, "opened", number) && number >= 1) count = (uint16_t)fminf(number, 1000.0f);
int lidNow = sensorLid;
if (jsonText(body, "lid", lid)) lidNow = lid == "open" ? 1 : lid == "closed" ? 0 : -1;
if (lidNow != sensorLid) changes++;
sensorLid = lidNow;
sensorHasRssi = jsonNumber(body, "rssi", number);
if (sensorHasRssi) sensorRssi = (int)number;
if (jsonNumber(body, "checkInSeconds", number) && number >= 1) sensorCheckInSeconds = (uint32_t)number;
sensorSeen = true;
sensorSeenMs = nowMs();
if (count > 0) raiseFlag(count);
sendJson(200, flag ? "{\"ok\":true,\"flag\":true}" : "{\"ok\":true,\"flag\":false}");
}
void setup() {
Serial.begin(115200);
pwmStart(PIN_FLAG, FLAG_CHANNEL, FLAG_PWM_HZ, FLAG_PWM_BITS);
pinMode(PIN_BUTTON, INPUT_PULLUP);
// A flag that was up before a restart is up again.
settings.begin("mailbox", false);
flag = settings.getBool("flag", false);
opened = settings.getUInt("opened", 0);
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()); });
server.on("/history", HTTP_GET, []() { sendJson(200, historyJson()); });
server.on("/event", HTTP_POST, handleEvent);
server.on("/clear", HTTP_POST, []() {
clearFlag(2);
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([]() { sendError(404, "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"
if (!Connectivitizer.begin(DEVICE_KEY, DEVICE_NAME)) {
Serial.println("Connectivitizer: check DEVICE_KEY, DEVICE_NAME and SHARED_KEY");
}
}
void loop() {
server.handleClient();
showFlag();
if (buttonPressed()) clearFlag(1);
// 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 light and the button must not wait
lastComplaint = nowMs();
Serial.printf("The platform refused this device: %s\n", Connectivitizer.lastError());
}
}
}