5#include "ch32_can_caps.hpp"
7namespace LibXR::CH32UsbCanShared
12using IrqFn = void (*)();
14inline std::atomic_bool usb_inited{
false};
15inline std::atomic_bool can1_inited{
false};
16inline std::atomic_bool can2_inited{
false};
19inline std::atomic_bool usb_pma_configured{
false};
21static constexpr uint16_t USBD_PMA_BYTES_SOLO = 512;
22static constexpr uint16_t USBD_PMA_BYTES_WITHCAN = 384;
23static constexpr uint16_t USBD_PMA_BYTES_WITHCAN2 = 256;
27#if defined(RCC_APB1Periph_USB)
28inline constexpr bool K_HAS_USB_DEV_FS =
true;
30inline constexpr bool K_HAS_USB_DEV_FS =
false;
34inline constexpr bool K_HAS_CAN1 =
true;
36inline constexpr bool K_HAS_CAN1 =
false;
39#if LIBXR_CH32_HAS_CAN2
40inline constexpr bool K_HAS_CAN2 =
true;
42inline constexpr bool K_HAS_CAN2 =
false;
45inline constexpr bool K_SINGLE_CAN1 = K_HAS_CAN1 && !K_HAS_CAN2;
48inline constexpr bool K_USB_CAN_IRQ_SHARE = K_HAS_USB_DEV_FS && K_HAS_CAN1;
51inline constexpr bool K_USB_CAN_SHARE = K_HAS_USB_DEV_FS && K_HAS_CAN1;
53inline constexpr bool usb_can_irq_share_enabled() {
return K_USB_CAN_IRQ_SHARE; }
54inline constexpr bool usb_can_share_enabled() {
return K_USB_CAN_SHARE; }
56inline uint16_t usb_pma_limit_bytes()
58 if constexpr (!K_USB_CAN_SHARE)
60 return USBD_PMA_BYTES_SOLO;
65 if constexpr (K_HAS_CAN2)
67 if (can2_inited.load(std::memory_order_acquire))
69 return USBD_PMA_BYTES_WITHCAN2;
72 return can1_inited.load(std::memory_order_acquire) ? USBD_PMA_BYTES_WITHCAN
73 : USBD_PMA_BYTES_SOLO;
76inline std::atomic<IrqFn> usb_irq_cb{
nullptr};
77inline std::atomic<IrqFn> can1_rx0_cb{
nullptr};
78inline std::atomic<IrqFn> can1_tx_cb{
nullptr};
82void register_usb_irq(IrqFn fn);
83void register_can1_rx0(IrqFn fn);
84void register_can1_tx(IrqFn fn);
86inline bool can1_active()
88 if constexpr (!K_USB_CAN_IRQ_SHARE)
92 return (can1_rx0_cb.load(std::memory_order_acquire) !=
nullptr) ||
93 (can1_tx_cb.load(std::memory_order_acquire) !=
nullptr);