Removed example files (can be recovered later)

Now it compiles with test main code
This commit is contained in:
Emanuele Trabattoni
2025-06-26 12:44:20 +02:00
parent b54c0e5018
commit 4acce987de
22 changed files with 63 additions and 1385 deletions

View File

@@ -1,37 +0,0 @@
#include <Arduino.h>
#include <HardwareSerial.h> // Reference the ESP32 built-in serial port library
#include "WS_MQTT.h"
#include "WS_Bluetooth.h"
#include "WS_GPIO.h"
#include "WS_Serial.h"
#include "WS_RTC.h"
#include "WS_GPIO.h"
#include "WS_DIN.h"
#include "WS_SD.h"
#include "WS_ETH.h"
uint32_t Simulated_time=0; // Analog time counting
/******************************************************** Initializing ********************************************************/
void setup() {
Flash_test();
GPIO_Init(); // RGB . Buzzer GPIO
//I2C_Init();
//RTC_Init(); // RTC
SD_Init();
Serial_Init(); // UART(RS485/CAN)
MQTT_Init();// MQTT
Bluetooth_Init();// Bluetooth
ETH_Init();
DIN_Init(); // If you don't want to control the relay through DIN, change Relay_Immediate_Default to 0 in WS_DIN.h and re-burn the program
Relay_Init();
printf("Connect to the WIFI network named \"ESP32-S3-POE-ETH-8DI-8RO\" and access the Internet using the connected IP address!!!\r\n");
}
/********************************************************** While **********************************************************/
void loop() {
}

View File

