can.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  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. #ifdef SOC_CAN_SUPPORTED
  15. #include "sdkconfig.h"
  16. #include "freertos/FreeRTOS.h"
  17. #include "freertos/portmacro.h"
  18. #include "freertos/task.h"
  19. #include "freertos/queue.h"
  20. #include "freertos/semphr.h"
  21. #include "esp_types.h"
  22. #include "esp_log.h"
  23. #include "esp_intr_alloc.h"
  24. #include "esp_pm.h"
  25. #include "esp_attr.h"
  26. #include "esp_heap_caps.h"
  27. #include "driver/gpio.h"
  28. #include "driver/periph_ctrl.h"
  29. #include "driver/can.h"
  30. #include "soc/can_periph.h"
  31. #include "hal/can_hal.h"
  32. /* ---------------------------- Definitions --------------------------------- */
  33. //Internal Macros
  34. #define CAN_CHECK(cond, ret_val) ({ \
  35. if (!(cond)) { \
  36. return (ret_val); \
  37. } \
  38. })
  39. #define CAN_CHECK_FROM_CRIT(cond, ret_val) ({ \
  40. if (!(cond)) { \
  41. CAN_EXIT_CRITICAL(); \
  42. return ret_val; \
  43. } \
  44. })
  45. #define CAN_SET_FLAG(var, mask) ((var) |= (mask))
  46. #define CAN_RESET_FLAG(var, mask) ((var) &= ~(mask))
  47. #ifdef CONFIG_CAN_ISR_IN_IRAM
  48. #define CAN_ISR_ATTR IRAM_ATTR
  49. #define CAN_MALLOC_CAPS (MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)
  50. #else
  51. #define CAN_TAG "CAN"
  52. #define CAN_ISR_ATTR
  53. #define CAN_MALLOC_CAPS MALLOC_CAP_DEFAULT
  54. #endif //CONFIG_CAN_ISR_IN_IRAM
  55. #define DRIVER_DEFAULT_INTERRUPTS 0xE7 //Exclude data overrun (bit[3]) and brp_div (bit[4])
  56. //Control flags
  57. #define CTRL_FLAG_STOPPED 0x001 //CAN peripheral in stopped state
  58. #define CTRL_FLAG_RECOVERING 0x002 //Bus is undergoing bus recovery
  59. #define CTRL_FLAG_ERR_WARN 0x004 //TEC or REC is >= error warning limit
  60. #define CTRL_FLAG_ERR_PASSIVE 0x008 //TEC or REC is >= 128
  61. #define CTRL_FLAG_BUS_OFF 0x010 //Bus-off due to TEC >= 256
  62. #define CTRL_FLAG_TX_BUFF_OCCUPIED 0x020 //Transmit buffer is occupied
  63. #define ALERT_LOG_LEVEL_WARNING CAN_ALERT_ARB_LOST //Alerts above and including this level use ESP_LOGW
  64. #define ALERT_LOG_LEVEL_ERROR CAN_ALERT_TX_FAILED //Alerts above and including this level use ESP_LOGE
  65. /* ------------------ Typedefs, structures, and variables ------------------- */
  66. //Control structure for CAN driver
  67. typedef struct {
  68. //Control and status members
  69. uint32_t control_flags;
  70. can_mode_t mode;
  71. uint32_t rx_missed_count;
  72. uint32_t tx_failed_count;
  73. uint32_t arb_lost_count;
  74. uint32_t bus_error_count;
  75. intr_handle_t isr_handle;
  76. //TX and RX
  77. #ifdef CONFIG_CAN_ISR_IN_IRAM
  78. void *tx_queue_buff;
  79. void *tx_queue_struct;
  80. void *rx_queue_buff;
  81. void *rx_queue_struct;
  82. void *semphr_struct;
  83. #endif
  84. QueueHandle_t tx_queue;
  85. QueueHandle_t rx_queue;
  86. int tx_msg_count;
  87. int rx_msg_count;
  88. //Alerts
  89. SemaphoreHandle_t alert_semphr;
  90. uint32_t alerts_enabled;
  91. uint32_t alerts_triggered;
  92. #ifdef CONFIG_PM_ENABLE
  93. //Power Management
  94. esp_pm_lock_handle_t pm_lock;
  95. #endif
  96. } can_obj_t;
  97. static can_obj_t *p_can_obj = NULL;
  98. static portMUX_TYPE can_spinlock = portMUX_INITIALIZER_UNLOCKED;
  99. #define CAN_ENTER_CRITICAL_ISR() portENTER_CRITICAL_ISR(&can_spinlock)
  100. #define CAN_EXIT_CRITICAL_ISR() portEXIT_CRITICAL_ISR(&can_spinlock)
  101. #define CAN_ENTER_CRITICAL() portENTER_CRITICAL(&can_spinlock)
  102. #define CAN_EXIT_CRITICAL() portEXIT_CRITICAL(&can_spinlock)
  103. static can_hal_context_t can_context;
  104. /* -------------------- Interrupt and Alert Handlers ------------------------ */
  105. CAN_ISR_ATTR static void can_alert_handler(uint32_t alert_code, int *alert_req)
  106. {
  107. if (p_can_obj->alerts_enabled & alert_code) {
  108. //Signify alert has occurred
  109. CAN_SET_FLAG(p_can_obj->alerts_triggered, alert_code);
  110. *alert_req = 1;
  111. #ifndef CONFIG_CAN_ISR_IN_IRAM //Only log if ISR is not in IRAM
  112. if (p_can_obj->alerts_enabled & CAN_ALERT_AND_LOG) {
  113. if (alert_code >= ALERT_LOG_LEVEL_ERROR) {
  114. ESP_EARLY_LOGE(CAN_TAG, "Alert %d", alert_code);
  115. } else if (alert_code >= ALERT_LOG_LEVEL_WARNING) {
  116. ESP_EARLY_LOGW(CAN_TAG, "Alert %d", alert_code);
  117. } else {
  118. ESP_EARLY_LOGI(CAN_TAG, "Alert %d", alert_code);
  119. }
  120. }
  121. #endif //CONFIG_CAN_ISR_IN_IRAM
  122. }
  123. }
  124. static inline void can_handle_bus_off(int *alert_req)
  125. {
  126. //Bus-Off condition. TEC should set and held at 127, REC should be 0, reset mode entered
  127. CAN_SET_FLAG(p_can_obj->control_flags, CTRL_FLAG_BUS_OFF);
  128. /* Note: REC is still allowed to increase during bus-off. REC > err_warn
  129. can prevent "bus recovery complete" interrupt from occurring. Set to
  130. listen only mode to freeze REC. */
  131. can_hal_handle_bus_off(&can_context);
  132. can_alert_handler(CAN_ALERT_BUS_OFF, alert_req);
  133. }
  134. static inline void can_handle_recovery_complete(int *alert_req)
  135. {
  136. //Bus recovery complete.
  137. bool recov_cplt = can_hal_handle_bus_recov_cplt(&can_context);
  138. assert(recov_cplt);
  139. //Reset and set flags to the equivalent of the stopped state
  140. CAN_RESET_FLAG(p_can_obj->control_flags, CTRL_FLAG_RECOVERING | CTRL_FLAG_ERR_WARN |
  141. CTRL_FLAG_ERR_PASSIVE | CTRL_FLAG_BUS_OFF |
  142. CTRL_FLAG_TX_BUFF_OCCUPIED);
  143. CAN_SET_FLAG(p_can_obj->control_flags, CTRL_FLAG_STOPPED);
  144. can_alert_handler(CAN_ALERT_BUS_RECOVERED, alert_req);
  145. }
  146. static inline void can_handle_recovery_in_progress(int * alert_req)
  147. {
  148. //Bus-recovery in progress. TEC has dropped below error warning limit
  149. can_alert_handler(CAN_ALERT_RECOVERY_IN_PROGRESS, alert_req);
  150. }
  151. static inline void can_handle_above_ewl(int *alert_req)
  152. {
  153. //TEC or REC surpassed error warning limit
  154. CAN_SET_FLAG(p_can_obj->control_flags, CTRL_FLAG_ERR_WARN);
  155. can_alert_handler(CAN_ALERT_ABOVE_ERR_WARN, alert_req);
  156. }
  157. static inline void can_handle_below_ewl(int *alert_req)
  158. {
  159. //TEC and REC are both below error warning
  160. CAN_RESET_FLAG(p_can_obj->control_flags, CTRL_FLAG_ERR_WARN);
  161. can_alert_handler(CAN_ALERT_BELOW_ERR_WARN, alert_req);
  162. }
  163. static inline void can_handle_error_passive(int *alert_req)
  164. {
  165. //Entered error passive
  166. CAN_SET_FLAG(p_can_obj->control_flags, CTRL_FLAG_ERR_PASSIVE);
  167. can_alert_handler(CAN_ALERT_ERR_PASS, alert_req);
  168. }
  169. static inline void can_handle_error_active(int *alert_req)
  170. {
  171. //Returned to error active
  172. CAN_RESET_FLAG(p_can_obj->control_flags, CTRL_FLAG_ERR_PASSIVE);
  173. can_alert_handler(CAN_ALERT_ERR_ACTIVE, alert_req);
  174. }
  175. static inline void can_handle_bus_error(int *alert_req)
  176. {
  177. // ECC register is read to re-arm bus error interrupt. ECC is not used
  178. can_hal_handle_bus_error(&can_context);
  179. p_can_obj->bus_error_count++;
  180. can_alert_handler(CAN_ALERT_BUS_ERROR, alert_req);
  181. }
  182. static inline void can_handle_arb_lost(int *alert_req)
  183. {
  184. //ALC register is read to re-arm arb lost interrupt. ALC is not used
  185. can_hal_handle_arb_lost(&can_context);
  186. p_can_obj->arb_lost_count++;
  187. can_alert_handler(CAN_ALERT_ARB_LOST, alert_req);
  188. }
  189. static inline void can_handle_rx_buffer_frames(BaseType_t *task_woken, int *alert_req)
  190. {
  191. uint32_t msg_count = can_hal_get_rx_msg_count(&can_context);
  192. for (int i = 0; i < msg_count; i++) {
  193. can_hal_frame_t frame;
  194. can_hal_read_rx_buffer_and_clear(&can_context, &frame);
  195. //Copy frame into RX Queue
  196. if (xQueueSendFromISR(p_can_obj->rx_queue, &frame, task_woken) == pdTRUE) {
  197. p_can_obj->rx_msg_count++;
  198. } else {
  199. p_can_obj->rx_missed_count++;
  200. can_alert_handler(CAN_ALERT_RX_QUEUE_FULL, alert_req);
  201. }
  202. }
  203. //Todo: Add Software Filters
  204. //Todo: Check for data overrun of RX FIFO, then trigger alert
  205. }
  206. static inline void can_handle_tx_buffer_frame(BaseType_t *task_woken, int *alert_req)
  207. {
  208. //Handle previously transmitted frame
  209. if (can_hal_check_last_tx_successful(&can_context)) {
  210. can_alert_handler(CAN_ALERT_TX_SUCCESS, alert_req);
  211. } else {
  212. p_can_obj->tx_failed_count++;
  213. can_alert_handler(CAN_ALERT_TX_FAILED, alert_req);
  214. }
  215. //Update TX message count
  216. p_can_obj->tx_msg_count--;
  217. assert(p_can_obj->tx_msg_count >= 0); //Sanity check
  218. //Check if there are more frames to transmit
  219. if (p_can_obj->tx_msg_count > 0 && p_can_obj->tx_queue != NULL) {
  220. can_hal_frame_t frame;
  221. int res = xQueueReceiveFromISR(p_can_obj->tx_queue, &frame, task_woken);
  222. if (res == pdTRUE) {
  223. can_hal_set_tx_buffer_and_transmit(&can_context, &frame);
  224. } else {
  225. assert(false && "failed to get a frame from TX queue");
  226. }
  227. } else {
  228. //No more frames to transmit
  229. CAN_RESET_FLAG(p_can_obj->control_flags, CTRL_FLAG_TX_BUFF_OCCUPIED);
  230. can_alert_handler(CAN_ALERT_TX_IDLE, alert_req);
  231. }
  232. }
  233. CAN_ISR_ATTR static void can_intr_handler_main(void *arg)
  234. {
  235. BaseType_t task_woken = pdFALSE;
  236. int alert_req = 0;
  237. uint32_t event;
  238. CAN_ENTER_CRITICAL_ISR();
  239. if (p_can_obj == NULL) { //Incase intr occurs whilst driver is being uninstalled
  240. CAN_EXIT_CRITICAL_ISR();
  241. return;
  242. }
  243. event = can_hal_decode_interrupt_events(&can_context, p_can_obj->control_flags & CTRL_FLAG_RECOVERING);
  244. if (event & CAN_HAL_EVENT_BUS_OFF) {
  245. can_handle_bus_off(&alert_req);
  246. }
  247. if (event & CAN_HAL_EVENT_BUS_RECOV_CPLT) {
  248. can_handle_recovery_complete(&alert_req);
  249. }
  250. if (event & CAN_HAL_EVENT_BUS_RECOV_PROGRESS) {
  251. can_handle_recovery_in_progress(&alert_req);
  252. }
  253. if (event & CAN_HAL_EVENT_ABOVE_EWL) {
  254. can_handle_above_ewl(&alert_req);
  255. }
  256. if (event & CAN_HAL_EVENT_BELOW_EWL) {
  257. can_handle_below_ewl(&alert_req);
  258. }
  259. if (event & CAN_HAL_EVENT_ERROR_PASSIVE) {
  260. can_handle_error_passive(&alert_req);
  261. }
  262. if (event & CAN_HAL_EVENT_ERROR_ACTIVE) {
  263. can_handle_error_active(&alert_req);
  264. }
  265. if (event & CAN_HAL_EVENT_BUS_ERR) {
  266. can_handle_bus_error(&alert_req);
  267. }
  268. if (event & CAN_HAL_EVENT_ARB_LOST) {
  269. can_handle_arb_lost(&alert_req);
  270. }
  271. if (event & CAN_HAL_EVENT_RX_BUFF_FRAME) {
  272. can_handle_rx_buffer_frames(&task_woken, &alert_req);
  273. }
  274. //TX command related handlers should be called last, so that other commands
  275. //do not overwrite the TX command related bits in the command register.
  276. if (event & CAN_HAL_EVENT_TX_BUFF_FREE) {
  277. can_handle_tx_buffer_frame(&task_woken, &alert_req);
  278. }
  279. CAN_EXIT_CRITICAL_ISR();
  280. if (p_can_obj->alert_semphr != NULL && alert_req) {
  281. //Give semaphore if alerts were triggered
  282. xSemaphoreGiveFromISR(p_can_obj->alert_semphr, &task_woken);
  283. }
  284. if (task_woken == pdTRUE) {
  285. portYIELD_FROM_ISR();
  286. }
  287. }
  288. /* -------------------------- Helper functions ----------------------------- */
  289. static void can_configure_gpio(gpio_num_t tx, gpio_num_t rx, gpio_num_t clkout, gpio_num_t bus_status)
  290. {
  291. //Set TX pin
  292. gpio_set_pull_mode(tx, GPIO_FLOATING);
  293. gpio_matrix_out(tx, CAN_TX_IDX, false, false);
  294. gpio_pad_select_gpio(tx);
  295. //Set RX pin
  296. gpio_set_pull_mode(rx, GPIO_FLOATING);
  297. gpio_matrix_in(rx, CAN_RX_IDX, false);
  298. gpio_pad_select_gpio(rx);
  299. gpio_set_direction(rx, GPIO_MODE_INPUT);
  300. //Configure output clock pin (Optional)
  301. if (clkout >= 0 && clkout < GPIO_NUM_MAX) {
  302. gpio_set_pull_mode(clkout, GPIO_FLOATING);
  303. gpio_matrix_out(clkout, CAN_CLKOUT_IDX, false, false);
  304. gpio_pad_select_gpio(clkout);
  305. }
  306. //Configure bus status pin (Optional)
  307. if (bus_status >= 0 && bus_status < GPIO_NUM_MAX) {
  308. gpio_set_pull_mode(bus_status, GPIO_FLOATING);
  309. gpio_matrix_out(bus_status, CAN_BUS_OFF_ON_IDX, false, false);
  310. gpio_pad_select_gpio(bus_status);
  311. }
  312. }
  313. static void can_free_driver_obj(can_obj_t *p_obj)
  314. {
  315. //Free driver object and any dependent SW resources it uses (queues, semaphores etc)
  316. #ifdef CONFIG_PM_ENABLE
  317. if (p_obj->pm_lock != NULL) {
  318. ESP_ERROR_CHECK(esp_pm_lock_delete(p_obj->pm_lock));
  319. }
  320. #endif
  321. //Delete queues and semaphores
  322. if (p_obj->tx_queue != NULL) {
  323. vQueueDelete(p_obj->tx_queue);
  324. }
  325. if (p_obj->rx_queue != NULL) {
  326. vQueueDelete(p_obj->rx_queue);
  327. }
  328. if (p_obj->alert_semphr != NULL) {
  329. vSemaphoreDelete(p_obj->alert_semphr);
  330. }
  331. #ifdef CONFIG_CAN_ISR_IN_IRAM
  332. //Free memory used by static queues and semaphores. free() allows freeing NULL pointers
  333. free(p_obj->tx_queue_buff);
  334. free(p_obj->tx_queue_struct);
  335. free(p_obj->rx_queue_buff);
  336. free(p_obj->rx_queue_struct);
  337. free(p_obj->semphr_struct);
  338. #endif //CONFIG_CAN_ISR_IN_IRAM
  339. free(p_obj);
  340. }
  341. static can_obj_t *can_alloc_driver_obj(uint32_t tx_queue_len, uint32_t rx_queue_len)
  342. {
  343. //Allocates driver object and any dependent SW resources it uses (queues, semaphores etc)
  344. //Create a CAN driver object
  345. can_obj_t *p_obj = heap_caps_calloc(1, sizeof(can_obj_t), CAN_MALLOC_CAPS);
  346. if (p_obj == NULL) {
  347. return NULL;
  348. }
  349. #ifdef CONFIG_CAN_ISR_IN_IRAM
  350. //Allocate memory for queues and semaphores in DRAM
  351. if (tx_queue_len > 0) {
  352. p_obj->tx_queue_buff = heap_caps_calloc(tx_queue_len, sizeof(can_hal_frame_t), CAN_MALLOC_CAPS);
  353. p_obj->tx_queue_struct = heap_caps_calloc(1, sizeof(StaticQueue_t), CAN_MALLOC_CAPS);
  354. if (p_obj->tx_queue_buff == NULL || p_obj->tx_queue_struct == NULL) {
  355. goto cleanup;
  356. }
  357. }
  358. p_obj->rx_queue_buff = heap_caps_calloc(rx_queue_len, sizeof(can_hal_frame_t), CAN_MALLOC_CAPS);
  359. p_obj->rx_queue_struct = heap_caps_calloc(1, sizeof(StaticQueue_t), CAN_MALLOC_CAPS);
  360. p_obj->semphr_struct = heap_caps_calloc(1, sizeof(StaticSemaphore_t), CAN_MALLOC_CAPS);
  361. if (p_obj->rx_queue_buff == NULL || p_obj->rx_queue_struct == NULL || p_obj->semphr_struct == NULL) {
  362. goto cleanup;
  363. }
  364. //Create static queues and semaphores
  365. if (tx_queue_len > 0) {
  366. p_obj->tx_queue = xQueueCreateStatic(tx_queue_len, sizeof(can_hal_frame_t), p_obj->tx_queue_buff, p_obj->tx_queue_struct);
  367. if (p_obj->tx_queue == NULL) {
  368. goto cleanup;
  369. }
  370. }
  371. p_obj->rx_queue = xQueueCreateStatic(rx_queue_len, sizeof(can_hal_frame_t), p_obj->rx_queue_buff, p_obj->rx_queue_struct);
  372. p_obj->alert_semphr = xSemaphoreCreateBinaryStatic(p_obj->semphr_struct);
  373. if (p_obj->rx_queue == NULL || p_obj->alert_semphr == NULL) {
  374. goto cleanup;
  375. }
  376. #else //CONFIG_CAN_ISR_IN_IRAM
  377. if (tx_queue_len > 0) {
  378. p_obj->tx_queue = xQueueCreate(tx_queue_len, sizeof(can_hal_frame_t));
  379. }
  380. p_obj->rx_queue = xQueueCreate(rx_queue_len, sizeof(can_hal_frame_t));
  381. p_obj->alert_semphr = xSemaphoreCreateBinary();
  382. if ((tx_queue_len > 0 && p_obj->tx_queue == NULL) || p_obj->rx_queue == NULL || p_obj->alert_semphr == NULL) {
  383. goto cleanup;
  384. }
  385. #endif //CONFIG_CAN_ISR_IN_IRAM
  386. #ifdef CONFIG_PM_ENABLE
  387. esp_err_t pm_err = esp_pm_lock_create(ESP_PM_APB_FREQ_MAX, 0, "can", &(p_obj->pm_lock));
  388. if (pm_err != ESP_OK ) {
  389. goto cleanup;
  390. }
  391. #endif
  392. return p_obj;
  393. cleanup:
  394. can_free_driver_obj(p_obj);
  395. return NULL;
  396. }
  397. /* ---------------------------- Public Functions ---------------------------- */
  398. esp_err_t can_driver_install(const can_general_config_t *g_config, const can_timing_config_t *t_config, const can_filter_config_t *f_config)
  399. {
  400. //Check arguments
  401. CAN_CHECK(g_config != NULL, ESP_ERR_INVALID_ARG);
  402. CAN_CHECK(t_config != NULL, ESP_ERR_INVALID_ARG);
  403. CAN_CHECK(f_config != NULL, ESP_ERR_INVALID_ARG);
  404. CAN_CHECK(g_config->rx_queue_len > 0, ESP_ERR_INVALID_ARG);
  405. CAN_CHECK(g_config->tx_io >= 0 && g_config->tx_io < GPIO_NUM_MAX, ESP_ERR_INVALID_ARG);
  406. CAN_CHECK(g_config->rx_io >= 0 && g_config->rx_io < GPIO_NUM_MAX, ESP_ERR_INVALID_ARG);
  407. #if (CONFIG_ESP32_REV_MIN >= 2)
  408. CAN_CHECK(t_config->brp >= CAN_BRP_MIN && t_config->brp <= CAN_BRP_MAX_ECO, ESP_ERR_INVALID_ARG);
  409. #else
  410. CAN_CHECK(t_config->brp >= CAN_BRP_MIN && t_config->brp <= CAN_BRP_MAX, ESP_ERR_INVALID_ARG);
  411. #endif
  412. #ifndef CONFIG_CAN_ISR_IN_IRAM
  413. CAN_CHECK(!(g_config->intr_flags & ESP_INTR_FLAG_IRAM), ESP_ERR_INVALID_ARG);
  414. #endif
  415. CAN_ENTER_CRITICAL();
  416. CAN_CHECK_FROM_CRIT(p_can_obj == NULL, ESP_ERR_INVALID_STATE);
  417. CAN_EXIT_CRITICAL();
  418. esp_err_t ret;
  419. can_obj_t *p_can_obj_dummy;
  420. //Create a CAN object (including queues and semaphores)
  421. p_can_obj_dummy = can_alloc_driver_obj(g_config->tx_queue_len, g_config->rx_queue_len);
  422. CAN_CHECK(p_can_obj_dummy != NULL, ESP_ERR_NO_MEM);
  423. //Initialize flags and variables. All other members are already set to zero by can_alloc_driver_obj()
  424. p_can_obj_dummy->control_flags = CTRL_FLAG_STOPPED;
  425. p_can_obj_dummy->mode = g_config->mode;
  426. p_can_obj_dummy->alerts_enabled = g_config->alerts_enabled;
  427. //Initialize CAN peripheral registers, and allocate interrupt
  428. CAN_ENTER_CRITICAL();
  429. if (p_can_obj == NULL) {
  430. p_can_obj = p_can_obj_dummy;
  431. } else {
  432. //Check if driver is already installed
  433. CAN_EXIT_CRITICAL();
  434. ret = ESP_ERR_INVALID_STATE;
  435. goto err;
  436. }
  437. periph_module_reset(PERIPH_CAN_MODULE);
  438. periph_module_enable(PERIPH_CAN_MODULE); //Enable APB CLK to CAN peripheral
  439. bool init = can_hal_init(&can_context);
  440. assert(init);
  441. can_hal_configure(&can_context, t_config, f_config, DRIVER_DEFAULT_INTERRUPTS, g_config->clkout_divider);
  442. //Todo: Allow interrupt to be registered to specified CPU
  443. CAN_EXIT_CRITICAL();
  444. //Allocate GPIO and Interrupts
  445. can_configure_gpio(g_config->tx_io, g_config->rx_io, g_config->clkout_io, g_config->bus_off_io);
  446. ESP_ERROR_CHECK(esp_intr_alloc(ETS_CAN_INTR_SOURCE, g_config->intr_flags, can_intr_handler_main, NULL, &p_can_obj->isr_handle));
  447. #ifdef CONFIG_PM_ENABLE
  448. ESP_ERROR_CHECK(esp_pm_lock_acquire(p_can_obj->pm_lock)); //Acquire pm_lock to keep APB clock at 80MHz
  449. #endif
  450. return ESP_OK; //CAN module is still in reset mode, users need to call can_start() afterwards
  451. err:
  452. can_free_driver_obj(p_can_obj_dummy);
  453. return ret;
  454. }
  455. esp_err_t can_driver_uninstall(void)
  456. {
  457. can_obj_t *p_can_obj_dummy;
  458. CAN_ENTER_CRITICAL();
  459. //Check state
  460. CAN_CHECK_FROM_CRIT(p_can_obj != NULL, ESP_ERR_INVALID_STATE);
  461. CAN_CHECK_FROM_CRIT(p_can_obj->control_flags & (CTRL_FLAG_STOPPED | CTRL_FLAG_BUS_OFF), ESP_ERR_INVALID_STATE);
  462. //Todo: Add check to see if in reset mode. //Enter reset mode to stop any CAN bus activity
  463. //Clear registers by reading
  464. can_hal_deinit(&can_context);
  465. periph_module_disable(PERIPH_CAN_MODULE); //Disable CAN peripheral
  466. p_can_obj_dummy = p_can_obj; //Use dummy to shorten critical section
  467. p_can_obj = NULL;
  468. CAN_EXIT_CRITICAL();
  469. ESP_ERROR_CHECK(esp_intr_free(p_can_obj_dummy->isr_handle)); //Free interrupt
  470. #ifdef CONFIG_PM_ENABLE
  471. //Release and delete power management lock
  472. ESP_ERROR_CHECK(esp_pm_lock_release(p_can_obj_dummy->pm_lock));
  473. #endif
  474. //Free can driver object
  475. can_free_driver_obj(p_can_obj_dummy);
  476. return ESP_OK;
  477. }
  478. esp_err_t can_start(void)
  479. {
  480. //Check state
  481. CAN_ENTER_CRITICAL();
  482. CAN_CHECK_FROM_CRIT(p_can_obj != NULL, ESP_ERR_INVALID_STATE);
  483. CAN_CHECK_FROM_CRIT(p_can_obj->control_flags & CTRL_FLAG_STOPPED, ESP_ERR_INVALID_STATE);
  484. //Reset RX queue, and RX message count
  485. xQueueReset(p_can_obj->rx_queue);
  486. p_can_obj->rx_msg_count = 0;
  487. //Todo: Add assert to see if in reset mode. //Should already be in bus-off mode, set again to make sure
  488. //Currently in listen only mode, need to set to mode specified by configuration
  489. bool started = can_hal_start(&can_context, p_can_obj->mode);
  490. assert(started);
  491. CAN_RESET_FLAG(p_can_obj->control_flags, CTRL_FLAG_STOPPED);
  492. CAN_EXIT_CRITICAL();
  493. return ESP_OK;
  494. }
  495. esp_err_t can_stop(void)
  496. {
  497. //Check state
  498. CAN_ENTER_CRITICAL();
  499. CAN_CHECK_FROM_CRIT(p_can_obj != NULL, ESP_ERR_INVALID_STATE);
  500. CAN_CHECK_FROM_CRIT(!(p_can_obj->control_flags & (CTRL_FLAG_STOPPED | CTRL_FLAG_BUS_OFF)), ESP_ERR_INVALID_STATE);
  501. bool stopped = can_hal_stop(&can_context);
  502. assert(stopped);
  503. CAN_RESET_FLAG(p_can_obj->control_flags, CTRL_FLAG_TX_BUFF_OCCUPIED);
  504. CAN_SET_FLAG(p_can_obj->control_flags, CTRL_FLAG_STOPPED);
  505. //Reset TX Queue and message count
  506. if (p_can_obj->tx_queue != NULL) {
  507. xQueueReset(p_can_obj->tx_queue);
  508. }
  509. p_can_obj->tx_msg_count = 0;
  510. CAN_EXIT_CRITICAL();
  511. return ESP_OK;
  512. }
  513. esp_err_t can_transmit(const can_message_t *message, TickType_t ticks_to_wait)
  514. {
  515. //Check arguments
  516. CAN_CHECK(p_can_obj != NULL, ESP_ERR_INVALID_STATE);
  517. CAN_CHECK(message != NULL, ESP_ERR_INVALID_ARG);
  518. CAN_CHECK((message->data_length_code <= CAN_FRAME_MAX_DLC) || message->dlc_non_comp, ESP_ERR_INVALID_ARG);
  519. CAN_ENTER_CRITICAL();
  520. //Check State
  521. CAN_CHECK_FROM_CRIT(!(p_can_obj->mode == CAN_MODE_LISTEN_ONLY), ESP_ERR_NOT_SUPPORTED);
  522. CAN_CHECK_FROM_CRIT(!(p_can_obj->control_flags & (CTRL_FLAG_STOPPED | CTRL_FLAG_BUS_OFF)), ESP_ERR_INVALID_STATE);
  523. //Format frame
  524. esp_err_t ret = ESP_FAIL;
  525. can_hal_frame_t tx_frame;
  526. can_hal_format_frame(message, &tx_frame);
  527. //Check if frame can be sent immediately
  528. if ((p_can_obj->tx_msg_count == 0) && !(p_can_obj->control_flags & CTRL_FLAG_TX_BUFF_OCCUPIED)) {
  529. //No other frames waiting to transmit. Bypass queue and transmit immediately
  530. can_hal_set_tx_buffer_and_transmit(&can_context, &tx_frame);
  531. p_can_obj->tx_msg_count++;
  532. CAN_SET_FLAG(p_can_obj->control_flags, CTRL_FLAG_TX_BUFF_OCCUPIED);
  533. ret = ESP_OK;
  534. }
  535. CAN_EXIT_CRITICAL();
  536. if (ret != ESP_OK) {
  537. if (p_can_obj->tx_queue == NULL) {
  538. //TX Queue is disabled and TX buffer is occupied, message was not sent
  539. ret = ESP_FAIL;
  540. } else if (xQueueSend(p_can_obj->tx_queue, &tx_frame, ticks_to_wait) == pdTRUE) {
  541. //Copied to TX Queue
  542. CAN_ENTER_CRITICAL();
  543. if (p_can_obj->control_flags & (CTRL_FLAG_STOPPED | CTRL_FLAG_BUS_OFF)) {
  544. //TX queue was reset (due to stop/bus_off), remove copied frame from queue to prevent transmission
  545. int res = xQueueReceive(p_can_obj->tx_queue, &tx_frame, 0);
  546. assert(res == pdTRUE);
  547. ret = ESP_ERR_INVALID_STATE;
  548. } else if ((p_can_obj->tx_msg_count == 0) && !(p_can_obj->control_flags & CTRL_FLAG_TX_BUFF_OCCUPIED)) {
  549. //TX buffer was freed during copy, manually trigger transmission
  550. int res = xQueueReceive(p_can_obj->tx_queue, &tx_frame, 0);
  551. assert(res == pdTRUE);
  552. can_hal_set_tx_buffer_and_transmit(&can_context, &tx_frame);
  553. p_can_obj->tx_msg_count++;
  554. CAN_SET_FLAG(p_can_obj->control_flags, CTRL_FLAG_TX_BUFF_OCCUPIED);
  555. ret = ESP_OK;
  556. } else {
  557. //Frame was copied to queue, waiting to be transmitted
  558. p_can_obj->tx_msg_count++;
  559. ret = ESP_OK;
  560. }
  561. CAN_EXIT_CRITICAL();
  562. } else {
  563. //Timed out waiting for free space on TX queue
  564. ret = ESP_ERR_TIMEOUT;
  565. }
  566. }
  567. return ret;
  568. }
  569. esp_err_t can_receive(can_message_t *message, TickType_t ticks_to_wait)
  570. {
  571. //Check arguments and state
  572. CAN_CHECK(p_can_obj != NULL, ESP_ERR_INVALID_STATE);
  573. CAN_CHECK(message != NULL, ESP_ERR_INVALID_ARG);
  574. //Get frame from RX Queue or RX Buffer
  575. can_hal_frame_t rx_frame;
  576. if (xQueueReceive(p_can_obj->rx_queue, &rx_frame, ticks_to_wait) != pdTRUE) {
  577. return ESP_ERR_TIMEOUT;
  578. }
  579. CAN_ENTER_CRITICAL();
  580. p_can_obj->rx_msg_count--;
  581. CAN_EXIT_CRITICAL();
  582. //Decode frame
  583. can_hal_parse_frame(&rx_frame, message);
  584. return ESP_OK;
  585. }
  586. esp_err_t can_read_alerts(uint32_t *alerts, TickType_t ticks_to_wait)
  587. {
  588. //Check arguments and state
  589. CAN_CHECK(p_can_obj != NULL, ESP_ERR_INVALID_STATE);
  590. CAN_CHECK(alerts != NULL, ESP_ERR_INVALID_ARG);
  591. //Wait for an alert to occur
  592. if (xSemaphoreTake(p_can_obj->alert_semphr, ticks_to_wait) == pdTRUE) {
  593. CAN_ENTER_CRITICAL();
  594. *alerts = p_can_obj->alerts_triggered;
  595. p_can_obj->alerts_triggered = 0; //Clear triggered alerts
  596. CAN_EXIT_CRITICAL();
  597. return ESP_OK;
  598. } else {
  599. *alerts = 0;
  600. return ESP_ERR_TIMEOUT;
  601. }
  602. }
  603. esp_err_t can_reconfigure_alerts(uint32_t alerts_enabled, uint32_t *current_alerts)
  604. {
  605. CAN_CHECK(p_can_obj != NULL, ESP_ERR_INVALID_STATE);
  606. CAN_ENTER_CRITICAL();
  607. //Clear any unhandled alerts
  608. if (current_alerts != NULL) {
  609. *current_alerts = p_can_obj->alerts_triggered;;
  610. }
  611. p_can_obj->alerts_triggered = 0;
  612. p_can_obj->alerts_enabled = alerts_enabled; //Update enabled alerts
  613. CAN_EXIT_CRITICAL();
  614. return ESP_OK;
  615. }
  616. esp_err_t can_initiate_recovery(void)
  617. {
  618. CAN_ENTER_CRITICAL();
  619. //Check state
  620. CAN_CHECK_FROM_CRIT(p_can_obj != NULL, ESP_ERR_INVALID_STATE);
  621. CAN_CHECK_FROM_CRIT(p_can_obj->control_flags & CTRL_FLAG_BUS_OFF, ESP_ERR_INVALID_STATE);
  622. CAN_CHECK_FROM_CRIT(!(p_can_obj->control_flags & CTRL_FLAG_RECOVERING), ESP_ERR_INVALID_STATE);
  623. //Reset TX Queue/Counters
  624. if (p_can_obj->tx_queue != NULL) {
  625. xQueueReset(p_can_obj->tx_queue);
  626. }
  627. p_can_obj->tx_msg_count = 0;
  628. CAN_RESET_FLAG(p_can_obj->control_flags, CTRL_FLAG_TX_BUFF_OCCUPIED);
  629. CAN_SET_FLAG(p_can_obj->control_flags, CTRL_FLAG_RECOVERING);
  630. //Trigger start of recovery process
  631. bool started = can_hal_start_bus_recovery(&can_context);
  632. assert(started);
  633. CAN_EXIT_CRITICAL();
  634. return ESP_OK;
  635. }
  636. esp_err_t can_get_status_info(can_status_info_t *status_info)
  637. {
  638. //Check parameters and state
  639. CAN_CHECK(p_can_obj != NULL, ESP_ERR_INVALID_STATE);
  640. CAN_CHECK(status_info != NULL, ESP_ERR_INVALID_ARG);
  641. CAN_ENTER_CRITICAL();
  642. status_info->tx_error_counter = can_hal_get_tec(&can_context);
  643. status_info->rx_error_counter = can_hal_get_rec(&can_context);
  644. status_info->msgs_to_tx = p_can_obj->tx_msg_count;
  645. status_info->msgs_to_rx = p_can_obj->rx_msg_count;
  646. status_info->tx_failed_count = p_can_obj->tx_failed_count;
  647. status_info->rx_missed_count = p_can_obj->rx_missed_count;
  648. status_info->arb_lost_count = p_can_obj->arb_lost_count;
  649. status_info->bus_error_count = p_can_obj->bus_error_count;
  650. if (p_can_obj->control_flags & CTRL_FLAG_RECOVERING) {
  651. status_info->state = CAN_STATE_RECOVERING;
  652. } else if (p_can_obj->control_flags & CTRL_FLAG_BUS_OFF) {
  653. status_info->state = CAN_STATE_BUS_OFF;
  654. } else if (p_can_obj->control_flags & CTRL_FLAG_STOPPED) {
  655. status_info->state = CAN_STATE_STOPPED;
  656. } else {
  657. status_info->state = CAN_STATE_RUNNING;
  658. }
  659. CAN_EXIT_CRITICAL();
  660. return ESP_OK;
  661. }
  662. esp_err_t can_clear_transmit_queue(void)
  663. {
  664. //Check State
  665. CAN_CHECK(p_can_obj != NULL, ESP_ERR_INVALID_STATE);
  666. CAN_CHECK(p_can_obj->tx_queue != NULL, ESP_ERR_NOT_SUPPORTED);
  667. CAN_ENTER_CRITICAL();
  668. //If a message is currently undergoing transmission, the tx interrupt handler will decrement tx_msg_count
  669. p_can_obj->tx_msg_count = (p_can_obj->control_flags & CTRL_FLAG_TX_BUFF_OCCUPIED) ? 1 : 0;
  670. xQueueReset(p_can_obj->tx_queue);
  671. CAN_EXIT_CRITICAL();
  672. return ESP_OK;
  673. }
  674. esp_err_t can_clear_receive_queue(void)
  675. {
  676. //Check State
  677. CAN_CHECK(p_can_obj != NULL, ESP_ERR_INVALID_STATE);
  678. CAN_ENTER_CRITICAL();
  679. p_can_obj->rx_msg_count = 0;
  680. xQueueReset(p_can_obj->rx_queue);
  681. CAN_EXIT_CRITICAL();
  682. return ESP_OK;
  683. }
  684. #endif