82 lines
2.1 KiB
C++
82 lines
2.1 KiB
C++
/**
|
|
* Sesame-Device
|
|
* Christoph Hagen, 2022.
|
|
*
|
|
* The code for a simple door unlock mechanism where a servo pushes on an existing
|
|
* physical button.
|
|
*/
|
|
#include <Arduino.h>
|
|
#include <WiFi.h>
|
|
#include <ESPAsyncWebServer.h>
|
|
|
|
#include "crypto.h"
|
|
#include "fresh.h"
|
|
#include "message.h"
|
|
#include "server.h"
|
|
#include "servo.h"
|
|
#include "config.h"
|
|
#include "controller.h"
|
|
|
|
/* Global variables */
|
|
|
|
ServerConnection server(serverUrl, serverPort, serverPath);
|
|
|
|
ServoController servo(pwmTimer, servoFrequency, servoPin);
|
|
|
|
AsyncWebServer local(localPort);
|
|
|
|
SesameController controller(&server, &servo, &local, remoteDeviceCount);
|
|
|
|
// Forward declare monitoring functions
|
|
void ensureWiFiConnection(uint32_t time);
|
|
void ensureWebSocketConnection(uint32_t time);
|
|
|
|
/* Logic */
|
|
|
|
void setup() {
|
|
Serial.begin(serialBaudRate);
|
|
Serial.setDebugOutput(true);
|
|
Serial.println("[INFO] Device started");
|
|
|
|
servo.configure(lockOpeningDuration, servoPressedState, servoReleasedState);
|
|
Serial.println("[INFO] Servo configured");
|
|
|
|
controller.configure();
|
|
}
|
|
|
|
void loop() {
|
|
uint32_t time = millis();
|
|
|
|
server.loop();
|
|
servo.loop();
|
|
|
|
ensureWiFiConnection(time);
|
|
ensureWebSocketConnection(time);
|
|
}
|
|
|
|
uint32_t nextWifiReconnect = 0;
|
|
bool isReconnecting = false;
|
|
|
|
void ensureWiFiConnection(uint32_t time) {
|
|
// Reconnect to WiFi
|
|
if(time > nextWifiReconnect && WiFi.status() != WL_CONNECTED) {
|
|
Serial.println("[INFO] Reconnecting WiFi...");
|
|
WiFi.setHostname(networkName);
|
|
WiFi.begin(wifiSSID, wifiPassword);
|
|
isReconnecting = true;
|
|
nextWifiReconnect = time + wifiReconnectInterval;
|
|
}
|
|
}
|
|
|
|
void ensureWebSocketConnection(uint32_t time) {
|
|
if (isReconnecting && WiFi.status() == WL_CONNECTED) {
|
|
isReconnecting = false;
|
|
Serial.println("IP address: ");
|
|
Serial.println(WiFi.localIP());
|
|
Serial.println("[INFO] WiFi connected, opening socket");
|
|
server.connect(serverAccessKey);
|
|
configureNTP(timeOffsetToGMT, timeOffsetDaylightSavings, ntpServerUrl);
|
|
printLocalTime();
|
|
local.begin();
|
|
}
|
|
} |