Initialize modern C++ rewrite

This commit is contained in:
GHOSCHT 2023-03-11 14:16:55 +01:00
parent 30ea3a3fd7
commit c68dfed3eb
19 changed files with 115 additions and 562 deletions

39
Firmware/include/README Normal file
View file

@ -0,0 +1,39 @@
This directory is intended for project header files.
A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.
```src/main.c
#include "header.h"
int main (void)
{
...
}
```
Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.
In C, the usual convention is to give header files names that end with `.h'.
It is most portable to use only letters, digits, dashes, and underscores in
header file names, and at most one dot.
Read more about using header files in official GCC documentation:
* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html

View file

@ -1,8 +0,0 @@
#include <BluetoothCommunicator.h>
#include <BluetoothSerial.h>
BluetoothCommunicator::BluetoothCommunicator(BluetoothSerial &p_out, int timeout, __SIZE_TYPE__ bufferSize) : StreamCommunicator(p_out, bufferSize)
{
p_out.begin("Heliox");
p_out.setTimeout(timeout);
}

View file

@ -1,8 +0,0 @@
#include <StreamCommunicator.h>
#include "BluetoothSerial.h"
class BluetoothCommunicator : public StreamCommunicator
{
public:
BluetoothCommunicator(BluetoothSerial &p_out, int timeout, __SIZE_TYPE__ bufferSize);
};

View file

@ -1,62 +0,0 @@
#include <Communicator.h>
#include <cstring>
#include <WString.h>
Communicator::Communicator(__SIZE_TYPE__ bufferSize){
this->messageBuffer = new char[bufferSize];
this->bufferSize = bufferSize;
}
void Communicator::sendMessage(int *values, __SIZE_TYPE__ numberOfValues)
{
}
void Communicator::sendMessage(const char message[])
{
}
char *Communicator::receiveMessage()
{
}
__SIZE_TYPE__ Communicator::calculateMessageOutSize(__SIZE_TYPE__ numberOfValues)
{
return numberOfValues + (numberOfValues - 1) + 1;
}
void Communicator::parseIDs(const int values[], __SIZE_TYPE__ numberOfValues, char *output)
{
String out = "";
__SIZE_TYPE__ outputSize = calculateMessageOutSize(numberOfValues);
__SIZE_TYPE__ outputCharPointer = 0;
for (__SIZE_TYPE__ i = 0; i < numberOfValues; i++)
{
out += values[i];
outputCharPointer++;
if (outputCharPointer < outputSize - 1)
{
out += ',';
outputCharPointer++;
}
}
strcpy(output, out.c_str());
}
char *Communicator::getBuffer()
{
return messageBuffer;
}
void Communicator::clearBuffer()
{
memset(getBuffer(), '\0', getBufferSize());
}
int Communicator::getBufferSize()
{
return this->bufferSize;
}

View file

@ -1,21 +0,0 @@
#ifndef _COMMUNICATOR_INCLUDED_
#define _COMMUNICATOR_INCLUDED_
class Communicator
{
protected:
char *messageBuffer;
__SIZE_TYPE__ bufferSize;
__SIZE_TYPE__ calculateMessageOutSize(__SIZE_TYPE__ numberOfValues);
void parseIDs(const int values[], __SIZE_TYPE__ numberOfValues, char *out);
public:
Communicator(__SIZE_TYPE__ bufferSize);
virtual void sendMessage(int *values, __SIZE_TYPE__ numberOfValues);
virtual void sendMessage(const char message[]);
virtual char *receiveMessage();
char *getBuffer();
void clearBuffer();
int getBufferSize();
};
#endif

View file

@ -1,8 +0,0 @@
#include <I2CCommunicator.h>
#include <Wire.h>
I2CCommunicator::I2CCommunicator(TwoWire &w_out, int slaveAddr, int timeout, __SIZE_TYPE__ bufferSize) : StreamCommunicator(w_out, bufferSize)
{
w_out.begin(slaveAddr);
w_out.setTimeout(timeout);
}

View file

@ -1,8 +0,0 @@
#include <StreamCommunicator.h>
#include <Wire.h>
class I2CCommunicator : public StreamCommunicator
{
public:
I2CCommunicator(TwoWire &w_out, int slaveAddr, int timeout, __SIZE_TYPE__ bufferSize);
};

View file

@ -1,137 +0,0 @@
#include <LightController.h>
#include <string.h>
#include <Arduino.h>
#include <EEPROM.h>
#include <analogWrite.h>
LightController::LightController(const int bjtPins[], __SIZE_TYPE__ bjtCount)
{
this->bjtCount = bjtCount;
this->bjtPins = bjtPins;
this->bjtState = new int[bjtCount];
EEPROM.begin(64);
initializePins();
initializeState();
}
void LightController::initializeState()
{
initializeStateDefaultValues();
restoreState();
}
void LightController::initializePins()
{
for (__SIZE_TYPE__ i = 0; i < bjtCount; i++)
{
pinMode(bjtPins[i], OUTPUT);
}
}
void LightController::initializeStateDefaultValues()
{
for (__SIZE_TYPE__ i = 0; i < bjtCount; i++)
{
bjtState[i] = 20;
}
}
void LightController::restoreState()
{
for (__SIZE_TYPE__ i = 0; i < bjtCount; i++)
{
bjtState[i] = EEPROM.readInt(i * sizeof(bjtState[i]));
commitPinState(i);
}
}
void LightController::updateState(const char data[], int steps)
{
for (__SIZE_TYPE__ i = 0; i < bjtCount; i++)
{
parseRelativeState(data, i, steps);
setAbsoluteState(data, i);
commitState(i);
}
}
void LightController::parseRelativeState(const char data[], int index, int steps)
{
char numChar[2];
itoa(index, numChar, 10);
if (data[0] == numChar[0])
{
if (data[1] == 't')
{
if (bjtState[index] != 0)
{
bjtState[index] = 0;
}
else
{
bjtState[index] = 255;
}
}
else if (data[1] == 'i')
{
bjtState[index] = clampState(bjtState[index] + steps);
}
else if (data[1] == 'd')
{
bjtState[index] = clampState(bjtState[index] - steps);
}
}
}
void LightController::setAbsoluteState(const char data[], int index)
{
if (strcmp(data, "off") == 0)
{
bjtState[index] = 0;
}
if (strcmp(data, "on") == 0)
{
bjtState[index] = 255;
}
}
int LightController::clampState(int stateValue)
{
int clampedState = stateValue;
if (stateValue > 255)
{
clampedState = 255;
}
else if (stateValue < 0)
{
clampedState = 0;
}
return clampedState;
}
void LightController::commitState(int index)
{
commitPinState(index);
EEPROM.writeInt(index * sizeof(bjtState[index]), bjtState[index]);
EEPROM.commit();
}
void LightController::commitPinState(int index)
{
analogWrite(bjtPins[index], bjtState[index]);
}
int LightController::getBjtCount()
{
return bjtCount;
}
const int *LightController::getBjtPins()
{
return bjtPins;
}
int *LightController::getBjtState()
{
return bjtState;
}

View file

@ -1,25 +0,0 @@
class LightController
{
protected:
__SIZE_TYPE__ bjtCount;
const int *bjtPins;
int *bjtState;
private:
void setAbsoluteState(const char data[], int index);
void parseRelativeState(const char data[], int index, int steps);
int clampState(int stateValue);
void commitState(int index);
void commitPinState(int index);
void initializeStateDefaultValues();
void restoreState();
void initializeState();
void initializePins();
public:
LightController(const int bjtPins[], __SIZE_TYPE__ bjtCount);
void updateState(const char data[], int steps);
int getBjtCount();
const int *getBjtPins();
int *getBjtState();
};

46
Firmware/lib/README Normal file
View file

@ -0,0 +1,46 @@
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into executable file.
The source code of each library should be placed in a an own separate directory
("lib/your_library_name/[here are source files]").
For example, see a structure of the following two libraries `Foo` and `Bar`:
|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c
and a contents of `src/main.c`:
```
#include <Foo.h>
#include <Bar.h>
int main (void)
{
...
}
```
PlatformIO Library Dependency Finder will find automatically dependent
libraries scanning project source files.
More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html

View file

@ -1,8 +0,0 @@
#include <SerialCommunicator.h>
#include <HardwareSerial.h>
SerialCommunicator::SerialCommunicator(HardwareSerial &p_out, int baudRate, int timeout, __SIZE_TYPE__ bufferSize) : StreamCommunicator(p_out, bufferSize)
{
p_out.begin(baudRate);
p_out.setTimeout(timeout);
}

View file

@ -1,8 +0,0 @@
#include <StreamCommunicator.h>
#include <HardwareSerial.h>
class SerialCommunicator : public StreamCommunicator
{
public:
SerialCommunicator(HardwareSerial &p_out, int baudRate, int timeout, __SIZE_TYPE__ bufferSize);
};

View file

@ -1,27 +0,0 @@
#include <StreamCommunicator.h>
StreamCommunicator::StreamCommunicator(Stream &s_out, __SIZE_TYPE__ bufferSize) : Communicator(bufferSize), stream(s_out)
{
}
void StreamCommunicator::sendMessage(int *values, __SIZE_TYPE__ numberOfValues)
{
char message[calculateMessageOutSize(numberOfValues)];
parseIDs(values, numberOfValues, message);
sendMessage(message);
}
void StreamCommunicator::sendMessage(const char message[])
{
stream.println(message);
}
char *StreamCommunicator::receiveMessage()
{
if (stream.available())
{
clearBuffer();
stream.readBytesUntil('\n', getBuffer(), getBufferSize());
}
return getBuffer();
}

View file

@ -1,18 +0,0 @@
#include "Stream.h"
#include "Communicator.h"
#ifndef _STREAM_COMMUNICATOR_INCLUDED_
#define _STREAM_COMMUNICATOR_INCLUDED_
class StreamCommunicator: public Communicator
{
protected:
Stream &stream;
public:
StreamCommunicator(Stream &s_out, __SIZE_TYPE__ bufferSize);
void sendMessage(int *values, __SIZE_TYPE__ numberOfValues) override;
void sendMessage(const char message[]) override;
char *receiveMessage() override;
};
#endif

View file

@ -1,61 +0,0 @@
#include <WebsocketCommunicator.h>
#include <ESPAsyncWebServer.h>
WebsocketCommunicator::WebsocketCommunicator(AsyncWebSocket &socket, AsyncWebServer &server, __SIZE_TYPE__ bufferSize) : Communicator(bufferSize), socket(socket), server(server)
{
AwsEventHandler onEvent = [this](AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,
void *arg, uint8_t *data, size_t len)
{
switch (type)
{
case WS_EVT_CONNECT:
Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
break;
case WS_EVT_DISCONNECT:
Serial.printf("WebSocket client #%u disconnected\n", client->id());
break;
case WS_EVT_DATA:
handleMessage(arg, data, len);
break;
case WS_EVT_PONG:
case WS_EVT_ERROR:
break;
}
};
msgRead = false;
socket.onEvent(onEvent);
server.addHandler(&socket);
}
void WebsocketCommunicator::sendMessage(int *values, __SIZE_TYPE__ numberOfValues)
{
char message[calculateMessageOutSize(numberOfValues)];
parseIDs(values, numberOfValues, message);
sendMessage(message);
}
void WebsocketCommunicator::sendMessage(const char message[])
{
socket.textAll(message);
}
char *WebsocketCommunicator::receiveMessage()
{
msgRead = true;
return getBuffer();
}
void WebsocketCommunicator::clearBufferSafely()
{
if (msgRead)
{
clearBuffer();
}
}
void WebsocketCommunicator::handleMessage(void *arg, uint8_t *data, size_t len)
{
msgRead = false;
int effectiveLen = len < bufferSize ? len : bufferSize;
strncpy(messageBuffer, (char *)data, effectiveLen);
}

View file

@ -1,20 +0,0 @@
#include <Communicator.h>
#include <ESPAsyncWebServer.h>
class WebsocketCommunicator : public Communicator
{
private:
void handleMessage(void *arg, uint8_t *data, size_t len);
bool msgRead;
protected:
AsyncWebSocket &socket;
AsyncWebServer &server;
public:
WebsocketCommunicator(AsyncWebSocket &socket, AsyncWebServer &server, __SIZE_TYPE__ bufferSize);
void sendMessage(int *values, __SIZE_TYPE__ numberOfValues) override;
void sendMessage(const char message[]) override;
char *receiveMessage() override;
void clearBufferSafely();
};

View file

@ -1,28 +1,15 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[platformio]
default_envs = Upload_UART
[env]
platform = espressif32
board = az-delivery-devkit-v4
framework = arduino
lib_deps =
erropix/ESP32 AnalogWrite@^0.2
ESP Async WebServer
board_build.partitions = huge_app.csv
[env:Upload_UART]
upload_port = COM9
monitor_port = COM9
[env:CI_Build]
build_flags = -D DEBUG=1
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
board_build.partitions = huge_app.csv

View file

@ -1,109 +1,9 @@
#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 setup() {
// put your setup code here, to run once:
}
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();
void loop() {
// put your main code here, to run repeatedly:
}

View file

@ -1,11 +1,11 @@
This directory is intended for PlatformIO Unit Testing and project tests.
Unit Testing is a software testing method by which individual units of
source code, sets of one or more MCU program modules together with associated
control data, usage procedures, and operating procedures, are tested to
determine whether they are fit for use. Unit testing finds problems early
in the development cycle.
More information about PlatformIO Unit Testing:
- https://docs.platformio.org/page/plus/unit-testing.html
This directory is intended for PlatformIO Test Runner and project tests.
Unit Testing is a software testing method by which individual units of
source code, sets of one or more MCU program modules together with associated
control data, usage procedures, and operating procedures, are tested to
determine whether they are fit for use. Unit testing finds problems early
in the development cycle.
More information about PlatformIO Unit Testing:
- https://docs.platformio.org/en/latest/advanced/unit-testing/index.html