ESPHome 2026.2.4
Loading...
Searching...
No Matches
logger_zephyr.cpp
Go to the documentation of this file.
1#ifdef USE_ZEPHYR
2
4#include "esphome/core/log.h"
5#include "logger.h"
6
7#include <zephyr/device.h>
8#include <zephyr/drivers/uart.h>
9#include <zephyr/sys/printk.h>
10#include <zephyr/usb/usb_device.h>
11
12namespace esphome::logger {
13
14static const char *const TAG = "logger";
15
16#ifdef USE_LOGGER_USB_CDC
18 if (this->uart_ != UART_SELECTION_USB_CDC || this->uart_dev_ == nullptr) {
19 return;
20 }
21 static bool opened = false;
22 uint32_t dtr = 0;
23 uart_line_ctrl_get(this->uart_dev_, UART_LINE_CTRL_DTR, &dtr);
24
25 /* Poll if the DTR flag was set, optional */
26 if (opened == dtr) {
27 return;
28 }
29
30 if (!opened) {
32 }
33 opened = !opened;
34}
35#endif
36
37void Logger::pre_setup() {
38 if (this->baud_rate_ > 0) {
39 static const struct device *uart_dev = nullptr;
40 switch (this->uart_) {
42 uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(uart0));
43 break;
45 uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(uart1));
46 break;
47#ifdef USE_LOGGER_USB_CDC
49 uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(cdc_acm_uart0));
50 if (device_is_ready(uart_dev)) {
51 usb_enable(nullptr);
52 }
53 break;
54#endif
55 }
56 if (!device_is_ready(uart_dev)) {
57 ESP_LOGE(TAG, "%s is not ready.", LOG_STR_ARG(get_uart_selection_()));
58 } else {
59 this->uart_dev_ = uart_dev;
60 }
61 }
62 global_logger = this;
63 ESP_LOGI(TAG, "Log initialized");
64}
65
66void HOT Logger::write_msg_(const char *msg, uint16_t len) {
67 // Single write with newline already in buffer (added by caller)
68#ifdef CONFIG_PRINTK
69 // Requires the debug component and an active SWD connection.
70 // It is used for pyocd rtt -t nrf52840
71 printk("%.*s", static_cast<int>(len), msg);
72#endif
73 if (this->uart_dev_ == nullptr) {
74 return;
75 }
76 for (uint16_t i = 0; i < len; ++i) {
77 uart_poll_out(this->uart_dev_, msg[i]);
78 }
79}
80
81const LogString *Logger::get_uart_selection_() {
82 switch (this->uart_) {
84 return LOG_STR("UART0");
86 return LOG_STR("UART1");
87#ifdef USE_LOGGER_USB_CDC
89 return LOG_STR("USB_CDC");
90#endif
91 default:
92 return LOG_STR("UNKNOWN");
93 }
94}
95
96} // namespace esphome::logger
97
98#endif
UARTSelection uart_
Definition logger.h:358
void write_msg_(const char *msg, uint16_t len)
const LogString * get_uart_selection_()
void pre_setup()
Set up this component.
const device * uart_dev_
Definition logger.h:319
@ UART_SELECTION_USB_CDC
Definition logger.h:117
@ UART_SELECTION_UART0
Definition logger.h:108
@ UART_SELECTION_UART1
Definition logger.h:112
Logger * global_logger
Definition logger.cpp:279
std::string size_t len
Definition helpers.h:692
Application App
Global storage of Application pointer - only one Application can exist.