can.c 25 KB

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