#pragma once #include "message.h" #include "crypto.h" #include struct ServerConfiguration { /** * @brief The url of the remote server to connect to */ const char* url; /** * @brief The server port */ int port; /** * @brief The path on the server */ const char* path; /** * @brief The authentication key for the server */ const char* key; uint32_t reconnectTime; uint32_t socketHeartbeatIntervalMs; uint32_t socketHeartbeatTimeoutMs; uint8_t socketHeartbeatFailureReconnectCount; }; class ServerConnectionCallbacks { public: virtual void sendServerError(MessageResult event) = 0; virtual void handleServerMessage(uint8_t* payload, size_t length) = 0; }; class ServerConnection { public: ServerConnection(ServerConfiguration configuration); /** * @brief Set the configuration and the callback handler * * @param callback The handler to handle messages and errors */ void setCallbacks(ServerConnectionCallbacks* callbacks); void shouldConnect(bool connect); /** * @brief Call this function regularly to handle socket operations. * * Connecting and disconnecting is done automatically. * */ void loop(uint32_t millis); /** * @brief Send a response message over the socket * * @param buffer The data buffer * @param length The number of bytes to send */ void sendResponse(uint8_t* buffer, uint16_t length); private: uint32_t currentTime = 0; bool shouldBeConnected = false; bool socketIsConnected() { return webSocket.isConnected(); } void connect(); bool isConnecting = false; bool isDisconnecting = false; uint32_t connectionTimeout = 0; uint32_t nextReconnectAttemptMs = 0; void didChangeConnectionState(bool isConnected); ServerConfiguration configuration; ServerConnectionCallbacks* controller = NULL; // WebSocket to connect to the control server WebSocketsClient webSocket; /** * Callback for WebSocket events. * * Updates the connection state and processes received keys. * * @param payload The pointer to received data * @param length The number of bytes received */ void webSocketEventHandler(WStype_t type, uint8_t * payload, size_t length); };