@@ -1,152 +0,0 @@
#include "WS_Bluetooth.h"
BLEServer* pServer; // Used to represent a BLE server
BLECharacteristic* pTxCharacteristic;
BLECharacteristic* pRxCharacteristic;
/********************************************************** Bluetooth *********************************************************/
class MyServerCallbacks : public BLEServerCallbacks { //By overriding the onConnect() and onDisconnect() functions
void onConnect(BLEServer* pServer) { // When the Device is connected, "Device connected" is printed.
Serial.println("Device connected");
}
void onDisconnect(BLEServer* pServer) { // "Device disconnected" will be printed when the device is disconnected
Serial.println("Device disconnected");
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); // Re-broadcast so that the device can query
pAdvertising->addServiceUUID(SERVICE_UUID); // Re-broadcast so that the device can query
pAdvertising->setScanResponse(true); // Re-broadcast so that the device can query
pAdvertising->setMinPreferred(0x06); // Re-broadcast so that the device can query
pAdvertising->setMinPreferred(0x12); // Re-broadcast so that the device can query
BLEDevice::startAdvertising(); // Re-broadcast so that the device can query
pRxCharacteristic->notify(); // Re-broadcast so that the device can query
pAdvertising->start(); // Re-broadcast so that the device can query
}
};
class MyRXCallback : public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic* pCharacteristic) { // The onWrite function is called when the remote device sends data to your feature
String rxValue = String(pCharacteristic->getValue().c_str());
if (!rxValue.isEmpty()) {
// The received data rxValue is processed here
if(rxValue.length() == 1)
{
printf("%s\n", rxValue.c_str()); // Print output through the serial port
uint8_t* valueBytes = reinterpret_cast<uint8_t*>(const_cast<char*>(rxValue.c_str())); // Convert value to uint8 t*
Relay_Analysis(valueBytes,Bluetooth_Mode); // pilot relay
}
else if(rxValue.length() == 2)
{
if(Extension_Enable)
{
printf("%s\n", rxValue.c_str()); // Print output through the serial port
uint8_t* valueBytes = reinterpret_cast<uint8_t*>(const_cast<char*>(rxValue.c_str())); // Convert value to uint8 t*
if(valueBytes[0] == 0x06) // Instruction check correct
RS485_Analysis(valueBytes); // Control external relay
else
printf("Note : Non-instruction data was received - Bluetooth !\r\n");
}
else
printf("Note : Non-instruction data was received or external relays are not enabled - Bluetooth !\r\n");
}
else if(rxValue.length() == 14)
{
if(RTC_Event_Enable)
{
// printf("%s\n", rxValue.c_str()); // Print output through the serial port
uint8_t* valueBytes = reinterpret_cast<uint8_t*>(const_cast<char*>(rxValue.c_str()));
BLE_Set_RTC_Event(valueBytes);
}
else
printf("Note : Non-instruction data was received or RTC events were not enabled - Bluetooth !\r\n");
}
else
{
printf("Note : Non-instruction data was received - Bluetooth !\r\n");
}
pRxCharacteristic->setValue(""); // After data is read, set it to blank for next read
}
}
};
void BLE_Set_RTC_Event(uint8_t* valueBytes){
if(valueBytes[0] == 0xA1 && valueBytes[6] == 0xAA && valueBytes[13] == 0xFF ){
datetime_t Event_Time={0};
Event_Time.year = (valueBytes[1]/16*10 + valueBytes[1] % 16) *100 + valueBytes[2]/16*10 + valueBytes[2] % 16;
Event_Time.month = valueBytes[3]/16*10 + valueBytes[3] % 16;
Event_Time.day = valueBytes[4]/16*10 + valueBytes[4] % 16;
Event_Time.dotw = valueBytes[5]/16*10 + valueBytes[5] % 16;
// valueBytes[6] == 0xAA; // check
Event_Time.hour = valueBytes[7]/16*10 + valueBytes[7] % 16;
Event_Time.minute = valueBytes[8]/16*10 + valueBytes[8] % 16;
Event_Time.second = valueBytes[9]/16*10 + valueBytes[9] % 16;
Repetition_event Repetition = (Repetition_event)valueBytes[12]; // cyclical indicators
if(valueBytes[11]){ // Whether to control all relays 1:Control all relays 0Control a relay
uint8_t CHxs = valueBytes[10]; // relay control
TimerEvent_CHxs_Set(Event_Time, CHxs, Repetition);
}
else{
uint8_t CHx = valueBytes[10]/16;
bool State = (valueBytes[10] % 16);
TimerEvent_CHx_Set(Event_Time,CHx, State, Repetition);
}
}
}
void Bluetooth_SendData(char* Data) { // Send data using Bluetooth
if (Data != nullptr && strlen(Data) > 0) {
if (pServer->getConnectedCount() > 0) {
String SendValue = String(Data); // Convert char* to String
pTxCharacteristic->setValue(SendValue.c_str()); // Set SendValue to the eigenvalue (String type)
pTxCharacteristic->notify(); // Sends a notification to all connected devices
}
}
}
void Bluetooth_Init()
{
/*************************************************************************
Bluetooth
*************************************************************************/
BLEDevice::init("ESP32-S3-POE-ETH-8DI-8RO"); // Initialize Bluetooth and start broadcasting
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
BLEService* pService = pServer->createService(SERVICE_UUID);
pTxCharacteristic = pService->createCharacteristic(
TX_CHARACTERISTIC_UUID,
BLECharacteristic:: PROPERTY_READ); // The eigenvalues are readable and can be read by remote devices
pRxCharacteristic = pService->createCharacteristic(
RX_CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_WRITE); // The eigenvalues are writable and can be written to by remote devices
pRxCharacteristic->setCallbacks(new MyRXCallback());
pRxCharacteristic->setValue("Successfully Connect To ESP32-S3-POE-ETH-8DI-8RO");
pService->start();
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(true);
pAdvertising->setMinPreferred(0x06);
pAdvertising->setMinPreferred(0x12);
BLEDevice::startAdvertising();
pRxCharacteristic->notify();
pAdvertising->start();
RGB_Open_Time(0, 0, 60,1000, 0);
printf("Now you can read it in your phone!\r\n");
xTaskCreatePinnedToCore(
BLETask,
"BLETask",
4096,
NULL,
2,
NULL,
0
);
}
void BLETask(void *parameter) {
while(1){
Bluetooth_SendData(ipStr);
vTaskDelay(pdMS_TO_TICKS(100));
}
vTaskDelete(NULL);
}

View File

