ESPHome 2026.1.0-dev
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
17void Logger::loop() {
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, size_t len) {
67 // Single write with newline already in buffer (added by caller)
68#ifdef CONFIG_PRINTK
69 k_str_out(const_cast<char *>(msg), len);
70#endif
71 if (this->uart_dev_ == nullptr) {
72 return;
73 }
74 for (size_t i = 0; i < len; ++i) {
75 uart_poll_out(this->uart_dev_, msg[i]);
76 }
77}
78
79const LogString *Logger::get_uart_selection_() {
80 switch (this->uart_) {
82 return LOG_STR("UART0");
84 return LOG_STR("UART1");
85#ifdef USE_LOGGER_USB_CDC
87 return LOG_STR("USB_CDC");
88#endif
89 default:
90 return LOG_STR("UNKNOWN");
91 }
92}
93
94} // namespace esphome::logger
95
96#endif
UARTSelection uart_
Definition logger.h:353
const LogString * get_uart_selection_()
void loop() override
Definition logger.cpp:183
void pre_setup()
Set up this component.
void write_msg_(const char *msg, size_t len)
const device * uart_dev_
Definition logger.h:323
@ UART_SELECTION_USB_CDC
Definition logger.h:137
@ UART_SELECTION_UART0
Definition logger.h:128
@ UART_SELECTION_UART1
Definition logger.h:132
Logger * global_logger
Definition logger.cpp:297
std::string size_t len
Definition helpers.h:533
Application App
Global storage of Application pointer - only one Application can exist.