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