@@ -1,24 +0,0 @@
#pragma once
#include <HardwareSerial.h> // Reference the ESP32 built-in serial port library
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#include "WS_GPIO.h"
#include "WS_Serial.h"
#include "WS_Information.h"
#include "WS_Relay.h"
#include "WS_MQTT.h"
#include "WS_RTC.h"
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" // UUID of the server
#define RX_CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" // UUID of the characteristic Tx
#define TX_CHARACTERISTIC_UUID "beb5484a-36e1-4688-b7f5-ea07361b26a8" // UUID of the characteristic Rx
#define Bluetooth_Mode 2
void Bluetooth_SendData(char * Data);
void Bluetooth_Init();
void BLETask(void *parameter);
void BLE_Set_RTC_Event(uint8_t* valueBytes);

View File

@@ -1,18 +0,0 @@
#pragma once
#define Extension_Enable 1 // Whether to extend the connection to external devices 1:Expansion device Modbus RTU Relay 0:No extend
#define RS485_CAN_Enable 1 // This item is configured according to product selection 1:Select RS485 0:Select CAN
#define RTC_Event_Enable 1 // Whether to enable RTC events (Bluetooth) 1:Enable 0:Disable
// Name and password of the WiFi access point
#define STASSID "JSBPI"
#define STAPSK "waveshare0755"
// Details about devices on the Waveshare cloud
#define MQTT_Server "mqtt.waveshare.cloud"
#define MQTT_Port 1883
#define MQTT_ID "fc2d8db5"
#define MQTT_Pub "Pub/59/54/fc2d8db5"
#define MQTT_Sub "Sub/59/54/fc2d8db5"

View File

