libxr  1.0
Want to be the best embedded framework
Loading...
Searching...
No Matches
ch32_usbcan_shared.hpp
1#pragma once
2#include <atomic>
3#include <cstdint>
4
5#include "libxr_def.hpp"
6#include DEF2STR(LIBXR_CH32_CONFIG_FILE)
7
8namespace LibXR::CH32UsbCanShared
9{
13using IrqFn = void (*)();
14
15inline std::atomic_bool usb_inited{false};
16inline std::atomic_bool can1_inited{false};
17
18static constexpr uint16_t USBD_PMA_BYTES_SOLO = 512;
19static constexpr uint16_t USBD_PMA_BYTES_WITHCAN = 384;
20
21// USB/CAN 共享中断拓扑的编译期能力标志。
22// Build-time capability flags for USB/CAN shared interrupt topology.
23#if defined(RCC_APB1Periph_USB)
24inline constexpr bool K_HAS_USB_DEV_FS = true;
25#else
26inline constexpr bool K_HAS_USB_DEV_FS = false;
27#endif
28
29#if defined(CAN1)
30inline constexpr bool K_HAS_CAN1 = true;
31#else
32inline constexpr bool K_HAS_CAN1 = false;
33#endif
34
35#if defined(CAN2)
36inline constexpr bool K_HAS_CAN2 = true;
37#else
38inline constexpr bool K_HAS_CAN2 = false;
39#endif
40
41inline constexpr bool K_SINGLE_CAN1 = K_HAS_CAN1 && !K_HAS_CAN2;
42inline constexpr bool K_USB_CAN_SHARE = K_HAS_USB_DEV_FS && K_SINGLE_CAN1;
43
44inline constexpr bool usb_can_share_enabled() { return K_USB_CAN_SHARE; }
45
46inline uint16_t usb_pma_limit_bytes()
47{
48 if constexpr (!K_USB_CAN_SHARE)
49 {
50 return USBD_PMA_BYTES_SOLO;
51 }
52
53 return can1_inited.load(std::memory_order_acquire) ? USBD_PMA_BYTES_WITHCAN
54 : USBD_PMA_BYTES_SOLO;
55}
56
57inline std::atomic<IrqFn> usb_irq_cb{nullptr};
58inline std::atomic<IrqFn> can1_rx0_cb{nullptr};
59inline std::atomic<IrqFn> can1_tx_cb{nullptr};
60
61inline void register_usb_irq(IrqFn fn)
62{
63 usb_irq_cb.store(fn, std::memory_order_release);
64}
65
66inline void register_can1_rx0(IrqFn fn)
67{
68 if constexpr (K_USB_CAN_SHARE)
69 {
70 can1_rx0_cb.store(fn, std::memory_order_release);
71 }
72 else
73 {
74 (void)fn;
75 }
76}
77
78inline void register_can1_tx(IrqFn fn)
79{
80 if constexpr (K_USB_CAN_SHARE)
81 {
82 can1_tx_cb.store(fn, std::memory_order_release);
83 }
84 else
85 {
86 (void)fn;
87 }
88}
89
90inline bool can1_active()
91{
92 if constexpr (!K_USB_CAN_SHARE)
93 {
94 return false;
95 }
96 return (can1_rx0_cb.load(std::memory_order_acquire) != nullptr) ||
97 (can1_tx_cb.load(std::memory_order_acquire) != nullptr);
98}
99} // namespace LibXR::CH32UsbCanShared