Sesame-Device/include/server.h

108 lines
2.7 KiB
C
Raw Normal View History

#pragma once
#include "message.h"
#include "crypto.h"
#include <WiFiMulti.h>
#include <WiFiClientSecure.h>
#include <WebSocketsClient.h>
/**
* An event signaled from the device
*/
enum class SesameEvent {
TextReceived = 1,
UnexpectedSocketEvent = 2,
InvalidPayloadSize = 3,
MessageAuthenticationFailed = 4,
MessageTimeMismatch = 5,
MessageCounterInvalid = 6,
MessageAccepted = 7,
InfoMessage = 8,
};
/**
* @brief A callback for messages received over the socket
*
* The first parameter is the received message.
* The second parameter is the response to the remote.
* The return value is the type of event to respond with.
*/
typedef SesameEvent (*MessageCallback)(AuthenticatedMessage*, AuthenticatedMessage*);
class ServerConnection {
public:
ServerConnection(const char* url, int port, const char* path);
void connect(const char* key, uint32_t reconnectTime = 5000);
void connectSSL(const char* key, uint32_t reconnectTime = 5000);
void loop();
void onMessage(MessageCallback callback);
// Indicator that the socket is connected.
bool socketIsConnected = false;
private:
const char* url;
int port;
const char* path;
const char* key = NULL;
MessageCallback messageCallback = NULL;
// WebSocket to connect to the control server
WebSocketsClient webSocket;
void reconnectAfter(uint32_t reconnectTime);
void registerEventCallback();
/**
* 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);
/**
* Process received binary data.
*
* Checks whether the received data is a valid and unused key,
* and then signals that the motor should move.
* Sends the event id to the server as a response to the request.
*
* If the key is valid, then `shouldStartOpening` is set to true.
*
* @param payload The pointer to the received data.
* @param length The number of bytes received.
*/
void processReceivedBytes(uint8_t* payload, size_t length);
/**
* Send a response event to the server and include the next key index.
*
* Sends the event type as three byte.
* @param event The event type
*/
void sendFailureResponse(SesameEvent event);
/**
* Send a response event to the server and include the next key index.
*
* Sends the event type as three byte.
* @param event The event type
*/
void sendResponse(SesameEvent event, AuthenticatedMessage* message);
};