@@ -1,248 +0,0 @@
#include "WS_MQTT.h"
// The name and password of the WiFi access point
const char* ssid = STASSID;
const char* password = STAPSK;
// Details about devices on the Waveshare cloud
const char* mqtt_server = MQTT_Server;
int PORT = MQTT_Port;
const char* ID = MQTT_ID; // Defining device ID
char pub[] = MQTT_Pub; // MQTT release topic
char sub[] = MQTT_Sub; // MQTT subscribe to topics
WiFiClient espClient; //MQTT initializes the contents
PubSubClient client(espClient);
JsonDocument sendJson;
JsonDocument readJson;
unsigned long lastUpdateTime = 0;
char msg[MSG_BUFFER_SIZE];
bool WIFI_Connection = 0;
bool WIFI_Connection_Old = 0;
char ipStr[16];
const unsigned long updateInterval = 5000;
void WIFI_Init(void)
{
xTaskCreatePinnedToCore(
WifiStaTask,
"WifiStaTask",
4096,
NULL,
3,
NULL,
0
);
}
void WifiStaTask(void *parameter) {
uint8_t Count = 0;
WiFi.mode(WIFI_STA);
WiFi.setSleep(true);
WiFi.begin(ssid, password); // Connect to the specified Wi-Fi network
while(1){
if(WiFi.status() != WL_CONNECTED)
{
WIFI_Connection = 0;
printf(".\n");
RGB_Open_Time(50, 0, 0, 500, 0);
Count++;
if(Count >= 10){
Count = 0;
printf("\r\n");
WiFi.disconnect();
vTaskDelay(pdMS_TO_TICKS(100));
WiFi.mode(WIFI_OFF);
vTaskDelay(pdMS_TO_TICKS(100));
WiFi.mode(WIFI_STA);
vTaskDelay(pdMS_TO_TICKS(100));
WiFi.begin(ssid, password);
}
}
else{
WIFI_Connection = 1;
IPAddress myIP = WiFi.localIP();
printf("IP Address: ");
sprintf(ipStr, "%d.%d.%d.%d", myIP[0], myIP[1], myIP[2], myIP[3]);
printf("%s\r\n", ipStr);
RGB_Open_Time(0, 50, 0, 1000, 0);
printf("WIFI connection is successful, relay control can be performed via Waveshare cloud.\r\n");
while (WiFi.status() == WL_CONNECTED){
vTaskDelay(pdMS_TO_TICKS(100));
}
}
vTaskDelay(pdMS_TO_TICKS(1000));
}
vTaskDelete(NULL);
}
// MQTT subscribes to callback functions for processing received messages
void callback(char* topic, byte* payload, unsigned int length) {
uint8_t CH_Flag = 0;
String inputString;
for (int i = 0; i < length; i++) {
inputString += (char)payload[i];
}
printf("%s\r\n",inputString.c_str()); // Format of data sent back by the server {"data":{"CH1":1}}
int dataBegin = inputString.indexOf("\"data\""); // Finds if "data" is present in the string (quotes also)
if (dataBegin == -1) {
printf("Missing 'data' field in JSON. - MQTT\r\n");
return;
}
int CH_Begin = -1;
if (inputString.indexOf("\"CH1\"", dataBegin) != -1){
CH_Flag = 1;
CH_Begin = inputString.indexOf("\"CH1\"", dataBegin);
}
else if (inputString.indexOf("\"CH2\"", dataBegin) != -1){
CH_Flag = 2;
CH_Begin = inputString.indexOf("\"CH2\"", dataBegin);
}
else if (inputString.indexOf("\"CH3\"", dataBegin) != -1){
CH_Flag = 3;
CH_Begin = inputString.indexOf("\"CH3\"", dataBegin);
}
else if (inputString.indexOf("\"CH4\"", dataBegin) != -1){
CH_Flag = 4;
CH_Begin = inputString.indexOf("\"CH4\"", dataBegin);
}
else if (inputString.indexOf("\"CH5\"", dataBegin) != -1){
CH_Flag = 5;
CH_Begin = inputString.indexOf("\"CH5\"", dataBegin);
}
else if (inputString.indexOf("\"CH6\"", dataBegin) != -1){
CH_Flag = 6;
CH_Begin = inputString.indexOf("\"CH6\"", dataBegin);
}
else if (inputString.indexOf("\"CH7\"", dataBegin) != -1){
CH_Flag = 7;
CH_Begin = inputString.indexOf("\"CH7\"", dataBegin);
}
else if (inputString.indexOf("\"CH8\"", dataBegin) != -1){
CH_Flag = 8;
CH_Begin = inputString.indexOf("\"CH8\"", dataBegin);
}
else if (inputString.indexOf("\"ALL\"", dataBegin) != -1){
CH_Flag = 9;
CH_Begin = inputString.indexOf("\"ALL\"", dataBegin);
}
else{
printf("Note : Non-instruction data was received - MQTT!\r\n");
CH_Flag = 0;
return;
}
int valueBegin = inputString.indexOf(':', CH_Begin);
int valueEnd = inputString.indexOf('}', valueBegin);
if (valueBegin != -1 && valueEnd != -1) {
if(CH_Flag != 0)
{
String ValueStr = inputString.substring(valueBegin + 1, valueEnd);
int Value = ValueStr.toInt();
if(CH_Flag < 9){
if(Value == 1 && Relay_Flag[CH_Flag - 1] == 0){
uint8_t Data[1]={CH_Flag+48};
Relay_Analysis(Data,MQTT_Mode);
}
else if(Value == 0 && Relay_Flag[CH_Flag - 1] == 1){
uint8_t Data[1]={CH_Flag+48};
Relay_Analysis(Data,MQTT_Mode);
}
}
else if(CH_Flag == 9){
if(Value == 1 && ((Relay_Flag[0] & Relay_Flag[1] & Relay_Flag[2] & Relay_Flag[3] & Relay_Flag[4] & Relay_Flag[5] & Relay_Flag[6] & Relay_Flag[7]) == 0)){
uint8_t Data[1]={9+48};
Relay_Analysis(Data,MQTT_Mode);
}
else if(Value == 0 && ((Relay_Flag[0] | Relay_Flag[1] | Relay_Flag[2] | Relay_Flag[3] | Relay_Flag[4] | Relay_Flag[5] | Relay_Flag[6] | Relay_Flag[7] )== 1)){
uint8_t Data[1]={0+48};
Relay_Analysis(Data,MQTT_Mode);
}
}
}
}
}
// Reconnect to the MQTT server
void reconnect(void) {
uint8_t Count = 0;
while (!client.connected()) {
Count++;
if (client.connect(ID)) {
client.subscribe(sub);
printf("Waveshare Cloud connection is successful and now you can use all features.\r\n");
}
else{
delay(500);
if(Count % 2 == 0 && Count != 0){
printf("%d\r\n", client.state());
RGB_Open_Time(50, 0, 50, 1000, 0);
}
if(Count % 10 == 0){ // 10 attempts failed to connect, cancel the connection, try again
client.disconnect();
delay(100);
client.setServer(mqtt_server, PORT);
delay(100);
client.setCallback(callback);
delay(100);
}
if(Count > 32){ // connection fail
Count = 0;
printf("warning: Waveshare cloud connection fails. Currently, only Bluetooth control is available !!!\r\n");
}
}
}
}
// Send data in JSON format to MQTT server
void sendJsonData(void) {
sendJson["ID"] = ID;
String pubres;
serializeJson(sendJson, pubres);
int str_len = pubres.length() + 1;
char char_array[str_len];
pubres.toCharArray(char_array, str_len);
client.publish(pub, char_array);
}
void MQTTTask(void *parameter) {
bool WIFI_Connection_Old;
while(1){
if(WIFI_Connection == 1)
{
if(!WIFI_Connection_Old){
WIFI_Connection_Old = 1;
client.setServer(mqtt_server, PORT);
client.setCallback(callback);
}
if (!client.connected()) {
reconnect();
}
client.loop();
}
else{
WIFI_Connection_Old = 0;
}
vTaskDelay(pdMS_TO_TICKS(10));
}
vTaskDelete(NULL);
}
void MQTT_Init(void)
{
WIFI_Init();
xTaskCreatePinnedToCore(
MQTTTask,
"MQTTTask",
4096,
NULL,
3,
NULL,
0
);
}

