Compare commits

..
16 Commits
15 changed files with 5141 additions and 226 deletions
+20
View File
@@ -13,6 +13,15 @@ get_code_gen:
gen_prot:
./alox.protogen -i prot.json -o main/uart
switch_to_s3:
idf.py set-target esp32s3
cp sdkconfig.s3 sdkconfig
idf.py build
switch_to_c3:
idf.py set-target esp32c3
cp sdkconfig.c3 sdkconfig
idf.py build
buildIdf:
idf.py build
@@ -26,6 +35,17 @@ flashMini2:
flashMini3:
idf.py flash -p /dev/ttyACM2
flashCluster:
idf.py flash -p /dev/ttyACM1
idf.py flash -p /dev/ttyACM2
idf.py flash -p /dev/ttyACM3
idf.py flash -p /dev/ttyACM4
idf.py flash -p /dev/ttyACM5
idf.py flash -p /dev/ttyACM6
idf.py flash -p /dev/ttyACM7
idf.py flash -p /dev/ttyACM8
monitorMini:
idf.py monitor -p /dev/ttyACM0
+66 -7
View File
@@ -69,7 +69,6 @@ type OTASyncManager struct {
func (ot *OTASyncManager) WaitForNextMessageTimeout() (*MessageReceive, error) {
select {
case msg := <-ot.NewOTAMessage:
log.Printf("OTASyncManager MessageReceive %v", msg)
return &msg, nil
case <-time.After(ot.TimeoutMessage):
return nil, fmt.Errorf("Message Timeout")
@@ -97,7 +96,7 @@ func addByteToParsedBuffer(mr *MessageReceive, pbyte byte) {
}
func parse_uart_ota_payload_payload(payloadBuffer []byte, payload_len int) {
fmt.Printf("RAW BUFFER: % 02X", payloadBuffer[:payload_len])
//fmt.Printf("RAW BUFFER: % 02X", payloadBuffer[:payload_len])
if payload_len != 4 {
fmt.Printf("Payload should be 4 is %v", payload_len)
return
@@ -106,6 +105,30 @@ func parse_uart_ota_payload_payload(payloadBuffer []byte, payload_len int) {
fmt.Printf("Sequence %v, WriteIndex %v", binary.LittleEndian.Uint16(payloadBuffer[0:1]), binary.LittleEndian.Uint16(payloadBuffer[2:3]))
}
func parse_uart_version_payload(payloadBuffer []byte, payload_len int) {
type payload_data struct {
Version uint16
BuildHash [7]uint8
}
tableHeaders := pterm.TableData{
{"Version", "Buildhash"},
}
tableData := tableHeaders
tableData = append(tableData, []string{
fmt.Sprintf("%d", binary.LittleEndian.Uint16(payloadBuffer[1:3])),
fmt.Sprintf("%s", payloadBuffer[3:10]),
})
err := pterm.DefaultTable.WithHasHeader().WithBoxed().WithData(tableData).Render()
if err != nil {
fmt.Printf("Fehler beim Rendern der Tabelle: %s\n", err)
}
}
func parse_uart_client_info_payload(payloadBuffer []byte, payload_len int) {
type payload_data struct {
@@ -181,6 +204,7 @@ func message_receive_callback(mr MessageReceive) {
case byte(UART_ECHO):
break
case UART_VERSION:
parse_uart_version_payload(mr.parsed_message, mr.write_index)
break
case UART_CLIENT_INFO:
parse_uart_client_info_payload(mr.parsed_message, mr.write_index)
@@ -206,7 +230,6 @@ func message_receive_failed_callback(mr MessageReceive) {
}
func parseByte(mr *MessageReceive, pbyte byte) {
fmt.Printf("Parsing %v", pbyte)
addByteToRawBuffer(mr, pbyte)
switch mr.state {
case WAITING_FOR_START_BYTE:
@@ -279,6 +302,10 @@ func buildMessage(payloadBuffer []byte, payload_len int, sendBuffer []byte) int
writeIndex++
checksum ^= b
}
if checksum == START_BYTE || checksum == ESCAPE_BYTE || checksum == END_BYTE {
sendBuffer[writeIndex] = ESCAPE_BYTE
writeIndex++
}
sendBuffer[writeIndex] = checksum
writeIndex++
sendBuffer[writeIndex] = END_BYTE
@@ -310,11 +337,12 @@ func main() {
OTA_MessageCounter: 0,
OTA_PayloadMessageSequence: 0,
NewOTAMessage: make(chan MessageReceive),
TimeoutMessage: time.Millisecond * 1000,
TimeoutMessage: time.Millisecond * 30000,
}
mode := &serial.Mode{
BaudRate: 115200,
//BaudRate: 115200,
BaudRate: 921600,
}
port, err := serial.Open("/dev/ttyUSB0", mode)
if err != nil {
@@ -367,15 +395,45 @@ func main() {
payload_buffer[0] = UART_OTA_START
n := buildMessage(payload_buffer, 1, send_buffer)
sendMessage(port, send_buffer[:n])
_, err = OTA_UpdateHandler.WaitForNextMessageTimeout()
msg, err := OTA_UpdateHandler.WaitForNextMessageTimeout()
if err != nil {
log.Printf("Error Message not acked %v", err)
} else {
log.Printf("Message Waiting hat funktionioert")
if msg.parsed_message[2] != 0x00 {
log.Printf("Update Start failed %v", msg.parsed_message[2])
return
} else {
log.Printf("Update Start confirmed Updating Partition %v", msg.parsed_message[1])
}
}
update_write_index := 0
// write update parts
for update_write_index < len(update) {
payload_buffer = make([]byte, 1024)
send_buffer = make([]byte, 1024)
payload_buffer[0] = UART_OTA_PAYLOAD
write_len := min(200, len(update)-update_write_index)
//end_payload_len := min(update_write_index+200, len(update))
copy(payload_buffer[1:write_len+1], update[update_write_index:update_write_index+write_len])
n = buildMessage(payload_buffer, write_len+1, send_buffer)
sendMessage(port, send_buffer[:n])
msg, err := OTA_UpdateHandler.WaitForNextMessageTimeout()
if err != nil {
log.Printf("Error Message not acked %v", err)
return
} else {
seqCounter := binary.LittleEndian.Uint16(msg.parsed_message[1:3])
buff_write_index := binary.LittleEndian.Uint16(msg.parsed_message[3:5])
log.Printf("Sequenzce Counter: %d, Update buffer Write Index: %d", seqCounter, buff_write_index)
}
update_write_index += 200
}
log.Printf("Update übertragen beende hier!!!")
// end
payload_buffer = make([]byte, 1024)
send_buffer = make([]byte, 1024)
@@ -386,6 +444,7 @@ func main() {
_, err = OTA_UpdateHandler.WaitForNextMessageTimeout()
if err != nil {
log.Printf("Error Message not acked %v", err)
return
} else {
log.Printf("Message Waiting hat funktionioert")
}
+265 -89
View File
@@ -1,3 +1,4 @@
#include "esp_err.h"
#include "esp_log.h"
#include "esp_now.h"
#include "esp_timer.h"
@@ -8,9 +9,97 @@
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
static const char *TAG = "ALOX - COM";
static struct ESP_MessageBroker mr;
static QueueHandle_t ESP_recieved_message_queue;
void free_ESPNOW_MessageInfo(ESPNOW_MessageInfo *msg) {
if (msg->esp_now_info.src_addr) {
free(msg->esp_now_info.src_addr);
msg->esp_now_info.src_addr = NULL;
}
if (msg->esp_now_info.des_addr) {
free(msg->esp_now_info.des_addr);
msg->esp_now_info.des_addr = NULL;
}
if (msg->esp_now_info.rx_ctrl) {
free(msg->esp_now_info.rx_ctrl);
msg->esp_now_info.rx_ctrl = NULL;
}
if (msg->data) {
free(msg->data);
msg->data = NULL;
}
}
void ESP_InitMessageBroker(QueueHandle_t msg_queue_handle) {
mr.num_direct_callbacks = 0;
mr.num_task_callbacks = 0;
ESP_recieved_message_queue = msg_queue_handle;
return;
}
void ESP_RegisterFunction(CommandPages command,
ESP_RegisterFunctionCallback callback) {
mr.FunctionList[mr.num_direct_callbacks].MSGID = command;
mr.FunctionList[mr.num_direct_callbacks].callback = callback;
mr.num_direct_callbacks++;
return;
}
void ESP_RegisterTask(CommandPages command, ESP_RegisterTaskCallback callback) {
mr.TaskList[mr.num_task_callbacks].MSGID = command;
mr.TaskList[mr.num_task_callbacks].task = callback;
mr.num_task_callbacks++;
}
void ESP_MessageBrokerTask(void *param) {
ESPNOW_MessageInfo received_msg;
ESP_MessageBrokerTaskParams_t *task_params =
(ESP_MessageBrokerTaskParams_t *)param;
// Extrahiere die einzelnen Parameter
QueueHandle_t msg_queue = task_params->message_queue;
if (msg_queue == NULL) {
ESP_LOGE(TAG, "Message queue not initialized. Terminating task.");
vTaskDelete(NULL);
}
ESP_LOGI(TAG, "Message broker task started.");
while (1) {
if (xQueueReceive(msg_queue, &received_msg, portMAX_DELAY)) {
ESP_LOGI(TAG, "Broker got message trying to relay it now");
const BaseMessage *message = (const BaseMessage *)received_msg.data;
ESP_LOGI(TAG, "Broker searching for command page %d",
message->commandPage);
for (int i = 0; i < mr.num_direct_callbacks;
i++) { // TODO: there should not be a loop needed here
if (mr.FunctionList[i].MSGID == message->commandPage) {
mr.FunctionList[i].callback(&received_msg.esp_now_info,
received_msg.data, received_msg.data_len);
ESP_LOGI(TAG, "Broker found matching msgid %d",
mr.FunctionList[i].MSGID);
free_ESPNOW_MessageInfo(&received_msg);
}
}
for (int i = 0; i < mr.num_direct_callbacks; i++) {
// if (mr.FunctionList[i].MSGID == received_msg.msgid) {
// TODO: Not yet implemented
// Only send data to task, task should be created beforhead and wait
// for new data in the queue.
//}
}
}
}
}
QueueHandle_t messageQueue = NULL; // Warteschlange für empfangene Nachrichten
static bool hasMaster = false;
static ClientList *esp_client_list;
@@ -20,7 +109,7 @@ static uint8_t channelNumber = 0;
int init_com(ClientList *clients, uint8_t wifi_channel) {
// Initialisiere die Kommunikations-Warteschlange
messageQueue = xQueueCreate(MESSAGE_QUEUE_SIZE, sizeof(BaseMessage));
messageQueue = xQueueCreate(MESSAGE_QUEUE_SIZE, sizeof(ESPNOW_MessageInfo));
if (messageQueue == NULL) {
ESP_LOGE(TAG, "Message queue creation failed");
return -1;
@@ -36,7 +125,7 @@ int add_peer(uint8_t *macAddr) {
esp_now_peer_info_t peerInfo = {
.channel = channelNumber,
.ifidx = ESP_IF_WIFI_STA,
.encrypt = false, // Keine Verschlüsselung (kann geändert werden)
.encrypt = false, // Keine Verschlüsselung // TODO: should be changed
};
memcpy(peerInfo.peer_addr, macAddr, ESP_NOW_ETH_ALEN);
@@ -72,13 +161,11 @@ BaseMessage MessageBuilder(CommandPages commandPage, PayloadUnion payload,
size_t payload_size) {
BaseMessage message;
// Initialisierung der BaseMessage
message.commandPage = commandPage;
message.version = 1;
message.length = (uint16_t)payload_size;
// Kopieren des Payloads in die Union
memset(&message.payload, 0, sizeof(message.payload)); // Sicherheitsmaßnahme
memset(&message.payload, 0, sizeof(message.payload));
memcpy(&message.payload, &payload, payload_size);
return message;
@@ -93,7 +180,8 @@ void master_broadcast_task(void *param) {
ESP_ERROR_CHECK(esp_now_send(broadcast_address, (uint8_t *)&message,
sizeof(BaseMessage)));
ESP_LOGI(TAG, "Broadcast Message sent");
// ESP_LOGI(TAG, "Broadcast Message sent");
vTaskDelay(pdMS_TO_TICKS(5000));
}
}
@@ -106,7 +194,7 @@ void master_broadcast_ping(void *param) {
MessageBuilder(PingPage, *(PayloadUnion *)&payload, sizeof(payload));
ESP_ERROR_CHECK(esp_now_send(broadcast_address, (uint8_t *)&message,
sizeof(BaseMessage)));
ESP_LOGI(TAG, "Broadcast PING Message sent");
// ESP_LOGI(TAG, "Broadcast PING Message sent");
vTaskDelay(pdMS_TO_TICKS(2500));
}
}
@@ -130,46 +218,25 @@ void master_ping_task(void *param) {
}
}
void master_receive_callback(const esp_now_recv_info_t *esp_now_info,
void master_StatusCallback(const esp_now_recv_info_t *esp_now_info,
const uint8_t *data, int data_len) {
ESP_LOGI(TAG, "MASTER GOT MESSAGE");
const BaseMessage *message = (const BaseMessage *)data;
ESP_LOGI(TAG, "SRC " MACSTR, MAC2STR(esp_now_info->src_addr));
ESP_LOGI(TAG,
"Status Message Received: status: %d, runningPartition: %d, uptime: "
"%d, version: %d",
message->payload.status_payload.status,
message->payload.status_payload.runningPartition,
message->payload.status_payload.uptime,
message->payload.status_payload.version);
}
void master_RegisterCallback(const esp_now_recv_info_t *esp_now_info,
const uint8_t *data, int data_len) {
BaseMessage replyMessage = {};
const BaseMessage *message = (const BaseMessage *)data;
int id;
switch (message->commandPage) {
case StatusPage:
ESP_LOGI(TAG, "GOT STATUS MESSAGE");
id = get_client_id(esp_client_list, esp_now_info->src_addr);
if (id >= 0) {
esp_client_list->Clients[id].clientVersion =
message->payload.status_payload.version;
}
break;
case PingPage:
ESP_LOGI(TAG, "GOT PING MESSAGE");
uint32_t currentTime = esp_timer_get_time();
uint32_t diff = currentTime - message->payload.ping_payload.timestamp;
ESP_LOGI(TAG, "Start: %lu, End: %lu, Diff: %lu, Ping: %lu",
message->payload.ping_payload.timestamp, currentTime, diff,
diff / 1000); // ping in ms
id = get_client_id(esp_client_list, esp_now_info->src_addr);
if (id >= 0) {
esp_client_list->Clients[id].lastSuccessfullPing = xTaskGetTickCount();
esp_client_list->Clients[id].lastPing = (diff / 1000);
ESP_LOGI(TAG, "Updated client %d: " MACSTR " last ping time to %lu", id,
MAC2STR(esp_now_info->src_addr),
esp_client_list->Clients[id].lastSuccessfullPing);
}
break;
case BroadCastPage:
ESP_LOGI(TAG, "MASTER SHOULD NOT GET BROADCAST MESSAGE, is there another "
"master calling?");
break;
case RegisterPage:
ESP_LOGI(TAG, "WILL REGISTER DEVICE");
esp_now_peer_info_t checkPeerInfo;
esp_err_t checkPeer =
@@ -190,69 +257,76 @@ void master_receive_callback(const esp_now_recv_info_t *esp_now_info,
ESP_LOGI(TAG, "ESP ERR ESPNOW_ARG");
break;
case (ESP_ERR_ESPNOW_NOT_FOUND):
ESP_LOGI(TAG, "CLIENT WIRD IN DIE LISTE AUFGENOMMEN");
add_peer(esp_now_info->src_addr);
ESP_LOGI(TAG, "CLIENT WIRD IN DIE LISTE AUFGENOMMEN " MACSTR,
MAC2STR(esp_now_info->src_addr));
int peer_err = add_peer(esp_now_info->src_addr);
if (peer_err < 0) {
ESP_LOGE(TAG, "Could not add ESP TO ClientList %d", peer_err);
}
ESP_LOGI(TAG, "FRAGE CLIENT STATUS AN");
GetStatusPayload payload = {};
replyMessage = MessageBuilder(GetStatusPage, *(PayloadUnion *)&payload,
sizeof(payload));
ESP_ERROR_CHECK(esp_now_send(esp_now_info->src_addr,
(uint8_t *)&replyMessage,
sizeof(BaseMessage)));
esp_err_t err = esp_now_send(esp_now_info->src_addr,
(uint8_t *)&replyMessage, sizeof(BaseMessage));
if (err != ESP_OK) {
ESP_LOGE(TAG, "Could not send Message Error %s", esp_err_to_name(err));
}
break;
default:
ESP_LOGI(TAG, "Unknown Message %i", checkPeer);
}
break;
default:
ESP_LOGI(TAG, "Unknown CommandPage %i", message->commandPage);
break;
}
void master_pingCallback(const esp_now_recv_info_t *esp_now_info,
const uint8_t *data, int data_len) {
BaseMessage replyMessage = {};
const BaseMessage *message = (const BaseMessage *)data;
ESP_LOGI(TAG, "GOT PING MESSAGE");
uint32_t currentTime = esp_timer_get_time();
uint32_t diff = currentTime - message->payload.ping_payload.timestamp;
ESP_LOGI(TAG, "Start: %lu, End: %lu, Diff: %lu, Ping: %lu",
message->payload.ping_payload.timestamp, currentTime, diff,
diff / 1000); // ping in ms
int id = get_client_id(esp_client_list, esp_now_info->src_addr);
if (id >= 0) {
esp_client_list->Clients[id].lastSuccessfullPing = xTaskGetTickCount();
esp_client_list->Clients[id].lastPing = (diff / 1000);
ESP_LOGI(TAG, "Updated client %d: " MACSTR " last ping time to %lu", id,
MAC2STR(esp_now_info->src_addr),
esp_client_list->Clients[id].lastSuccessfullPing);
}
}
void client_receive_callback(const esp_now_recv_info_t *esp_now_info,
void master_broadcastCallback(const esp_now_recv_info_t *esp_now_info,
const uint8_t *data, int data_len) {
ESP_LOGI(TAG, "SLAVE GOT MESSAGE");
ESP_LOGI(TAG, "Received message from: " MACSTR,
ESP_LOGI(TAG,
"Master should not recieve Broadcast is there another master "
"Calling got message from " MACSTR,
MAC2STR(esp_now_info->src_addr));
ESP_LOGI(TAG, "Message: %.*s", data_len, data);
}
void ESPNOW_RegisterMasterCallbacks() {
ESP_RegisterFunction(StatusPage, master_StatusCallback);
ESP_RegisterFunction(RegisterPage, master_RegisterCallback);
ESP_RegisterFunction(PingPage, master_pingCallback);
ESP_RegisterFunction(BroadCastPage, master_broadcastCallback);
}
void slave_broadcastCallback(const esp_now_recv_info_t *esp_now_info,
const uint8_t *data, int data_len) {
BaseMessage replyMessage = {};
const BaseMessage *message = (const BaseMessage *)data;
switch (message->commandPage) {
case StatusPage:
ESP_LOGI(TAG, "GOT STATUS MESSAGE");
break;
case GetStatusPage: {
StatusPayload payload = {
.status = 1,
.runningPartition = 1,
.uptime = 100,
.version = 0x0002,
};
replyMessage =
MessageBuilder(StatusPage, *(PayloadUnion *)&payload, sizeof(payload));
ESP_ERROR_CHECK(esp_now_send(
esp_now_info->src_addr, (uint8_t *)&replyMessage, sizeof(BaseMessage)));
} break;
case PingPage:
ESP_LOGI(TAG, "GOT PING MESSAGE");
replyMessage = MessageBuilder(PingPage, *(PayloadUnion *)&message->payload,
sizeof(message->payload));
ESP_ERROR_CHECK(esp_now_send(
esp_now_info->src_addr, (uint8_t *)&replyMessage, sizeof(BaseMessage)));
break;
case BroadCastPage:
ESP_LOGI(TAG, "GOT BROADCAST MESSAGE");
if (!hasMaster) {
if (IS_BROADCAST_ADDR(esp_now_info->des_addr)) {
ESP_LOGI(TAG,
"GOT BROADCAST MESSAGE ATTEMPTING TO REGISTER TO MASTER!");
ESP_LOGI(TAG, "GOT BROADCAST MESSAGE ATTEMPTING TO REGISTER TO MASTER!");
add_peer(esp_now_info->src_addr);
replyMessage =
MessageBuilder(RegisterPage, *(PayloadUnion *)&message->payload,
@@ -262,14 +336,116 @@ void client_receive_callback(const esp_now_recv_info_t *esp_now_info,
sizeof(BaseMessage)));
hasMaster = true;
}
} else {
ESP_LOGI(TAG, "Already have master wont register by the new one");
}
break;
case RegisterPage:
break;
default:
ESP_LOGI(TAG, "GOT UNKONW MESSAGE");
break;
}
void slave_getstatusCallback(const esp_now_recv_info_t *esp_now_info,
const uint8_t *data, int data_len) {
BaseMessage replyMessage = {};
const BaseMessage *message = (const BaseMessage *)data;
StatusPayload payload = {
.status = 1,
.runningPartition = 1,
.uptime = 100,
.version = 0x0002,
};
replyMessage =
MessageBuilder(StatusPage, *(PayloadUnion *)&payload, sizeof(payload));
ESP_ERROR_CHECK(esp_now_send(esp_now_info->src_addr, (uint8_t *)&replyMessage,
sizeof(BaseMessage)));
}
void slave_pingCallback(const esp_now_recv_info_t *esp_now_info,
const uint8_t *data, int data_len) {
if (!hasMaster)
return;
BaseMessage replyMessage = {};
const BaseMessage *message = (const BaseMessage *)data;
ESP_LOGI(TAG, "GOT PING MESSAGE");
replyMessage = MessageBuilder(PingPage, *(PayloadUnion *)&message->payload,
sizeof(message->payload));
ESP_ERROR_CHECK(esp_now_send(esp_now_info->src_addr, (uint8_t *)&replyMessage,
sizeof(BaseMessage)));
}
void ESPNOW_RegisterSlaveCallbacks() {
ESP_RegisterFunction(BroadCastPage, slave_broadcastCallback);
ESP_RegisterFunction(GetStatusPage, slave_getstatusCallback);
ESP_RegisterFunction(PingPage, slave_pingCallback);
}
void master_receive_callback(const esp_now_recv_info_t *esp_now_info,
const uint8_t *data, int data_len) {
ESP_LOGI(TAG, "MASTER GOT MESSAGE");
// Allokiere Speicher für die Daten und kopiere sie
uint8_t *copied_data = (uint8_t *)malloc(data_len);
if (copied_data == NULL) {
ESP_LOGE(TAG, "Failed to allocate memory for message data.");
return;
}
memcpy(copied_data, data, data_len);
// Fülle die neue Struktur mit kopierten Daten
ESPNOW_MessageInfo msg_info;
msg_info.esp_now_info.src_addr = malloc(6);
if (msg_info.esp_now_info.src_addr) {
memcpy(msg_info.esp_now_info.src_addr, esp_now_info->src_addr, 6);
}
// Speicher für des_addr kopieren
msg_info.esp_now_info.des_addr = malloc(6);
if (msg_info.esp_now_info.des_addr) {
memcpy(msg_info.esp_now_info.des_addr, esp_now_info->des_addr, 6);
}
// rx_ctrl Struktur kopieren
msg_info.esp_now_info.rx_ctrl = malloc(sizeof(wifi_pkt_rx_ctrl_t));
if (msg_info.esp_now_info.rx_ctrl) {
memcpy(msg_info.esp_now_info.rx_ctrl, esp_now_info->rx_ctrl,
sizeof(wifi_pkt_rx_ctrl_t));
}
msg_info.data = copied_data;
msg_info.data_len = data_len;
if (xQueueSend(ESP_recieved_message_queue, &msg_info, portMAX_DELAY) !=
pdPASS) {
// Fehlerbehandlung: Queue voll oder Senden fehlgeschlagen
ESP_LOGE(TAG, "Failed to send parsed message to queue.");
}
return;
}
void client_receive_callback(const esp_now_recv_info_t *esp_now_info,
const uint8_t *data, int data_len) {
ESP_LOGI(TAG, "SLAVE GOT MESSAGE");
ESP_LOGI(TAG, "Received message from: " MACSTR,
MAC2STR(esp_now_info->src_addr));
uint8_t *copied_data = (uint8_t *)malloc(data_len);
if (copied_data == NULL) {
ESP_LOGE(TAG, "Failed to allocate memory for message data.");
return;
}
memcpy(copied_data, data, data_len);
// Fülle die neue Struktur mit kopierten Daten
ESPNOW_MessageInfo msg_info;
memcpy(&msg_info.esp_now_info, esp_now_info, sizeof(esp_now_recv_info_t));
msg_info.data = copied_data;
msg_info.data_len = data_len;
if (xQueueSend(ESP_recieved_message_queue, &msg_info, portMAX_DELAY) !=
pdPASS) {
// Fehlerbehandlung: Queue voll oder Senden fehlgeschlagen
ESP_LOGE(TAG, "Failed to send parsed message to queue.");
}
return;
}
void client_data_sending_task(void *param) {
+62 -2
View File
@@ -28,16 +28,35 @@ static uint8_t broadcast_address[ESP_NOW_ETH_ALEN] = {0xFF, 0xFF, 0xFF,
#define MESSAGE_QUEUE_SIZE 10
typedef enum {
OTA_PREP_UPGRADE,
OTA_SEND_PAYLOAD,
OTA_WRITE_UPDATE_BUFFER,
OTA_SEND_MISSING,
OTA_UPDATE_INFO,
OTA_END_UPGRADE,
StatusPage,
GetStatusPage,
ConfigPage,
PingPage,
BroadCastPage,
RegisterPage,
FirmwarePrepPage,
FirmwarePayloadPage,
} CommandPages;
typedef struct __attribute__((packed)) {
} OTA_PREP_UPGRADE_Payload;
typedef struct __attribute__((packed)) {
} OTA_SEND_PAYLOAD_Payload;
typedef struct __attribute__((packed)) {
} OTA_WRITE_UPDATE_BUFFER_Payload;
typedef struct __attribute__((packed)) {
} OTA_SEND_MISSING_Payload;
typedef struct __attribute__((packed)) {
} OTA_UPDATE_INFO_Payload;
typedef struct __attribute__((packed)) {
} OTA_END_UPGRADE_Payload;
typedef struct __attribute__((packed)) {
uint16_t version; // software version
uint8_t runningPartition;
@@ -97,6 +116,47 @@ typedef struct __attribute__((packed)) {
static_assert(sizeof(BaseMessage) <= 255,
"BaseMessage darf nicht größer als 255 sein");
typedef void (*ESP_RegisterFunctionCallback)(
const esp_now_recv_info_t *esp_now_info, const uint8_t *data, int data_len);
typedef void (*ESP_RegisterTaskCallback)(
const esp_now_recv_info_t *esp_now_info, const uint8_t *data, int data_len);
struct ESP_RegisterdFunction {
CommandPages MSGID;
ESP_RegisterFunctionCallback callback;
};
struct ESP_RegisterdTask {
CommandPages MSGID;
ESP_RegisterTaskCallback task;
};
struct ESP_MessageBroker {
struct ESP_RegisterdFunction FunctionList[64];
uint8_t num_direct_callbacks;
struct ESP_RegisterdTask TaskList[64];
uint8_t num_task_callbacks;
};
typedef struct {
QueueHandle_t message_queue;
} ESP_MessageBrokerTaskParams_t;
typedef struct {
esp_now_recv_info_t esp_now_info;
uint8_t *data;
int data_len;
} ESPNOW_MessageInfo;
void ESP_InitMessageBroker(QueueHandle_t msg_queue_handle);
void ESP_RegisterFunction(CommandPages command,
ESP_RegisterFunctionCallback callback);
void ESP_RegisterTask(CommandPages command, ESP_RegisterTaskCallback callback);
void ESP_MessageBrokerTask(void *param);
void ESPNOW_RegisterMasterCallbacks();
void ESPNOW_RegisterSlaveCallbacks();
int init_com(ClientList *clients, uint8_t wifi_channel);
int getNextFreeClientId();
int add_peer(uint8_t *macAddr);
View File
View File
+14 -4
View File
@@ -36,6 +36,7 @@ static uint8_t send_message_buffer[1024];
static uint8_t send_message_payload_buffer[512];
static MessageBrokerTaskParams_t broker_task_params;
static ESP_MessageBrokerTaskParams_t esp_broker_task_params;
ClientList clientList = {.Clients = {{0}}, .ClientCount = 0};
@@ -74,8 +75,6 @@ void versionCallback(uint8_t msgid, const uint8_t *payload, size_t payload_len,
send_payload_buffer[1] = (uint8_t)((version >> 8) & 0xFF);
memcpy(&send_payload_buffer[2], &BUILD_GIT_HASH, git_build_hash_len);
// currently running partition
int len = build_message(UART_VERSION, send_payload_buffer, needed_buffer_size,
send_buffer, send_buffer_size);
if (len < 0) {
@@ -85,7 +84,7 @@ void versionCallback(uint8_t msgid, const uint8_t *payload, size_t payload_len,
payload_len, send_buffer_size, len);
return;
}
uart_write_bytes(MASTER_UART, send_buffer, len - 1);
uart_write_bytes(MASTER_UART, send_buffer, len);
}
void clientInfoCallback(uint8_t msgid, const uint8_t *payload,
@@ -143,7 +142,7 @@ void clientInfoCallback(uint8_t msgid, const uint8_t *payload,
int len = build_message(UART_CLIENT_INFO, send_payload_buffer,
needed_buffer_size, send_buffer, send_buffer_size);
ESP_LOG_BUFFER_HEX("SEND BUFFER: ", send_buffer, send_buffer_size);
// ESP_LOG_BUFFER_HEX("SEND BUFFER: ", send_buffer, send_buffer_size);
if (len < 0) {
ESP_LOGE(TAG,
@@ -259,9 +258,19 @@ void app_main(void) {
}
nvs_close(nt);
QueueHandle_t espnow_message_queue =
xQueueCreate(10, sizeof(ESPNOW_MessageInfo));
ESP_InitMessageBroker(espnow_message_queue);
esp_broker_task_params.message_queue = espnow_message_queue;
xTaskCreate(ESP_MessageBrokerTask, "espnow_message_broker_task", 4096,
(void *)&esp_broker_task_params, 4, NULL);
// Tasks starten basierend auf Master/Client
if (isMaster) {
ESP_LOGI(TAG, "Started in Mastermode");
ESPNOW_RegisterMasterCallbacks();
add_peer(broadcast_address);
xTaskCreate(master_broadcast_task, "MasterBroadcast", 4096, NULL, 1, NULL);
// xTaskCreate(master_ping_task, "MasterPing", 4096, NULL, 1, NULL);
@@ -297,6 +306,7 @@ void app_main(void) {
// NULL);
} else {
ESP_LOGI(TAG, "Started in Slavemode");
ESPNOW_RegisterSlaveCallbacks();
// xTaskCreate(client_data_sending_task, "ClientDataSending", 4096, NULL, 1,
// NULL);
}
+2 -3
View File
@@ -20,8 +20,8 @@ bool add_byte_with_length_check(uint8_t byte, size_t write_index, uint8_t *data,
int build_message(uint8_t msgid, const uint8_t *payload, size_t payload_len,
uint8_t *msg_buffer, size_t msg_buffer_size) {
ESP_LOGE("BM", "payload_len %d, msg_buffer_size %d", payload_len + 4,
msg_buffer_size);
//ESP_LOGE("BM", "payload_len %d, msg_buffer_size %d", payload_len + 4,
// msg_buffer_size);
if (payload_len + 4 > msg_buffer_size) {
return PayloadBiggerThenBuffer;
}
@@ -75,6 +75,5 @@ int build_message(uint8_t msgid, const uint8_t *payload, size_t payload_len,
msg_buffer[write_index++] = checksum;
msg_buffer[write_index++] = EndByte;
ESP_LOGE("BM", "MESSAGE FERTIG GEBAUT");
return write_index;
}
+2 -2
View File
@@ -46,8 +46,8 @@ void MessageBrokerTask(void *param) {
while (1) {
if (xQueueReceive(msg_queue, &received_msg, portMAX_DELAY)) {
ESP_LOGI(TAG, "Received message from queue: MSGID=0x%02X, Length=%u",
received_msg.msgid, received_msg.payload_len);
//ESP_LOGI(TAG, "Received message from queue: MSGID=0x%02X, Length=%u",
// received_msg.msgid, received_msg.payload_len);
for (int i = 0; i < mr.num_direct_callbacks; i++) {
if (mr.FunctionList[i].MSGID == received_msg.msgid) {
+89 -27
View File
@@ -4,6 +4,7 @@
#include "esp_log.h"
#include "esp_ota_ops.h"
#include "esp_partition.h"
#include "esp_system.h"
#include "message_builder.h"
#include "message_handler.h"
#include "uart_handler.h"
@@ -17,17 +18,20 @@
static uint8_t update_buffer[UPDATE_BUFFER_SIZE];
static uint16_t update_buffer_write_index;
static uint32_t update_size;
static uint16_t sequenz_counter; // how often the update buffer gets written
static const char *TAG = "ALOX - OTA";
static esp_ota_handle_t update_handle;
void prepare_ota_update() {
int prepare_ota_update() {
const esp_partition_t *running = esp_ota_get_running_partition();
ESP_LOGI(TAG, "OTA: Running Partition: %s", running->label);
int part = 0;
char partition_to_update[] = "ota_0";
if (strcmp(running->label, "ota_0") == 0) {
strcpy(partition_to_update, "ota_1");
part = 1;
}
const esp_partition_t *update_partition = esp_partition_find_first(
@@ -36,7 +40,7 @@ void prepare_ota_update() {
// Check if the partition was found
if (update_partition == NULL) {
ESP_LOGE(TAG, "Failed to find OTA partition: %s", partition_to_update);
return; // Or handle the error appropriately
return -1; // Or handle the error appropriately
}
ESP_LOGI(TAG, "Gonna write OTA Update in Partition: %s",
@@ -47,11 +51,11 @@ void prepare_ota_update() {
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ota_begin failed (%s)", esp_err_to_name(err));
esp_ota_abort(update_handle);
return;
return -2;
}
ESP_LOGI(TAG, "OTA update started successfully.");
// Proceed with writing the new firmware to the partition...
return part;
}
void start_uart_update(uint8_t msgid, const uint8_t *payload,
@@ -60,10 +64,23 @@ void start_uart_update(uint8_t msgid, const uint8_t *payload,
size_t send_buffer_size) {
ESP_LOGI(TAG, "OTA Update Start Uart Command");
prepare_ota_update();
vTaskPrioritySet(NULL, 2);
update_size = 0;
int part = prepare_ota_update();
// Message:
// byte partition
// byte error
if (part < 0) {
send_payload_buffer[1] = (part * -1) & 0xff;
} else {
send_payload_buffer[0] = part & 0xff;
}
int send_payload_len = 2;
send_payload_buffer[0] = 0xff;
int len = build_message(UART_OTA_START, send_payload_buffer, send_payload_len,
send_buffer, send_buffer_size);
if (len < 0) {
@@ -77,35 +94,47 @@ void start_uart_update(uint8_t msgid, const uint8_t *payload,
uart_write_bytes(MASTER_UART, send_buffer, len);
}
void payload_uart_update(uint8_t msgid, const uint8_t *payload,
size_t payload_len, uint8_t *send_payload_buffer,
size_t send_payload_buffer_size, uint8_t *send_buffer,
size_t send_buffer_size) {
ESP_LOGI(TAG, "OTA Update Payload Uart Command");
if (update_buffer_write_index < UPDATE_BUFFER_SIZE - UPDATE_PAYLOAD_SIZE) {
uint32_t write_len = MIN(UPDATE_PAYLOAD_SIZE, payload_len);
ESP_LOGI(TAG, "Writing Data to Update BUffer Sequence %d, writing Data %d",
sequenz_counter, write_len);
memcpy(&update_buffer[update_buffer_write_index], payload, write_len);
update_buffer_write_index += write_len;
} else {
ESP_LOGI(TAG, "Update Buffer full, writing it to OTA Update");
esp_err_t write_ota_update(uint32_t write_len, const uint8_t *payload) {
if (update_buffer_write_index > UPDATE_BUFFER_SIZE - write_len) {
// ESP_LOGI(TAG, "Writing Data to Update BUffer Sequence %d, writing Data
// %d",
// sequenz_counter, write_len);
// write to ota
esp_err_t err =
esp_ota_write(update_handle, update_buffer, update_buffer_write_index);
if (err != ESP_OK) {
ESP_LOGE(TAG, "GOT ESP ERROR WRITE OTA %d", err);
return err;
}
update_buffer_write_index = 0;
sequenz_counter++;
return err;
}
memcpy(&update_buffer[update_buffer_write_index], payload, write_len);
update_buffer_write_index += write_len;
return ESP_OK;
}
void payload_uart_update(uint8_t msgid, const uint8_t *payload,
size_t payload_len, uint8_t *send_payload_buffer,
size_t send_payload_buffer_size, uint8_t *send_buffer,
size_t send_buffer_size) {
// ESP_LOGI(TAG, "OTA Update Payload Uart Command");
uint32_t write_len = MIN(UPDATE_PAYLOAD_SIZE, payload_len);
update_size += write_len;
esp_err_t err = write_ota_update(write_len, payload);
if (err != ESP_OK) {
ESP_LOGE(TAG, "GOT ESP ERROR WRITE OTA %d", err);
}
size_t send_payload_len = 4;
memcpy(send_payload_buffer, &sequenz_counter, 2);
memcpy(&send_payload_buffer[2], &update_buffer_write_index, 2);
send_payload_buffer[4] = 0x00; // error
int len = build_message(UART_OTA_PAYLOAD, send_payload_buffer,
send_payload_len, send_buffer, send_buffer_size);
@@ -120,17 +149,48 @@ void payload_uart_update(uint8_t msgid, const uint8_t *payload,
uart_write_bytes(MASTER_UART, send_buffer, len);
}
esp_err_t end_ota_update() {
esp_err_t err =
esp_ota_write(update_handle, update_buffer, update_buffer_write_index);
if (err != ESP_OK) {
ESP_LOGE(TAG, "GOT ESP ERROR WRITE OTA %d", err);
}
err = esp_ota_end(update_handle);
if (err != ESP_OK) {
ESP_LOGE(TAG, "GOT ESP ERROR WRITE OTA %d", err);
}
ESP_LOGE(TAG, "UPDATE ENDE UPDATGE SIZE SIND %d BYTES", update_size);
// Hol dir die zuletzt geschriebene Partition
const esp_partition_t *partition = esp_ota_get_next_update_partition(NULL);
if (partition == NULL) {
ESP_LOGE(TAG, "Failed to get updated partition");
err = ESP_FAIL;
}
// Setze sie als Boot-Partition
ESP_LOGE(TAG, "Setzte nächste Partition auf %s", partition->label);
err = esp_ota_set_boot_partition(partition);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ota_set_boot_partition failed: %s",
esp_err_to_name(err));
}
return err;
}
void end_uart_update(uint8_t msgid, const uint8_t *payload, size_t payload_len,
uint8_t *send_payload_buffer,
size_t send_payload_buffer_size, uint8_t *send_buffer,
size_t send_buffer_size) {
ESP_LOGI(TAG, "OTA Update End Uart Command");
esp_err_t err = esp_ota_end(update_handle);
if (err != ESP_OK) {
ESP_LOGE(TAG, "GOT ESP ERROR WRITE OTA %d", err);
}
int send_payload_len = 0;
esp_err_t err = end_ota_update();
// message ret esp_err_t
int send_payload_len = 1;
send_payload_buffer[0] = err & 0xff;
int len = build_message(UART_OTA_END, send_payload_buffer, send_payload_len,
send_buffer, send_buffer_size);
if (len < 0) {
@@ -142,6 +202,8 @@ void end_uart_update(uint8_t msgid, const uint8_t *payload, size_t payload_len,
}
uart_write_bytes(MASTER_UART, send_buffer, len);
vTaskPrioritySet(NULL, 1);
}
void write_ota_update_from_uart_task(void *param) {}
+8 -3
View File
@@ -1,9 +1,12 @@
#ifndef OTA_UPDATE_H
#define OTA_UPDATE_H
#include "esp_err.h"
#include <stdint.h>
#include <sys/types.h>
#define UPDATE_BUFFER_SIZE 4000
#define UPDATE_PAYLOAD_SIZE 200
#define UPDATE_MAX_SEQUENZES (UPDATE_BUFFER_SIZE/UPDATE_PAYLOAD_SIZE)
#define UPDATE_MAX_SEQUENZES (UPDATE_BUFFER_SIZE / UPDATE_PAYLOAD_SIZE)
void init_ota();
@@ -13,8 +16,10 @@ enum OTA_UPDATE_STATES {
WAITING_FOR_PAYLOAD,
WRITING_OTA_TO_PARTITION,
};
int prepare_ota_update();
esp_err_t write_ota_update(uint32_t write_len, const uint8_t *payload);
esp_err_t end_ota_update();
#endif
+3 -3
View File
@@ -18,7 +18,7 @@ static const char *TAG = "ALOX - UART";
static QueueHandle_t parsed_message_queue;
void init_uart(QueueHandle_t msg_queue_handle) {
uart_config_t uart_config = {.baud_rate = 115200,
uart_config_t uart_config = {.baud_rate = 921600, // 921600, 115200
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
@@ -61,9 +61,9 @@ void send_message_hook(const uint8_t *buffer, size_t length) {
void HandleMessageReceivedCallback(uint8_t msgid, const uint8_t *payload,
size_t payload_len) {
ESP_LOGI(TAG, "GOT UART MESSAGE MSGID: %02X, Len: %u bytes \nMSG: ", msgid,
/*ESP_LOGI(TAG, "GOT UART MESSAGE MSGID: %02X, Len: %u bytes \nMSG: ", msgid,
payload_len, payload);
ESP_LOG_BUFFER_HEX(TAG, payload, payload_len);
ESP_LOG_BUFFER_HEX(TAG, payload, payload_len);*/
ParsedMessage_t msg_to_send;
msg_to_send.msgid = msgid;
+104 -35
View File
@@ -2,54 +2,123 @@
## Struktur einer Nachricht
0xAA = Startbyte
checksum = XOR über alle Bytes (ohne Startbyte und Checksum-Byte)
- Control Bytes:
- 0xAA = Startbyte
- 0xBB = EscapeByte
- 0xCC = EndByte
## Nachrichtenaufbau (Message Frame)
checksum = XOR über alle Bytes (ohne Control Bytes und Checksum-Byte)
[ Startbyte ] [ Length ] [ CommandPage ] [ Payload (variabel) ] [ Checksum ]
Command, Payload und Checksum werden Escaped sollten sie einem Control Byte ensteprechend
| Startbyte | Command | Payload (variable) | Checksum | Endbyte |
|-----------|---------|--------------------|----------|---------|
### Felder im Detail:
- **Length** (`uint8_t`):
Gibt die Gesamtlänge der Nachricht **ab `CommandPage` bis einschließlich `Payload`** an.
- **CommandPage** (`uint8_t`):
Gibt an, welcher Nachrichtentyp oder Befehl gesendet wird.
- **Command** (`uint8_t`):
Gibt an, welcher Nachrichtentyp gesendet wird.
- **Payload** (`variabel`):
Datenfeld mit variabler Länge, abhängig vom `CommandPage`.
Datenfeld mit variabler Länge, abhängig vom `Command`.
- **Checksum** (`uint8_t`):
XOR über alle Bytes ab `Length` bis einschließlich `Payload`.
### Nachrichten von PC zu ESP:
clientid: 0x00 für master, 0xFF für broadcast, ansonsten 0xA0-0xB3 // 19 Clients
### RequestPing 0xE1
Payload: byte: clientid
### RequestInfo 0xE2
Payload: byte: clientid
### RequestRestart 0xE3
Payload: byte: clientid
### PrepareFirmwareUpdate 0xF1
Payload: none
### FirmwareUpdateLine 0xF2
Payload: firmware line 240Bytes MAX
### ExecuteFirmwareUpdate 0xF3
Payload: none
### Nachrichten von ESP zu PC:
XOR über aller Bytes von `Command` und `Payload`.
### Messages
---
Command:
- UART_ECHO = 0x01
- UART_VERSION = 0x02
- UART_CLIENT_INFO = 0x03
# Roadmap
- [ ] SEND STATUS OF DEVICE OVER UART
- [ ] CONFIGURE PEERS OVER MASTER
- [ ] SAVE PIN CONFIG ON PEERS
Grundlegend sind alle Zahlenwerte im LittleEndian format!
#### UART_ECHO:
- Send Message: AA 01 01 CC
- Message Received: AA 01 01 CC
Sendet zurück was geschickt wird.
#### UART_VERSION:
| Offset | Länge (Bytes) | Bezeichnung | Beschreibung |
|--------|---------------|-------------|------------------|
| 0 | 2 | Version | Software Version |
| 2 | 7 | BuildHash | Git Hash |
- Send Message: AA 02 02 CC
- Message Received: AA 02 01 00 33 62 35 36 30 37 39 6F CC
| Version | Buildhash |
|---------|-----------|
| 1 | 3b56078 |
Sendet die Version und den Buildhash vom Master zurück.
#### UART_CLIENT_INFO:
Das erste Datenbyte nach dem Commando gibt an wie viele Client Infos in dieser Nachricht vorhanden sind.
Danach teilt sich ein Eintrag wie Folgt auf:
| Offset | Länge (Bytes) | Bezeichnung | Beschreibung |
|--------|---------------|----------------------------|---------------------------------------------------------------|
| 0 | 1 | Client ID | Eindeutige ID des Clients. |
| 1 | 1 | Ist verfügbar | Boolean-Wert (0 = nein, 1 = ja), ob der Client verfügbar ist. |
| 2 | 1 | Slot genutzt | Boolean-Wert (0 = nein, 1 = ja), ob der Slot belegt ist. |
| 3 | 6 | MAC-Adresse | Die Hardware-Adresse des Clients. |
| 9 | 4 | Letzter Ping | Zeit in Millisekunden seit dem letzten Ping. |
| 13 | 4 | Letzter erfolgreicher Ping | Zeit in Millisekunden seit dem letzten erfolgreichen Ping. |
| 17 | 2 | Version | Versionsnummer des Clients. |
##### Ein Client
- Send Message: AA 03 03 CC
- Message Received: AA 03 01 00 01 01 50 78 7D 18 89 F8 34 00 00 00 61 1F 00 00 02 00 76 CC
| Client ID | Verfügbar | Genutzt | MAC-Adresse | Last Ping | Last Successful Ping | Version |
|-----------|-----------|---------|-------------------|-----------|----------------------|---------|
| 0 | 1 | 1 | 50:78:7D:18:89:F8 | 52 | 8033 | 2 |
##### Zwei Clients
- Send Message: AA 03 03 CC
- Message Received: AA 03 02 00 01 01 50 78 7D 18 89 F8 22 00 00 00 F4 2A 01 00 02 00 01 01 01 50 78 7D 18 0C B4 10 00 00 00 F1 2A 01 00 02 00 FE CC
| Client ID | Verfügbar | Genutzt | MAC-Adresse | Last Ping | Last Successful Ping | Version |
|-----------|-----------|---------|-------------------|-----------|----------------------|---------|
| 0 | 1 | 1 | 50:78:7D:18:89:F8 | 34 | 76532 | 2 |
| 1 | 1 | 1 | 50:78:7D:18:C:B4 | 16 | 76529 | 2 |
#### UART_CLIENT_INPUT:
Die Identifizierung wird hier anhand der vorher gesendeten ClientID gemacht also muss einmal vorher `UART_CLIENT_INFO` aufgerufen werden.
Das erste Datenbyte nach dem Commando gibt an wie viele Client Infos in dieser Nachricht vorhanden sind.
Danach teilt sich ein Eintrag wie Folgt auf:
| Offset | Länge (Bytes) | Bezeichnung | Beschreibung |
|--------|---------------|-------------|----------------------------------------------------------------------------------|
| 0 | 1 | Client ID | Eindeutige ID des Clients. |
| 1 | 4 | LageX | Float Wert von der X Lage. |
| 5 | 4 | LageY | Float Wert von der Y Lage. |
| 9 | 4 | InputMaske | Int32 Wert der als Bitmaske genutzt wird um bis zu 32 Boolische Werte anzugeben. |
Inputmaske:
Taster1, Taster2, IOError1, IOErro2, AkkuStand1, AkkuStand2 (2 Bit kodiert für 25%,50%,75%,100%), rest unbelegt, default 0
| Bit1 | Bit2 | Akkustand |
|------|------|-----------|
| 0 | 0 | 25% |
| 0 | 1 | 50% |
| 1 | 0 | 75% |
| 1 | 1 | 100% |
<div style="page-break-after: always;"></div>
# Machbarkeits-Studie
+2098
View File
File diff suppressed because it is too large Load Diff
+2357
View File
File diff suppressed because it is too large Load Diff