rmt + some of link layer

This commit is contained in:
Justin Chow
2025-07-06 00:28:01 -04:00
committed by Johnathon Slightham
parent e87abf9eef
commit 707e10f89b
18 changed files with 2555 additions and 169 deletions

View File

@@ -1,3 +1,40 @@
idf_component_register(SRCS "main.cpp"
PRIV_REQUIRES spi_flash nvs_flash esp_event rpc constants config
PRIV_REQUIRES spi_flash nvs_flash esp_event rpc constants config rmt esp_driver_gptimer dataLink
INCLUDE_DIRS "")
if(DEFINED BOARD_NAME AND BOARD_NAME)
message(STATUS "Building for board name: " ${BOARD_NAME})
idf_build_set_property(COMPILE_DEFINITIONS BOARD_${BOARD_NAME} APPEND)
endif()
if(DEFINED TIME_TEST AND TIME_TEST)
message(STATUS "Building with TIME_TEST: " ${TIME_TEST})
idf_build_set_property(COMPILE_DEFINITIONS TIME_TEST APPEND)
endif()
if(DEFINED MANCHESTER_40 AND MANCHESTER_40)
message(STATUS "Building with MANCHESTER_40: " ${MANCHESTER_40})
idf_build_set_property(COMPILE_DEFINITIONS MANCHESTER_40 APPEND)
endif()
if(DEFINED NRZ_INVERTED AND NRZ_INVERTED)
message(STATUS "Building with NRZ_INVERTED: " ${NRZ_INVERTED})
idf_build_set_property(COMPILE_DEFINITIONS NRZ_INVERTED APPEND)
endif()
if(DEFINED NRZ_INVERTED_10 AND NRZ_INVERTED_10)
message(STATUS "Building with NRZ_INVERTED_10: " ${NRZ_INVERTED_10})
idf_build_set_property(COMPILE_DEFINITIONS NRZ_INVERTED_10 APPEND)
endif()
if(DEFINED NRZ_INVERTED_20 AND NRZ_INVERTED_20)
message(STATUS "Building with NRZ_INVERTED_20: " ${NRZ_INVERTED_20})
idf_build_set_property(COMPILE_DEFINITIONS NRZ_INVERTED_20 APPEND)
endif()
if(DEFINED NRZ_INVERTED_2 AND NRZ_INVERTED_2)
message(STATUS "Building with NRZ_INVERTED_2: " ${NRZ_INVERTED_2})
idf_build_set_property(COMPILE_DEFINITIONS NRZ_INVERTED_2 APPEND)
endif()
if(DEFINED NRZ_INVERTED_40_HZ AND NRZ_INVERTED_40_HZ)
message(STATUS "Building with NRZ_INVERTED_40_HZ: " ${NRZ_INVERTED_40_HZ})
idf_build_set_property(COMPILE_DEFINITIONS NRZ_INVERTED_40_HZ APPEND)
endif()
if(DEFINED VERIFY_RECEIVE AND VERIFY_RECEIVE)
message(STATUS "Building with VERIFY_RECEIVE: " ${VERIFY_RECEIVE})
idf_build_set_property(COMPILE_DEFINITIONS VERIFY_RECEIVE APPEND)
endif()

5
main/README.md Normal file
View File

@@ -0,0 +1,5 @@
# RMT Sample Code
WIP
Creates 2 threads per channel (there are 4 channels - 4 TX and 4 RX). Each tx thread is sending messages and the corresponding rx thread will receive the message and print its contents if it is a valid frame.

256
main/link_layer_main.cpp Normal file
View File

