Files
project-vesper/vesper/WebSocket_Functions.hpp
bonamin 101f9e7135 MAJOR update. More like a Backup before things get Crazy
Added Websocket Support
Added Universal Message Handling for both MQTT and WS
Added Timekeeper Class, that handles Physical Clock and Scheduling
Added Bell Assignment Settings, Note to Bell mapping
2025-09-05 19:27:13 +03:00

50 lines
1.8 KiB
C++

#pragma once
void sendToApp(String jsonMessage) {
if (activeClient && activeClient->status() == WS_CONNECTED) {
activeClient->text(jsonMessage);
} else {
Serial.println("No active WebSocket client connected.");
}
}
void replyOnWebSocket(AsyncWebSocketClient *client, String list) {
LOG_DEBUG("Sending WebSocket reply: %s", list.c_str());
client->text(list);
}
// Handles incoming WebSocket messages on subscribed topics.
// Could move logic out of this into a dedicated function.
void onWebSocketReceived(AsyncWebSocketClient *client, void *arg, uint8_t *data, size_t len) {
AwsFrameInfo *info = (AwsFrameInfo*)arg;
if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
data[len] = '\0'; // Null-terminate the received data
Serial.printf("Received message: %s\n", (char*)data);
JsonDocument json = payload2json((char*)data);
handleCommand(json, client);
}
}
void onWebSocketEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {
if (type == WS_EVT_DATA) {
onWebSocketReceived(client, arg, data, len);
Serial.println("WebSocket Message Received");
}
if (type == WS_EVT_CONNECT) {
Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
activeClient = client; // Save the connected client
}
if (type == WS_EVT_DISCONNECT) {
Serial.printf("WebSocket client #%u disconnected\n", client->id());
if (client == activeClient) {
activeClient = nullptr; // Clear it if it's the one we saved
}
}
if (type == WS_EVT_ERROR) {
Serial.printf("WebSocket client #%u error(%u): %s\n", client->id(), *((uint16_t*)arg), (char*)data);
}
}