Sesame-Device/include/controller.h
2023-11-04 11:14:40 +01:00

83 lines
2.3 KiB
C++

#pragma once
#include "server.h"
#include "servo.h"
#include "message.h"
#include "storage.h"
#include "fresh.h"
#include <ESPAsyncWebServer.h>
struct WifiConfiguration {
// The WiFi network to connect to
const char* ssid;
// The WiFi password to connect to the above network
const char* password;
// The name of the device on the network
const char* networkName;
// The interval to reconnect to WiFi if the connection is broken
uint32_t reconnectInterval;
uint32_t periodicReconnectInterval;
};
struct KeyConfiguration {
const uint8_t* remoteKey;
const uint8_t* localKey;
};
class SesameController: public ServerConnectionCallbacks {
public:
SesameController(uint16_t localWebServerPort, uint8_t remoteDeviceCount);
void configure(ServoConfiguration servoConfig, ServerConfiguration serverConfig, TimeConfiguration timeConfig, WifiConfiguration wifiConfig, KeyConfiguration keyConfig);
void loop(uint32_t millis);
private:
ServerConnection server;
ServoController servo;
AsyncWebServer localWebServer;
TimeCheck timeCheck;
Storage storage;
WifiConfiguration wifiConfig;
KeyConfiguration keyConfig;
bool isReconnecting = false;
// The buffer to hold a received message while it is read
uint8_t receivedMessageBuffer[AUTHENTICATED_MESSAGE_SIZE];
// The buffer to hold a response while it is sent
uint8_t responseBuffer[AUTHENTICATED_MESSAGE_SIZE+1];
SesameEvent* responseStatus;
AuthenticatedMessage* responseMessage;
uint16_t responseSize = 0;
void ensureWiFiConnection(uint32_t time);
void ensureWebSocketConnection();
void handleLocalMessage(AsyncWebServerRequest *request);
// Based on https://stackoverflow.com/a/23898449/266720
bool convertHexMessageToBinary(const char* str);
void handleServerMessage(uint8_t* payload, size_t length);
void sendServerError(SesameEvent event);
void processMessage(AuthenticatedMessage* message);
SesameEvent verifyAndProcessReceivedMessage(AuthenticatedMessage* message);
void prepareResponseBuffer(SesameEvent event, uint8_t deviceId = 0);
void sendPreparedLocalResponse(AsyncWebServerRequest *request);
void sendPreparedServerResponse();
void periodicallyReconnectWifiAndSocket(uint32_t millis);
};