Files
klubhaus-doorbell/sketches/doorbell/doorbell.ino
2026-02-12 05:28:32 -08:00

448 lines
11 KiB
C++

#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <Arduino_GFX_Library.h>
#include <time.h>
// ============== CONFIGURATION ==============
const char* ssid = "iot-2GHz";
const char* password = "lesson-greater";
const char* COMMAND_POLL_URL = "http://ntfy.sh/ALERT_klubhaus_topic/json";
const char* SILENCE_POLL_URL = "http://ntfy.sh/SILENCE_klubhaus_topic/json";
const char* STATUS_POST_URL = "http://ntfy.sh/STATUS_klubhaus_topic";
const unsigned long COMMAND_POLL_INTERVAL = 30000;
const unsigned long SILENCE_POLL_INTERVAL = 5000;
const unsigned long BLINK_DURATION = 180000;
const unsigned long BLINK_PERIOD = 1000;
const unsigned long ERROR_BACKOFF = 60000;
#define BACKLIGHT_PIN 22
#define BUTTON_PIN 9
#define COLOR_BLACK 0x0000
#define COLOR_COCAINE 0xFFFE
#define COLOR_TEAL 0x05F5
#define COLOR_FUCHSIA 0xFC6E
#define COLOR_MINT 0x674D
#define ALERT_BG_1 COLOR_TEAL
#define ALERT_TEXT_1 COLOR_COCAINE
#define ALERT_BG_2 COLOR_FUCHSIA
#define ALERT_TEXT_2 COLOR_COCAINE
#define SCREEN_WIDTH 320
#define SCREEN_HEIGHT 172
Arduino_DataBus *bus = new Arduino_HWSPI(15, 14, 7, 6, -1);
Arduino_GFX *gfx = new Arduino_ST7789(bus, 21, 1, true, 172, 320, 34, 0, 34, 0);
enum State { STATE_SILENT, STATE_ALERT };
State currentState = STATE_SILENT;
State lastPublishedState = STATE_SILENT;
unsigned long lastCommandPoll = 0;
unsigned long lastSilencePoll = 0;
unsigned long nextPollTime = 0;
unsigned long blinkStartTime = 0;
bool blinkPhase = false;
String lastCommandId = "";
String lastSilenceId = "";
bool lastButtonState = false;
String alertMessage = "";
unsigned long long epochOffsetMs = 0;
void setup() {
Serial.begin(115200);
delay(3000);
Serial.println("\n=== KLUBHAUS DOORBELL v3.6.1 ===");
Serial.println("Fix: restored missing loop() function");
pinMode(BACKLIGHT_PIN, OUTPUT);
digitalWrite(BACKLIGHT_PIN, LOW);
pinMode(BUTTON_PIN, INPUT_PULLUP);
gfx->begin();
digitalWrite(BACKLIGHT_PIN, HIGH);
testDisplay();
delay(300);
transitionTo(STATE_SILENT);
WiFi.begin(ssid, password);
int timeout = 0;
while (WiFi.status() != WL_CONNECTED && timeout < 40) {
delay(500);
Serial.print(".");
timeout++;
}
if (WiFi.status() != WL_CONNECTED) {
Serial.println("\nWiFi FAILED");
showFatalError("OFFLINE");
} else {
Serial.println("\nWiFi OK: " + WiFi.localIP().toString());
initEpochTime();
publishStatus();
}
Serial.println("=== READY ===");
}
// ============== EPOCH TIME ==============
void initEpochTime() {
configTime(0, 0, "pool.ntp.org", "time.nist.gov");
Serial.print("Syncing NTP...");
time_t now = 0;
int retries = 0;
while (now < 1000000000 && retries < 30) {
delay(500);
now = time(nullptr);
Serial.print(".");
retries++;
}
if (now > 1000000000) {
epochOffsetMs = (now * 1000ULL) - millis();
Serial.println(" OK");
Serial.print("Epoch offset: ");
Serial.println((unsigned long)epochOffsetMs);
} else {
Serial.println(" FAILED — using boot-relative time");
epochOffsetMs = 0;
}
}
unsigned long long getEpochMs() {
if (epochOffsetMs == 0) {
return millis();
}
return epochOffsetMs + millis();
}
// ============== MAIN LOOP (RESTORED) ==============
void loop() {
unsigned long now = millis();
if (now < nextPollTime) {
delay(100);
return;
}
handleButton();
switch (currentState) {
case STATE_SILENT:
if (now - lastSilencePoll >= SILENCE_POLL_INTERVAL) {
lastSilencePoll = now;
checkSilenceTopic();
}
if (now - lastCommandPoll >= COMMAND_POLL_INTERVAL) {
lastCommandPoll = now;
checkCommandTopic();
}
break;
case STATE_ALERT:
if (now - lastSilencePoll >= SILENCE_POLL_INTERVAL) {
lastSilencePoll = now;
checkSilenceTopic();
}
updateBlink(now);
if (now - blinkStartTime >= BLINK_DURATION) {
Serial.println("ALERT TIMEOUT");
transitionTo(STATE_SILENT);
}
break;
}
delay(50);
}
// ============== STATUS PUBLISHING ==============
void publishStatus() {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Status: skip (no WiFi)");
return;
}
HTTPClient http;
http.begin(STATUS_POST_URL);
http.addHeader("Content-Type", "text/plain");
StaticJsonDocument<256> doc;
doc["state"] = (currentState == STATE_SILENT) ? "SILENT" : "ALERTING";
doc["message"] = alertMessage;
doc["timestamp"] = (unsigned long long)getEpochMs();
String payload;
serializeJson(doc, payload);
int code = http.POST(payload);
Serial.print("Status: ");
Serial.print(payload);
Serial.println(String(" (") + code + ")");
http.end();
lastPublishedState = currentState;
}
void transitionTo(State newState) {
if (newState == currentState) return;
Serial.print("STATE: ");
Serial.print(currentState == STATE_SILENT ? "SILENT" : "ALERT");
Serial.print(" -> ");
Serial.println(newState == STATE_SILENT ? "SILENT" : "ALERT");
currentState = newState;
switch (currentState) {
case STATE_SILENT:
alertMessage = "";
gfx->fillScreen(COLOR_BLACK);
digitalWrite(BACKLIGHT_PIN, LOW);
break;
case STATE_ALERT:
digitalWrite(BACKLIGHT_PIN, HIGH);
blinkStartTime = millis();
blinkPhase = false;
drawAlertScreen(ALERT_BG_1, ALERT_TEXT_1);
break;
}
publishStatus();
}
// ============== TOPIC POLLING ==============
void checkCommandTopic() {
Serial.println("Poll COMMAND...");
String response = fetchNtfyJson(COMMAND_POLL_URL);
if (response.length() == 0) return;
StaticJsonDocument<512> doc;
DeserializationError error = deserializeJson(doc, response);
if (error) {
Serial.print(" JSON error: ");
Serial.println(error.c_str());
return;
}
String id = doc["id"] | "";
String message = doc["message"] | "";
message.trim();
if (message.length() == 0) {
Serial.println(" Empty message, skip");
return;
}
if (id == lastCommandId && id.length() > 0) {
Serial.println(" Same ID, skip");
return;
}
lastCommandId = id;
Serial.print(" NEW: [");
Serial.print(message);
Serial.println("]");
if (message.equalsIgnoreCase("SILENCE")) {
Serial.println(" -> SILENCE command");
transitionTo(STATE_SILENT);
flashConfirm("SILENCE", COLOR_MINT, COLOR_BLACK);
} else {
Serial.println(" -> ALERT trigger");
alertMessage = message;
transitionTo(STATE_ALERT);
}
}
void checkSilenceTopic() {
String response = fetchNtfyJson(SILENCE_POLL_URL);
if (response.length() == 0) return;
StaticJsonDocument<512> doc;
DeserializationError error = deserializeJson(doc, response);
if (error) return;
String id = doc["id"] | "";
String message = doc["message"] | "";
message.trim();
if (message.length() == 0) return;
if (id == lastSilenceId && id.length() > 0) return;
lastSilenceId = id;
Serial.print("Silence topic: [");
Serial.print(message);
Serial.println("]");
if (currentState == STATE_ALERT) {
Serial.println(" -> Force silence");
transitionTo(STATE_SILENT);
flashConfirm("SILENCED", COLOR_MINT, COLOR_BLACK);
}
}
String fetchNtfyJson(const char* url) {
HTTPClient http;
http.begin(url);
http.setTimeout(8000);
int code = http.GET();
if (code == 204) {
http.end();
return "";
}
if (code == 429 || code == 500 || code == 502 || code == 503) {
Serial.print(" HTTP error ");
Serial.print(code);
Serial.println(" — backing off 60s");
nextPollTime = millis() + ERROR_BACKOFF;
http.end();
return "";
}
if (code != 200) {
Serial.print(" HTTP error: ");
Serial.println(code);
http.end();
return "";
}
String payload = http.getString();
http.end();
int newline = payload.indexOf('\n');
if (newline > 0) payload = payload.substring(0, newline);
return payload;
}
// ============== VISUALS ==============
void flashConfirm(const char* text, uint16_t bgColor, uint16_t textColor) {
digitalWrite(BACKLIGHT_PIN, HIGH);
gfx->fillScreen(bgColor);
drawCenteredText(text, 3, textColor, bgColor, 70);
delay(500);
gfx->fillScreen(COLOR_BLACK);
digitalWrite(BACKLIGHT_PIN, LOW);
}
void drawAlertScreen(uint16_t bgColor, uint16_t textColor) {
gfx->fillScreen(bgColor);
drawCenteredText("ALERT", 3, textColor, bgColor, 20);
if (alertMessage.length() > 0) {
drawAutoSizedMessage(alertMessage, textColor, bgColor, 70);
}
}
void drawAutoSizedMessage(String message, uint16_t textColor, uint16_t bgColor, int yPos) {
int textSize = calculateOptimalTextSize(message, SCREEN_WIDTH - 40, SCREEN_HEIGHT - yPos - 20);
gfx->setTextSize(textSize);
gfx->setTextColor(textColor, bgColor);
gfx->setTextBound(20, yPos, SCREEN_WIDTH - 20, SCREEN_HEIGHT - 10);
gfx->setCursor(20, yPos);
gfx->println(message);
}
int calculateOptimalTextSize(String message, int maxWidth, int maxHeight) {
for (int size = 5; size >= 1; size--) {
gfx->setTextSize(size);
int charWidth = 6 * size;
int lineHeight = 8 * size;
int charsPerLine = maxWidth / charWidth;
int numLines = (message.length() + charsPerLine - 1) / charsPerLine;
int totalHeight = numLines * lineHeight;
if (totalHeight <= maxHeight && charsPerLine >= 4) return size;
}
return 1;
}
void drawCenteredText(const char* text, int textSize, uint16_t textColor, uint16_t bgColor, int yPos) {
gfx->setTextSize(textSize);
gfx->setTextColor(textColor, bgColor);
int textWidth = strlen(text) * 6 * textSize;
int xPos = (SCREEN_WIDTH - textWidth) / 2;
if (xPos < 20) xPos = 20;
gfx->setCursor(xPos, yPos);
gfx->println(text);
}
void showFatalError(const char* text) {
digitalWrite(BACKLIGHT_PIN, HIGH);
gfx->fillScreen(COLOR_BLACK);
drawCenteredText(text, 3, COLOR_FUCHSIA, COLOR_BLACK, 70);
delay(3000);
digitalWrite(BACKLIGHT_PIN, LOW);
}
// ============== BUTTON ==============
void handleButton() {
bool pressed = (digitalRead(BUTTON_PIN) == LOW);
if (pressed && !lastButtonState) {
Serial.println("BUTTON PRESSED");
digitalWrite(BACKLIGHT_PIN, HIGH);
gfx->fillScreen(COLOR_COCAINE);
drawCenteredText("TEST MODE", 2, COLOR_BLACK, COLOR_COCAINE, 70);
}
else if (!pressed && lastButtonState) {
Serial.println("BUTTON RELEASED");
if (currentState == STATE_ALERT) {
Serial.println(" -> Reset to SILENT");
transitionTo(STATE_SILENT);
flashConfirm("SILENCED", COLOR_MINT, COLOR_BLACK);
} else {
gfx->fillScreen(COLOR_BLACK);
digitalWrite(BACKLIGHT_PIN, LOW);
}
}
lastButtonState = pressed;
}
// ============== BLINK ==============
void updateBlink(unsigned long now) {
unsigned long elapsed = now - blinkStartTime;
bool newPhase = ((elapsed / BLINK_PERIOD) % 2) == 1;
if (newPhase != blinkPhase) {
blinkPhase = newPhase;
uint16_t bgColor = blinkPhase ? ALERT_BG_2 : ALERT_BG_1;
uint16_t textColor = blinkPhase ? ALERT_TEXT_2 : ALERT_TEXT_1;
drawAlertScreen(bgColor, textColor);
}
}
// ============== TEST ==============
void testDisplay() {
uint16_t colors[] = {COLOR_TEAL, COLOR_FUCHSIA, COLOR_COCAINE, COLOR_MINT, COLOR_BLACK};
for (int i = 0; i < 5; i++) {
gfx->fillScreen(colors[i]);
delay(100);
}
gfx->fillScreen(COLOR_BLACK);
drawCenteredText("KLUBHAUS", 3, COLOR_TEAL, COLOR_BLACK, 50);
drawCenteredText("DOORBELL", 3, COLOR_FUCHSIA, COLOR_BLACK, 90);
delay(400);
gfx->fillScreen(COLOR_BLACK);
}