429 lines
12 KiB
C++
429 lines
12 KiB
C++
#include <WiFi.h>
|
|
#include <HTTPClient.h>
|
|
#include <ArduinoJson.h>
|
|
#include <Arduino_GFX_Library.h>
|
|
|
|
// ============== CONFIGURATION ==============
|
|
const char* ssid = "iot-2GHz";
|
|
const char* password = "lesson-greater";
|
|
|
|
// Refactored topic architecture
|
|
const char* commandTopic = "http://ntfy.sh/ALERT_klubhaus_topic/json?poll=1"; // Incoming: FRONT DOOR, LOADING DOCK, custom
|
|
const char* silenceTopic = "http://ntfy.sh/SILENCE_klubhaus_topic/json?poll=1"; // Incoming: any message = silence
|
|
const char* statusTopic = "http://ntfy.sh/STATUS_klubhaus_topic"; // Outgoing: device publishes state
|
|
|
|
const unsigned long POLL_INTERVAL = 15000;
|
|
const unsigned long SILENCE_POLL_INTERVAL = 5000;
|
|
const unsigned long BLINK_DURATION = 180000;
|
|
const unsigned long BLINK_PERIOD = 1000;
|
|
const unsigned long STATUS_PUBLISH_INTERVAL = 30000; // Periodic status broadcast
|
|
|
|
#define BACKLIGHT_PIN 22
|
|
#define BUTTON_PIN 9
|
|
|
|
// ============== COCAINE CHIC PALETTE ==============
|
|
#define COLOR_BLACK 0x0000 // #000000
|
|
#define COLOR_COCAINE 0xFFFE // #fff8fa — warm white
|
|
#define COLOR_TEAL 0x05F5 // #0bd3d3 — electric teal
|
|
#define COLOR_FUCHSIA 0xFC6E // #f890e7 — hot pink
|
|
#define COLOR_MINT 0x674D // #64e8ba — confirmation
|
|
|
|
#define ALERT_BG_1 COLOR_TEAL
|
|
#define ALERT_TEXT_1 COLOR_COCAINE
|
|
#define ALERT_BG_2 COLOR_FUCHSIA
|
|
#define ALERT_TEXT_2 COLOR_COCAINE
|
|
|
|
// ============== DISPLAY SETUP (LANDSCAPE) ==============
|
|
#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);
|
|
|
|
// ============== STATE MANAGEMENT ==============
|
|
enum State { STATE_SILENT, STATE_ALERT };
|
|
|
|
State currentState = STATE_SILENT;
|
|
State lastPublishedState = STATE_SILENT;
|
|
|
|
unsigned long lastPoll = 0;
|
|
unsigned long lastSilencePoll = 0;
|
|
unsigned long lastStatusPublish = 0;
|
|
unsigned long blinkStartTime = 0;
|
|
bool blinkState = false;
|
|
|
|
String lastCommandId = "";
|
|
String lastSilenceId = "";
|
|
bool lastButtonState = false;
|
|
String alertMessage = ""; // The message that triggered current alert
|
|
|
|
// ===========================================
|
|
|
|
void setup() {
|
|
Serial.begin(115200);
|
|
delay(3000);
|
|
Serial.println("\n=== KLUBHAUS DOORBELL v3 ===");
|
|
Serial.println("Topics: COMMAND / SILENCE / STATUS");
|
|
Serial.println("Aesthetic: Cocaine Chic (Miami Vice minimal)");
|
|
|
|
pinMode(BACKLIGHT_PIN, OUTPUT);
|
|
digitalWrite(BACKLIGHT_PIN, LOW);
|
|
|
|
pinMode(BUTTON_PIN, INPUT_PULLUP);
|
|
Serial.println("GPIO ready");
|
|
|
|
Serial.println("Init GFX...");
|
|
gfx->begin();
|
|
Serial.println("GFX ready — 320x172 landscape");
|
|
|
|
digitalWrite(BACKLIGHT_PIN, HIGH);
|
|
testDisplay();
|
|
delay(300);
|
|
|
|
transitionTo(STATE_SILENT);
|
|
|
|
// WiFi
|
|
Serial.println("Connecting WiFi...");
|
|
WiFi.begin(ssid, password);
|
|
|
|
int wifiTimeout = 0;
|
|
while (WiFi.status() != WL_CONNECTED && wifiTimeout < 40) {
|
|
delay(500);
|
|
Serial.print(".");
|
|
wifiTimeout++;
|
|
}
|
|
|
|
if (WiFi.status() != WL_CONNECTED) {
|
|
Serial.println("\nWiFi FAILED");
|
|
digitalWrite(BACKLIGHT_PIN, HIGH);
|
|
gfx->fillScreen(COLOR_BLACK);
|
|
drawCenteredText("OFFLINE", 3, COLOR_FUCHSIA, COLOR_BLACK, 70);
|
|
delay(3000);
|
|
digitalWrite(BACKLIGHT_PIN, LOW);
|
|
} else {
|
|
Serial.println("\nWiFi OK: " + WiFi.localIP().toString());
|
|
publishStatus(); // Initial status
|
|
}
|
|
|
|
Serial.println("=== SETUP COMPLETE ===");
|
|
}
|
|
|
|
void loop() {
|
|
unsigned long now = millis();
|
|
handleButton();
|
|
|
|
// Publish status periodically and on state change
|
|
if (now - lastStatusPublish >= STATUS_PUBLISH_INTERVAL || currentState != lastPublishedState) {
|
|
lastStatusPublish = now;
|
|
publishStatus();
|
|
}
|
|
|
|
switch (currentState) {
|
|
case STATE_SILENT:
|
|
if (now - lastSilencePoll >= SILENCE_POLL_INTERVAL) {
|
|
lastSilencePoll = now;
|
|
checkSilenceTopic();
|
|
}
|
|
if (now - lastPoll >= POLL_INTERVAL) {
|
|
lastPoll = 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 — auto silence");
|
|
transitionTo(STATE_SILENT);
|
|
}
|
|
break;
|
|
}
|
|
|
|
delay(10);
|
|
}
|
|
|
|
// ============== STATUS PUBLISHING ==============
|
|
|
|
void publishStatus() {
|
|
if (WiFi.status() != WL_CONNECTED) {
|
|
Serial.println("Status: skip (no WiFi)");
|
|
return;
|
|
}
|
|
|
|
HTTPClient http;
|
|
http.begin(statusTopic);
|
|
http.addHeader("Content-Type", "application/json");
|
|
|
|
StaticJsonDocument<256> doc;
|
|
doc["state"] = (currentState == STATE_SILENT) ? "SILENT" : "ALERTING";
|
|
doc["message"] = alertMessage;
|
|
doc["timestamp"] = millis();
|
|
|
|
String payload;
|
|
serializeJson(doc, payload);
|
|
|
|
int code = http.POST(payload);
|
|
Serial.print("Status publish: ");
|
|
Serial.print(payload);
|
|
Serial.print(" (HTTP ");
|
|
Serial.print(code);
|
|
Serial.println(")");
|
|
|
|
http.end();
|
|
lastPublishedState = currentState;
|
|
}
|
|
|
|
// ============== STATE TRANSITIONS ==============
|
|
|
|
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);
|
|
Serial.println("Silent: screen dark, gallery void");
|
|
break;
|
|
|
|
case STATE_ALERT:
|
|
digitalWrite(BACKLIGHT_PIN, HIGH);
|
|
blinkStartTime = millis();
|
|
blinkState = false;
|
|
drawAlertScreen(ALERT_BG_1, ALERT_TEXT_1);
|
|
Serial.println("Alert: neon pulse active");
|
|
break;
|
|
}
|
|
|
|
publishStatus(); // Immediate state broadcast
|
|
}
|
|
|
|
// ============== TOPIC POLLING ==============
|
|
|
|
void checkCommandTopic() {
|
|
Serial.println("Poll COMMAND...");
|
|
String response = fetchNtfyJson(commandTopic);
|
|
if (response.length() == 0) {
|
|
Serial.println(" No new command");
|
|
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"] | "";
|
|
if (id == lastCommandId) {
|
|
Serial.println(" Same ID, skip");
|
|
return;
|
|
}
|
|
lastCommandId = id;
|
|
|
|
String message = doc["message"] | "";
|
|
Serial.print(" NEW: ");
|
|
Serial.println(message);
|
|
|
|
// SILENCE command = go silent
|
|
if (message.equalsIgnoreCase("SILENCE")) {
|
|
Serial.println(" -> SILENCE command");
|
|
transitionTo(STATE_SILENT);
|
|
flashConfirm("SILENCE", COLOR_MINT, COLOR_BLACK);
|
|
}
|
|
// Any other message = ALERT (FRONT DOOR, LOADING DOCK, custom text)
|
|
else {
|
|
Serial.println(" -> ALERT trigger");
|
|
alertMessage = message; // Store for display
|
|
transitionTo(STATE_ALERT);
|
|
}
|
|
}
|
|
|
|
void checkSilenceTopic() {
|
|
String response = fetchNtfyJson(silenceTopic);
|
|
if (response.length() == 0) return;
|
|
|
|
StaticJsonDocument<512> doc;
|
|
DeserializationError error = deserializeJson(doc, response);
|
|
if (error) return;
|
|
|
|
String id = doc["id"] | "";
|
|
if (id == lastSilenceId) return;
|
|
lastSilenceId = id;
|
|
|
|
String message = doc["message"] | "";
|
|
Serial.print("Silence topic: ");
|
|
Serial.println(message);
|
|
|
|
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(5000);
|
|
|
|
int code = http.GET();
|
|
if (code != 200) {
|
|
Serial.print(" HTTP error: ");
|
|
Serial.println(code);
|
|
http.end();
|
|
return "";
|
|
}
|
|
|
|
String payload = http.getString();
|
|
http.end();
|
|
|
|
// ntfy JSON stream may have multiple lines; take first
|
|
int newline = payload.indexOf('\n');
|
|
if (newline > 0) payload = payload.substring(0, newline);
|
|
|
|
return payload;
|
|
}
|
|
|
|
// ============== VISUAL FEEDBACK ==============
|
|
|
|
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);
|
|
|
|
// "ALERT" header
|
|
drawCenteredText("ALERT", 3, textColor, bgColor, 20);
|
|
|
|
// The triggering message, auto-sized
|
|
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);
|
|
}
|
|
|
|
// ============== BUTTON HANDLING ==============
|
|
|
|
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 CONTROL ==============
|
|
|
|
void updateBlink(unsigned long now) {
|
|
unsigned long elapsed = now - blinkStartTime;
|
|
bool newState = ((elapsed / BLINK_PERIOD) % 2) == 1;
|
|
|
|
if (newState != blinkState) {
|
|
blinkState = newState;
|
|
uint16_t bgColor = blinkState ? ALERT_BG_2 : ALERT_BG_1;
|
|
uint16_t textColor = blinkState ? ALERT_TEXT_2 : ALERT_TEXT_1;
|
|
drawAlertScreen(bgColor, textColor);
|
|
Serial.println(blinkState ? " FUCHSIA flash" : " TEAL flash");
|
|
}
|
|
}
|
|
|
|
// ============== DISPLAY TEST ==============
|
|
|
|
void testDisplay() {
|
|
Serial.println("Display test:");
|
|
|
|
const char* colors[] = {"TEAL", "FUCHSIA", "COCAINE", "MINT", "BLACK"};
|
|
uint16_t colorVals[] = {COLOR_TEAL, COLOR_FUCHSIA, COLOR_COCAINE, COLOR_MINT, COLOR_BLACK};
|
|
|
|
for (int i = 0; i < 5; i++) {
|
|
Serial.print(" ");
|
|
Serial.println(colors[i]);
|
|
gfx->fillScreen(colorVals[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);
|
|
Serial.println("Test complete");
|
|
}
|
|
|