View File

@@ -1,25 +0,0 @@
#ifndef _WS_MQTT_H_
#define _WS_MQTT_H_
#include <ArduinoJson.h>
#include <Arduino.h>
#include <PubSubClient.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include "WS_GPIO.h"
#include "WS_Information.h"
#include "WS_Relay.h"
#define MSG_BUFFER_SIZE (50)
extern char ipStr[16];
void WIFI_Init(void);
void WifiStaTask(void *parameter);
void callback(char* topic, byte* payload, unsigned int length); // MQTT subscribes to callback functions for processing received messages
void reconnect(void); // Reconnect to the MQTT server
void sendJsonData(void); // Send data in JSON format to MQTT server
void MQTT_Init(void);
#endif

View File

@@ -1,113 +0,0 @@
#include "WS_SD.h"
bool SDCard_Flag = 0;
bool SDCard_Finish = 0;
uint16_t SDCard_Size = 0;
uint16_t Flash_Size = 0;
void SD_Init() {
// SD MMC
if(!SD_MMC.setPins(SD_CLK_PIN, SD_CMD_PIN, SD_D0_PIN,-1,-1,-1)){
printf("SD MMC: Pin change failed!\r\n");
return;
}
if (SD_MMC.begin("/sdcard", true, true)) { // "/sdcard", true, true or "/sdcard", true, false
printf("SD card initialization successful!\r\n");
} else {
printf("SD card initialization failed!\r\n");
}
uint8_t cardType = SD_MMC.cardType();
if(cardType == CARD_NONE){
printf("No SD card attached\r\n");
return;
}
else{
printf("SD Card Type: ");
if(cardType == CARD_MMC){
printf("MMC\r\n");
} else if(cardType == CARD_SD){
printf("SDSC\r\n");
} else if(cardType == CARD_SDHC){
printf("SDHC\r\n");
} else {
printf("UNKNOWN\r\n");
}
uint64_t totalBytes = SD_MMC.totalBytes();
uint64_t usedBytes = SD_MMC.usedBytes();
SDCard_Size = totalBytes/(1024*1024);
printf("Total space: %llu\n", totalBytes);
printf("Used space: %llu\n", usedBytes);
printf("Free space: %llu\n", totalBytes - usedBytes);
}
}
bool File_Search(const char* directory, const char* fileName)
{
File Path = SD_MMC.open(directory);
if (!Path) {
printf("Path: <%s> does not exist\r\n",directory);
return false;
}
File file = Path.openNextFile();
while (file) {
if (strcmp(file.name(), fileName) == 0) {
if (strcmp(directory, "/") == 0)
printf("File '%s%s' found in root directory.\r\n",directory,fileName);
else
printf("File '%s/%s' found in root directory.\r\n",directory,fileName);
Path.close();
return true;
}
file = Path.openNextFile();
}
if (strcmp(directory, "/") == 0)
printf("File '%s%s' not found in root directory.\r\n",directory,fileName);
else
printf("File '%s/%s' not found in root directory.\r\n",directory,fileName);
Path.close();
return false;
}
uint16_t Folder_retrieval(const char* directory, const char* fileExtension, char File_Name[][100],uint16_t maxFiles)
{
File Path = SD_MMC.open(directory);
if (!Path) {
printf("Path: <%s> does not exist\r\n",directory);
return false;
}
uint16_t fileCount = 0;
char filePath[100];
File file = Path.openNextFile();
while (file && fileCount < maxFiles) {
if (!file.isDirectory() && strstr(file.name(), fileExtension)) {
strncpy(File_Name[fileCount], file.name(), sizeof(File_Name[fileCount]));
if (strcmp(directory, "/") == 0) {
snprintf(filePath, 100, "%s%s", directory, file.name());
} else {
snprintf(filePath, 100, "%s/%s", directory, file.name());
}
printf("File found: %s\r\n", filePath);
fileCount++;
}
file = Path.openNextFile();
}
Path.close();
if (fileCount > 0) {
printf("Retrieved %d mp3 files\r\n",fileCount);
return fileCount;
} else {
printf("No files with extension '%s' found in directory: %s\r\n", fileExtension, directory);
return 0;
}
}
void Flash_test()
{
printf("/********** RAM Test**********/\r\n");
// Get Flash size
uint32_t flashSize = ESP.getFlashChipSize();
Flash_Size = flashSize/1024/1024;
printf("Flash size: %d MB \r\n", flashSize/1024/1024);
printf("/******* RAM Test Over********/\r\n\r\n");
}

