twai.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. // Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. #include "soc/soc_caps.h"
  14. #include "sdkconfig.h"
  15. #include "freertos/FreeRTOS.h"
  16. #include "freertos/task.h"
  17. #include "freertos/queue.h"
  18. #include "freertos/semphr.h"
  19. #include "esp_types.h"
  20. #include "esp_log.h"
  21. #include "esp_intr_alloc.h"
  22. #include "esp_pm.h"
  23. #include "esp_attr.h"
  24. #include "esp_heap_caps.h"
  25. #include "driver/gpio.h"
  26. #include "driver/periph_ctrl.h"
  27. #include "driver/twai.h"
  28. #include "soc/twai_periph.h"
  29. #include "hal/twai_hal.h"
  30. /* ---------------------------- Definitions --------------------------------- */
  31. //Internal Macros
  32. #define TWAI_CHECK(cond, ret_val) ({ \
  33. if (!(cond)) { \
  34. return (ret_val); \
  35. } \
  36. })
  37. #define TWAI_CHECK_FROM_CRIT(cond, ret_val) ({ \
  38. if (!(cond)) { \
  39. TWAI_EXIT_CRITICAL(); \
  40. return ret_val; \
  41. } \
  42. })
  43. #define TWAI_SET_FLAG(var, mask) ((var) |= (mask))
  44. #define TWAI_RESET_FLAG(var, mask) ((var) &= ~(mask))
  45. #ifdef CONFIG_TWAI_ISR_IN_IRAM
  46. #define TWAI_ISR_ATTR IRAM_ATTR
  47. #define TWAI_MALLOC_CAPS (MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)
  48. #else
  49. #define TWAI_TAG "TWAI"
  50. #define TWAI_ISR_ATTR
  51. #define TWAI_MALLOC_CAPS MALLOC_CAP_DEFAULT
  52. #endif //CONFIG_TWAI_ISR_IN_IRAM
  53. #define DRIVER_DEFAULT_INTERRUPTS 0xE7 //Exclude data overrun (bit[3]) and brp_div (bit[4])
  54. //Control flags
  55. #define CTRL_FLAG_STOPPED 0x001 //TWAI peripheral in stopped state
  56. #define CTRL_FLAG_RECOVERING 0x002 //Bus is undergoing bus recovery
  57. #define CTRL_FLAG_ERR_WARN 0x004 //TEC or REC is >= error warning limit
  58. #define CTRL_FLAG_ERR_PASSIVE 0x008 //TEC or REC is >= 128
  59. #define CTRL_FLAG_BUS_OFF 0x010 //Bus-off due to TEC >= 256
  60. #define CTRL_FLAG_TX_BUFF_OCCUPIED 0x020 //Transmit buffer is occupied
  61. #define ALERT_LOG_LEVEL_WARNING TWAI_ALERT_ARB_LOST //Alerts above and including this level use ESP_LOGW
  62. #define ALERT_LOG_LEVEL_ERROR TWAI_ALERT_TX_FAILED //Alerts above and including this level use ESP_LOGE
  63. /* ------------------ Typedefs, structures, and variables ------------------- */
  64. //Control structure for TWAI driver
  65. typedef struct {
  66. //Control and status members
  67. uint32_t control_flags;
  68. twai_mode_t mode;
  69. uint32_t rx_missed_count;
  70. uint32_t tx_failed_count;
  71. uint32_t arb_lost_count;
  72. uint32_t bus_error_count;
  73. intr_handle_t isr_handle;
  74. //TX and RX
  75. #ifdef CONFIG_TWAI_ISR_IN_IRAM
  76. void *tx_queue_buff;
  77. void *tx_queue_struct;
  78. void *rx_queue_buff;
  79. void *rx_queue_struct;
  80. void *semphr_struct;
  81. #endif
  82. QueueHandle_t tx_queue;
  83. QueueHandle_t rx_queue;
  84. int tx_msg_count;
  85. int rx_msg_count;
  86. //Alerts
  87. SemaphoreHandle_t alert_semphr;
  88. uint32_t alerts_enabled;
  89. uint32_t alerts_triggered;
  90. #ifdef CONFIG_PM_ENABLE
  91. //Power Management
  92. esp_pm_lock_handle_t pm_lock;
  93. #endif
  94. } twai_obj_t;
  95. static twai_obj_t *p_twai_obj = NULL;
  96. static portMUX_TYPE twai_spinlock = portMUX_INITIALIZER_UNLOCKED;
  97. #define TWAI_ENTER_CRITICAL_ISR() portENTER_CRITICAL_ISR(&twai_spinlock)
  98. #define TWAI_EXIT_CRITICAL_ISR() portEXIT_CRITICAL_ISR(&twai_spinlock)
  99. #define TWAI_ENTER_CRITICAL() portENTER_CRITICAL(&twai_spinlock)
  100. #define TWAI_EXIT_CRITICAL() portEXIT_CRITICAL(&twai_spinlock)
  101. static twai_hal_context_t twai_context;
  102. /* -------------------- Interrupt and Alert Handlers ------------------------ */
  103. TWAI_ISR_ATTR static void twai_alert_handler(uint32_t alert_code, int *alert_req)
  104. {
  105. if (p_twai_obj->alerts_enabled & alert_code) {
  106. //Signify alert has occurred
  107. TWAI_SET_FLAG(p_twai_obj->alerts_triggered, alert_code);
  108. *alert_req = 1;
  109. #ifndef CONFIG_TWAI_ISR_IN_IRAM //Only log if ISR is not in IRAM
  110. if (p_twai_obj->alerts_enabled & TWAI_ALERT_AND_LOG) {
  111. if (alert_code >= ALERT_LOG_LEVEL_ERROR) {
  112. ESP_EARLY_LOGE(TWAI_TAG, "Alert %d", alert_code);
  113. } else if (alert_code >= ALERT_LOG_LEVEL_WARNING) {
  114. ESP_EARLY_LOGW(TWAI_TAG, "Alert %d", alert_code);
  115. } else {
  116. ESP_EARLY_LOGI(TWAI_TAG, "Alert %d", alert_code);
  117. }
  118. }
  119. #endif
  120. }
  121. }
  122. static inline void twai_handle_bus_off(int *alert_req)
  123. {
  124. //Bus-Off condition. TEC should set and held at 127, REC should be 0, reset mode entered
  125. TWAI_SET_FLAG(p_twai_obj->control_flags, CTRL_FLAG_BUS_OFF);
  126. /* Note: REC is still allowed to increase during bus-off. REC > err_warn
  127. can prevent "bus recovery complete" interrupt from occurring. Set to
  128. listen only mode to freeze REC. */
  129. twai_hal_handle_bus_off(&twai_context);
  130. twai_alert_handler(TWAI_ALERT_BUS_OFF, alert_req);
  131. }
  132. static inline void twai_handle_recovery_complete(int *alert_req)
  133. {
  134. //Bus recovery complete.
  135. bool recov_cplt = twai_hal_handle_bus_recov_cplt(&twai_context);
  136. assert(recov_cplt);
  137. //Reset and set flags to the equivalent of the stopped state
  138. TWAI_RESET_FLAG(p_twai_obj->control_flags, CTRL_FLAG_RECOVERING | CTRL_FLAG_ERR_WARN |
  139. CTRL_FLAG_ERR_PASSIVE | CTRL_FLAG_BUS_OFF |
  140. CTRL_FLAG_TX_BUFF_OCCUPIED);
  141. TWAI_SET_FLAG(p_twai_obj->control_flags, CTRL_FLAG_STOPPED);
  142. twai_alert_handler(TWAI_ALERT_BUS_RECOVERED, alert_req);
  143. }
  144. static inline void twai_handle_recovery_in_progress(int * alert_req)
  145. {
  146. //Bus-recovery in progress. TEC has dropped below error warning limit
  147. twai_alert_handler(TWAI_ALERT_RECOVERY_IN_PROGRESS, alert_req);
  148. }
  149. static inline void twai_handle_above_ewl(int *alert_req)
  150. {
  151. //TEC or REC surpassed error warning limit
  152. TWAI_SET_FLAG(p_twai_obj->control_flags, CTRL_FLAG_ERR_WARN);
  153. twai_alert_handler(TWAI_ALERT_ABOVE_ERR_WARN, alert_req);
  154. }
  155. static inline void twai_handle_below_ewl(int *alert_req)
  156. {
  157. //TEC and REC are both below error warning
  158. TWAI_RESET_FLAG(p_twai_obj->control_flags, CTRL_FLAG_ERR_WARN);
  159. twai_alert_handler(TWAI_ALERT_BELOW_ERR_WARN, alert_req);
  160. }
  161. static inline void twai_handle_error_passive(int *alert_req)
  162. {
  163. //Entered error passive
  164. TWAI_SET_FLAG(p_twai_obj->control_flags, CTRL_FLAG_ERR_PASSIVE);
  165. twai_alert_handler(TWAI_ALERT_ERR_PASS, alert_req);
  166. }
  167. static inline void twai_handle_error_active(int *alert_req)
  168. {
  169. //Returned to error active
  170. TWAI_RESET_FLAG(p_twai_obj->control_flags, CTRL_FLAG_ERR_PASSIVE);
  171. twai_alert_handler(TWAI_ALERT_ERR_ACTIVE, alert_req);
  172. }
  173. static inline void twai_handle_bus_error(int *alert_req)
  174. {
  175. // ECC register is read to re-arm bus error interrupt. ECC is not used
  176. twai_hal_handle_bus_error(&twai_context);
  177. p_twai_obj->bus_error_count++;
  178. twai_alert_handler(TWAI_ALERT_BUS_ERROR, alert_req);
  179. }
  180. static inline void twai_handle_arb_lost(int *alert_req)
  181. {
  182. //ALC register is read to re-arm arb lost interrupt. ALC is not used
  183. twai_hal_handle_arb_lost(&twai_context);
  184. p_twai_obj->arb_lost_count++;
  185. twai_alert_handler(TWAI_ALERT_ARB_LOST, alert_req);
  186. }
  187. static inline void twai_handle_rx_buffer_frames(BaseType_t *task_woken, int *alert_req)
  188. {
  189. uint32_t msg_count = twai_hal_get_rx_msg_count(&twai_context);
  190. for (int i = 0; i < msg_count; i++) {
  191. twai_hal_frame_t frame;
  192. twai_hal_read_rx_buffer_and_clear(&twai_context, &frame);
  193. //Copy frame into RX Queue
  194. if (xQueueSendFromISR(p_twai_obj->rx_queue, &frame, task_woken) == pdTRUE) {
  195. p_twai_obj->rx_msg_count++;
  196. } else {
  197. p_twai_obj->rx_missed_count++;
  198. twai_alert_handler(TWAI_ALERT_RX_QUEUE_FULL, alert_req);
  199. }
  200. }
  201. //Todo: Add Software Filters
  202. //Todo: Check for data overrun of RX FIFO, then trigger alert
  203. }
  204. static inline void twai_handle_tx_buffer_frame(BaseType_t *task_woken, int *alert_req)
  205. {
  206. //Handle previously transmitted frame
  207. if (twai_hal_check_last_tx_successful(&twai_context)) {
  208. twai_alert_handler(TWAI_ALERT_TX_SUCCESS, alert_req);
  209. } else {
  210. p_twai_obj->tx_failed_count++;
  211. twai_alert_handler(TWAI_ALERT_TX_FAILED, alert_req);
  212. }
  213. //Update TX message count
  214. p_twai_obj->tx_msg_count--;
  215. assert(p_twai_obj->tx_msg_count >= 0); //Sanity check
  216. //Check if there are more frames to transmit
  217. if (p_twai_obj->tx_msg_count > 0 && p_twai_obj->tx_queue != NULL) {
  218. twai_hal_frame_t frame;
  219. int res = xQueueReceiveFromISR(p_twai_obj->tx_queue, &frame, task_woken);
  220. if (res == pdTRUE) {
  221. twai_hal_set_tx_buffer_and_transmit(&twai_context, &frame);
  222. } else {
  223. assert(false && "failed to get a frame from TX queue");
  224. }
  225. } else {
  226. //No more frames to transmit
  227. TWAI_RESET_FLAG(p_twai_obj->control_flags, CTRL_FLAG_TX_BUFF_OCCUPIED);
  228. twai_alert_handler(TWAI_ALERT_TX_IDLE, alert_req);
  229. }
  230. }
  231. TWAI_ISR_ATTR static void twai_intr_handler_main(void *arg)
  232. {
  233. BaseType_t task_woken = pdFALSE;
  234. int alert_req = 0;
  235. uint32_t event;
  236. TWAI_ENTER_CRITICAL_ISR();
  237. if (p_twai_obj == NULL) { //Incase intr occurs whilst driver is being uninstalled
  238. TWAI_EXIT_CRITICAL_ISR();
  239. return;
  240. }
  241. event = twai_hal_decode_interrupt_events(&twai_context, p_twai_obj->control_flags & CTRL_FLAG_RECOVERING);
  242. if (event & TWAI_HAL_EVENT_BUS_OFF) {
  243. twai_handle_bus_off(&alert_req);
  244. }
  245. if (event & TWAI_HAL_EVENT_BUS_RECOV_CPLT) {
  246. twai_handle_recovery_complete(&alert_req);
  247. }
  248. if (event & TWAI_HAL_EVENT_BUS_RECOV_PROGRESS) {
  249. twai_handle_recovery_in_progress(&alert_req);
  250. }
  251. if (event & TWAI_HAL_EVENT_ABOVE_EWL) {
  252. twai_handle_above_ewl(&alert_req);
  253. }
  254. if (event & TWAI_HAL_EVENT_BELOW_EWL) {
  255. twai_handle_below_ewl(&alert_req);
  256. }
  257. if (event & TWAI_HAL_EVENT_ERROR_PASSIVE) {
  258. twai_handle_error_passive(&alert_req);
  259. }
  260. if (event & TWAI_HAL_EVENT_ERROR_ACTIVE) {
  261. twai_handle_error_active(&alert_req);
  262. }
  263. if (event & TWAI_HAL_EVENT_BUS_ERR) {
  264. twai_handle_bus_error(&alert_req);
  265. }
  266. if (event & TWAI_HAL_EVENT_ARB_LOST) {
  267. twai_handle_arb_lost(&alert_req);
  268. }
  269. if (event & TWAI_HAL_EVENT_RX_BUFF_FRAME) {
  270. twai_handle_rx_buffer_frames(&task_woken, &alert_req);
  271. }
  272. //TX command related handlers should be called last, so that other commands
  273. //do not overwrite the TX command related bits in the command register.
  274. if (event & TWAI_HAL_EVENT_TX_BUFF_FREE) {
  275. twai_handle_tx_buffer_frame(&task_woken, &alert_req);
  276. }
  277. TWAI_EXIT_CRITICAL_ISR();
  278. if (p_twai_obj->alert_semphr != NULL && alert_req) {
  279. //Give semaphore if alerts were triggered
  280. xSemaphoreGiveFromISR(p_twai_obj->alert_semphr, &task_woken);
  281. }
  282. if (task_woken == pdTRUE) {
  283. portYIELD_FROM_ISR();
  284. }
  285. }
  286. /* -------------------------- Helper functions ----------------------------- */
  287. static void twai_configure_gpio(gpio_num_t tx, gpio_num_t rx, gpio_num_t clkout, gpio_num_t bus_status)
  288. {
  289. //Set TX pin
  290. gpio_set_pull_mode(tx, GPIO_FLOATING);
  291. gpio_matrix_out(tx, TWAI_TX_IDX, false, false);
  292. gpio_pad_select_gpio(tx);
  293. //Set RX pin
  294. gpio_set_pull_mode(rx, GPIO_FLOATING);
  295. gpio_matrix_in(rx, TWAI_RX_IDX, false);
  296. gpio_pad_select_gpio(rx);
  297. gpio_set_direction(rx, GPIO_MODE_INPUT);
  298. //Configure output clock pin (Optional)
  299. if (clkout >= 0 && clkout < GPIO_NUM_MAX) {
  300. gpio_set_pull_mode(clkout, GPIO_FLOATING);
  301. gpio_matrix_out(clkout, TWAI_CLKOUT_IDX, false, false);
  302. gpio_pad_select_gpio(clkout);
  303. }
  304. //Configure bus status pin (Optional)
  305. if (bus_status >= 0 && bus_status < GPIO_NUM_MAX) {
  306. gpio_set_pull_mode(bus_status, GPIO_FLOATING);
  307. gpio_matrix_out(bus_status, TWAI_BUS_OFF_ON_IDX, false, false);
  308. gpio_pad_select_gpio(bus_status);
  309. }
  310. }
  311. static void twai_free_driver_obj(twai_obj_t *p_obj)
  312. {
  313. //Free driver object and any dependent SW resources it uses (queues, semaphores etc)
  314. #ifdef CONFIG_PM_ENABLE
  315. if (p_obj->pm_lock != NULL) {
  316. ESP_ERROR_CHECK(esp_pm_lock_delete(p_obj->pm_lock));
  317. }
  318. #endif
  319. //Delete queues and semaphores
  320. if (p_obj->tx_queue != NULL) {
  321. vQueueDelete(p_obj->tx_queue);
  322. }
  323. if (p_obj->rx_queue != NULL) {
  324. vQueueDelete(p_obj->rx_queue);
  325. }
  326. if (p_obj->alert_semphr != NULL) {
  327. vSemaphoreDelete(p_obj->alert_semphr);
  328. }
  329. #ifdef CONFIG_TWAI_ISR_IN_IRAM
  330. //Free memory used by static queues and semaphores. free() allows freeing NULL pointers
  331. free(p_obj->tx_queue_buff);
  332. free(p_obj->tx_queue_struct);
  333. free(p_obj->rx_queue_buff);
  334. free(p_obj->rx_queue_struct);
  335. free(p_obj->semphr_struct);
  336. #endif //CONFIG_TWAI_ISR_IN_IRAM
  337. free(p_obj);
  338. }
  339. static twai_obj_t *twai_alloc_driver_obj(uint32_t tx_queue_len, uint32_t rx_queue_len)
  340. {
  341. //Allocates driver object and any dependent SW resources it uses (queues, semaphores etc)
  342. //Create a TWAI driver object
  343. twai_obj_t *p_obj = heap_caps_calloc(1, sizeof(twai_obj_t), TWAI_MALLOC_CAPS);
  344. if (p_obj == NULL) {
  345. return NULL;
  346. }
  347. #ifdef CONFIG_TWAI_ISR_IN_IRAM
  348. //Allocate memory for queues and semaphores in DRAM
  349. if (tx_queue_len > 0) {
  350. p_obj->tx_queue_buff = heap_caps_calloc(tx_queue_len, sizeof(twai_hal_frame_t), TWAI_MALLOC_CAPS);
  351. p_obj->tx_queue_struct = heap_caps_calloc(1, sizeof(StaticQueue_t), TWAI_MALLOC_CAPS);
  352. if (p_obj->tx_queue_buff == NULL || p_obj->tx_queue_struct == NULL) {
  353. goto cleanup;
  354. }
  355. }
  356. p_obj->rx_queue_buff = heap_caps_calloc(rx_queue_len, sizeof(twai_hal_frame_t), TWAI_MALLOC_CAPS);
  357. p_obj->rx_queue_struct = heap_caps_calloc(1, sizeof(StaticQueue_t), TWAI_MALLOC_CAPS);
  358. p_obj->semphr_struct = heap_caps_calloc(1, sizeof(StaticSemaphore_t), TWAI_MALLOC_CAPS);
  359. if (p_obj->rx_queue_buff == NULL || p_obj->rx_queue_struct == NULL || p_obj->semphr_struct == NULL) {
  360. goto cleanup;
  361. }
  362. //Create static queues and semaphores
  363. if (tx_queue_len > 0) {
  364. p_obj->tx_queue = xQueueCreateStatic(tx_queue_len, sizeof(twai_hal_frame_t), p_obj->tx_queue_buff, p_obj->tx_queue_struct);
  365. if (p_obj->tx_queue == NULL) {
  366. goto cleanup;
  367. }
  368. }
  369. p_obj->rx_queue = xQueueCreateStatic(rx_queue_len, sizeof(twai_hal_frame_t), p_obj->rx_queue_buff, p_obj->rx_queue_struct);
  370. p_obj->alert_semphr = xSemaphoreCreateBinaryStatic(p_obj->semphr_struct);
  371. if (p_obj->rx_queue == NULL || p_obj->alert_semphr == NULL) {
  372. goto cleanup;
  373. }
  374. #else //CONFIG_TWAI_ISR_IN_IRAM
  375. if (tx_queue_len > 0) {
  376. p_obj->tx_queue = xQueueCreate(tx_queue_len, sizeof(twai_hal_frame_t));
  377. }
  378. p_obj->rx_queue = xQueueCreate(rx_queue_len, sizeof(twai_hal_frame_t));
  379. p_obj->alert_semphr = xSemaphoreCreateBinary();
  380. if ((tx_queue_len > 0 && p_obj->tx_queue == NULL) || p_obj->rx_queue == NULL || p_obj->alert_semphr == NULL) {
  381. goto cleanup;
  382. }
  383. #endif //CONFIG_TWAI_ISR_IN_IRAM
  384. #ifdef CONFIG_PM_ENABLE
  385. esp_err_t pm_err = esp_pm_lock_create(ESP_PM_APB_FREQ_MAX, 0, "twai", &(p_obj->pm_lock));
  386. if (pm_err != ESP_OK ) {
  387. goto cleanup;
  388. }
  389. #endif
  390. return p_obj;
  391. cleanup:
  392. twai_free_driver_obj(p_obj);
  393. return NULL;
  394. }
  395. /* ---------------------------- Public Functions ---------------------------- */
  396. esp_err_t twai_driver_install(const twai_general_config_t *g_config, const twai_timing_config_t *t_config, const twai_filter_config_t *f_config)
  397. {
  398. //Check arguments
  399. TWAI_CHECK(g_config != NULL, ESP_ERR_INVALID_ARG);
  400. TWAI_CHECK(t_config != NULL, ESP_ERR_INVALID_ARG);
  401. TWAI_CHECK(f_config != NULL, ESP_ERR_INVALID_ARG);
  402. TWAI_CHECK(g_config->rx_queue_len > 0, ESP_ERR_INVALID_ARG);
  403. TWAI_CHECK(g_config->tx_io >= 0 && g_config->tx_io < GPIO_NUM_MAX, ESP_ERR_INVALID_ARG);
  404. TWAI_CHECK(g_config->rx_io >= 0 && g_config->rx_io < GPIO_NUM_MAX, ESP_ERR_INVALID_ARG);
  405. #if (CONFIG_ESP32_REV_MIN >= 2)
  406. TWAI_CHECK(t_config->brp >= TWAI_BRP_MIN && t_config->brp <= TWAI_BRP_MAX_ECO, ESP_ERR_INVALID_ARG);
  407. #else
  408. TWAI_CHECK(t_config->brp >= TWAI_BRP_MIN && t_config->brp <= TWAI_BRP_MAX, ESP_ERR_INVALID_ARG);
  409. #endif
  410. #ifndef CONFIG_TWAI_ISR_IN_IRAM
  411. TWAI_CHECK(!(g_config->intr_flags & ESP_INTR_FLAG_IRAM), ESP_ERR_INVALID_ARG);
  412. #endif
  413. TWAI_ENTER_CRITICAL();
  414. TWAI_CHECK_FROM_CRIT(p_twai_obj == NULL, ESP_ERR_INVALID_STATE);
  415. TWAI_EXIT_CRITICAL();
  416. esp_err_t ret;
  417. twai_obj_t *p_twai_obj_dummy;
  418. //Create a TWAI object (including queues and semaphores)
  419. p_twai_obj_dummy = twai_alloc_driver_obj(g_config->tx_queue_len, g_config->rx_queue_len);
  420. TWAI_CHECK(p_twai_obj_dummy != NULL, ESP_ERR_NO_MEM);
  421. //Initialize flags and variables. All other members are already set to zero by twai_alloc_driver_obj()
  422. p_twai_obj_dummy->control_flags = CTRL_FLAG_STOPPED;
  423. p_twai_obj_dummy->mode = g_config->mode;
  424. p_twai_obj_dummy->alerts_enabled = g_config->alerts_enabled;
  425. //Initialize TWAI peripheral registers, and allocate interrupt
  426. TWAI_ENTER_CRITICAL();
  427. if (p_twai_obj == NULL) {
  428. p_twai_obj = p_twai_obj_dummy;
  429. } else {
  430. //Check if driver is already installed
  431. TWAI_EXIT_CRITICAL();
  432. ret = ESP_ERR_INVALID_STATE;
  433. goto err;
  434. }
  435. periph_module_reset(PERIPH_TWAI_MODULE);
  436. periph_module_enable(PERIPH_TWAI_MODULE); //Enable APB CLK to TWAI peripheral
  437. bool init = twai_hal_init(&twai_context);
  438. assert(init);
  439. twai_hal_configure(&twai_context, t_config, f_config, DRIVER_DEFAULT_INTERRUPTS, g_config->clkout_divider);
  440. //Todo: Allow interrupt to be registered to specified CPU
  441. TWAI_EXIT_CRITICAL();
  442. //Allocate GPIO and Interrupts
  443. twai_configure_gpio(g_config->tx_io, g_config->rx_io, g_config->clkout_io, g_config->bus_off_io);
  444. ESP_ERROR_CHECK(esp_intr_alloc(ETS_TWAI_INTR_SOURCE, g_config->intr_flags, twai_intr_handler_main, NULL, &p_twai_obj->isr_handle));
  445. #ifdef CONFIG_PM_ENABLE
  446. ESP_ERROR_CHECK(esp_pm_lock_acquire(p_twai_obj->pm_lock)); //Acquire pm_lock to keep APB clock at 80MHz
  447. #endif
  448. return ESP_OK; //TWAI module is still in reset mode, users need to call twai_start() afterwards
  449. err:
  450. //Free can driver object
  451. twai_free_driver_obj(p_twai_obj_dummy);
  452. return ret;
  453. }
  454. esp_err_t twai_driver_uninstall(void)
  455. {
  456. twai_obj_t *p_twai_obj_dummy;
  457. TWAI_ENTER_CRITICAL();
  458. //Check state
  459. TWAI_CHECK_FROM_CRIT(p_twai_obj != NULL, ESP_ERR_INVALID_STATE);
  460. TWAI_CHECK_FROM_CRIT(p_twai_obj->control_flags & (CTRL_FLAG_STOPPED | CTRL_FLAG_BUS_OFF), ESP_ERR_INVALID_STATE);
  461. //Todo: Add check to see if in reset mode. //Enter reset mode to stop any TWAI bus activity
  462. //Clear registers by reading
  463. twai_hal_deinit(&twai_context);
  464. periph_module_disable(PERIPH_TWAI_MODULE); //Disable TWAI peripheral
  465. p_twai_obj_dummy = p_twai_obj; //Use dummy to shorten critical section
  466. p_twai_obj = NULL;
  467. TWAI_EXIT_CRITICAL();
  468. ESP_ERROR_CHECK(esp_intr_free(p_twai_obj_dummy->isr_handle)); //Free interrupt
  469. #ifdef CONFIG_PM_ENABLE
  470. //Release and delete power management lock
  471. ESP_ERROR_CHECK(esp_pm_lock_release(p_twai_obj_dummy->pm_lock));
  472. #endif
  473. //Free can driver object
  474. twai_free_driver_obj(p_twai_obj_dummy);
  475. return ESP_OK;
  476. }
  477. esp_err_t twai_start(void)
  478. {
  479. //Check state
  480. TWAI_ENTER_CRITICAL();
  481. TWAI_CHECK_FROM_CRIT(p_twai_obj != NULL, ESP_ERR_INVALID_STATE);
  482. TWAI_CHECK_FROM_CRIT(p_twai_obj->control_flags & CTRL_FLAG_STOPPED, ESP_ERR_INVALID_STATE);
  483. //Reset RX queue, and RX message count
  484. xQueueReset(p_twai_obj->rx_queue);
  485. p_twai_obj->rx_msg_count = 0;
  486. //Todo: Add assert to see if in reset mode. //Should already be in bus-off mode, set again to make sure
  487. //Currently in listen only mode, need to set to mode specified by configuration
  488. bool started = twai_hal_start(&twai_context, p_twai_obj->mode);
  489. assert(started);
  490. TWAI_RESET_FLAG(p_twai_obj->control_flags, CTRL_FLAG_STOPPED);
  491. TWAI_EXIT_CRITICAL();
  492. return ESP_OK;
  493. }
  494. esp_err_t twai_stop(void)
  495. {
  496. //Check state
  497. TWAI_ENTER_CRITICAL();
  498. TWAI_CHECK_FROM_CRIT(p_twai_obj != NULL, ESP_ERR_INVALID_STATE);
  499. TWAI_CHECK_FROM_CRIT(!(p_twai_obj->control_flags & (CTRL_FLAG_STOPPED | CTRL_FLAG_BUS_OFF)), ESP_ERR_INVALID_STATE);
  500. bool stopped = twai_hal_stop(&twai_context);
  501. assert(stopped);
  502. TWAI_RESET_FLAG(p_twai_obj->control_flags, CTRL_FLAG_TX_BUFF_OCCUPIED);
  503. TWAI_SET_FLAG(p_twai_obj->control_flags, CTRL_FLAG_STOPPED);
  504. //Reset TX Queue and message count
  505. if (p_twai_obj->tx_queue != NULL) {
  506. xQueueReset(p_twai_obj->tx_queue);
  507. }
  508. p_twai_obj->tx_msg_count = 0;
  509. TWAI_EXIT_CRITICAL();
  510. return ESP_OK;
  511. }
  512. esp_err_t twai_transmit(const twai_message_t *message, TickType_t ticks_to_wait)
  513. {
  514. //Check arguments
  515. TWAI_CHECK(p_twai_obj != NULL, ESP_ERR_INVALID_STATE);
  516. TWAI_CHECK(message != NULL, ESP_ERR_INVALID_ARG);
  517. TWAI_CHECK((message->data_length_code <= TWAI_FRAME_MAX_DLC) || message->dlc_non_comp, ESP_ERR_INVALID_ARG);
  518. TWAI_ENTER_CRITICAL();
  519. //Check State
  520. TWAI_CHECK_FROM_CRIT(!(p_twai_obj->mode == TWAI_MODE_LISTEN_ONLY), ESP_ERR_NOT_SUPPORTED);
  521. TWAI_CHECK_FROM_CRIT(!(p_twai_obj->control_flags & (CTRL_FLAG_STOPPED | CTRL_FLAG_BUS_OFF)), ESP_ERR_INVALID_STATE);
  522. //Format frame
  523. esp_err_t ret = ESP_FAIL;
  524. twai_hal_frame_t tx_frame;
  525. twai_hal_format_frame(message, &tx_frame);
  526. //Check if frame can be sent immediately
  527. if ((p_twai_obj->tx_msg_count == 0) && !(p_twai_obj->control_flags & CTRL_FLAG_TX_BUFF_OCCUPIED)) {
  528. //No other frames waiting to transmit. Bypass queue and transmit immediately
  529. twai_hal_set_tx_buffer_and_transmit(&twai_context, &tx_frame);
  530. p_twai_obj->tx_msg_count++;
  531. TWAI_SET_FLAG(p_twai_obj->control_flags, CTRL_FLAG_TX_BUFF_OCCUPIED);
  532. ret = ESP_OK;
  533. }
  534. TWAI_EXIT_CRITICAL();
  535. if (ret != ESP_OK) {
  536. if (p_twai_obj->tx_queue == NULL) {
  537. //TX Queue is disabled and TX buffer is occupied, message was not sent
  538. ret = ESP_FAIL;
  539. } else if (xQueueSend(p_twai_obj->tx_queue, &tx_frame, ticks_to_wait) == pdTRUE) {
  540. //Copied to TX Queue
  541. TWAI_ENTER_CRITICAL();
  542. if (p_twai_obj->control_flags & (CTRL_FLAG_STOPPED | CTRL_FLAG_BUS_OFF)) {
  543. //TX queue was reset (due to stop/bus_off), remove copied frame from queue to prevent transmission
  544. int res = xQueueReceive(p_twai_obj->tx_queue, &tx_frame, 0);
  545. assert(res == pdTRUE);
  546. ret = ESP_ERR_INVALID_STATE;
  547. } else if ((p_twai_obj->tx_msg_count == 0) && !(p_twai_obj->control_flags & CTRL_FLAG_TX_BUFF_OCCUPIED)) {
  548. //TX buffer was freed during copy, manually trigger transmission
  549. int res = xQueueReceive(p_twai_obj->tx_queue, &tx_frame, 0);
  550. assert(res == pdTRUE);
  551. twai_hal_set_tx_buffer_and_transmit(&twai_context, &tx_frame);
  552. p_twai_obj->tx_msg_count++;
  553. TWAI_SET_FLAG(p_twai_obj->control_flags, CTRL_FLAG_TX_BUFF_OCCUPIED);
  554. ret = ESP_OK;
  555. } else {
  556. //Frame was copied to queue, waiting to be transmitted
  557. p_twai_obj->tx_msg_count++;
  558. ret = ESP_OK;
  559. }
  560. TWAI_EXIT_CRITICAL();
  561. } else {
  562. //Timed out waiting for free space on TX queue
  563. ret = ESP_ERR_TIMEOUT;
  564. }
  565. }
  566. return ret;
  567. }
  568. esp_err_t twai_receive(twai_message_t *message, TickType_t ticks_to_wait)
  569. {
  570. //Check arguments and state
  571. TWAI_CHECK(p_twai_obj != NULL, ESP_ERR_INVALID_STATE);
  572. TWAI_CHECK(message != NULL, ESP_ERR_INVALID_ARG);
  573. //Get frame from RX Queue or RX Buffer
  574. twai_hal_frame_t rx_frame;
  575. if (xQueueReceive(p_twai_obj->rx_queue, &rx_frame, ticks_to_wait) != pdTRUE) {
  576. return ESP_ERR_TIMEOUT;
  577. }
  578. TWAI_ENTER_CRITICAL();
  579. p_twai_obj->rx_msg_count--;
  580. TWAI_EXIT_CRITICAL();
  581. //Decode frame
  582. twai_hal_parse_frame(&rx_frame, message);
  583. return ESP_OK;
  584. }
  585. esp_err_t twai_read_alerts(uint32_t *alerts, TickType_t ticks_to_wait)
  586. {
  587. //Check arguments and state
  588. TWAI_CHECK(p_twai_obj != NULL, ESP_ERR_INVALID_STATE);
  589. TWAI_CHECK(alerts != NULL, ESP_ERR_INVALID_ARG);
  590. //Wait for an alert to occur
  591. if (xSemaphoreTake(p_twai_obj->alert_semphr, ticks_to_wait) == pdTRUE) {
  592. TWAI_ENTER_CRITICAL();
  593. *alerts = p_twai_obj->alerts_triggered;
  594. p_twai_obj->alerts_triggered = 0; //Clear triggered alerts
  595. TWAI_EXIT_CRITICAL();
  596. return ESP_OK;
  597. } else {
  598. *alerts = 0;
  599. return ESP_ERR_TIMEOUT;
  600. }
  601. }
  602. esp_err_t twai_reconfigure_alerts(uint32_t alerts_enabled, uint32_t *current_alerts)
  603. {
  604. TWAI_CHECK(p_twai_obj != NULL, ESP_ERR_INVALID_STATE);
  605. TWAI_ENTER_CRITICAL();
  606. //Clear any unhandled alerts
  607. if (current_alerts != NULL) {
  608. *current_alerts = p_twai_obj->alerts_triggered;;
  609. }
  610. p_twai_obj->alerts_triggered = 0;
  611. p_twai_obj->alerts_enabled = alerts_enabled; //Update enabled alerts
  612. TWAI_EXIT_CRITICAL();
  613. return ESP_OK;
  614. }
  615. esp_err_t twai_initiate_recovery(void)
  616. {
  617. TWAI_ENTER_CRITICAL();
  618. //Check state
  619. TWAI_CHECK_FROM_CRIT(p_twai_obj != NULL, ESP_ERR_INVALID_STATE);
  620. TWAI_CHECK_FROM_CRIT(p_twai_obj->control_flags & CTRL_FLAG_BUS_OFF, ESP_ERR_INVALID_STATE);
  621. TWAI_CHECK_FROM_CRIT(!(p_twai_obj->control_flags & CTRL_FLAG_RECOVERING), ESP_ERR_INVALID_STATE);
  622. //Reset TX Queue/Counters
  623. if (p_twai_obj->tx_queue != NULL) {
  624. xQueueReset(p_twai_obj->tx_queue);
  625. }
  626. p_twai_obj->tx_msg_count = 0;
  627. TWAI_RESET_FLAG(p_twai_obj->control_flags, CTRL_FLAG_TX_BUFF_OCCUPIED);
  628. TWAI_SET_FLAG(p_twai_obj->control_flags, CTRL_FLAG_RECOVERING);
  629. //Trigger start of recovery process
  630. bool started = twai_hal_start_bus_recovery(&twai_context);
  631. assert(started);
  632. TWAI_EXIT_CRITICAL();
  633. return ESP_OK;
  634. }
  635. esp_err_t twai_get_status_info(twai_status_info_t *status_info)
  636. {
  637. //Check parameters and state
  638. TWAI_CHECK(p_twai_obj != NULL, ESP_ERR_INVALID_STATE);
  639. TWAI_CHECK(status_info != NULL, ESP_ERR_INVALID_ARG);
  640. TWAI_ENTER_CRITICAL();
  641. status_info->tx_error_counter = twai_hal_get_tec(&twai_context);
  642. status_info->rx_error_counter = twai_hal_get_rec(&twai_context);
  643. status_info->msgs_to_tx = p_twai_obj->tx_msg_count;
  644. status_info->msgs_to_rx = p_twai_obj->rx_msg_count;
  645. status_info->tx_failed_count = p_twai_obj->tx_failed_count;
  646. status_info->rx_missed_count = p_twai_obj->rx_missed_count;
  647. status_info->arb_lost_count = p_twai_obj->arb_lost_count;
  648. status_info->bus_error_count = p_twai_obj->bus_error_count;
  649. if (p_twai_obj->control_flags & CTRL_FLAG_RECOVERING) {
  650. status_info->state = TWAI_STATE_RECOVERING;
  651. } else if (p_twai_obj->control_flags & CTRL_FLAG_BUS_OFF) {
  652. status_info->state = TWAI_STATE_BUS_OFF;
  653. } else if (p_twai_obj->control_flags & CTRL_FLAG_STOPPED) {
  654. status_info->state = TWAI_STATE_STOPPED;
  655. } else {
  656. status_info->state = TWAI_STATE_RUNNING;
  657. }
  658. TWAI_EXIT_CRITICAL();
  659. return ESP_OK;
  660. }
  661. esp_err_t twai_clear_transmit_queue(void)
  662. {
  663. //Check State
  664. TWAI_CHECK(p_twai_obj != NULL, ESP_ERR_INVALID_STATE);
  665. TWAI_CHECK(p_twai_obj->tx_queue != NULL, ESP_ERR_NOT_SUPPORTED);
  666. TWAI_ENTER_CRITICAL();
  667. //If a message is currently undergoing transmission, the tx interrupt handler will decrement tx_msg_count
  668. p_twai_obj->tx_msg_count = (p_twai_obj->control_flags & CTRL_FLAG_TX_BUFF_OCCUPIED) ? 1 : 0;
  669. xQueueReset(p_twai_obj->tx_queue);
  670. TWAI_EXIT_CRITICAL();
  671. return ESP_OK;
  672. }
  673. esp_err_t twai_clear_receive_queue(void)
  674. {
  675. //Check State
  676. TWAI_CHECK(p_twai_obj != NULL, ESP_ERR_INVALID_STATE);
  677. TWAI_ENTER_CRITICAL();
  678. p_twai_obj->rx_msg_count = 0;
  679. xQueueReset(p_twai_obj->rx_queue);
  680. TWAI_EXIT_CRITICAL();
  681. return ESP_OK;
  682. }