diff --git a/main/can.c b/main/can.c index d49cd1e..8f0af17 100644 --- a/main/can.c +++ b/main/can.c @@ -71,10 +71,24 @@ void can_bus_off_check() { } } +void can_msg_to_str(twai_message_t *can_msg, char *out_str) { + char byte_str[3]; + out_str[0] = '\0'; + sprintf(out_str, "can frame: ID: %08X dlc: %d ", (int) can_msg->identifier, can_msg->data_length_code); + if (can_msg->data_length_code == 0) { + strcat(out_str, "(no data)"); + } else { + strcat(out_str, "data: "); + for (int i = 0; i < can_msg->data_length_code; i++) { + sprintf(byte_str, "%02X", can_msg->data[i]); + strcat(out_str, byte_str); + } + } +} + void can_task(void* arg) { twai_message_t rx_msg; - char byte_str[3]; - char data_bytes_str[20]; + char data_bytes_str[50]; // ESP_ERROR_CHECK(esp_task_wdt_add(NULL)); for (;;) { // A Task shall never return or exit. // esp_task_wdt_reset(); @@ -83,12 +97,7 @@ void can_task(void* arg) { // TODO: add software filtering // if ((((rx_msg.identifier >> 8) & 0xFF) != CONFIG_DEVICE_ID) && (((rx_msg.identifier >> 8) & 0xFF) != 0xFF)) continue; // ESP_LOGI(LOG_TAG, "received can frame: %" PRIu32, rx_msg.identifier); - data_bytes_str[0] = '\0'; - for (int i = 0; i < rx_msg.data_length_code; i++) { - sprintf(byte_str, "%02X", rx_msg.data[i]); - strcat(data_bytes_str, byte_str); - } - xprintf("received can frame: ID: %" PRIu32 " dlc: %d data: %s\n", rx_msg.identifier, rx_msg.data_length_code, data_bytes_str); + can_msg_to_str(&rx_msg, data_bytes_str); + xprintf(LOG_COLOR(LOG_COLOR_BLUE) "recv %s\n" LOG_RESET_COLOR, data_bytes_str); } } - diff --git a/main/can.h b/main/can.h index f88dd29..a32c7df 100644 --- a/main/can.h +++ b/main/can.h @@ -15,5 +15,6 @@ void can_stop(); void calculate_hw_can_filter(uint32_t device_id, twai_filter_config_t* filter, bool ota_mode); void can_bus_off_check(); void can_task(void* arg); +void can_msg_to_str(twai_message_t *can_msg, char *out_str); #endif // MAIN_CAN_H diff --git a/main/cmd_can.c b/main/cmd_can.c index 50370b2..d98d046 100644 --- a/main/cmd_can.c +++ b/main/cmd_can.c @@ -1,7 +1,36 @@ #include "cmd_can.h" #include "driver/twai.h" +#include "freertos/projdefs.h" #include "hal/twai_types.h" +#include "string.h" +#include "esp_console.h" +#include "xvprintf.h" +#include "can.h" + +static void register_send_can_frame(void); void register_can_commands(void) { + register_send_can_frame(); } + +static int send_can_frame(int argc, char **argv) { + char data_bytes_str[30]; + twai_message_t msg = {.extd = 1}; + msg.data_length_code = 0; + msg.identifier = 0xFF << 8; + twai_transmit(&msg, pdMS_TO_TICKS(1000)); + can_msg_to_str(&msg, data_bytes_str); + printf("sent %s\n", data_bytes_str); + return 0; +} + +static void register_send_can_frame(void) { + const esp_console_cmd_t cmd = { + .command = "cansend", + .help = "Send a can message to the bus", + .hint = NULL, + .func = &send_can_frame, + }; + ESP_ERROR_CHECK( esp_console_cmd_register(&cmd) ); +}