Compare commits

..
31 changed files with 861 additions and 1118 deletions

No files matched your search

@@ -63,13 +63,25 @@ void CST816Touchscreen::update_touches() {
uint8_t data[13];
if (!this->status_comm_result(this->read_bytes(REG_STATUS, data, sizeof data)))
return;
uint8_t num_of_touches = data[REG_TOUCH_NUM] & 3;
// The low nibble is the touch count. CST816/CST820 are single-touch;
// CST826/CST836 can report two points, but this driver only reads the first
// point. Some CST8xx controllers report an all-0xFF frame when idle or after
// disabling auto-sleep: the count lands above two and the coordinates are
// the 0xFFF sentinel, so both guards below reject it.
uint8_t num_of_touches = low_nibble(data[REG_TOUCH_NUM]);
if (num_of_touches == 0) {
return;
}
if (num_of_touches > 2) {
return;
}
uint16_t x = encode_uint16(low_nibble(data[REG_XPOS_HIGH]), data[REG_XPOS_LOW]);
uint16_t y = encode_uint16(low_nibble(data[REG_YPOS_HIGH]), data[REG_YPOS_LOW]);
if (x == 0x0FFF || y == 0x0FFF) {
return;
}
ESP_LOGV(TAG, "Read touch %d/%d", x, y);
this->add_raw_touch_position_(0, x, y);
}
+2
View File
@@ -94,5 +94,7 @@ FILTER_SOURCE_FILES = filter_source_files_from_platform(
PlatformFramework.LN882X_ARDUINO,
},
"debug_zephyr.cpp": {PlatformFramework.NRF52_ZEPHYR},
"debug_nrf52.cpp": {PlatformFramework.NRF52_ZEPHYR},
"debug_nrf54l.cpp": {PlatformFramework.NRF52_ZEPHYR},
}
)
+380
View File
@@ -0,0 +1,380 @@
#include "debug_component.h"
#ifdef USE_ZEPHYR
#include <nrfx.h>
#endif
#if defined(USE_ZEPHYR) && !defined(NRF54L_SERIES)
#include <cinttypes>
#include <cstdint>
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include <hal/nrf_power.h>
#define BOOTLOADER_VERSION_REGISTER NRF_TIMER2->CC[0]
namespace esphome::debug {
ESPHOME_LOG_TAG(TAG, "debug");
// Check if an nRF peripheral's ENABLE register indicates it is enabled.
// periph: peripheral register prefix (e.g. USBD, UARTE, SPI)
// reg: register block pointer (e.g. NRF_USBD, NRF_UARTE0)
#define NRF_PERIPH_ENABLED(periph, reg) \
YESNO(((reg)->ENABLE & periph##_ENABLE_ENABLE_Msk) == (periph##_ENABLE_ENABLE_Enabled << periph##_ENABLE_ENABLE_Pos))
constexpr std::uintptr_t MBR_PARAM_PAGE_ADDR = 0xFFC;
constexpr std::uintptr_t MBR_BOOTLOADER_ADDR = 0xFF8;
static inline uint32_t read_mem_u32(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint32_t *>(addr);
}
static inline uint8_t read_mem_u8(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint8_t *>(addr);
}
// defines from https://github.com/adafruit/Adafruit_nRF52_Bootloader which prints those information
constexpr uint32_t SD_MAGIC_NUMBER = 0x51B1E5DB;
constexpr uintptr_t MBR_SIZE = 0x1000;
constexpr uintptr_t SOFTDEVICE_INFO_STRUCT_OFFSET = 0x2000;
constexpr uintptr_t SD_ID_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x10;
constexpr uintptr_t SD_VERSION_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x14;
static inline bool is_sd_present() {
return read_mem_u32(SOFTDEVICE_INFO_STRUCT_OFFSET + MBR_SIZE + 4) == SD_MAGIC_NUMBER;
}
static inline uint32_t sd_id_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_ID_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_ID_OFFSET);
}
return 0;
}
static inline uint32_t sd_version_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_VERSION_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_VERSION_OFFSET);
}
return 0;
}
#ifdef ESPHOME_LOG_HAS_VERBOSE
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF peripheral registers are MMIO at fixed addresses
static void log_peripherals_info() {
// most peripherals are enabled only when in use so ESP_LOGV is enough
ESP_LOGV(TAG, "Peripherals status:");
ESP_LOGV(TAG, " USBD: %-3s| UARTE0: %-3s| UARTE1: %-3s| UART0: %-3s", //
NRF_PERIPH_ENABLED(USBD, NRF_USBD), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE0),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE1), NRF_PERIPH_ENABLED(UART, NRF_UART0));
ESP_LOGV(TAG, " TWIS0: %-3s| TWIS1: %-3s| TWIM0: %-3s| TWIM1: %-3s", //
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS0), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS1),
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM0), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM1));
ESP_LOGV(TAG, " TWI0: %-3s| TWI1: %-3s| COMP: %-3s| CCM: %-3s", //
NRF_PERIPH_ENABLED(TWI, NRF_TWI0), NRF_PERIPH_ENABLED(TWI, NRF_TWI1), NRF_PERIPH_ENABLED(COMP, NRF_COMP),
NRF_PERIPH_ENABLED(CCM, NRF_CCM));
ESP_LOGV(TAG, " PDM: %-3s| SPIS0: %-3s| SPIS1: %-3s| SPIS2: %-3s", //
NRF_PERIPH_ENABLED(PDM, NRF_PDM), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS0), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS1),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS2));
ESP_LOGV(TAG, " SPIM0: %-3s| SPIM1: %-3s| SPIM2: %-3s| SPIM3: %-3s", //
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM0), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM1),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM2), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM3));
ESP_LOGV(TAG, " SPI0: %-3s| SPI1: %-3s| SPI2: %-3s| SAADC: %-3s", //
NRF_PERIPH_ENABLED(SPI, NRF_SPI0), NRF_PERIPH_ENABLED(SPI, NRF_SPI1), NRF_PERIPH_ENABLED(SPI, NRF_SPI2),
NRF_PERIPH_ENABLED(SAADC, NRF_SAADC));
ESP_LOGV(TAG, " QSPI: %-3s| QDEC: %-3s| LPCOMP: %-3s| I2S: %-3s", //
NRF_PERIPH_ENABLED(QSPI, NRF_QSPI), NRF_PERIPH_ENABLED(QDEC, NRF_QDEC),
NRF_PERIPH_ENABLED(LPCOMP, NRF_LPCOMP), NRF_PERIPH_ENABLED(I2S, NRF_I2S));
ESP_LOGV(TAG, " PWM0: %-3s| PWM1: %-3s| PWM2: %-3s| PWM3: %-3s", //
NRF_PERIPH_ENABLED(PWM, NRF_PWM0), NRF_PERIPH_ENABLED(PWM, NRF_PWM1), NRF_PERIPH_ENABLED(PWM, NRF_PWM2),
NRF_PERIPH_ENABLED(PWM, NRF_PWM3));
ESP_LOGV(TAG, " AAR: %-3s| QSPI deep power-down:%-3s| CRYPTOCELL: %-3s", NRF_PERIPH_ENABLED(AAR, NRF_AAR),
YESNO((NRF_QSPI->IFCONFIG0 & QSPI_IFCONFIG0_DPMENABLE_Msk) ==
(QSPI_IFCONFIG0_DPMENABLE_Enable << QSPI_IFCONFIG0_DPMENABLE_Pos)),
YESNO((NRF_CRYPTOCELL->ENABLE & CRYPTOCELL_ENABLE_ENABLE_Msk) ==
(CRYPTOCELL_ENABLE_ENABLE_Enabled << CRYPTOCELL_ENABLE_ENABLE_Pos)));
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#endif
static const char *regout0_to_str(uint32_t value) {
switch (value) {
case (UICR_REGOUT0_VOUT_DEFAULT):
return "1.8V (default)";
case (UICR_REGOUT0_VOUT_1V8):
return "1.8V";
case (UICR_REGOUT0_VOUT_2V1):
return "2.1V";
case (UICR_REGOUT0_VOUT_2V4):
return "2.4V";
case (UICR_REGOUT0_VOUT_2V7):
return "2.7V";
case (UICR_REGOUT0_VOUT_3V0):
return "3.0V";
case (UICR_REGOUT0_VOUT_3V3):
return "3.3V";
default:
break;
}
return "???V";
}
size_t DebugComponent::get_device_info_(std::span<char, DEVICE_INFO_BUFFER_SIZE> buffer, size_t pos) {
constexpr size_t size = DEVICE_INFO_BUFFER_SIZE;
char *buf = buffer.data();
// Main supply status
// NOLINTNEXTLINE(clang-analyzer-core.FixedAddressDereference) -- NRF_POWER is MMIO at a fixed address
auto regstatus = nrf_power_mainregstatus_get(NRF_POWER);
const char *supply_status = (regstatus == NRF_POWER_MAINREGSTATUS_NORMAL) ? "Normal voltage." : "High voltage.";
ESP_LOGD(TAG, "Main supply status: %s", supply_status);
pos = buf_append_str(buf, size, pos, "|Main supply status: ");
pos = buf_append_str(buf, size, pos, supply_status);
// Regulator stage 0
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *reg0_type = nrf_power_dcdcen_vddh_get(NRF_POWER) ? "DC/DC" : "LDO";
const char *reg0_voltage = regout0_to_str((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos);
ESP_LOGD(TAG, "Regulator stage 0: %s, %s", reg0_type, reg0_voltage);
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: ");
pos = buf_append_str(buf, size, pos, reg0_type);
pos = buf_append_str(buf, size, pos, ", ");
pos = buf_append_str(buf, size, pos, reg0_voltage);
#ifdef USE_NRF52_REG0_VOUT
if ((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos != USE_NRF52_REG0_VOUT) {
ESP_LOGE(TAG, "Regulator stage 0: expected %s", regout0_to_str(USE_NRF52_REG0_VOUT));
}
#endif
} else {
ESP_LOGD(TAG, "Regulator stage 0: disabled");
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: disabled");
}
// Regulator stage 1
const char *reg1_type = nrf_power_dcdcen_get(NRF_POWER) ? "DC/DC" : "LDO";
ESP_LOGD(TAG, "Regulator stage 1: %s", reg1_type);
pos = buf_append_str(buf, size, pos, "|Regulator stage 1: ");
pos = buf_append_str(buf, size, pos, reg1_type);
// USB power state
const char *usb_state;
if (nrf_power_usbregstatus_vbusdet_get(NRF_POWER)) {
usb_state = nrf_power_usbregstatus_outrdy_get(NRF_POWER) ? "ready" : "connected (regulator is not ready)";
} else {
usb_state = "disconnected";
}
ESP_LOGD(TAG, "USB power state: %s", usb_state);
pos = buf_append_str(buf, size, pos, "|USB power state: ");
pos = buf_append_str(buf, size, pos, usb_state);
// Power-fail comparator
bool enabled;
nrf_power_pof_thr_t pof_thr = nrf_power_pofcon_get(NRF_POWER, &enabled);
if (enabled) {
const char *pof_voltage;
switch (pof_thr) {
case POWER_POFCON_THRESHOLD_V17:
pof_voltage = "1.7V";
break;
case POWER_POFCON_THRESHOLD_V18:
pof_voltage = "1.8V";
break;
case POWER_POFCON_THRESHOLD_V19:
pof_voltage = "1.9V";
break;
case POWER_POFCON_THRESHOLD_V20:
pof_voltage = "2.0V";
break;
case POWER_POFCON_THRESHOLD_V21:
pof_voltage = "2.1V";
break;
case POWER_POFCON_THRESHOLD_V22:
pof_voltage = "2.2V";
break;
case POWER_POFCON_THRESHOLD_V23:
pof_voltage = "2.3V";
break;
case POWER_POFCON_THRESHOLD_V24:
pof_voltage = "2.4V";
break;
case POWER_POFCON_THRESHOLD_V25:
pof_voltage = "2.5V";
break;
case POWER_POFCON_THRESHOLD_V26:
pof_voltage = "2.6V";
break;
case POWER_POFCON_THRESHOLD_V27:
pof_voltage = "2.7V";
break;
case POWER_POFCON_THRESHOLD_V28:
pof_voltage = "2.8V";
break;
default:
pof_voltage = "???V";
break;
}
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *vddh_voltage;
switch (nrf_power_pofcon_vddh_get(NRF_POWER)) {
case NRF_POWER_POFTHRVDDH_V27:
vddh_voltage = "2.7V";
break;
case NRF_POWER_POFTHRVDDH_V28:
vddh_voltage = "2.8V";
break;
case NRF_POWER_POFTHRVDDH_V29:
vddh_voltage = "2.9V";
break;
case NRF_POWER_POFTHRVDDH_V30:
vddh_voltage = "3.0V";
break;
case NRF_POWER_POFTHRVDDH_V31:
vddh_voltage = "3.1V";
break;
case NRF_POWER_POFTHRVDDH_V32:
vddh_voltage = "3.2V";
break;
case NRF_POWER_POFTHRVDDH_V33:
vddh_voltage = "3.3V";
break;
case NRF_POWER_POFTHRVDDH_V34:
vddh_voltage = "3.4V";
break;
case NRF_POWER_POFTHRVDDH_V35:
vddh_voltage = "3.5V";
break;
case NRF_POWER_POFTHRVDDH_V36:
vddh_voltage = "3.6V";
break;
case NRF_POWER_POFTHRVDDH_V37:
vddh_voltage = "3.7V";
break;
case NRF_POWER_POFTHRVDDH_V38:
vddh_voltage = "3.8V";
break;
case NRF_POWER_POFTHRVDDH_V39:
vddh_voltage = "3.9V";
break;
case NRF_POWER_POFTHRVDDH_V40:
vddh_voltage = "4.0V";
break;
case NRF_POWER_POFTHRVDDH_V41:
vddh_voltage = "4.1V";
break;
case NRF_POWER_POFTHRVDDH_V42:
vddh_voltage = "4.2V";
break;
default:
vddh_voltage = "???V";
break;
}
ESP_LOGD(TAG, "Power-fail comparator: %s, VDDH: %s", pof_voltage, vddh_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
pos = buf_append_str(buf, size, pos, ", VDDH: ");
pos = buf_append_str(buf, size, pos, vddh_voltage);
} else {
ESP_LOGD(TAG, "Power-fail comparator: %s", pof_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
}
} else {
ESP_LOGD(TAG, "Power-fail comparator: disabled");
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: disabled");
}
auto package = [](uint32_t value) {
switch (value) {
case 0x2004:
return "QIxx - 7x7 73-pin aQFN";
case 0x2000:
return "QFxx - 6x6 48-pin QFN";
case 0x2005:
return "CKxx - 3.544 x 3.607 WLCSP";
default:
break;
}
return "Unspecified";
};
char mac_pretty[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
get_mac_address_pretty_into_buffer(mac_pretty);
ESP_LOGD(TAG,
"nRF debug info:\n"
" Code page size: %u, code size: %u, device id: 0x%08x%08x\n"
" Encryption root: 0x%08x%08x%08x%08x, Identity Root: 0x%08x%08x%08x%08x\n"
" Device address type: %s, address: %s\n"
" Part code: nRF%x, version: %c%c%c%c, package: %s\n"
" RAM: %ukB, Flash: %ukB, production test: %sdone",
NRF_FICR->CODEPAGESIZE, NRF_FICR->CODESIZE, NRF_FICR->DEVICEID[1], NRF_FICR->DEVICEID[0], NRF_FICR->ER[0],
NRF_FICR->ER[1], NRF_FICR->ER[2], NRF_FICR->ER[3], NRF_FICR->IR[0], NRF_FICR->IR[1], NRF_FICR->IR[2],
NRF_FICR->IR[3], (NRF_FICR->DEVICEADDRTYPE & 0x1 ? LOG_STR_LITERAL("Random") : LOG_STR_LITERAL("Public")),
mac_pretty, NRF_FICR->INFO.PART, NRF_FICR->INFO.VARIANT >> 24 & 0xFF, NRF_FICR->INFO.VARIANT >> 16 & 0xFF,
NRF_FICR->INFO.VARIANT >> 8 & 0xFF, NRF_FICR->INFO.VARIANT & 0xFF, package(NRF_FICR->INFO.PACKAGE),
NRF_FICR->INFO.RAM, NRF_FICR->INFO.FLASH,
(NRF_FICR->PRODTEST[0] == 0xBB42319F ? LOG_STR_LITERAL("") : LOG_STR_LITERAL("not ")));
bool n_reset_enabled = NRF_UICR->PSELRESET[0] == NRF_UICR->PSELRESET[1] &&
(NRF_UICR->PSELRESET[0] & UICR_PSELRESET_CONNECT_Msk) == UICR_PSELRESET_CONNECT_Connected
<< UICR_PSELRESET_CONNECT_Pos;
ESP_LOGD(
TAG, " GPIO as NFC pins: %s, GPIO as nRESET pin: %s",
YESNO((NRF_UICR->NFCPINS & UICR_NFCPINS_PROTECT_Msk) == (UICR_NFCPINS_PROTECT_NFC << UICR_NFCPINS_PROTECT_Pos)),
YESNO(n_reset_enabled));
if (n_reset_enabled) {
uint8_t port = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PORT_Msk) >> UICR_PSELRESET_PORT_Pos;
uint8_t pin = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PIN_Msk) >> UICR_PSELRESET_PIN_Pos;
ESP_LOGD(TAG, " nRESET port P%u.%02u", port, pin);
}
#ifdef USE_BOOTLOADER_MCUBOOT
ESP_LOGD(TAG, " Bootloader: mcuboot");
#else
ESP_LOGD(TAG, " Bootloader: Adafruit, version %u.%u.%u", (BOOTLOADER_VERSION_REGISTER >> 16) & 0xFF,
(BOOTLOADER_VERSION_REGISTER >> 8) & 0xFF, BOOTLOADER_VERSION_REGISTER & 0xFF);
ESP_LOGD(TAG, " MBR bootloader addr 0x%08x, UICR bootloader addr 0x%08x", read_mem_u32(MBR_BOOTLOADER_ADDR),
NRF_UICR->NRFFW[0]);
ESP_LOGD(TAG, " MBR param page addr 0x%08x, UICR param page addr 0x%08x", read_mem_u32(MBR_PARAM_PAGE_ADDR),
NRF_UICR->NRFFW[1]);
if (is_sd_present()) {
uint32_t const sd_id = sd_id_get();
uint32_t const sd_version = sd_version_get();
uint32_t ver[3];
ver[0] = sd_version / 1000000;
ver[1] = (sd_version - ver[0] * 1000000) / 1000;
ver[2] = (sd_version - ver[0] * 1000000 - ver[1] * 1000);
ESP_LOGD(TAG, " SoftDevice: S%u %u.%u.%u", sd_id, ver[0], ver[1], ver[2]);
#ifdef USE_SOFTDEVICE_ID
#ifdef USE_SOFTDEVICE_VERSION
if (USE_SOFTDEVICE_ID != sd_id || USE_SOFTDEVICE_VERSION != ver[0]) {
ESP_LOGE(TAG, "Built for SoftDevice S%u %u.x.y. It may crash due to mismatch of bootloader version.",
USE_SOFTDEVICE_ID, USE_SOFTDEVICE_VERSION);
}
#else
if (USE_SOFTDEVICE_ID != sd_id) {
ESP_LOGE(TAG, "Built for SoftDevice S%u. It may crash due to mismatch of bootloader version.", USE_SOFTDEVICE_ID);
}
#endif
#endif
}
#endif
// 13 words of 8 hex digits, separated by spaces
char uicr_buf[13 * 9];
auto uicr = [&uicr_buf](volatile uint32_t *data, uint8_t size) {
size_t len = 0;
for (size_t i = 0; i < size; i++) {
len = buf_append_printf(uicr_buf, sizeof(uicr_buf), len, i > 0 ? " %08" PRIX32 : "%08" PRIX32, data[i]);
}
return uicr_buf;
};
ESP_LOGD(TAG, " NRFFW %s", uicr(NRF_UICR->NRFFW, 13));
ESP_LOGD(TAG, " NRFHW %s", uicr(NRF_UICR->NRFHW, 12));
#ifdef ESPHOME_LOG_HAS_VERBOSE
log_peripherals_info();
#endif
return pos;
}
#undef NRF_PERIPH_ENABLED
} // namespace esphome::debug
#endif
+113
View File
@@ -0,0 +1,113 @@
#include "debug_component.h"
#ifdef USE_ZEPHYR
#include <nrfx.h>
#endif
#if defined(USE_ZEPHYR) && defined(NRF54L_SERIES)
#include <cinttypes>
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
namespace esphome::debug {
ESPHOME_LOG_TAG(TAG, "debug");
// Check if an nRF peripheral's ENABLE register indicates it is enabled.
// periph: peripheral register prefix (e.g. USBD, UARTE, SPI)
// reg: register block pointer (e.g. NRF_USBD, NRF_UARTE0)
#define NRF_PERIPH_ENABLED(periph, reg) \
YESNO(((reg)->ENABLE & periph##_ENABLE_ENABLE_Msk) == (periph##_ENABLE_ENABLE_Enabled << periph##_ENABLE_ENABLE_Pos))
#ifdef ESPHOME_LOG_HAS_VERBOSE
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF peripheral registers are MMIO at fixed addresses
static void log_peripherals_info() {
// most peripherals are enabled only when in use so ESP_LOGV is enough
// UARTE, SPIM, SPIS, TWIM and TWIS with the same number share one instance
ESP_LOGV(TAG, "Peripherals status:");
ESP_LOGV(TAG, " UARTE00: %-3s| UARTE20: %-3s| UARTE21: %-3s| UARTE22: %-3s| UARTE30: %-3s", //
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE00), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE20),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE21), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE22),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE30));
ESP_LOGV(TAG, " SPIM00: %-3s| SPIM20: %-3s| SPIM21: %-3s| SPIM22: %-3s| SPIM30: %-3s", //
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM00), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM20),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM21), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM22),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM30));
ESP_LOGV(TAG, " SPIS00: %-3s| SPIS20: %-3s| SPIS21: %-3s| SPIS22: %-3s| SPIS30: %-3s", //
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS00), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS20),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS21), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS22),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS30));
ESP_LOGV(TAG, " TWIM20: %-3s| TWIM21: %-3s| TWIM22: %-3s| TWIM30: %-3s", //
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM20), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM21),
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM22), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM30));
ESP_LOGV(TAG, " TWIS20: %-3s| TWIS21: %-3s| TWIS22: %-3s| TWIS30: %-3s", //
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS20), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS21),
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS22), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS30));
ESP_LOGV(TAG, " PWM20: %-3s| PWM21: %-3s| PWM22: %-3s| SAADC: %-3s", //
NRF_PERIPH_ENABLED(PWM, NRF_PWM20), NRF_PERIPH_ENABLED(PWM, NRF_PWM21), NRF_PERIPH_ENABLED(PWM, NRF_PWM22),
NRF_PERIPH_ENABLED(SAADC, NRF_SAADC));
ESP_LOGV(TAG, " PDM20: %-3s| PDM21: %-3s| QDEC20: %-3s| QDEC21: %-3s", //
NRF_PERIPH_ENABLED(PDM, NRF_PDM20), NRF_PERIPH_ENABLED(PDM, NRF_PDM21), NRF_PERIPH_ENABLED(QDEC, NRF_QDEC20),
NRF_PERIPH_ENABLED(QDEC, NRF_QDEC21));
ESP_LOGV(TAG, " COMP: %-3s| LPCOMP: %-3s| AAR00: %-3s| CCM00: %-3s", //
NRF_PERIPH_ENABLED(COMP, NRF_COMP), NRF_PERIPH_ENABLED(LPCOMP, NRF_LPCOMP),
NRF_PERIPH_ENABLED(AAR, NRF_AAR00), NRF_PERIPH_ENABLED(CCM, NRF_CCM00));
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#endif
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF registers are MMIO at fixed addresses
size_t DebugComponent::get_device_info_(std::span<char, DEVICE_INFO_BUFFER_SIZE> buffer, size_t pos) {
constexpr size_t size = DEVICE_INFO_BUFFER_SIZE;
char *buf = buffer.data();
// Main regulator
const char *reg_type = (NRF_REGULATORS->VREGMAIN.DCDCEN & REGULATORS_VREGMAIN_DCDCEN_VAL_Msk) ==
(REGULATORS_VREGMAIN_DCDCEN_VAL_Enabled << REGULATORS_VREGMAIN_DCDCEN_VAL_Pos)
? "DC/DC"
: "LDO";
ESP_LOGD(TAG, "Main regulator: %s", reg_type);
pos = buf_append_str(buf, size, pos, "|Main regulator: ");
pos = buf_append_str(buf, size, pos, reg_type);
// Power-fail comparator, the threshold goes from 1.7V up in 0.1V steps
const uint32_t pofcon = NRF_REGULATORS->POFCON;
if ((pofcon & REGULATORS_POFCON_POF_Msk) == (REGULATORS_POFCON_POF_Enabled << REGULATORS_POFCON_POF_Pos)) {
const uint32_t decivolts = 17 + ((pofcon & REGULATORS_POFCON_THRESHOLD_Msk) >> REGULATORS_POFCON_THRESHOLD_Pos);
ESP_LOGD(TAG, "Power-fail comparator: %" PRIu32 ".%" PRIu32 "V", decivolts / 10, decivolts % 10);
pos = buf_append_printf(buf, size, pos, "|Power-fail comparator: %" PRIu32 ".%" PRIu32 "V", decivolts / 10,
decivolts % 10);
} else {
ESP_LOGD(TAG, "Power-fail comparator: disabled");
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: disabled");
}
char mac_pretty[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
get_mac_address_pretty_into_buffer(mac_pretty);
const uint32_t variant = NRF_FICR->INFO.VARIANT;
ESP_LOGD(TAG,
"nRF debug info:\n"
" Device id: 0x%08" PRIx32 "%08" PRIx32 "\n"
" Encryption root: 0x%08" PRIx32 "%08" PRIx32 "%08" PRIx32 "%08" PRIx32 ", Identity Root: 0x%08" PRIx32
"%08" PRIx32 "%08" PRIx32 "%08" PRIx32 "\n"
" Device address type: %s, address: %s\n"
" Part code: 0x%" PRIx32 ", version: %c%c%c%c, package: 0x%" PRIx32 "\n"
" RAM: %" PRIu32 "kB, RRAM: %" PRIu32 "kB",
NRF_FICR->INFO.DEVICEID[1], NRF_FICR->INFO.DEVICEID[0], NRF_FICR->ER[0], NRF_FICR->ER[1], NRF_FICR->ER[2],
NRF_FICR->ER[3], NRF_FICR->IR[0], NRF_FICR->IR[1], NRF_FICR->IR[2], NRF_FICR->IR[3],
(NRF_FICR->DEVICEADDRTYPE & 0x1 ? LOG_STR_LITERAL("Random") : LOG_STR_LITERAL("Public")), mac_pretty,
NRF_FICR->INFO.PART, static_cast<char>(variant >> 24 & 0xFF), static_cast<char>(variant >> 16 & 0xFF),
static_cast<char>(variant >> 8 & 0xFF), static_cast<char>(variant & 0xFF), NRF_FICR->INFO.PACKAGE,
NRF_FICR->INFO.RAM, NRF_FICR->INFO.RRAM);
#ifdef USE_BOOTLOADER_MCUBOOT
ESP_LOGD(TAG, " Bootloader: mcuboot");
#endif
#ifdef ESPHOME_LOG_HAS_VERBOSE
log_peripherals_info();
#endif
return pos;
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#undef NRF_PERIPH_ENABLED
} // namespace esphome::debug
#endif
-364
View File
@@ -2,55 +2,14 @@
#ifdef USE_ZEPHYR
#include <cinttypes>
#include <climits>
#include "esphome/core/alloc_helpers.h"
#include "esphome/core/log.h"
#include <esphome/components/zephyr/reset_reason.h>
#include <zephyr/drivers/hwinfo.h>
#include <zephyr/kernel.h>
#include <hal/nrf_power.h>
#include <cstdint>
#include <zephyr/storage/flash_map.h>
#define BOOTLOADER_VERSION_REGISTER NRF_TIMER2->CC[0]
namespace esphome::debug {
ESPHOME_LOG_TAG(TAG, "debug");
constexpr std::uintptr_t MBR_PARAM_PAGE_ADDR = 0xFFC;
constexpr std::uintptr_t MBR_BOOTLOADER_ADDR = 0xFF8;
static inline uint32_t read_mem_u32(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint32_t *>(addr);
}
static inline uint8_t read_mem_u8(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint8_t *>(addr);
}
// defines from https://github.com/adafruit/Adafruit_nRF52_Bootloader which prints those information
constexpr uint32_t SD_MAGIC_NUMBER = 0x51B1E5DB;
constexpr uintptr_t MBR_SIZE = 0x1000;
constexpr uintptr_t SOFTDEVICE_INFO_STRUCT_OFFSET = 0x2000;
constexpr uintptr_t SD_ID_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x10;
constexpr uintptr_t SD_VERSION_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x14;
static inline bool is_sd_present() {
return read_mem_u32(SOFTDEVICE_INFO_STRUCT_OFFSET + MBR_SIZE + 4) == SD_MAGIC_NUMBER;
}
static inline uint32_t sd_id_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_ID_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_ID_OFFSET);
}
return 0;
}
static inline uint32_t sd_version_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_VERSION_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_VERSION_OFFSET);
}
return 0;
}
const char *DebugComponent::get_reset_reason_(std::span<char, RESET_REASON_BUFFER_SIZE> buffer) {
const char *buf = zephyr::get_reset_reason(buffer);
@@ -96,329 +55,6 @@ void DebugComponent::log_partition_info_() {
flash_area_foreach(fa_cb, nullptr);
}
#ifdef ESPHOME_LOG_HAS_VERBOSE
// Check if an nRF peripheral's ENABLE register indicates it is enabled.
// periph: peripheral register prefix (e.g. USBD, UARTE, SPI)
// reg: register block pointer (e.g. NRF_USBD, NRF_UARTE0)
#define NRF_PERIPH_ENABLED(periph, reg) \
YESNO(((reg)->ENABLE & periph##_ENABLE_ENABLE_Msk) == (periph##_ENABLE_ENABLE_Enabled << periph##_ENABLE_ENABLE_Pos))
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF peripheral registers are MMIO at fixed addresses
static void log_peripherals_info() {
// most peripherals are enabled only when in use so ESP_LOGV is enough
ESP_LOGV(TAG, "Peripherals status:");
ESP_LOGV(TAG, " USBD: %-3s| UARTE0: %-3s| UARTE1: %-3s| UART0: %-3s", //
NRF_PERIPH_ENABLED(USBD, NRF_USBD), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE0),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE1), NRF_PERIPH_ENABLED(UART, NRF_UART0));
ESP_LOGV(TAG, " TWIS0: %-3s| TWIS1: %-3s| TWIM0: %-3s| TWIM1: %-3s", //
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS0), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS1),
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM0), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM1));
ESP_LOGV(TAG, " TWI0: %-3s| TWI1: %-3s| COMP: %-3s| CCM: %-3s", //
NRF_PERIPH_ENABLED(TWI, NRF_TWI0), NRF_PERIPH_ENABLED(TWI, NRF_TWI1), NRF_PERIPH_ENABLED(COMP, NRF_COMP),
NRF_PERIPH_ENABLED(CCM, NRF_CCM));
ESP_LOGV(TAG, " PDM: %-3s| SPIS0: %-3s| SPIS1: %-3s| SPIS2: %-3s", //
NRF_PERIPH_ENABLED(PDM, NRF_PDM), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS0), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS1),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS2));
ESP_LOGV(TAG, " SPIM0: %-3s| SPIM1: %-3s| SPIM2: %-3s| SPIM3: %-3s", //
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM0), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM1),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM2), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM3));
ESP_LOGV(TAG, " SPI0: %-3s| SPI1: %-3s| SPI2: %-3s| SAADC: %-3s", //
NRF_PERIPH_ENABLED(SPI, NRF_SPI0), NRF_PERIPH_ENABLED(SPI, NRF_SPI1), NRF_PERIPH_ENABLED(SPI, NRF_SPI2),
NRF_PERIPH_ENABLED(SAADC, NRF_SAADC));
ESP_LOGV(TAG, " QSPI: %-3s| QDEC: %-3s| LPCOMP: %-3s| I2S: %-3s", //
NRF_PERIPH_ENABLED(QSPI, NRF_QSPI), NRF_PERIPH_ENABLED(QDEC, NRF_QDEC),
NRF_PERIPH_ENABLED(LPCOMP, NRF_LPCOMP), NRF_PERIPH_ENABLED(I2S, NRF_I2S));
ESP_LOGV(TAG, " PWM0: %-3s| PWM1: %-3s| PWM2: %-3s| PWM3: %-3s", //
NRF_PERIPH_ENABLED(PWM, NRF_PWM0), NRF_PERIPH_ENABLED(PWM, NRF_PWM1), NRF_PERIPH_ENABLED(PWM, NRF_PWM2),
NRF_PERIPH_ENABLED(PWM, NRF_PWM3));
ESP_LOGV(TAG, " AAR: %-3s| QSPI deep power-down:%-3s| CRYPTOCELL: %-3s", NRF_PERIPH_ENABLED(AAR, NRF_AAR),
YESNO((NRF_QSPI->IFCONFIG0 & QSPI_IFCONFIG0_DPMENABLE_Msk) ==
(QSPI_IFCONFIG0_DPMENABLE_Enable << QSPI_IFCONFIG0_DPMENABLE_Pos)),
YESNO((NRF_CRYPTOCELL->ENABLE & CRYPTOCELL_ENABLE_ENABLE_Msk) ==
(CRYPTOCELL_ENABLE_ENABLE_Enabled << CRYPTOCELL_ENABLE_ENABLE_Pos)));
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#undef NRF_PERIPH_ENABLED
#endif
static const char *regout0_to_str(uint32_t value) {
switch (value) {
case (UICR_REGOUT0_VOUT_DEFAULT):
return "1.8V (default)";
case (UICR_REGOUT0_VOUT_1V8):
return "1.8V";
case (UICR_REGOUT0_VOUT_2V1):
return "2.1V";
case (UICR_REGOUT0_VOUT_2V4):
return "2.4V";
case (UICR_REGOUT0_VOUT_2V7):
return "2.7V";
case (UICR_REGOUT0_VOUT_3V0):
return "3.0V";
case (UICR_REGOUT0_VOUT_3V3):
return "3.3V";
default:
break;
}
return "???V";
}
size_t DebugComponent::get_device_info_(std::span<char, DEVICE_INFO_BUFFER_SIZE> buffer, size_t pos) {
constexpr size_t size = DEVICE_INFO_BUFFER_SIZE;
char *buf = buffer.data();
// Main supply status
// NOLINTNEXTLINE(clang-analyzer-core.FixedAddressDereference) -- NRF_POWER is MMIO at a fixed address
auto regstatus = nrf_power_mainregstatus_get(NRF_POWER);
const char *supply_status = (regstatus == NRF_POWER_MAINREGSTATUS_NORMAL) ? "Normal voltage." : "High voltage.";
ESP_LOGD(TAG, "Main supply status: %s", supply_status);
pos = buf_append_str(buf, size, pos, "|Main supply status: ");
pos = buf_append_str(buf, size, pos, supply_status);
// Regulator stage 0
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *reg0_type = nrf_power_dcdcen_vddh_get(NRF_POWER) ? "DC/DC" : "LDO";
const char *reg0_voltage = regout0_to_str((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos);
ESP_LOGD(TAG, "Regulator stage 0: %s, %s", reg0_type, reg0_voltage);
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: ");
pos = buf_append_str(buf, size, pos, reg0_type);
pos = buf_append_str(buf, size, pos, ", ");
pos = buf_append_str(buf, size, pos, reg0_voltage);
#ifdef USE_NRF52_REG0_VOUT
if ((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos != USE_NRF52_REG0_VOUT) {
ESP_LOGE(TAG, "Regulator stage 0: expected %s", regout0_to_str(USE_NRF52_REG0_VOUT));
}
#endif
} else {
ESP_LOGD(TAG, "Regulator stage 0: disabled");
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: disabled");
}
// Regulator stage 1
const char *reg1_type = nrf_power_dcdcen_get(NRF_POWER) ? "DC/DC" : "LDO";
ESP_LOGD(TAG, "Regulator stage 1: %s", reg1_type);
pos = buf_append_str(buf, size, pos, "|Regulator stage 1: ");
pos = buf_append_str(buf, size, pos, reg1_type);
// USB power state
const char *usb_state;
if (nrf_power_usbregstatus_vbusdet_get(NRF_POWER)) {
usb_state = nrf_power_usbregstatus_outrdy_get(NRF_POWER) ? "ready" : "connected (regulator is not ready)";
} else {
usb_state = "disconnected";
}
ESP_LOGD(TAG, "USB power state: %s", usb_state);
pos = buf_append_str(buf, size, pos, "|USB power state: ");
pos = buf_append_str(buf, size, pos, usb_state);
// Power-fail comparator
bool enabled;
nrf_power_pof_thr_t pof_thr = nrf_power_pofcon_get(NRF_POWER, &enabled);
if (enabled) {
const char *pof_voltage;
switch (pof_thr) {
case POWER_POFCON_THRESHOLD_V17:
pof_voltage = "1.7V";
break;
case POWER_POFCON_THRESHOLD_V18:
pof_voltage = "1.8V";
break;
case POWER_POFCON_THRESHOLD_V19:
pof_voltage = "1.9V";
break;
case POWER_POFCON_THRESHOLD_V20:
pof_voltage = "2.0V";
break;
case POWER_POFCON_THRESHOLD_V21:
pof_voltage = "2.1V";
break;
case POWER_POFCON_THRESHOLD_V22:
pof_voltage = "2.2V";
break;
case POWER_POFCON_THRESHOLD_V23:
pof_voltage = "2.3V";
break;
case POWER_POFCON_THRESHOLD_V24:
pof_voltage = "2.4V";
break;
case POWER_POFCON_THRESHOLD_V25:
pof_voltage = "2.5V";
break;
case POWER_POFCON_THRESHOLD_V26:
pof_voltage = "2.6V";
break;
case POWER_POFCON_THRESHOLD_V27:
pof_voltage = "2.7V";
break;
case POWER_POFCON_THRESHOLD_V28:
pof_voltage = "2.8V";
break;
default:
pof_voltage = "???V";
break;
}
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *vddh_voltage;
switch (nrf_power_pofcon_vddh_get(NRF_POWER)) {
case NRF_POWER_POFTHRVDDH_V27:
vddh_voltage = "2.7V";
break;
case NRF_POWER_POFTHRVDDH_V28:
vddh_voltage = "2.8V";
break;
case NRF_POWER_POFTHRVDDH_V29:
vddh_voltage = "2.9V";
break;
case NRF_POWER_POFTHRVDDH_V30:
vddh_voltage = "3.0V";
break;
case NRF_POWER_POFTHRVDDH_V31:
vddh_voltage = "3.1V";
break;
case NRF_POWER_POFTHRVDDH_V32:
vddh_voltage = "3.2V";
break;
case NRF_POWER_POFTHRVDDH_V33:
vddh_voltage = "3.3V";
break;
case NRF_POWER_POFTHRVDDH_V34:
vddh_voltage = "3.4V";
break;
case NRF_POWER_POFTHRVDDH_V35:
vddh_voltage = "3.5V";
break;
case NRF_POWER_POFTHRVDDH_V36:
vddh_voltage = "3.6V";
break;
case NRF_POWER_POFTHRVDDH_V37:
vddh_voltage = "3.7V";
break;
case NRF_POWER_POFTHRVDDH_V38:
vddh_voltage = "3.8V";
break;
case NRF_POWER_POFTHRVDDH_V39:
vddh_voltage = "3.9V";
break;
case NRF_POWER_POFTHRVDDH_V40:
vddh_voltage = "4.0V";
break;
case NRF_POWER_POFTHRVDDH_V41:
vddh_voltage = "4.1V";
break;
case NRF_POWER_POFTHRVDDH_V42:
vddh_voltage = "4.2V";
break;
default:
vddh_voltage = "???V";
break;
}
ESP_LOGD(TAG, "Power-fail comparator: %s, VDDH: %s", pof_voltage, vddh_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
pos = buf_append_str(buf, size, pos, ", VDDH: ");
pos = buf_append_str(buf, size, pos, vddh_voltage);
} else {
ESP_LOGD(TAG, "Power-fail comparator: %s", pof_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
}
} else {
ESP_LOGD(TAG, "Power-fail comparator: disabled");
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: disabled");
}
auto package = [](uint32_t value) {
switch (value) {
case 0x2004:
return "QIxx - 7x7 73-pin aQFN";
case 0x2000:
return "QFxx - 6x6 48-pin QFN";
case 0x2005:
return "CKxx - 3.544 x 3.607 WLCSP";
default:
break;
}
return "Unspecified";
};
char mac_pretty[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
get_mac_address_pretty_into_buffer(mac_pretty);
ESP_LOGD(TAG,
"nRF debug info:\n"
" Code page size: %u, code size: %u, device id: 0x%08x%08x\n"
" Encryption root: 0x%08x%08x%08x%08x, Identity Root: 0x%08x%08x%08x%08x\n"
" Device address type: %s, address: %s\n"
" Part code: nRF%x, version: %c%c%c%c, package: %s\n"
" RAM: %ukB, Flash: %ukB, production test: %sdone",
NRF_FICR->CODEPAGESIZE, NRF_FICR->CODESIZE, NRF_FICR->DEVICEID[1], NRF_FICR->DEVICEID[0], NRF_FICR->ER[0],
NRF_FICR->ER[1], NRF_FICR->ER[2], NRF_FICR->ER[3], NRF_FICR->IR[0], NRF_FICR->IR[1], NRF_FICR->IR[2],
NRF_FICR->IR[3], (NRF_FICR->DEVICEADDRTYPE & 0x1 ? "Random" : "Public"), mac_pretty, NRF_FICR->INFO.PART,
NRF_FICR->INFO.VARIANT >> 24 & 0xFF, NRF_FICR->INFO.VARIANT >> 16 & 0xFF, NRF_FICR->INFO.VARIANT >> 8 & 0xFF,
NRF_FICR->INFO.VARIANT & 0xFF, package(NRF_FICR->INFO.PACKAGE), NRF_FICR->INFO.RAM, NRF_FICR->INFO.FLASH,
(NRF_FICR->PRODTEST[0] == 0xBB42319F ? "" : "not "));
bool n_reset_enabled = NRF_UICR->PSELRESET[0] == NRF_UICR->PSELRESET[1] &&
(NRF_UICR->PSELRESET[0] & UICR_PSELRESET_CONNECT_Msk) == UICR_PSELRESET_CONNECT_Connected
<< UICR_PSELRESET_CONNECT_Pos;
ESP_LOGD(
TAG, " GPIO as NFC pins: %s, GPIO as nRESET pin: %s",
YESNO((NRF_UICR->NFCPINS & UICR_NFCPINS_PROTECT_Msk) == (UICR_NFCPINS_PROTECT_NFC << UICR_NFCPINS_PROTECT_Pos)),
YESNO(n_reset_enabled));
if (n_reset_enabled) {
uint8_t port = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PORT_Msk) >> UICR_PSELRESET_PORT_Pos;
uint8_t pin = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PIN_Msk) >> UICR_PSELRESET_PIN_Pos;
ESP_LOGD(TAG, " nRESET port P%u.%02u", port, pin);
}
#ifdef USE_BOOTLOADER_MCUBOOT
ESP_LOGD(TAG, " Bootloader: mcuboot");
#else
ESP_LOGD(TAG, " Bootloader: Adafruit, version %u.%u.%u", (BOOTLOADER_VERSION_REGISTER >> 16) & 0xFF,
(BOOTLOADER_VERSION_REGISTER >> 8) & 0xFF, BOOTLOADER_VERSION_REGISTER & 0xFF);
ESP_LOGD(TAG, " MBR bootloader addr 0x%08x, UICR bootloader addr 0x%08x", read_mem_u32(MBR_BOOTLOADER_ADDR),
NRF_UICR->NRFFW[0]);
ESP_LOGD(TAG, " MBR param page addr 0x%08x, UICR param page addr 0x%08x", read_mem_u32(MBR_PARAM_PAGE_ADDR),
NRF_UICR->NRFFW[1]);
if (is_sd_present()) {
uint32_t const sd_id = sd_id_get();
uint32_t const sd_version = sd_version_get();
uint32_t ver[3];
ver[0] = sd_version / 1000000;
ver[1] = (sd_version - ver[0] * 1000000) / 1000;
ver[2] = (sd_version - ver[0] * 1000000 - ver[1] * 1000);
ESP_LOGD(TAG, " SoftDevice: S%u %u.%u.%u", sd_id, ver[0], ver[1], ver[2]);
#ifdef USE_SOFTDEVICE_ID
#ifdef USE_SOFTDEVICE_VERSION
if (USE_SOFTDEVICE_ID != sd_id || USE_SOFTDEVICE_VERSION != ver[0]) {
ESP_LOGE(TAG, "Built for SoftDevice S%u %u.x.y. It may crash due to mismatch of bootloader version.",
USE_SOFTDEVICE_ID, USE_SOFTDEVICE_VERSION);
}
#else
if (USE_SOFTDEVICE_ID != sd_id) {
ESP_LOGE(TAG, "Built for SoftDevice S%u. It may crash due to mismatch of bootloader version.", USE_SOFTDEVICE_ID);
}
#endif
#endif
}
#endif
// 13 words of 8 hex digits, separated by spaces
char uicr_buf[13 * 9];
auto uicr = [&uicr_buf](volatile uint32_t *data, uint8_t size) {
size_t len = 0;
for (size_t i = 0; i < size; i++) {
len = buf_append_printf(uicr_buf, sizeof(uicr_buf), len, i > 0 ? " %08" PRIX32 : "%08" PRIX32, data[i]);
}
return uicr_buf;
};
ESP_LOGD(TAG, " NRFFW %s", uicr(NRF_UICR->NRFFW, 13));
ESP_LOGD(TAG, " NRFHW %s", uicr(NRF_UICR->NRFHW, 12));
#ifdef ESPHOME_LOG_HAS_VERBOSE
log_peripherals_info();
#endif
return pos;
}
// The Python side enables the statistics only for a verbose logger
#ifdef CONFIG_SCHED_THREAD_USAGE_ANALYSIS
static void log_thread_usage(const struct k_thread *thread, void *user_data) {
+1 -1
View File
@@ -9,7 +9,7 @@ void HOT Logger::write_msg_(const char *msg, uint16_t len) {
char buffer[TIMESTAMP_LEN + ESPHOME_LOGGER_TX_BUFFER_SIZE + HEADROOM];
time_t rawtime;
time(&rawtime);
::time(&rawtime);
struct tm timeinfo;
localtime_r(&rawtime, &timeinfo); // Thread-safe version
size_t pos = strftime(buffer, TIMESTAMP_LEN + 1, "[%H:%M:%S]", &timeinfo);
-164
View File
@@ -1,164 +0,0 @@
#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
-56
View File
@@ -1,56 +0,0 @@
#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
+47 -295
View File
@@ -1,6 +1,5 @@
#ifdef USE_ESP32
#include "modem_component.h"
#include "at_reply.h"
#include "soc/soc_caps.h"
#include <driver/uart.h>
@@ -43,14 +42,6 @@ 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
@@ -65,12 +56,6 @@ 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;
@@ -88,21 +73,8 @@ 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",
"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);
}
"PIN record not saved", "APN or radio setup failed", "No network attachment", "PPP link failed",
"Modem teardown failed");
// Indexed by esp_modem::command_result
PROGMEM_STRING_TABLE(CommandResultStrings, "OK", "FAIL", "TIMEOUT");
@@ -614,9 +586,6 @@ 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
@@ -642,18 +611,21 @@ 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 (this->set_uart_baud_(baud) != ESP_OK) {
if (uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), 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) {
@@ -661,31 +633,11 @@ ModemState ModemComponent::handle_state_enabling_() {
}
}
if (!found) {
// 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) {
// The detection at the current rate already failed; a UART that refused every other rate set BAUD
if (!probed && !rejected) {
this->not_responding_(detected);
}
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);
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
}
ESP_LOGD(TAG, "Modem responded at baud %d", this->current_baud_rate_);
break;
@@ -719,19 +671,10 @@ 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.
@@ -747,7 +690,6 @@ 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);
@@ -756,11 +698,12 @@ 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 (this->set_uart_baud_(this->baud_rate_) != ESP_OK) {
if (uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), 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);
@@ -788,7 +731,6 @@ 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;
}
@@ -804,13 +746,12 @@ 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; a command that timed out comes back here unsure of the modem
// ENABLING just synced; only a failed attachment read comes back here unsure of the modem
if (this->resync_) {
this->resync_ = false;
if (this->dce_->sync() != command_result::OK) {
@@ -851,78 +792,35 @@ ModemState ModemComponent::handle_state_connecting_() {
}
this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON;
this->attach_polls_ = 0;
this->idle_polls_ = 0;
this->unknown_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;
}
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->request_resync_();
this->connect_step_ = ConnectStep::CONNECT_STEP_START; // start over with a sync on the next pass
this->resync_ = true;
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, mode = -1; // -1 stays when the query fails
int rssi = 99, ber = 99, registration = -1, mode = -1; // -1 stays when the query fails
this->dce_->get_network_registration_state(registration);
this->dce_->get_signal_quality(rssi, ber);
this->dce_->get_network_system_mode(mode);
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_);
}
ESP_LOGW(TAG, "Modem not attached yet: registration %d, network type %d, CSQ %d, BER %d", registration, mode,
rssi, ber);
this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON; // request the attachment again
}
this->set_fault_(registration == REGISTRATION_DENIED ? ModemFault::MODEM_FAULT_REGISTRATION_DENIED
: ModemFault::MODEM_FAULT_NOT_ATTACHED);
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
return this->retry_(ModemState::MODEM_STATE_CONNECTING, ATTACH_POLL_MS);
}
@@ -1025,114 +923,11 @@ 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) {
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);
}
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); }
@@ -1159,54 +954,13 @@ 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) {
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("...") : "";
std::string output;
const command_result result = this->dce_->at(cmd, output, timeout);
if (result == command_result::OK) {
ESP_LOGI(TAG, "AT '%s' -> OK: %s%s", cmd, cut, this->reply_);
ESP_LOGI(TAG, "AT '%s' -> OK: %s", cmd, output.c_str());
} else {
ESP_LOGW(TAG, "AT '%s' -> %s: %s%s", cmd, LOG_STR_ARG(result_to_str(result)), cut, this->reply_);
ESP_LOGW(TAG, "AT '%s' -> %s: %s", cmd, LOG_STR_ARG(result_to_str(result)), output.c_str());
}
return result;
}
@@ -1219,27 +973,25 @@ SimResult ModemComponent::prepare_sim_() {
return SimResult::SIM_RESULT_RETRY; // the save wakes the task
}
#endif
// 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) {
std::string output;
if (this->dce_->at("AT+CPIN?", output, COMMAND_TIMEOUT_MS) != 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", this->reply_);
this->sim_not_ready_(this->reply_);
ESP_LOGD(TAG, "SIM status not readable yet: %s", output.c_str());
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
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 = sim_status(this->reply_);
const char *found = strstr(output.c_str(), "+CPIN:");
if (found != nullptr) {
found += sizeof("+CPIN:") - 1;
while (*found == ' ') {
found++;
}
}
const StringRef status = found != nullptr ? StringRef(found) : StringRef();
if (status.empty()) {
ESP_LOGD(TAG, "SIM status not reported yet: %s", this->reply_);
this->sim_not_ready_(this->reply_);
ESP_LOGD(TAG, "SIM status not reported yet: %s", output.c_str());
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
return SimResult::SIM_RESULT_RETRY;
}
ESP_LOGD(TAG, "SIM: %s", status.c_str());
@@ -1267,8 +1019,8 @@ SimResult ModemComponent::prepare_sim_() {
this->set_fault_(ModemFault::MODEM_FAULT_SIM_LOCKED);
return SimResult::SIM_RESULT_LOCKED;
}
ESP_LOGD(TAG, "SIM not ready: %s", status.c_str()); // e.g. NOT READY or NOT INSERTED
this->sim_not_ready_(status.c_str());
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);
return SimResult::SIM_RESULT_RETRY;
}
#ifdef USE_MODEM_PIN_CODE
+1 -22
View File
@@ -62,7 +62,6 @@ 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,
};
@@ -152,7 +151,6 @@ 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;
@@ -202,20 +200,8 @@ 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
@@ -235,9 +221,6 @@ 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_;
@@ -308,9 +291,6 @@ 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};
@@ -318,8 +298,7 @@ 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 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 resync_{false}; // the attachment read failed, 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];
+12 -3
View File
@@ -323,12 +323,17 @@ bool MQTTClientComponent::can_proceed() {
}
void MQTTClientComponent::start_dnslookup_() {
this->status_set_warning();
// No lookup can start before the network is up: there is no DNS server to ask yet.
// Stay disconnected, and loop() calls this again.
if (!network::is_connected())
return;
for (auto &subscription : this->subscriptions_) {
subscription.subscribed = false;
subscription.resubscribe_timeout = 0;
}
this->status_set_warning();
this->dns_resolve_error_ = false;
this->dns_resolved_ = false;
ip_addr_t addr;
@@ -358,9 +363,13 @@ void MQTTClientComponent::start_dnslookup_() {
}
default:
case ERR_ARG: {
// error
// The lookup never started, so there is no answer to wait for; loop() tries again in 5 seconds
ESP_LOGW(TAG, "Error resolving broker IP address: %d", err);
break;
this->state_ = MQTT_CLIENT_DISCONNECTED;
this->disconnect_reason_ = MQTTClientDisconnectReason::DNS_RESOLVE_ERROR;
this->on_disconnect_.call(MQTTClientDisconnectReason::DNS_RESOLVE_ERROR);
this->connect_begin_ = millis();
return;
}
}
+8 -10
View File
@@ -105,14 +105,13 @@ def _one_of_units(
validator: Callable[[object], float],
allowed: list[int],
unit: str,
scale: float = 1000,
) -> Callable[[object], float]:
"""Validate a quantity with `validator` and accept only the listed values, given in units * `scale`."""
"""Validate a quantity with `validator` and accept only the listed values, given in thousandths of `unit`."""
def validate(value: object) -> float:
value = validator(value)
if round(value * scale) not in allowed:
options = ", ".join(f"{v / scale:g}{unit}" for v in allowed)
if _millis(value) not in allowed:
options = ", ".join(f"{v / 1000:g}{unit}" for v in allowed)
raise cv.Invalid(f"Must be one of {options}")
return value
@@ -139,15 +138,14 @@ 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)
value = cv.resistance(value)
if round(value) not in (kilohms * 1000 for kilohms in THERMISTOR_RESISTANCES):
options = ", ".join(f"{kilohms}kOhm" for kilohms in THERMISTOR_RESISTANCES)
raise cv.Invalid(f"Must be one of {options} or {THERMISTOR_NONE}")
return value
def thermistor_beta(config: ConfigType) -> int:
+10 -3
View File
@@ -13,6 +13,7 @@ from esphome.build_helpers.ccache import resolve_ccache_path
import esphome.codegen as cg
from esphome.components import network
from esphome.components.zephyr import (
PreferenceStorage,
Section,
add_extra_script,
copy_files as zephyr_copy_files,
@@ -106,6 +107,7 @@ from .const import (
VARIANT_NRF52832,
VARIANT_NRF52840,
VARIANT_REGULATOR,
VARIANTS_NRF54L,
VARIANTS_WITHOUT_USB,
)
from .framework import (
@@ -536,6 +538,11 @@ def _final_validate(config):
FINAL_VALIDATE_SCHEMA = _final_validate
def _preferences_storage(variant: str) -> PreferenceStorage:
"""The storage for preferences: ZMS on the RRAM of the nRF54L, NVS on flash."""
return "ZMS" if variant in VARIANTS_NRF54L else "NVS"
@coroutine_with_priority(CoroPriority.PLATFORM)
async def to_code(config: ConfigType) -> None:
"""Convert the configuration to code."""
@@ -544,7 +551,7 @@ async def to_code(config: ConfigType) -> None:
variant = get_nrf52_variant()
cg.add_define("ESPHOME_VARIANT", variant)
cg.add_build_flag(f"-DUSE_NRF52_VARIANT_{variant}")
if variant in (VARIANT_NRF54L15, VARIANT_NRF54LM20):
if variant in VARIANTS_NRF54L:
# The entropy driver runs on the CRACEN crypto unit, which needs Nordic's PSA crypto
include_west_project("mbedtls")
include_west_project("oberon-psa-crypto")
@@ -612,11 +619,11 @@ async def to_code(config: ConfigType) -> None:
if config[KEY_BOOTLOADER] in ADAFRUIT_BOOTLOADERS:
cg.add_define("USE_BOOTLOADER_ADAFRUIT")
zephyr_setup_preferences()
zephyr_setup_preferences(_preferences_storage(variant))
zephyr_to_code(config)
# The nRF54L has RRAM (cpuapp_rram) and no flash0 node
if CORE.testing_mode and variant not in (VARIANT_NRF54L15, VARIANT_NRF54LM20):
if CORE.testing_mode and variant not in VARIANTS_NRF54L:
zephyr_add_overlay(
f"""
&flash0 {{
+2 -1
View File
@@ -17,6 +17,7 @@ from .const import (
VARIANT_NRF54LM20,
VARIANT_NRF52832,
VARIANT_NRF52840,
VARIANTS_NRF54L,
)
from .framework import (
check_and_install,
@@ -145,7 +146,7 @@ def upload_using_cmsis_dap(unique_id: str | None = None) -> None:
pyocd = [str(paths["python_executable"]), "-m", "pyocd"]
probe = ["-t", target] + (["-u", unique_id] if unique_id else [])
cmd = [*pyocd, "flash", "--no-wait", *probe, "-e", "sector"]
if variant in (VARIANT_NRF54L15, VARIANT_NRF54LM20):
if variant in VARIANTS_NRF54L:
cmd += ["--script", str(_NRF54L_WATCHDOG_SCRIPT)]
cmd += [str(image) for image in images]
if not run_command_ok(cmd, env=env, stream_output=True):
+2
View File
@@ -41,6 +41,8 @@ VARIANT_I2C = {
VARIANT_NRF54LM20: VariantI2C("i2c21", (1, 3)),
}
VARIANTS_WITHOUT_USB = frozenset({VARIANT_NRF52832, VARIANT_NRF54L15})
# The nRF54L family: RRAM instead of flash, the CRACEN crypto unit and the wdt31 watchdog
VARIANTS_NRF54L = frozenset({VARIANT_NRF54L15, VARIANT_NRF54LM20})
# Devicetree label of the main regulator, reg1 on the others
VARIANT_REGULATOR = {VARIANT_NRF52832: "reg"}
VARIANT_FLASH_SIZE = {VARIANT_NRF52832: 0x80000, VARIANT_NRF52840: 0x100000}
@@ -15,6 +15,9 @@ namespace esphome::uart {
ESPHOME_LOG_TAG(TAG, "uart");
// GPIO32-47 (RP2350B) and GPIO64 (CYW43) are in no mask; a 32-bit shift by them is undefined.
static constexpr bool pin_in_mask(uint8_t pin, uint32_t mask) { return pin < 32 && (mask & (1U << pin)) != 0; }
uint16_t RP2UartComponent::get_config() {
uint16_t config = 0;
@@ -81,9 +84,9 @@ void RP2UartComponent::setup() {
if (this->tx_pin_->is_inverted()) {
ESP_LOGD(TAG, "An inverted TX pin %u can only be used with SerialPIO", this->tx_pin_->get_pin());
} else {
if (((1 << this->tx_pin_->get_pin()) & valid_tx_uart_0) != 0) {
if (pin_in_mask(this->tx_pin_->get_pin(), valid_tx_uart_0)) {
tx_hw = 0;
} else if (((1 << this->tx_pin_->get_pin()) & valid_tx_uart_1) != 0) {
} else if (pin_in_mask(this->tx_pin_->get_pin(), valid_tx_uart_1)) {
tx_hw = 1;
} else {
ESP_LOGD(TAG, "TX pin %u can only be used with SerialPIO", this->tx_pin_->get_pin());
@@ -95,9 +98,9 @@ void RP2UartComponent::setup() {
if (this->rx_pin_->is_inverted()) {
ESP_LOGD(TAG, "An inverted RX pin %u can only be used with SerialPIO", this->rx_pin_->get_pin());
} else {
if (((1 << this->rx_pin_->get_pin()) & valid_rx_uart_0) != 0) {
if (pin_in_mask(this->rx_pin_->get_pin(), valid_rx_uart_0)) {
rx_hw = 0;
} else if (((1 << this->rx_pin_->get_pin()) & valid_rx_uart_1) != 0) {
} else if (pin_in_mask(this->rx_pin_->get_pin(), valid_rx_uart_1)) {
rx_hw = 1;
} else {
ESP_LOGD(TAG, "RX pin %u can only be used with SerialPIO", this->rx_pin_->get_pin());
+11 -3
View File
@@ -1,7 +1,7 @@
from collections.abc import Callable
from pathlib import Path
import textwrap
from typing import NamedTuple, TypedDict
from typing import Literal, NamedTuple, TypedDict
import esphome.codegen as cg
import esphome.config_validation as cv
@@ -212,10 +212,18 @@ async def _cdc_acm_to_code() -> None:
_cdc_acm_add_ports()
def zephyr_setup_preferences() -> None:
PreferenceStorage = Literal["NVS", "ZMS"]
def zephyr_setup_preferences(storage: PreferenceStorage = "NVS") -> None:
"""Store preferences through the settings subsystem.
`storage` picks the Zephyr storage backend: NVS for flash, ZMS for RRAM and MRAM.
"""
cg.add(zephyr_ns.setup_preferences())
zephyr_add_prj_conf("SETTINGS", True)
zephyr_add_prj_conf("NVS", True)
zephyr_add_prj_conf(storage, True)
zephyr_add_prj_conf(f"SETTINGS_{storage}", True)
zephyr_add_prj_conf("FLASH_MAP", True)
zephyr_add_prj_conf("FLASH", True)
+3 -1
View File
@@ -846,7 +846,9 @@ def convert_visual_temperatures(
that needs ``full_config`` is left for final validation, which runs this again with it."""
if (unit := entity_temperature_unit(config, full_config)) is None:
return config
visual = config[CONF_VISUAL]
# A platform entry that only holds nested entities has no visual section of its own
if (visual := config.get(CONF_VISUAL)) is None:
return config
convert_temperature_keys(visual, (CONF_MIN_TEMPERATURE, CONF_MAX_TEMPERATURE), unit)
section = visual if delta_section is None else visual.get(delta_section)
if section is not None:
@@ -222,6 +222,20 @@ def test_a_resolved_unit_waits_for_the_full_config() -> None:
assert config[CONF_VISUAL][CONF_MIN_TEMPERATURE] == pytest.approx(59.0)
def test_final_validate_skips_a_platform_that_only_holds_nested_climates() -> None:
"""A hub platform may put each of its climates under a key of one platform entry."""
nested = climate_schema(climate_ns.class_("NestedClimate", Climate))
platform_schema = cv.Schema({cv.Optional("zone_1"): nested})
config = platform_schema(
{"zone_1": {CONF_NAME: "Zone 1", CONF_VISUAL: {CONF_MIN_TEMPERATURE: "50°F"}}}
)
# The platform entry itself is not a climate and has no visual section
assert CONF_VISUAL not in config
_final_validate([config])
# The nested climate was converted by its own schema
assert config["zone_1"][CONF_VISUAL][CONF_MIN_TEMPERATURE] == pytest.approx(10.0)
@pytest.mark.parametrize(
("use_fahrenheit", "cn105_lines"),
[
@@ -15,6 +15,7 @@ from esphome.components.npm1300 import (
_config,
_output_config,
_termination_voltage_code,
_thermistor_resistance,
_vbus_current_limit_code,
thermistor_beta,
)
@@ -186,3 +187,21 @@ def test_config_thermistor(
fields = _fields(_config(config))
assert fields["thermistor"] == code
assert fields["thermistor_beta"] == beta
@pytest.mark.parametrize(
("value", "result"),
[
("10kOhm", 10000.0),
("0.047MOhm", 47000.0),
("100000", 100000.0),
("None", "none"),
],
)
def test_thermistor_resistance(value: str, result: float | str) -> None:
assert _thermistor_resistance(value) == result
def test_thermistor_resistance_rejected() -> None:
with pytest.raises(cv.Invalid, match="10kOhm, 47kOhm, 100kOhm or none"):
_thermistor_resistance("22kOhm")
+6
View File
@@ -0,0 +1,6 @@
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
# touchscreen.h includes display.h
manifest.dependencies = manifest.dependencies + ["display"]
+42
View File
@@ -0,0 +1,42 @@
#pragma once
#include <array>
#include <gtest/gtest.h>
#include "esphome/components/cst816/touchscreen/cst816_touchscreen.h"
namespace esphome::cst816::testing {
static constexpr uint8_t ADDRESS = 0x15;
// The driver reads REG_STATUS onwards in one transfer: status, gesture, touch count, then two points.
static constexpr size_t FRAME_SIZE = 13;
/// Serves one fixed status frame.
class FrameBus final : public i2c::I2CBus {
public:
explicit FrameBus(std::array<uint8_t, FRAME_SIZE> frame) : frame_(frame) {}
i2c::ErrorCode write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
size_t read_count) override {
EXPECT_EQ(address, ADDRESS);
for (size_t i = 0; i < read_count; i++)
read_buffer[i] = i < FRAME_SIZE ? this->frame_[i] : 0;
return i2c::ERROR_OK;
}
protected:
std::array<uint8_t, FRAME_SIZE> frame_;
};
inline std::array<uint8_t, FRAME_SIZE> make_frame(uint8_t touch_num, uint16_t x = 0, uint16_t y = 0) {
std::array<uint8_t, FRAME_SIZE> frame{};
frame[REG_TOUCH_NUM] = touch_num;
frame[REG_XPOS_HIGH] = (x >> 8) & 0x0F;
frame[REG_XPOS_LOW] = x & 0xFF;
frame[REG_YPOS_HIGH] = (y >> 8) & 0x0F;
frame[REG_YPOS_LOW] = y & 0xFF;
return frame;
}
} // namespace esphome::cst816::testing
@@ -0,0 +1,88 @@
#include <gtest/gtest.h>
#include <memory>
#include "../common.h"
namespace esphome::cst816::testing {
class CST816TouchscreenTest : public ::testing::Test {
protected:
void feed_(const std::array<uint8_t, FRAME_SIZE> &frame) {
this->bus_ = std::make_unique<FrameBus>(frame);
this->touchscreen_.set_i2c_bus(this->bus_.get());
this->touchscreen_.set_i2c_address(ADDRESS);
this->touchscreen_.update_touches();
}
std::unique_ptr<FrameBus> bus_;
CST816Touchscreen touchscreen_;
};
// An idle frame reports 0xFF in the touch count byte and 0xFFF coordinates. Masking 0xFF to the
// low two bits turns that into three touches at the maximum position, a phantom tap.
TEST_F(CST816TouchscreenTest, IdleAllOnesFrameIsIgnored) {
this->feed_(make_frame(0xFF, 0x0FFF, 0x0FFF));
EXPECT_TRUE(this->touchscreen_.get_touches().empty());
}
TEST_F(CST816TouchscreenTest, ZeroTouchCountIsIgnored) {
this->feed_(make_frame(0));
EXPECT_TRUE(this->touchscreen_.get_touches().empty());
}
// Three is the boundary the guard rejects: the old mask turned a count of three into three
// touches, so this is the value whose behaviour changes.
TEST_F(CST816TouchscreenTest, TouchCountThreeIsIgnored) {
this->feed_(make_frame(3, 100, 200));
EXPECT_TRUE(this->touchscreen_.get_touches().empty());
}
// The count is the whole low nibble, so 0x05 must not be masked down to one touch by a 0x03 mask.
TEST_F(CST816TouchscreenTest, TouchCountFiveIsIgnored) {
this->feed_(make_frame(0x05, 100, 200));
EXPECT_TRUE(this->touchscreen_.get_touches().empty());
}
TEST_F(CST816TouchscreenTest, SingleTouchIsReported) {
this->feed_(make_frame(1, 300, 100));
auto touches = this->touchscreen_.get_touches();
ASSERT_EQ(touches.size(), 1u);
EXPECT_EQ(touches[0].x_raw, 300);
EXPECT_EQ(touches[0].y_raw, 100);
}
// CST826/CST836 can report two points; the driver only consumes the first one.
TEST_F(CST816TouchscreenTest, TwoPointFrameReportsFirstPoint) {
this->feed_(make_frame(2, 300, 100));
auto touches = this->touchscreen_.get_touches();
ASSERT_EQ(touches.size(), 1u);
EXPECT_EQ(touches[0].x_raw, 300);
EXPECT_EQ(touches[0].y_raw, 100);
}
TEST_F(CST816TouchscreenTest, SentinelPositionIsIgnored) {
this->feed_(make_frame(1, 0x0FFF, 100));
EXPECT_TRUE(this->touchscreen_.get_touches().empty());
}
// The sentinel is checked on both axes; a valid X with Y=0xFFF is still an idle reading.
TEST_F(CST816TouchscreenTest, SentinelYPositionIsIgnored) {
this->feed_(make_frame(1, 100, 0x0FFF));
EXPECT_TRUE(this->touchscreen_.get_touches().empty());
}
// x_raw_max_/y_raw_max_ are calibration endpoints, not validity limits: the base class applies them
// after swapping axes and clamps readings outside them. A touch beyond the calibrated maximum is
// still a real touch and must reach the base class.
TEST_F(CST816TouchscreenTest, CalibrationBoundsDoNotDropTouches) {
this->touchscreen_.set_calibration(0, 240, 0, 320);
this->touchscreen_.set_swap_xy(true);
this->feed_(make_frame(1, 300, 100));
auto touches = this->touchscreen_.get_touches();
ASSERT_EQ(touches.size(), 1u);
EXPECT_EQ(touches[0].x_raw, 100);
EXPECT_EQ(touches[0].y_raw, 300);
}
} // namespace esphome::cst816::testing
@@ -0,0 +1,2 @@
packages:
debug: !include common.yaml
@@ -0,0 +1,2 @@
packages:
debug: !include common.yaml
-11
View File
@@ -1,11 +0,0 @@
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}
)
-177
View File
@@ -1,177 +0,0 @@
#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
@@ -0,0 +1,39 @@
"""Each SoC variant stores preferences in the storage made for its memory."""
import pytest
from esphome.components import nrf52
from esphome.components.nrf52.const import (
VARIANT_NRF54L15,
VARIANT_NRF54LM20,
VARIANT_NRF51822,
VARIANT_NRF52832,
VARIANT_NRF52840,
)
from esphome.components.zephyr import zephyr_setup_preferences
from esphome.components.zephyr.const import KEY_PRJ_CONF, KEY_ZEPHYR
from esphome.core import CORE
@pytest.mark.parametrize(
("variant", "storage", "other"),
[
(VARIANT_NRF54L15, "ZMS", "NVS"),
(VARIANT_NRF54LM20, "ZMS", "NVS"),
(VARIANT_NRF52840, "NVS", "ZMS"),
(VARIANT_NRF52832, "NVS", "ZMS"),
(VARIANT_NRF51822, "NVS", "ZMS"),
],
)
def test_variant_picks_the_settings_backend(
variant: str, storage: str, other: str
) -> None:
CORE.data[KEY_ZEPHYR] = {KEY_PRJ_CONF: {}}
zephyr_setup_preferences(nrf52._preferences_storage(variant))
prj_conf = CORE.data[KEY_ZEPHYR][KEY_PRJ_CONF][""]
assert prj_conf[f"CONFIG_{storage}"] == (True, True)
assert prj_conf[f"CONFIG_SETTINGS_{storage}"] == (True, True)
assert f"CONFIG_{other}" not in prj_conf
assert f"CONFIG_SETTINGS_{other}" not in prj_conf
@@ -1550,6 +1550,15 @@ def test_convert_visual_temperatures(
convert_visual_temperatures({"visual": {}}, delta_keys, delta_section)
def test_convert_visual_temperatures_without_a_visual_section() -> None:
"""A platform entry that only holds nested entities has no visual section and is left alone."""
nested = {"visual": {"min_temperature": (50.0, "°F")}}
config = {"zone_1": nested}
assert convert_visual_temperatures(config, ("step",)) is config
assert nested["visual"]["min_temperature"] == (50.0, "°F")
@pytest.mark.asyncio
async def test_setup_entity_integrations_registers_mqtt_and_web_server(
monkeypatch: pytest.MonkeyPatch, setup_test_environment: list[str]
+7 -1
View File
@@ -1792,7 +1792,13 @@ def test_ccache_env_opt_in_without_binary(
# Explicit IDF_CCACHE_ENABLE=1 forces it on; without a usable binary
# IDF's CMake silently skips ccache, so this branch must say so out loud.
p1, p2, p3 = _ccache_patches(tmp_path, None, tmp_path / "build")
with patch.dict("os.environ", {"IDF_CCACHE_ENABLE": "1"}, clear=True), p1, p2, p3:
with (
patch.dict("os.environ", {"IDF_CCACHE_ENABLE": "1"}, clear=True),
patch("esphome.espidf.framework.shutil.which", return_value=None),
p1,
p2,
p3,
):
env = _ccache_env()
assert env["IDF_CCACHE_ENABLE"] == "1"
assert env["CCACHE_DIR"] == str(tmp_path / "tools" / "ccache")
+21 -1
View File
@@ -2,7 +2,11 @@
import pytest
from esphome.components.zephyr import zephyr_add_prj_conf, zephyr_add_prj_conf_min
from esphome.components.zephyr import (
zephyr_add_prj_conf,
zephyr_add_prj_conf_min,
zephyr_setup_preferences,
)
from esphome.components.zephyr.const import KEY_PRJ_CONF, KEY_ZEPHYR
from esphome.core import CORE
@@ -28,3 +32,19 @@ def test_largest_min_wins_in_any_order() -> None:
zephyr_add_prj_conf_min("MAIN_STACK_SIZE", 4096)
assert _prj_conf()["CONFIG_MAIN_STACK_SIZE"] == (8192, True)
def test_preferences_use_nvs_by_default() -> None:
zephyr_setup_preferences()
assert _prj_conf()["CONFIG_NVS"] == (True, True)
assert _prj_conf()["CONFIG_SETTINGS_NVS"] == (True, True)
assert "CONFIG_ZMS" not in _prj_conf()
def test_preferences_can_use_zms() -> None:
zephyr_setup_preferences("ZMS")
assert _prj_conf()["CONFIG_ZMS"] == (True, True)
assert _prj_conf()["CONFIG_SETTINGS_ZMS"] == (True, True)
assert "CONFIG_NVS" not in _prj_conf()