can.c 25 KB

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