@@ -0,0 +1,256 @@
//Used for link layer testing (change name to main.cpp to use)
#include <cstdio>
#include <memory>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_flash.h"
#include "nvs_flash.h"
#include "RMTManager.h"
#include "DataLinkManager.h"
#include <esp_netif.h>
#include <esp_event.h>
#include <freertos/semphr.h>
#include "driver/gptimer.h"
#include "esp_log.h"
struct TaskArgs{
DataLinkManager* link_layer_obj;
uint8_t task_id;
uint8_t receiver_id;
QueueHandle_t receive_queue;
};
struct ReceviedFrame{
uint8_t buf[MAX_CONTROL_DATA_LEN + CONTROL_FRAME_OVERHEAD]; //max 41B
size_t len;
};
void receive_frames(void* arg){
TaskArgs* args = (TaskArgs*)arg;
DataLinkManager* obj = args->link_layer_obj;
if (obj == nullptr){
ESP_LOGE("thread", "bad pointer\n");
vTaskDelete(NULL); //should never get here
}
QueueHandle_t shared_queue = (QueueHandle_t)args->receive_queue;
uint8_t curr_channel = args-> task_id;
printf("RX JOB for task %d starting...\n", curr_channel);
esp_err_t res;
uint8_t recv_buf[256];
memset(recv_buf, 0, 256);
size_t recv_len = 0;
ReceviedFrame recv_frame = {};
while(true){
res = obj->start_receive_frames(curr_channel); // this will be moved to a separate thread with a shared queue
if (res != ESP_OK){
ESP_LOGE("thread", "Failed to start rx async job on thread %d", curr_channel);
continue;
}
res = obj->receive(recv_buf, sizeof(recv_buf), &recv_len, curr_channel);
if (res != ESP_OK){
ESP_LOGE("thread", "Failed to receive message on thread %d", curr_channel);
continue;
} else {
// printf("Successfully receive message\n");
}
if (recv_len == 0){
continue;
}
recv_frame.len = recv_len;
memcpy((void*)recv_frame.buf, (void*)recv_buf, recv_len);
if (xQueueSendToBack(shared_queue, (void*)&recv_frame, (TickType_t) 10) != pdPASS){
ESP_LOGE("RX Job", "Failed to push received frame onto shared queue for channel %d", curr_channel);
}
}
}
void multi_transceiver(void* arg) {
TaskArgs* args = (TaskArgs*)arg;
DataLinkManager* obj = args->link_layer_obj;
if (obj == nullptr){
ESP_LOGE("thread", "bad pointer\n");
vTaskDelete(NULL); //should never get here
}
xTaskCreate(receive_frames, "receive_frame_job", 4096, arg, 5, NULL);
uint8_t dest_board_id = args->receiver_id; //using a dummy number for now - there is no board with id 2 right now
const char* message = "THIS IS A TEXT MESSAGE";
uint8_t curr_channel = args->task_id;
QueueHandle_t shared_queue = (QueueHandle_t)args->receive_queue;
uint8_t send_buf[256];
uint8_t recv_buf[256];
memset(recv_buf, 0, 256);
memset(send_buf, 0, 256);
size_t recv_len = 0;
uint8_t iteration = 0;
esp_err_t res;
gptimer_handle_t gptimer = NULL;
gptimer_config_t timer_config = {
.clk_src = GPTIMER_CLK_SRC_DEFAULT,
.direction = GPTIMER_COUNT_UP,
.resolution_hz = 1 * 1000 * 1000, // 1MHz, 1 tick = 1us
};
ESP_ERROR_CHECK(gptimer_new_timer(&timer_config, &gptimer));
ESP_ERROR_CHECK(gptimer_enable(gptimer));
ESP_ERROR_CHECK(gptimer_start(gptimer));
uint64_t start_count = 0, end_count = 0;
uint32_t num_incorrect = 0;
uint32_t total_transactions = 0;
ReceviedFrame recv_frame = {};
printf("task %d starting...\n", curr_channel);
while(true){
vTaskDelay(1000 / portTICK_PERIOD_MS); // wait 1 second before trying to send again
snprintf(reinterpret_cast<char*>(send_buf), sizeof(send_buf), "%s %d CH. %d", message, iteration, curr_channel);
ESP_ERROR_CHECK(gptimer_get_raw_count(gptimer, &start_count));
res = obj->send(dest_board_id, send_buf, strlen(reinterpret_cast<char*>(send_buf)), FrameType::DEBUG_CONTROL_TYPE, curr_channel);
ESP_ERROR_CHECK(gptimer_get_raw_count(gptimer, &end_count));
snprintf(reinterpret_cast<char*>(send_buf), sizeof(send_buf), "%s RANDOM", message); //modifying the data while it transmits shouldn't affect the actual transmission here
if (res != ESP_OK){
ESP_LOGE("thread", "Failed to send message on thread %d", curr_channel);
} else {
printf("Successfully sent message\n");
// printf("Sent %zu B sized in %" PRIu64 " us\n", strlen(reinterpret_cast<char*>(send_buf)) + CONTROL_FRAME_OVERHEAD, end_count-start_count);
}
//wait on a queue for a few ms (if there's nothing, just send another frame. otherwise pop from queue and read it)
if (xQueueReceive(shared_queue, (void*)&recv_frame, (TickType_t) 50) != pdPASS){
memset(send_buf, 0, 256);
continue; //nothing or failed to pop from queue
}
res = obj->print_frame_info(recv_frame.buf, recv_frame.len, recv_buf);
if (res != ESP_OK){
num_incorrect++;
printf("Received %ld bad frames on tx/rx round %ld for thread %d\n", num_incorrect, total_transactions, curr_channel);
} else {
printf("Received message %s on channel %d on round %ld. Total bad frames %ld\n", recv_buf, curr_channel, total_transactions, num_incorrect);
}
total_transactions++;
iteration++;
if (iteration == 100){
iteration = 0;
}
// vTaskDelay(1000 / portTICK_PERIOD_MS); // wait 1 second before trying to send again
//reset temp buffers
memset(recv_buf, 0, 256);
memset(send_buf, 0, 256);
}
}
void print_binary(unsigned char c) {
for (int i = 7; i >= 0; i--) {
printf("%d", (c >> i) & 1);
}
}
void print_string_binary(const char *str) {
while (*str) {
print_binary((unsigned char)*str);
printf(" "); // space between bytes for readability
str++;
}
printf("\n");
}
extern "C" [[noreturn]] void app_main(void) {
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
esp_netif_init();
esp_event_loop_create_default();
printf("finished esp init\n");
printf("Hello world!\n");
// uint8_t iteration = 0;
// const char* message = "THIS IS A TEXT MESSAGE";
uint8_t board_id = 69;
std::unique_ptr<DataLinkManager> obj = std::make_unique<DataLinkManager>(board_id);
// uint8_t dest_board_id = 2; //using a dummy number for now - there is no board with id 2 right now
// esp_err_t res;
// uint8_t send_buf[256];
// uint8_t recv_buf[256];
// size_t recv_len = 0;
// uint8_t curr_channel = 0;
DataLinkManager* obj_to_send = obj.release();
TaskArgs args[4] = {};
for (uint8_t i = 0; i < MAX_CHANNELS; i++){
args[i].link_layer_obj = obj_to_send;
args[i].task_id = i;
args[i].receiver_id = i+1;
args[i].receive_queue = xQueueCreate(10, sizeof(ReceviedFrame)); //queue storing up to 10 control frames
xTaskCreate(multi_transceiver, "multi_transceiver", 4096, static_cast<void*>(&args[i]), 5, NULL);
vTaskDelay(500 / portTICK_PERIOD_MS);
}
printf("Tasks have been created\n");
while(true){
//do nothing
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
for (int i = 5; i >= 0; i--) {
printf("Restarting in %d seconds...\n", i);
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
printf("Restarting now.\n");
fflush(stdout);
esp_restart();
while(true){
//dummy wait
vTaskDelay(2000 / portTICK_PERIOD_MS);
}
}

View File

@@ -1,3 +1,4 @@
//mdns and other stuff main file
#include <cstdio>
#include <memory>

237
main/main_rmt_timing.cpp Normal file
View File

@@ -0,0 +1,237 @@
#include <cstdio>
#include <memory>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_flash.h"
#include "nvs_flash.h"
#include "RMTManager.h"
#include <esp_netif.h>
#include <esp_event.h>
#include <freertos/semphr.h>
#define BOARD_A_MESSAGE "MESSAGE FROM BOARD A"
#define BOARD_B_MESSAGE "MESSAGE FROM BOARD B"
#ifdef TIME_TEST
#include <inttypes.h>
#include "driver/gptimer.h"
#endif //TIME_TEST
// void rmt_task(void* arg) {
// vTaskDelay(pdMS_TO_TICKS(3000)); // wait 3 seconds to stabilize heap
// const auto obj = std::make_unique<RMTManager>();
// const char* message = "THIS IS A SAMPLE TEXT MESSAGE";
// rmt_transmit_config_t tx_config = {
// .loop_count = 0,
// .flags = {
// .eot_level = 0 // typically 0 or 1, depending on your output idle level
// }
// };
// int res = obj->send(message, strlen(message), &tx_config);
// if (res == ESP_OK){
// printf("Successfully sent '%s'\n", message);
// } else{
// printf("Failed to send '%s'\n", message);
// }
// vTaskDelete(NULL);
// }
void print_binary(unsigned char c) {
for (int i = 7; i >= 0; i--) {
printf("%d", (c >> i) & 1);
}
}
void print_string_binary(const char *str) {
while (*str) {
print_binary((unsigned char)*str);
printf(" "); // space between bytes for readability
str++;
}
printf("\n");
}
/**
* @brief This main function shows the RMT TX and RX working by sending a message string in `message` over a GPIO pin and receiving on another pin
*
*/
extern "C" [[noreturn]] void app_main(void) {
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
esp_netif_init();
esp_event_loop_create_default();
printf("finished esp init\n");
printf("Hello world!\n");
const auto obj = std::make_unique<RMTManager>();
#ifdef TIME_TEST
gptimer_handle_t gptimer = NULL;
gptimer_config_t timer_config = {
.clk_src = GPTIMER_CLK_SRC_DEFAULT,
.direction = GPTIMER_COUNT_UP,
.resolution_hz = 1 * 1000 * 1000, // 1MHz, 1 tick = 1us
};
ESP_ERROR_CHECK(gptimer_new_timer(&timer_config, &gptimer));
ESP_ERROR_CHECK(gptimer_enable(gptimer));
ESP_ERROR_CHECK(gptimer_start(gptimer));
uint64_t start_count = 0, end_count = 0;
uint64_t sum = 0; //used to calculate the average send time
uint64_t num_iterations = 0;
#endif //TIME_TEST
#ifdef BOARD_A
const char* message = BOARD_A_MESSAGE;
#elif BOARD_B
const char* message = BOARD_B_MESSAGE;
#else
const char* message = "THIS IS A SAMPLE TEXT MESSAGE";
#endif
#ifdef VERIFY_RECEIVE
uint64_t num_received = 0;
uint64_t num_corrupted = 0;
#endif //VERIFY_RECEIVE
// const char* message = "t";
rmt_transmit_config_t tx_config = {
.loop_count = 0,
.flags = {
.eot_level = 0 // typically 0 or 1, depending on your output idle level
}
};
int res = ESP_OK;
char recv_message[256];
// xTaskCreate(rmt_task, "rmt_task", 4096, NULL, 5, NULL);
while(true){
#ifndef TIME_TEST
printf("Starting RX receive\n");
res = obj->start_receiving();
if (res != ESP_OK){
printf("Something went wrong... terminating..\n");
continue;
}
#endif //TIME_TEST
printf("sending message %s - binary:\n", message);
print_string_binary(message);
#ifdef TIME_TEST
ESP_ERROR_CHECK(gptimer_get_raw_count(gptimer, &start_count));
#endif //TIME_TEST
res = obj->send(message, strlen(message), &tx_config);
if (res == ESP_OK){
// printf("Successfully started send job for message '%s'\n", message);
} else{
printf("Failed to start send job for message '%s'\n", message);
// continue; //do not continue on
}
res = obj->wait_until_send_complete(); //will wait until the the message is sent
#ifdef TIME_TEST
ESP_ERROR_CHECK(gptimer_get_raw_count(gptimer, &end_count));
#endif //TIME_TEST
if (res == ESP_OK){
#ifndef TIME_TEST
printf("Successfully sent message '%s'\n", message);
#else
printf("Sent %zu B sized message %s in %" PRIu64 " us on iteration %" PRIu64 "\n", strlen(message), message, end_count-start_count, num_iterations);
sum += (end_count - start_count);
#endif //TIME_TEST
} else{
printf("Failed to send '%s'\n", message);
continue;
}
#ifndef TIME_TEST
res = obj->receive(recv_message, sizeof(recv_message));
if (res != 0){
printf("Failed to receive message\n");
} else {
printf("Received message %s\n", recv_message);
}
#ifdef VERIFY_RECEIVE
printf("Checking message for corruption on iteration %lld\n", num_received);
#ifdef BOARD_A
//check if BOARD_B_MESSAGE was received correctly
if (strcmp(recv_message, BOARD_B_MESSAGE) != 0){
num_corrupted++;
}
#elif BOARD_B
if (strcmp(recv_message, BOARD_A_MESSAGE) != 0){
num_corrupted++;
}
#endif //BOARD_B
num_received++;
#endif //VERIFY_RECEIVE
memset(recv_message, 0, sizeof(recv_message));
#endif //TIME_TEST
vTaskDelay(2000 / portTICK_PERIOD_MS);
#ifdef TIME_TEST
num_iterations++;
if (num_iterations > 100){
break;
}
#endif //TIME_TEST
#ifdef VERIFY_RECEIVE
if (num_received > 100){
break;
}
#endif //VERIFY_RECEIVE
}
#ifdef TIME_TEST
float avg = (sum/num_iterations) / 1e6; //avg send time us to s
printf("Average Transmission Rate is: %.9f bits per second\n", (float)((strlen(message) * 8)/avg));
printf("Average sent time is: %.9f seconds\n", avg);
#endif //TIME_TEST
#ifdef VERIFY_RECEIVE
float avg_received_corrupted = (num_corrupted * 100) / (num_received-1);
printf("Average corruption rate is: %.6f %% \n", avg_received_corrupted);
printf("Total number of corrupted messages over %lld iterations is: %lld\n", num_received-1, num_corrupted);
#endif //VERIFY_RECEIVE
for (int i = 5; i >= 0; i--) {
printf("Restarting in %d seconds...\n", i);
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
printf("Restarting now.\n");
fflush(stdout);
esp_restart();
while(true){
//dummy wait
vTaskDelay(2000 / portTICK_PERIOD_MS);
}
}