1 /*
2  * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 /*******************************************************************************
8  * NOTICE
9  * The hal is not public api, don't use in application code.
10  * See readme.md in hal/include/hal/readme.md
11  ******************************************************************************/
12 
13 #pragma once
14 
15 #include <stddef.h>
16 #include <stdbool.h>
17 #include "sdkconfig.h"
18 #include "hal/twai_types.h"
19 #include "hal/twai_ll.h"
20 
21 #ifdef __cplusplus
22 extern "C" {
23 #endif
24 
25 /* ------------------------- Defines and Typedefs --------------------------- */
26 
27 #define TWAI_HAL_SET_BITS(var, flag)            ((var) |= (flag))
28 #define TWAI_HAL_CLEAR_BITS(var, flag)          ((var) &= ~(flag))
29 
30 //HAL state flags
31 #define TWAI_HAL_STATE_FLAG_RUNNING             (1 << 0)    //Controller is active (not in reset mode)
32 #define TWAI_HAL_STATE_FLAG_RECOVERING          (1 << 1)    //Bus is undergoing bus recovery
33 #define TWAI_HAL_STATE_FLAG_ERR_WARN            (1 << 2)    //TEC or REC is >= error warning limit
34 #define TWAI_HAL_STATE_FLAG_ERR_PASSIVE         (1 << 3)    //TEC or REC is >= 128
35 #define TWAI_HAL_STATE_FLAG_BUS_OFF             (1 << 4)    //Bus-off due to TEC >= 256
36 #define TWAI_HAL_STATE_FLAG_TX_BUFF_OCCUPIED    (1 << 5)    //Transmit buffer is occupied
37 #if defined(CONFIG_TWAI_ERRATA_FIX_RX_FRAME_INVALID) || defined(CONFIG_TWAI_ERRATA_FIX_RX_FIFO_CORRUPT)
38 #define TWAI_HAL_STATE_FLAG_TX_NEED_RETRY       (1 << 7)    //TX needs to be restarted due to errata workarounds
39 #endif
40 
41 //Interrupt Events
42 #define TWAI_HAL_EVENT_BUS_OFF                  (1 << 0)
43 #define TWAI_HAL_EVENT_BUS_RECOV_CPLT           (1 << 1)
44 #define TWAI_HAL_EVENT_BUS_RECOV_PROGRESS       (1 << 2)
45 #define TWAI_HAL_EVENT_ABOVE_EWL                (1 << 3)
46 #define TWAI_HAL_EVENT_BELOW_EWL                (1 << 4)
47 #define TWAI_HAL_EVENT_ERROR_PASSIVE            (1 << 5)
48 #define TWAI_HAL_EVENT_ERROR_ACTIVE             (1 << 6)
49 #define TWAI_HAL_EVENT_BUS_ERR                  (1 << 7)
50 #define TWAI_HAL_EVENT_ARB_LOST                 (1 << 8)
51 #define TWAI_HAL_EVENT_RX_BUFF_FRAME            (1 << 9)
52 #define TWAI_HAL_EVENT_TX_BUFF_FREE             (1 << 10)
53 #if defined(CONFIG_TWAI_ERRATA_FIX_RX_FRAME_INVALID) || defined(CONFIG_TWAI_ERRATA_FIX_RX_FIFO_CORRUPT)
54 #define TWAI_HAL_EVENT_NEED_PERIPH_RESET        (1 << 11)
55 #endif
56 
57 typedef twai_ll_frame_buffer_t twai_hal_frame_t;
58 
59 typedef struct {
60     twai_dev_t *dev;
61     uint32_t state_flags;
62     uint32_t clock_source_hz;
63 #if defined(CONFIG_TWAI_ERRATA_FIX_RX_FRAME_INVALID) || defined(CONFIG_TWAI_ERRATA_FIX_RX_FIFO_CORRUPT)
64     twai_hal_frame_t tx_frame_save;
65     twai_ll_reg_save_t reg_save;
66     uint8_t rx_msg_cnt_save;
67 #endif
68 } twai_hal_context_t;
69 
70 /* ---------------------------- Init and Config ----------------------------- */
71 
72 typedef struct {
73     int controller_id;
74     uint32_t clock_source_hz;
75 } twai_hal_config_t;
76 
77 /**
78  * @brief Initialize TWAI peripheral and HAL context
79  *
80  * Sets HAL context, puts TWAI peripheral into reset mode, then sets some
81  * registers with default values.
82  *
83  * @param hal_ctx Context of the HAL layer
84  * @param config HAL driver configuration
85  * @return True if successfully initialized, false otherwise.
86  */
87 bool twai_hal_init(twai_hal_context_t *hal_ctx, const twai_hal_config_t *config);
88 
89 /**
90  * @brief Deinitialize the TWAI peripheral and HAL context
91  *
92  * Clears any unhandled interrupts and unsets HAL context
93  *
94  * @param hal_ctx Context of the HAL layer
95  */
96 void twai_hal_deinit(twai_hal_context_t *hal_ctx);
97 
98 /**
99  * @brief Configure the TWAI peripheral
100  *
101  * @param hal_ctx Context of the HAL layer
102  * @param t_config Pointer to timing configuration structure
103  * @param f_config Pointer to filter configuration structure
104  * @param intr_mask Mask of interrupts to enable
105  * @param clkout_divider Clock divider value for CLKOUT. Set to -1 to disable CLKOUT
106  */
107 void twai_hal_configure(twai_hal_context_t *hal_ctx, const twai_timing_config_t *t_config, const twai_filter_config_t *f_config, uint32_t intr_mask, uint32_t clkout_divider);
108 
109 /* -------------------------------- Actions --------------------------------- */
110 
111 /**
112  * @brief Start the TWAI peripheral
113  *
114  * Start the TWAI peripheral by configuring its operating mode, then exiting
115  * reset mode so that the TWAI peripheral can participate in bus activities.
116  *
117  * @param hal_ctx Context of the HAL layer
118  * @param mode Operating mode
119  */
120 void twai_hal_start(twai_hal_context_t *hal_ctx, twai_mode_t mode);
121 
122 /**
123  * @brief Stop the TWAI peripheral
124  *
125  * Stop the TWAI peripheral by entering reset mode to stop any bus activity, then
126  * setting the operating mode to Listen Only so that REC is frozen.
127  *
128  * @param hal_ctx Context of the HAL layer
129  */
130 void twai_hal_stop(twai_hal_context_t *hal_ctx);
131 
132 /**
133  * @brief Start bus recovery
134  *
135  * @param hal_ctx Context of the HAL layer
136  */
twai_hal_start_bus_recovery(twai_hal_context_t * hal_ctx)137 static inline void twai_hal_start_bus_recovery(twai_hal_context_t *hal_ctx)
138 {
139     TWAI_HAL_SET_BITS(hal_ctx->state_flags, TWAI_HAL_STATE_FLAG_RECOVERING);
140     twai_ll_exit_reset_mode(hal_ctx->dev);
141 }
142 
143 /**
144  * @brief Get the value of the TX Error Counter
145  *
146  * @param hal_ctx Context of the HAL layer
147  * @return TX Error Counter Value
148  */
twai_hal_get_tec(twai_hal_context_t * hal_ctx)149 static inline uint32_t twai_hal_get_tec(twai_hal_context_t *hal_ctx)
150 {
151     return twai_ll_get_tec((hal_ctx)->dev);
152 }
153 
154 /**
155  * @brief Get the value of the RX Error Counter
156  *
157  * @param hal_ctx Context of the HAL layer
158  * @return RX Error Counter Value
159  */
twai_hal_get_rec(twai_hal_context_t * hal_ctx)160 static inline uint32_t twai_hal_get_rec(twai_hal_context_t *hal_ctx)
161 {
162     return twai_ll_get_rec((hal_ctx)->dev);
163 }
164 
165 /**
166  * @brief Get the RX message count register
167  *
168  * @param hal_ctx Context of the HAL layer
169  * @return RX message count
170  */
171 __attribute__((always_inline))
twai_hal_get_rx_msg_count(twai_hal_context_t * hal_ctx)172 static inline uint32_t twai_hal_get_rx_msg_count(twai_hal_context_t *hal_ctx)
173 {
174     return twai_ll_get_rx_msg_count((hal_ctx)->dev);
175 }
176 
177 /**
178  * @brief Check if the last transmitted frame was successful
179  *
180  * @param hal_ctx Context of the HAL layer
181  * @return True if successful
182  */
183 __attribute__((always_inline))
twai_hal_check_last_tx_successful(twai_hal_context_t * hal_ctx)184 static inline bool twai_hal_check_last_tx_successful(twai_hal_context_t *hal_ctx)
185 {
186     return twai_ll_is_last_tx_successful((hal_ctx)->dev);
187 }
188 
189 /**
190  * @brief Check if certain HAL state flags are set
191  *
192  * The HAL will maintain a record of the controller's state via a set of flags.
193  * These flags are automatically maintained (i.e., set and reset) inside various
194  * HAL function calls. This function checks if certain flags are currently set.
195  *
196  * @param hal_ctx Context of the HAL layer
197  * @param check_flags Bit mask of flags to check
198  * @return True if one or more of the flags in check_flags are set
199  */
200 
twai_hal_check_state_flags(twai_hal_context_t * hal_ctx,uint32_t check_flags)201 static inline bool twai_hal_check_state_flags(twai_hal_context_t *hal_ctx, uint32_t check_flags)
202 {
203     return hal_ctx->state_flags & check_flags;
204 }
205 
206 /* ----------------------------- Event Handling ----------------------------- */
207 
208 /**
209  * @brief Get a bit mask of the events that triggered that triggered an interrupt
210  *
211  * This function should be called at the beginning of an interrupt. This function will do the following:
212  * - Read and clear interrupt register
213  * - Calculate what events have triggered the interrupt
214  * - Respond to low latency interrupt events
215  *      - Bus off: Change to LOM to freeze TEC/REC. Errata 1 Fix
216  *      - Recovery complete: Enter reset mode
217  *      - Clear ECC and ALC so that their interrupts are re-armed
218  * - Update HAL state flags based on interrupts that have occurred.
219  * - For the ESP32, check for errata conditions. If a HW reset is required, this function
220  *   will set the TWAI_HAL_EVENT_NEED_PERIPH_RESET event.
221  *
222  * @param hal_ctx Context of the HAL layer
223  * @return Bit mask of events that have occurred
224  */
225 uint32_t twai_hal_get_events(twai_hal_context_t *hal_ctx);
226 
227 /* ------------------------------- TX and RX -------------------------------- */
228 
229 /**
230  * @brief Format a TWAI Frame
231  *
232  * This function takes a TWAI message structure (containing ID, DLC, data, and
233  * flags) and formats it to match the layout of the TX frame buffer.
234  *
235  * @param message Pointer to TWAI message
236  * @param frame Pointer to empty frame structure
237  */
twai_hal_format_frame(const twai_message_t * message,twai_hal_frame_t * frame)238 static inline void twai_hal_format_frame(const twai_message_t *message, twai_hal_frame_t *frame)
239 {
240     //Direct call to ll function
241     twai_ll_format_frame_buffer(message->identifier, message->data_length_code, message->data,
242                                 message->flags, frame);
243 }
244 
245 /**
246  * @brief Parse a TWAI Frame
247  *
248  * This function takes a TWAI frame (in the format of the RX frame buffer) and
249  * parses it to a TWAI message (containing ID, DLC, data and flags).
250  *
251  * @param frame Pointer to frame structure
252  * @param message Pointer to empty message structure
253  */
twai_hal_parse_frame(twai_hal_frame_t * frame,twai_message_t * message)254 static inline void twai_hal_parse_frame(twai_hal_frame_t *frame, twai_message_t *message)
255 {
256     //Direct call to ll function
257     twai_ll_parse_frame_buffer(frame, &message->identifier, &message->data_length_code,
258                                message->data, &message->flags);
259 }
260 
261 /**
262  * @brief Copy a frame into the TX buffer and transmit
263  *
264  * This function copies a formatted TX frame into the TX buffer, and the
265  * transmit by setting the correct transmit command (e.g. normal, single shot,
266  * self RX) in the command register.
267  *
268  * @param hal_ctx Context of the HAL layer
269  * @param tx_frame Pointer to structure containing formatted TX frame
270  */
271 void twai_hal_set_tx_buffer_and_transmit(twai_hal_context_t *hal_ctx, twai_hal_frame_t *tx_frame);
272 
273 /**
274  * @brief Copy a frame from the RX buffer and release
275  *
276  * This function copies a frame from the RX buffer, then release the buffer (so
277  * that it loads the next frame in the RX FIFO). False is returned under the
278  * following conditions:
279  * - On the ESP32S2, false is returned if the RX buffer points to an overrun frame
280  * - On the ESP32, false is returned if the RX buffer points to the first overrun
281  * frame in the RX FIFO
282  *
283  * @param hal_ctx Context of the HAL layer
284  * @param rx_frame Pointer to structure to store RX frame
285  * @return True if a valid frame was copied and released. False if overrun.
286  */
287 __attribute__((always_inline))
twai_hal_read_rx_buffer_and_clear(twai_hal_context_t * hal_ctx,twai_hal_frame_t * rx_frame)288 static inline bool twai_hal_read_rx_buffer_and_clear(twai_hal_context_t *hal_ctx, twai_hal_frame_t *rx_frame)
289 {
290 #ifdef SOC_TWAI_SUPPORTS_RX_STATUS
291     if (twai_ll_get_status(hal_ctx->dev) & TWAI_LL_STATUS_MS) {
292         //Release the buffer for this particular overrun frame
293         twai_ll_set_cmd_release_rx_buffer(hal_ctx->dev);
294         return false;
295     }
296 #else
297     if (twai_ll_get_status(hal_ctx->dev) & TWAI_LL_STATUS_DOS) {
298         //No need to release RX buffer as we'll be releaseing all RX frames in continuously later
299         return false;
300     }
301 #endif
302     twai_ll_get_rx_buffer(hal_ctx->dev, rx_frame);
303     twai_ll_set_cmd_release_rx_buffer(hal_ctx->dev);
304     return true;
305 }
306 
307 #ifndef SOC_TWAI_SUPPORTS_RX_STATUS
308 /**
309  * @brief Clear the RX FIFO of overrun frames
310  *
311  * This function will clear the RX FIFO of overrun frames. The RX message count
312  * will return to 0 after calling this function.
313  *
314  * @param hal_ctx Context of the HAL layer
315  * @return Number of overrun messages cleared from RX FIFO
316  */
317 __attribute__((always_inline))
twai_hal_clear_rx_fifo_overrun(twai_hal_context_t * hal_ctx)318 static inline uint32_t twai_hal_clear_rx_fifo_overrun(twai_hal_context_t *hal_ctx)
319 {
320     uint32_t msg_cnt = 0;
321     //Note: Need to keep polling th rx message counter incase another message arrives whilst clearing
322     while (twai_ll_get_rx_msg_count(hal_ctx->dev) > 0) {
323         twai_ll_set_cmd_release_rx_buffer(hal_ctx->dev);
324         msg_cnt++;
325     }
326     //Set a clear data overrun command to clear the data overrun status bit
327     twai_ll_set_cmd_clear_data_overrun(hal_ctx->dev);
328 
329     return msg_cnt;
330 }
331 #endif  //SOC_TWAI_SUPPORTS_RX_STATUS
332 
333 /* --------------------------- Errata Workarounds --------------------------- */
334 
335 #if defined(CONFIG_TWAI_ERRATA_FIX_RX_FRAME_INVALID) || defined(CONFIG_TWAI_ERRATA_FIX_RX_FIFO_CORRUPT)
336 /**
337  * @brief Prepare the peripheral for a HW reset
338  *
339  * Some HW erratas will require the peripheral be reset. This function should be
340  * called if twai_hal_get_events() returns the TWAI_HAL_EVENT_NEED_PERIPH_RESET event.
341  * Preparing for a reset involves the following:
342  * - Checking if a reset will cancel a TX. If so, mark that we need to retry that message after the reset
343  * - Save how many RX messages were lost due to this reset
344  * - Enter reset mode to stop any the peripheral from receiving any bus activity
345  * - Store the regsiter state of the peripheral
346  *
347  * @param hal_ctx Context of the HAL layer
348  */
349 void twai_hal_prepare_for_reset(twai_hal_context_t *hal_ctx);
350 
351 /**
352  * @brief Recover the peripheral after a HW reset
353  *
354  * This should be called after calling twai_hal_prepare_for_reset() and then
355  * executing the HW reset.
356  * Recovering the peripheral from a HW reset involves the following:
357  * - Restoring the previously saved register state
358  * - Exiting reset mode to allow receiving of bus activity
359  * - Retrying any TX message that was cancelled by the HW reset
360  *
361  * @param hal_ctx Context of the HAL layer
362  */
363 void twai_hal_recover_from_reset(twai_hal_context_t *hal_ctx);
364 
365 /**
366  * @brief Get how many RX messages were lost due to HW reset
367  *
368  * @note The number of lost RX messages are saved during twai_hal_prepare_for_reset()
369  *
370  * @param hal_ctx Context of the HAL layer
371  * @return uint32_t Number of RX messages lost due to HW reset
372  */
373 __attribute__((always_inline))
twai_hal_get_reset_lost_rx_cnt(twai_hal_context_t * hal_ctx)374 static inline uint32_t twai_hal_get_reset_lost_rx_cnt(twai_hal_context_t *hal_ctx)
375 {
376     return hal_ctx->rx_msg_cnt_save;
377 }
378 #endif  //defined(CONFIG_TWAI_ERRATA_FIX_RX_FRAME_INVALID) || defined(CONFIG_TWAI_ERRATA_FIX_RX_FIFO_CORRUPT)
379 
380 #ifdef __cplusplus
381 }
382 #endif
383