View File

@@ -1,18 +0,0 @@
#pragma once
#include "Arduino.h"
#include <cstring>
#include "FS.h"
#include "SD_MMC.h"
#define SD_CLK_PIN 48
#define SD_CMD_PIN 47
#define SD_D0_PIN 45
extern uint16_t SDCard_Size;
extern uint16_t Flash_Size;
void SD_Init();
void Flash_test();
bool File_Search(const char* directory, const char* fileName);
uint16_t Folder_retrieval(const char* directory, const char* fileExtension, char File_Name[][100],uint16_t maxFiles);

View File

@@ -1,8 +0,0 @@
#include "WS_Serial.h"
void Serial_Init()
{
if(RS485_CAN_Enable)
RS485_Init();
//else
//CAN_Init();
}

View File

@@ -1,8 +0,0 @@
#pragma once
#include "WS_Information.h"
#include "WS_RS485.h"
//#include "WS_CAN.h"
void Serial_Init(); // Example Initialize the system serial port and RS485
void Serial_Loop(); // Read RS485 data, parse and control relays

38
src/main.cpp Normal file
View File

@@ -0,0 +1,38 @@
#include <Arduino.h>
#include <RS485_Driver.h>
void setup() {
bool success = true;
auto bus = drivers::MODBUS(9600, SERIAL_8N1);
const uint8_t devAddress(0x01);
const uint8_t baseRegister(0x02);
log_i("Write single coil");
success &= bus.writeCoil(devAddress, baseRegister, true);
success &=bus.writeCoil(devAddress, baseRegister, false);
log_i("Write multiple coils");
const uint16_t coilsNum(32);
std::vector<bool> coilsValues(coilsNum, false);
bool v=true;
for (auto i(0); i < coilsNum; i++) {
coilsValues[i] = v;
v=~v;
}
success &=bus.writeCoils(devAddress, baseRegister, coilsValues);
log_i("Write single register");
success &=bus.writeRegister(devAddress, baseRegister, 0xAA);
log_i("Write multiple registers");
const uint16_t regNum(16);
std::vector<uint16_t> regValues(regNum, 0);
for (uint16_t i(0); i < regNum; i++) {
regValues[i] = i*2;
}
}
void loop() {
}