This repository has been archived on 2023-12-22. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
old-monorepo/modules/control/Firmware/src/main.cpp

109 lines
No EOL
2.4 KiB
C++

#include <Arduino.h>
#include <LightController.h>
#include <SerialCommunicator.h>
#include <BluetoothCommunicator.h>
#include <WebsocketCommunicator.h>
#include <PinMap/PinMap.h>
#include <esp_spi_flash.h>
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <Credentials/CredentialManager.h>
const int STEPS = 5;
const int WIFI_TIMEOUT = 20;
const int bjtCount = 4;
const int bjtPin[bjtCount] = {SIG1A, SIG1B, SIG2A, SIG2B};
BluetoothSerial bt;
AsyncWebServer server(80);
AsyncWebSocket ws("/ws");
Communicator *computer;
Communicator *phone;
WebsocketCommunicator *websocket;
LightController *light;
void websocketTask(void *parameter)
{
while (true)
{
websocket->sendMessage(light->getBjtState(), light->getBjtCount());
vTaskDelay(100 / portTICK_PERIOD_MS);
}
vTaskDelete(NULL);
}
void registerWebSocketTask()
{
xTaskCreate(websocketTask, "websocketTask", 10000, NULL, 1, NULL);
}
void connectWifi(int timeout)
{
int secondsPassed = 0;
WiFi.setHostname("Heliox");
WiFi.begin(WIFI_SSID, WIFI_PW);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED)
{
if (secondsPassed < timeout)
{
Serial.print(".");
delay(1000);
secondsPassed++;
}
else
{
Serial.println("");
Serial.println("WiFi timed out");
return;
}
}
Serial.println("");
Serial.println(WiFi.localIP());
digitalWrite(LEDB, HIGH);
}
void setup()
{
pinMode(LEDB, OUTPUT);
digitalWrite(LEDB, LOW);
computer = new SerialCommunicator(Serial, 9600, 5, 50);
phone = new BluetoothCommunicator(bt, 5, 50);
light = new LightController(bjtPin, bjtCount);
websocket = new WebsocketCommunicator(ws, server, 50);
connectWifi(WIFI_TIMEOUT);
server.begin();
registerWebSocketTask();
}
void computerCycle()
{
light->updateState(computer->receiveMessage(), STEPS);
computer->sendMessage(light->getBjtState(), light->getBjtCount());
computer->clearBuffer();
}
void phoneCycle()
{
light->updateState(phone->receiveMessage(), STEPS);
phone->sendMessage(light->getBjtState(), light->getBjtCount());
phone->clearBuffer();
}
void websocketCycle()
{
light->updateState(websocket->receiveMessage(), STEPS);
websocket->clearBufferSafely();
}
void loop()
{
computerCycle();
phoneCycle();
websocketCycle();
ws.cleanupClients();
}