Sesame-Device/include/server.h

111 lines
2.3 KiB
C
Raw Normal View History

#pragma once
#include "message.h"
#include "crypto.h"
#include <WebSocketsClient.h>
2023-08-09 15:02:24 +02:00
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;
2023-12-05 21:31:11 +01:00
uint32_t socketHeartbeatIntervalMs;
uint32_t socketHeartbeatTimeoutMs;
uint8_t socketHeartbeatFailureReconnectCount;
2023-08-09 15:02:24 +02:00
};
2023-08-09 12:55:11 +02:00
class ServerConnectionCallbacks {
public:
2023-12-05 20:46:41 +01:00
virtual void sendServerError(MessageResult event) = 0;
2023-08-09 12:55:11 +02:00
virtual void handleServerMessage(uint8_t* payload, size_t length) = 0;
};
class ServerConnection {
public:
2023-08-09 15:02:24 +02:00
ServerConnection();
2023-08-09 12:55:11 +02:00
/**
2023-08-09 15:02:24 +02:00
* @brief Set the configuration and the callback handler
2023-08-09 12:55:11 +02:00
*
* @param callback The handler to handle messages and errors
*/
2023-08-09 15:02:24 +02:00
void configure(ServerConfiguration configuration, ServerConnectionCallbacks* callbacks);
2023-12-05 21:31:11 +01:00
/**
* @brief Call this function regularly to handle socket operations.
*
* Connecting and disconnecting is done automatically.
*
*/
void loop(uint32_t millis);
2023-08-09 12:55:11 +02:00
/**
* @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);
2023-12-05 21:31:11 +01:00
private:
uint32_t currentTime;
bool socketIsConnected() {
2023-11-03 14:33:22 +01:00
return webSocket.isConnected();
2023-08-09 12:55:11 +02:00
}
2023-12-05 21:31:11 +01:00
void connect();
void disconnect();
bool shouldReconnect = true;
bool isConnecting = false;
uint32_t connectionTimeout = 0;
2023-12-05 21:31:11 +01:00
uint32_t nextReconnectAttemptMs = 0;
void didDisconnect();
void didConnect();
2023-08-09 15:02:24 +02:00
ServerConfiguration configuration;
2023-08-09 12:55:11 +02:00
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);
};