mirror of
https://github.com/esphome/esphome.git
synced 2026-11-17 18:46:08 +00:00
Compare commits
51
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
19d776f84f | ||
|
|
f5c761cc81 | ||
|
|
38448e1262 | ||
|
|
291c09da90 | ||
|
|
bc2bafe845 | ||
|
|
1bcc27f1c2 | ||
|
|
34b24d0cf5 | ||
|
|
e27614fda3 | ||
|
|
8426d04138 | ||
|
|
641c8bedc9 | ||
|
|
4a39ca1b71 | ||
|
|
4a218fdbd8 | ||
|
|
c09e7d0171 | ||
|
|
3d02285028 | ||
|
|
ff249d9d7e | ||
|
|
d8fc1cd214 | ||
|
|
1e030b7371 | ||
|
|
3b113f2c39 | ||
|
|
73468592a9 | ||
|
|
a1b456150d | ||
|
|
865a883abb | ||
|
|
357a6717c8 | ||
|
|
bcb434e05e | ||
|
|
fb65fcc5f6 | ||
|
|
b5e379a9d4 | ||
|
|
05286dfd5d | ||
|
|
36184f09aa | ||
|
|
449933891e | ||
|
|
a5bfa6dac3 | ||
|
|
5aaa5b0552 | ||
|
|
9ab090a818 | ||
|
|
28645445e2 | ||
|
|
02d0bb56a6 | ||
|
|
b667e442a6 | ||
|
|
b0f91221fd | ||
|
|
ecc8778131 | ||
|
|
fd7a13e82d | ||
|
|
a2e068579c | ||
|
|
00ac20b3e7 | ||
|
|
630cef640a | ||
|
|
eecc278683 | ||
|
|
b4cbcb25fa | ||
|
|
d46e1c4504 | ||
|
|
744eeae81f | ||
|
|
f5ec3faf07 | ||
|
|
c15b1fad7e | ||
|
|
410cef8725 | ||
|
|
8ca094dab6 | ||
|
|
59b889925a | ||
|
|
d1158860db | ||
|
|
3f3da41c62 |
No files matched your search
@@ -515,18 +515,12 @@ void CC1101Component::dump_config() {
|
||||
}
|
||||
|
||||
void CC1101Component::begin_tx() {
|
||||
this->wake_up();
|
||||
// Read the mode before the PKTCTRL0 write below overwrites it in state_
|
||||
const bool packet_mode = this->state_.PKT_FORMAT == static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO);
|
||||
// Ensure Packet Format is 3 (Async Serial)
|
||||
this->write_(Register::PKTCTRL0, 0x32);
|
||||
if (this->state_.PKT_FORMAT == static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO)) {
|
||||
ESP_LOGW(TAG, "begin_tx is for async serial mode; use send_packet in packet mode");
|
||||
return;
|
||||
}
|
||||
ESP_LOGV(TAG, "Beginning TX sequence");
|
||||
if (this->gdo0_pin_ != nullptr) {
|
||||
// setup() only attaches the interrupt in packet mode. In async serial mode the pin may be
|
||||
// shared with remote_receiver, and detaching here would remove the receiver's interrupt.
|
||||
if (packet_mode) {
|
||||
this->gdo0_pin_->detach_interrupt();
|
||||
}
|
||||
this->gdo0_pin_->pin_mode(gpio::FLAG_OUTPUT);
|
||||
}
|
||||
// Transition through IDLE to bypass CCA (Clear Channel Assessment) which can
|
||||
|
||||
@@ -94,7 +94,6 @@ UART_SELECTION_RP2040 = [USB_CDC, UART0, UART1]
|
||||
|
||||
UART_SELECTION_NRF52 = [USB_CDC, UART0]
|
||||
|
||||
# Read by device-builder
|
||||
HARDWARE_UART_TO_UART_SELECTION = {
|
||||
UART0: logger_ns.UART_SELECTION_UART0,
|
||||
UART0_SWAP: logger_ns.UART_SELECTION_UART0_SWAP,
|
||||
@@ -539,17 +538,17 @@ async def to_code(config: ConfigType) -> None:
|
||||
cg.add(log.set_boot_log_level(tag, LOG_LEVELS[log_level]))
|
||||
if CORE.is_esp32 or CORE.is_host:
|
||||
cg.add(log.create_pthread_key())
|
||||
if (hardware_uart := config.get(CONF_HARDWARE_UART)) is not None:
|
||||
cg.add_define(f"USE_LOGGER_UART_SELECTION_{hardware_uart}")
|
||||
cg.add_define(
|
||||
"ESPHOME_LOGGER_UART_SELECTION",
|
||||
cg.RawExpression(f"logger::UART_SELECTION_{hardware_uart}"),
|
||||
)
|
||||
# ESP8266 without serial logging never opens a port
|
||||
cg.add_define(
|
||||
"ESPHOME_LOGGER_UART_NAME",
|
||||
"NONE" if CORE.is_esp8266 and baud_rate == 0 else hardware_uart,
|
||||
)
|
||||
# set_uart_selection() must be called before pre_setup() because
|
||||
# pre_setup() switches on uart_ to decide which hardware to initialize
|
||||
# (e.g. UART0 vs USB_SERIAL_JTAG). Without this, uart_ is still the
|
||||
# default UART_SELECTION_UART0 and the wrong hardware gets initialized.
|
||||
# uart_ is UART0 in C++ except on LibreTiny where it is DEFAULT; skip the
|
||||
# setter when the config matches it.
|
||||
cpp_default_uart = DEFAULT if CORE.is_libretiny else UART0
|
||||
if (
|
||||
hardware_uart := config.get(CONF_HARDWARE_UART)
|
||||
) is not None and hardware_uart != cpp_default_uart:
|
||||
cg.add(log.set_uart_selection(HARDWARE_UART_TO_UART_SELECTION[hardware_uart]))
|
||||
# pre_setup() sets global_logger and must run before any other code
|
||||
# that may call ESP_LOG* (e.g. setup_preferences contains ESP_LOGVV).
|
||||
cg.add(log.pre_setup())
|
||||
@@ -646,6 +645,7 @@ async def _late_logger_init(config: ConfigType) -> None:
|
||||
add_idf_sdkconfig_option("CONFIG_ESP_CONSOLE_USB_CDC", True)
|
||||
elif config[CONF_HARDWARE_UART] == USB_SERIAL_JTAG:
|
||||
add_idf_sdkconfig_option("CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG", True)
|
||||
cg.add_define("USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG")
|
||||
# Log V2 formats centrally in esp_log() (~4KB flash, ~180B RAM). 6.1
|
||||
# adds CONSTRAINED_ENV_SAFE=n, keeping early/DRAM logs on
|
||||
# esp_rom_printf instead of pulling ~1.2KB esp_rom_vprintf into IRAM.
|
||||
@@ -663,12 +663,10 @@ async def _late_logger_init(config: ConfigType) -> None:
|
||||
# --wrap: a strong definition collides; see logger_esp32.cpp
|
||||
cg.add_build_flag("-Wl,--wrap=esp_log_format")
|
||||
# Zephyr polls the USB port only when it logs there
|
||||
if (
|
||||
CORE.using_zephyr
|
||||
and has_serial_logging
|
||||
and config[CONF_HARDWARE_UART] == USB_CDC
|
||||
if config.get(CONF_HARDWARE_UART) == USB_CDC and (
|
||||
has_serial_logging or not CORE.is_nrf52
|
||||
):
|
||||
cg.add_define("USE_LOGGER_ZEPHYR_CDC_LOOP")
|
||||
cg.add_define("USE_LOGGER_UART_SELECTION_USB_CDC")
|
||||
# Define platform support flags for components that need auto-detection
|
||||
try:
|
||||
uart_selection(USB_SERIAL_JTAG)
|
||||
@@ -886,15 +884,6 @@ def request_logger_level_listeners() -> None:
|
||||
_request_log_listener_slot = cg.slot_counter("ESPHOME_LOG_MAX_LISTENERS")
|
||||
|
||||
|
||||
def request_console() -> None:
|
||||
"""Compile in Logger::console_read() and console_write(); call from to_code.
|
||||
|
||||
On ESP32 a USB_CDC logger only has a console where ESP-IDF sets CONFIG_ESP_CONSOLE_USB_CDC (targets with
|
||||
USB OTG); elsewhere, such as the C3, C6 or H2, both do nothing. Host and Zephyr have no console API.
|
||||
"""
|
||||
cg.add_define("USE_LOGGER_CONSOLE")
|
||||
|
||||
|
||||
def request_log_listener() -> None:
|
||||
"""Reserve a log listener slot; call once per listener from to_code."""
|
||||
cg.add_define("USE_LOG_LISTENERS")
|
||||
|
||||
@@ -248,10 +248,10 @@ Logger::Logger(uint32_t baud_rate) : baud_rate_(baud_rate) {
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || defined(USE_LOGGER_ZEPHYR_CDC_LOOP)
|
||||
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || (defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
|
||||
void Logger::loop() {
|
||||
this->process_messages_();
|
||||
#ifdef USE_LOGGER_ZEPHYR_CDC_LOOP
|
||||
#if defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
|
||||
this->cdc_loop_();
|
||||
#endif
|
||||
}
|
||||
@@ -278,7 +278,7 @@ void Logger::process_messages_() {
|
||||
}
|
||||
}
|
||||
// Zephyr with USB CDC keeps the loop running for cdc_loop_()
|
||||
#ifndef USE_LOGGER_ZEPHYR_CDC_LOOP
|
||||
#if !(defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
|
||||
else {
|
||||
// A concurrent enable_loop_soon_any_context() still wakes the next iteration
|
||||
this->disable_loop();
|
||||
@@ -371,25 +371,6 @@ static const LogString *get_log_level_str(uint8_t level) {
|
||||
return LogLevelStrings::get_log_str(level, LogLevelStrings::LAST_INDEX);
|
||||
}
|
||||
|
||||
#ifndef USE_HOST
|
||||
const LogString *Logger::get_uart_selection_() {
|
||||
#ifdef USE_LOGGER_UART_SELECTION_DEFAULT
|
||||
// LibreTiny resolves DEFAULT to the board's port only when serial logging is on
|
||||
if (this->baud_rate_ > 0) {
|
||||
switch (this->get_uart()) {
|
||||
case UART_SELECTION_UART0:
|
||||
return LOG_STR("UART0");
|
||||
case UART_SELECTION_UART1:
|
||||
return LOG_STR("UART1");
|
||||
default:
|
||||
return LOG_STR("UART2");
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return LOG_STR(ESPHOME_LOGGER_UART_NAME);
|
||||
}
|
||||
#endif
|
||||
|
||||
void Logger::dump_config() {
|
||||
ESP_LOGCONFIG(TAG,
|
||||
"Logger:\n"
|
||||
|
||||
@@ -124,9 +124,6 @@ enum UARTSelection : uint8_t {
|
||||
UART_SELECTION_UART0_SWAP,
|
||||
#endif // USE_ESP8266
|
||||
};
|
||||
|
||||
// The port chosen by hardware_uart, fixed at build time
|
||||
static constexpr UARTSelection CONFIGURED_UART_SELECTION = ESPHOME_LOGGER_UART_SELECTION;
|
||||
#endif // USE_ESP32 || USE_ESP8266 || USE_RP2 || USE_LIBRETINY || USE_ZEPHYR
|
||||
|
||||
/**
|
||||
@@ -149,7 +146,7 @@ static constexpr UARTSelection CONFIGURED_UART_SELECTION = ESPHOME_LOGGER_UART_S
|
||||
class Logger final : public Component {
|
||||
public:
|
||||
explicit Logger(uint32_t baud_rate);
|
||||
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || defined(USE_LOGGER_ZEPHYR_CDC_LOOP)
|
||||
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || (defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
|
||||
void loop() override;
|
||||
#endif
|
||||
#if defined(USE_RP2_CRASH_HANDLER) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
|
||||
@@ -163,11 +160,11 @@ class Logger final : public Component {
|
||||
#endif
|
||||
#ifdef USE_ESP32
|
||||
/// UART_NUM_0 when logging to USB
|
||||
constexpr uart_port_t get_uart_num() const {
|
||||
uart_port_t get_uart_num() const {
|
||||
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC) || defined(USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG)
|
||||
return UART_NUM_0;
|
||||
#else
|
||||
return static_cast<uart_port_t>(CONFIGURED_UART_SELECTION);
|
||||
return static_cast<uart_port_t>(this->uart_);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
@@ -175,35 +172,9 @@ class Logger final : public Component {
|
||||
void create_pthread_key() { pthread_key_create(&this->log_recursion_key_, nullptr); }
|
||||
#endif
|
||||
#if defined(USE_ESP32) || defined(USE_ESP8266) || defined(USE_RP2) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
|
||||
void set_uart_selection(UARTSelection uart_selection) { this->uart_ = uart_selection; }
|
||||
/// Get the UART used by the logger.
|
||||
#ifdef USE_LIBRETINY
|
||||
// DEFAULT resolves to the board's default port
|
||||
constexpr UARTSelection get_uart() const {
|
||||
return CONFIGURED_UART_SELECTION == UART_SELECTION_DEFAULT ? static_cast<UARTSelection>(LT_UART_DEFAULT_SERIAL + 1)
|
||||
: CONFIGURED_UART_SELECTION;
|
||||
}
|
||||
#else
|
||||
constexpr UARTSelection get_uart() const { return CONFIGURED_UART_SELECTION; }
|
||||
#endif
|
||||
#endif
|
||||
#ifdef USE_LOGGER_CONSOLE
|
||||
// Raw bytes on the console port, without log framing; request with logger.request_console()
|
||||
// console_write() returns the bytes written: a UART write blocks until all are queued, but a USB write can stop
|
||||
// short when the host is not reading (USB Serial/JTAG gives up after 20 ms)
|
||||
#if defined(USE_ARDUINO) && !defined(USE_ESP32)
|
||||
size_t console_write(const uint8_t *data, size_t len) { return this->hw_serial_->write(data, len); }
|
||||
bool console_read(uint8_t &byte) {
|
||||
int c = this->hw_serial_->read();
|
||||
if (c < 0)
|
||||
return false;
|
||||
byte = c;
|
||||
return true;
|
||||
}
|
||||
#elif defined(USE_ESP32)
|
||||
size_t console_write(const uint8_t *data, size_t len);
|
||||
/// Non-blocking read of one byte; false if none is waiting.
|
||||
bool console_read(uint8_t &byte);
|
||||
#endif
|
||||
UARTSelection get_uart() const { return this->uart_; }
|
||||
#endif
|
||||
|
||||
/// Set the default log level for this logger.
|
||||
@@ -280,7 +251,7 @@ class Logger final : public Component {
|
||||
void log_vprintf_non_main_thread_(uint8_t level, const char *tag, int line, const char *format, va_list args,
|
||||
const char *thread_name);
|
||||
#endif
|
||||
#ifdef USE_LOGGER_ZEPHYR_CDC_LOOP
|
||||
#if defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
|
||||
void cdc_loop_();
|
||||
#endif
|
||||
void process_messages_();
|
||||
@@ -440,6 +411,10 @@ class Logger final : public Component {
|
||||
bool boot_log_done_{false}; // Set on first replay; stops further capture
|
||||
#endif
|
||||
uint8_t current_level_{ESPHOME_LOG_LEVEL_VERY_VERBOSE};
|
||||
#if defined(USE_ESP32) || defined(USE_ESP8266) || defined(USE_RP2) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
|
||||
// 0 is UART0, or DEFAULT on LibreTiny; must match cpp_default_uart in __init__.py
|
||||
UARTSelection uart_{};
|
||||
#endif
|
||||
bool main_task_recursion_guard_{false}; // Guards tx_buffer_ on the main loop
|
||||
#ifdef USE_LIBRETINY
|
||||
bool non_main_task_recursion_guard_{false}; // Shared guard for all non-main tasks on LibreTiny
|
||||
|
||||
@@ -17,10 +17,6 @@
|
||||
#include <driver/usb_serial_jtag_vfs.h>
|
||||
#endif
|
||||
#endif
|
||||
// The logger accepts USB_CDC on targets without USB OTG (C3, C6, H2, ...), where IDF has no CDC console
|
||||
#if defined(USE_LOGGER_CONSOLE) && defined(USE_LOGGER_UART_SELECTION_USB_CDC) && defined(CONFIG_ESP_CONSOLE_USB_CDC)
|
||||
#include <esp_private/usb_console.h>
|
||||
#endif
|
||||
#if defined(CONFIG_PM_ENABLE) && defined(CONFIG_FREERTOS_USE_TICKLESS_IDLE) && \
|
||||
(ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0))
|
||||
#include "esp_sleep.h"
|
||||
@@ -77,7 +73,6 @@ static void init_usb_serial_jtag() {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !defined(USE_LOGGER_UART_SELECTION_USB_CDC) && !defined(USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG)
|
||||
static void init_uart(uart_port_t uart_num, uint32_t baud_rate, int tx_buffer_size) {
|
||||
uart_config_t uart_config{};
|
||||
uart_config.baud_rate = (int) baud_rate;
|
||||
@@ -102,7 +97,6 @@ static void init_uart(uart_port_t uart_num, uint32_t baud_rate, int tx_buffer_si
|
||||
esp_sleep_set_console_uart_handling_mode(ESP_SLEEP_ALWAYS_FLUSH_UART);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
// get_uart_num() and pre_setup() cast the selection straight to a port
|
||||
static_assert(static_cast<int>(UART_SELECTION_UART0) == static_cast<int>(UART_NUM_0) &&
|
||||
@@ -113,11 +107,26 @@ static_assert(static_cast<int>(UART_SELECTION_UART2) == static_cast<int>(UART_NU
|
||||
|
||||
void Logger::pre_setup() {
|
||||
if (this->baud_rate_ > 0) {
|
||||
#ifdef USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG
|
||||
init_usb_serial_jtag();
|
||||
#elif !defined(USE_LOGGER_UART_SELECTION_USB_CDC)
|
||||
init_uart(this->get_uart_num(), this->baud_rate_, ESPHOME_LOGGER_TX_BUFFER_SIZE);
|
||||
switch (this->uart_) {
|
||||
case UART_SELECTION_UART0:
|
||||
case UART_SELECTION_UART1:
|
||||
#ifdef USE_ESP32_VARIANT_ESP32
|
||||
case UART_SELECTION_UART2:
|
||||
#endif
|
||||
init_uart(static_cast<uart_port_t>(this->uart_), this->baud_rate_, ESPHOME_LOGGER_TX_BUFFER_SIZE);
|
||||
break;
|
||||
#ifdef USE_LOGGER_USB_CDC
|
||||
case UART_SELECTION_USB_CDC:
|
||||
break;
|
||||
#endif
|
||||
#ifdef USE_LOGGER_USB_SERIAL_JTAG
|
||||
case UART_SELECTION_USB_SERIAL_JTAG:
|
||||
#ifdef USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG
|
||||
init_usb_serial_jtag();
|
||||
#endif
|
||||
break;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
global_logger = this;
|
||||
@@ -129,36 +138,29 @@ void Logger::pre_setup() {
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef USE_LOGGER_CONSOLE
|
||||
size_t Logger::console_write(const uint8_t *data, size_t len) {
|
||||
int written = 0;
|
||||
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC)
|
||||
#ifdef CONFIG_ESP_CONSOLE_USB_CDC // keep: not set without USB OTG, see the include above
|
||||
written = esp_usb_console_write_buf(reinterpret_cast<const char *>(data), len);
|
||||
const LogString *Logger::get_uart_selection_() {
|
||||
switch (this->uart_) {
|
||||
case UART_SELECTION_UART0:
|
||||
return LOG_STR("UART0");
|
||||
case UART_SELECTION_UART1:
|
||||
return LOG_STR("UART1");
|
||||
#ifdef USE_ESP32_VARIANT_ESP32
|
||||
case UART_SELECTION_UART2:
|
||||
return LOG_STR("UART2");
|
||||
#endif
|
||||
#elif defined(USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG)
|
||||
written = usb_serial_jtag_write_bytes(data, len, pdMS_TO_TICKS(20));
|
||||
#else
|
||||
written = uart_write_bytes(this->get_uart_num(), data, len);
|
||||
#ifdef USE_LOGGER_USB_CDC
|
||||
case UART_SELECTION_USB_CDC:
|
||||
return LOG_STR("USB_CDC");
|
||||
#endif
|
||||
return written > 0 ? written : 0;
|
||||
#ifdef USE_LOGGER_USB_SERIAL_JTAG
|
||||
case UART_SELECTION_USB_SERIAL_JTAG:
|
||||
return LOG_STR("USB_SERIAL_JTAG");
|
||||
#endif
|
||||
default:
|
||||
return LOG_STR("UNKNOWN");
|
||||
}
|
||||
}
|
||||
|
||||
bool Logger::console_read(uint8_t &byte) {
|
||||
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC)
|
||||
#ifdef CONFIG_ESP_CONSOLE_USB_CDC // keep: not set without USB OTG, see the include above
|
||||
return esp_usb_console_available_for_read() && esp_usb_console_read_buf(reinterpret_cast<char *>(&byte), 1) == 1;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
#elif defined(USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG)
|
||||
return usb_serial_jtag_read_bytes(&byte, 1, 0) > 0;
|
||||
#else
|
||||
return uart_read_bytes(this->get_uart_num(), &byte, 1, 0) > 0;
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_CRASH_HANDLER
|
||||
bool crash_log_pending() { return esp32::crash_handler_has_data(); }
|
||||
void log_crash_to_client() {
|
||||
|
||||
@@ -14,9 +14,9 @@ void Logger::pre_setup() {
|
||||
#if defined(USE_ESP8266_LOGGER_SERIAL)
|
||||
this->hw_serial_ = &Serial;
|
||||
Serial.begin(this->baud_rate_);
|
||||
#ifdef USE_LOGGER_UART_SELECTION_UART0_SWAP
|
||||
Serial.swap();
|
||||
#endif
|
||||
if (this->uart_ == UART_SELECTION_UART0_SWAP) {
|
||||
Serial.swap();
|
||||
}
|
||||
Serial.setDebugOutput(ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE);
|
||||
#elif defined(USE_ESP8266_LOGGER_SERIAL1)
|
||||
this->hw_serial_ = &Serial1;
|
||||
@@ -35,6 +35,19 @@ void Logger::pre_setup() {
|
||||
#endif
|
||||
}
|
||||
|
||||
const LogString *Logger::get_uart_selection_() {
|
||||
#if defined(USE_ESP8266_LOGGER_SERIAL)
|
||||
if (this->uart_ == UART_SELECTION_UART0_SWAP) {
|
||||
return LOG_STR("UART0_SWAP");
|
||||
}
|
||||
return LOG_STR("UART0");
|
||||
#elif defined(USE_ESP8266_LOGGER_SERIAL1)
|
||||
return LOG_STR("UART1");
|
||||
#else
|
||||
return LOG_STR("NONE");
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef USE_CRASH_HANDLER
|
||||
bool crash_log_pending() { return esp8266::crash_handler_has_data(); }
|
||||
void log_crash_to_client() { esp8266::crash_handler_log(); }
|
||||
|
||||
@@ -12,28 +12,45 @@ ESPHOME_LOG_TAG(TAG, "logger");
|
||||
|
||||
void Logger::pre_setup() {
|
||||
if (this->baud_rate_ > 0) {
|
||||
#if defined(USE_LOGGER_UART_SELECTION_UART0) && LT_HW_UART0
|
||||
this->hw_serial_ = &Serial0;
|
||||
libretiny::ensure_serial_handle(0);
|
||||
Serial0.begin(this->baud_rate_);
|
||||
#elif defined(USE_LOGGER_UART_SELECTION_UART1) && LT_HW_UART1
|
||||
this->hw_serial_ = &Serial1;
|
||||
libretiny::ensure_serial_handle(1);
|
||||
Serial1.begin(this->baud_rate_);
|
||||
#elif defined(USE_LOGGER_UART_SELECTION_UART2) && LT_HW_UART2
|
||||
this->hw_serial_ = &Serial2;
|
||||
libretiny::ensure_serial_handle(2);
|
||||
Serial2.begin(this->baud_rate_);
|
||||
#else
|
||||
this->hw_serial_ = &Serial;
|
||||
Serial.begin(this->baud_rate_);
|
||||
if (CONFIGURED_UART_SELECTION != UART_SELECTION_DEFAULT) {
|
||||
ESP_LOGW(TAG, " The chosen logger UART port is not available on this board."
|
||||
"The default port was used instead.");
|
||||
}
|
||||
switch (this->uart_) {
|
||||
#if LT_HW_UART0
|
||||
case UART_SELECTION_UART0:
|
||||
this->hw_serial_ = &Serial0;
|
||||
libretiny::ensure_serial_handle(0);
|
||||
Serial0.begin(this->baud_rate_);
|
||||
break;
|
||||
#endif
|
||||
#if LT_HW_UART1
|
||||
case UART_SELECTION_UART1:
|
||||
this->hw_serial_ = &Serial1;
|
||||
libretiny::ensure_serial_handle(1);
|
||||
Serial1.begin(this->baud_rate_);
|
||||
break;
|
||||
#endif
|
||||
#if LT_HW_UART2
|
||||
case UART_SELECTION_UART2:
|
||||
this->hw_serial_ = &Serial2;
|
||||
libretiny::ensure_serial_handle(2);
|
||||
Serial2.begin(this->baud_rate_);
|
||||
break;
|
||||
#endif
|
||||
default:
|
||||
this->hw_serial_ = &Serial;
|
||||
Serial.begin(this->baud_rate_);
|
||||
if (this->uart_ != UART_SELECTION_DEFAULT) {
|
||||
ESP_LOGW(TAG, " The chosen logger UART port is not available on this board."
|
||||
"The default port was used instead.");
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// change lt_log() port to match default Serial
|
||||
lt_log_set_port(this->get_uart() - 1);
|
||||
if (this->uart_ == UART_SELECTION_DEFAULT) {
|
||||
this->uart_ = (UARTSelection) (LT_UART_DEFAULT_SERIAL + 1);
|
||||
lt_log_set_port(LT_UART_DEFAULT_SERIAL);
|
||||
} else {
|
||||
lt_log_set_port(this->uart_ - 1);
|
||||
}
|
||||
}
|
||||
|
||||
global_logger = this;
|
||||
@@ -43,6 +60,20 @@ void Logger::pre_setup() {
|
||||
#endif
|
||||
}
|
||||
|
||||
const LogString *Logger::get_uart_selection_() {
|
||||
switch (this->uart_) {
|
||||
case UART_SELECTION_DEFAULT:
|
||||
return LOG_STR("DEFAULT");
|
||||
case UART_SELECTION_UART0:
|
||||
return LOG_STR("UART0");
|
||||
case UART_SELECTION_UART1:
|
||||
return LOG_STR("UART1");
|
||||
case UART_SELECTION_UART2:
|
||||
default:
|
||||
return LOG_STR("UART2");
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef USE_LIBRETINY_CRASH_HANDLER
|
||||
bool crash_log_pending() { return libretiny::crash_handler_has_data(); }
|
||||
void log_crash_to_client() { libretiny::crash_handler_log(); }
|
||||
|
||||
@@ -26,16 +26,20 @@ void Logger::setup() {
|
||||
|
||||
void Logger::pre_setup() {
|
||||
if (this->baud_rate_ > 0) {
|
||||
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC)
|
||||
this->hw_serial_ = &Serial;
|
||||
Serial.begin(this->baud_rate_);
|
||||
#elif defined(USE_LOGGER_UART_SELECTION_UART1)
|
||||
this->hw_serial_ = &Serial2;
|
||||
Serial2.begin(this->baud_rate_);
|
||||
#else
|
||||
this->hw_serial_ = &Serial1;
|
||||
Serial1.begin(this->baud_rate_);
|
||||
#endif
|
||||
switch (this->uart_) {
|
||||
case UART_SELECTION_UART0:
|
||||
this->hw_serial_ = &Serial1;
|
||||
Serial1.begin(this->baud_rate_);
|
||||
break;
|
||||
case UART_SELECTION_UART1:
|
||||
this->hw_serial_ = &Serial2;
|
||||
Serial2.begin(this->baud_rate_);
|
||||
break;
|
||||
case UART_SELECTION_USB_CDC:
|
||||
this->hw_serial_ = &Serial;
|
||||
Serial.begin(this->baud_rate_);
|
||||
break;
|
||||
}
|
||||
}
|
||||
global_logger = this;
|
||||
ESP_LOGI(TAG, "Log initialized");
|
||||
@@ -45,6 +49,19 @@ void Logger::pre_setup() {
|
||||
#endif
|
||||
}
|
||||
|
||||
const LogString *Logger::get_uart_selection_() {
|
||||
switch (this->uart_) {
|
||||
case UART_SELECTION_UART0:
|
||||
return LOG_STR("UART0");
|
||||
case UART_SELECTION_UART1:
|
||||
return LOG_STR("UART1");
|
||||
case UART_SELECTION_USB_CDC:
|
||||
return LOG_STR("USB_CDC");
|
||||
default:
|
||||
return LOG_STR("UNKNOWN");
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef USE_CRASH_HANDLER
|
||||
bool crash_log_pending() { return rp2::crash_handler_has_data(); }
|
||||
void log_crash_to_client() { rp2::crash_handler_log(); }
|
||||
|
||||
@@ -42,7 +42,7 @@ __attribute__((section(".noinit"))) struct {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "logger");
|
||||
|
||||
#ifdef USE_LOGGER_ZEPHYR_CDC_LOOP
|
||||
#ifdef USE_LOGGER_UART_SELECTION_USB_CDC
|
||||
void Logger::cdc_loop_() {
|
||||
if (this->uart_dev_ == nullptr) {
|
||||
return;
|
||||
@@ -75,19 +75,25 @@ void Logger::pre_setup() {
|
||||
#ifdef CONFIG_SERIAL
|
||||
if (this->baud_rate_ > 0) {
|
||||
const struct device *uart_dev = nullptr;
|
||||
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC)
|
||||
switch (this->uart_) {
|
||||
case UART_SELECTION_UART0: // NOLINT(bugprone-branch-clone)
|
||||
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(ESPHOME_LOGGER_UART0_NODE));
|
||||
break;
|
||||
case UART_SELECTION_UART1:
|
||||
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(uart1));
|
||||
break;
|
||||
#ifdef USE_LOGGER_USB_CDC
|
||||
case UART_SELECTION_USB_CDC:
|
||||
#if defined(CONFIG_USB_DEVICE_STACK) || defined(CONFIG_USB_DEVICE_STACK_NEXT)
|
||||
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(cdc_acm_uart0));
|
||||
if (device_is_ready(uart_dev)) {
|
||||
// Nothing can log this early, and the logger has no output without USB anyway
|
||||
zephyr::usb_device_enable();
|
||||
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(cdc_acm_uart0));
|
||||
if (device_is_ready(uart_dev)) {
|
||||
// Nothing can log this early, and the logger has no output without USB anyway
|
||||
zephyr::usb_device_enable();
|
||||
}
|
||||
#endif
|
||||
break;
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
#elif defined(USE_LOGGER_UART_SELECTION_UART1)
|
||||
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(uart1));
|
||||
#else
|
||||
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(ESPHOME_LOGGER_UART0_NODE));
|
||||
#endif
|
||||
if (device_is_ready(uart_dev)) {
|
||||
this->uart_dev_ = uart_dev;
|
||||
#if defined(USE_LOGGER_WAIT_FOR_CDC) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
|
||||
@@ -111,7 +117,7 @@ void Logger::pre_setup() {
|
||||
this->dump_crash_();
|
||||
#endif
|
||||
// Nobody reads a USB port this early; cdc_loop_() reports the dump once the port is opened
|
||||
#if defined(USE_CRASH_HANDLER) && !defined(USE_LOGGER_ZEPHYR_CDC_LOOP)
|
||||
#if defined(USE_CRASH_HANDLER) && !defined(USE_LOGGER_UART_SELECTION_USB_CDC)
|
||||
// Without a UART (baud_rate: 0, or one that did not come up) nothing reaches the console
|
||||
if (this->uart_dev_ != nullptr)
|
||||
log_crash_to_client();
|
||||
@@ -133,6 +139,21 @@ void HOT Logger::write_msg_(const char *msg, uint16_t len) {
|
||||
}
|
||||
}
|
||||
|
||||
const LogString *Logger::get_uart_selection_() {
|
||||
switch (this->uart_) {
|
||||
case UART_SELECTION_UART0:
|
||||
return LOG_STR("UART0");
|
||||
case UART_SELECTION_UART1:
|
||||
return LOG_STR("UART1");
|
||||
#ifdef USE_LOGGER_USB_CDC
|
||||
case UART_SELECTION_USB_CDC:
|
||||
return LOG_STR("USB_CDC");
|
||||
#endif
|
||||
default:
|
||||
return LOG_STR("UNKNOWN");
|
||||
}
|
||||
}
|
||||
|
||||
static constexpr uint8_t REASON_BUF_SIZE = 32;
|
||||
|
||||
static const char *reason_to_str(unsigned int reason, char *buf) {
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
#include "at_reply.h"
|
||||
|
||||
#include <cctype>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <strings.h>
|
||||
|
||||
namespace esphome::modem {
|
||||
|
||||
bool collect_reply(char *buf, size_t size, size_t &len, const char *data, size_t data_len, bool whole) {
|
||||
const size_t capacity = size - 1;
|
||||
if (whole) {
|
||||
len = 0;
|
||||
}
|
||||
bool dropped = false;
|
||||
if (data_len > capacity) {
|
||||
memcpy(buf, data + data_len - capacity, capacity);
|
||||
len = capacity;
|
||||
dropped = true;
|
||||
} else {
|
||||
if (len + data_len > capacity) {
|
||||
const size_t drop = len + data_len - capacity;
|
||||
memmove(buf, buf + drop, len - drop);
|
||||
len -= drop;
|
||||
dropped = true;
|
||||
}
|
||||
memcpy(buf + len, data, data_len);
|
||||
len += data_len;
|
||||
}
|
||||
buf[len] = '\0';
|
||||
return dropped;
|
||||
}
|
||||
|
||||
ReplyEnd reply_end(const char *data, size_t len, bool skip_first) {
|
||||
const char *end = data + len;
|
||||
const char *line = data;
|
||||
if (skip_first) {
|
||||
const auto *newline = static_cast<const char *>(memchr(data, '\n', len));
|
||||
line = newline != nullptr ? newline + 1 : end;
|
||||
}
|
||||
while (line < end) {
|
||||
const auto *newline = static_cast<const char *>(memchr(line, '\n', end - line));
|
||||
if (newline == nullptr) {
|
||||
break; // the line has not ended yet
|
||||
}
|
||||
size_t size = newline - line;
|
||||
if (size != 0 && line[size - 1] == '\r') {
|
||||
size--;
|
||||
}
|
||||
if (size == 2 && memcmp(line, "OK", 2) == 0) {
|
||||
return ReplyEnd::REPLY_END_OK;
|
||||
}
|
||||
if ((size == 5 && memcmp(line, "ERROR", 5) == 0) || (size >= 11 && memcmp(line, "+CME ERROR:", 11) == 0) ||
|
||||
(size >= 11 && memcmp(line, "+CMS ERROR:", 11) == 0)) {
|
||||
return ReplyEnd::REPLY_END_ERROR;
|
||||
}
|
||||
line = newline + 1;
|
||||
}
|
||||
return ReplyEnd::REPLY_END_NONE;
|
||||
}
|
||||
|
||||
size_t flatten_reply(char *reply, size_t len) {
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
if (reply[i] == '\r' || reply[i] == '\n') {
|
||||
reply[i] = ' ';
|
||||
}
|
||||
}
|
||||
while (len != 0 && reply[len - 1] == ' ') {
|
||||
len--;
|
||||
}
|
||||
if (len >= 2 && memcmp(reply + len - 2, "OK", 2) == 0 && (len == 2 || reply[len - 3] == ' ')) {
|
||||
len -= 2;
|
||||
while (len != 0 && reply[len - 1] == ' ') {
|
||||
len--;
|
||||
}
|
||||
}
|
||||
size_t start = 0;
|
||||
while (start < len && reply[start] == ' ') {
|
||||
start++;
|
||||
}
|
||||
len -= start;
|
||||
memmove(reply, reply + start, len);
|
||||
reply[len] = '\0';
|
||||
return len;
|
||||
}
|
||||
|
||||
int registration_from_reply(const char *reply, const char *prefix) {
|
||||
const size_t prefix_len = strlen(prefix);
|
||||
for (const char *line = strstr(reply, prefix); line != nullptr; line = strstr(line + 1, prefix)) {
|
||||
const char *start = line + prefix_len;
|
||||
char *end = nullptr;
|
||||
strtol(start, &end, 10);
|
||||
if (end == start || *end != ',') {
|
||||
continue;
|
||||
}
|
||||
start = end + 1;
|
||||
const auto stat = static_cast<int32_t>(strtol(start, &end, 10));
|
||||
if (end != start) {
|
||||
return stat;
|
||||
}
|
||||
}
|
||||
return REGISTRATION_UNKNOWN;
|
||||
}
|
||||
|
||||
int merge_registration(int lte, int legacy) {
|
||||
// A multimode modem can be registered or still searching on one network type while the other refuses it
|
||||
if (is_registered(lte)) {
|
||||
return lte;
|
||||
}
|
||||
if (is_registered(legacy)) {
|
||||
return legacy;
|
||||
}
|
||||
// A definite answer from one query outweighs a timeout of the other
|
||||
if (lte == REGISTRATION_SEARCHING || legacy == REGISTRATION_SEARCHING) {
|
||||
return REGISTRATION_SEARCHING;
|
||||
}
|
||||
if (lte == REGISTRATION_DENIED || legacy == REGISTRATION_DENIED) {
|
||||
return REGISTRATION_DENIED;
|
||||
}
|
||||
if (lte >= 0 || legacy >= 0) {
|
||||
return lte >= 0 ? lte : legacy;
|
||||
}
|
||||
if (lte == REGISTRATION_NO_ANSWER || legacy == REGISTRATION_NO_ANSWER) {
|
||||
return REGISTRATION_NO_ANSWER;
|
||||
}
|
||||
if (lte == REGISTRATION_UNSUPPORTED && legacy == REGISTRATION_UNSUPPORTED) {
|
||||
return REGISTRATION_UNSUPPORTED;
|
||||
}
|
||||
return REGISTRATION_UNKNOWN;
|
||||
}
|
||||
|
||||
bool reply_names_unsupported(const char *reply) {
|
||||
static constexpr char PREFIX[] = "+CME ERROR:";
|
||||
static constexpr char TEXT[] = "operation not supported";
|
||||
const char *code = strstr(reply, PREFIX);
|
||||
if (code == nullptr) {
|
||||
return false;
|
||||
}
|
||||
code += sizeof(PREFIX) - 1;
|
||||
while (*code == ' ') {
|
||||
code++;
|
||||
}
|
||||
return strncasecmp(code, TEXT, sizeof(TEXT) - 1) == 0 || (code[0] == '4' && !isdigit(code[1]));
|
||||
}
|
||||
|
||||
const char *sim_status(char *reply) {
|
||||
static constexpr char PREFIX[] = "+CPIN:";
|
||||
char *status = strstr(reply, PREFIX);
|
||||
if (status == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
status += sizeof(PREFIX) - 1;
|
||||
while (*status == ' ') {
|
||||
status++;
|
||||
}
|
||||
// A URC in the same reply follows on its own line, which flatten_reply() turned into two spaces
|
||||
char *end = strstr(status, " ");
|
||||
if (end != nullptr) {
|
||||
*end = '\0';
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
} // namespace esphome::modem
|
||||
@@ -0,0 +1,56 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
// Parsers for raw AT replies; free of esp_modem so they build and run in host unit tests
|
||||
namespace esphome::modem {
|
||||
|
||||
enum class ReplyEnd : uint8_t {
|
||||
REPLY_END_NONE, // no complete final result line yet
|
||||
REPLY_END_OK, // an OK line
|
||||
REPLY_END_ERROR, // an ERROR, +CME ERROR: or +CMS ERROR: line
|
||||
};
|
||||
|
||||
// AT+CEREG? and AT+CREG? <stat> values
|
||||
static constexpr int REGISTRATION_NOT_SEARCHING = 0;
|
||||
static constexpr int REGISTRATION_HOME = 1;
|
||||
static constexpr int REGISTRATION_SEARCHING = 2;
|
||||
static constexpr int REGISTRATION_DENIED = 3;
|
||||
static constexpr int REGISTRATION_REPORTED_UNKNOWN = 4;
|
||||
static constexpr int REGISTRATION_ROAMING = 5;
|
||||
// Results beyond the 3GPP values
|
||||
static constexpr int REGISTRATION_UNKNOWN = -1; // no readable answer
|
||||
static constexpr int REGISTRATION_UNSUPPORTED = -2; // the query is not supported
|
||||
static constexpr int REGISTRATION_NO_ANSWER = -3; // the query timed out
|
||||
|
||||
inline bool is_registered(int registration) {
|
||||
return registration == REGISTRATION_HOME || registration == REGISTRATION_ROAMING;
|
||||
}
|
||||
|
||||
/// Add data to the reply in buf (size includes the terminator, len is the current length). With whole, data is
|
||||
/// everything received so far (UART) and replaces the reply; otherwise it is one new CMUX frame and is appended. A
|
||||
/// reply longer than the buffer keeps its newest bytes, where the final line is. Returns true when bytes were dropped.
|
||||
bool collect_reply(char *buf, size_t size, size_t &len, const char *data, size_t data_len, bool whole);
|
||||
|
||||
/// How the reply ends. Only a complete final result line counts, so ERROR inside a payload line does not. With
|
||||
/// skip_first, the first line is a cut-off fragment and is ignored.
|
||||
ReplyEnd reply_end(const char *data, size_t len, bool skip_first);
|
||||
|
||||
/// Puts a raw reply on one line for the log and drops the final OK; returns the new length
|
||||
size_t flatten_reply(char *reply, size_t len);
|
||||
|
||||
/// The <stat> after the first comma of the "<n>,<stat>" line starting with prefix (+CREG: and friends), or
|
||||
/// REGISTRATION_UNKNOWN; a one-field line is an unsolicited notification and is skipped
|
||||
int registration_from_reply(const char *reply, const char *prefix);
|
||||
|
||||
/// The state that tells most from the AT+CEREG? (LTE) and AT+CREG? (2G and 3G) results
|
||||
int merge_registration(int lte, int legacy);
|
||||
|
||||
/// Whether an error reply says the command is not supported (+CME ERROR: 4 or its verbose text)
|
||||
bool reply_names_unsupported(const char *reply);
|
||||
|
||||
/// The SIM status in a flattened AT+CPIN? reply, cut before any following line, or nullptr
|
||||
const char *sim_status(char *reply);
|
||||
|
||||
} // namespace esphome::modem
|
||||
@@ -1,5 +1,6 @@
|
||||
#ifdef USE_ESP32
|
||||
#include "modem_component.h"
|
||||
#include "at_reply.h"
|
||||
#include "soc/soc_caps.h"
|
||||
#include <driver/uart.h>
|
||||
|
||||
@@ -42,6 +43,14 @@ static constexpr uint32_t PROBE_TIMEOUT_MS = 100;
|
||||
// A silent modem is not going to answer the next second, so its probes are spaced out, doubling up to a minute
|
||||
static constexpr uint32_t PROBE_RETRY_DELAY_MS = 5000;
|
||||
static constexpr uint32_t PROBE_RETRY_MAX_MS = 60000;
|
||||
// A modem in command mode answers the ATE0 sent before the mode detection within this time
|
||||
static constexpr uint32_t ECHO_OFF_TIMEOUT_MS = 100;
|
||||
// The +++ escape needs a second of silence before it; esp_modem waits for the answer after it
|
||||
static constexpr uint32_t ESCAPE_GUARD_MS = 1100;
|
||||
// A SIM7670 left in CMUX by an ESP reset ignores every frame until this many flag bytes overflow its receive buffer;
|
||||
// it then reinitialises its AT channel within about 2 s
|
||||
static constexpr size_t CMUX_FLUSH_BYTES = 4096;
|
||||
static constexpr uint32_t CMUX_FLUSH_SETTLE_MS = 3000;
|
||||
// How long the task waits for the main loop to run on_sync before attaching
|
||||
static constexpr uint32_t SYNC_ACK_TIMEOUT_MS = 5000;
|
||||
// esp_modem's command strings and the log lines are built on this stack
|
||||
@@ -56,6 +65,12 @@ static constexpr uint8_t PIN_MAX_UNCONFIRMED_SENDS = 2;
|
||||
// The attachment is polled every 4 s; the signal and operator queries only every 4th poll
|
||||
static constexpr uint32_t ATTACH_POLL_MS = 4000;
|
||||
static constexpr uint8_t ATTACH_DIAG_EVERY = 4;
|
||||
static constexpr uint8_t ATTACH_UNKNOWN_POLLS = 15; // about a minute of polls
|
||||
// AT+CGATT=1: SIMCom documents up to 75 s, but a SIM7080G that is not registered yet held it for 141 s
|
||||
static constexpr uint32_t ATTACH_TIMEOUT_MS = 150000;
|
||||
// SIM status polls that fail before a warning, and between repeats of it
|
||||
static constexpr uint8_t SIM_WARN_AFTER = 10;
|
||||
static constexpr uint8_t SIM_WARN_EVERY = 60;
|
||||
static constexpr int RADIO_STATE_MINIMUM = 0; // CFUN=0: radio off and the SIM powered down
|
||||
static constexpr int RADIO_STATE_RF_OFF = 4; // CFUN=4: transmit and receive off, SIM still powered
|
||||
static constexpr uint8_t UART_EVENT_QUEUE_SIZE = 10;
|
||||
@@ -73,8 +88,21 @@ static const LogString *state_to_str(ModemState state) {
|
||||
// Indexed by ModemFault
|
||||
PROGMEM_STRING_TABLE(ModemFaultStrings, "", "Modem not responding", "Configured baud rate failed",
|
||||
"init_at command failed", "SIM not ready", "SIM locked", "SIM PIN not sent; check pin_code",
|
||||
"PIN record not saved", "APN or radio setup failed", "No network attachment", "PPP link failed",
|
||||
"Modem teardown failed");
|
||||
"PIN record not saved", "APN or radio setup failed", "No network attachment",
|
||||
"Network registration denied", "PPP link failed", "Modem teardown failed");
|
||||
|
||||
// Indexed by the AT+CEREG? <stat> value
|
||||
PROGMEM_STRING_TABLE(RegistrationStrings, "not searching", "registered", "searching", "denied", "unknown", "roaming",
|
||||
"other");
|
||||
static const LogString *registration_to_str(int registration) {
|
||||
if (registration == REGISTRATION_UNSUPPORTED) {
|
||||
return LOG_STR("not supported");
|
||||
}
|
||||
if (registration < 0) {
|
||||
return LOG_STR("not reported");
|
||||
}
|
||||
return RegistrationStrings::get_log_str(static_cast<uint8_t>(registration), RegistrationStrings::LAST_INDEX);
|
||||
}
|
||||
|
||||
// Indexed by esp_modem::command_result
|
||||
PROGMEM_STRING_TABLE(CommandResultStrings, "OK", "FAIL", "TIMEOUT");
|
||||
@@ -586,6 +614,9 @@ ModemState ModemComponent::compute_next_state_() {
|
||||
}
|
||||
|
||||
ModemState ModemComponent::handle_state_enabling_() {
|
||||
// With echo on (SIM7670G after power-up), the modem sends esp_modem's PPP probe back and the detection takes it for
|
||||
// a PPP reply; in PPP or CMUX these bytes are dropped as a bad frame
|
||||
this->at_reply_("ATE0", ECHO_OFF_TIMEOUT_MS);
|
||||
// Find the baud rate the modem answers at and leave it in command mode, synced
|
||||
if (!this->dce_->set_mode(modem_mode::AUTODETECT)) {
|
||||
// A failed detection keeps the previous mode, which would skip the baud rate search below
|
||||
@@ -611,21 +642,18 @@ ModemState ModemComponent::handle_state_enabling_() {
|
||||
exited = false;
|
||||
const int bauds[] = {this->restored_baud_, this->baud_rate_, FALLBACK_BAUD_RATE};
|
||||
bool found = false;
|
||||
bool probed = false;
|
||||
bool rejected = false;
|
||||
for (size_t i = 0; i != std::size(bauds) && !found; i++) {
|
||||
const int baud = bauds[i];
|
||||
if (baud == 0 || baud == detected || std::find(bauds, bauds + i, baud) != bauds + i) {
|
||||
continue;
|
||||
}
|
||||
if (uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), baud) != ESP_OK) {
|
||||
if (this->set_uart_baud_(baud) != ESP_OK) {
|
||||
ESP_LOGW(TAG, "UART rejected baud rate %d", baud);
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
|
||||
rejected = true;
|
||||
continue;
|
||||
}
|
||||
this->current_baud_rate_ = baud;
|
||||
probed = true;
|
||||
std::string output;
|
||||
found = this->dce_->at("AT", output, PROBE_TIMEOUT_MS) == command_result::OK;
|
||||
if (!found) {
|
||||
@@ -633,11 +661,31 @@ ModemState ModemComponent::handle_state_enabling_() {
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
// The detection at the current rate already failed; a UART that refused every other rate set BAUD
|
||||
if (!probed && !rejected) {
|
||||
// A modem left in data mode before PPP started, or stuck in CMUX, answers none of the probes; both recoveries
|
||||
// go out at the rate the detection used
|
||||
if (this->current_baud_rate_ != detected) {
|
||||
const esp_err_t err = this->set_uart_baud_(detected);
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGW(TAG, "UART rejected baud rate %d (%s); data mode and CMUX recovery skipped", detected,
|
||||
esp_err_to_name(err));
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
|
||||
rejected = true;
|
||||
}
|
||||
}
|
||||
// The escape before the flush is what a stuck SIM7670G responds to; the order is measured, not arbitrary
|
||||
if (this->current_baud_rate_ == detected && (this->escape_data_mode_() || this->flush_cmux_())) {
|
||||
exited = true;
|
||||
break;
|
||||
}
|
||||
// A UART that refused a rate set BAUD
|
||||
if (!rejected) {
|
||||
this->not_responding_(detected);
|
||||
}
|
||||
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
|
||||
const uint32_t delay_ms = this->next_probe_delay_();
|
||||
if (delay_ms == PROBE_RETRY_MAX_MS) {
|
||||
this->answered_ = false; // silent for minutes, so the wiring hint applies again
|
||||
}
|
||||
return this->retry_(ModemState::MODEM_STATE_ENABLING, delay_ms);
|
||||
}
|
||||
ESP_LOGD(TAG, "Modem responded at baud %d", this->current_baud_rate_);
|
||||
break;
|
||||
@@ -671,10 +719,19 @@ ModemState ModemComponent::handle_state_enabling_() {
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_TEARDOWN);
|
||||
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
|
||||
}
|
||||
// The modem answers AT, so it is in command mode. A failed data mode exit leaves esp_modem's UART side in data mode,
|
||||
// from where its later switch to CMUX fails at once, so its mode is set to match; this sends nothing to the modem.
|
||||
if (!this->dce_->set_mode(modem_mode::RESUME_COMMAND_MODE)) {
|
||||
ESP_LOGW(TAG, "esp_modem refused command mode; the switch to PPP may fail");
|
||||
}
|
||||
// esp_modem keeps the last line before OK as the reply, which can be the echoed command
|
||||
if (this->dce_->set_echo(false) != command_result::OK) {
|
||||
ESP_LOGW(TAG, "Failed to disable command echo");
|
||||
}
|
||||
// Verbose +CME ERROR text, so a failed command or a missing SIM says why; a modem without it keeps plain ERROR
|
||||
if (this->dce_->config_mobile_termination_error(2) != command_result::OK) {
|
||||
ESP_LOGW(TAG, "Modem refused verbose errors (AT+CMEE=2)");
|
||||
}
|
||||
|
||||
// The SIM7670G only uses an APN written at CFUN=0 (else the attach fails with an ESM failure); CFUN=0 also drops a
|
||||
// session left by a warm reboot. A modem that refuses gets the APN after the SIM check instead, as before.
|
||||
@@ -690,6 +747,7 @@ ModemState ModemComponent::handle_state_enabling_() {
|
||||
ESP_LOGW(TAG, "Failed to power the SIM up");
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
|
||||
this->modem_synced_ = true; // it answers, so a disable() still tears it down
|
||||
this->answered_ = true;
|
||||
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
|
||||
}
|
||||
this->probe_backoff_.store(0, std::memory_order_relaxed);
|
||||
@@ -698,12 +756,11 @@ ModemState ModemComponent::handle_state_enabling_() {
|
||||
ESP_LOGD(TAG, "Setting baud rate: %d -> %d", this->current_baud_rate_, this->baud_rate_);
|
||||
if (this->dce_->set_baud(this->baud_rate_) == command_result::OK) {
|
||||
delay(200); // NOLINT
|
||||
if (uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), this->baud_rate_) != ESP_OK) {
|
||||
if (this->set_uart_baud_(this->baud_rate_) != ESP_OK) {
|
||||
ESP_LOGE(TAG, "UART rejected baud rate %d", this->baud_rate_);
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
|
||||
return ModemState::MODEM_STATE_DISCONNECTING;
|
||||
}
|
||||
this->current_baud_rate_ = this->baud_rate_;
|
||||
if (this->dce_->sync() != command_result::OK) {
|
||||
ESP_LOGE(TAG, "Failed to sync modem at baud rate %d.", this->baud_rate_);
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
|
||||
@@ -731,6 +788,7 @@ ModemState ModemComponent::handle_state_enabling_() {
|
||||
ESP_LOGW(TAG, "Modem refused hardware flow control; UART overruns are possible");
|
||||
}
|
||||
this->modem_synced_ = true;
|
||||
this->answered_ = true;
|
||||
return ModemState::MODEM_STATE_SYNCED;
|
||||
}
|
||||
|
||||
@@ -746,12 +804,13 @@ ModemState ModemComponent::handle_state_synced_() {
|
||||
this->clear_config_fault_(ModemFault::MODEM_FAULT_INIT_AT);
|
||||
}
|
||||
this->connect_step_ = ConnectStep::CONNECT_STEP_START;
|
||||
this->sim_polls_ = 0;
|
||||
return ModemState::MODEM_STATE_CONNECTING;
|
||||
}
|
||||
|
||||
ModemState ModemComponent::handle_state_connecting_() {
|
||||
if (this->connect_step_ == ConnectStep::CONNECT_STEP_START) {
|
||||
// ENABLING just synced; only a failed attachment read comes back here unsure of the modem
|
||||
// ENABLING just synced; a command that timed out comes back here unsure of the modem
|
||||
if (this->resync_) {
|
||||
this->resync_ = false;
|
||||
if (this->dce_->sync() != command_result::OK) {
|
||||
@@ -792,35 +851,78 @@ ModemState ModemComponent::handle_state_connecting_() {
|
||||
}
|
||||
this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON;
|
||||
this->attach_polls_ = 0;
|
||||
}
|
||||
|
||||
if (this->connect_step_ == ConnectStep::CONNECT_STEP_RADIO_ON) {
|
||||
// A modem still searching for a network refuses this; the attachment poll asks again
|
||||
if (this->dce_->set_network_attachment_state(1) != command_result::OK) {
|
||||
ESP_LOGD(TAG, "Network attachment request refused");
|
||||
}
|
||||
this->connect_step_ = ConnectStep::CONNECT_STEP_ATTACH_REQUESTED;
|
||||
this->idle_polls_ = 0;
|
||||
this->unknown_polls_ = 0;
|
||||
}
|
||||
|
||||
int attached = 0;
|
||||
if (this->dce_->get_network_attachment_state(attached) != command_result::OK) {
|
||||
ESP_LOGW(TAG, "Failed to read the network attachment state");
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
|
||||
this->connect_step_ = ConnectStep::CONNECT_STEP_START; // start over with a sync on the next pass
|
||||
this->resync_ = true;
|
||||
this->request_resync_();
|
||||
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
|
||||
}
|
||||
if (!attached) {
|
||||
const int registration = this->read_registration_();
|
||||
if (registration == REGISTRATION_NO_ANSWER) {
|
||||
// The state is open, so the modem is checked with a sync instead
|
||||
ESP_LOGW(TAG, "No answer to a registration query");
|
||||
this->request_resync_();
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
|
||||
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
|
||||
}
|
||||
// "Not searching" for a few polls in a row means the attachment is off; right after CFUN=1 it is only brief
|
||||
this->idle_polls_ = registration == REGISTRATION_NOT_SEARCHING ? static_cast<uint8_t>(this->idle_polls_ + 1) : 0;
|
||||
const bool idle = this->idle_polls_ >= ATTACH_DIAG_EVERY;
|
||||
// A state that cannot be read or means nothing here holds the request back only for a while
|
||||
const bool unknown = registration == REGISTRATION_UNKNOWN || registration == REGISTRATION_REPORTED_UNKNOWN ||
|
||||
registration > REGISTRATION_ROAMING;
|
||||
this->unknown_polls_ = unknown ? static_cast<uint8_t>(this->unknown_polls_ + 1) : 0;
|
||||
const bool unknown_too_long = this->unknown_polls_ >= ATTACH_UNKNOWN_POLLS;
|
||||
if (this->connect_step_ == ConnectStep::CONNECT_STEP_RADIO_ON &&
|
||||
(is_registered(registration) || registration == REGISTRATION_UNSUPPORTED || idle || unknown_too_long)) {
|
||||
if (unknown_too_long) {
|
||||
ESP_LOGI(TAG, "Registration state %d (%s) for %u polls; requesting the network attachment anyway", registration,
|
||||
LOG_STR_ARG(registration_to_str(registration)), this->unknown_polls_);
|
||||
this->unknown_polls_ = 0;
|
||||
}
|
||||
// Before registration a modem can hold the AT channel on this for minutes and drop every command meanwhile,
|
||||
// so it waits for one; the fallbacks above send it anyway, and ATTACH_TIMEOUT_MS covers that hold
|
||||
const command_result attach = this->at_reply_("AT+CGATT=1", ATTACH_TIMEOUT_MS);
|
||||
if (attach == command_result::TIMEOUT) {
|
||||
ESP_LOGW(TAG, "No answer to the network attachment request");
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
|
||||
this->request_resync_();
|
||||
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
|
||||
}
|
||||
if (attach != command_result::OK) {
|
||||
ESP_LOGW(TAG, "Network attachment request refused: %s", this->reply_);
|
||||
}
|
||||
this->connect_step_ = ConnectStep::CONNECT_STEP_ATTACH_REQUESTED;
|
||||
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
|
||||
}
|
||||
if (this->attach_polls_++ % ATTACH_DIAG_EVERY == 0) {
|
||||
int rssi = 99, ber = 99, registration = -1, mode = -1; // -1 stays when the query fails
|
||||
this->dce_->get_network_registration_state(registration);
|
||||
int rssi = 99, ber = 99, mode = -1; // -1 stays when the query fails
|
||||
this->dce_->get_signal_quality(rssi, ber);
|
||||
this->dce_->get_network_system_mode(mode);
|
||||
ESP_LOGW(TAG, "Modem not attached yet: registration %d, network type %d, CSQ %d, BER %d", registration, mode,
|
||||
rssi, ber);
|
||||
ESP_LOGW(TAG, "Modem not attached yet: registration %d (%s), network type %d, CSQ %d, BER %d", registration,
|
||||
LOG_STR_ARG(registration_to_str(registration)), mode, rssi, ber);
|
||||
if (unknown) {
|
||||
ESP_LOGW(TAG, "Network attachment request held back while the registration state is unknown (%u of %u polls)",
|
||||
this->unknown_polls_, ATTACH_UNKNOWN_POLLS);
|
||||
}
|
||||
if (registration == REGISTRATION_DENIED) {
|
||||
// The modem's reason tells a rejected APN (ESM failure) from a SIM the network does not serve
|
||||
const command_result reason_read = this->at_reply_("AT+CEER");
|
||||
ESP_LOGW(TAG,
|
||||
"The network refused registration (AT+CEER %s: %s); check the APN and that the SIM's plan covers "
|
||||
"this modem's network types",
|
||||
LOG_STR_ARG(result_to_str(reason_read)), this->reply_);
|
||||
}
|
||||
this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON; // request the attachment again
|
||||
}
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
|
||||
this->set_fault_(registration == REGISTRATION_DENIED ? ModemFault::MODEM_FAULT_REGISTRATION_DENIED
|
||||
: ModemFault::MODEM_FAULT_NOT_ATTACHED);
|
||||
return this->retry_(ModemState::MODEM_STATE_CONNECTING, ATTACH_POLL_MS);
|
||||
}
|
||||
|
||||
@@ -923,11 +1025,114 @@ void ModemComponent::transition_to_(ModemState next_state) {
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t ModemComponent::set_uart_baud_(int baud) {
|
||||
const esp_err_t err = uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), baud);
|
||||
if (err == ESP_OK) {
|
||||
this->current_baud_rate_ = baud;
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
||||
bool ModemComponent::escape_data_mode_() {
|
||||
delay(ESCAPE_GUARD_MS); // NOLINT
|
||||
if (this->dce_->set_command_mode() != command_result::OK) {
|
||||
ESP_LOGD(TAG, "No answer after the data mode escape");
|
||||
return false;
|
||||
}
|
||||
ESP_LOGW(TAG, "Modem was left in data mode; escaped to command mode");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ModemComponent::flush_cmux_() {
|
||||
// With RTS/CTS a silent modem can hold CTS off; the flag bytes would then stay queued and block every later write
|
||||
if (this->rts_pin_ != nullptr) {
|
||||
ESP_LOGW(TAG, "CMUX recovery is not available with RTS/CTS flow control");
|
||||
return false;
|
||||
}
|
||||
static constexpr uint8_t CMUX_FLAG = 0xF9;
|
||||
uint8_t flags[64];
|
||||
memset(flags, CMUX_FLAG, sizeof(flags));
|
||||
const auto port = static_cast<uart_port_t>(this->uart_port_);
|
||||
for (size_t sent = 0; sent < CMUX_FLUSH_BYTES; sent += sizeof(flags)) {
|
||||
if (this->dte_->write(flags, sizeof(flags)) != static_cast<int>(sizeof(flags))) {
|
||||
ESP_LOGW(TAG, "CMUX flush: short write after %u bytes", static_cast<unsigned>(sent));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// 10 bits per byte, plus a margin
|
||||
const uint32_t send_ms = CMUX_FLUSH_BYTES * 10 * 1000 / this->current_baud_rate_ + 100;
|
||||
if (uart_wait_tx_done(port, pdMS_TO_TICKS(send_ms)) != ESP_OK) {
|
||||
ESP_LOGW(TAG, "CMUX flush: transmit not finished after %u ms", static_cast<unsigned>(send_ms));
|
||||
return false;
|
||||
}
|
||||
delay(CMUX_FLUSH_SETTLE_MS); // NOLINT
|
||||
if (this->dce_->sync() != command_result::OK) {
|
||||
ESP_LOGD(TAG, "No answer after the CMUX flush");
|
||||
return false;
|
||||
}
|
||||
ESP_LOGW(TAG, "Modem was stuck in CMUX; reset it to command mode");
|
||||
return true;
|
||||
}
|
||||
|
||||
// A command timed out: the next pass checks with a sync that the modem still answers
|
||||
void ModemComponent::request_resync_() {
|
||||
this->connect_step_ = ConnectStep::CONNECT_STEP_START;
|
||||
this->resync_ = true;
|
||||
}
|
||||
|
||||
// One registration query: the <stat>, REGISTRATION_UNSUPPORTED, REGISTRATION_NO_ANSWER or REGISTRATION_UNKNOWN
|
||||
int ModemComponent::read_stat_(const char *cmd, const char *prefix) {
|
||||
const command_result result = this->at_reply_(cmd);
|
||||
if (result == command_result::TIMEOUT) {
|
||||
return REGISTRATION_NO_ANSWER;
|
||||
}
|
||||
if (result == command_result::FAIL && reply_names_unsupported(this->reply_)) {
|
||||
return REGISTRATION_UNSUPPORTED;
|
||||
}
|
||||
const int stat = result == command_result::OK ? registration_from_reply(this->reply_, prefix) : REGISTRATION_UNKNOWN;
|
||||
if (stat == REGISTRATION_UNKNOWN) {
|
||||
// An error such as a SIM failure is a warning on the diagnostic polls, so it shows at the default log level
|
||||
if (result == command_result::FAIL && this->attach_polls_ % ATTACH_DIAG_EVERY == 0) {
|
||||
ESP_LOGW(TAG, "%s failed: %s", cmd, this->reply_);
|
||||
} else {
|
||||
ESP_LOGD(TAG, "%s gave no state: %s", cmd, this->reply_);
|
||||
}
|
||||
}
|
||||
return stat;
|
||||
}
|
||||
|
||||
// AT+CEREG covers LTE; on 2G and 3G the network registration is in AT+CREG, and AT+CGATT=1 is answered quickly once
|
||||
// it is set. Returns the <stat> that tells most, or one of the negative REGISTRATION_ values.
|
||||
int ModemComponent::read_registration_() {
|
||||
const int lte = this->read_stat_("AT+CEREG?", "+CEREG:");
|
||||
if (is_registered(lte)) {
|
||||
return lte;
|
||||
}
|
||||
return merge_registration(lte, this->read_stat_("AT+CREG?", "+CREG:"));
|
||||
}
|
||||
|
||||
void ModemComponent::not_responding_(int baud) {
|
||||
ESP_LOGW(TAG, "Modem not responding at %d baud. Check power, PWRKEY and TX/RX wiring.", baud);
|
||||
if (this->answered_) {
|
||||
// It answered before, so the wiring is fine; a long command or a modem restart keeps it silent for minutes
|
||||
ESP_LOGW(TAG, "Modem not responding at %d baud; it may be busy or restarting", baud);
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Modem not responding at %d baud. Check power, PWRKEY and TX/RX wiring.", baud);
|
||||
}
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_NO_RESPONSE);
|
||||
}
|
||||
|
||||
void ModemComponent::sim_not_ready_(const char *reason) {
|
||||
// A missing or broken SIM never gets ready; the status is polled every second, so only some polls warn
|
||||
if (++this->sim_polls_ == SIM_WARN_AFTER + SIM_WARN_EVERY) {
|
||||
this->sim_polls_ = SIM_WARN_AFTER;
|
||||
}
|
||||
if (this->sim_polls_ == SIM_WARN_AFTER) {
|
||||
ESP_LOGW(TAG, "SIM not ready: %s. Check that a working SIM is inserted",
|
||||
reason[0] != '\0' ? reason : LOG_STR_LITERAL("no reply"));
|
||||
}
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
|
||||
}
|
||||
|
||||
#ifdef USE_MODEM_SEND_AT
|
||||
bool ModemComponent::send_at(const std::string &cmd, uint32_t timeout) { return this->send_at(cmd.c_str(), timeout); }
|
||||
|
||||
@@ -954,13 +1159,54 @@ bool ModemComponent::send_at(const char *cmd, uint32_t timeout) {
|
||||
|
||||
#endif
|
||||
|
||||
// at() keeps no text from a failed command, so the raw reply is collected into reply_ to show the +CME ERROR
|
||||
command_result ModemComponent::at_reply_(const char *cmd, uint32_t timeout) {
|
||||
std::string line = cmd; // poll commands fit the short string buffer
|
||||
line += '\r';
|
||||
this->reply_len_ = 0;
|
||||
this->reply_[0] = '\0';
|
||||
#ifdef CONFIG_ESP_MODEM_USE_INFLATABLE_BUFFER_IF_NEEDED
|
||||
// The inflatable buffer gathers CMUX frames too, so every reply comes over whole each time
|
||||
const bool whole = true;
|
||||
#else
|
||||
// esp_modem hands a UART reply over whole each time, and a CMUX reply one frame at a time
|
||||
const modem_mode mode = this->dce_->get_mode();
|
||||
const bool whole = mode != modem_mode::CMUX_MODE && mode != modem_mode::CMUX_MANUAL_MODE &&
|
||||
mode != modem_mode::CMUX_MANUAL_DATA && mode != modem_mode::CMUX_MANUAL_COMMAND;
|
||||
#endif
|
||||
struct {
|
||||
bool whole;
|
||||
bool cut;
|
||||
} state{whole, false};
|
||||
const command_result result = this->dce_->command(
|
||||
line,
|
||||
[this, &state](const uint8_t *data, size_t len) {
|
||||
// OK, or FAIL once an ERROR line has ended (the +CME ERROR reason may still be on its way), else TIMEOUT
|
||||
state.cut |= collect_reply(this->reply_, sizeof(this->reply_), this->reply_len_,
|
||||
reinterpret_cast<const char *>(data), len, state.whole);
|
||||
switch (reply_end(this->reply_, this->reply_len_, state.cut)) {
|
||||
case ReplyEnd::REPLY_END_OK:
|
||||
return command_result::OK;
|
||||
case ReplyEnd::REPLY_END_ERROR:
|
||||
return command_result::FAIL;
|
||||
default:
|
||||
return command_result::TIMEOUT;
|
||||
}
|
||||
},
|
||||
timeout);
|
||||
this->reply_len_ = flatten_reply(this->reply_, this->reply_len_);
|
||||
this->reply_cut_ = state.cut;
|
||||
return result;
|
||||
}
|
||||
|
||||
command_result ModemComponent::at_(const char *cmd, uint32_t timeout) {
|
||||
std::string output;
|
||||
const command_result result = this->dce_->at(cmd, output, timeout);
|
||||
const command_result result = this->at_reply_(cmd, timeout);
|
||||
// A reply longer than the buffer kept only its end
|
||||
const char *cut = this->reply_cut_ ? LOG_STR_LITERAL("...") : "";
|
||||
if (result == command_result::OK) {
|
||||
ESP_LOGI(TAG, "AT '%s' -> OK: %s", cmd, output.c_str());
|
||||
ESP_LOGI(TAG, "AT '%s' -> OK: %s%s", cmd, cut, this->reply_);
|
||||
} else {
|
||||
ESP_LOGW(TAG, "AT '%s' -> %s: %s", cmd, LOG_STR_ARG(result_to_str(result)), output.c_str());
|
||||
ESP_LOGW(TAG, "AT '%s' -> %s: %s%s", cmd, LOG_STR_ARG(result_to_str(result)), cut, this->reply_);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -973,25 +1219,27 @@ SimResult ModemComponent::prepare_sim_() {
|
||||
return SimResult::SIM_RESULT_RETRY; // the save wakes the task
|
||||
}
|
||||
#endif
|
||||
std::string output;
|
||||
if (this->dce_->at("AT+CPIN?", output, COMMAND_TIMEOUT_MS) != command_result::OK) {
|
||||
// The raw reply keeps the +CME ERROR text a missing SIM gives; status below points into it
|
||||
const command_result result = this->at_reply_("AT+CPIN?");
|
||||
if (result == command_result::TIMEOUT) {
|
||||
// The next pass checks with a sync whether the modem or only the SIM interface is silent
|
||||
ESP_LOGD(TAG, "No answer to the SIM status request");
|
||||
this->sim_not_ready_(LOG_STR_LITERAL("no answer to AT+CPIN?"));
|
||||
this->request_resync_();
|
||||
return SimResult::SIM_RESULT_RETRY;
|
||||
}
|
||||
if (result != command_result::OK) {
|
||||
// A SIM that is still starting answers with an error for a second or so
|
||||
ESP_LOGD(TAG, "SIM status not readable yet: %s", output.c_str());
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
|
||||
ESP_LOGD(TAG, "SIM status not readable yet: %s", this->reply_);
|
||||
this->sim_not_ready_(this->reply_);
|
||||
return SimResult::SIM_RESULT_RETRY;
|
||||
}
|
||||
// Anything else, such as an echoed command, is not a status and must not reach the lock checks below
|
||||
const char *found = strstr(output.c_str(), "+CPIN:");
|
||||
if (found != nullptr) {
|
||||
found += sizeof("+CPIN:") - 1;
|
||||
while (*found == ' ') {
|
||||
found++;
|
||||
}
|
||||
}
|
||||
const char *found = sim_status(this->reply_);
|
||||
const StringRef status = found != nullptr ? StringRef(found) : StringRef();
|
||||
if (status.empty()) {
|
||||
ESP_LOGD(TAG, "SIM status not reported yet: %s", output.c_str());
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
|
||||
ESP_LOGD(TAG, "SIM status not reported yet: %s", this->reply_);
|
||||
this->sim_not_ready_(this->reply_);
|
||||
return SimResult::SIM_RESULT_RETRY;
|
||||
}
|
||||
ESP_LOGD(TAG, "SIM: %s", status.c_str());
|
||||
@@ -1019,8 +1267,8 @@ SimResult ModemComponent::prepare_sim_() {
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SIM_LOCKED);
|
||||
return SimResult::SIM_RESULT_LOCKED;
|
||||
}
|
||||
ESP_LOGW(TAG, "SIM not ready: %s", status.c_str()); // e.g. NOT READY or NOT INSERTED
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
|
||||
ESP_LOGD(TAG, "SIM not ready: %s", status.c_str()); // e.g. NOT READY or NOT INSERTED
|
||||
this->sim_not_ready_(status.c_str());
|
||||
return SimResult::SIM_RESULT_RETRY;
|
||||
}
|
||||
#ifdef USE_MODEM_PIN_CODE
|
||||
|
||||
@@ -62,6 +62,7 @@ enum class ModemFault : uint8_t {
|
||||
MODEM_FAULT_PIN_RECORD,
|
||||
MODEM_FAULT_SETUP,
|
||||
MODEM_FAULT_NOT_ATTACHED,
|
||||
MODEM_FAULT_REGISTRATION_DENIED,
|
||||
MODEM_FAULT_PPP,
|
||||
MODEM_FAULT_TEARDOWN,
|
||||
};
|
||||
@@ -151,6 +152,7 @@ class ModemComponent : public Component {
|
||||
static constexpr uint32_t RETRY_DELAY_MS = 1000;
|
||||
static constexpr size_t URC_LINE_SIZE = 128;
|
||||
static constexpr size_t AT_COMMAND_SIZE = 128;
|
||||
static constexpr size_t REPLY_SIZE = 256; // a longer reply keeps its newest bytes, so its final line counts
|
||||
#ifdef USE_MODEM_POLL
|
||||
static constexpr uint8_t CSQ_UNKNOWN = 99; // AT+CSQ rssi or ber the modem cannot tell
|
||||
static constexpr uint8_t CSQ_RSSI_MAX = 31;
|
||||
@@ -200,8 +202,20 @@ class ModemComponent : public Component {
|
||||
void hand_over_(uint32_t pending);
|
||||
/// Send an AT command from the task and log the result; blocks for up to the timeout
|
||||
esp_modem::command_result at_(const char *cmd, uint32_t timeout = COMMAND_TIMEOUT_MS);
|
||||
/// Send an AT command; reply_ gets the whole reply on one line, including any +CME ERROR text
|
||||
esp_modem::command_result at_reply_(const char *cmd, uint32_t timeout = COMMAND_TIMEOUT_MS);
|
||||
void publish_status_();
|
||||
/// Send the +++ escape with its guard times; true when the modem answered
|
||||
bool escape_data_mode_();
|
||||
/// Overflow a stuck CMUX receiver with flag bytes; true when the modem answers AT afterwards
|
||||
bool flush_cmux_();
|
||||
void request_resync_();
|
||||
int read_stat_(const char *cmd, const char *prefix);
|
||||
int read_registration_();
|
||||
/// Set the UART rate; current_baud_rate_ follows when the UART takes it
|
||||
esp_err_t set_uart_baud_(int baud);
|
||||
void not_responding_(int baud);
|
||||
void sim_not_ready_(const char *reason);
|
||||
void dump_connect_params_();
|
||||
SimResult prepare_sim_();
|
||||
#ifdef USE_MODEM_PIN_CODE
|
||||
@@ -221,6 +235,9 @@ class ModemComponent : public Component {
|
||||
const char *urc_line_{nullptr}; // the line urc_pending_ hands to loop(), inside urc_reader_
|
||||
#endif
|
||||
std::unique_ptr<esp_modem::DCE> dce_;
|
||||
char reply_[REPLY_SIZE + 1]{}; // task only; the last reply, null-terminated
|
||||
size_t reply_len_{0};
|
||||
bool reply_cut_{false}; // the last reply was longer than reply_ and kept only its end
|
||||
std::shared_ptr<esp_modem::DTE> dte_;
|
||||
esp_netif_t *ppp_netif_{nullptr};
|
||||
ESPPreferenceObject pref_;
|
||||
@@ -291,6 +308,9 @@ class ModemComponent : public Component {
|
||||
uint8_t init_at_count_{0};
|
||||
uint8_t uart_port_{UART_NUM_MAX};
|
||||
uint8_t attach_polls_{0};
|
||||
uint8_t idle_polls_{0}; // polls in a row that reported "not searching"
|
||||
uint8_t unknown_polls_{0}; // polls in a row with no usable registration state
|
||||
uint8_t sim_polls_{0}; // failed SIM status reads in this attempt
|
||||
#ifdef USE_MODEM_POLL
|
||||
uint8_t poll_rssi_{CSQ_UNKNOWN}; // raw AT+CSQ answers
|
||||
uint8_t poll_ber_{CSQ_UNKNOWN};
|
||||
@@ -298,7 +318,8 @@ class ModemComponent : public Component {
|
||||
#endif
|
||||
bool connect_timeout_armed_{false};
|
||||
bool modem_synced_{false}; // a modem that never answered has nothing to tear down
|
||||
bool resync_{false}; // the attachment read failed, so CONNECTING syncs again first
|
||||
bool answered_{false}; // the modem synced since boot, so its wiring and power are fine
|
||||
bool resync_{false}; // a command timed out, so CONNECTING syncs again first
|
||||
bool apn_pending_{false}; // ENABLING could not set the APN at CFUN=0, so CONNECTING sets it after the SIM check
|
||||
#ifdef USE_MODEM_SEND_AT
|
||||
char at_command_[AT_COMMAND_SIZE];
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from collections.abc import Callable
|
||||
import logging
|
||||
|
||||
from esphome import automation
|
||||
import esphome.codegen as cg
|
||||
@@ -8,6 +9,8 @@ import esphome.config_validation as cv
|
||||
from esphome.const import CONF_DURATION, CONF_ID, CONF_MODE, CONF_VOLTAGE
|
||||
from esphome.types import ConfigType
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CODEOWNERS = ["@tomaszduda23"]
|
||||
DEPENDENCIES = ["i2c"]
|
||||
DOMAIN = "npm1300"
|
||||
@@ -42,20 +45,18 @@ NPM1300_CHILD_SCHEMA = cv.Schema(
|
||||
{cv.GenerateID(CONF_NPM1300_ID): cv.use_id(NPM1300Component)}
|
||||
)
|
||||
|
||||
# Status registers read on each update: VBUSINSTATUS, BCHGCHARGESTATUS and BCHGERRREASON
|
||||
NPM1300Status = npm1300_ns.struct("NPM1300Status")
|
||||
# The status registers read on each update
|
||||
STATUS_PUBLISHER = cg.HubFunction(
|
||||
"status",
|
||||
cg.void,
|
||||
[
|
||||
(cg.uint8, "vbus_status"),
|
||||
(cg.uint8, "charge_status"),
|
||||
(cg.uint8, "error_reason"),
|
||||
],
|
||||
[(NPM1300Status.operator("const").operator("ref"), "status")],
|
||||
define="USE_NPM1300_STATUS_PUBLISHER",
|
||||
)
|
||||
VBUS_STATUS = STATUS_PUBLISHER.param("vbus_status")
|
||||
CHARGE_STATUS = STATUS_PUBLISHER.param("charge_status")
|
||||
ERROR_REASON = STATUS_PUBLISHER.param("error_reason")
|
||||
STATUS = STATUS_PUBLISHER.param("status")
|
||||
VBUS_STATUS = STATUS.vbus
|
||||
CHARGE_STATUS = STATUS.charge
|
||||
ERROR_REASON = STATUS.error_reason
|
||||
# The ADC results and the amperes per code of the battery current
|
||||
DATA_PUBLISHER = cg.HubFunction(
|
||||
"data",
|
||||
@@ -77,7 +78,10 @@ OUTPUTS = NPM1300Output.options(
|
||||
# Written for a field the YAML leaves out
|
||||
NPM1300_UNSET = 0xFF
|
||||
# ADCNTCRSEL codes, by kiloohms
|
||||
THERMISTOR_NONE = "none"
|
||||
THERMISTOR_RESISTANCES = {10: 1, 47: 2, 100: 3}
|
||||
# B25/50 of the thermistors the product specification lists for each resistance, by kiloohms
|
||||
THERMISTOR_BETAS = {10: 3380, 47: 4050, 100: 4250}
|
||||
LDO_MODES = {"load_switch": 0, "ldo": 1}
|
||||
TERMINATION_CURRENTS = {"10%": 0, "20%": 1}
|
||||
# BCHGVTRICKLESEL, by millivolts
|
||||
@@ -135,6 +139,24 @@ def _stepped(
|
||||
return validate
|
||||
|
||||
|
||||
_THERMISTOR_RESISTANCE = _one_of_units(
|
||||
cv.resistance, list(THERMISTOR_RESISTANCES), "kOhm", scale=0.001
|
||||
)
|
||||
|
||||
|
||||
def _thermistor_resistance(value: object) -> float | str:
|
||||
if isinstance(value, str) and value.lower() == THERMISTOR_NONE:
|
||||
return THERMISTOR_NONE
|
||||
return _THERMISTOR_RESISTANCE(value)
|
||||
|
||||
|
||||
def thermistor_beta(config: ConfigType) -> int:
|
||||
"""The B constant of the hub's thermistor: the configured one, or the one listed for its resistance."""
|
||||
if (beta := config.get(CONF_THERMISTOR_BETA)) is not None:
|
||||
return beta
|
||||
return THERMISTOR_BETAS[round(config[CONF_THERMISTOR_RESISTANCE] / 1000)]
|
||||
|
||||
|
||||
OUTPUT_VOLTAGE = _stepped(cv.voltage, 1000, 3300, 100, "V")
|
||||
VBUS_CURRENT_LIMIT = _stepped(cv.current, 100, 1500, 100, "A")
|
||||
|
||||
@@ -150,15 +172,58 @@ LDO_SCHEMA = BUCK_SCHEMA.extend(
|
||||
}
|
||||
)
|
||||
|
||||
CHARGER_SCHEMA = cv.Schema(
|
||||
WARM_TERMINATION_VOLTAGE_DEFAULT = 3.6
|
||||
|
||||
|
||||
def _warm_termination_default(config: ConfigType) -> ConfigType:
|
||||
"""Keep the default warm termination voltage at or below the termination voltage.
|
||||
|
||||
Warn when the default stays below a higher termination voltage.
|
||||
"""
|
||||
if (
|
||||
not isinstance(config, dict)
|
||||
or CONF_WARM_TERMINATION_VOLTAGE in config
|
||||
or CONF_TERMINATION_VOLTAGE not in config
|
||||
):
|
||||
return config
|
||||
try:
|
||||
termination = cv.voltage(config[CONF_TERMINATION_VOLTAGE])
|
||||
except cv.Invalid:
|
||||
# The schema reports it
|
||||
return config
|
||||
if termination < WARM_TERMINATION_VOLTAGE_DEFAULT - 0.001:
|
||||
# A warm battery is never charged higher than a cool one
|
||||
return {
|
||||
**config,
|
||||
CONF_WARM_TERMINATION_VOLTAGE: config[CONF_TERMINATION_VOLTAGE],
|
||||
}
|
||||
if termination > WARM_TERMINATION_VOLTAGE_DEFAULT + 0.001:
|
||||
_LOGGER.warning(
|
||||
"npm1300 '%s' is not set, so a warm battery (45 °C to 60 °C by default) stops "
|
||||
"charging at %.2fV instead of the %.2fV of '%s'. Set '%s' to the value your "
|
||||
"battery allows when warm",
|
||||
CONF_WARM_TERMINATION_VOLTAGE,
|
||||
WARM_TERMINATION_VOLTAGE_DEFAULT,
|
||||
termination,
|
||||
CONF_TERMINATION_VOLTAGE,
|
||||
CONF_WARM_TERMINATION_VOLTAGE,
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
_CHARGER_SETTINGS_SCHEMA = cv.Schema(
|
||||
{
|
||||
cv.Required(CONF_CHARGE_CURRENT): _stepped(cv.current, 32, 800, 2, "A"),
|
||||
cv.Optional(CONF_TERMINATION_VOLTAGE, default="4.2V"): _one_of_units(
|
||||
cv.voltage, TERMINATION_VOLTAGES, "V"
|
||||
# Defaults are the reset values of the product specification
|
||||
cv.Optional(CONF_CHARGE_CURRENT, default="32mA"): _stepped(
|
||||
cv.current, 32, 800, 2, "A"
|
||||
),
|
||||
cv.Optional(CONF_WARM_TERMINATION_VOLTAGE): _one_of_units(
|
||||
cv.Optional(CONF_TERMINATION_VOLTAGE, default="3.6V"): _one_of_units(
|
||||
cv.voltage, TERMINATION_VOLTAGES, "V"
|
||||
),
|
||||
cv.Optional(
|
||||
CONF_WARM_TERMINATION_VOLTAGE,
|
||||
default=f"{WARM_TERMINATION_VOLTAGE_DEFAULT}V",
|
||||
): _one_of_units(cv.voltage, TERMINATION_VOLTAGES, "V"),
|
||||
cv.Optional(CONF_TERMINATION_CURRENT, default="10%"): cv.enum(
|
||||
TERMINATION_CURRENTS
|
||||
),
|
||||
@@ -169,22 +234,37 @@ CHARGER_SCHEMA = cv.Schema(
|
||||
cv.current, list(DISCHARGE_CURRENT_LIMITS), "A"
|
||||
),
|
||||
cv.Optional(CONF_RECHARGE, default=True): cv.boolean,
|
||||
cv.Optional(CONF_ENABLED, default=True): cv.boolean,
|
||||
cv.Optional(CONF_ENABLED, default=False): cv.boolean,
|
||||
}
|
||||
)
|
||||
CHARGER_SCHEMA = cv.All(_warm_termination_default, _CHARGER_SETTINGS_SCHEMA)
|
||||
|
||||
|
||||
CONFIG_SCHEMA = (
|
||||
def _check_thermistor(config: ConfigType) -> ConfigType:
|
||||
"""A wrong thermistor shifts the battery temperature the charger sees, so charging needs one chosen."""
|
||||
resistance = config.get(CONF_THERMISTOR_RESISTANCE)
|
||||
if CONF_CHARGER in config and resistance is None:
|
||||
raise cv.Invalid(
|
||||
f"'{CONF_THERMISTOR_RESISTANCE}' is required with '{CONF_CHARGER}': set the nominal "
|
||||
f"resistance of the battery thermistor, or '{THERMISTOR_NONE}'",
|
||||
path=[CONF_THERMISTOR_RESISTANCE],
|
||||
)
|
||||
if CONF_THERMISTOR_BETA in config and resistance in (None, THERMISTOR_NONE):
|
||||
raise cv.Invalid(
|
||||
f"'{CONF_THERMISTOR_BETA}' needs '{CONF_THERMISTOR_RESISTANCE}' set to the "
|
||||
"resistance of the thermistor",
|
||||
path=[CONF_THERMISTOR_BETA],
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(NPM1300Component),
|
||||
cv.Optional(CONF_VBUS_CURRENT_LIMIT): VBUS_CURRENT_LIMIT,
|
||||
cv.Optional(CONF_THERMISTOR_RESISTANCE): _one_of_units(
|
||||
cv.resistance, list(THERMISTOR_RESISTANCES), "kOhm", scale=0.001
|
||||
),
|
||||
cv.Optional(CONF_THERMISTOR_BETA, default=3380): cv.int_range(
|
||||
min=1, max=65535
|
||||
),
|
||||
cv.Optional(CONF_THERMISTOR_RESISTANCE): _thermistor_resistance,
|
||||
cv.Optional(CONF_THERMISTOR_BETA): cv.int_range(min=1, max=65535),
|
||||
cv.Optional(CONF_CHARGER): CHARGER_SCHEMA,
|
||||
cv.Optional(CONF_BUCK1): BUCK_SCHEMA,
|
||||
cv.Optional(CONF_BUCK2): BUCK_SCHEMA,
|
||||
@@ -193,7 +273,8 @@ CONFIG_SCHEMA = (
|
||||
}
|
||||
)
|
||||
.extend(cv.polling_component_schema("60s"))
|
||||
.extend(i2c.i2c_device_schema(0x6B))
|
||||
.extend(i2c.i2c_device_schema(0x6B)),
|
||||
_check_thermistor,
|
||||
)
|
||||
|
||||
|
||||
@@ -208,7 +289,7 @@ def _vbus_current_limit_code(amps: float) -> int:
|
||||
|
||||
def _charger_config(config: ConfigType) -> cg.StructInitializer:
|
||||
termination = _termination_voltage_code(config[CONF_TERMINATION_VOLTAGE])
|
||||
warm = config.get(CONF_WARM_TERMINATION_VOLTAGE)
|
||||
warm = _termination_voltage_code(config[CONF_WARM_TERMINATION_VOLTAGE])
|
||||
return cg.StructInitializer(
|
||||
NPM1300ChargerConfig,
|
||||
("current", _millis(config[CONF_CHARGE_CURRENT]) // 2),
|
||||
@@ -217,10 +298,7 @@ def _charger_config(config: ConfigType) -> cg.StructInitializer:
|
||||
DISCHARGE_CURRENT_LIMITS[_millis(config[CONF_DISCHARGE_CURRENT_LIMIT])],
|
||||
),
|
||||
("termination_voltage", termination),
|
||||
(
|
||||
"warm_termination_voltage",
|
||||
termination if warm is None else _termination_voltage_code(warm),
|
||||
),
|
||||
("warm_termination_voltage", warm),
|
||||
("trickle_voltage", TRICKLE_VOLTAGES[_millis(config[CONF_TRICKLE_VOLTAGE])]),
|
||||
("termination_current", TERMINATION_CURRENTS[config[CONF_TERMINATION_CURRENT]]),
|
||||
("recharge", config[CONF_RECHARGE]),
|
||||
@@ -247,6 +325,13 @@ def _output_config(config: ConfigType | None) -> cg.StructInitializer:
|
||||
def _config(config: ConfigType) -> cg.StructInitializer:
|
||||
charger = config.get(CONF_CHARGER)
|
||||
resistance = config.get(CONF_THERMISTOR_RESISTANCE)
|
||||
if resistance is None:
|
||||
thermistor, beta = NPM1300_UNSET, 0
|
||||
elif resistance == THERMISTOR_NONE:
|
||||
thermistor, beta = 0, 0
|
||||
else:
|
||||
thermistor = THERMISTOR_RESISTANCES[round(resistance / 1000)]
|
||||
beta = thermistor_beta(config)
|
||||
return cg.StructInitializer(
|
||||
NPM1300Config,
|
||||
(
|
||||
@@ -254,13 +339,8 @@ def _config(config: ConfigType) -> cg.StructInitializer:
|
||||
cg.ArrayInitializer(*(_output_config(config.get(key)) for key in OUTPUTS)),
|
||||
),
|
||||
("charger", None if charger is None else _charger_config(charger)),
|
||||
("thermistor_beta", config[CONF_THERMISTOR_BETA]),
|
||||
(
|
||||
"thermistor",
|
||||
NPM1300_UNSET
|
||||
if resistance is None
|
||||
else THERMISTOR_RESISTANCES[round(resistance / 1000)],
|
||||
),
|
||||
("thermistor_beta", beta),
|
||||
("thermistor", thermistor),
|
||||
("charger_configured", charger is not None),
|
||||
)
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ static constexpr uint16_t REG_BCHG_VTERM = 0x030C;
|
||||
static constexpr uint16_t REG_BCHG_VTERM_R = 0x030D;
|
||||
static constexpr uint16_t REG_BCHG_VTRICKLE_SEL = 0x030E;
|
||||
static constexpr uint16_t REG_BCHG_ITERM_SEL = 0x030F;
|
||||
static constexpr uint16_t REG_BCHG_NTC_STATUS = 0x0332;
|
||||
static constexpr uint16_t REG_BCHG_CHARGE_STATUS = 0x0334;
|
||||
static constexpr uint16_t REG_BCHG_ERR_REASON = 0x0336;
|
||||
static constexpr uint16_t REG_BUCK1_ENA_SET = 0x0400;
|
||||
@@ -53,6 +54,9 @@ static constexpr uint16_t REG_SHIP_TASK_SHIP_MODE = 0x0B02;
|
||||
|
||||
// VBUSINSTATUS
|
||||
static constexpr uint8_t VBUS_PRESENT = 0x01;
|
||||
// NTCSTATUS
|
||||
static constexpr uint8_t NTC_STATUS_COLD = 0x01;
|
||||
static constexpr uint8_t NTC_STATUS_HOT = 0x08;
|
||||
// BCHGCHARGESTATUS; bit 0 (battery detected) is reserved since C00 silicon
|
||||
static constexpr uint8_t CHARGE_STATUS_COMPLETED = 0x02;
|
||||
static constexpr uint8_t CHARGE_STATUS_TRICKLE = 0x04;
|
||||
@@ -107,26 +111,36 @@ float ntc_temperature(uint16_t code, float inv_beta) {
|
||||
#endif
|
||||
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
PROGMEM_STRING_TABLE(ChargerStatusStrings, "Error", "Paused, Die Too Hot", "Charge Complete", "Trickle Charge",
|
||||
"Constant Current", "Constant Voltage", "Discharging", "Not Charging");
|
||||
// BCHGCHARGESTATUS bits in order of priority; bit i is reported as string i + 1
|
||||
PROGMEM_STRING_TABLE(ChargerStatusStrings, "Discharging", "Error", "Disabled", "Paused, PMIC Too Hot",
|
||||
"Charge Complete", "Trickle Charge", "Constant Current", "Constant Voltage",
|
||||
"Paused, Battery Too Cold", "Paused, Battery Too Hot", "Not Charging");
|
||||
static constexpr uint8_t CHARGER_STATUS_FIRST_BIT = 3;
|
||||
// BCHGCHARGESTATUS bits in order of priority, reported from string CHARGER_STATUS_FIRST_BIT on
|
||||
static const uint8_t CHARGER_STATUS_BITS[] PROGMEM = {CHARGE_STATUS_DIE_TEMP_HIGH, CHARGE_STATUS_COMPLETED,
|
||||
CHARGE_STATUS_TRICKLE, CHARGE_STATUS_CONSTANT_CURRENT,
|
||||
CHARGE_STATUS_CONSTANT_VOLTAGE};
|
||||
|
||||
static uint8_t charger_status_index(uint8_t vbus_status, uint8_t charge_status, uint8_t error_reason) {
|
||||
if (error_reason != 0)
|
||||
static uint8_t charger_status_index(const NPM1300Status &status) {
|
||||
if ((status.vbus & VBUS_PRESENT) == 0)
|
||||
return 0;
|
||||
if (status.error_reason != 0)
|
||||
return 1;
|
||||
if ((status.charger_enable & 1) == 0)
|
||||
return 2;
|
||||
for (size_t i = 0; i < sizeof(CHARGER_STATUS_BITS); i++) {
|
||||
if ((charge_status & progmem_read_byte(&CHARGER_STATUS_BITS[i])) != 0)
|
||||
return i + 1;
|
||||
if ((status.charge & progmem_read_byte(&CHARGER_STATUS_BITS[i])) != 0)
|
||||
return CHARGER_STATUS_FIRST_BIT + i;
|
||||
}
|
||||
return (vbus_status & VBUS_PRESENT) == 0 ? 6 : 7;
|
||||
// The charger stops without an error outside the cold and hot limits of the battery temperature
|
||||
if ((status.ntc & NTC_STATUS_COLD) != 0)
|
||||
return 8;
|
||||
if ((status.ntc & NTC_STATUS_HOT) != 0)
|
||||
return 9;
|
||||
return 10;
|
||||
}
|
||||
|
||||
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, uint8_t vbus_status, uint8_t charge_status,
|
||||
uint8_t error_reason) {
|
||||
const uint8_t index = charger_status_index(vbus_status, charge_status, error_reason);
|
||||
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, const NPM1300Status &status) {
|
||||
const uint8_t index = charger_status_index(status);
|
||||
if (index == last)
|
||||
return;
|
||||
last = index;
|
||||
@@ -198,7 +212,7 @@ bool NPM1300Component::configure_charger_(const NPM1300Config &config) {
|
||||
split_9bit(charger.discharge_limit, discharge);
|
||||
uint8_t disable = charger.recharge ? 0 : CHARGER_DISABLE_RECHARGE;
|
||||
// Without a thermistor the charger reports an NTC error and does not charge
|
||||
if (config.thermistor == NPM1300_UNSET)
|
||||
if (config.thermistor == 0 || config.thermistor == NPM1300_UNSET)
|
||||
disable |= CHARGER_DISABLE_NTC;
|
||||
const uint8_t enable = (CHARGER_DISABLE_RECHARGE | CHARGER_DISABLE_NTC) & ~disable;
|
||||
if (this->write_register16(REG_BCHG_ISET_MSB, current, sizeof(current)) != i2c::ERROR_OK ||
|
||||
@@ -292,33 +306,40 @@ void NPM1300Component::hibernate(uint32_t duration_ms) {
|
||||
}
|
||||
|
||||
void NPM1300Component::update() {
|
||||
uint8_t vbus_status;
|
||||
uint8_t charge_status;
|
||||
uint8_t error_reason;
|
||||
if (!this->status_comm_check(this->read_byte_reg16(REG_VBUSIN_STATUS, &vbus_status) &&
|
||||
this->read_byte_reg16(REG_BCHG_CHARGE_STATUS, &charge_status) &&
|
||||
this->read_byte_reg16(REG_BCHG_ERR_REASON, &error_reason)))
|
||||
NPM1300Status status;
|
||||
// NTCSTATUS, DIETEMPSTATUS and BCHGCHARGESTATUS
|
||||
uint8_t charger_status[3];
|
||||
if (!this->status_comm_check(this->read_byte_reg16(REG_VBUSIN_STATUS, &status.vbus) &&
|
||||
this->read_byte_reg16(REG_BCHG_ENABLE_SET, &status.charger_enable) &&
|
||||
this->read_register16(REG_BCHG_NTC_STATUS, charger_status, sizeof(charger_status)) ==
|
||||
i2c::ERROR_OK &&
|
||||
this->read_byte_reg16(REG_BCHG_ERR_REASON, &status.error_reason)))
|
||||
return;
|
||||
status.ntc = charger_status[0];
|
||||
status.charge = charger_status[2];
|
||||
// Without a thermistor the NTC pin is grounded and can read as a hot battery
|
||||
if (progmem_read_byte(&this->config_->thermistor) == 0)
|
||||
status.ntc = 0;
|
||||
|
||||
// The chip goes back to its default VBUS current limit whenever VBUS is removed
|
||||
const bool vbus_present = (vbus_status & VBUS_PRESENT) != 0;
|
||||
const bool vbus_present = (status.vbus & VBUS_PRESENT) != 0;
|
||||
if (vbus_present && !this->vbus_present_ && this->vbus_current_limit_ != NPM1300_UNSET &&
|
||||
!this->status_comm_check(this->apply_vbus_current_limit_()))
|
||||
return;
|
||||
this->vbus_present_ = vbus_present;
|
||||
|
||||
if (error_reason != this->last_error_reason_) {
|
||||
this->last_error_reason_ = error_reason;
|
||||
if (error_reason != 0) {
|
||||
ESP_LOGW(TAG, "Charger error, BCHGERRREASON 0x%02X", error_reason);
|
||||
if (status.error_reason != this->last_error_reason_) {
|
||||
this->last_error_reason_ = status.error_reason;
|
||||
if (status.error_reason != 0) {
|
||||
ESP_LOGW(TAG, "Charger error, BCHGERRREASON 0x%02X", status.error_reason);
|
||||
}
|
||||
}
|
||||
#ifdef USE_NPM1300_STATUS_PUBLISHER
|
||||
if (this->status_publisher_ != nullptr)
|
||||
this->status_publisher_(vbus_status, charge_status, error_reason);
|
||||
this->status_publisher_(status);
|
||||
#endif
|
||||
#ifdef USE_SWITCH
|
||||
if (!this->status_comm_check(this->publish_switches_()))
|
||||
if (!this->status_comm_check(this->publish_switches_(status)))
|
||||
return;
|
||||
#endif
|
||||
|
||||
@@ -348,16 +369,10 @@ void NPM1300Component::update() {
|
||||
}
|
||||
|
||||
#ifdef USE_SWITCH
|
||||
bool NPM1300Component::publish_switches_() {
|
||||
bool NPM1300Component::publish_switches_(const NPM1300Status &status) {
|
||||
PUBLISH_STATE(this->charger_switch_, (status.charger_enable & 1) != 0);
|
||||
uint8_t value;
|
||||
bool ok = true;
|
||||
if (this->charger_switch_ != nullptr) {
|
||||
if (this->read_byte_reg16(REG_BCHG_ENABLE_SET, &value)) {
|
||||
this->charger_switch_->publish_state((value & 1) != 0);
|
||||
} else {
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
switch_::Switch *const bucks[2] = {this->buck1_switch_, this->buck2_switch_};
|
||||
if (bucks[0] != nullptr || bucks[1] != nullptr) {
|
||||
if (this->read_byte_reg16(REG_BUCK_STATUS, &value)) {
|
||||
@@ -461,7 +476,9 @@ void NPM1300Component::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, " Enabled at boot: %s", YESNO(output.enabled != 0));
|
||||
}
|
||||
}
|
||||
if (config.thermistor != NPM1300_UNSET) {
|
||||
if (config.thermistor == 0) {
|
||||
ESP_LOGCONFIG(TAG, " Thermistor: none");
|
||||
} else if (config.thermistor != NPM1300_UNSET) {
|
||||
ESP_LOGCONFIG(TAG, " Thermistor B constant: %u", config.thermistor_beta);
|
||||
}
|
||||
#ifdef USE_SENSOR
|
||||
|
||||
@@ -54,10 +54,19 @@ struct NPM1300Config {
|
||||
NPM1300OutputConfig outputs[NPM1300_OUTPUT_COUNT];
|
||||
NPM1300ChargerConfig charger; // only applied when charger_configured
|
||||
uint16_t thermistor_beta;
|
||||
uint8_t thermistor; // ADCNTCRSEL code: 1 for 10 kOhm, 2 for 47 kOhm, 3 for 100 kOhm, or NPM1300_UNSET
|
||||
uint8_t thermistor; // ADCNTCRSEL code: 0 for none, 1 for 10 kOhm, 2 for 47 kOhm, 3 for 100 kOhm, or NPM1300_UNSET
|
||||
bool charger_configured;
|
||||
};
|
||||
|
||||
/// The status registers read on every update
|
||||
struct NPM1300Status {
|
||||
uint8_t vbus; // VBUSINSTATUS
|
||||
uint8_t charger_enable; // BCHGENABLESET
|
||||
uint8_t ntc; // NTCSTATUS
|
||||
uint8_t charge; // BCHGCHARGESTATUS
|
||||
uint8_t error_reason; // BCHGERRREASON
|
||||
};
|
||||
|
||||
#ifdef USE_NPM1300_DATA_PUBLISHER
|
||||
/// The 10-bit ADC result whose high 8 bits are adc[msb] and low 2 bits are at `shift` in adc[lsbs]
|
||||
inline uint16_t adc_code(const uint8_t *adc, uint8_t msb, uint8_t lsbs, uint8_t shift) {
|
||||
@@ -68,8 +77,7 @@ float ntc_temperature(uint16_t code, float inv_beta);
|
||||
#endif
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
/// Publish the charger status text, only when it differs from `last`
|
||||
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, uint8_t vbus_status, uint8_t charge_status,
|
||||
uint8_t error_reason);
|
||||
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, const NPM1300Status &status);
|
||||
#endif
|
||||
|
||||
class NPM1300Component : public PollingComponent, public i2c::I2CDevice {
|
||||
@@ -95,7 +103,7 @@ class NPM1300Component : public PollingComponent, public i2c::I2CDevice {
|
||||
float get_setup_priority() const override { return setup_priority::BUS - 1.0f; }
|
||||
|
||||
#ifdef USE_NPM1300_STATUS_PUBLISHER
|
||||
HUB_PUBLISHER(status, uint8_t, uint8_t, uint8_t)
|
||||
HUB_PUBLISHER(status, const NPM1300Status &)
|
||||
#endif
|
||||
#ifdef USE_NPM1300_DATA_PUBLISHER
|
||||
HUB_PUBLISHER(data, const uint8_t *, float)
|
||||
@@ -128,7 +136,7 @@ class NPM1300Component : public PollingComponent, public i2c::I2CDevice {
|
||||
#endif
|
||||
#ifdef USE_SWITCH
|
||||
/// Returns false when a status read failed
|
||||
bool publish_switches_();
|
||||
bool publish_switches_(const NPM1300Status &status);
|
||||
#endif
|
||||
|
||||
const NPM1300Config *config_;
|
||||
|
||||
@@ -21,7 +21,6 @@ from esphome.types import ConfigType
|
||||
from . import (
|
||||
ADC,
|
||||
CONF_NPM1300_ID,
|
||||
CONF_THERMISTOR_BETA,
|
||||
CONF_THERMISTOR_RESISTANCE,
|
||||
CONF_VBUS_CURRENT_LIMIT,
|
||||
DATA_PUBLISHER,
|
||||
@@ -30,7 +29,9 @@ from . import (
|
||||
DUMP_TAG,
|
||||
IBAT_SCALE,
|
||||
NPM1300_CHILD_SCHEMA,
|
||||
THERMISTOR_NONE,
|
||||
npm1300_ns,
|
||||
thermistor_beta,
|
||||
)
|
||||
|
||||
DEPENDENCIES = ["npm1300"]
|
||||
@@ -109,10 +110,10 @@ def _final_validate(config: ConfigType) -> None:
|
||||
if CONF_BATTERY_TEMPERATURE not in config:
|
||||
return
|
||||
hub = fv.get_declaring_config(config[CONF_NPM1300_ID])
|
||||
if CONF_THERMISTOR_RESISTANCE not in hub:
|
||||
if hub.get(CONF_THERMISTOR_RESISTANCE, THERMISTOR_NONE) == THERMISTOR_NONE:
|
||||
raise cv.Invalid(
|
||||
f"'{CONF_BATTERY_TEMPERATURE}' needs '{CONF_THERMISTOR_RESISTANCE}' "
|
||||
"set on the npm1300 component",
|
||||
f"'{CONF_BATTERY_TEMPERATURE}' needs '{CONF_THERMISTOR_RESISTANCE}' set to the "
|
||||
"nominal resistance of the battery thermistor on the npm1300 component",
|
||||
path=[CONF_BATTERY_TEMPERATURE],
|
||||
)
|
||||
|
||||
@@ -145,7 +146,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
if (var := await sensors(CONF_BATTERY_TEMPERATURE, None)) is not None:
|
||||
hub_config = next(c for c in CORE.config[DOMAIN] if c[CONF_ID] == hub_id)
|
||||
state = npm1300_ns.ntc_temperature(
|
||||
_adc(2, 5, 2), 1.0 / hub_config[CONF_THERMISTOR_BETA]
|
||||
_adc(2, 5, 2), 1.0 / thermistor_beta(hub_config)
|
||||
)
|
||||
_add_adc_sensor(hub, var, state, "Battery Temperature")
|
||||
await sensors(CONF_VBUS_CURRENT_LIMIT, hub.set_vbus_current_limit_sensor)
|
||||
@@ -15,6 +15,7 @@ from . import (
|
||||
CONF_THERMISTOR_RESISTANCE,
|
||||
NPM1300_CHILD_SCHEMA,
|
||||
OUTPUTS,
|
||||
THERMISTOR_NONE,
|
||||
)
|
||||
|
||||
DEPENDENCIES = ["npm1300"]
|
||||
@@ -44,11 +45,18 @@ def _final_validate(config: ConfigType) -> None:
|
||||
if CONF_CHARGER not in config:
|
||||
return
|
||||
hub = fv.get_declaring_config(config[CONF_NPM1300_ID])
|
||||
# Only the charger block turns off the NTC check, without which the charger never starts
|
||||
if CONF_CHARGER not in hub and CONF_THERMISTOR_RESISTANCE not in hub:
|
||||
# A wrong thermistor shifts the battery temperature the charger sees
|
||||
if CONF_THERMISTOR_RESISTANCE not in hub:
|
||||
raise cv.Invalid(
|
||||
f"The '{CONF_CHARGER}' switch needs a '{CONF_CHARGER}' block or "
|
||||
f"'{CONF_THERMISTOR_RESISTANCE}' on the npm1300 component",
|
||||
f"The '{CONF_CHARGER}' switch needs '{CONF_THERMISTOR_RESISTANCE}' on the npm1300 "
|
||||
f"component: the nominal resistance of the battery thermistor, or '{THERMISTOR_NONE}'",
|
||||
path=[CONF_CHARGER],
|
||||
)
|
||||
# Only the charger block turns off the NTC check, without which the charger never starts
|
||||
if CONF_CHARGER not in hub and hub[CONF_THERMISTOR_RESISTANCE] == THERMISTOR_NONE:
|
||||
raise cv.Invalid(
|
||||
f"The '{CONF_CHARGER}' switch needs a '{CONF_CHARGER}' block when "
|
||||
f"'{CONF_THERMISTOR_RESISTANCE}' is '{THERMISTOR_NONE}'",
|
||||
path=[CONF_CHARGER],
|
||||
)
|
||||
|
||||
|
||||
@@ -11,14 +11,12 @@ from esphome.cpp_generator import (
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from . import (
|
||||
CHARGE_STATUS,
|
||||
CONF_NPM1300_ID,
|
||||
DUMP,
|
||||
DUMP_TAG,
|
||||
ERROR_REASON,
|
||||
NPM1300_CHILD_SCHEMA,
|
||||
STATUS,
|
||||
STATUS_PUBLISHER,
|
||||
VBUS_STATUS,
|
||||
npm1300_ns,
|
||||
)
|
||||
|
||||
@@ -48,9 +46,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
)
|
||||
STATUS_PUBLISHER.add(
|
||||
hub,
|
||||
npm1300_ns.publish_charger_status(
|
||||
parent_ref(var), last, VBUS_STATUS, CHARGE_STATUS, ERROR_REASON
|
||||
),
|
||||
npm1300_ns.publish_charger_status(parent_ref(var), last, STATUS),
|
||||
)
|
||||
DUMP.add(
|
||||
hub,
|
||||
|
||||
+3
-25
@@ -153,7 +153,6 @@
|
||||
#define USE_LINE_READER
|
||||
#define USE_LOCK
|
||||
#define USE_LOGGER
|
||||
#define USE_LOGGER_CONSOLE
|
||||
#define USE_LOGGER_LEVEL_LISTENERS
|
||||
#define USE_LOGGER_RUNTIME_TAG_LEVELS
|
||||
#define USE_LVGL
|
||||
@@ -768,26 +767,16 @@
|
||||
#if defined(USE_ESP32_VARIANT_ESP32S2)
|
||||
#define USE_LOGGER_USB_CDC
|
||||
#define USE_LOGGER_UART_SELECTION_USB_CDC
|
||||
#define ESPHOME_LOGGER_UART_NAME "USB_CDC"
|
||||
#define ESPHOME_LOGGER_UART_SELECTION logger::UART_SELECTION_USB_CDC
|
||||
#elif defined(USE_ESP32_VARIANT_ESP32H21)
|
||||
#define USE_LOGGER_USB_SERIAL_JTAG
|
||||
#define USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG
|
||||
#define ESPHOME_LOGGER_UART_NAME "USB_SERIAL_JTAG"
|
||||
#define ESPHOME_LOGGER_UART_SELECTION logger::UART_SELECTION_USB_SERIAL_JTAG
|
||||
#elif defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C5) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32C6) || defined(USE_ESP32_VARIANT_ESP32C61) || defined(USE_ESP32_VARIANT_ESP32H2) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32H4) || defined(USE_ESP32_VARIANT_ESP32P4) || defined(USE_ESP32_VARIANT_ESP32S3) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32S31)
|
||||
defined(USE_ESP32_VARIANT_ESP32H21) || defined(USE_ESP32_VARIANT_ESP32H4) || defined(USE_ESP32_VARIANT_ESP32P4) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32S3) || defined(USE_ESP32_VARIANT_ESP32S31)
|
||||
#define USE_LOGGER_USB_CDC
|
||||
#define USE_LOGGER_UART_SELECTION_USB_CDC
|
||||
#define USE_LOGGER_USB_SERIAL_JTAG
|
||||
#define USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG
|
||||
#define ESPHOME_LOGGER_UART_NAME "USB_SERIAL_JTAG"
|
||||
#define ESPHOME_LOGGER_UART_SELECTION logger::UART_SELECTION_USB_SERIAL_JTAG
|
||||
#else
|
||||
#define USE_LOGGER_UART_SELECTION_UART0
|
||||
#define ESPHOME_LOGGER_UART_NAME "UART0"
|
||||
#define ESPHOME_LOGGER_UART_SELECTION logger::UART_SELECTION_UART0
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -801,9 +790,6 @@
|
||||
#define USE_WIFI_SCAN_RESULTS_LOCK
|
||||
#define USE_ESP8266_LOGGER_SERIAL
|
||||
#define USE_ESP8266_LOGGER_SERIAL1
|
||||
#define USE_LOGGER_UART_SELECTION_UART0
|
||||
#define ESPHOME_LOGGER_UART_NAME "UART0"
|
||||
#define ESPHOME_LOGGER_UART_SELECTION logger::UART_SELECTION_UART0
|
||||
#define USE_ESP8266_PREFERENCES_FLASH
|
||||
#define ESP8266_PREFERENCES_FLASH_WORDS 128
|
||||
#define ESP8266_PREFERENCES_RTC_EBOOT_WORDS 32
|
||||
@@ -849,8 +835,6 @@
|
||||
#define USE_I2C
|
||||
#define USE_LOGGER_USB_CDC
|
||||
#define USE_LOGGER_UART_SELECTION_USB_CDC
|
||||
#define ESPHOME_LOGGER_UART_NAME "USB_CDC"
|
||||
#define ESPHOME_LOGGER_UART_SELECTION logger::UART_SELECTION_USB_CDC
|
||||
#define USE_SOCKET_IMPL_LWIP_TCP
|
||||
#define USE_RP2040_BLE
|
||||
#define USE_RP2_BLE_TRACKER
|
||||
@@ -881,9 +865,6 @@
|
||||
#if defined(USE_BK72XX) || defined(USE_RTL87XX) || defined(USE_LN882X)
|
||||
#define USE_LIBRETINY_CRASH_HANDLER
|
||||
#endif
|
||||
#define USE_LOGGER_UART_SELECTION_DEFAULT
|
||||
#define ESPHOME_LOGGER_UART_NAME "DEFAULT"
|
||||
#define ESPHOME_LOGGER_UART_SELECTION logger::UART_SELECTION_DEFAULT
|
||||
#ifdef USE_BK72XX
|
||||
#define USE_REMOTE_RECEIVER_TIMER_SAMPLING
|
||||
#endif
|
||||
@@ -938,11 +919,8 @@
|
||||
#define ESPHOME_TASK_LOG_BUFFER_SIZE 768
|
||||
#define USE_LOGGER_EARLY_MESSAGE
|
||||
#define USE_LOGGER_UART_SELECTION_USB_CDC
|
||||
#define ESPHOME_LOGGER_UART_NAME "USB_CDC"
|
||||
#define ESPHOME_LOGGER_UART_SELECTION logger::UART_SELECTION_USB_CDC
|
||||
#define USE_LOGGER_USB_CDC
|
||||
#define USE_LOGGER_WAIT_FOR_CDC
|
||||
#define USE_LOGGER_ZEPHYR_CDC_LOOP
|
||||
#define USE_NRF52_DFU
|
||||
#define USE_NRF52_REG0_VOUT 5
|
||||
#define USE_NRF52_UICR_ERASE
|
||||
|
||||
@@ -68,6 +68,38 @@ def test_logger_pre_setup_before_other_components(generate_main):
|
||||
)
|
||||
|
||||
|
||||
def test_default_uart_selection_is_not_emitted(generate_main):
|
||||
"""UART0 is the C++ initializer on ESP8266, so the setter is skipped."""
|
||||
main_cpp = generate_main("tests/component_tests/logger/test_logger.yaml")
|
||||
|
||||
assert "set_uart_selection(" not in main_cpp
|
||||
|
||||
|
||||
def test_custom_uart_selection_is_emitted(generate_main):
|
||||
"""A non default UART still reaches the setter before pre_setup()."""
|
||||
main_cpp = generate_main("tests/component_tests/logger/test_logger_uart1.yaml")
|
||||
|
||||
assert "set_uart_selection(logger::UART_SELECTION_UART1);" in main_cpp
|
||||
|
||||
|
||||
def test_libretiny_default_uart_selection_is_not_emitted(generate_main):
|
||||
"""DEFAULT is the C++ initializer on LibreTiny, so the setter is skipped."""
|
||||
main_cpp = generate_main(
|
||||
"tests/component_tests/logger/test_logger_libretiny_default.yaml"
|
||||
)
|
||||
|
||||
assert "set_uart_selection(" not in main_cpp
|
||||
|
||||
|
||||
def test_libretiny_uart0_is_emitted(generate_main):
|
||||
"""UART0 is not the LibreTiny initializer, so it must still be set."""
|
||||
main_cpp = generate_main(
|
||||
"tests/component_tests/logger/test_logger_libretiny_uart0.yaml"
|
||||
)
|
||||
|
||||
assert "set_uart_selection(logger::UART_SELECTION_UART0);" in main_cpp
|
||||
|
||||
|
||||
def test_ram_log_strings_is_deprecated(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
@@ -136,76 +168,35 @@ def test_log_v2_only_on_native_toolchain(
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("config", "port", "zephyr_cdc_loop"),
|
||||
("config", "expected"),
|
||||
[
|
||||
pytest.param("test_logger.yaml", "UART0", False, id="esp8266_default"),
|
||||
pytest.param("test_logger_uart1.yaml", "UART1", False, id="esp8266_uart1"),
|
||||
pytest.param(
|
||||
"test_logger_uart0_swap.yaml", "UART0_SWAP", False, id="esp8266_uart0_swap"
|
||||
),
|
||||
pytest.param(
|
||||
"test_logger_libretiny_default.yaml",
|
||||
"DEFAULT",
|
||||
False,
|
||||
id="libretiny_default",
|
||||
),
|
||||
pytest.param(
|
||||
"test_logger_libretiny_uart0.yaml", "UART0", False, id="libretiny_uart0"
|
||||
),
|
||||
pytest.param(
|
||||
"test_logger_rp2_usb_cdc.yaml", "USB_CDC", False, id="rp2_usb_cdc"
|
||||
),
|
||||
pytest.param("test_logger_rp2_uart0.yaml", "UART0", False, id="rp2_uart0"),
|
||||
pytest.param(
|
||||
"test_logger_esp32_usb_cdc.yaml", "USB_CDC", False, id="esp32_usb_cdc"
|
||||
),
|
||||
pytest.param("test_logger_rp2_usb_cdc.yaml", {"USB_CDC"}, id="rp2_usb_cdc"),
|
||||
pytest.param("test_logger_rp2_uart0.yaml", set(), id="rp2_uart0"),
|
||||
pytest.param("test_logger_esp32_usb_cdc.yaml", {"USB_CDC"}, id="esp32_usb_cdc"),
|
||||
pytest.param(
|
||||
"test_logger_esp32_usb_serial_jtag.yaml",
|
||||
"USB_SERIAL_JTAG",
|
||||
False,
|
||||
{"USB_SERIAL_JTAG"},
|
||||
id="esp32_usb_serial_jtag",
|
||||
),
|
||||
pytest.param(
|
||||
"test_logger_nrf52_usb_cdc.yaml", "USB_CDC", True, id="nrf52_usb_cdc"
|
||||
),
|
||||
pytest.param("test_logger_nrf52_usb_cdc.yaml", {"USB_CDC"}, id="nrf52_usb_cdc"),
|
||||
# Zephyr polls the USB port only when it logs there
|
||||
pytest.param(
|
||||
"test_logger_nrf52_usb_cdc_no_serial.yaml",
|
||||
"USB_CDC",
|
||||
False,
|
||||
id="nrf52_no_serial",
|
||||
"test_logger_nrf52_usb_cdc_no_serial.yaml", set(), id="nrf52_no_serial"
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_uart_selection_defines(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
config: str,
|
||||
port: str,
|
||||
zephyr_cdc_loop: bool,
|
||||
expected: set[str],
|
||||
) -> None:
|
||||
"""The chosen port is fixed at build time: one flag, its enum value and its dump_config name."""
|
||||
"""USB ports get a selection define, which gates their port code and crash replay."""
|
||||
generate_main(f"tests/component_tests/logger/{config}")
|
||||
|
||||
defines = {d.name: d.value for d in CORE.defines}
|
||||
prefix = "USE_LOGGER_UART_SELECTION_"
|
||||
assert {d.removeprefix(prefix) for d in defines if d.startswith(prefix)} == {port}
|
||||
assert (
|
||||
str(defines["ESPHOME_LOGGER_UART_SELECTION"])
|
||||
== f"logger::UART_SELECTION_{port}"
|
||||
)
|
||||
assert str(defines["ESPHOME_LOGGER_UART_NAME"]) == f'"{port}"'
|
||||
assert ("USE_LOGGER_ZEPHYR_CDC_LOOP" in defines) is zephyr_cdc_loop
|
||||
|
||||
|
||||
def test_esp8266_without_serial_dumps_no_port(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
) -> None:
|
||||
"""ESP8266 without serial logging keeps UART0 selected but never opens it."""
|
||||
generate_main("tests/component_tests/logger/test_logger_no_serial.yaml")
|
||||
|
||||
defines = {d.name: d.value for d in CORE.defines}
|
||||
assert "USE_LOGGER_UART_SELECTION_UART0" in defines
|
||||
assert str(defines["ESPHOME_LOGGER_UART_NAME"]) == '"NONE"'
|
||||
assert {
|
||||
d.name.removeprefix(prefix) for d in CORE.defines if d.name.startswith(prefix)
|
||||
} == expected
|
||||
|
||||
|
||||
def test_log_listener_slots_count_every_listener(
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
esphome:
|
||||
name: test
|
||||
|
||||
esp8266:
|
||||
board: d1_mini_lite
|
||||
|
||||
logger:
|
||||
baud_rate: 0
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
esphome:
|
||||
name: test
|
||||
|
||||
esp8266:
|
||||
board: d1_mini_lite
|
||||
|
||||
logger:
|
||||
hardware_uart: UART0_SWAP
|
||||
@@ -8,11 +8,15 @@ from esphome.components.npm1300 import (
|
||||
CHARGER_SCHEMA,
|
||||
NPM1300_UNSET,
|
||||
OUTPUT_VOLTAGE,
|
||||
THERMISTOR_NONE,
|
||||
VBUS_CURRENT_LIMIT,
|
||||
_charger_config,
|
||||
_check_thermistor,
|
||||
_config,
|
||||
_output_config,
|
||||
_termination_voltage_code,
|
||||
_vbus_current_limit_code,
|
||||
thermistor_beta,
|
||||
)
|
||||
from esphome.const import CONF_MODE, CONF_VOLTAGE
|
||||
from esphome.cpp_generator import StructInitializer
|
||||
@@ -54,10 +58,35 @@ def test_termination_voltage_gap_rejected(voltage: str) -> None:
|
||||
CHARGER_SCHEMA({"charge_current": "100mA", "termination_voltage": voltage})
|
||||
|
||||
|
||||
def test_warm_termination_defaults_to_termination() -> None:
|
||||
def test_warm_termination_defaults_to_reset_value() -> None:
|
||||
fields = _charger({"charge_current": "100mA", "termination_voltage": "4.1V"})
|
||||
assert fields["termination_voltage"] == "6"
|
||||
assert fields["warm_termination_voltage"] == "6"
|
||||
assert fields["warm_termination_voltage"] == "2"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("config", "warns"),
|
||||
[
|
||||
({"termination_voltage": "4.2V"}, True),
|
||||
({"termination_voltage": "3.5V"}, False),
|
||||
({"termination_voltage": "3.6V"}, False),
|
||||
({}, False),
|
||||
({"termination_voltage": "4.2V", "warm_termination_voltage": "4.0V"}, False),
|
||||
],
|
||||
)
|
||||
def test_warm_termination_default_warning(
|
||||
config: ConfigType, warns: bool, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
CHARGER_SCHEMA(config)
|
||||
assert ("warm_termination_voltage" in caplog.text) is warns
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("termination", "code"), [("3.5V", "0"), ("3.55V", "1")])
|
||||
def test_warm_termination_default_not_above_termination(
|
||||
termination: str, code: str
|
||||
) -> None:
|
||||
fields = _charger({"termination_voltage": termination})
|
||||
assert fields["warm_termination_voltage"] == code
|
||||
|
||||
|
||||
def test_warm_termination_code() -> None:
|
||||
@@ -112,3 +141,48 @@ def test_vbus_current_limit_code(limit: str, code: int) -> None:
|
||||
def test_vbus_current_limit_rejected(limit: str) -> None:
|
||||
with pytest.raises(cv.Invalid):
|
||||
VBUS_CURRENT_LIMIT(limit)
|
||||
|
||||
|
||||
def test_charger_needs_thermistor() -> None:
|
||||
with pytest.raises(cv.Invalid, match="thermistor_resistance"):
|
||||
_check_thermistor({"charger": {}})
|
||||
config = {"charger": {}, "thermistor_resistance": THERMISTOR_NONE}
|
||||
assert _check_thermistor(config) is config
|
||||
|
||||
|
||||
@pytest.mark.parametrize("resistance", [None, THERMISTOR_NONE])
|
||||
def test_thermistor_beta_needs_resistance(resistance: str | None) -> None:
|
||||
config = {"thermistor_beta": 3380}
|
||||
if resistance is not None:
|
||||
config["thermistor_resistance"] = resistance
|
||||
with pytest.raises(cv.Invalid, match="thermistor_beta"):
|
||||
_check_thermistor(config)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("resistance", "beta"), [(10000.0, 3380), (47000.0, 4050), (100000.0, 4250)]
|
||||
)
|
||||
def test_thermistor_beta_default(resistance: float, beta: int) -> None:
|
||||
assert thermistor_beta({"thermistor_resistance": resistance}) == beta
|
||||
|
||||
|
||||
def test_thermistor_beta_configured() -> None:
|
||||
config = {"thermistor_resistance": 47000.0, "thermistor_beta": 3950}
|
||||
assert thermistor_beta(config) == 3950
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("resistance", "code", "beta"),
|
||||
[
|
||||
(None, str(NPM1300_UNSET), "0"),
|
||||
(THERMISTOR_NONE, "0", "0"),
|
||||
(100000.0, "3", "4250"),
|
||||
],
|
||||
)
|
||||
def test_config_thermistor(
|
||||
resistance: str | float | None, code: str, beta: str
|
||||
) -> None:
|
||||
config = {} if resistance is None else {"thermistor_resistance": resistance}
|
||||
fields = _fields(_config(config))
|
||||
assert fields["thermistor"] == code
|
||||
assert fields["thermistor_beta"] == beta
|
||||
@@ -0,0 +1,11 @@
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_USE_ADDRESS
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
# Only the reply parsers are tested; the build still needs the address a modem config provides.
|
||||
manifest.dependencies = []
|
||||
manifest.config_schema = cv.Schema(
|
||||
{cv.Optional(CONF_USE_ADDRESS, default="test.local"): cv.string_strict}
|
||||
)
|
||||
@@ -0,0 +1,177 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
#include "esphome/components/modem/at_reply.h"
|
||||
|
||||
namespace esphome::modem::testing {
|
||||
|
||||
// Runs a raw reply through flatten_reply() as at_reply_() does
|
||||
static std::string flat(const char *raw) {
|
||||
char buf[256];
|
||||
const size_t len = strlen(raw);
|
||||
memcpy(buf, raw, len + 1);
|
||||
return std::string(buf, flatten_reply(buf, len));
|
||||
}
|
||||
|
||||
static ReplyEnd end_of(const char *reply, bool skip_first = false) {
|
||||
return reply_end(reply, strlen(reply), skip_first);
|
||||
}
|
||||
|
||||
TEST(ModemReplyEnd, OnlyCompleteFinalLinesCount) {
|
||||
EXPECT_EQ(end_of("\r\n+CSQ: 20,99\r\n\r\nOK\r\n"), ReplyEnd::REPLY_END_OK);
|
||||
EXPECT_EQ(end_of("\r\nERROR\r\n"), ReplyEnd::REPLY_END_ERROR);
|
||||
EXPECT_EQ(end_of("\r\n+CME ERROR: SIM not inserted\r\n"), ReplyEnd::REPLY_END_ERROR);
|
||||
EXPECT_EQ(end_of("\r\n+CMS ERROR: 500\r\n"), ReplyEnd::REPLY_END_ERROR);
|
||||
// ERROR inside a payload line is not a result
|
||||
EXPECT_EQ(end_of("\r\n+CEER: PROTOCOL_ERROR\r\n"), ReplyEnd::REPLY_END_NONE);
|
||||
EXPECT_EQ(end_of("\r\n+CEER: PROTOCOL_ERROR\r\n\r\nOK\r\n"), ReplyEnd::REPLY_END_OK);
|
||||
// A line that has not ended yet
|
||||
EXPECT_EQ(end_of("\r\nOK"), ReplyEnd::REPLY_END_NONE);
|
||||
EXPECT_EQ(end_of("\r\n+CME ERROR: 10"), ReplyEnd::REPLY_END_NONE);
|
||||
}
|
||||
|
||||
TEST(ModemReplyEnd, CutFirstLineIsSkipped) {
|
||||
// The tail of "...OK" from a longer line must not count as a result
|
||||
EXPECT_EQ(end_of("OK\r\nmore text\r\n", true), ReplyEnd::REPLY_END_NONE);
|
||||
EXPECT_EQ(end_of("OK\r\nmore text\r\n", false), ReplyEnd::REPLY_END_OK);
|
||||
EXPECT_EQ(end_of("tail\r\nOK\r\n", true), ReplyEnd::REPLY_END_OK);
|
||||
}
|
||||
|
||||
TEST(ModemCollectReply, UartReplyComesBackWhole) {
|
||||
char buf[9];
|
||||
size_t len = 0;
|
||||
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "abc", 3, true));
|
||||
EXPECT_STREQ(buf, "abc");
|
||||
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "abcdef", 6, true));
|
||||
EXPECT_STREQ(buf, "abcdef");
|
||||
// Data longer than the buffer keeps its tail
|
||||
EXPECT_TRUE(collect_reply(buf, sizeof(buf), len, "0123456789", 10, true));
|
||||
EXPECT_STREQ(buf, "23456789");
|
||||
}
|
||||
|
||||
TEST(ModemCollectReply, GatheredCmuxFramesAreNotRepeated) {
|
||||
// With esp_modem's inflatable buffer, each CMUX frame comes with the ones before it
|
||||
char buf[64];
|
||||
size_t len = 0;
|
||||
const char *first = "\r\n+CSQ: 20,99\r\n";
|
||||
const char *both = "\r\n+CSQ: 20,99\r\n\r\nOK\r\n";
|
||||
collect_reply(buf, sizeof(buf), len, first, strlen(first), true);
|
||||
collect_reply(buf, sizeof(buf), len, both, strlen(both), true);
|
||||
EXPECT_STREQ(buf, both);
|
||||
EXPECT_EQ(reply_end(buf, len, false), ReplyEnd::REPLY_END_OK);
|
||||
}
|
||||
|
||||
TEST(ModemCollectReply, ExactlyFullIsNotCut) {
|
||||
char buf[9];
|
||||
size_t len = 0;
|
||||
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "OK\r\nabcd", 8, true));
|
||||
EXPECT_STREQ(buf, "OK\r\nabcd");
|
||||
len = 0;
|
||||
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "OK\r\nabcd", 8, false));
|
||||
EXPECT_EQ(reply_end(buf, len, false), ReplyEnd::REPLY_END_OK);
|
||||
// Filling up by appending is not a cut either, one more byte is
|
||||
len = 0;
|
||||
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "OK\r\n", 4, false));
|
||||
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "abcd", 4, false));
|
||||
EXPECT_TRUE(collect_reply(buf, sizeof(buf), len, "e", 1, false));
|
||||
EXPECT_STREQ(buf, "K\r\nabcde");
|
||||
}
|
||||
|
||||
TEST(ModemCollectReply, CmuxFramesAreAppended) {
|
||||
char buf[9];
|
||||
size_t len = 0;
|
||||
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "abc", 3, false));
|
||||
// A frame that starts like the text so far is still new data
|
||||
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "abcd", 4, false));
|
||||
EXPECT_STREQ(buf, "abcabcd");
|
||||
// The oldest bytes go once the buffer is full
|
||||
EXPECT_TRUE(collect_reply(buf, sizeof(buf), len, "XY", 2, false));
|
||||
EXPECT_STREQ(buf, "bcabcdXY");
|
||||
EXPECT_EQ(len, 8u);
|
||||
EXPECT_TRUE(collect_reply(buf, sizeof(buf), len, "0123456789", 10, false));
|
||||
EXPECT_STREQ(buf, "23456789");
|
||||
}
|
||||
|
||||
TEST(ModemFlattenReply, OneLineWithoutFinalOk) {
|
||||
EXPECT_EQ(flat("\r\n+CSQ: 20,99\r\n\r\nOK\r\n"), "+CSQ: 20,99");
|
||||
EXPECT_EQ(flat("\r\nOK\r\n"), "");
|
||||
EXPECT_EQ(flat("\r\n+CME ERROR: SIM not inserted\r\n"), "+CME ERROR: SIM not inserted");
|
||||
EXPECT_EQ(flat("\r\n+COPS: 0,0,\"NOK\"\r\n"), "+COPS: 0,0,\"NOK\"");
|
||||
// A line ending in OK is not the final result
|
||||
EXPECT_EQ(flat("\r\n+CSPN: NOK\r\n"), "+CSPN: NOK");
|
||||
EXPECT_EQ(flat(""), "");
|
||||
}
|
||||
|
||||
TEST(ModemRegistration, QueryAnswerNotNotification) {
|
||||
// A one-field URC before the query answer is skipped
|
||||
EXPECT_EQ(registration_from_reply("+CEREG: 2 +CEREG: 0,1", "+CEREG:"), 1);
|
||||
EXPECT_EQ(registration_from_reply("+CEREG: 2,5,\"1A2B\",\"01A2B3C4\",7", "+CEREG:"), 5);
|
||||
EXPECT_EQ(registration_from_reply("+CREG: 0,3", "+CREG:"), 3);
|
||||
EXPECT_EQ(registration_from_reply("+CEREG: 1", "+CEREG:"), REGISTRATION_UNKNOWN);
|
||||
EXPECT_EQ(registration_from_reply("+CREG: 0,1", "+CEREG:"), REGISTRATION_UNKNOWN);
|
||||
EXPECT_EQ(registration_from_reply("", "+CEREG:"), REGISTRATION_UNKNOWN);
|
||||
}
|
||||
|
||||
TEST(ModemMergeRegistration, RegisteredOnEitherSideWins) {
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_HOME, REGISTRATION_DENIED), REGISTRATION_HOME);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_DENIED, REGISTRATION_ROAMING), REGISTRATION_ROAMING);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_NO_ANSWER, REGISTRATION_HOME), REGISTRATION_HOME);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_UNSUPPORTED, REGISTRATION_ROAMING), REGISTRATION_ROAMING);
|
||||
}
|
||||
|
||||
TEST(ModemMergeRegistration, SearchingBeatsDenied) {
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_SEARCHING, REGISTRATION_DENIED), REGISTRATION_SEARCHING);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_DENIED, REGISTRATION_SEARCHING), REGISTRATION_SEARCHING);
|
||||
}
|
||||
|
||||
TEST(ModemMergeRegistration, DefiniteAnswerBeatsTimeout) {
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_DENIED, REGISTRATION_NO_ANSWER), REGISTRATION_DENIED);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_NO_ANSWER, REGISTRATION_SEARCHING), REGISTRATION_SEARCHING);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_NO_ANSWER, REGISTRATION_NO_ANSWER), REGISTRATION_NO_ANSWER);
|
||||
// Any reported <stat> outweighs a timeout, so the fallbacks still count it
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_NOT_SEARCHING, REGISTRATION_NO_ANSWER), REGISTRATION_NOT_SEARCHING);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_NO_ANSWER, REGISTRATION_NOT_SEARCHING), REGISTRATION_NOT_SEARCHING);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_REPORTED_UNKNOWN, REGISTRATION_NO_ANSWER), REGISTRATION_REPORTED_UNKNOWN);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_NO_ANSWER, REGISTRATION_REPORTED_UNKNOWN), REGISTRATION_REPORTED_UNKNOWN);
|
||||
// Only a timeout and no <stat> at all leave the state open
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_UNSUPPORTED, REGISTRATION_NO_ANSWER), REGISTRATION_NO_ANSWER);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_NO_ANSWER, REGISTRATION_UNKNOWN), REGISTRATION_NO_ANSWER);
|
||||
}
|
||||
|
||||
TEST(ModemMergeRegistration, UnsupportedOnlyWhenBothAre) {
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_UNSUPPORTED, REGISTRATION_UNSUPPORTED), REGISTRATION_UNSUPPORTED);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_UNSUPPORTED, REGISTRATION_NOT_SEARCHING), REGISTRATION_NOT_SEARCHING);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_UNKNOWN, REGISTRATION_UNSUPPORTED), REGISTRATION_UNKNOWN);
|
||||
}
|
||||
|
||||
TEST(ModemMergeRegistration, UnknownFallback) {
|
||||
// The LTE value goes first, then the 2G and 3G one, then unknown
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_NOT_SEARCHING, REGISTRATION_REPORTED_UNKNOWN), REGISTRATION_NOT_SEARCHING);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_UNKNOWN, REGISTRATION_REPORTED_UNKNOWN), REGISTRATION_REPORTED_UNKNOWN);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_UNKNOWN, REGISTRATION_UNKNOWN), REGISTRATION_UNKNOWN);
|
||||
}
|
||||
|
||||
TEST(ModemUnsupported, OnlyWhenTheErrorSaysSo) {
|
||||
EXPECT_TRUE(reply_names_unsupported("+CME ERROR: operation not supported"));
|
||||
EXPECT_TRUE(reply_names_unsupported("+CME ERROR: Operation Not Supported"));
|
||||
EXPECT_TRUE(reply_names_unsupported("+CME ERROR: 4"));
|
||||
EXPECT_FALSE(reply_names_unsupported("+CME ERROR: 40"));
|
||||
EXPECT_FALSE(reply_names_unsupported("+CME ERROR: SIM busy"));
|
||||
EXPECT_FALSE(reply_names_unsupported("ERROR"));
|
||||
EXPECT_FALSE(reply_names_unsupported(""));
|
||||
}
|
||||
|
||||
TEST(ModemSimStatus, CutBeforeTheNextLine) {
|
||||
char ready[] = "+CPIN: READY";
|
||||
EXPECT_STREQ(sim_status(ready), "READY");
|
||||
char with_urc[] = "+CPIN: SIM PIN +CGEV: ME PDN DEACT 1";
|
||||
EXPECT_STREQ(sim_status(with_urc), "SIM PIN");
|
||||
char echoed[] = "AT+CPIN?";
|
||||
EXPECT_EQ(sim_status(echoed), nullptr);
|
||||
char empty[] = "+CPIN:";
|
||||
EXPECT_STREQ(sim_status(empty), "");
|
||||
}
|
||||
|
||||
} // namespace esphome::modem::testing
|
||||
@@ -1,29 +1,38 @@
|
||||
npm1300:
|
||||
id: pmic
|
||||
i2c_id: i2c_bus
|
||||
vbus_current_limit: 500mA
|
||||
thermistor_resistance: 10kOhm
|
||||
thermistor_beta: 3380
|
||||
charger:
|
||||
charge_current: 150mA
|
||||
termination_voltage: 4.2V
|
||||
warm_termination_voltage: 4.0V
|
||||
termination_current: 20%
|
||||
trickle_voltage: 2.5V
|
||||
discharge_current_limit: 1000mA
|
||||
recharge: true
|
||||
buck2:
|
||||
voltage: 3.3V
|
||||
ldo1:
|
||||
voltage: 3.3V
|
||||
mode: ldo
|
||||
enabled: true
|
||||
ldo2:
|
||||
mode: load_switch
|
||||
enabled: false
|
||||
- id: pmic
|
||||
i2c_id: i2c_bus
|
||||
vbus_current_limit: 500mA
|
||||
thermistor_resistance: 10kOhm
|
||||
thermistor_beta: 3380
|
||||
charger:
|
||||
charge_current: 150mA
|
||||
termination_voltage: 4.2V
|
||||
warm_termination_voltage: 4.0V
|
||||
termination_current: 20%
|
||||
trickle_voltage: 2.5V
|
||||
discharge_current_limit: 1000mA
|
||||
recharge: true
|
||||
buck2:
|
||||
voltage: 3.3V
|
||||
ldo1:
|
||||
voltage: 3.3V
|
||||
mode: ldo
|
||||
enabled: true
|
||||
ldo2:
|
||||
mode: load_switch
|
||||
enabled: false
|
||||
# A battery without a thermistor
|
||||
- id: pmic_no_ntc
|
||||
i2c_id: i2c_bus
|
||||
address: 0x6C
|
||||
thermistor_resistance: none
|
||||
charger:
|
||||
termination_voltage: 3.5V
|
||||
enabled: true
|
||||
|
||||
sensor:
|
||||
- platform: npm1300
|
||||
npm1300_id: pmic
|
||||
battery_voltage:
|
||||
name: Battery Voltage
|
||||
battery_current:
|
||||
@@ -41,6 +50,7 @@ sensor:
|
||||
|
||||
binary_sensor:
|
||||
- platform: npm1300
|
||||
npm1300_id: pmic
|
||||
vbus_present:
|
||||
name: VBUS Present
|
||||
vbus_current_limit_active:
|
||||
@@ -54,11 +64,13 @@ binary_sensor:
|
||||
|
||||
text_sensor:
|
||||
- platform: npm1300
|
||||
npm1300_id: pmic
|
||||
charger_status:
|
||||
name: Charger Status
|
||||
|
||||
switch:
|
||||
- platform: npm1300
|
||||
npm1300_id: pmic
|
||||
charger:
|
||||
name: Charger
|
||||
buck1:
|
||||
@@ -67,6 +79,10 @@ switch:
|
||||
name: LDO1
|
||||
ldo2:
|
||||
name: LDO2
|
||||
- platform: npm1300
|
||||
npm1300_id: pmic_no_ntc
|
||||
charger:
|
||||
name: Charger Without Thermistor
|
||||
|
||||
button:
|
||||
- platform: template
|
||||
|
||||
@@ -17,6 +17,7 @@ void setup() {
|
||||
App.pre_setup(name, sizeof(name) - 1, friendly_name, sizeof(friendly_name) - 1);
|
||||
auto *log = new logger::Logger(115200); // NOLINT
|
||||
log->pre_setup();
|
||||
log->set_uart_selection(logger::UART_SELECTION_UART0);
|
||||
App.register_component_(log);
|
||||
|
||||
auto *wifi = new wifi::WiFiComponent(); // NOLINT
|
||||
|
||||
Reference in new issue
Block a user