Parcourir la source

fixed handling of CAN bus off state

Andrew Tridgell il y a 3 ans
Parent
commit
e7a0510b52
2 fichiers modifiés avec 24 ajouts et 0 suppressions
  1. 23 0
      RemoteIDModule/CANDriver.cpp
  2. 1 0
      RemoteIDModule/CANDriver.h

+ 23 - 0
RemoteIDModule/CANDriver.cpp

@@ -227,7 +227,30 @@ bool CANDriver::send(const CANFrame &frame)
     message.data_length_code = frame.dlc;
     memcpy(message.data, frame.data, 8);
 
+    twai_status_info_t info {};
+    twai_get_status_info(&info);
+    switch (info.state) {
+    case TWAI_STATE_STOPPED:
+        twai_start();
+        break;
+    case TWAI_STATE_RUNNING:
+    case TWAI_STATE_RECOVERING:
+        break;
+    case TWAI_STATE_BUS_OFF: {
+        uint32_t now = millis();
+        if (now - last_bus_recovery_ms > 2000) {
+            last_bus_recovery_ms = now;
+            twai_initiate_recovery();
+        }
+        break;
+    }
+    }
+
     const esp_err_t sts = twai_transmit(&message, pdMS_TO_TICKS(5));
+    if (sts == ESP_OK) {
+        last_bus_recovery_ms = 0;
+    }
+
     return (sts == ESP_OK);
 }
 

+ 1 - 0
RemoteIDModule/CANDriver.h

@@ -29,6 +29,7 @@ private:
     bool computeTimings(uint32_t target_bitrate, Timings& out_timings);
 
     uint32_t bitrate;
+    uint32_t last_bus_recovery_ms;
 };
 
 /**