ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
cdc_acm.cpp
Go to the documentation of this file.
1#include "cdc_acm.h"
2#if defined(USE_ZEPHYR_CDC_ACM_RATE_CALLBACK)
4#include <array>
5#include <zephyr/drivers/uart.h>
6#ifndef CONFIG_USB_DEVICE_STACK_NEXT
7#include <zephyr/drivers/uart/cdc_acm.h>
8#endif
9
10#define DEVICE_AND_COMMA(node_id) DEVICE_DT_GET(node_id),
11
12namespace esphome::zephyr {
13
14namespace {
15constexpr std::array<const device *, DT_NUM_INST_STATUS_OKAY(zephyr_cdc_acm_uart)> CDC_DEVICES{
16 DT_FOREACH_STATUS_OKAY(zephyr_cdc_acm_uart, DEVICE_AND_COMMA)};
17
18// USB starts in the logger's pre_setup(), before App exists, so nothing is posted until start_(). Reading a rate
19// and posting it under one lock keeps the posts in the order the rates were read. The legacy stack reports a rate
20// as the host sets it; the new stack queues a message without the rate, so when the host changes the rate again
21// before that message is delivered, only the latest rate is posted.
22Mutex rate_lock; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
23bool started = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
24} // namespace
25
27 LockGuard guard(rate_lock);
28 started = true;
29 for (const device *dev : CDC_DEVICES) {
30#ifndef CONFIG_USB_DEVICE_STACK_NEXT
31 // The new stack reports rates with a USB device message, which usb_device.cpp passes to rate_changed()
32 cdc_acm_dte_rate_callback_set(dev, [](const device *dev, uint32_t) { CdcAcm::rate_changed(dev); });
33#endif
34 post_rate(dev);
35 }
36}
37
38void CdcAcm::rate_changed(const device *dev) {
39 LockGuard guard(rate_lock);
40 if (started)
41 post_rate(dev);
42}
43
44void CdcAcm::post_rate(const device *dev) {
45 uint32_t rate = 0;
46 if (uart_line_ctrl_get(dev, UART_LINE_CTRL_BAUD_RATE, &rate) != 0)
47 return;
48 // 0 ms timeouts run on the main loop in the order they are posted
49 App.scheduler.set_timeout(static_cast<Component *>(nullptr), static_cast<const char *>(nullptr), 0,
50 [dev, rate]() { rate_callbacks.call(dev, rate); });
51}
52
53} // namespace esphome::zephyr
54
55#endif
Helper class that wraps a mutex with a RAII-style API.
Definition helpers.h:2494
Mutex implementation, with API based on the unavailable std::mutex.
Definition helpers.h:2455
static CallbackManager< void(const device *, uint32_t)> rate_callbacks
Definition cdc_acm.h:29
static void post_rate(const device *dev)
Definition cdc_acm.cpp:44
static void start()
Definition cdc_acm.cpp:26
static void rate_changed(const device *dev)
Called by the USB driver, from its own thread, after the host set the bit rate of dev.
Definition cdc_acm.cpp:38
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t