From 189535b059c58f5f90bd2472638b195a9eca468b Mon Sep 17 00:00:00 2001 From: Peter Poetzi Date: Wed, 29 Dec 2021 03:11:31 +0100 Subject: [PATCH] feature can bus reset on error --- main/can.cpp | 31 +++++++++++++++++++++++++++++++ main/newsettings.h | 4 ++++ 2 files changed, 35 insertions(+) diff --git a/main/can.cpp b/main/can.cpp index aa9cb82..a2da16e 100644 --- a/main/can.cpp +++ b/main/can.cpp @@ -18,6 +18,7 @@ #include "bobbycar-can.h" #include "globals.h" #include "buttons.h" +#include "newsettings.h" using namespace std::chrono_literals; @@ -279,6 +280,9 @@ void parseCanInput() break; } +uint32_t can_total_error_cnt = 0; +uint32_t can_sequential_error_cnt = 0; + void sendCanCommands() { constexpr auto send = [](uint32_t addr, auto value){ @@ -290,11 +294,38 @@ void sendCanCommands() std::memcpy(message.data, &value, sizeof(value)); const auto timeout = std::chrono::ceil(espchrono::milliseconds32{settings.controllerHardware.canTransmitTimeout}).count(); + + const auto timestamp_before = espchrono::millis_clock::now(); const auto result = twai_transmit(&message, timeout); if (result != ESP_OK && result != ESP_ERR_TIMEOUT) { ESP_LOGE(TAG, "ERROR: twai_transmit() failed with %s", esp_err_to_name(result)); } + + if (result == ESP_ERR_TIMEOUT) { + can_sequential_error_cnt++; + can_total_error_cnt++; + ESP_LOGW(TAG, "twai_transmit() took %lld ms, seq err: %d, total err: %d", + espchrono::ago(timestamp_before).count(), + can_sequential_error_cnt, + can_total_error_cnt); + } else { + can_sequential_error_cnt = 0; + } + + + if (can_sequential_error_cnt > 3) { + can_sequential_error_cnt = 0; + if (configs.canBusResetOnError.value) { + if (const auto err = twai_stop(); err != ESP_OK || true) + ESP_LOGE(TAG, "ERROR: twai_stop() failed with %s", esp_err_to_name(err)); + + if (const auto err = twai_start(); err != ESP_OK || true) + ESP_LOGE(TAG, "ERROR: twai_start() failed with %s", esp_err_to_name(err)); + + } + } + return result; }; diff --git a/main/newsettings.h b/main/newsettings.h index 7b1775e..08bc1e9 100644 --- a/main/newsettings.h +++ b/main/newsettings.h @@ -78,6 +78,8 @@ public: ConfigWrapper wifiApChannel {1, DoReset, {}, "wifiApChannel" }; ConfigWrapper wifiApAuthmode{WIFI_AUTH_WPA2_PSK, DoReset, {}, "wifiApAuthmode" }; + ConfigWrapper canBusResetOnError {false, DoReset, {}, "canBusRstErr" }; + ConfigWrapper bluetoothName {defaultHostname, DoReset, StringMinMaxSize<4, 32>, "bluetoothName" }; #define NEW_SETTINGS(x) \ @@ -194,6 +196,8 @@ public: x(wifiApChannel) \ x(wifiApAuthmode) \ \ + x(canBusResetOnError) \ + \ //x(bluetoothName) template