Compare commits
21
Commits
441347fc95
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d8716c232e | ||
|
|
a3e330ed77 | ||
|
|
672267b991 | ||
|
|
8398442544 | ||
|
|
b29512d922 | ||
|
|
6e4525df38 | ||
|
|
60a304a93d | ||
|
|
f504553ab6 | ||
|
|
bbfe61a9ed | ||
|
|
73bc078465 | ||
|
|
8d4f1da028 | ||
|
|
1d36a757c0 | ||
|
|
648e201f5e | ||
|
|
400d308f4a | ||
|
|
1c9120a197 | ||
|
|
3b560799af | ||
|
|
3abdd8816c | ||
|
|
cf42e86322 | ||
|
|
59dbd7b035 | ||
|
|
d3e44125a2 | ||
|
|
ebb739a3a0 |
@@ -13,6 +13,15 @@ get_code_gen:
|
|||||||
gen_prot:
|
gen_prot:
|
||||||
./alox.protogen -i prot.json -o main/uart
|
./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:
|
buildIdf:
|
||||||
idf.py build
|
idf.py build
|
||||||
@@ -26,6 +35,17 @@ flashMini2:
|
|||||||
flashMini3:
|
flashMini3:
|
||||||
idf.py flash -p /dev/ttyACM2
|
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:
|
monitorMini:
|
||||||
idf.py monitor -p /dev/ttyACM0
|
idf.py monitor -p /dev/ttyACM0
|
||||||
|
|
||||||
|
|||||||
+202
-12
@@ -3,8 +3,11 @@ package main
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/pterm/pterm"
|
"github.com/pterm/pterm"
|
||||||
"go.bug.st/serial"
|
"go.bug.st/serial"
|
||||||
@@ -12,6 +15,19 @@ import (
|
|||||||
|
|
||||||
type ParserState int
|
type ParserState int
|
||||||
|
|
||||||
|
const (
|
||||||
|
// MISC
|
||||||
|
UART_ECHO = 0x01
|
||||||
|
UART_VERSION = 0x02
|
||||||
|
UART_CLIENT_INFO = 0x03
|
||||||
|
|
||||||
|
// OTA
|
||||||
|
UART_OTA_START = 0x10
|
||||||
|
UART_OTA_PAYLOAD = 0x11
|
||||||
|
UART_OTA_END = 0x12
|
||||||
|
UART_OTA_STATUS = 0x13
|
||||||
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
WAITING_FOR_START_BYTE ParserState = iota
|
WAITING_FOR_START_BYTE ParserState = iota
|
||||||
ESCAPED_MESSAGE_ID
|
ESCAPED_MESSAGE_ID
|
||||||
@@ -43,6 +59,22 @@ type MessageReceive struct {
|
|||||||
raw_write_index int
|
raw_write_index int
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type OTASyncManager struct {
|
||||||
|
OTA_MessageCounter int
|
||||||
|
OTA_PayloadMessageSequence int
|
||||||
|
NewOTAMessage chan MessageReceive
|
||||||
|
TimeoutMessage time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ot *OTASyncManager) WaitForNextMessageTimeout() (*MessageReceive, error) {
|
||||||
|
select {
|
||||||
|
case msg := <-ot.NewOTAMessage:
|
||||||
|
return &msg, nil
|
||||||
|
case <-time.After(ot.TimeoutMessage):
|
||||||
|
return nil, fmt.Errorf("Message Timeout")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func initMessageReceive(mr *MessageReceive) {
|
func initMessageReceive(mr *MessageReceive) {
|
||||||
mr.raw_message = make([]byte, 1024*4)
|
mr.raw_message = make([]byte, 1024*4)
|
||||||
mr.parsed_message = make([]byte, 1024*4)
|
mr.parsed_message = make([]byte, 1024*4)
|
||||||
@@ -63,7 +95,41 @@ func addByteToParsedBuffer(mr *MessageReceive, pbyte byte) {
|
|||||||
mr.checksum ^= pbyte
|
mr.checksum ^= pbyte
|
||||||
}
|
}
|
||||||
|
|
||||||
func parse_03_payload(payloadBuffer []byte, payload_len int) {
|
func parse_uart_ota_payload_payload(payloadBuffer []byte, payload_len int) {
|
||||||
|
//fmt.Printf("RAW BUFFER: % 02X", payloadBuffer[:payload_len])
|
||||||
|
if payload_len != 4 {
|
||||||
|
fmt.Printf("Payload should be 4 is %v", payload_len)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
type payload_data struct {
|
||||||
ClientID uint8
|
ClientID uint8
|
||||||
@@ -135,12 +201,26 @@ func parse_03_payload(payloadBuffer []byte, payload_len int) {
|
|||||||
func message_receive_callback(mr MessageReceive) {
|
func message_receive_callback(mr MessageReceive) {
|
||||||
log.Printf("Message Received: % 02X\n", mr.raw_message[:mr.raw_write_index])
|
log.Printf("Message Received: % 02X\n", mr.raw_message[:mr.raw_write_index])
|
||||||
switch mr.parsed_message[0] {
|
switch mr.parsed_message[0] {
|
||||||
case 0x01:
|
case byte(UART_ECHO):
|
||||||
break
|
break
|
||||||
case 0x02:
|
case UART_VERSION:
|
||||||
|
parse_uart_version_payload(mr.parsed_message, mr.write_index)
|
||||||
break
|
break
|
||||||
case 0x03:
|
case UART_CLIENT_INFO:
|
||||||
parse_03_payload(mr.parsed_message, mr.write_index)
|
parse_uart_client_info_payload(mr.parsed_message, mr.write_index)
|
||||||
|
break
|
||||||
|
case UART_OTA_START:
|
||||||
|
OTA_UpdateHandler.NewOTAMessage <- mr
|
||||||
|
break
|
||||||
|
case UART_OTA_PAYLOAD:
|
||||||
|
parse_uart_ota_payload_payload(mr.parsed_message, mr.write_index)
|
||||||
|
OTA_UpdateHandler.NewOTAMessage <- mr
|
||||||
|
break
|
||||||
|
case UART_OTA_END:
|
||||||
|
OTA_UpdateHandler.NewOTAMessage <- mr
|
||||||
|
break
|
||||||
|
case UART_OTA_STATUS:
|
||||||
|
OTA_UpdateHandler.NewOTAMessage <- mr
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -179,18 +259,18 @@ func parseByte(mr *MessageReceive, pbyte byte) {
|
|||||||
}
|
}
|
||||||
if pbyte == START_BYTE {
|
if pbyte == START_BYTE {
|
||||||
mr.error = UNEXPECETD_BYTE
|
mr.error = UNEXPECETD_BYTE
|
||||||
message_receive_failed_callback(*mr)
|
go message_receive_failed_callback(*mr)
|
||||||
initMessageReceive(mr)
|
initMessageReceive(mr)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if pbyte == END_BYTE {
|
if pbyte == END_BYTE {
|
||||||
if mr.checksum != 0 { // checksum wrong
|
if mr.checksum != 0 { // checksum wrong
|
||||||
mr.error = WRONG_CHECKSUM
|
mr.error = WRONG_CHECKSUM
|
||||||
message_receive_failed_callback(*mr)
|
go message_receive_failed_callback(*mr)
|
||||||
initMessageReceive(mr)
|
initMessageReceive(mr)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
message_receive_callback(*mr)
|
go message_receive_callback(*mr)
|
||||||
initMessageReceive(mr)
|
initMessageReceive(mr)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -222,6 +302,10 @@ func buildMessage(payloadBuffer []byte, payload_len int, sendBuffer []byte) int
|
|||||||
writeIndex++
|
writeIndex++
|
||||||
checksum ^= b
|
checksum ^= b
|
||||||
}
|
}
|
||||||
|
if checksum == START_BYTE || checksum == ESCAPE_BYTE || checksum == END_BYTE {
|
||||||
|
sendBuffer[writeIndex] = ESCAPE_BYTE
|
||||||
|
writeIndex++
|
||||||
|
}
|
||||||
sendBuffer[writeIndex] = checksum
|
sendBuffer[writeIndex] = checksum
|
||||||
writeIndex++
|
writeIndex++
|
||||||
sendBuffer[writeIndex] = END_BYTE
|
sendBuffer[writeIndex] = END_BYTE
|
||||||
@@ -240,9 +324,25 @@ func sendMessage(port serial.Port, sendBuffer []byte) {
|
|||||||
fmt.Printf("Send Message % 02X\n", sendBuffer[:n])
|
fmt.Printf("Send Message % 02X\n", sendBuffer[:n])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
updatePath string
|
||||||
|
OTA_UpdateHandler OTASyncManager
|
||||||
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
flag.StringVar(&updatePath, "update", "", "Path to Updatefile")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
OTA_UpdateHandler = OTASyncManager{
|
||||||
|
OTA_MessageCounter: 0,
|
||||||
|
OTA_PayloadMessageSequence: 0,
|
||||||
|
NewOTAMessage: make(chan MessageReceive),
|
||||||
|
TimeoutMessage: time.Millisecond * 30000,
|
||||||
|
}
|
||||||
|
|
||||||
mode := &serial.Mode{
|
mode := &serial.Mode{
|
||||||
BaudRate: 115200,
|
//BaudRate: 115200,
|
||||||
|
BaudRate: 921600,
|
||||||
}
|
}
|
||||||
port, err := serial.Open("/dev/ttyUSB0", mode)
|
port, err := serial.Open("/dev/ttyUSB0", mode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -279,6 +379,78 @@ func main() {
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
if updatePath != "" {
|
||||||
|
// start update
|
||||||
|
update, err := os.ReadFile(updatePath)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Could not read Update file %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Printf("Update Buffer read, update size %v", len(update))
|
||||||
|
log.Printf("Gonna break it down in 200 Bytes packages will send %v packages", len(update)/200)
|
||||||
|
|
||||||
|
// start
|
||||||
|
payload_buffer := make([]byte, 1024)
|
||||||
|
send_buffer := make([]byte, 1024)
|
||||||
|
payload_buffer[0] = UART_OTA_START
|
||||||
|
n := buildMessage(payload_buffer, 1, send_buffer)
|
||||||
|
sendMessage(port, send_buffer[:n])
|
||||||
|
msg, err := OTA_UpdateHandler.WaitForNextMessageTimeout()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error Message not acked %v", err)
|
||||||
|
} else {
|
||||||
|
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)
|
||||||
|
payload_buffer[0] = UART_OTA_END
|
||||||
|
n = buildMessage(payload_buffer, 1, send_buffer)
|
||||||
|
sendMessage(port, send_buffer[:n])
|
||||||
|
|
||||||
|
_, err = OTA_UpdateHandler.WaitForNextMessageTimeout()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error Message not acked %v", err)
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
log.Printf("Message Waiting hat funktionioert")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
for {
|
for {
|
||||||
var input string
|
var input string
|
||||||
_, err := fmt.Scanln(&input)
|
_, err := fmt.Scanln(&input)
|
||||||
@@ -293,24 +465,42 @@ func main() {
|
|||||||
case "1":
|
case "1":
|
||||||
payload_buffer := make([]byte, 1024)
|
payload_buffer := make([]byte, 1024)
|
||||||
send_buffer := make([]byte, 1024)
|
send_buffer := make([]byte, 1024)
|
||||||
payload_buffer[0] = 0x01
|
payload_buffer[0] = UART_ECHO
|
||||||
n := buildMessage(payload_buffer, 1, send_buffer)
|
n := buildMessage(payload_buffer, 1, send_buffer)
|
||||||
sendMessage(port, send_buffer[:n])
|
sendMessage(port, send_buffer[:n])
|
||||||
break
|
break
|
||||||
case "2":
|
case "2":
|
||||||
payload_buffer := make([]byte, 1024)
|
payload_buffer := make([]byte, 1024)
|
||||||
send_buffer := make([]byte, 1024)
|
send_buffer := make([]byte, 1024)
|
||||||
payload_buffer[0] = 0x02
|
payload_buffer[0] = UART_VERSION
|
||||||
n := buildMessage(payload_buffer, 1, send_buffer)
|
n := buildMessage(payload_buffer, 1, send_buffer)
|
||||||
sendMessage(port, send_buffer[:n])
|
sendMessage(port, send_buffer[:n])
|
||||||
break
|
break
|
||||||
case "3":
|
case "3":
|
||||||
payload_buffer := make([]byte, 1024)
|
payload_buffer := make([]byte, 1024)
|
||||||
send_buffer := make([]byte, 1024)
|
send_buffer := make([]byte, 1024)
|
||||||
payload_buffer[0] = 0x03
|
payload_buffer[0] = UART_CLIENT_INFO
|
||||||
n := buildMessage(payload_buffer, 1, send_buffer)
|
n := buildMessage(payload_buffer, 1, send_buffer)
|
||||||
sendMessage(port, send_buffer[:n])
|
sendMessage(port, send_buffer[:n])
|
||||||
break
|
break
|
||||||
|
case "4": // start update
|
||||||
|
payload_buffer := make([]byte, 1024)
|
||||||
|
send_buffer := make([]byte, 1024)
|
||||||
|
payload_buffer[0] = UART_OTA_START
|
||||||
|
n := buildMessage(payload_buffer, 1, send_buffer)
|
||||||
|
sendMessage(port, send_buffer[:n])
|
||||||
|
break
|
||||||
|
case "5": // send payload
|
||||||
|
payload_buffer := make([]byte, 1024)
|
||||||
|
send_buffer := make([]byte, 1024)
|
||||||
|
payload_buffer[0] = UART_OTA_PAYLOAD
|
||||||
|
for i := range 200 {
|
||||||
|
payload_buffer[i+1] = byte(i)
|
||||||
|
}
|
||||||
|
n := buildMessage(payload_buffer, 201, send_buffer)
|
||||||
|
sendMessage(port, send_buffer[:n])
|
||||||
|
break
|
||||||
|
case "6": // end update
|
||||||
default:
|
default:
|
||||||
fmt.Printf("Not a valid input")
|
fmt.Printf("Not a valid input")
|
||||||
}
|
}
|
||||||
|
|||||||
+309
-133
@@ -1,3 +1,4 @@
|
|||||||
|
#include "esp_err.h"
|
||||||
#include "esp_log.h"
|
#include "esp_log.h"
|
||||||
#include "esp_now.h"
|
#include "esp_now.h"
|
||||||
#include "esp_timer.h"
|
#include "esp_timer.h"
|
||||||
@@ -8,9 +9,97 @@
|
|||||||
#include <stdbool.h>
|
#include <stdbool.h>
|
||||||
#include <stdint.h>
|
#include <stdint.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
|
||||||
static const char *TAG = "ALOX - COM";
|
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
|
QueueHandle_t messageQueue = NULL; // Warteschlange für empfangene Nachrichten
|
||||||
static bool hasMaster = false;
|
static bool hasMaster = false;
|
||||||
static ClientList *esp_client_list;
|
static ClientList *esp_client_list;
|
||||||
@@ -20,7 +109,7 @@ static uint8_t channelNumber = 0;
|
|||||||
|
|
||||||
int init_com(ClientList *clients, uint8_t wifi_channel) {
|
int init_com(ClientList *clients, uint8_t wifi_channel) {
|
||||||
// Initialisiere die Kommunikations-Warteschlange
|
// Initialisiere die Kommunikations-Warteschlange
|
||||||
messageQueue = xQueueCreate(MESSAGE_QUEUE_SIZE, sizeof(BaseMessage));
|
messageQueue = xQueueCreate(MESSAGE_QUEUE_SIZE, sizeof(ESPNOW_MessageInfo));
|
||||||
if (messageQueue == NULL) {
|
if (messageQueue == NULL) {
|
||||||
ESP_LOGE(TAG, "Message queue creation failed");
|
ESP_LOGE(TAG, "Message queue creation failed");
|
||||||
return -1;
|
return -1;
|
||||||
@@ -36,7 +125,7 @@ int add_peer(uint8_t *macAddr) {
|
|||||||
esp_now_peer_info_t peerInfo = {
|
esp_now_peer_info_t peerInfo = {
|
||||||
.channel = channelNumber,
|
.channel = channelNumber,
|
||||||
.ifidx = ESP_IF_WIFI_STA,
|
.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);
|
memcpy(peerInfo.peer_addr, macAddr, ESP_NOW_ETH_ALEN);
|
||||||
|
|
||||||
@@ -72,13 +161,11 @@ BaseMessage MessageBuilder(CommandPages commandPage, PayloadUnion payload,
|
|||||||
size_t payload_size) {
|
size_t payload_size) {
|
||||||
BaseMessage message;
|
BaseMessage message;
|
||||||
|
|
||||||
// Initialisierung der BaseMessage
|
|
||||||
message.commandPage = commandPage;
|
message.commandPage = commandPage;
|
||||||
message.version = 1;
|
message.version = 1;
|
||||||
message.length = (uint16_t)payload_size;
|
message.length = (uint16_t)payload_size;
|
||||||
|
|
||||||
// Kopieren des Payloads in die Union
|
memset(&message.payload, 0, sizeof(message.payload));
|
||||||
memset(&message.payload, 0, sizeof(message.payload)); // Sicherheitsmaßnahme
|
|
||||||
memcpy(&message.payload, &payload, payload_size);
|
memcpy(&message.payload, &payload, payload_size);
|
||||||
|
|
||||||
return message;
|
return message;
|
||||||
@@ -93,7 +180,8 @@ void master_broadcast_task(void *param) {
|
|||||||
|
|
||||||
ESP_ERROR_CHECK(esp_now_send(broadcast_address, (uint8_t *)&message,
|
ESP_ERROR_CHECK(esp_now_send(broadcast_address, (uint8_t *)&message,
|
||||||
sizeof(BaseMessage)));
|
sizeof(BaseMessage)));
|
||||||
ESP_LOGI(TAG, "Broadcast Message sent");
|
|
||||||
|
// ESP_LOGI(TAG, "Broadcast Message sent");
|
||||||
vTaskDelay(pdMS_TO_TICKS(5000));
|
vTaskDelay(pdMS_TO_TICKS(5000));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -106,7 +194,7 @@ void master_broadcast_ping(void *param) {
|
|||||||
MessageBuilder(PingPage, *(PayloadUnion *)&payload, sizeof(payload));
|
MessageBuilder(PingPage, *(PayloadUnion *)&payload, sizeof(payload));
|
||||||
ESP_ERROR_CHECK(esp_now_send(broadcast_address, (uint8_t *)&message,
|
ESP_ERROR_CHECK(esp_now_send(broadcast_address, (uint8_t *)&message,
|
||||||
sizeof(BaseMessage)));
|
sizeof(BaseMessage)));
|
||||||
ESP_LOGI(TAG, "Broadcast PING Message sent");
|
// ESP_LOGI(TAG, "Broadcast PING Message sent");
|
||||||
vTaskDelay(pdMS_TO_TICKS(2500));
|
vTaskDelay(pdMS_TO_TICKS(2500));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -130,86 +218,207 @@ void master_ping_task(void *param) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void master_StatusCallback(const esp_now_recv_info_t *esp_now_info,
|
||||||
|
const uint8_t *data, int data_len) {
|
||||||
|
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;
|
||||||
|
|
||||||
|
ESP_LOGI(TAG, "WILL REGISTER DEVICE");
|
||||||
|
esp_now_peer_info_t checkPeerInfo;
|
||||||
|
esp_err_t checkPeer =
|
||||||
|
esp_now_get_peer(esp_now_info->src_addr, &checkPeerInfo);
|
||||||
|
switch (checkPeer) {
|
||||||
|
case (ESP_OK):
|
||||||
|
ESP_LOGI(TAG, "CLIENT BEKANNT");
|
||||||
|
int id = get_client_id(esp_client_list, esp_now_info->src_addr);
|
||||||
|
esp_client_list->Clients[id].isAvailable = true;
|
||||||
|
esp_client_list->Clients[id].lastSuccessfullPing = xTaskGetTickCount();
|
||||||
|
ESP_LOGI(TAG, "Updated client %d last ping time to %lu", id,
|
||||||
|
esp_client_list->Clients[id].lastSuccessfullPing);
|
||||||
|
break;
|
||||||
|
case (ESP_ERR_ESPNOW_NOT_INIT):
|
||||||
|
ESP_LOGI(TAG, "Not initalised");
|
||||||
|
break;
|
||||||
|
case (ESP_ERR_ESPNOW_ARG):
|
||||||
|
ESP_LOGI(TAG, "ESP ERR ESPNOW_ARG");
|
||||||
|
break;
|
||||||
|
case (ESP_ERR_ESPNOW_NOT_FOUND):
|
||||||
|
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_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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 master_broadcastCallback(const esp_now_recv_info_t *esp_now_info,
|
||||||
|
const uint8_t *data, int data_len) {
|
||||||
|
ESP_LOGI(TAG,
|
||||||
|
"Master should not recieve Broadcast is there another master "
|
||||||
|
"Calling got message from " MACSTR,
|
||||||
|
MAC2STR(esp_now_info->src_addr));
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
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!");
|
||||||
|
add_peer(esp_now_info->src_addr);
|
||||||
|
replyMessage =
|
||||||
|
MessageBuilder(RegisterPage, *(PayloadUnion *)&message->payload,
|
||||||
|
sizeof(message->payload));
|
||||||
|
ESP_ERROR_CHECK(esp_now_send(esp_now_info->src_addr,
|
||||||
|
(uint8_t *)&replyMessage,
|
||||||
|
sizeof(BaseMessage)));
|
||||||
|
hasMaster = true;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ESP_LOGI(TAG, "Already have master wont register by the new one");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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,
|
void master_receive_callback(const esp_now_recv_info_t *esp_now_info,
|
||||||
const uint8_t *data, int data_len) {
|
const uint8_t *data, int data_len) {
|
||||||
ESP_LOGI(TAG, "MASTER GOT MESSAGE");
|
ESP_LOGI(TAG, "MASTER GOT MESSAGE");
|
||||||
|
|
||||||
BaseMessage replyMessage = {};
|
// Allokiere Speicher für die Daten und kopiere sie
|
||||||
const BaseMessage *message = (const BaseMessage *)data;
|
uint8_t *copied_data = (uint8_t *)malloc(data_len);
|
||||||
int id;
|
if (copied_data == NULL) {
|
||||||
switch (message->commandPage) {
|
ESP_LOGE(TAG, "Failed to allocate memory for message data.");
|
||||||
case StatusPage:
|
return;
|
||||||
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 =
|
|
||||||
esp_now_get_peer(esp_now_info->src_addr, &checkPeerInfo);
|
|
||||||
switch (checkPeer) {
|
|
||||||
case (ESP_OK):
|
|
||||||
ESP_LOGI(TAG, "CLIENT BEKANNT");
|
|
||||||
int id = get_client_id(esp_client_list, esp_now_info->src_addr);
|
|
||||||
esp_client_list->Clients[id].isAvailable = true;
|
|
||||||
esp_client_list->Clients[id].lastSuccessfullPing = xTaskGetTickCount();
|
|
||||||
ESP_LOGI(TAG, "Updated client %d last ping time to %lu", id,
|
|
||||||
esp_client_list->Clients[id].lastSuccessfullPing);
|
|
||||||
break;
|
|
||||||
case (ESP_ERR_ESPNOW_NOT_INIT):
|
|
||||||
ESP_LOGI(TAG, "Not initalised");
|
|
||||||
break;
|
|
||||||
case (ESP_ERR_ESPNOW_ARG):
|
|
||||||
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, "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)));
|
|
||||||
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
ESP_LOGI(TAG, "Unknown Message %i", checkPeer);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
ESP_LOGI(TAG, "Unknown CommandPage %i", message->commandPage);
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
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,
|
void client_receive_callback(const esp_now_recv_info_t *esp_now_info,
|
||||||
@@ -217,59 +426,26 @@ void client_receive_callback(const esp_now_recv_info_t *esp_now_info,
|
|||||||
ESP_LOGI(TAG, "SLAVE GOT MESSAGE");
|
ESP_LOGI(TAG, "SLAVE GOT MESSAGE");
|
||||||
ESP_LOGI(TAG, "Received message from: " MACSTR,
|
ESP_LOGI(TAG, "Received message from: " MACSTR,
|
||||||
MAC2STR(esp_now_info->src_addr));
|
MAC2STR(esp_now_info->src_addr));
|
||||||
ESP_LOGI(TAG, "Message: %.*s", data_len, data);
|
|
||||||
|
|
||||||
BaseMessage replyMessage = {};
|
uint8_t *copied_data = (uint8_t *)malloc(data_len);
|
||||||
|
if (copied_data == NULL) {
|
||||||
const BaseMessage *message = (const BaseMessage *)data;
|
ESP_LOGE(TAG, "Failed to allocate memory for message data.");
|
||||||
switch (message->commandPage) {
|
return;
|
||||||
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!");
|
|
||||||
add_peer(esp_now_info->src_addr);
|
|
||||||
replyMessage =
|
|
||||||
MessageBuilder(RegisterPage, *(PayloadUnion *)&message->payload,
|
|
||||||
sizeof(message->payload));
|
|
||||||
ESP_ERROR_CHECK(esp_now_send(esp_now_info->src_addr,
|
|
||||||
(uint8_t *)&replyMessage,
|
|
||||||
sizeof(BaseMessage)));
|
|
||||||
hasMaster = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case RegisterPage:
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
ESP_LOGI(TAG, "GOT UNKONW MESSAGE");
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
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) {
|
void client_data_sending_task(void *param) {
|
||||||
|
|||||||
@@ -28,16 +28,35 @@ static uint8_t broadcast_address[ESP_NOW_ETH_ALEN] = {0xFF, 0xFF, 0xFF,
|
|||||||
#define MESSAGE_QUEUE_SIZE 10
|
#define MESSAGE_QUEUE_SIZE 10
|
||||||
|
|
||||||
typedef enum {
|
typedef enum {
|
||||||
|
OTA_PREP_UPGRADE,
|
||||||
|
OTA_SEND_PAYLOAD,
|
||||||
|
OTA_WRITE_UPDATE_BUFFER,
|
||||||
|
OTA_SEND_MISSING,
|
||||||
|
OTA_UPDATE_INFO,
|
||||||
|
OTA_END_UPGRADE,
|
||||||
StatusPage,
|
StatusPage,
|
||||||
GetStatusPage,
|
GetStatusPage,
|
||||||
ConfigPage,
|
ConfigPage,
|
||||||
PingPage,
|
PingPage,
|
||||||
BroadCastPage,
|
BroadCastPage,
|
||||||
RegisterPage,
|
RegisterPage,
|
||||||
FirmwarePrepPage,
|
|
||||||
FirmwarePayloadPage,
|
|
||||||
} CommandPages;
|
} 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)) {
|
typedef struct __attribute__((packed)) {
|
||||||
uint16_t version; // software version
|
uint16_t version; // software version
|
||||||
uint8_t runningPartition;
|
uint8_t runningPartition;
|
||||||
@@ -97,6 +116,47 @@ typedef struct __attribute__((packed)) {
|
|||||||
static_assert(sizeof(BaseMessage) <= 255,
|
static_assert(sizeof(BaseMessage) <= 255,
|
||||||
"BaseMessage darf nicht größer als 255 sein");
|
"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 init_com(ClientList *clients, uint8_t wifi_channel);
|
||||||
int getNextFreeClientId();
|
int getNextFreeClientId();
|
||||||
int add_peer(uint8_t *macAddr);
|
int add_peer(uint8_t *macAddr);
|
||||||
|
|||||||
+17
-4
@@ -19,6 +19,7 @@
|
|||||||
|
|
||||||
#include "communication_handler.h"
|
#include "communication_handler.h"
|
||||||
#include "main.h"
|
#include "main.h"
|
||||||
|
#include "ota_update.h"
|
||||||
#include "uart_handler.h"
|
#include "uart_handler.h"
|
||||||
#include <stdbool.h>
|
#include <stdbool.h>
|
||||||
#include <stddef.h>
|
#include <stddef.h>
|
||||||
@@ -35,6 +36,7 @@ static uint8_t send_message_buffer[1024];
|
|||||||
static uint8_t send_message_payload_buffer[512];
|
static uint8_t send_message_payload_buffer[512];
|
||||||
|
|
||||||
static MessageBrokerTaskParams_t broker_task_params;
|
static MessageBrokerTaskParams_t broker_task_params;
|
||||||
|
static ESP_MessageBrokerTaskParams_t esp_broker_task_params;
|
||||||
|
|
||||||
ClientList clientList = {.Clients = {{0}}, .ClientCount = 0};
|
ClientList clientList = {.Clients = {{0}}, .ClientCount = 0};
|
||||||
|
|
||||||
@@ -73,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);
|
send_payload_buffer[1] = (uint8_t)((version >> 8) & 0xFF);
|
||||||
memcpy(&send_payload_buffer[2], &BUILD_GIT_HASH, git_build_hash_len);
|
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,
|
int len = build_message(UART_VERSION, send_payload_buffer, needed_buffer_size,
|
||||||
send_buffer, send_buffer_size);
|
send_buffer, send_buffer_size);
|
||||||
if (len < 0) {
|
if (len < 0) {
|
||||||
@@ -84,7 +84,7 @@ void versionCallback(uint8_t msgid, const uint8_t *payload, size_t payload_len,
|
|||||||
payload_len, send_buffer_size, len);
|
payload_len, send_buffer_size, len);
|
||||||
return;
|
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,
|
void clientInfoCallback(uint8_t msgid, const uint8_t *payload,
|
||||||
@@ -142,7 +142,7 @@ void clientInfoCallback(uint8_t msgid, const uint8_t *payload,
|
|||||||
int len = build_message(UART_CLIENT_INFO, send_payload_buffer,
|
int len = build_message(UART_CLIENT_INFO, send_payload_buffer,
|
||||||
needed_buffer_size, send_buffer, send_buffer_size);
|
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) {
|
if (len < 0) {
|
||||||
ESP_LOGE(TAG,
|
ESP_LOGE(TAG,
|
||||||
@@ -258,9 +258,19 @@ void app_main(void) {
|
|||||||
}
|
}
|
||||||
nvs_close(nt);
|
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
|
// Tasks starten basierend auf Master/Client
|
||||||
if (isMaster) {
|
if (isMaster) {
|
||||||
ESP_LOGI(TAG, "Started in Mastermode");
|
ESP_LOGI(TAG, "Started in Mastermode");
|
||||||
|
ESPNOW_RegisterMasterCallbacks();
|
||||||
|
|
||||||
add_peer(broadcast_address);
|
add_peer(broadcast_address);
|
||||||
xTaskCreate(master_broadcast_task, "MasterBroadcast", 4096, NULL, 1, NULL);
|
xTaskCreate(master_broadcast_task, "MasterBroadcast", 4096, NULL, 1, NULL);
|
||||||
// xTaskCreate(master_ping_task, "MasterPing", 4096, NULL, 1, NULL);
|
// xTaskCreate(master_ping_task, "MasterPing", 4096, NULL, 1, NULL);
|
||||||
@@ -289,11 +299,14 @@ void app_main(void) {
|
|||||||
RegisterCallback(0x02, versionCallback);
|
RegisterCallback(0x02, versionCallback);
|
||||||
RegisterCallback(0x03, clientInfoCallback);
|
RegisterCallback(0x03, clientInfoCallback);
|
||||||
|
|
||||||
|
init_ota();
|
||||||
|
|
||||||
// xTaskCreate(uart_status_task, "MasterUartStatusTask", 4096, NULL, 1,
|
// xTaskCreate(uart_status_task, "MasterUartStatusTask", 4096, NULL, 1,
|
||||||
// NULL); xTaskCreate(SendClientInfoTask, "SendCientInfo", 4096, NULL, 1,
|
// NULL); xTaskCreate(SendClientInfoTask, "SendCientInfo", 4096, NULL, 1,
|
||||||
// NULL);
|
// NULL);
|
||||||
} else {
|
} else {
|
||||||
ESP_LOGI(TAG, "Started in Slavemode");
|
ESP_LOGI(TAG, "Started in Slavemode");
|
||||||
|
ESPNOW_RegisterSlaveCallbacks();
|
||||||
// xTaskCreate(client_data_sending_task, "ClientDataSending", 4096, NULL, 1,
|
// xTaskCreate(client_data_sending_task, "ClientDataSending", 4096, NULL, 1,
|
||||||
// NULL);
|
// NULL);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,
|
int build_message(uint8_t msgid, const uint8_t *payload, size_t payload_len,
|
||||||
uint8_t *msg_buffer, size_t msg_buffer_size) {
|
uint8_t *msg_buffer, size_t msg_buffer_size) {
|
||||||
|
|
||||||
ESP_LOGE("BM", "payload_len %d, msg_buffer_size %d", payload_len + 4,
|
//ESP_LOGE("BM", "payload_len %d, msg_buffer_size %d", payload_len + 4,
|
||||||
msg_buffer_size);
|
// msg_buffer_size);
|
||||||
if (payload_len + 4 > msg_buffer_size) {
|
if (payload_len + 4 > msg_buffer_size) {
|
||||||
return PayloadBiggerThenBuffer;
|
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++] = checksum;
|
||||||
msg_buffer[write_index++] = EndByte;
|
msg_buffer[write_index++] = EndByte;
|
||||||
|
|
||||||
ESP_LOGE("BM", "MESSAGE FERTIG GEBAUT");
|
|
||||||
return write_index;
|
return write_index;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,8 +46,8 @@ void MessageBrokerTask(void *param) {
|
|||||||
|
|
||||||
while (1) {
|
while (1) {
|
||||||
if (xQueueReceive(msg_queue, &received_msg, portMAX_DELAY)) {
|
if (xQueueReceive(msg_queue, &received_msg, portMAX_DELAY)) {
|
||||||
ESP_LOGI(TAG, "Received message from queue: MSGID=0x%02X, Length=%u",
|
//ESP_LOGI(TAG, "Received message from queue: MSGID=0x%02X, Length=%u",
|
||||||
received_msg.msgid, received_msg.payload_len);
|
// received_msg.msgid, received_msg.payload_len);
|
||||||
|
|
||||||
for (int i = 0; i < mr.num_direct_callbacks; i++) {
|
for (int i = 0; i < mr.num_direct_callbacks; i++) {
|
||||||
if (mr.FunctionList[i].MSGID == received_msg.msgid) {
|
if (mr.FunctionList[i].MSGID == received_msg.msgid) {
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
#include <stddef.h>
|
#include <stddef.h>
|
||||||
#include <stdint.h>
|
#include <stdint.h>
|
||||||
|
|
||||||
#define MAX_MESSAGE_PAYLOAD_LENGTH 128
|
#define MAX_MESSAGE_PAYLOAD_LENGTH 512
|
||||||
#define MAX_TOTAL_CONTENT_LENGTH (MAX_MESSAGE_PAYLOAD_LENGTH + 1)
|
#define MAX_TOTAL_CONTENT_LENGTH (MAX_MESSAGE_PAYLOAD_LENGTH + 1)
|
||||||
|
|
||||||
enum ParserState {
|
enum ParserState {
|
||||||
@@ -33,7 +33,7 @@ struct MessageReceive {
|
|||||||
enum ParserError error;
|
enum ParserError error;
|
||||||
uint8_t messageid;
|
uint8_t messageid;
|
||||||
uint8_t message[MAX_MESSAGE_PAYLOAD_LENGTH];
|
uint8_t message[MAX_MESSAGE_PAYLOAD_LENGTH];
|
||||||
uint8_t index;
|
uint16_t index;
|
||||||
uint8_t checksum;
|
uint8_t checksum;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+176
-11
@@ -1,25 +1,87 @@
|
|||||||
#include "ota_update.h"
|
#include "ota_update.h"
|
||||||
|
#include "driver/uart.h"
|
||||||
|
#include "esp_err.h"
|
||||||
#include "esp_log.h"
|
#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 "message_handler.h"
|
||||||
|
#include "uart_handler.h"
|
||||||
|
#include "uart_msg_ids.h"
|
||||||
#include <stddef.h>
|
#include <stddef.h>
|
||||||
#include <stdint.h>
|
#include <stdint.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
|
|
||||||
static uint8_t updateBuffer[4000];
|
#define MAX(a, b) ((a) > (b) ? (a) : (b))
|
||||||
|
#define MIN(a, b) ((a) < (b) ? (a) : (b))
|
||||||
|
|
||||||
|
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 const char *TAG = "ALOX - OTA";
|
||||||
|
static esp_ota_handle_t update_handle;
|
||||||
|
|
||||||
|
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(
|
||||||
|
ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_ANY, partition_to_update);
|
||||||
|
|
||||||
|
// Check if the partition was found
|
||||||
|
if (update_partition == NULL) {
|
||||||
|
ESP_LOGE(TAG, "Failed to find OTA partition: %s", partition_to_update);
|
||||||
|
return -1; // Or handle the error appropriately
|
||||||
|
}
|
||||||
|
|
||||||
|
ESP_LOGI(TAG, "Gonna write OTA Update in Partition: %s",
|
||||||
|
update_partition->label);
|
||||||
|
|
||||||
|
esp_err_t err =
|
||||||
|
esp_ota_begin(update_partition, OTA_SIZE_UNKNOWN, &update_handle);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
ESP_LOGE(TAG, "esp_ota_begin failed (%s)", esp_err_to_name(err));
|
||||||
|
esp_ota_abort(update_handle);
|
||||||
|
return -2;
|
||||||
|
}
|
||||||
|
|
||||||
|
ESP_LOGI(TAG, "OTA update started successfully.");
|
||||||
|
return part;
|
||||||
|
}
|
||||||
|
|
||||||
void start_uart_update(uint8_t msgid, const uint8_t *payload,
|
void start_uart_update(uint8_t msgid, const uint8_t *payload,
|
||||||
size_t payload_len, uint8_t *send_payload_buffer,
|
size_t payload_len, uint8_t *send_payload_buffer,
|
||||||
size_t send_payload_buffer_size, uint8_t *send_buffer,
|
size_t send_payload_buffer_size, uint8_t *send_buffer,
|
||||||
size_t send_buffer_size) {
|
size_t send_buffer_size) {
|
||||||
ESP_LOGI(TAG, "OTA Update Uart Command");
|
ESP_LOGI(TAG, "OTA Update Start Uart Command");
|
||||||
|
|
||||||
// prepare for writing new partition with ota api
|
vTaskPrioritySet(NULL, 2);
|
||||||
// will get 200 bytes each uart message
|
|
||||||
// fill update buffer
|
|
||||||
// write update buffer complete
|
|
||||||
|
|
||||||
/*int len = build_message(0x02, send_payload_buffer, needed_buffer_size,
|
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;
|
||||||
|
int len = build_message(UART_OTA_START, send_payload_buffer, send_payload_len,
|
||||||
send_buffer, send_buffer_size);
|
send_buffer, send_buffer_size);
|
||||||
if (len < 0) {
|
if (len < 0) {
|
||||||
ESP_LOGE(TAG,
|
ESP_LOGE(TAG,
|
||||||
@@ -28,23 +90,126 @@ void start_uart_update(uint8_t msgid, const uint8_t *payload,
|
|||||||
payload_len, send_buffer_size, len);
|
payload_len, send_buffer_size, len);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
uart_write_bytes(MASTER_UART, send_buffer, len - 1);*/
|
|
||||||
|
uart_write_bytes(MASTER_UART, send_buffer, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
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,
|
void payload_uart_update(uint8_t msgid, const uint8_t *payload,
|
||||||
size_t payload_len, uint8_t *send_payload_buffer,
|
size_t payload_len, uint8_t *send_payload_buffer,
|
||||||
size_t send_payload_buffer_size, uint8_t *send_buffer,
|
size_t send_payload_buffer_size, uint8_t *send_buffer,
|
||||||
size_t send_buffer_size) {
|
size_t send_buffer_size) {
|
||||||
ESP_LOGI(TAG, "OTA Update Uart Command");
|
// 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);
|
||||||
|
if (len < 0) {
|
||||||
|
ESP_LOGE(TAG,
|
||||||
|
"Error Building UART Message: payload_len, %d, sendbuffer_size: "
|
||||||
|
"%d, mes_len(error): %d",
|
||||||
|
payload_len, send_buffer_size, len);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
void end_uart_update(uint8_t msgid, const uint8_t *payload, size_t payload_len,
|
||||||
uint8_t *send_payload_buffer,
|
uint8_t *send_payload_buffer,
|
||||||
size_t send_payload_buffer_size, uint8_t *send_buffer,
|
size_t send_payload_buffer_size, uint8_t *send_buffer,
|
||||||
size_t send_buffer_size) {
|
size_t send_buffer_size) {
|
||||||
ESP_LOGI(TAG, "OTA Update Uart Command");
|
ESP_LOGI(TAG, "OTA Update End Uart Command");
|
||||||
|
|
||||||
|
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) {
|
||||||
|
ESP_LOGE(TAG,
|
||||||
|
"Error Building UART Message: payload_len, %d, sendbuffer_size: "
|
||||||
|
"%d, mes_len(error): %d",
|
||||||
|
payload_len, send_buffer_size, len);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
uart_write_bytes(MASTER_UART, send_buffer, len);
|
||||||
|
|
||||||
|
vTaskPrioritySet(NULL, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void write_ota_update_from_uart_task(void *param) {}
|
||||||
|
|
||||||
void init_ota() {
|
void init_ota() {
|
||||||
RegisterCallback(uint8_t msgid, RegisterFunctionCallback callback);
|
RegisterCallback(UART_OTA_START, start_uart_update);
|
||||||
|
RegisterCallback(UART_OTA_PAYLOAD, payload_uart_update);
|
||||||
|
RegisterCallback(UART_OTA_END, end_uart_update);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,25 @@
|
|||||||
#ifndef OTA_UPDATE_H
|
#ifndef OTA_UPDATE_H
|
||||||
#define 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)
|
||||||
|
|
||||||
|
void init_ota();
|
||||||
|
|
||||||
|
enum OTA_UPDATE_STATES {
|
||||||
|
IDEL,
|
||||||
|
START_REQUESTED,
|
||||||
|
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
|
#endif
|
||||||
|
|||||||
+3
-3
@@ -18,7 +18,7 @@ static const char *TAG = "ALOX - UART";
|
|||||||
static QueueHandle_t parsed_message_queue;
|
static QueueHandle_t parsed_message_queue;
|
||||||
|
|
||||||
void init_uart(QueueHandle_t msg_queue_handle) {
|
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,
|
.data_bits = UART_DATA_8_BITS,
|
||||||
.parity = UART_PARITY_DISABLE,
|
.parity = UART_PARITY_DISABLE,
|
||||||
.stop_bits = UART_STOP_BITS_1,
|
.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,
|
void HandleMessageReceivedCallback(uint8_t msgid, const uint8_t *payload,
|
||||||
size_t payload_len) {
|
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);
|
payload_len, payload);
|
||||||
ESP_LOG_BUFFER_HEX(TAG, payload, payload_len);
|
ESP_LOG_BUFFER_HEX(TAG, payload, payload_len);*/
|
||||||
|
|
||||||
ParsedMessage_t msg_to_send;
|
ParsedMessage_t msg_to_send;
|
||||||
msg_to_send.msgid = msgid;
|
msg_to_send.msgid = msgid;
|
||||||
|
|||||||
@@ -2,54 +2,123 @@
|
|||||||
|
|
||||||
## Struktur einer Nachricht
|
## Struktur einer Nachricht
|
||||||
|
|
||||||
0xAA = Startbyte
|
- Control Bytes:
|
||||||
checksum = XOR über alle Bytes (ohne Startbyte und Checksum-Byte)
|
- 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:
|
### Felder im Detail:
|
||||||
|
|
||||||
- **Length** (`uint8_t`):
|
- **Command** (`uint8_t`):
|
||||||
Gibt die Gesamtlänge der Nachricht **ab `CommandPage` bis einschließlich `Payload`** an.
|
Gibt an, welcher Nachrichtentyp gesendet wird.
|
||||||
|
|
||||||
- **CommandPage** (`uint8_t`):
|
|
||||||
Gibt an, welcher Nachrichtentyp oder Befehl gesendet wird.
|
|
||||||
|
|
||||||
- **Payload** (`variabel`):
|
- **Payload** (`variabel`):
|
||||||
Datenfeld mit variabler Länge, abhängig vom `CommandPage`.
|
Datenfeld mit variabler Länge, abhängig vom `Command`.
|
||||||
|
|
||||||
- **Checksum** (`uint8_t`):
|
- **Checksum** (`uint8_t`):
|
||||||
XOR über alle Bytes ab `Length` bis einschließlich `Payload`.
|
XOR über aller Bytes von `Command` und `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:
|
|
||||||
|
|
||||||
|
|
||||||
|
### Messages
|
||||||
|
|
||||||
---
|
Command:
|
||||||
|
- UART_ECHO = 0x01
|
||||||
|
- UART_VERSION = 0x02
|
||||||
|
- UART_CLIENT_INFO = 0x03
|
||||||
|
|
||||||
# Roadmap
|
Grundlegend sind alle Zahlenwerte im LittleEndian format!
|
||||||
- [ ] SEND STATUS OF DEVICE OVER UART
|
|
||||||
- [ ] CONFIGURE PEERS OVER MASTER
|
#### UART_ECHO:
|
||||||
- [ ] SAVE PIN CONFIG ON PEERS
|
|
||||||
|
- 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
|
# Machbarkeits-Studie
|
||||||
|
|
||||||
|
|||||||
+2098
File diff suppressed because it is too large
Load Diff
+2357
File diff suppressed because it is too large
Load Diff
-248
@@ -1,248 +0,0 @@
|
|||||||
import queue # Zum sicheren Datenaustausch zwischen Threads
|
|
||||||
import serial
|
|
||||||
import time
|
|
||||||
import threading
|
|
||||||
import sys
|
|
||||||
from parser import UartMessageParser, ParserError
|
|
||||||
from message_builder import MessageBuilder, MessageBuilderError, PayloadTooLargeError, BufferOverflowError
|
|
||||||
import payload_parser
|
|
||||||
from rich.console import Console
|
|
||||||
from rich.table import Table
|
|
||||||
|
|
||||||
SERIAL_PORT = "/dev/ttyUSB0"
|
|
||||||
BAUDRATE = 115200
|
|
||||||
WRITE_TIMEOUT = 1.5
|
|
||||||
READ_TIMEOUT = 2.0
|
|
||||||
|
|
||||||
payload_parser = payload_parser.PayloadParser()
|
|
||||||
|
|
||||||
|
|
||||||
def on_message_received_from_uart(parsed_message):
|
|
||||||
print(f"[CALLBACK] Nachricht empfangen: MSGID=0x{
|
|
||||||
parsed_message.msgid:02X}, Length={parsed_message.payload_len}")
|
|
||||||
received_message_queue.put(parsed_message)
|
|
||||||
|
|
||||||
|
|
||||||
def on_message_fail_from_uart(error_message):
|
|
||||||
print(f"[CALLBACK] Fehler beim Parsen: {error_message}")
|
|
||||||
|
|
||||||
|
|
||||||
class ParsedMessage:
|
|
||||||
def __init__(self, msgid, payload_len):
|
|
||||||
self.msgid = msgid
|
|
||||||
self.payload_len = payload_len
|
|
||||||
|
|
||||||
|
|
||||||
received_message_queue = queue.Queue()
|
|
||||||
|
|
||||||
|
|
||||||
class SerialReader(threading.Thread):
|
|
||||||
# Ändere den Konstruktor, um eine bereits geöffnete serielle Instanz zu akzeptieren
|
|
||||||
def __init__(self, ser_instance, read_timeout, parser):
|
|
||||||
super().__init__()
|
|
||||||
# Speichere die übergebene serielle Instanz
|
|
||||||
self.ser = ser_instance
|
|
||||||
self.read_timeout = read_timeout
|
|
||||||
self.parser = parser
|
|
||||||
self.running = False
|
|
||||||
self.daemon = True # Thread beendet sich mit dem Hauptprogramm
|
|
||||||
|
|
||||||
def run(self):
|
|
||||||
# Überprüfe, ob die serielle Schnittstelle wirklich offen ist, bevor du beginnst
|
|
||||||
if not self.ser or not self.ser.is_open:
|
|
||||||
print(
|
|
||||||
f"[{self.name}] Fehler: Serielle Schnittstelle ist nicht geöffnet.")
|
|
||||||
return
|
|
||||||
|
|
||||||
print(f"[{self.name}] Lese-Thread gestartet. Überwache {self.ser.port}...")
|
|
||||||
self.ser.timeout = self.read_timeout # Setze den Timeout für byteweises Lesen
|
|
||||||
self.running = True
|
|
||||||
|
|
||||||
while self.running:
|
|
||||||
try:
|
|
||||||
byte = self.ser.read(1)
|
|
||||||
if byte:
|
|
||||||
self.parser.parse_byte(byte[0])
|
|
||||||
else:
|
|
||||||
pass # Timeout, kein Byte verfügbar, Thread läuft weiter
|
|
||||||
except serial.SerialException as e:
|
|
||||||
print(f"[{self.name}] Lesefehler: {e}")
|
|
||||||
self.running = False
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[{self.name}] Unerwarteter Fehler im Lese-Thread: {e}")
|
|
||||||
self.running = False
|
|
||||||
|
|
||||||
# Der Thread schließt den Port NICHT mehr, das ist Aufgabe des Hauptprogramms.
|
|
||||||
print(f"[{self.name}] Lese-Thread beendet.")
|
|
||||||
|
|
||||||
def stop(self):
|
|
||||||
self.running = False
|
|
||||||
print(f"[{self.name}] Lese-Thread wird beendet...")
|
|
||||||
|
|
||||||
|
|
||||||
def on_message_received_from_uart(message_id: int, payload: bytes, payload_length: int):
|
|
||||||
"""
|
|
||||||
Callback-Funktion, die aufgerufen wird, wenn der Parser eine vollständige,
|
|
||||||
gültige Nachricht empfangen hat.
|
|
||||||
"""
|
|
||||||
print(f"\n[MAIN] Nachricht erfolgreich empfangen! ID: 0x{
|
|
||||||
message_id:02X}")
|
|
||||||
print(f"[MAIN] Payload ({payload_length} Bytes): {
|
|
||||||
payload[:payload_length].hex().upper()}")
|
|
||||||
|
|
||||||
parsed_object = payload_parser.parse_payload(
|
|
||||||
message_id, payload[:payload_length])
|
|
||||||
|
|
||||||
if message_id == 0x04:
|
|
||||||
print(parsed_object)
|
|
||||||
table = Table(title="Clients")
|
|
||||||
columns = ["ClientId", "IsAvailable",
|
|
||||||
"IsSlotUsed", "MAC", "LastPing", "LastSuccesfullPing"]
|
|
||||||
|
|
||||||
rows = []
|
|
||||||
for x in parsed_object.clients:
|
|
||||||
mac_string = ':'.join(f'{byte:02x}' for byte in x.mac_address)
|
|
||||||
rows.append([str(x.client_id), str(x.is_available), str(x.is_slot_used), mac_string,
|
|
||||||
str(x.last_ping), str(x.last_successfull_ping)])
|
|
||||||
|
|
||||||
for column in columns:
|
|
||||||
table.add_column(column)
|
|
||||||
|
|
||||||
for row in rows:
|
|
||||||
table.add_row(*row, style='bright_green')
|
|
||||||
|
|
||||||
console = Console()
|
|
||||||
console.print(table)
|
|
||||||
|
|
||||||
|
|
||||||
def on_message_fail_from_uart(message_id: int, current_message_buffer: bytes,
|
|
||||||
current_index: int, error_type: ParserError):
|
|
||||||
"""
|
|
||||||
Callback-Funktion, die aufgerufen wird, wenn der Parser einen Fehler
|
|
||||||
beim Empfang einer Nachricht feststellt.
|
|
||||||
"""
|
|
||||||
print(f"\n[MAIN] Fehler beim Parsen der Nachricht! ID: 0x{
|
|
||||||
message_id:02X}")
|
|
||||||
print(f"[MAIN] Fehler: {error_type.name}")
|
|
||||||
print(f"[MAIN] Bisheriger Puffer ({current_index} Bytes): {
|
|
||||||
current_message_buffer[:current_index].hex().upper()}")
|
|
||||||
|
|
||||||
|
|
||||||
def run_uart_test():
|
|
||||||
"""
|
|
||||||
Führt den UART-Test durch: Sendet eine Nachricht und liest alle Antworten.
|
|
||||||
"""
|
|
||||||
ser = None
|
|
||||||
|
|
||||||
parser = UartMessageParser(
|
|
||||||
on_message_received_callback=on_message_received_from_uart,
|
|
||||||
on_message_fail_callback=on_message_fail_from_uart
|
|
||||||
)
|
|
||||||
message_builder = MessageBuilder()
|
|
||||||
|
|
||||||
try:
|
|
||||||
ser = serial.Serial(
|
|
||||||
port=SERIAL_PORT,
|
|
||||||
baudrate=BAUDRATE,
|
|
||||||
timeout=READ_TIMEOUT,
|
|
||||||
write_timeout=WRITE_TIMEOUT
|
|
||||||
)
|
|
||||||
print(f"Serielle Schnittstelle {
|
|
||||||
SERIAL_PORT} mit Baudrate {BAUDRATE} geöffnet.")
|
|
||||||
|
|
||||||
reader_thread = SerialReader(
|
|
||||||
ser_instance=ser,
|
|
||||||
read_timeout=10,
|
|
||||||
parser=parser
|
|
||||||
)
|
|
||||||
reader_thread.start() # Starte den Lese-Thread
|
|
||||||
|
|
||||||
while not reader_thread.running:
|
|
||||||
time.sleep(0.1)
|
|
||||||
|
|
||||||
print("\n--- UART Testkonsole ---")
|
|
||||||
print("Gib eine Zahl (1-10) ein, um eine Nachricht zu senden.")
|
|
||||||
print("Gib 'q' oder 'exit' ein, um das Programm zu beenden.")
|
|
||||||
|
|
||||||
while True:
|
|
||||||
# Warte auf Benutzereingabe
|
|
||||||
user_input = sys.stdin.readline().strip().lower()
|
|
||||||
|
|
||||||
if user_input in ('q', 'exit'):
|
|
||||||
break
|
|
||||||
|
|
||||||
try:
|
|
||||||
choice = int(user_input)
|
|
||||||
if choice in MESSAGES:
|
|
||||||
msg_info = MESSAGES[choice]
|
|
||||||
print(f"\n[MAIN] Sende Nachricht für Option {
|
|
||||||
choice} (MSGID: 0x{msg_info['msg_id']:02X})...")
|
|
||||||
try:
|
|
||||||
message_to_send = message_builder.build_message(
|
|
||||||
msg_info["msg_id"],
|
|
||||||
msg_info["payload"],
|
|
||||||
255 # Max Payload Length
|
|
||||||
)
|
|
||||||
print(f"[MAIN] Gebaute Nachricht zum Senden: {
|
|
||||||
message_to_send.hex().upper()}")
|
|
||||||
bytes_written = ser.write(message_to_send)
|
|
||||||
print(f"[MAIN] {bytes_written} Bytes gesendet.")
|
|
||||||
except (PayloadTooLargeError, BufferOverflowError) as e:
|
|
||||||
print(f"[MAIN] Fehler beim Bauen der Nachricht: {e}")
|
|
||||||
except Exception as e:
|
|
||||||
print(
|
|
||||||
f"[MAIN] Ein unerwarteter Fehler beim Senden der Nachricht ist aufgetreten: {e}")
|
|
||||||
else:
|
|
||||||
print(
|
|
||||||
"Ungültige Option. Bitte gib eine Zahl zwischen 1 und 10 ein.")
|
|
||||||
except ValueError:
|
|
||||||
print("Ungültige Eingabe. Bitte gib eine Zahl oder 'q' ein.")
|
|
||||||
except Exception as e:
|
|
||||||
print(
|
|
||||||
f"[MAIN] Ein unerwarteter Fehler bei der Eingabeverarbeitung ist aufgetreten: {e}")
|
|
||||||
|
|
||||||
# Verarbeite empfangene Nachrichten, die sich in der Queue angesammelt haben
|
|
||||||
while not received_message_queue.empty():
|
|
||||||
msg = received_message_queue.get()
|
|
||||||
print(
|
|
||||||
f" > [MAIN-Loop] Verarbeitet: MSGID=0x{msg.msgid:02X}, Length={msg.payload_len}")
|
|
||||||
received_message_queue.task_done()
|
|
||||||
|
|
||||||
except serial.SerialException as e:
|
|
||||||
print(f"Fehler beim Zugriff auf die serielle Schnittstelle: {e}")
|
|
||||||
print(f"Stelle sicher, dass '{
|
|
||||||
SERIAL_PORT}' der korrekte Port ist und nicht von einer anderen Anwendung verwendet wird.")
|
|
||||||
except KeyboardInterrupt:
|
|
||||||
print("\n[MAIN] Test durch Benutzer abgebrochen (Ctrl+C).")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"Ein unerwarteter Fehler im Hauptprogramm ist aufgetreten: {e}")
|
|
||||||
finally:
|
|
||||||
if 'reader_thread' in locals() and reader_thread.is_alive():
|
|
||||||
reader_thread.stop()
|
|
||||||
reader_thread.join(timeout=5)
|
|
||||||
if reader_thread.is_alive():
|
|
||||||
print(
|
|
||||||
"[MAIN] Warnung: Lese-Thread konnte nicht sauber beendet werden.")
|
|
||||||
if ser and ser.is_open:
|
|
||||||
ser.close()
|
|
||||||
print("Serielle Schnittstelle geschlossen.")
|
|
||||||
print("[MAIN] Programm beendet.")
|
|
||||||
|
|
||||||
|
|
||||||
# Nachrichten-Mapping
|
|
||||||
MESSAGES = {
|
|
||||||
1: {"msg_id": 0x01, "payload": b"Echo Message 1"},
|
|
||||||
2: {"msg_id": 0x02, "payload": b"Version Request"},
|
|
||||||
3: {"msg_id": 0x03, "payload": b"Client Info Request"},
|
|
||||||
4: {"msg_id": 0x04, "payload": b"Custom Data 4"},
|
|
||||||
5: {"msg_id": 0x05, "payload": b"Custom Data 5"},
|
|
||||||
6: {"msg_id": 0x06, "payload": b"Custom Data 6"},
|
|
||||||
7: {"msg_id": 0x07, "payload": b"Custom Data 7"},
|
|
||||||
8: {"msg_id": 0x08, "payload": b"Custom Data 8"},
|
|
||||||
9: {"msg_id": 0x09, "payload": b"Custom Data 9"},
|
|
||||||
10: {"msg_id": 0x0A, "payload": b"Custom Data 10 - Last One!"},
|
|
||||||
}
|
|
||||||
|
|
||||||
# Führe den Test aus
|
|
||||||
if __name__ == "__main__":
|
|
||||||
run_uart_test()
|
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
import enum
|
|
||||||
|
|
||||||
START_BYTE = 0xAA
|
|
||||||
ESCAPE_BYTE = 0xBB
|
|
||||||
END_BYTE = 0xCC
|
|
||||||
|
|
||||||
|
|
||||||
class MessageBuilderError(Exception):
|
|
||||||
"""Basisklasse für Fehler des Message Builders."""
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class PayloadTooLargeError(MessageBuilderError):
|
|
||||||
"""Ausnahme, wenn der Payload zu groß für den Puffer ist."""
|
|
||||||
|
|
||||||
def __init__(self, required_size, buffer_size):
|
|
||||||
super().__init__(f"Payload ({
|
|
||||||
required_size} bytes) ist größer als der verfügbare Puffer ({buffer_size} bytes).")
|
|
||||||
self.required_size = required_size
|
|
||||||
self.buffer_size = buffer_size
|
|
||||||
|
|
||||||
|
|
||||||
class BufferOverflowError(MessageBuilderError):
|
|
||||||
"""Ausnahme, wenn der Puffer während des Bauens überläuft."""
|
|
||||||
|
|
||||||
def __init__(self, current_size, max_size, byte_to_add=None):
|
|
||||||
msg = f"Pufferüberlauf: Aktuelle Größe {
|
|
||||||
current_size}, Max. Größe {max_size}."
|
|
||||||
if byte_to_add is not None:
|
|
||||||
msg += f" Versuch, Byte 0x{byte_to_add:02X} hinzuzufügen."
|
|
||||||
super().__init__(msg)
|
|
||||||
self.current_size = current_size
|
|
||||||
self.max_size = max_size
|
|
||||||
self.byte_to_add = byte_to_add
|
|
||||||
|
|
||||||
|
|
||||||
class MessageBuilder:
|
|
||||||
"""
|
|
||||||
Klasse zum Aufbau von UART-Nachrichten gemäß dem definierten Protokoll,
|
|
||||||
inklusive Stuffing und Checksummenberechnung.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def _needs_stuffing_byte(self, byte: int) -> bool:
|
|
||||||
"""
|
|
||||||
Prüft, ob ein Byte ein Stuffing-Byte benötigt (d.h. ob es ein Steuerbyte ist).
|
|
||||||
"""
|
|
||||||
return (byte == START_BYTE or byte == ESCAPE_BYTE or byte == END_BYTE)
|
|
||||||
|
|
||||||
def _add_byte_with_length_check(self, byte: int, buffer: bytearray, max_length: int):
|
|
||||||
"""
|
|
||||||
Fügt ein Byte zum Puffer hinzu und prüft auf Pufferüberlauf.
|
|
||||||
Löst BufferOverflowError aus, wenn der Puffer voll ist.
|
|
||||||
"""
|
|
||||||
if len(buffer) >= max_length:
|
|
||||||
raise BufferOverflowError(len(buffer), max_length, byte)
|
|
||||||
buffer.append(byte)
|
|
||||||
|
|
||||||
def build_message(self, msgid: int, payload: bytes, msg_buffer_size: int) -> bytes:
|
|
||||||
"""
|
|
||||||
Baut eine vollständige UART-Nachricht.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
msgid (int): Die Message ID (0-255).
|
|
||||||
payload (bytes): Die Nutzdaten der Nachricht als Byte-Objekt.
|
|
||||||
msg_buffer_size (int): Die maximale Größe des Ausgabepuffers.
|
|
||||||
Dies ist die maximale Länge der *fertigen* Nachricht.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
bytes: Die fertig aufgebaute Nachricht als Byte-Objekt.
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
PayloadTooLargeError: Wenn der Payload (mit Overhead) den Puffer überschreiten würde.
|
|
||||||
BufferOverflowError: Wenn während des Bauens ein Pufferüberlauf auftritt.
|
|
||||||
"""
|
|
||||||
|
|
||||||
if len(payload) + 4 > msg_buffer_size:
|
|
||||||
raise PayloadTooLargeError(len(payload) + 4, msg_buffer_size)
|
|
||||||
|
|
||||||
checksum = 0
|
|
||||||
msg_buffer = bytearray()
|
|
||||||
|
|
||||||
# 1. StartByte hinzufügen
|
|
||||||
self._add_byte_with_length_check(
|
|
||||||
START_BYTE, msg_buffer, msg_buffer_size)
|
|
||||||
|
|
||||||
# 2. Message ID hinzufügen (mit Stuffing)
|
|
||||||
if self._needs_stuffing_byte(msgid):
|
|
||||||
self._add_byte_with_length_check(
|
|
||||||
ESCAPE_BYTE, msg_buffer, msg_buffer_size)
|
|
||||||
self._add_byte_with_length_check(msgid, msg_buffer, msg_buffer_size)
|
|
||||||
checksum ^= msgid
|
|
||||||
|
|
||||||
# 3. Payload-Bytes hinzufügen (mit Stuffing)
|
|
||||||
for byte_val in payload:
|
|
||||||
if self._needs_stuffing_byte(byte_val):
|
|
||||||
self._add_byte_with_length_check(
|
|
||||||
ESCAPE_BYTE, msg_buffer, msg_buffer_size)
|
|
||||||
self._add_byte_with_length_check(
|
|
||||||
byte_val, msg_buffer, msg_buffer_size)
|
|
||||||
checksum ^= byte_val
|
|
||||||
|
|
||||||
# 4. Checksumme hinzufügen (mit Stuffing)
|
|
||||||
if self._needs_stuffing_byte(checksum):
|
|
||||||
self._add_byte_with_length_check(
|
|
||||||
ESCAPE_BYTE, msg_buffer, msg_buffer_size)
|
|
||||||
self._add_byte_with_length_check(checksum, msg_buffer, msg_buffer_size)
|
|
||||||
|
|
||||||
# 5. EndByte hinzufügen
|
|
||||||
self._add_byte_with_length_check(END_BYTE, msg_buffer, msg_buffer_size)
|
|
||||||
|
|
||||||
# Konvertiere bytearray zu unveränderlichem bytes-Objekt
|
|
||||||
return bytes(msg_buffer)
|
|
||||||
-170
@@ -1,170 +0,0 @@
|
|||||||
import enum
|
|
||||||
|
|
||||||
# --- Konstanten für das UART-Protokoll ---
|
|
||||||
# Diese Werte müssen mit denen auf deinem Embedded-System übereinstimmen
|
|
||||||
START_BYTE = 0xAA
|
|
||||||
END_BYTE = 0xCC
|
|
||||||
ESCAPE_BYTE = 0x7D # Beispielwert, bitte an dein Protokoll anpassen
|
|
||||||
|
|
||||||
MAX_PAYLOAD_LENGTH = 255 # Maximale Länge des Nachrichten-Payloads (ohne Message ID und Checksumme)
|
|
||||||
# MAX_TOTAL_CONTENT_LENGTH in C beinhaltet Message ID, Payload und Checksumme.
|
|
||||||
# Hier definieren wir MAX_PAYLOAD_LENGTH, da der Parser den Payload sammelt.
|
|
||||||
# Die Gesamtgröße des empfangenen Puffers (message + checksum) darf MAX_PAYLOAD_LENGTH + 1 nicht überschreiten,
|
|
||||||
# da die Checksumme als letztes Byte des Payloads behandelt wird.
|
|
||||||
|
|
||||||
# --- Enumerationen für Parser-Zustände und Fehler ---
|
|
||||||
class ParserState(enum.Enum):
|
|
||||||
WAITING_FOR_START_BYTE = 0
|
|
||||||
GET_MESSAGE_TYPE = 1
|
|
||||||
ESCAPED_MESSAGE_TYPE = 2
|
|
||||||
IN_PAYLOAD = 3
|
|
||||||
ESCAPE_PAYLOAD_BYTE = 4
|
|
||||||
|
|
||||||
class ParserError(enum.Enum):
|
|
||||||
NO_ERROR = 0
|
|
||||||
UNEXPECTED_COMMAND_BYTE = 1
|
|
||||||
WRONG_CHECKSUM = 2
|
|
||||||
MESSAGE_TOO_LONG = 3
|
|
||||||
|
|
||||||
class UartMessageParser:
|
|
||||||
"""
|
|
||||||
Ein State-Machine-Parser für UART-Nachrichten basierend auf der bereitgestellten C-Logik.
|
|
||||||
|
|
||||||
Nachrichtenformat (angenommen):
|
|
||||||
[START_BYTE] [MESSAGE_ID] [PAYLOAD_BYTES...] [CHECKSUM_BYTE] [END_BYTE]
|
|
||||||
|
|
||||||
Escape-Sequenzen:
|
|
||||||
Wenn START_BYTE, END_BYTE oder ESCAPE_BYTE im MESSAGE_ID oder PAYLOAD vorkommen,
|
|
||||||
werden sie durch ESCAPE_BYTE gefolgt vom ursprünglichen Byte (nicht XORed) ersetzt.
|
|
||||||
Die Checksumme wird über die unescaped Bytes berechnet.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, on_message_received_callback=None, on_message_fail_callback=None):
|
|
||||||
"""
|
|
||||||
Initialisiert den UART-Nachrichten-Parser.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
on_message_received_callback (callable, optional): Eine Funktion, die aufgerufen wird,
|
|
||||||
wenn eine gültige Nachricht empfangen wurde.
|
|
||||||
Signatur: on_message_received(message_id: int, payload: bytes, payload_length: int)
|
|
||||||
on_message_fail_callback (callable, optional): Eine Funktion, die aufgerufen wird,
|
|
||||||
wenn ein Nachrichtenfehler auftritt.
|
|
||||||
Signatur: on_message_fail(message_id: int, current_message_buffer: bytes,
|
|
||||||
current_index: int, error_type: ParserError)
|
|
||||||
"""
|
|
||||||
self.state = ParserState.WAITING_FOR_START_BYTE
|
|
||||||
self.index = 0
|
|
||||||
self.checksum = 0
|
|
||||||
self.message_id = 0
|
|
||||||
self.message_buffer = bytearray(MAX_PAYLOAD_LENGTH + 1) # +1 für Checksummen-Byte
|
|
||||||
self.error = ParserError.NO_ERROR
|
|
||||||
|
|
||||||
# Callbacks für die Anwendung. Standardmäßig None oder einfache Print-Funktionen.
|
|
||||||
self.on_message_received = on_message_received_callback if on_message_received_callback else self._default_on_message_received
|
|
||||||
self.on_message_fail = on_message_fail_callback if on_message_fail_callback else self._default_on_message_fail
|
|
||||||
|
|
||||||
def _default_on_message_received(self, message_id, payload, payload_length):
|
|
||||||
"""Standard-Callback für empfangene Nachrichten, falls keiner angegeben ist."""
|
|
||||||
print(f"Parser: Nachricht empfangen! ID: 0x{message_id:02X}, "
|
|
||||||
f"Payload ({payload_length} Bytes): {payload[:payload_length].hex().upper()}")
|
|
||||||
|
|
||||||
def _default_on_message_fail(self, message_id, current_message_buffer, current_index, error_type):
|
|
||||||
"""Standard-Callback für Nachrichtenfehler, falls keiner angegeben ist."""
|
|
||||||
print(f"Parser: Fehler bei Nachricht! ID: 0x{message_id:02X}, "
|
|
||||||
f"Fehler: {error_type.name}, "
|
|
||||||
f"Bisheriger Puffer ({current_index} Bytes): {current_message_buffer[:current_index].hex().upper()}")
|
|
||||||
|
|
||||||
def parse_byte(self, pbyte: int):
|
|
||||||
"""
|
|
||||||
Verarbeitet ein einzelnes empfangenes Byte.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
pbyte (int): Das empfangene Byte (0-255).
|
|
||||||
"""
|
|
||||||
# Sicherstellen, dass pbyte ein Integer im Bereich 0-255 ist
|
|
||||||
if not isinstance(pbyte, int) or not (0 <= pbyte <= 255):
|
|
||||||
print(f"Parser: Ungültiges Byte empfangen: {pbyte}. Muss ein Integer von 0-255 sein.")
|
|
||||||
return
|
|
||||||
|
|
||||||
current_state = self.state # Für bessere Lesbarkeit
|
|
||||||
|
|
||||||
if current_state == ParserState.WAITING_FOR_START_BYTE:
|
|
||||||
if pbyte == START_BYTE:
|
|
||||||
self.index = 0
|
|
||||||
self.checksum = 0
|
|
||||||
self.message_id = 0 # Reset message_id
|
|
||||||
self.error = ParserError.NO_ERROR # Reset error
|
|
||||||
self.state = ParserState.GET_MESSAGE_TYPE
|
|
||||||
# Andernfalls ignorieren wir Bytes, bis ein Start-Byte gefunden wird
|
|
||||||
|
|
||||||
elif current_state == ParserState.ESCAPED_MESSAGE_TYPE:
|
|
||||||
self.message_id = pbyte
|
|
||||||
self.checksum ^= pbyte
|
|
||||||
self.state = ParserState.IN_PAYLOAD
|
|
||||||
|
|
||||||
elif current_state == ParserState.GET_MESSAGE_TYPE:
|
|
||||||
if pbyte == ESCAPE_BYTE:
|
|
||||||
self.state = ParserState.ESCAPED_MESSAGE_TYPE
|
|
||||||
return # Dieses Byte wurde als Escape-Sequenz verarbeitet, nicht zum Payload hinzufügen
|
|
||||||
if pbyte == START_BYTE or pbyte == END_BYTE:
|
|
||||||
self.state = ParserState.WAITING_FOR_START_BYTE
|
|
||||||
self.error = ParserError.UNEXPECTED_COMMAND_BYTE
|
|
||||||
self.on_message_fail(self.message_id, self.message_buffer, self.index, self.error)
|
|
||||||
return
|
|
||||||
self.message_id = pbyte
|
|
||||||
self.checksum ^= pbyte
|
|
||||||
self.state = ParserState.IN_PAYLOAD
|
|
||||||
|
|
||||||
elif current_state == ParserState.ESCAPE_PAYLOAD_BYTE:
|
|
||||||
# Das escapte Byte ist Teil des Payloads
|
|
||||||
if self.index < MAX_PAYLOAD_LENGTH + 1: # +1 für Checksummen-Byte
|
|
||||||
self.message_buffer[self.index] = pbyte
|
|
||||||
self.index += 1
|
|
||||||
self.checksum ^= pbyte
|
|
||||||
self.state = ParserState.IN_PAYLOAD
|
|
||||||
else:
|
|
||||||
self.state = ParserState.WAITING_FOR_START_BYTE
|
|
||||||
self.error = ParserError.MESSAGE_TOO_LONG
|
|
||||||
self.on_message_fail(self.message_id, self.message_buffer, self.index, self.error)
|
|
||||||
return
|
|
||||||
|
|
||||||
elif current_state == ParserState.IN_PAYLOAD:
|
|
||||||
if pbyte == ESCAPE_BYTE:
|
|
||||||
self.state = ParserState.ESCAPE_PAYLOAD_BYTE
|
|
||||||
return # Dieses Byte wurde als Escape-Sequenz verarbeitet
|
|
||||||
if pbyte == START_BYTE:
|
|
||||||
self.state = ParserState.WAITING_FOR_START_BYTE
|
|
||||||
self.error = ParserError.UNEXPECTED_COMMAND_BYTE
|
|
||||||
self.on_message_fail(self.message_id, self.message_buffer, self.index, self.error)
|
|
||||||
return
|
|
||||||
if pbyte == END_BYTE:
|
|
||||||
if self.checksum != 0x00:
|
|
||||||
# Checksummenfehler: Die Checksumme wurde bis zum End-Byte XORed.
|
|
||||||
# Wenn die empfangene Checksumme korrekt war, sollte das Ergebnis 0 sein.
|
|
||||||
self.state = ParserState.WAITING_FOR_START_BYTE
|
|
||||||
self.error = ParserError.WRONG_CHECKSUM
|
|
||||||
self.on_message_fail(self.message_id, self.message_buffer, self.index, self.error)
|
|
||||||
return
|
|
||||||
|
|
||||||
# Erfolgreich empfangen! Die Checksumme ist das letzte Byte im Puffer.
|
|
||||||
# Die Länge des Payloads ist index - 1 (da das letzte Byte die Checksumme war).
|
|
||||||
payload_length = self.index - 1
|
|
||||||
if payload_length < 0: # Falls nur Message ID und Checksumme, aber kein Payload
|
|
||||||
payload_length = 0
|
|
||||||
|
|
||||||
self.on_message_received(self.message_id, self.message_buffer, payload_length)
|
|
||||||
self.state = ParserState.WAITING_FOR_START_BYTE
|
|
||||||
return # EndByte wurde verarbeitet, nicht zum Payload hinzufügen
|
|
||||||
|
|
||||||
# Normales Payload-Byte
|
|
||||||
if self.index < MAX_PAYLOAD_LENGTH + 1: # +1 für Checksummen-Byte
|
|
||||||
self.message_buffer[self.index] = pbyte
|
|
||||||
self.index += 1
|
|
||||||
self.checksum ^= pbyte
|
|
||||||
else:
|
|
||||||
# Nachricht zu lang
|
|
||||||
self.state = ParserState.WAITING_FOR_START_BYTE
|
|
||||||
self.error = ParserError.MESSAGE_TOO_LONG
|
|
||||||
self.on_message_fail(self.message_id, self.message_buffer, self.index, self.error)
|
|
||||||
return
|
|
||||||
|
|
||||||
@@ -1,192 +0,0 @@
|
|||||||
import dataclasses
|
|
||||||
import struct
|
|
||||||
from typing import Optional, Union, List
|
|
||||||
|
|
||||||
|
|
||||||
@dataclasses.dataclass
|
|
||||||
class StatusMessage:
|
|
||||||
"""
|
|
||||||
Repräsentiert eine Status-Nachricht (z.B. Message ID 0x01).
|
|
||||||
Payload-Format: [status_code: uint8], [battery_level: uint8], [uptime_seconds: uint16]
|
|
||||||
"""
|
|
||||||
status_code: int
|
|
||||||
battery_level: int # 0-100%
|
|
||||||
uptime_seconds: int
|
|
||||||
|
|
||||||
|
|
||||||
@dataclasses.dataclass
|
|
||||||
class SensorDataMessage:
|
|
||||||
"""
|
|
||||||
Repräsentiert eine Sensor-Daten-Nachricht (z.B. Message ID 0x02).
|
|
||||||
Payload-Format: [temperature_celsius: int16], [humidity_percent: uint16]
|
|
||||||
"""
|
|
||||||
temperature_celsius: int # signed short
|
|
||||||
humidity_percent: int # unsigned short
|
|
||||||
|
|
||||||
|
|
||||||
@dataclasses.dataclass
|
|
||||||
class ClientEntry:
|
|
||||||
"""
|
|
||||||
Repräsentiert die Informationen für einen einzelnen Client innerhalb der ClientInfoMessage.
|
|
||||||
Payload-Format:
|
|
||||||
[client_id: uint8]
|
|
||||||
[is_available: uint8] (0=false, >0=true)
|
|
||||||
[is_slot_used: uint8] (0=false, >0=true)
|
|
||||||
[mac_address: bytes (6)]
|
|
||||||
[unoccupied_value_1: uint32]
|
|
||||||
[unoccupied_value_2: uint32]
|
|
||||||
Gesamt: 1 + 1 + 1 + 6 + 4 + 4 = 17 Bytes pro Eintrag.
|
|
||||||
"""
|
|
||||||
client_id: int
|
|
||||||
is_available: bool
|
|
||||||
is_slot_used: bool
|
|
||||||
mac_address: bytes # 6 Bytes MAC-Adresse
|
|
||||||
last_ping: int # 4 Bytes, unbelegt
|
|
||||||
last_successfull_ping: int # 4 Bytes, unbelegt
|
|
||||||
|
|
||||||
|
|
||||||
@dataclasses.dataclass
|
|
||||||
class ClientInfoMessage:
|
|
||||||
"""
|
|
||||||
Repräsentiert eine Nachricht mit Client-Informationen (Message ID 0x03).
|
|
||||||
Payload-Format:
|
|
||||||
[num_clients: uint8]
|
|
||||||
[client_entry_1: ClientEntry]
|
|
||||||
[client_entry_2: ClientEntry]
|
|
||||||
...
|
|
||||||
"""
|
|
||||||
num_clients: int
|
|
||||||
clients: List[ClientEntry]
|
|
||||||
|
|
||||||
|
|
||||||
@dataclasses.dataclass
|
|
||||||
class UnknownMessage:
|
|
||||||
"""
|
|
||||||
Repräsentiert eine Nachricht mit unbekannter ID oder fehlerhaftem Payload.
|
|
||||||
"""
|
|
||||||
message_id: int
|
|
||||||
raw_payload: bytes
|
|
||||||
error_message: str
|
|
||||||
|
|
||||||
# --- Payload Parser Klasse ---
|
|
||||||
|
|
||||||
|
|
||||||
class PayloadParser:
|
|
||||||
"""
|
|
||||||
Interpretiert den Payload einer UART-Nachricht basierend auf ihrer Message ID
|
|
||||||
und wandelt ihn in ein strukturiertes Python-Objekt (dataclass) um.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
# Ein Dictionary, das Message IDs auf ihre entsprechenden Parsing-Funktionen abbildet.
|
|
||||||
self._parser_map = {
|
|
||||||
0x01: self._parse_status_message,
|
|
||||||
0x02: self._parse_sensor_data_message,
|
|
||||||
# Aktualisiert für die neue 0x03 Struktur
|
|
||||||
0x03: self._parse_client_info_message,
|
|
||||||
0x04: self._parse_client_info_message,
|
|
||||||
# Füge hier weitere Message IDs und ihre Parsing-Funktionen hinzu
|
|
||||||
}
|
|
||||||
|
|
||||||
def _parse_status_message(self, payload: bytes) -> Union[StatusMessage, UnknownMessage]:
|
|
||||||
"""Parsen des Payloads für Message ID 0x01 (StatusMessage)."""
|
|
||||||
# Erwartetes Format: 1 Byte Status, 1 Byte Battery, 2 Bytes Uptime (Little-Endian)
|
|
||||||
if len(payload) != 4:
|
|
||||||
return UnknownMessage(0x01, payload, f"Falsche Payload-Länge für StatusMessage: Erwartet 4, Got {len(payload)}")
|
|
||||||
try:
|
|
||||||
# '<BBH' bedeutet: Little-Endian, Byte (unsigned char), Byte (unsigned char), Half-word (unsigned short)
|
|
||||||
status_code, battery_level, uptime_seconds = struct.unpack(
|
|
||||||
'<BBH', payload)
|
|
||||||
return StatusMessage(status_code, battery_level, uptime_seconds)
|
|
||||||
except struct.error as e:
|
|
||||||
return UnknownMessage(0x01, payload, f"Fehler beim Entpacken der StatusMessage: {e}")
|
|
||||||
|
|
||||||
def _parse_sensor_data_message(self, payload: bytes) -> Union[SensorDataMessage, UnknownMessage]:
|
|
||||||
"""Parsen des Payloads für Message ID 0x02 (SensorDataMessage)."""
|
|
||||||
# Erwartetes Format: 2 Bytes Temperatur (signed short), 2 Bytes Feuchtigkeit (unsigned short) (Little-Endian)
|
|
||||||
if len(payload) != 4:
|
|
||||||
return UnknownMessage(0x02, payload, f"Falsche Payload-Länge für SensorDataMessage: Erwartet 4, Got {len(payload)}")
|
|
||||||
try:
|
|
||||||
# '<hH' bedeutet: Little-Endian, short (signed), unsigned short
|
|
||||||
temperature_celsius, humidity_percent = struct.unpack(
|
|
||||||
'<hH', payload)
|
|
||||||
return SensorDataMessage(temperature_celsius, humidity_percent)
|
|
||||||
except struct.error as e:
|
|
||||||
return UnknownMessage(0x02, payload, f"Fehler beim Entpacken der SensorDataMessage: {e}")
|
|
||||||
|
|
||||||
def _parse_client_info_message(self, payload: bytes) -> Union[ClientInfoMessage, UnknownMessage]:
|
|
||||||
"""Parsen des Payloads für Message ID 0x03 (ClientInfoMessage)."""
|
|
||||||
if not payload:
|
|
||||||
# Wenn der Payload leer ist, aber num_clients erwartet wird, ist das ein Fehler
|
|
||||||
return UnknownMessage(0x03, payload, "Payload für ClientInfoMessage ist leer, aber num_clients erwartet.")
|
|
||||||
|
|
||||||
try:
|
|
||||||
# Das erste Byte ist die Anzahl der Clients
|
|
||||||
num_clients = payload[0]
|
|
||||||
# Die restlichen Bytes sind die Client-Einträge
|
|
||||||
client_data_bytes = payload[1:]
|
|
||||||
|
|
||||||
# 1 (ID) + 1 (Avail) + 1 (Used) + 6 (MAC) + 4 (Val1) + 4 (Val2)
|
|
||||||
EXPECTED_CLIENT_ENTRY_SIZE = 17
|
|
||||||
|
|
||||||
if len(client_data_bytes) != num_clients * EXPECTED_CLIENT_ENTRY_SIZE:
|
|
||||||
return UnknownMessage(0x03, payload,
|
|
||||||
f"Falsche Payload-Länge für Client-Einträge: Erwartet {
|
|
||||||
num_clients * EXPECTED_CLIENT_ENTRY_SIZE}, "
|
|
||||||
f"Got {len(client_data_bytes)} nach num_clients.")
|
|
||||||
|
|
||||||
clients_list: List[ClientEntry] = []
|
|
||||||
# Formatstring für einen Client-Eintrag:
|
|
||||||
# < : Little-Endian
|
|
||||||
# B : uint8 (client_id, is_available, is_slot_used)
|
|
||||||
# 6s: 6 Bytes (mac_address)
|
|
||||||
# I : uint32 (unoccupied_value_1, unoccupied_value_2)
|
|
||||||
CLIENT_ENTRY_FORMAT = '<BBB6sII'
|
|
||||||
|
|
||||||
for i in range(num_clients):
|
|
||||||
start_index = i * EXPECTED_CLIENT_ENTRY_SIZE
|
|
||||||
end_index = start_index + EXPECTED_CLIENT_ENTRY_SIZE
|
|
||||||
entry_bytes = client_data_bytes[start_index:end_index]
|
|
||||||
|
|
||||||
# Entpacke die Daten für einen Client-Eintrag
|
|
||||||
client_id, is_available_byte, is_slot_used_byte, mac_address, val1, val2 = \
|
|
||||||
struct.unpack(CLIENT_ENTRY_FORMAT, entry_bytes)
|
|
||||||
|
|
||||||
# Konvertiere 0/1 Bytes zu boolschen Werten
|
|
||||||
is_available = bool(is_available_byte)
|
|
||||||
is_slot_used = bool(is_slot_used_byte)
|
|
||||||
|
|
||||||
clients_list.append(ClientEntry(
|
|
||||||
client_id=client_id,
|
|
||||||
is_available=is_available,
|
|
||||||
is_slot_used=is_slot_used,
|
|
||||||
mac_address=mac_address,
|
|
||||||
last_ping=val1,
|
|
||||||
last_successfull_ping=val2
|
|
||||||
))
|
|
||||||
|
|
||||||
return ClientInfoMessage(num_clients=num_clients, clients=clients_list)
|
|
||||||
|
|
||||||
except struct.error as e:
|
|
||||||
return UnknownMessage(0x03, payload, f"Fehler beim Entpacken der ClientInfoMessage-Einträge: {e}")
|
|
||||||
except Exception as e:
|
|
||||||
return UnknownMessage(0x03, payload, f"Unerwarteter Fehler beim Parsen der ClientInfoMessage: {e}")
|
|
||||||
|
|
||||||
def parse_payload(self, message_id: int, payload: bytes) -> Union[StatusMessage, SensorDataMessage, ClientInfoMessage, UnknownMessage]:
|
|
||||||
"""
|
|
||||||
Interpretiert den gegebenen Payload basierend auf der Message ID.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
message_id (int): Die ID der Nachricht.
|
|
||||||
payload (bytes): Die rohen Nutzdaten der Nachricht.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Union[StatusMessage, SensorDataMessage, ClientInfoMessage, UnknownMessage]:
|
|
||||||
Ein dataclass-Objekt, das die dekodierten Daten repräsentiert,
|
|
||||||
oder ein UnknownMessage-Objekt bei unbekannter ID oder Parsing-Fehler.
|
|
||||||
"""
|
|
||||||
parser_func = self._parser_map.get(message_id)
|
|
||||||
if parser_func:
|
|
||||||
return parser_func(payload)
|
|
||||||
else:
|
|
||||||
return UnknownMessage(message_id, payload, "Unbekannte Message ID.")
|
|
||||||
Reference in New Issue
Block a user