This commit is contained in:
2026-02-12 12:19:04 -08:00
parent 6555a933a6
commit 29a4832894
2 changed files with 137 additions and 141 deletions

View File

@@ -337,7 +337,11 @@
<button class="admin-btn" onclick="sendAdmin('SILENCE')">Force Silence</button>
<button class="admin-btn" onclick="sendAdmin('PING')">Ping Device</button>
<button class="admin-btn danger" onclick="sendAdmin('REBOOT')">Reboot</button>
<button class="admin-btn" onclick="showHelp()">Help</button>
<button class="admin-btn" onclick="setLogLevel('DEBUG')">Log: Debug</button>
<button class="admin-btn" onclick="setLogLevel('INFO')">Log: Info</button>
<button class="admin-btn" onclick="setLogLevel('WARN')">Log: Warn</button>
<button class="admin-btn" onclick="setLogLevel('ERROR')">Log: Error</button>
<button class="admin-btn" onclick="setLogLevel('NONE')">Log: Off</button> <button class="admin-btn" onclick="showHelp()">Help</button>
</div>
</div>

View File

@@ -1,5 +1,5 @@
// ============== KLUBHAUS DOORBELL v4.0.0 ==============
// Features: Screen fallback mode, LED-only mode, Serial config commands, Admin topic
// ============== KLUBHAUS DOORBELL v4.1.0 ==============
// Features: Configurable log levels, faster serial, optimized polling
#include <WiFi.h>
#include <HTTPClient.h>
@@ -14,7 +14,7 @@
#define NTFY_ALERT_TOPIC "ALERT_klubhaus_topic"
#define NTFY_SILENCE_TOPIC "SILENCE_klubhaus_topic"
#define NTFY_STATUS_TOPIC "STATUS_klubhaus_topic"
#define NTFY_ADMIN_TOPIC "ADMIN_klubhaus_topic" // NEW: Admin/config topic
#define NTFY_ADMIN_TOPIC "ADMIN_klubhaus_topic"
#define NTFY_SERVER "ntfy.sh"
// Display pins for ESP32-C6-LCD-1.47
@@ -25,9 +25,7 @@
#define TFT_RST 21
#define TFT_BL 22
#define BUTTON_PIN 9
// LED pin (built-in or external) - adjust for your board
#define LED_PIN 8 // ESP32-C6 built-in RGB LED or GPIO for external LED
#define LED_PIN 8
// ============== COLORS ==============
#define COLOR_TEAL 0x0BD3D3
@@ -36,6 +34,18 @@
#define COLOR_MINT 0x64E8BA
#define COLOR_BLACK 0x0A0A0A
// ============== LOGGING ==============
// Configurable at runtime - stored in RAM (could use Preferences for persistence)
enum LogLevel { LOG_DEBUG = 0, LOG_INFO = 1, LOG_WARN = 2, LOG_ERROR = 3, LOG_FATAL = 4, LOG_NONE = 5 };
LogLevel currentLogLevel = LOG_INFO; // Default: INFO and above (no DEBUG spam)
const char* LOG_NAMES[] = {"DBG", "INF", "WRN", "ERR", "FTL", "OFF"};
// Fast log function - checks level first, minimal overhead
#define LOG(level, component, msg) do { \
if (level >= currentLogLevel) logMsg(level, component, msg); \
} while(0)
// ============== DISPLAY ==============
Arduino_DataBus *bus = new Arduino_SWSPI(TFT_DC, TFT_CS, TFT_SCLK, TFT_MOSI, GFX_NOT_DEFINED);
Arduino_GFX *gfx = new Arduino_ST7789(bus, TFT_RST, 0, true, 172, 320);
@@ -50,22 +60,21 @@ unsigned long lastAlertPoll = 0;
unsigned long lastSilencePoll = 0;
unsigned long lastAdminPoll = 0;
const unsigned long POLL_INTERVAL_MS = 3000;
const unsigned long ADMIN_POLL_INTERVAL_MS = 10000; // Admin checks less frequently
const unsigned long ADMIN_POLL_INTERVAL_MS = 10000;
// ============== FALLBACK MODE ==============
enum DisplayMode { MODE_SCREEN, MODE_LED_ONLY };
DisplayMode currentDisplayMode = MODE_SCREEN;
bool screenAvailable = true; // Set to false if screen init fails
bool screenAvailable = true;
// ============== SERIAL COMMANDS ==============
String serialBuffer = "";
static const size_t SERIAL_BUFFER_MAX = 64; // Limit buffer size
// ============== LOGGING ==============
enum LogLevel { LOG_DEBUG, LOG_INFO, LOG_WARN, LOG_ERROR, LOG_FATAL };
// ============== FAST LOGGING ==============
void logMsg(LogLevel level, const char* component, const String& msg) {
const char* lvl[] = {"DBG", "INF", "WRN", "ERR", "FTL"};
Serial.printf("[%s] %s: %s\n", lvl[level], component, msg.c_str());
// Use printf for single-call output (faster than multiple Serial calls)
Serial.printf("[%s] %s: %s\n", LOG_NAMES[level], component, msg.c_str());
}
void logMsg(LogLevel level, const char* component, const char* msg) {
@@ -73,7 +82,9 @@ void logMsg(LogLevel level, const char* component, const char* msg) {
}
// ============== HTTP ERROR DECODER ==============
// Only compile error strings when needed (LOG_DEBUG level)
String decodeHttpError(int code) {
#ifdef DEBUG_HTTP_CODES
if (code == -1) return "CONNECTION_REFUSED";
if (code == -2) return "SEND_PAYLOAD_FAILED";
if (code == -3) return "NOT_CONNECTED";
@@ -85,21 +96,14 @@ String decodeHttpError(int code) {
if (code == -9) return "STREAM_WRITE";
if (code == -10) return "READ_TIMEOUT";
if (code == -11) return "CONNECTION_TIMEOUT";
#endif
return "HTTP_" + String(code);
}
// ============== TIME ==============
unsigned long getEpochMs() {
return millis();
}
// ============== LED CONTROL ==============
void initLED() {
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
// For RGB LED on ESP32-C6, you might need neopixel library
// This is basic single-color LED control
}
void setLED(bool on) {
@@ -118,7 +122,6 @@ void flashLED(int times, int onMs = 200, int offMs = 200) {
void pulseLED(int durationMs) {
unsigned long start = millis();
while (millis() - start < durationMs) {
// Simple pulse effect
setLED(true);
delay(100);
setLED(false);
@@ -131,7 +134,6 @@ void initDisplay() {
pinMode(TFT_BL, OUTPUT);
digitalWrite(TFT_BL, LOW);
// Try to init screen - if it fails, we fall back to LED mode
gfx->begin();
gfx->setRotation(1);
gfx->fillScreen(COLOR_BLACK);
@@ -141,7 +143,7 @@ void initDisplay() {
delay(500);
digitalWrite(TFT_BL, LOW);
logMsg(LOG_INFO, "DISPLAY", "Screen initialized");
LOG(LOG_INFO, "DISPLAY", "Screen initialized");
}
void setBacklight(bool on) {
@@ -162,8 +164,7 @@ void showSilent() {
void showAlert(const String& msg) {
if (currentDisplayMode == MODE_LED_ONLY) {
// Flash LED pattern for alert
pulseLED(5000); // Pulse for 5 seconds
pulseLED(5000);
return;
}
@@ -187,7 +188,7 @@ void showAlert(const String& msg) {
void flashConfirm(const char* text) {
if (currentDisplayMode == MODE_LED_ONLY) {
flashLED(3, 100, 100); // Quick triple flash
flashLED(3, 100, 100);
return;
}
@@ -209,13 +210,13 @@ void flashConfirm(const char* text) {
// ============== NETWORK ==============
void initWiFi() {
logMsg(LOG_INFO, "WIFI", "Connecting...");
LOG(LOG_INFO, "WIFI", "Connecting...");
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500); Serial.print(".");
}
Serial.println();
logMsg(LOG_INFO, "WIFI", "IP: " + WiFi.localIP().toString());
LOG(LOG_INFO, "WIFI", "IP: " + WiFi.localIP().toString());
}
// ============== ntfy.sh ==============
@@ -223,6 +224,7 @@ void initWiFi() {
bool parseNtfyLine(const String& line, String& outId, String& outMessage, String& outEvent) {
if (line.length() == 0 || line.indexOf('{') < 0) return false;
// Fast extraction without creating intermediate strings when possible
auto extract = [&](const char* key) -> String {
String search = String("\"") + key + "\":\"";
int start = line.indexOf(search);
@@ -249,17 +251,16 @@ bool parseNtfyLine(const String& line, String& outId, String& outMessage, String
bool fetchNtfy(const char* topic, String& outId, String& outMessage, String& outEvent) {
HTTPClient http;
String url = String("https://") + NTFY_SERVER + "/" + topic + "/json?since=all";
logMsg(LOG_DEBUG, "HTTP", "GET " + url);
LOG(LOG_DEBUG, "HTTP", "GET " + url);
http.setTimeout(8000);
http.begin(url);
int code = http.GET();
if (code != 200) {
logMsg(LOG_ERROR, "HTTP", String(code) + "=" + decodeHttpError(code));
LOG(LOG_ERROR, "HTTP", String(code) + "=" + decodeHttpError(code));
http.end();
return false;
}
@@ -267,9 +268,12 @@ bool fetchNtfy(const char* topic, String& outId, String& outMessage, String& out
String payload = http.getString();
http.end();
// Only log full payload at DEBUG level
#if 0 // Disabled - too slow
String preview = payload.substring(0, min((int)payload.length(), 150));
preview.replace("\n", "\\n");
logMsg(LOG_DEBUG, "RAW", preview);
LOG(LOG_DEBUG, "RAW", preview);
#endif
bool found = false;
int lineStart = 0;
@@ -286,7 +290,7 @@ bool fetchNtfy(const char* topic, String& outId, String& outMessage, String& out
if (line.length() > 0) {
String id, msg, evt;
if (parseNtfyLine(line, id, msg, evt)) {
logMsg(LOG_DEBUG, "JSON", String("L") + lineNum + " evt=" + evt + " id=" + id + " msg=" + (msg.length() ? msg : "EMPTY"));
LOG(LOG_DEBUG, "JSON", String("L") + lineNum + " evt=" + evt + " id=" + id);
if (evt == "message" && msg.length() > 0) {
outId = id;
@@ -310,26 +314,54 @@ void postStatus(const char* state, const String& msg) {
http.begin(url);
http.addHeader("Content-Type", "application/json");
int code = http.POST(payload);
logMsg(LOG_INFO, "STATUS", String("POST ") + code + " " + payload);
LOG(LOG_INFO, "STATUS", String("POST ") + code + " " + payload);
http.end();
}
// ============== LOG LEVEL CONTROL ==============
void setLogLevel(LogLevel level) {
currentLogLevel = level;
LOG(LOG_INFO, "CONFIG", String("Log level set to ") + LOG_NAMES[level]);
}
void setLogLevel(const String& levelStr) {
if (levelStr == "DEBUG" || levelStr == "0") setLogLevel(LOG_DEBUG);
else if (levelStr == "INFO" || levelStr == "1") setLogLevel(LOG_INFO);
else if (levelStr == "WARN" || levelStr == "WARNING" || levelStr == "2") setLogLevel(LOG_WARN);
else if (levelStr == "ERROR" || levelStr == "3") setLogLevel(LOG_ERROR);
else if (levelStr == "FATAL" || levelStr == "4") setLogLevel(LOG_FATAL);
else if (levelStr == "NONE" || levelStr == "OFF" || levelStr == "5") setLogLevel(LOG_NONE);
else {
LOG(LOG_WARN, "CONFIG", "Unknown log level: " + levelStr);
}
}
// ============== ADMIN / CONFIG ==============
void processAdminCommand(const String& cmd) {
logMsg(LOG_INFO, "ADMIN", "Processing: " + cmd);
LOG(LOG_INFO, "ADMIN", "Processing: " + cmd);
// Log level commands
if (cmd.startsWith("LOG ")) {
String level = cmd.substring(4);
level.trim();
setLogLevel(level);
postStatus("CONFIG", "log=" + level);
return;
}
if (cmd == "MODE_SCREEN") {
currentDisplayMode = MODE_SCREEN;
logMsg(LOG_INFO, "ADMIN", "Switched to SCREEN mode");
LOG(LOG_INFO, "ADMIN", "Switched to SCREEN mode");
postStatus("CONFIG", "mode=screen");
flashConfirm("SCREEN MODE");
}
else if (cmd == "MODE_LED") {
currentDisplayMode = MODE_LED_ONLY;
logMsg(LOG_INFO, "ADMIN", "Switched to LED mode");
LOG(LOG_INFO, "ADMIN", "Switched to LED mode");
postStatus("CONFIG", "mode=led");
showSilent(); // Turn off screen
showSilent();
flashConfirm("LED MODE");
}
else if (cmd == "SILENCE" || cmd == "SILENT") {
@@ -342,24 +374,17 @@ void processAdminCommand(const String& cmd) {
postStatus("PONG", "device=klubhaus");
}
else if (cmd == "REBOOT") {
logMsg(LOG_INFO, "ADMIN", "Rebooting...");
LOG(LOG_INFO, "ADMIN", "Rebooting...");
postStatus("CONFIG", "rebooting");
delay(500);
ESP.restart();
}
else if (cmd.startsWith("WIFI ")) {
// Format: WIFI newssid newpassword
// Not implementing full reconnection here for safety
logMsg(LOG_WARN, "ADMIN", "WiFi change requested - manual reboot required");
LOG(LOG_WARN, "ADMIN", "WiFi change requires manual reboot");
postStatus("CONFIG", "wifi_change_pending");
}
else if (cmd.startsWith("TOPIC ")) {
// Format: TOPIC ALERT newtopicname
logMsg(LOG_WARN, "ADMIN", "Topic change not implemented in runtime");
postStatus("CONFIG", "topic_change_ignored");
}
else {
logMsg(LOG_WARN, "ADMIN", "Unknown command: " + cmd);
LOG(LOG_WARN, "ADMIN", "Unknown command: " + cmd);
}
}
@@ -367,13 +392,13 @@ void checkAdminTopic() {
String id, message, event;
if (fetchNtfy(NTFY_ADMIN_TOPIC, id, message, event)) {
logMsg(LOG_INFO, "ADMIN", "GOT: id=" + id + " msg=[" + message + "]");
LOG(LOG_INFO, "ADMIN", "GOT: id=" + id + " msg=[" + message + "]");
if (id != lastProcessedAdminId) {
lastProcessedAdminId = id;
processAdminCommand(message);
} else {
logMsg(LOG_DEBUG, "ADMIN", "Duplicate ID, ignored");
LOG(LOG_DEBUG, "ADMIN", "Duplicate ID, ignored");
}
}
}
@@ -381,33 +406,38 @@ void checkAdminTopic() {
// ============== SERIAL COMMANDS ==============
void processSerialCommand(const String& cmd) {
logMsg(LOG_INFO, "SERIAL", "Command: " + cmd);
LOG(LOG_INFO, "SERIAL", "Command: " + cmd);
// Same commands as admin topic
if (cmd == "help" || cmd == "?") {
Serial.println("=== KLUBHAUS COMMANDS ===");
Serial.println("mode screen - Use screen + LED");
Serial.println("mode led - LED only (screen off)");
Serial.println("silence - Force silence");
Serial.println("ping - Test connectivity");
Serial.println("reboot - Restart device");
Serial.println("status - Show current state");
Serial.println("wifi <ssid> <pass> - Change WiFi (reboot required)");
Serial.println("=========================");
Serial.println("mode screen - Use screen + LED");
Serial.println("mode led - LED only (screen off)");
Serial.println("log <level> - Set log level (debug/info/warn/error/fatal/none)");
Serial.println("silence - Force silence");
Serial.println("ping - Test connectivity");
Serial.println("reboot - Restart device");
Serial.println("status - Show current state");
Serial.println("============================");
}
else if (cmd == "mode screen") {
currentDisplayMode = MODE_SCREEN;
logMsg(LOG_INFO, "SERIAL", "Switched to SCREEN mode");
LOG(LOG_INFO, "SERIAL", "Switched to SCREEN mode");
postStatus("CONFIG", "mode=screen");
flashConfirm("SCREEN MODE");
}
else if (cmd == "mode led") {
currentDisplayMode = MODE_LED_ONLY;
logMsg(LOG_INFO, "SERIAL", "Switched to LED mode");
LOG(LOG_INFO, "SERIAL", "Switched to LED mode");
postStatus("CONFIG", "mode=led");
showSilent();
flashConfirm("LED MODE");
}
else if (cmd.startsWith("log ")) {
String level = cmd.substring(4);
level.trim();
setLogLevel(level);
Serial.printf("Log level: %s\n", LOG_NAMES[currentLogLevel]);
}
else if (cmd == "silence") {
if (currentState == ALERTING) {
setState(SILENT, "");
@@ -419,59 +449,43 @@ void processSerialCommand(const String& cmd) {
Serial.println("pong");
}
else if (cmd == "reboot") {
logMsg(LOG_INFO, "SERIAL", "Rebooting...");
LOG(LOG_INFO, "SERIAL", "Rebooting...");
ESP.restart();
}
else if (cmd == "status") {
Serial.printf("State: %s\n", currentState == ALERTING ? "ALERTING" : "SILENT");
Serial.printf("Mode: %s\n", currentDisplayMode == MODE_SCREEN ? "SCREEN" : "LED_ONLY");
Serial.printf("Log: %s\n", LOG_NAMES[currentLogLevel]);
Serial.printf("Message: %s\n", currentMessage.c_str());
Serial.printf("Screen: %s\n", screenAvailable ? "OK" : "BROKEN/UNAVAILABLE");
Serial.printf("WiFi: %s\n", WiFi.isConnected() ? "CONNECTED" : "DISCONNECTED");
Serial.printf("IP: %s\n", WiFi.localIP().toString().c_str());
}
else if (cmd.startsWith("wifi ")) {
// Parse: wifi ssid password
int firstSpace = cmd.indexOf(' ');
int secondSpace = cmd.indexOf(' ', firstSpace + 1);
if (secondSpace > 0) {
String newSsid = cmd.substring(firstSpace + 1, secondSpace);
String newPass = cmd.substring(secondSpace + 1);
logMsg(LOG_INFO, "SERIAL", "WiFi config updated (reboot to apply)");
Serial.println("WiFi updated. Reboot to apply:");
Serial.println(" SSID: " + newSsid);
// Don't print password
// Store in preferences or just inform user to update code
} else {
Serial.println("Usage: wifi <ssid> <password>");
}
}
else {
Serial.println("Unknown command. Type 'help' for list.");
Serial.println("Unknown. Type 'help'");
}
}
void checkSerial() {
// Fast check - avoid String building when possible
while (Serial.available()) {
char c = Serial.read();
if (c == '\n' || c == '\r') {
if (serialBuffer.length() > 0) {
serialBuffer.trim();
serialBuffer.toLowerCase();
processSerialCommand(serialBuffer);
// Convert to lowercase for matching, but keep original for values
String cmdLower = serialBuffer;
cmdLower.toLowerCase();
processSerialCommand(cmdLower);
serialBuffer = "";
}
} else {
serialBuffer += c;
// Prevent buffer overflow
if (serialBuffer.length() > 100) {
serialBuffer = "";
Serial.println("Command too long, cleared");
} else if (c >= 32 && c < 127) { // Printable ASCII only
if (serialBuffer.length() < SERIAL_BUFFER_MAX) {
serialBuffer += c;
}
}
// Ignore non-printable characters (including backspace for speed)
}
}
@@ -490,11 +504,10 @@ void setState(State newState, const String& msg) {
postStatus(newState == ALERTING ? "ALERTING" : "SILENT", msg);
}
// ============== BUTTON HANDLING (WITH DOUBLE-PRESS) ==============
// ============== BUTTON HANDLING ==============
void checkButton() {
static bool lastState = HIGH;
static unsigned long pressStart = 0;
static unsigned long lastPressEnd = 0;
static bool wasPressed = false;
static int pressCount = 0;
static unsigned long firstPressTime = 0;
@@ -502,72 +515,53 @@ void checkButton() {
bool pressed = (digitalRead(BUTTON_PIN) == LOW);
if (pressed && !lastState) {
// Button just pressed
logMsg(LOG_INFO, "BUTTON", "PRESSED");
setBacklight(true);
pressStart = millis();
wasPressed = true;
// Check for double press
if (pressCount == 0) {
firstPressTime = millis();
pressCount = 1;
} else if (millis() - firstPressTime < 500) {
// Double press detected!
pressCount = 2;
logMsg(LOG_INFO, "BUTTON", "DOUBLE PRESS - TOGLING MODE");
LOG(LOG_INFO, "BUTTON", "DOUBLE PRESS - TOGLING MODE");
// Toggle display mode
if (currentDisplayMode == MODE_SCREEN) {
currentDisplayMode = MODE_LED_ONLY;
showSilent(); // Turn off screen immediately
showSilent();
flashConfirm("LED MODE");
logMsg(LOG_INFO, "BUTTON", "Switched to LED mode");
LOG(LOG_INFO, "BUTTON", "Switched to LED mode");
postStatus("CONFIG", "mode=led (button)");
} else {
currentDisplayMode = MODE_SCREEN;
flashConfirm("SCREEN MODE");
logMsg(LOG_INFO, "BUTTON", "Switched to SCREEN mode");
LOG(LOG_INFO, "BUTTON", "Switched to SCREEN mode");
postStatus("CONFIG", "mode=screen (button)");
}
}
} else if (!pressed && lastState && wasPressed) {
// Button just released
unsigned long duration = millis() - pressStart;
unsigned long now = millis();
logMsg(LOG_INFO, "BUTTON", String("RELEASED ") + duration + "ms");
// Handle single press actions
if (pressCount == 1) {
if (now - firstPressTime > 500) {
// Single press confirmed (not part of double)
if (millis() - firstPressTime > 500) {
if (currentState == ALERTING) {
logMsg(LOG_INFO, "BUTTON", "Force silence");
LOG(LOG_INFO, "BUTTON", "Force silence");
setState(SILENT, "");
flashConfirm("SILENCED");
} else {
// Just flash to acknowledge
flashConfirm("READY");
}
pressCount = 0;
} else {
// Wait to see if this becomes a double press
// Don't clear pressCount yet
}
} else if (pressCount == 2) {
// Double press already handled on press, just reset
pressCount = 0;
}
wasPressed = false;
lastPressEnd = now;
}
// Timeout for single press detection
if (pressCount == 1 && millis() - firstPressTime > 500) {
// Single press timeout - treat as single press
if (currentState == ALERTING) {
logMsg(LOG_INFO, "BUTTON", "Force silence (single)");
LOG(LOG_INFO, "BUTTON", "Force silence (single)");
setState(SILENT, "");
flashConfirm("SILENCED");
} else {
@@ -582,39 +576,36 @@ void checkButton() {
// ============== MAIN ==============
void setup() {
Serial.begin(115200);
delay(1000);
// Don't wait for serial - continue boot immediately
// This makes the device responsive even without serial monitor
logMsg(LOG_INFO, "MAIN", "=== KLUBHAUS DOORBELL v4.0.0 ===");
logMsg(LOG_INFO, "MAIN", "Features: Fallback mode, Serial commands, Admin topic");
delay(100); // Brief delay for hardware init
LOG(LOG_INFO, "MAIN", "=== KLUBHAUS DOORBELL v4.1.0 ===");
LOG(LOG_INFO, "MAIN", "Log level: INFO (set via 'log debug' for verbose)");
pinMode(BUTTON_PIN, INPUT_PULLUP);
initLED();
// Try to init display - if it fails, auto-fallback to LED
// You can force LED mode by holding button during boot
bool forceLedMode = (digitalRead(BUTTON_PIN) == LOW);
if (forceLedMode) {
logMsg(LOG_INFO, "MAIN", "Button held at boot - forcing LED mode");
LOG(LOG_INFO, "MAIN", "Button held at boot - forcing LED mode");
currentDisplayMode = MODE_LED_ONLY;
screenAvailable = false;
delay(500); // Wait for button release
delay(500);
} else {
// Try to init display
// If screen is broken, this might hang or fail silently
// For now we assume it works unless explicitly disabled
initDisplay();
}
initWiFi();
postStatus("SILENT", "");
logMsg(LOG_INFO, "MAIN", "READY - Double-press button to toggle mode");
logMsg(LOG_INFO, "MAIN", "Serial commands available - type 'help'");
LOG(LOG_INFO, "MAIN", "READY - Double-press: toggle mode | Serial: 'help'");
}
void loop() {
checkButton();
checkSerial(); // NEW: Check for serial commands
checkSerial();
unsigned long now = millis();
@@ -625,31 +616,31 @@ void loop() {
String id, message, event;
if (fetchNtfy(NTFY_ALERT_TOPIC, id, message, event)) {
logMsg(LOG_INFO, "ALERT", "GOT: id=" + id + " msg=[" + message + "]");
LOG(LOG_INFO, "ALERT", "GOT: id=" + id + " msg=[" + message + "]");
if (id != lastProcessedAlertId) {
lastProcessedAlertId = id;
if (message != "SILENCE") {
logMsg(LOG_INFO, "ALERT", "TRIGGER: " + message);
LOG(LOG_INFO, "ALERT", "TRIGGER: " + message);
setState(ALERTING, message);
}
} else {
logMsg(LOG_DEBUG, "ALERT", "Duplicate ID, ignored");
LOG(LOG_DEBUG, "ALERT", "Duplicate ID, ignored");
}
}
}
// Poll silence topic
// Poll silence topic (staggered)
if (now - lastSilencePoll >= POLL_INTERVAL_MS + 1500) {
lastSilencePoll = now;
String id, message, event;
if (fetchNtfy(NTFY_SILENCE_TOPIC, id, message, event)) {
logMsg(LOG_INFO, "SILENCE", "GOT: id=" + id + " msg=[" + message + "]");
LOG(LOG_INFO, "SILENCE", "GOT: id=" + id);
if (message.indexOf("silence") >= 0 || message == "SILENCE") {
logMsg(LOG_INFO, "SILENCE", "ACKNOWLEDGED");
LOG(LOG_INFO, "SILENCE", "ACKNOWLEDGED");
if (currentState == ALERTING) {
setState(SILENT, "");
}
@@ -657,12 +648,13 @@ void loop() {
}
}
// Poll admin topic (less frequently)
// Poll admin topic
if (now - lastAdminPoll >= ADMIN_POLL_INTERVAL_MS) {
lastAdminPoll = now;
checkAdminTopic();
}
delay(50);
// Yield to allow WiFi stack processing
delay(1);
}