Compare commits

..
80 changed files with 639 additions and 3390 deletions

No files matched your search

-2
View File
@@ -146,7 +146,6 @@ esphome/components/cover/* @esphome/core
esphome/components/cs5460a/* @balrog-kun
esphome/components/cse7761/* @berfenger
esphome/components/cst226/* @clydebarrow
esphome/components/cst3240/* @tpruvot
esphome/components/cst328/* @latonita
esphome/components/cst816/* @clydebarrow
esphome/components/cst9220/* @clydebarrow
@@ -468,7 +467,6 @@ esphome/components/nfc/* @jesserockz @kbx81
esphome/components/noblex/* @AGalfra
esphome/components/noise/* @esphome/core
esphome/components/npi19/* @bakerkj
esphome/components/npm1300/* @tomaszduda23
esphome/components/nrf52/* @tomaszduda23
esphome/components/ns2009/* @tchilov
esphome/components/ns2009/touchscreen/* @tchilov
@@ -278,9 +278,10 @@ APIError APINoiseFrameHelper::state_action_client_hello_() {
state_ = State::FAILED;
return APIError::OUT_OF_MEMORY;
}
uint8_t *payload = put_be16(dst, rx_size);
dst[0] = (uint8_t) (rx_size >> 8);
dst[1] = (uint8_t) rx_size;
if (rx_size > 0) {
std::memcpy(payload, this->rx_buf_.data(), rx_size);
std::memcpy(dst + 2, this->rx_buf_.data(), rx_size);
}
#ifdef USE_API_OUTGOING_CONNECTION
@@ -463,8 +464,10 @@ APIError APINoiseFrameHelper::encrypt_noise_message_(uint8_t *buf_start, uint16_
// Write message header (to be encrypted)
constexpr uint8_t msg_offset = noise::FRAME_HEADER_SIZE;
put_be16(buf_start + msg_offset, message_type);
put_be16(buf_start + msg_offset + 2, payload_size);
buf_start[msg_offset] = static_cast<uint8_t>(message_type >> 8); // type high byte
buf_start[msg_offset + 1] = static_cast<uint8_t>(message_type); // type low byte
buf_start[msg_offset + 2] = static_cast<uint8_t>(payload_size >> 8); // data_len high byte
buf_start[msg_offset + 3] = static_cast<uint8_t>(payload_size); // data_len low byte
// payload data is already in the buffer starting at offset + 7
// Encrypt the message in place
@@ -1,7 +1,6 @@
#include "api_overflow_buffer.h"
#ifdef USE_API
#include <cstring>
#include "esphome/core/helpers.h"
namespace esphome::api {
@@ -18,7 +17,7 @@ ssize_t APIOverflowBuffer::try_drain(socket::Socket *socket) {
while (this->count_ > 0) {
uint8_t *msg = this->buf_.data() + this->head_;
size_t len = encode_value_le<uint16_t>(msg);
size_t len = msg[0] | (msg[1] << 8);
ssize_t sent = socket->write(msg + LEN_PREFIX, len);
if (sent <= 0)
+1 -5
View File
@@ -35,11 +35,7 @@ async def to_code(config: ConfigType) -> None:
add_idf_component(name="esp32async/asynctcp", ref="3.4.91")
elif CORE.is_libretiny:
# https://github.com/ESP32Async/AsyncTCP
cg.add_library("ESP32Async/AsyncTCP", "3.5.0")
# AsyncTCP 3.5.0 debug logs call xPortGetCoreID(), which LibreTiny (single core) lacks; they are compiled
# in by LibreTiny's debug level or CONFIG_ASYNC_TCP_DEBUG, so the call always expands to int(), which is 0
# (a function-like -D does not survive PlatformIO's build flags)
cg.add_build_flag("-DxPortGetCoreID=int")
cg.add_library("ESP32Async/AsyncTCP", "3.4.5")
elif CORE.is_esp8266:
# https://github.com/ESP32Async/ESPAsyncTCP
cg.add_library("ESP32Async/ESPAsyncTCP", "2.0.0")
@@ -2,7 +2,6 @@
#include <algorithm>
#include <cstring>
#include "esphome/core/helpers.h"
namespace esphome::ble_device_base {
@@ -164,7 +163,8 @@ bool aes_ccm_auth_decrypt(const uint8_t key[16], const uint8_t *nonce, size_t no
if (aad_len > 0) {
// Only the < 2^16-2^8 encoding is needed for BLE-sized AAD.
uint8_t blk[16] = {0};
put_be16(blk, aad_len);
blk[0] = static_cast<uint8_t>((aad_len >> 8) & 0xff);
blk[1] = static_cast<uint8_t>(aad_len & 0xff);
size_t ai = 0;
size_t pos = 2;
while (pos < 16 && ai < aad_len)
+2 -2
View File
@@ -1,7 +1,6 @@
#include "cse7761.h"
#include "esphome/core/log.h"
#include "esphome/core/helpers.h"
namespace esphome::cse7761 {
@@ -105,7 +104,8 @@ void CSE7761Component::write_(uint8_t reg, uint16_t data) {
buffer[2] = data & 0xFF;
len = 3;
} else {
put_be16(buffer + 2, data);
buffer[2] = (data >> 8) & 0xFF;
buffer[3] = data & 0xFF;
len = 4;
}
buffer[len] = ~sum_bytes(buffer, len);
-7
View File
@@ -1,7 +0,0 @@
import esphome.codegen as cg
CODEOWNERS = ["@tpruvot"]
DEPENDENCIES = ["i2c"]
DOMAIN = "cst3240"
cst3240_ns = cg.esphome_ns.namespace("cst3240")
@@ -1,14 +0,0 @@
from esphome.components import cstxxx
from esphome.types import ConfigType
from .. import cst3240_ns
AUTO_LOAD = ["cstxxx"]
CST3240Touchscreen = cst3240_ns.class_("CST3240Touchscreen", cstxxx.CSTTouchscreen)
CONFIG_SCHEMA = cstxxx.cst_touchscreen_schema(CST3240Touchscreen, 0x5A)
async def to_code(config: ConfigType) -> None:
await cstxxx.new_cst_touchscreen(config)
@@ -1,112 +0,0 @@
#include "cst3240_touchscreen.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include <utility>
namespace esphome::cst3240 {
ESPHOME_LOG_TAG(TAG, "cst3240.touchscreen");
void CST3240Touchscreen::setup() {
if (this->reset_pin_ == nullptr) {
this->continue_setup_();
return;
}
pulse_reset(this->reset_pin_, {.high_before_ms = 5, .low_ms = 5});
this->set_timeout(30, [this] { this->continue_setup_(); });
}
void CST3240Touchscreen::continue_setup_() {
if (!this->enter_command_mode_())
return;
if (!this->setup_check(this->read_words_(cstxxx::REG_CHIP_INFO, this->project_id_, this->chip_id_),
LOG_STR("Failed to read chip ID")))
return;
// Only warn: the chip ID has not been confirmed on enough boards to fail setup on it
if (this->chip_id_ != CST3240_CHIP_ID) {
ESP_LOGW(TAG, "Unexpected chip ID 0x%04X", this->chip_id_);
}
this->read_words_(cstxxx::REG_FW_VERSION, this->fw_build_, this->fw_version_);
if (this->x_raw_max_ == this->x_raw_min_ || this->y_raw_max_ == this->y_raw_min_) {
uint16_t x_max, y_max;
if (this->read_words_(cstxxx::REG_RESOLUTION, x_max, y_max)) {
this->x_raw_max_ = x_max;
this->y_raw_max_ = y_max;
if (this->swap_x_y_)
std::swap(this->x_raw_max_, this->y_raw_max_);
} else {
this->x_raw_max_ = this->display_->get_native_width();
this->y_raw_max_ = this->display_->get_native_height();
}
}
this->status_comm_check(this->write_register16(cstxxx::REG_NORMAL_MODE, nullptr, 0) == i2c::ERROR_OK);
this->setup_interrupt_pin_(gpio::INTERRUPT_RISING_EDGE);
this->setup_complete_ = true;
}
void CST3240Touchscreen::update_touches() {
if (!this->setup_complete_) {
this->skip_update_ = true;
return;
}
uint8_t data[CST3240_REPORT_SIZE];
if (!this->status_comm_result(this->read_register16(cstxxx::REG_TOUCH_DATA, data, sizeof(data)) == i2c::ERROR_OK)) {
this->skip_update_ = true;
return;
}
const uint8_t sync = data[cstxxx::SYNC_IDX];
if (sync != cstxxx::SYNC_BYTE) {
this->skip_update_ = true;
if (sync != 0) {
ESP_LOGV(TAG, "Skipping report, sync byte 0x%02X", sync);
this->clear_report_();
}
return;
}
const uint8_t count = data[cstxxx::FINGER_COUNT_IDX] & 0x0F;
if (count <= CST3240_MAX_TOUCHES) {
for (uint8_t i = 0; i < count; i++) {
auto touch = cstxxx::decode_touch(data, i);
// A released finger is still listed once, with both press bits clear
if ((touch.event & TOUCH_EVENT_PRESSED) == 0)
continue;
this->add_raw_touch_position_(touch.id, touch.x, touch.y, touch.z);
}
}
if (this->interrupt_pin_ == nullptr) {
this->clear_report_();
} else if (!this->write_byte_reg16(cstxxx::REG_FINGER_COUNT, 0) ||
!this->write_byte_reg16(cstxxx::REG_TOUCH_DATA, cstxxx::SYNC_BYTE)) {
ESP_LOGW(TAG, "Failed to acknowledge the report");
}
}
void CST3240Touchscreen::clear_report_() {
// Built on the stack: write_register16() heap allocates a frame this long
uint8_t frame[2 + CST3240_REPORT_SIZE]{};
put_be16(frame, cstxxx::REG_TOUCH_DATA);
if (this->write(frame, sizeof(frame)) != i2c::ERROR_OK) {
ESP_LOGW(TAG, "Failed to clear the report");
}
}
void CST3240Touchscreen::dump_config() {
ESP_LOGCONFIG(TAG,
"CST3240 Touchscreen:\n"
" Chip ID: 0x%04X, Project ID: 0x%04X\n"
" FW version: %d.%d.%d\n"
" X/Y resolution: %d/%d",
this->chip_id_, this->project_id_, this->fw_version_ >> 8, this->fw_version_ & 0xFF, this->fw_build_,
this->x_raw_max_, this->y_raw_max_);
LOG_I2C_DEVICE(this);
LOG_PIN(" Interrupt Pin: ", this->interrupt_pin_);
LOG_PIN(" Reset Pin: ", this->reset_pin_);
}
} // namespace esphome::cst3240
@@ -1,31 +0,0 @@
#pragma once
#include "esphome/components/cstxxx/cstxxx.h"
#include "esphome/core/component.h"
#include "esphome/core/hal.h"
namespace esphome::cst3240 {
static constexpr uint16_t CST3240_CHIP_ID = 0x3240;
static constexpr uint8_t CST3240_MAX_TOUCHES = 5;
static constexpr uint8_t CST3240_REPORT_SIZE = cstxxx::report_size(CST3240_MAX_TOUCHES);
static constexpr uint8_t TOUCH_EVENT_PRESSED = 0x06;
class CST3240Touchscreen : public cstxxx::CSTTouchscreen {
public:
void setup() override;
void dump_config() override;
protected:
void update_touches() override;
void continue_setup_();
/// Zeroes the touch report block, which polling relies on to tell new reports from old.
void clear_report_();
uint16_t chip_id_{};
uint16_t project_id_{};
uint16_t fw_version_{};
uint16_t fw_build_{};
};
} // namespace esphome::cst3240
+1 -3
View File
@@ -1,5 +1,6 @@
import esphome.codegen as cg
from esphome.components import logger
from esphome.components.nrf52.framework import include_west_project
from esphome.components.zephyr import zephyr_add_prj_conf
from esphome.config_helpers import filter_source_files_from_platform
import esphome.config_validation as cv
@@ -52,9 +53,6 @@ CONFIG_SCHEMA = cv.All(
async def to_code(config: ConfigType) -> None:
if CORE.using_zephyr:
# Imported here so configs for other platforms do not load the nrf52 package
from esphome.components.nrf52.framework import include_west_project
zephyr_add_prj_conf("HWINFO", True)
# gdb thread support
zephyr_add_prj_conf("DEBUG_THREAD_INFO", True)
+1 -1
View File
@@ -173,7 +173,7 @@ void DFPlayer::loop() {
}
// Parse valid received command
uint8_t cmd = this->read_buffer_[3];
uint16_t argument = encode_uint16(this->read_buffer_[5], this->read_buffer_[6]);
uint16_t argument = (this->read_buffer_[5] << 8) | this->read_buffer_[6];
ESP_LOGV(TAG, "Received message cmd: %#02x arg %#04x", cmd, argument);
+1 -1
View File
@@ -22,7 +22,7 @@ void EE895Component::setup() {
uint8_t serial_number[20];
this->read(serial_number, 20);
crc16_check = encode_value_le<uint16_t>(serial_number + 18);
crc16_check = (serial_number[19] << 8) + serial_number[18];
if (!this->setup_check(crc16_check == calc_crc16_(serial_number, 18), LOG_STR("CRC check failed")))
return;
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
@@ -4,7 +4,6 @@
#include <cstring>
#include "esphome/core/application.h"
#include "esphome/core/log.h"
#include "esphome/core/helpers.h"
namespace esphome::entity_transport {
@@ -374,7 +373,8 @@ size_t EntityTransport::write_record_(const LocalEntity &entity, uint8_t *record
#endif
uint16_t tag =
entity.number | (type << TAG_TYPE_SHIFT) | (payload << TAG_PAYLOAD_SHIFT) | (value ? TAG_VALUE_BIT : 0);
put_le16(record, tag);
record[0] = tag;
record[1] = tag >> 8;
return size;
}
+1 -3
View File
@@ -56,6 +56,7 @@ from esphome.const import (
from esphome.core import CORE, EsphomeError, HexInt
from esphome.core.config import BOARD_MAX_LENGTH
from esphome.coroutine import CoroPriority, coroutine_with_priority
from esphome.espidf import sbom
from esphome.espidf.component import IDFComponent, generate_idf_components
import esphome.final_validate as fv
from esphome.helpers import copy_file_if_changed, rmtree, write_file_if_changed
@@ -4032,9 +4033,6 @@ def copy_files():
CORE.relative_build_path("version.txt"),
__version__,
)
# Imported here: sbom loads git and urllib helpers that config validation does not need
from esphome.espidf import sbom
sbom.write_manifests()
# Remote extra build files are fetched into the shared download cache in
+12 -18
View File
@@ -5,8 +5,6 @@
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include <cstring>
namespace esphome::i2c {
ESPHOME_LOG_TAG(TAG, "i2c");
@@ -54,26 +52,22 @@ ErrorCode I2CDevice::read_register16(uint16_t a_register, uint8_t *data, size_t
return bus_->write_readv(this->address_, reinterpret_cast<const uint8_t *>(&a_register), 2, data, len);
}
ErrorCode I2CBus::write_prefixed(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *data,
size_t len) {
SmallBufferWithHeapFallback<20> buffer_alloc(prefix_len + len);
uint8_t *buffer = buffer_alloc.get();
// memcpy needs valid pointers even for a zero length
if (prefix_len != 0)
std::memcpy(buffer, prefix, prefix_len);
if (len != 0)
std::memcpy(buffer + prefix_len, data, len);
return this->write_readv(address, buffer, prefix_len + len, nullptr, 0);
}
ErrorCode I2CDevice::write_register(uint8_t a_register, const uint8_t *data, size_t len) const {
return this->bus_->write_prefixed(this->address_, &a_register, 1, data, len);
SmallBufferWithHeapFallback<17> buffer_alloc(len + 1); // Most I2C writes are <= 16 bytes
uint8_t *buffer = buffer_alloc.get();
buffer[0] = a_register;
std::copy(data, data + len, buffer + 1);
return this->bus_->write_readv(this->address_, buffer, len + 1, nullptr, 0);
}
ErrorCode I2CDevice::write_register16(uint16_t a_register, const uint8_t *data, size_t len) const {
uint8_t reg[2];
put_be16(reg, a_register);
return this->bus_->write_prefixed(this->address_, reg, sizeof(reg), data, len);
SmallBufferWithHeapFallback<18> buffer_alloc(len + 2); // Most I2C writes are <= 16 bytes + 2 for register
uint8_t *buffer = buffer_alloc.get();
put_be16(buffer, a_register);
std::copy(data, data + len, buffer + 2);
return this->bus_->write_readv(this->address_, buffer, len + 2, nullptr, 0);
}
bool I2CDevice::write_registers(const I2CRegValue *table, size_t count) const {
-6
View File
@@ -44,12 +44,6 @@ class I2CBus {
virtual ErrorCode write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
size_t read_count) = 0;
/// @brief Writes `prefix` then `data` in one transaction, as for a register address followed by its data.
/// The built-in buses send the two parts without copying them; the default joins them in a buffer for
/// write_readv(), on the stack for up to 20 bytes.
virtual ErrorCode write_prefixed(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *data,
size_t len);
// Legacy functions for compatibility
ErrorCode read(uint8_t address, uint8_t *buffer, size_t len) {
+5 -8
View File
@@ -84,9 +84,8 @@ void ArduinoI2CBus::dump_config() {
this->dump_scan_results_();
}
ErrorCode ArduinoI2CBus::transfer_(uint8_t address, const uint8_t *prefix, size_t prefix_len,
const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
size_t read_count) {
ErrorCode ArduinoI2CBus::write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count,
uint8_t *read_buffer, size_t read_count) {
#if defined(USE_ESP8266)
this->set_pins_and_clock_(); // reconfigure Wire global state in case there are multiple instances
#endif
@@ -95,15 +94,13 @@ ErrorCode ArduinoI2CBus::transfer_(uint8_t address, const uint8_t *prefix, size_
return ERROR_NOT_INITIALIZED;
}
if (prefix_len != 0)
ESP_LOGV_HEX(TAG, prefix, prefix_len, I2C_MAX_LOG_BYTES, "0x%02X TX prefix %s", address);
ESP_LOGV_HEX(TAG, write_buffer, write_count, I2C_MAX_LOG_BYTES, "0x%02X TX %s", address);
uint8_t status = 0;
if (prefix_len != 0 || write_count != 0 || read_count == 0) {
if (write_count != 0 || read_count == 0) {
this->wire_->beginTransmission(address);
if ((prefix_len != 0 && this->wire_->write(prefix, prefix_len) != prefix_len) ||
this->wire_->write(write_buffer, write_count) != write_count) {
size_t ret = this->wire_->write(write_buffer, write_count);
if (ret != write_count) {
ESP_LOGV(TAG, "TX failed");
return ERROR_UNKNOWN;
}
+1 -10
View File
@@ -19,13 +19,7 @@ class ArduinoI2CBus final : public InternalI2CBus, public Component {
void setup() override;
void dump_config() override;
ErrorCode write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
size_t read_count) override {
return this->transfer_(address, nullptr, 0, write_buffer, write_count, read_buffer, read_count);
}
ErrorCode write_prefixed(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *data,
size_t len) override {
return this->transfer_(address, prefix, prefix_len, data, len, nullptr, 0);
}
size_t read_count) override;
float get_setup_priority() const override { return setup_priority::BUS; }
void set_scan(bool scan) { this->scan_ = scan; }
@@ -41,9 +35,6 @@ class ArduinoI2CBus final : public InternalI2CBus, public Component {
#endif
private:
/// Writes `prefix` then `write_buffer` in one transaction, then reads
ErrorCode transfer_(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *write_buffer,
size_t write_count, uint8_t *read_buffer, size_t read_count);
void recover_();
void set_pins_and_clock_();
RecoveryCode recovery_result_;
+40 -34
View File
@@ -200,8 +200,8 @@ void IDFI2CBus::dump_config() {
this->dump_scan_results_();
}
ErrorCode IDFI2CBus::transfer_(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *write_buffer,
size_t write_count, uint8_t *read_buffer, size_t read_count) {
ErrorCode IDFI2CBus::write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
size_t read_count) {
// logging is only enabled with v level, if warnings are shown the caller
// should log them
if (!this->initialized_) {
@@ -209,44 +209,50 @@ ErrorCode IDFI2CBus::transfer_(uint8_t address, const uint8_t *prefix, size_t pr
return ERROR_NOT_INITIALIZED;
}
// START, address, prefix, data, START, address, two reads, STOP
i2c_operation_job_t jobs[9]{};
i2c_operation_job_t jobs[8]{};
size_t num_jobs = 0;
auto add_write = [&jobs, &num_jobs](const uint8_t *data, size_t len) ESPHOME_ALWAYS_INLINE {
jobs[num_jobs].command = I2C_MASTER_CMD_WRITE;
jobs[num_jobs].write.ack_check = true;
jobs[num_jobs].write.data = const_cast<uint8_t *>(data);
jobs[num_jobs++].write.total_bytes = len;
};
uint8_t write_addr = (address << 1) | I2C_MASTER_WRITE;
uint8_t read_addr = (address << 1) | I2C_MASTER_READ;
ESP_LOGV(TAG, "Writing %zu bytes, reading %zu bytes", prefix_len + write_count, read_count);
// With nothing to write or read this only addresses the device (the bus scan probe)
if (prefix_len != 0 || write_count != 0 || read_count == 0) {
if (prefix_len != 0)
ESP_LOGV_HEX(TAG, prefix, prefix_len, I2C_MAX_LOG_BYTES, "0x%02X TX prefix %s", address);
ESP_LOGV_HEX(TAG, write_buffer, write_count, I2C_MAX_LOG_BYTES, "0x%02X TX %s", address);
ESP_LOGV(TAG, "Writing %zu bytes, reading %zu bytes", write_count, read_count);
if (read_count == 0 && write_count == 0) {
// basically just a bus probe. Send a start, address and stop
ESP_LOGV(TAG, "0x%02X BUS PROBE", address);
jobs[num_jobs++].command = I2C_MASTER_CMD_START;
add_write(&write_addr, 1);
if (prefix_len != 0)
add_write(prefix, prefix_len);
if (write_count != 0)
add_write(write_buffer, write_count);
}
if (read_count != 0) {
ESP_LOGV(TAG, "0x%02X RX bytes %zu", address, read_count);
jobs[num_jobs++].command = I2C_MASTER_CMD_START;
add_write(&read_addr, 1);
if (read_count > 1) {
jobs[num_jobs].command = I2C_MASTER_CMD_WRITE;
jobs[num_jobs].write.ack_check = true;
jobs[num_jobs].write.data = &write_addr;
jobs[num_jobs++].write.total_bytes = 1;
} else {
if (write_count != 0) {
ESP_LOGV_HEX(TAG, write_buffer, write_count, I2C_MAX_LOG_BYTES, "0x%02X TX %s", address);
jobs[num_jobs++].command = I2C_MASTER_CMD_START;
jobs[num_jobs].command = I2C_MASTER_CMD_WRITE;
jobs[num_jobs].write.ack_check = true;
jobs[num_jobs].write.data = &write_addr;
jobs[num_jobs++].write.total_bytes = 1;
jobs[num_jobs].command = I2C_MASTER_CMD_WRITE;
jobs[num_jobs].write.ack_check = true;
jobs[num_jobs].write.data = (uint8_t *) write_buffer;
jobs[num_jobs++].write.total_bytes = write_count;
}
if (read_count != 0) {
ESP_LOGV(TAG, "0x%02X RX bytes %zu", address, read_count);
jobs[num_jobs++].command = I2C_MASTER_CMD_START;
jobs[num_jobs].command = I2C_MASTER_CMD_WRITE;
jobs[num_jobs].write.ack_check = true;
jobs[num_jobs].write.data = &read_addr;
jobs[num_jobs++].write.total_bytes = 1;
if (read_count > 1) {
jobs[num_jobs].command = I2C_MASTER_CMD_READ;
jobs[num_jobs].read.ack_value = I2C_ACK_VAL;
jobs[num_jobs].read.data = read_buffer;
jobs[num_jobs++].read.total_bytes = read_count - 1;
}
jobs[num_jobs].command = I2C_MASTER_CMD_READ;
jobs[num_jobs].read.ack_value = I2C_ACK_VAL;
jobs[num_jobs].read.data = read_buffer;
jobs[num_jobs++].read.total_bytes = read_count - 1;
jobs[num_jobs].read.ack_value = I2C_NACK_VAL;
jobs[num_jobs].read.data = read_buffer + read_count - 1;
jobs[num_jobs++].read.total_bytes = 1;
}
jobs[num_jobs].command = I2C_MASTER_CMD_READ;
jobs[num_jobs].read.ack_value = I2C_NACK_VAL;
jobs[num_jobs].read.data = read_buffer + read_count - 1;
jobs[num_jobs++].read.total_bytes = 1;
}
jobs[num_jobs++].command = I2C_MASTER_CMD_STOP;
ESP_LOGV(TAG, "Sending %zu jobs", num_jobs);
+1 -10
View File
@@ -19,13 +19,7 @@ class IDFI2CBus final : public InternalI2CBus, public Component {
void setup() override;
void dump_config() override;
ErrorCode write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
size_t read_count) override {
return this->transfer_(address, nullptr, 0, write_buffer, write_count, read_buffer, read_count);
}
ErrorCode write_prefixed(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *data,
size_t len) override {
return this->transfer_(address, prefix, prefix_len, data, len, nullptr, 0);
}
size_t read_count) override;
float get_setup_priority() const override { return setup_priority::BUS; }
void set_scan(bool scan) { this->scan_ = scan; }
@@ -48,9 +42,6 @@ class IDFI2CBus final : public InternalI2CBus, public Component {
#endif
private:
/// Writes `prefix` then `write_buffer` in one transaction, then reads
ErrorCode transfer_(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *write_buffer,
size_t write_count, uint8_t *read_buffer, size_t read_count);
void recover_();
i2c_master_dev_handle_t add_device_(uint32_t frequency);
RecoveryCode recovery_result_{};
+6 -10
View File
@@ -197,9 +197,8 @@ uint8_t SoftwareI2CBus::read_byte_(bool ack) {
return data;
}
ErrorCode SoftwareI2CBus::transfer_(uint8_t address, const uint8_t *prefix, size_t prefix_len,
const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
size_t read_count) {
ErrorCode SoftwareI2CBus::write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count,
uint8_t *read_buffer, size_t read_count) {
if (!this->initialized_) {
ESP_LOGD(TAG, "i2c bus not initialized!");
return ERROR_NOT_INITIALIZED;
@@ -210,28 +209,25 @@ ErrorCode SoftwareI2CBus::transfer_(uint8_t address, const uint8_t *prefix, size
}
this->bus_stuck_ = false;
if (prefix_len != 0)
ESP_LOGV_HEX(TAG, prefix, prefix_len, I2C_MAX_LOG_BYTES, "0x%02X TX prefix %s", address);
ESP_LOGV_HEX(TAG, write_buffer, write_count, I2C_MAX_LOG_BYTES, "0x%02X TX %s", address);
this->timed_out_ = false;
ErrorCode err = ERROR_OK;
this->start_();
// An empty transfer only addresses the device (used by the bus scan)
const size_t total = prefix_len + write_count;
if (total != 0 || read_count == 0) {
if (write_count != 0 || read_count == 0) {
if (!this->write_byte_(address << 1)) {
err = ERROR_NOT_ACKNOWLEDGED;
}
for (size_t i = 0; err == ERROR_OK && i < total; i++) {
if (!this->write_byte_(i < prefix_len ? prefix[i] : write_buffer[i - prefix_len])) {
for (size_t i = 0; err == ERROR_OK && i < write_count; i++) {
if (!this->write_byte_(write_buffer[i])) {
ESP_LOGVV(TAG, "TX of byte %u to 0x%02X not acknowledged", (unsigned) i, address);
err = ERROR_NOT_ACKNOWLEDGED;
}
}
}
if (err == ERROR_OK && read_count != 0) {
if (total != 0) {
if (write_count != 0) {
this->start_(); // repeated start
}
if (!this->write_byte_((address << 1) | 1)) {
+1 -10
View File
@@ -16,13 +16,7 @@ class SoftwareI2CBus final : public I2CBus, public Component {
void setup() override;
void dump_config() override;
ErrorCode write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
size_t read_count) override {
return this->transfer_(address, nullptr, 0, write_buffer, write_count, read_buffer, read_count);
}
ErrorCode write_prefixed(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *data,
size_t len) override {
return this->transfer_(address, prefix, prefix_len, data, len, nullptr, 0);
}
size_t read_count) override;
float get_setup_priority() const override { return setup_priority::BUS; }
void set_scan(bool scan) { this->scan_ = scan; }
@@ -37,9 +31,6 @@ class SoftwareI2CBus final : public I2CBus, public Component {
void set_timeout(uint32_t timeout) { this->timeout_ = timeout; }
protected:
/// Writes `prefix` then `write_buffer` in one transaction, then reads
ErrorCode transfer_(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *write_buffer,
size_t write_count, uint8_t *read_buffer, size_t read_count);
bool recover_();
void update_half_period_();
void start_();
@@ -1,6 +1,5 @@
#include "inkbird_ibsth1_mini.h"
#include "esphome/core/log.h"
#include "esphome/core/helpers.h"
namespace esphome::inkbird_ibsth1_mini {
@@ -83,7 +82,7 @@ bool InkbirdIbstH1Mini::parse_device(const ble_device_base::ESPBTDevice &device)
}
auto battery_level = mnf_data.data[5];
auto humidity = encode_value_le<uint16_t>(mnf_data.data.data()) / 100.0f;
auto humidity = ((mnf_data.data[1] << 8) + mnf_data.data[0]) / 100.0f;
// Send temperature only if the value is set
if (!std::isnan(temperature) && this->temperature_sensor_ != nullptr) {
+1 -2
View File
@@ -1,5 +1,4 @@
#include "modbus_helpers.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include <algorithm>
@@ -472,7 +471,7 @@ PduBuffer create_client_pdu(FunctionCode function_code, uint16_t start_address,
values[1]);
return pdu;
}
append_pdu_header(pdu, function_code, start_address, encode_uint16(values[0], values[1]));
append_pdu_header(pdu, function_code, start_address, uint16_t((values[0] << 8) | values[1]));
return pdu;
}
// The quantity is spec-bounded above, so the data length just has to agree with it exactly
-303
View File
@@ -1,303 +0,0 @@
from collections.abc import Callable
from esphome import automation
import esphome.codegen as cg
from esphome.components import i2c
from esphome.components.const import CONF_CHARGE_CURRENT, CONF_ENABLED
import esphome.config_validation as cv
from esphome.const import CONF_DURATION, CONF_ID, CONF_MODE, CONF_VOLTAGE
from esphome.types import ConfigType
CODEOWNERS = ["@tomaszduda23"]
DEPENDENCIES = ["i2c"]
DOMAIN = "npm1300"
MULTI_CONF = True
CONF_NPM1300_ID = "npm1300_id"
CONF_VBUS_CURRENT_LIMIT = "vbus_current_limit"
CONF_THERMISTOR_RESISTANCE = "thermistor_resistance"
CONF_THERMISTOR_BETA = "thermistor_beta"
CONF_CHARGER = "charger"
CONF_TERMINATION_VOLTAGE = "termination_voltage"
CONF_WARM_TERMINATION_VOLTAGE = "warm_termination_voltage"
CONF_TERMINATION_CURRENT = "termination_current"
CONF_TRICKLE_VOLTAGE = "trickle_voltage"
CONF_DISCHARGE_CURRENT_LIMIT = "discharge_current_limit"
CONF_RECHARGE = "recharge"
CONF_BUCK1 = "buck1"
CONF_BUCK2 = "buck2"
CONF_LDO1 = "ldo1"
CONF_LDO2 = "ldo2"
npm1300_ns = cg.esphome_ns.namespace("npm1300")
NPM1300Component = npm1300_ns.class_(
"NPM1300Component", cg.PollingComponent, i2c.I2CDevice
)
NPM1300Output = npm1300_ns.enum("NPM1300Output", is_class=True)
NPM1300OutputConfig = npm1300_ns.struct("NPM1300OutputConfig")
NPM1300ChargerConfig = npm1300_ns.struct("NPM1300ChargerConfig")
NPM1300Config = npm1300_ns.struct("NPM1300Config")
NPM1300_CHILD_SCHEMA = cv.Schema(
{cv.GenerateID(CONF_NPM1300_ID): cv.use_id(NPM1300Component)}
)
# Status registers read on each update: VBUSINSTATUS, BCHGCHARGESTATUS and BCHGERRREASON
STATUS_PUBLISHER = cg.HubFunction(
"status",
cg.void,
[
(cg.uint8, "vbus_status"),
(cg.uint8, "charge_status"),
(cg.uint8, "error_reason"),
],
define="USE_NPM1300_STATUS_PUBLISHER",
)
VBUS_STATUS = STATUS_PUBLISHER.param("vbus_status")
CHARGE_STATUS = STATUS_PUBLISHER.param("charge_status")
ERROR_REASON = STATUS_PUBLISHER.param("error_reason")
# The ADC results and the amperes per code of the battery current
DATA_PUBLISHER = cg.HubFunction(
"data",
cg.void,
[(cg.uint8.operator("const").operator("ptr"), "adc"), (cg.float_, "ibat_scale")],
define="USE_NPM1300_DATA_PUBLISHER",
)
ADC = DATA_PUBLISHER.param("adc")
IBAT_SCALE = DATA_PUBLISHER.param("ibat_scale")
# The dump lines of the children decoded by the two functions above
DUMP = cg.HubFunction("dump", cg.void, [(cg.const_char_ptr, "tag")])
DUMP_TAG = DUMP.param("tag")
# Config key of each regulator and its NPM1300Output enumerator
OUTPUTS = NPM1300Output.options(
CONF_BUCK1, CONF_BUCK2, CONF_LDO1, CONF_LDO2, prefix="NPM1300_OUTPUT_"
)
# Written for a field the YAML leaves out
NPM1300_UNSET = 0xFF
# ADCNTCRSEL codes, by kiloohms
THERMISTOR_RESISTANCES = {10: 1, 47: 2, 100: 3}
LDO_MODES = {"load_switch": 0, "ldo": 1}
TERMINATION_CURRENTS = {"10%": 0, "20%": 1}
# BCHGVTRICKLESEL, by millivolts
TRICKLE_VOLTAGES = {2900: 0, 2500: 1}
# BCHGISETDISCHARGE codes, by milliamperes
DISCHARGE_CURRENT_LIMITS = {200: 84, 1000: 415}
# BCHGVTERM: 3.50 V to 3.65 V, then 4.00 V to 4.45 V, both in 50 mV steps
TERMINATION_VOLTAGES = [3500 + 50 * i for i in range(4)] + [
4000 + 50 * i for i in range(10)
]
# The wake-up timer counts 16 ms ticks in a 24-bit register
HIBERNATE_TICK_MS = 16
HIBERNATE_MAX_TICKS = 0xFFFFFF
def _millis(value: float) -> int:
return round(value * 1000)
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`."""
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)
raise cv.Invalid(f"Must be one of {options}")
return value
return validate
def _stepped(
validator: Callable[[object], float],
minimum: int,
maximum: int,
step: int,
unit: str,
) -> Callable[[object], float]:
"""Validate a quantity in a range of milli-units, in steps of `step`."""
allowed = list(range(minimum, maximum + 1, step))
in_range = cv.All(validator, cv.Range(min=minimum / 1000, max=maximum / 1000))
def validate(value: object) -> float:
value = in_range(value)
if _millis(value) not in allowed:
raise cv.Invalid(f"Must be a multiple of {step}m{unit}")
return value
return validate
OUTPUT_VOLTAGE = _stepped(cv.voltage, 1000, 3300, 100, "V")
VBUS_CURRENT_LIMIT = _stepped(cv.current, 100, 1500, 100, "A")
BUCK_SCHEMA = cv.Schema(
{
cv.Optional(CONF_VOLTAGE): OUTPUT_VOLTAGE,
cv.Optional(CONF_ENABLED): cv.boolean,
}
)
LDO_SCHEMA = BUCK_SCHEMA.extend(
{
cv.Optional(CONF_MODE): cv.enum(LDO_MODES, lower=True),
}
)
CHARGER_SCHEMA = cv.Schema(
{
cv.Required(CONF_CHARGE_CURRENT): _stepped(cv.current, 32, 800, 2, "A"),
cv.Optional(CONF_TERMINATION_VOLTAGE, default="4.2V"): _one_of_units(
cv.voltage, TERMINATION_VOLTAGES, "V"
),
cv.Optional(CONF_WARM_TERMINATION_VOLTAGE): _one_of_units(
cv.voltage, TERMINATION_VOLTAGES, "V"
),
cv.Optional(CONF_TERMINATION_CURRENT, default="10%"): cv.enum(
TERMINATION_CURRENTS
),
cv.Optional(CONF_TRICKLE_VOLTAGE, default="2.9V"): _one_of_units(
cv.voltage, list(TRICKLE_VOLTAGES), "V"
),
cv.Optional(CONF_DISCHARGE_CURRENT_LIMIT, default="1000mA"): _one_of_units(
cv.current, list(DISCHARGE_CURRENT_LIMITS), "A"
),
cv.Optional(CONF_RECHARGE, default=True): cv.boolean,
cv.Optional(CONF_ENABLED, default=True): cv.boolean,
}
)
CONFIG_SCHEMA = (
cv.Schema(
{
cv.GenerateID(): cv.declare_id(NPM1300Component),
cv.Optional(CONF_VBUS_CURRENT_LIMIT): VBUS_CURRENT_LIMIT,
cv.Optional(CONF_THERMISTOR_RESISTANCE): _one_of_units(
cv.resistance, list(THERMISTOR_RESISTANCES), "kOhm", scale=0.001
),
cv.Optional(CONF_THERMISTOR_BETA, default=3380): cv.int_range(
min=1, max=65535
),
cv.Optional(CONF_CHARGER): CHARGER_SCHEMA,
cv.Optional(CONF_BUCK1): BUCK_SCHEMA,
cv.Optional(CONF_BUCK2): BUCK_SCHEMA,
cv.Optional(CONF_LDO1): LDO_SCHEMA,
cv.Optional(CONF_LDO2): LDO_SCHEMA,
}
)
.extend(cv.polling_component_schema("60s"))
.extend(i2c.i2c_device_schema(0x6B))
)
def _termination_voltage_code(volts: float) -> int:
return TERMINATION_VOLTAGES.index(_millis(volts))
def _vbus_current_limit_code(amps: float) -> int:
"""VBUSINILIM0: 100 mA per step of the code."""
return _millis(amps) // 100
def _charger_config(config: ConfigType) -> cg.StructInitializer:
termination = _termination_voltage_code(config[CONF_TERMINATION_VOLTAGE])
warm = config.get(CONF_WARM_TERMINATION_VOLTAGE)
return cg.StructInitializer(
NPM1300ChargerConfig,
("current", _millis(config[CONF_CHARGE_CURRENT]) // 2),
(
"discharge_limit",
DISCHARGE_CURRENT_LIMITS[_millis(config[CONF_DISCHARGE_CURRENT_LIMIT])],
),
("termination_voltage", termination),
(
"warm_termination_voltage",
termination if warm is None else _termination_voltage_code(warm),
),
("trickle_voltage", TRICKLE_VOLTAGES[_millis(config[CONF_TRICKLE_VOLTAGE])]),
("termination_current", TERMINATION_CURRENTS[config[CONF_TERMINATION_CURRENT]]),
("recharge", config[CONF_RECHARGE]),
("enabled", config[CONF_ENABLED]),
)
def _output_config(config: ConfigType | None) -> cg.StructInitializer:
config = config or {}
voltage = config.get(CONF_VOLTAGE)
mode = config.get(CONF_MODE)
enabled = config.get(CONF_ENABLED)
return cg.StructInitializer(
NPM1300OutputConfig,
(
"voltage",
NPM1300_UNSET if voltage is None else (_millis(voltage) - 1000) // 100,
),
("ldo_mode", NPM1300_UNSET if mode is None else LDO_MODES[mode]),
("enabled", NPM1300_UNSET if enabled is None else int(enabled)),
)
def _config(config: ConfigType) -> cg.StructInitializer:
charger = config.get(CONF_CHARGER)
resistance = config.get(CONF_THERMISTOR_RESISTANCE)
return cg.StructInitializer(
NPM1300Config,
(
"outputs",
cg.ArrayInitializer(*(_output_config(config.get(key)) for key in OUTPUTS)),
),
("charger", None if charger is None else _charger_config(charger)),
("thermistor_beta", config[CONF_THERMISTOR_BETA]),
(
"thermistor",
NPM1300_UNSET
if resistance is None
else THERMISTOR_RESISTANCES[round(resistance / 1000)],
),
("charger_configured", charger is not None),
)
async def to_code(config: ConfigType) -> None:
# In flash: only setup() and dump_config() read it
table = cg.shared_progmem_array(
"npm1300_config", NPM1300Config, cg.ArrayInitializer(_config(config))
)
var = await i2c.new_i2c_component(config, table)
if (limit := config.get(CONF_VBUS_CURRENT_LIMIT)) is not None:
cg.add(var.set_vbus_current_limit(_vbus_current_limit_code(limit)))
automation.register_apply_action(
"npm1300.enter_ship_mode",
automation.maybe_simple_id({cv.Required(CONF_ID): cv.use_id(NPM1300Component)}),
automation.ApplyCall("enter_ship_mode()"),
)
automation.register_apply_action(
"npm1300.hibernate",
cv.Schema(
{
cv.Required(CONF_ID): cv.use_id(NPM1300Component),
cv.Required(CONF_DURATION): cv.templatable(
cv.All(
cv.positive_time_period_milliseconds,
cv.Range(
min=cv.TimePeriod(milliseconds=HIBERNATE_TICK_MS),
max=cv.TimePeriod(
milliseconds=HIBERNATE_TICK_MS * HIBERNATE_MAX_TICKS
),
),
)
),
}
),
automation.ApplyField(CONF_DURATION, "hibernate", cg.uint32),
)
-106
View File
@@ -1,106 +0,0 @@
from dataclasses import dataclass
from esphome.automation import parent_ref
import esphome.codegen as cg
from esphome.components import binary_sensor
import esphome.config_validation as cv
from esphome.const import (
DEVICE_CLASS_BATTERY_CHARGING,
DEVICE_CLASS_POWER,
DEVICE_CLASS_PROBLEM,
ENTITY_CATEGORY_DIAGNOSTIC,
)
from esphome.cpp_generator import HexIntLiteral
from esphome.types import ConfigType
from . import (
CHARGE_STATUS,
CONF_NPM1300_ID,
DUMP,
DUMP_TAG,
ERROR_REASON,
NPM1300_CHILD_SCHEMA,
STATUS_PUBLISHER,
VBUS_STATUS,
)
DEPENDENCIES = ["npm1300"]
@dataclass(frozen=True, kw_only=True)
class _StatusBits:
"""On when any bit of mask is set in the status register."""
key: str
register: cg.MockObj
mask: int
name: str
device_class: str = cv.UNDEFINED
entity_category: str = cv.UNDEFINED
_FIELDS = (
_StatusBits(
key="vbus_present",
register=VBUS_STATUS,
mask=0x01,
name="VBUS Present",
device_class=DEVICE_CLASS_POWER,
),
_StatusBits(
key="vbus_current_limit_active",
register=VBUS_STATUS,
mask=0x02,
name="VBUS Current Limit Active",
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
# Trickle, constant current or constant voltage charging
_StatusBits(
key="charging",
register=CHARGE_STATUS,
mask=0x1C,
name="Charging",
device_class=DEVICE_CLASS_BATTERY_CHARGING,
),
_StatusBits(
key="charge_complete",
register=CHARGE_STATUS,
mask=0x02,
name="Charge Complete",
),
_StatusBits(
key="charger_error",
register=ERROR_REASON,
mask=0xFF,
name="Charger Error",
device_class=DEVICE_CLASS_PROBLEM,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
)
CONFIG_SCHEMA = NPM1300_CHILD_SCHEMA.extend(
{
cv.Optional(field.key): binary_sensor.binary_sensor_schema(
device_class=field.device_class, entity_category=field.entity_category
)
for field in _FIELDS
}
)
async def to_code(config: ConfigType) -> None:
hub = await cg.get_variable(config[CONF_NPM1300_ID])
sensors = binary_sensor.sub_binary_sensors(config)
for field in _FIELDS:
if (var := await sensors(field.key, None)) is not None:
state = (field.register & HexIntLiteral(field.mask)) != 0
STATUS_PUBLISHER.add(hub, parent_ref(var).publish_state(state))
DUMP.add(
hub,
binary_sensor.binary_sensor_ns.log_binary_sensor(
DUMP_TAG,
" ",
cg.RawExpression(f'LOG_STR_LITERAL("{field.name}")'),
parent_ref(var),
),
)
-483
View File
@@ -1,483 +0,0 @@
#include "npm1300.h"
#include <algorithm>
#include <cinttypes>
#include <cmath>
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
#ifdef USE_TEXT_SENSOR
#include "esphome/core/progmem.h"
#endif
namespace esphome::npm1300 {
ESPHOME_LOG_TAG(TAG, "npm1300");
// Registers: the base address of the peripheral in the high byte, the offset in the low byte
static constexpr uint16_t REG_VBUSIN_TASK_UPDATE_ILIM = 0x0200;
static constexpr uint16_t REG_VBUSIN_ILIM0 = 0x0201;
static constexpr uint16_t REG_VBUSIN_ILIM_STARTUP = 0x0202;
static constexpr uint16_t REG_VBUSIN_STATUS = 0x0207;
static constexpr uint16_t REG_BCHG_TASK_RELEASE_ERR = 0x0300;
static constexpr uint16_t REG_BCHG_TASK_CLEAR_CHG_ERR = 0x0301;
static constexpr uint16_t REG_BCHG_ENABLE_SET = 0x0304;
static constexpr uint16_t REG_BCHG_ENABLE_CLR = 0x0305;
static constexpr uint16_t REG_BCHG_DISABLE_SET = 0x0306;
static constexpr uint16_t REG_BCHG_DISABLE_CLR = 0x0307;
static constexpr uint16_t REG_BCHG_ISET_MSB = 0x0308;
static constexpr uint16_t REG_BCHG_ISET_DISCHARGE_MSB = 0x030A;
static constexpr uint16_t REG_BCHG_VTERM = 0x030C;
static constexpr uint16_t REG_BCHG_VTERM_R = 0x030D;
static constexpr uint16_t REG_BCHG_VTRICKLE_SEL = 0x030E;
static constexpr uint16_t REG_BCHG_ITERM_SEL = 0x030F;
static constexpr uint16_t REG_BCHG_CHARGE_STATUS = 0x0334;
static constexpr uint16_t REG_BCHG_ERR_REASON = 0x0336;
static constexpr uint16_t REG_BUCK1_ENA_SET = 0x0400;
static constexpr uint16_t REG_BUCK1_NORM_VOUT = 0x0408;
static constexpr uint16_t REG_BUCK_SW_CTRL_SEL = 0x040F;
static constexpr uint16_t REG_BUCK_STATUS = 0x0434;
static constexpr uint16_t REG_ADC_TASK_VBAT = 0x0500;
static constexpr uint16_t REG_ADC_TASK_VBUS = 0x0507;
static constexpr uint16_t REG_ADC_NTC_R_SEL = 0x050A;
static constexpr uint16_t REG_ADC_TASK_AUTO_TIM_UPDATE = 0x050C;
static constexpr uint16_t REG_ADC_RESULTS = 0x0510;
static constexpr uint16_t REG_ADC_IBAT_MEAS_EN = 0x0524;
static constexpr uint16_t REG_TIMER_TARGET_STROBE = 0x0703;
static constexpr uint16_t REG_TIMER_CONFIG = 0x0705;
static constexpr uint16_t REG_TIMER_HI_BYTE = 0x0708;
static constexpr uint16_t REG_LDSW1_TASK_SET = 0x0800;
static constexpr uint16_t REG_LDSW_STATUS = 0x0804;
static constexpr uint16_t REG_LDSW1_LDO_SEL = 0x0808;
static constexpr uint16_t REG_LDSW1_VOUT_SEL = 0x080C;
static constexpr uint16_t REG_SHIP_TASK_HIBERNATE = 0x0B00;
static constexpr uint16_t REG_SHIP_TASK_SHIP_MODE = 0x0B02;
// VBUSINSTATUS
static constexpr uint8_t VBUS_PRESENT = 0x01;
// BCHGCHARGESTATUS; bit 0 (battery detected) is reserved since C00 silicon
static constexpr uint8_t CHARGE_STATUS_COMPLETED = 0x02;
static constexpr uint8_t CHARGE_STATUS_TRICKLE = 0x04;
static constexpr uint8_t CHARGE_STATUS_CONSTANT_CURRENT = 0x08;
static constexpr uint8_t CHARGE_STATUS_CONSTANT_VOLTAGE = 0x10;
static constexpr uint8_t CHARGE_STATUS_DIE_TEMP_HIGH = 0x40;
// BCHGDISABLESET and BCHGDISABLECLR
static constexpr uint8_t CHARGER_DISABLE_RECHARGE = 0x01;
static constexpr uint8_t CHARGER_DISABLE_NTC = 0x02;
// BUCKSTATUS power good, LDSWSTATUS powered up as load switch or as LDO
static constexpr uint8_t BUCK_POWER_GOOD[2] = {0x04, 0x40};
static constexpr uint8_t LDSW_POWERED[2] = {0x03, 0x0C};
// TIMERCONFIG: wake-up timer with the 16 ms prescaler
static constexpr uint8_t TIMER_CONFIG_WAKEUP = 0x04;
static constexpr uint32_t TIMER_TICK_MS = 16;
static constexpr uint32_t TIMER_MAX_TICKS = 0xFFFFFF;
// BCHGISETDISCHARGE codes up to this one select the 200 mA discharge limit, the others 1000 mA
static constexpr uint16_t DISCHARGE_LIMIT_200MA_CODE = 84;
static uint16_t discharge_limit_ma(uint16_t code) { return code <= DISCHARGE_LIMIT_200MA_CODE ? 200 : 1000; }
// BCHGISET and BCHGISETDISCHARGE hold a 9-bit code: the high 8 bits, then bit 0 in the next register
static void split_9bit(uint16_t code, uint8_t *out) {
out[0] = code >> 1;
out[1] = code & 1;
}
#ifdef USE_NPM1300_DATA_PUBLISHER
static uint16_t join_9bit(const uint8_t *in) { return (in[0] << 1) | (in[1] & 1); }
// ADCIBATMEASSTATUS
static constexpr uint8_t IBAT_MEAS_INVALID = 0x10;
static constexpr uint8_t IBAT_MODE_SHIFT = 2;
static constexpr uint8_t IBAT_MODE_DISCHARGE = 0x01;
static constexpr uint8_t IBAT_MODE_CHARGE = 0x03;
// Full scale of the battery current measurement per milliampere of the charge and discharge limits
static constexpr float CHARGE_FULL_SCALE_FACTOR = 1.25f;
static constexpr float DISCHARGE_FULL_SCALE_FACTOR = 1.12f;
static constexpr float ADC_MAX_CODE = 1023.0f;
// Five conversions of 250 us each; the loop runs the timeout later than this anyway
static constexpr uint32_t CONVERSION_TIME_MS = 2;
static constexpr uint32_t READ_TIMEOUT_ID = 0;
float ntc_temperature(uint16_t code, float inv_beta) {
if (code == 0)
return NAN;
// The NTC divider gives code = 1024 * R / (R + R_nominal)
return 1.0f / (1.0f / 298.15f - logf(1024.0f / code - 1.0f) * inv_beta) - 273.15f;
}
#endif
#ifdef USE_TEXT_SENSOR
PROGMEM_STRING_TABLE(ChargerStatusStrings, "Error", "Paused, Die Too Hot", "Charge Complete", "Trickle Charge",
"Constant Current", "Constant Voltage", "Discharging", "Not Charging");
// BCHGCHARGESTATUS bits in order of priority; bit i is reported as string i + 1
static const uint8_t CHARGER_STATUS_BITS[] PROGMEM = {CHARGE_STATUS_DIE_TEMP_HIGH, CHARGE_STATUS_COMPLETED,
CHARGE_STATUS_TRICKLE, CHARGE_STATUS_CONSTANT_CURRENT,
CHARGE_STATUS_CONSTANT_VOLTAGE};
static uint8_t charger_status_index(uint8_t vbus_status, uint8_t charge_status, uint8_t error_reason) {
if (error_reason != 0)
return 0;
for (size_t i = 0; i < sizeof(CHARGER_STATUS_BITS); i++) {
if ((charge_status & progmem_read_byte(&CHARGER_STATUS_BITS[i])) != 0)
return i + 1;
}
return (vbus_status & VBUS_PRESENT) == 0 ? 6 : 7;
}
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, uint8_t vbus_status, uint8_t charge_status,
uint8_t error_reason) {
const uint8_t index = charger_status_index(vbus_status, charge_status, error_reason);
if (index == last)
return;
last = index;
sensor->publish_state(ChargerStatusStrings::get_progmem_str(index, ChargerStatusStrings::LAST_INDEX));
}
#endif
NPM1300Config NPM1300Component::load_config_() const {
NPM1300Config config;
progmem_memcpy(&config, this->config_, sizeof(config));
return config;
}
void NPM1300Component::setup() {
uint8_t status;
if (!this->setup_check(this->read_byte_reg16(REG_BCHG_CHARGE_STATUS, &status)))
return;
// Raise the VBUS current limit before anything turns on a regulator: at the power-on limit of 100 mA the
// inrush current of a regulator can trip the over-current protection and brown out the board
if (this->vbus_current_limit_ != NPM1300_UNSET &&
!this->setup_check(this->write_byte_reg16(REG_VBUSIN_ILIM_STARTUP, this->vbus_current_limit_) &&
this->apply_vbus_current_limit_()))
return;
const NPM1300Config config = this->load_config_();
if (config.thermistor != NPM1300_UNSET &&
!this->setup_check(this->write_byte_reg16(REG_ADC_NTC_R_SEL, config.thermistor)))
return;
if (config.charger_configured && !this->setup_check(this->configure_charger_(config)))
return;
for (uint8_t i = 0; i < NPM1300_OUTPUT_COUNT; i++) {
if (!this->setup_check(this->configure_output_(i, config.outputs[i])))
return;
}
#ifdef USE_NPM1300_DATA_PUBLISHER
if (this->data_publisher_ != nullptr) {
// The battery current is measured after every battery voltage measurement
if (!this->setup_check(this->write_byte_reg16(REG_ADC_IBAT_MEAS_EN, 1)))
return;
if (config.charger_configured) {
this->charge_code_ = config.charger.current;
this->discharge_limit_high_ = discharge_limit_ma(config.charger.discharge_limit) == 1000;
} else if (!this->setup_check(this->read_charge_currents_())) {
return;
}
}
#endif
this->update();
}
bool NPM1300Component::apply_vbus_current_limit_() {
return this->write_byte_reg16(REG_VBUSIN_ILIM0, this->vbus_current_limit_) &&
this->write_byte_reg16(REG_VBUSIN_TASK_UPDATE_ILIM, 1);
}
bool NPM1300Component::configure_charger_(const NPM1300Config &config) {
const NPM1300ChargerConfig &charger = config.charger;
// The charge settings are only taken while the charger is off
if (!this->write_byte_reg16(REG_BCHG_ENABLE_CLR, 1))
return false;
uint8_t current[2];
uint8_t discharge[2];
split_9bit(charger.current, current);
split_9bit(charger.discharge_limit, discharge);
uint8_t disable = charger.recharge ? 0 : CHARGER_DISABLE_RECHARGE;
// Without a thermistor the charger reports an NTC error and does not charge
if (config.thermistor == NPM1300_UNSET)
disable |= CHARGER_DISABLE_NTC;
const uint8_t enable = (CHARGER_DISABLE_RECHARGE | CHARGER_DISABLE_NTC) & ~disable;
if (this->write_register16(REG_BCHG_ISET_MSB, current, sizeof(current)) != i2c::ERROR_OK ||
this->write_register16(REG_BCHG_ISET_DISCHARGE_MSB, discharge, sizeof(discharge)) != i2c::ERROR_OK ||
!this->write_byte_reg16(REG_BCHG_VTERM, charger.termination_voltage) ||
!this->write_byte_reg16(REG_BCHG_VTERM_R, charger.warm_termination_voltage) ||
!this->write_byte_reg16(REG_BCHG_VTRICKLE_SEL, charger.trickle_voltage) ||
!this->write_byte_reg16(REG_BCHG_ITERM_SEL, charger.termination_current) ||
!this->write_byte_reg16(REG_BCHG_DISABLE_SET, disable) || !this->write_byte_reg16(REG_BCHG_DISABLE_CLR, enable) ||
// Measure the battery temperature automatically while charging
!this->write_byte_reg16(REG_ADC_TASK_AUTO_TIM_UPDATE, 1))
return false;
return !charger.enabled || this->set_charger_enabled(true);
}
bool NPM1300Component::configure_output_(uint8_t index, const NPM1300OutputConfig &config) {
const uint8_t channel = index & 1;
if (index < 2) {
// The software voltage replaces the one set by the VSET pin only once its SWCTRLSEL bit is set
if (config.voltage != NPM1300_UNSET &&
(!this->write_byte_reg16(REG_BUCK1_NORM_VOUT + channel * 2, config.voltage) ||
!this->update_register16(REG_BUCK_SW_CTRL_SEL, 1 << channel, 1 << channel)))
return false;
} else if ((config.voltage != NPM1300_UNSET &&
!this->write_byte_reg16(REG_LDSW1_VOUT_SEL + channel, config.voltage)) ||
(config.ldo_mode != NPM1300_UNSET &&
!this->write_byte_reg16(REG_LDSW1_LDO_SEL + channel, config.ldo_mode))) {
return false;
}
return config.enabled == NPM1300_UNSET ||
this->set_output_enabled(static_cast<NPM1300Output>(index), config.enabled != 0);
}
#ifdef USE_NPM1300_DATA_PUBLISHER
bool NPM1300Component::read_charge_currents_() {
uint8_t charge[2];
uint8_t discharge[2];
if (this->read_register16(REG_BCHG_ISET_MSB, charge, sizeof(charge)) != i2c::ERROR_OK ||
this->read_register16(REG_BCHG_ISET_DISCHARGE_MSB, discharge, sizeof(discharge)) != i2c::ERROR_OK)
return false;
this->charge_code_ = join_9bit(charge);
this->discharge_limit_high_ = discharge_limit_ma(join_9bit(discharge)) == 1000;
return true;
}
#endif
bool NPM1300Component::set_charger_enabled(bool enabled) {
if (this->is_failed())
return false;
if (!enabled)
return this->write_byte_reg16(REG_BCHG_ENABLE_CLR, 1);
// A charger error stops the charger until the error is cleared and the charger released
return this->write_byte_reg16(REG_BCHG_TASK_CLEAR_CHG_ERR, 1) &&
this->write_byte_reg16(REG_BCHG_TASK_RELEASE_ERR, 1) && this->write_byte_reg16(REG_BCHG_ENABLE_SET, 1);
}
bool NPM1300Component::set_output_enabled(NPM1300Output output, bool enabled) {
if (this->is_failed())
return false;
const uint8_t index = static_cast<uint8_t>(output);
// A pair of SET and CLR task registers per output
const uint16_t base = index < 2 ? REG_BUCK1_ENA_SET : REG_LDSW1_TASK_SET;
const uint16_t reg = base + (index & 1) * 2 + (enabled ? 0 : 1);
if (!this->write_byte_reg16(reg, 1)) {
ESP_LOGW(TAG, "Turning output %u %s failed", index, enabled ? LOG_STR_LITERAL("on") : LOG_STR_LITERAL("off"));
return false;
}
return true;
}
void NPM1300Component::enter_ship_mode() {
ESP_LOGI(TAG, "Entering ship mode");
this->write_byte_reg16(REG_SHIP_TASK_SHIP_MODE, 1);
}
void NPM1300Component::hibernate(uint32_t duration_ms) {
// A zero period would never wake the chip
const uint32_t ticks = std::clamp<uint32_t>(duration_ms / TIMER_TICK_MS, 1, TIMER_MAX_TICKS);
uint8_t timer[3];
put_be24(timer, ticks);
ESP_LOGI(TAG, "Hibernating for %" PRIu32 " ms", ticks * TIMER_TICK_MS);
if (!this->write_byte_reg16(REG_TIMER_CONFIG, TIMER_CONFIG_WAKEUP) ||
this->write_register16(REG_TIMER_HI_BYTE, timer, sizeof(timer)) != i2c::ERROR_OK ||
!this->write_byte_reg16(REG_TIMER_TARGET_STROBE, 1)) {
ESP_LOGW(TAG, "Setting the wake-up timer failed");
return;
}
// The timer needs a moment to load the new period
delay(1);
this->write_byte_reg16(REG_SHIP_TASK_HIBERNATE, 1);
}
void NPM1300Component::update() {
uint8_t vbus_status;
uint8_t charge_status;
uint8_t error_reason;
if (!this->status_comm_check(this->read_byte_reg16(REG_VBUSIN_STATUS, &vbus_status) &&
this->read_byte_reg16(REG_BCHG_CHARGE_STATUS, &charge_status) &&
this->read_byte_reg16(REG_BCHG_ERR_REASON, &error_reason)))
return;
// The chip goes back to its default VBUS current limit whenever VBUS is removed
const bool vbus_present = (vbus_status & VBUS_PRESENT) != 0;
if (vbus_present && !this->vbus_present_ && this->vbus_current_limit_ != NPM1300_UNSET &&
!this->status_comm_check(this->apply_vbus_current_limit_()))
return;
this->vbus_present_ = vbus_present;
if (error_reason != this->last_error_reason_) {
this->last_error_reason_ = error_reason;
if (error_reason != 0) {
ESP_LOGW(TAG, "Charger error, BCHGERRREASON 0x%02X", error_reason);
}
}
#ifdef USE_NPM1300_STATUS_PUBLISHER
if (this->status_publisher_ != nullptr)
this->status_publisher_(vbus_status, charge_status, error_reason);
#endif
#ifdef USE_SWITCH
if (!this->status_comm_check(this->publish_switches_()))
return;
#endif
#ifdef USE_SENSOR
if (this->vbus_current_limit_sensor_ != nullptr) {
uint8_t code;
if (!this->status_comm_check(this->read_byte_reg16(REG_VBUSIN_ILIM0, &code)))
return;
// 100 mA per step of the code, but code 0 is 500 mA
const uint16_t milliamps = code == 0 ? 500 : code * 100;
this->vbus_current_limit_sensor_->publish_state(milliamps / 1000.0f);
}
#endif
#ifdef USE_NPM1300_DATA_PUBLISHER
if (this->data_publisher_ != nullptr) {
// Start the battery voltage (followed by the battery current), NTC, die temperature and system voltage
// conversions, then the VBUS one
static constexpr uint8_t START[4] = {1, 1, 1, 1};
if (!this->status_comm_check(this->write_register16(REG_ADC_TASK_VBAT, START, sizeof(START)) == i2c::ERROR_OK &&
this->write_byte_reg16(REG_ADC_TASK_VBUS, 1)))
return;
this->set_timeout(READ_TIMEOUT_ID, CONVERSION_TIME_MS, [this]() { this->read_measurements_(); });
return;
}
#endif
this->status_comm_result(true);
}
#ifdef USE_SWITCH
bool NPM1300Component::publish_switches_() {
uint8_t value;
bool ok = true;
if (this->charger_switch_ != nullptr) {
if (this->read_byte_reg16(REG_BCHG_ENABLE_SET, &value)) {
this->charger_switch_->publish_state((value & 1) != 0);
} else {
ok = false;
}
}
switch_::Switch *const bucks[2] = {this->buck1_switch_, this->buck2_switch_};
if (bucks[0] != nullptr || bucks[1] != nullptr) {
if (this->read_byte_reg16(REG_BUCK_STATUS, &value)) {
for (uint8_t i = 0; i < 2; i++)
PUBLISH_STATE(bucks[i], (value & BUCK_POWER_GOOD[i]) != 0);
} else {
ok = false;
}
}
switch_::Switch *const ldos[2] = {this->ldo1_switch_, this->ldo2_switch_};
if (ldos[0] != nullptr || ldos[1] != nullptr) {
if (this->read_byte_reg16(REG_LDSW_STATUS, &value)) {
for (uint8_t i = 0; i < 2; i++)
PUBLISH_STATE(ldos[i], (value & LDSW_POWERED[i]) != 0);
} else {
ok = false;
}
}
return ok;
}
#endif
#ifdef USE_NPM1300_DATA_PUBLISHER
void NPM1300Component::read_measurements_() {
// ADCIBATMEASSTATUS, then the VBAT, NTC, TEMP and VSYS results, their low bits, VBAT0 to VBAT3 (VBAT2 holds the
// battery current and VBAT3 the VBUS voltage) and their low bits
uint8_t adc[11];
if (!this->status_comm_result(this->read_register16(REG_ADC_RESULTS, adc, sizeof(adc)) == i2c::ERROR_OK))
return;
// Amperes per code of the battery current, positive while charging and negative while discharging
float ibat_scale = NAN;
// Any other mode means the system runs from VBUS and the battery current is not measured
const uint8_t mode = (adc[0] >> IBAT_MODE_SHIFT) & 0x03;
if ((adc[0] & IBAT_MEAS_INVALID) == 0) {
if (mode == IBAT_MODE_CHARGE) {
ibat_scale = this->charge_code_ * (2 * CHARGE_FULL_SCALE_FACTOR) / (ADC_MAX_CODE * 1000.0f);
} else if (mode == IBAT_MODE_DISCHARGE) {
ibat_scale = -(this->discharge_limit_high_ ? 1000 : 200) * DISCHARGE_FULL_SCALE_FACTOR / (ADC_MAX_CODE * 1000.0f);
}
}
if (this->data_publisher_ != nullptr)
this->data_publisher_(adc, ibat_scale);
}
#endif
// BCHGVTERM: 3.50 V to 3.65 V, then 4.00 V to 4.45 V, both in 50 mV steps
static uint16_t termination_voltage_mv(uint8_t code) { return code < 4 ? 3500 + 50 * code : 4000 + 50 * (code - 4); }
static const LogString *output_name(uint8_t index) {
switch (static_cast<NPM1300Output>(index)) {
case NPM1300Output::NPM1300_OUTPUT_BUCK1:
return LOG_STR("BUCK1");
case NPM1300Output::NPM1300_OUTPUT_BUCK2:
return LOG_STR("BUCK2");
case NPM1300Output::NPM1300_OUTPUT_LDO1:
return LOG_STR("LDO1");
default:
return LOG_STR("LDO2");
}
}
void NPM1300Component::dump_config() {
ESP_LOGCONFIG(TAG, "nPM1300:");
LOG_I2C_DEVICE(this);
LOG_UPDATE_INTERVAL(this);
if (this->vbus_current_limit_ != NPM1300_UNSET) {
// 100 mA per step of the code
ESP_LOGCONFIG(TAG, " VBUS current limit: %u mA", this->vbus_current_limit_ * 100u);
}
const NPM1300Config config = this->load_config_();
if (config.charger_configured) {
const NPM1300ChargerConfig &charger = config.charger;
ESP_LOGCONFIG(TAG,
" Charger:\n"
" Current: %u mA\n"
" Discharge limit: %u mA\n"
" Termination voltage: %u mV\n"
" Warm termination voltage: %u mV\n"
" Termination current: %u%%\n"
" Trickle voltage: %u mV\n"
" Enabled: %s\n"
" Recharge: %s",
charger.current * 2u, discharge_limit_ma(charger.discharge_limit),
termination_voltage_mv(charger.termination_voltage),
termination_voltage_mv(charger.warm_termination_voltage), charger.termination_current ? 20u : 10u,
charger.trickle_voltage ? 2500u : 2900u, YESNO(charger.enabled), YESNO(charger.recharge));
}
for (uint8_t i = 0; i < NPM1300_OUTPUT_COUNT; i++) {
const NPM1300OutputConfig &output = config.outputs[i];
if (output.voltage == NPM1300_UNSET && output.ldo_mode == NPM1300_UNSET && output.enabled == NPM1300_UNSET)
continue;
ESP_LOGCONFIG(TAG, " %s:", LOG_STR_ARG(output_name(i)));
if (output.voltage != NPM1300_UNSET) {
ESP_LOGCONFIG(TAG, " Voltage: %u mV", 1000u + output.voltage * 100u);
}
if (output.ldo_mode != NPM1300_UNSET) {
ESP_LOGCONFIG(TAG, " Mode: %s",
output.ldo_mode != 0 ? LOG_STR_LITERAL("LDO") : LOG_STR_LITERAL("load switch"));
}
if (output.enabled != NPM1300_UNSET) {
ESP_LOGCONFIG(TAG, " Enabled at boot: %s", YESNO(output.enabled != 0));
}
}
if (config.thermistor != NPM1300_UNSET) {
ESP_LOGCONFIG(TAG, " Thermistor B constant: %u", config.thermistor_beta);
}
#ifdef USE_SENSOR
LOG_SENSOR(" ", "VBUS Current Limit", this->vbus_current_limit_sensor_);
#endif
#ifdef USE_SWITCH
LOG_SWITCH(" ", "Charger", this->charger_switch_);
LOG_SWITCH(" ", "BUCK1", this->buck1_switch_);
LOG_SWITCH(" ", "BUCK2", this->buck2_switch_);
LOG_SWITCH(" ", "LDO1", this->ldo1_switch_);
LOG_SWITCH(" ", "LDO2", this->ldo2_switch_);
#endif
#if defined(USE_NPM1300_STATUS_PUBLISHER) || defined(USE_NPM1300_DATA_PUBLISHER)
if (this->dump_publisher_ != nullptr)
this->dump_publisher_(TAG);
#endif
}
} // namespace esphome::npm1300
-145
View File
@@ -1,145 +0,0 @@
#pragma once
// Product specification: https://docs.nordicsemi.com/bundle/ps_npm1300/page/keyfeatures_html5.html
#include "esphome/components/i2c/i2c.h"
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#include "esphome/core/helpers.h"
#ifdef USE_SENSOR
#include "esphome/components/sensor/sensor.h"
#endif
#ifdef USE_TEXT_SENSOR
#include "esphome/components/text_sensor/text_sensor.h"
#endif
#ifdef USE_SWITCH
#include "esphome/components/switch/switch.h"
#endif
namespace esphome::npm1300 {
/// The regulators, in the order of their enable task registers
enum class NPM1300Output : uint8_t {
NPM1300_OUTPUT_BUCK1 = 0,
NPM1300_OUTPUT_BUCK2 = 1,
NPM1300_OUTPUT_LDO1 = 2,
NPM1300_OUTPUT_LDO2 = 3,
};
static constexpr uint8_t NPM1300_OUTPUT_COUNT = 4;
/// A configuration field the YAML leaves out, so the chip keeps its own value
static constexpr uint8_t NPM1300_UNSET = 0xFF;
/// Register codes for one regulator, NPM1300_UNSET where the YAML leaves the field out
struct NPM1300OutputConfig {
uint8_t voltage; // VOUT: (millivolts - 1000) / 100
uint8_t ldo_mode; // LDSWxLDOSEL, LDO1 and LDO2 only: 1 LDO, 0 load switch
uint8_t enabled; // turned on (1) or off (0) at boot
};
/// Register codes for the battery charger
struct NPM1300ChargerConfig {
uint16_t current; // BCHGISET: milliamperes / 2
uint16_t discharge_limit; // BCHGISETDISCHARGE: 84 for 200 mA, 415 for 1000 mA
uint8_t termination_voltage; // BCHGVTERM
uint8_t warm_termination_voltage; // BCHGVTERMR
uint8_t trickle_voltage; // BCHGVTRICKLESEL: 0 for 2.9 V, 1 for 2.5 V
uint8_t termination_current; // BCHGITERMSEL: 0 for 10 %, 1 for 20 %
bool recharge;
bool enabled;
};
/// The settings applied in setup(), built by code generation into a PROGMEM table
struct NPM1300Config {
NPM1300OutputConfig outputs[NPM1300_OUTPUT_COUNT];
NPM1300ChargerConfig charger; // only applied when charger_configured
uint16_t thermistor_beta;
uint8_t thermistor; // ADCNTCRSEL code: 1 for 10 kOhm, 2 for 47 kOhm, 3 for 100 kOhm, or NPM1300_UNSET
bool charger_configured;
};
#ifdef USE_NPM1300_DATA_PUBLISHER
/// The 10-bit ADC result whose high 8 bits are adc[msb] and low 2 bits are at `shift` in adc[lsbs]
inline uint16_t adc_code(const uint8_t *adc, uint8_t msb, uint8_t lsbs, uint8_t shift) {
return (adc[msb] << 2) | ((adc[lsbs] >> shift) & 0x03);
}
/// Battery temperature in degrees Celsius from the NTC code and 1 / B constant of the thermistor
float ntc_temperature(uint16_t code, float inv_beta);
#endif
#ifdef USE_TEXT_SENSOR
/// Publish the charger status text, only when it differs from `last`
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, uint8_t vbus_status, uint8_t charge_status,
uint8_t error_reason);
#endif
class NPM1300Component : public PollingComponent, public i2c::I2CDevice {
#ifdef USE_SENSOR
SUB_SENSOR(vbus_current_limit)
#endif
#ifdef USE_SWITCH
SUB_SWITCH(charger)
SUB_SWITCH(buck1)
SUB_SWITCH(buck2)
SUB_SWITCH(ldo1)
SUB_SWITCH(ldo2)
#endif
public:
/// `config` points into PROGMEM
explicit NPM1300Component(const NPM1300Config *config) : config_(config) {}
void setup() override;
void update() override;
void dump_config() override;
// Right after the I2C bus: the regulators may power other peripherals
float get_setup_priority() const override { return setup_priority::BUS - 1.0f; }
#ifdef USE_NPM1300_STATUS_PUBLISHER
HUB_PUBLISHER(status, uint8_t, uint8_t, uint8_t)
#endif
#ifdef USE_NPM1300_DATA_PUBLISHER
HUB_PUBLISHER(data, const uint8_t *, float)
#endif
#if defined(USE_NPM1300_STATUS_PUBLISHER) || defined(USE_NPM1300_DATA_PUBLISHER)
HUB_PUBLISHER(dump, const char *)
#endif
/// VBUSINILIM0 code: 100 mA per step (code 0, the reset value, is 500 mA)
void set_vbus_current_limit(uint8_t code) { this->vbus_current_limit_ = code; }
/// Turn the battery charger on or off; turning it on also clears a charger error
bool set_charger_enabled(bool enabled);
/// Turn a regulator on or off
bool set_output_enabled(NPM1300Output output, bool enabled);
/// Enter ship mode: every output is turned off until the SHPHLD button is pressed or VBUS is connected
void enter_ship_mode();
/// Enter hibernate mode: every output is turned off for `duration_ms`, or until the SHPHLD button is
/// pressed or VBUS is connected
void hibernate(uint32_t duration_ms);
protected:
NPM1300Config load_config_() const;
bool apply_vbus_current_limit_();
bool configure_charger_(const NPM1300Config &config);
bool configure_output_(uint8_t index, const NPM1300OutputConfig &config);
#ifdef USE_NPM1300_DATA_PUBLISHER
bool read_charge_currents_();
void read_measurements_();
#endif
#ifdef USE_SWITCH
/// Returns false when a status read failed
bool publish_switches_();
#endif
const NPM1300Config *config_;
#ifdef USE_NPM1300_DATA_PUBLISHER
// BCHGISET code and discharge limit, for the full scale of the battery current measurement
uint16_t charge_code_{0};
bool discharge_limit_high_{false};
#endif
uint8_t vbus_current_limit_{NPM1300_UNSET};
uint8_t last_error_reason_{0};
bool vbus_present_{false};
};
} // namespace esphome::npm1300
-151
View File
@@ -1,151 +0,0 @@
from esphome.automation import parent_ref
import esphome.codegen as cg
from esphome.components import sensor
import esphome.config_validation as cv
from esphome.const import (
CONF_BATTERY_VOLTAGE,
CONF_ID,
DEVICE_CLASS_CURRENT,
DEVICE_CLASS_TEMPERATURE,
DEVICE_CLASS_VOLTAGE,
ENTITY_CATEGORY_DIAGNOSTIC,
STATE_CLASS_MEASUREMENT,
UNIT_AMPERE,
UNIT_CELSIUS,
UNIT_VOLT,
)
from esphome.core import CORE
import esphome.final_validate as fv
from esphome.types import ConfigType
from . import (
ADC,
CONF_NPM1300_ID,
CONF_THERMISTOR_BETA,
CONF_THERMISTOR_RESISTANCE,
CONF_VBUS_CURRENT_LIMIT,
DATA_PUBLISHER,
DOMAIN,
DUMP,
DUMP_TAG,
IBAT_SCALE,
NPM1300_CHILD_SCHEMA,
npm1300_ns,
)
DEPENDENCIES = ["npm1300"]
CONF_BATTERY_CURRENT = "battery_current"
CONF_BATTERY_TEMPERATURE = "battery_temperature"
CONF_DIE_TEMPERATURE = "die_temperature"
CONF_SYSTEM_VOLTAGE = "system_voltage"
CONF_VBUS_VOLTAGE = "vbus_voltage"
ADC_MAX_CODE = 1023
def _adc(msb: int, lsbs: int, shift: int) -> cg.MockObj:
"""The 10-bit result in adc[msb] and bits shift..shift+1 of adc[lsbs]."""
return npm1300_ns.adc_code(ADC, msb, lsbs, shift)
# The decoded value and the dump name of each ADC sensor but the battery temperature, which needs the hub config.
# Voltages scale by their full scale (product specification, section ADC).
STATES = {
CONF_BATTERY_VOLTAGE: (_adc(1, 5, 0) * (5.0 / ADC_MAX_CODE), "Battery Voltage"),
CONF_BATTERY_CURRENT: (_adc(8, 10, 4) * IBAT_SCALE, "Battery Current"),
# Product specification: T = 394.67 - 0.7926 * code
CONF_DIE_TEMPERATURE: (394.67 - 0.7926 * _adc(3, 5, 4), "Die Temperature"),
CONF_SYSTEM_VOLTAGE: (_adc(4, 5, 6) * (6.375 / ADC_MAX_CODE), "System Voltage"),
CONF_VBUS_VOLTAGE: (_adc(9, 10, 6) * (7.5 / ADC_MAX_CODE), "VBUS Voltage"),
}
def _voltage_schema() -> cv.Schema:
return sensor.sensor_schema(
unit_of_measurement=UNIT_VOLT,
accuracy_decimals=3,
device_class=DEVICE_CLASS_VOLTAGE,
state_class=STATE_CLASS_MEASUREMENT,
)
def _temperature_schema(**extra: str) -> cv.Schema:
return sensor.sensor_schema(
unit_of_measurement=UNIT_CELSIUS,
accuracy_decimals=1,
device_class=DEVICE_CLASS_TEMPERATURE,
state_class=STATE_CLASS_MEASUREMENT,
**extra,
)
CONFIG_SCHEMA = NPM1300_CHILD_SCHEMA.extend(
{
cv.Optional(CONF_BATTERY_VOLTAGE): _voltage_schema(),
cv.Optional(CONF_BATTERY_CURRENT): sensor.sensor_schema(
unit_of_measurement=UNIT_AMPERE,
accuracy_decimals=3,
device_class=DEVICE_CLASS_CURRENT,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_BATTERY_TEMPERATURE): _temperature_schema(),
cv.Optional(CONF_DIE_TEMPERATURE): _temperature_schema(
entity_category=ENTITY_CATEGORY_DIAGNOSTIC
),
cv.Optional(CONF_SYSTEM_VOLTAGE): _voltage_schema(),
cv.Optional(CONF_VBUS_VOLTAGE): _voltage_schema(),
cv.Optional(CONF_VBUS_CURRENT_LIMIT): sensor.sensor_schema(
unit_of_measurement=UNIT_AMPERE,
accuracy_decimals=1,
device_class=DEVICE_CLASS_CURRENT,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
}
)
def _final_validate(config: ConfigType) -> None:
if CONF_BATTERY_TEMPERATURE not in config:
return
hub = fv.get_declaring_config(config[CONF_NPM1300_ID])
if CONF_THERMISTOR_RESISTANCE not in hub:
raise cv.Invalid(
f"'{CONF_BATTERY_TEMPERATURE}' needs '{CONF_THERMISTOR_RESISTANCE}' "
"set on the npm1300 component",
path=[CONF_BATTERY_TEMPERATURE],
)
FINAL_VALIDATE_SCHEMA = _final_validate
def _add_adc_sensor(
hub: cg.MockObj, var: cg.MockObj, state: cg.MockObj, name: str
) -> None:
DATA_PUBLISHER.add(hub, parent_ref(var).publish_state(state))
DUMP.add(
hub,
sensor.sensor_ns.log_sensor(
DUMP_TAG,
" ",
cg.RawExpression(f'LOG_STR_LITERAL("{name}")'),
parent_ref(var),
),
)
async def to_code(config: ConfigType) -> None:
hub_id = config[CONF_NPM1300_ID]
hub = await cg.get_variable(hub_id)
sensors = sensor.sub_sensors(config)
for key, (state, name) in STATES.items():
if (var := await sensors(key, None)) is not None:
_add_adc_sensor(hub, var, state, name)
if (var := await sensors(CONF_BATTERY_TEMPERATURE, None)) is not None:
hub_config = next(c for c in CORE.config[DOMAIN] if c[CONF_ID] == hub_id)
state = npm1300_ns.ntc_temperature(
_adc(2, 5, 2), 1.0 / hub_config[CONF_THERMISTOR_BETA]
)
_add_adc_sensor(hub, var, state, "Battery Temperature")
await sensors(CONF_VBUS_CURRENT_LIMIT, hub.set_vbus_current_limit_sensor)
-95
View File
@@ -1,95 +0,0 @@
import esphome.codegen as cg
from esphome.components import switch
import esphome.config_validation as cv
from esphome.const import ENTITY_CATEGORY_CONFIG
import esphome.final_validate as fv
from esphome.types import ConfigType
from . import (
CONF_BUCK1,
CONF_BUCK2,
CONF_CHARGER,
CONF_LDO1,
CONF_LDO2,
CONF_NPM1300_ID,
CONF_THERMISTOR_RESISTANCE,
NPM1300_CHILD_SCHEMA,
OUTPUTS,
)
DEPENDENCIES = ["npm1300"]
def _switch_schema() -> cv.Schema:
# The switches show the state of the chip, so nothing is restored at boot
return switch.switch_schema(
switch.ApplySwitch,
default_restore_mode="DISABLED",
entity_category=ENTITY_CATEGORY_CONFIG,
)
CONFIG_SCHEMA = NPM1300_CHILD_SCHEMA.extend(
{
cv.Optional(CONF_CHARGER): _switch_schema(),
cv.Optional(CONF_BUCK1): _switch_schema(),
cv.Optional(CONF_BUCK2): _switch_schema(),
cv.Optional(CONF_LDO1): _switch_schema(),
cv.Optional(CONF_LDO2): _switch_schema(),
}
)
def _final_validate(config: ConfigType) -> None:
if CONF_CHARGER not in config:
return
hub = fv.get_declaring_config(config[CONF_NPM1300_ID])
# Only the charger block turns off the NTC check, without which the charger never starts
if CONF_CHARGER not in hub and CONF_THERMISTOR_RESISTANCE not in hub:
raise cv.Invalid(
f"The '{CONF_CHARGER}' switch needs a '{CONF_CHARGER}' block or "
f"'{CONF_THERMISTOR_RESISTANCE}' on the npm1300 component",
path=[CONF_CHARGER],
)
FINAL_VALIDATE_SCHEMA = _final_validate
def _output_apply(key: str) -> str:
return f"set_output_enabled({OUTPUTS[key]}, state)"
async def to_code(config: ConfigType) -> None:
hub = await cg.get_variable(config[CONF_NPM1300_ID])
switches = switch.sub_switches(config, parent=hub)
await switches(
CONF_CHARGER,
hub.set_charger_switch,
apply="set_charger_enabled(state)",
publish="on_success",
)
await switches(
CONF_BUCK1,
hub.set_buck1_switch,
apply=_output_apply(CONF_BUCK1),
publish="on_success",
)
await switches(
CONF_BUCK2,
hub.set_buck2_switch,
apply=_output_apply(CONF_BUCK2),
publish="on_success",
)
await switches(
CONF_LDO1,
hub.set_ldo1_switch,
apply=_output_apply(CONF_LDO1),
publish="on_success",
)
await switches(
CONF_LDO2,
hub.set_ldo2_switch,
apply=_output_apply(CONF_LDO2),
publish="on_success",
)
-63
View File
@@ -1,63 +0,0 @@
from esphome.automation import parent_ref
import esphome.codegen as cg
from esphome.components import text_sensor
import esphome.config_validation as cv
from esphome.const import ICON_BATTERY
from esphome.cpp_generator import (
AssignmentExpression,
HexIntLiteral,
VariableDeclarationExpression,
)
from esphome.types import ConfigType
from . import (
CHARGE_STATUS,
CONF_NPM1300_ID,
DUMP,
DUMP_TAG,
ERROR_REASON,
NPM1300_CHILD_SCHEMA,
STATUS_PUBLISHER,
VBUS_STATUS,
npm1300_ns,
)
DEPENDENCIES = ["npm1300"]
CONF_CHARGER_STATUS = "charger_status"
CONFIG_SCHEMA = NPM1300_CHILD_SCHEMA.extend(
{
cv.Optional(CONF_CHARGER_STATUS): text_sensor.text_sensor_schema(
icon=ICON_BATTERY,
),
}
)
async def to_code(config: ConfigType) -> None:
hub = await cg.get_variable(config[CONF_NPM1300_ID])
text_sensors = text_sensor.sub_text_sensors(config)
if (var := await text_sensors(CONF_CHARGER_STATUS, None)) is None:
return
last = cg.MockObj(f"esphome__{var}__last")
# 0xFF so the first update publishes
declaration = VariableDeclarationExpression(cg.uint8, "", last, static=True)
STATUS_PUBLISHER.add(
hub, AssignmentExpression(None, None, declaration, HexIntLiteral(0xFF))
)
STATUS_PUBLISHER.add(
hub,
npm1300_ns.publish_charger_status(
parent_ref(var), last, VBUS_STATUS, CHARGE_STATUS, ERROR_REASON
),
)
DUMP.add(
hub,
text_sensor.text_sensor_ns.log_text_sensor(
DUMP_TAG,
" ",
cg.RawExpression('LOG_STR_LITERAL("Charger Status")'),
parent_ref(var),
),
)
@@ -283,7 +283,7 @@ void HdlcReliability::receive_(const PacketBuffer &data, const PacketMetaData &m
size_t length = frame.size() - FRAME_OVERHEAD;
uint8_t control = frame[0];
const uint8_t *payload = frame.data() + 1;
uint16_t crc = encode_value_le<uint16_t>(frame.data() + length + 1);
uint16_t crc = frame[length + 1] | (frame[length + 2] << 8);
if (frame_crc(control, payload, length) != crc) {
ESP_LOGV(TAG, "%s: CRC error, frame dropped", this->name_);
this->note_received_(false);
+29 -18
View File
@@ -434,31 +434,42 @@ bool RTSPSession::queue_next_packet_() {
const size_t rtp_len = header_len - INTERLEAVED_HEADER_LEN + qtables_len + payload_len;
auto *buf = reinterpret_cast<uint8_t *>(this->send_buf_.data());
uint8_t *p = buf;
*p++ = '$';
*p++ = 0; // interleaved channel 0
p = put_be16(p, rtp_len);
size_t pos = 0;
buf[pos++] = '$';
buf[pos++] = 0; // interleaved channel 0
buf[pos++] = static_cast<uint8_t>(rtp_len >> 8);
buf[pos++] = static_cast<uint8_t>(rtp_len);
*p++ = 0x80; // V=2, P=0, X=0, CC=0
*p++ = static_cast<uint8_t>((last_fragment ? 0x80 : 0x00) | RTP_PAYLOAD_TYPE_JPEG);
p = put_be16(p, this->sequence_number_);
buf[pos++] = 0x80; // V=2, P=0, X=0, CC=0
buf[pos++] = static_cast<uint8_t>((last_fragment ? 0x80 : 0x00) | RTP_PAYLOAD_TYPE_JPEG);
buf[pos++] = static_cast<uint8_t>(this->sequence_number_ >> 8);
buf[pos++] = static_cast<uint8_t>(this->sequence_number_);
this->sequence_number_++;
p = put_be32(p, this->rtp_timestamp_);
p = put_be32(p, this->ssrc_);
buf[pos++] = static_cast<uint8_t>(this->rtp_timestamp_ >> 24);
buf[pos++] = static_cast<uint8_t>(this->rtp_timestamp_ >> 16);
buf[pos++] = static_cast<uint8_t>(this->rtp_timestamp_ >> 8);
buf[pos++] = static_cast<uint8_t>(this->rtp_timestamp_);
buf[pos++] = static_cast<uint8_t>(this->ssrc_ >> 24);
buf[pos++] = static_cast<uint8_t>(this->ssrc_ >> 16);
buf[pos++] = static_cast<uint8_t>(this->ssrc_ >> 8);
buf[pos++] = static_cast<uint8_t>(this->ssrc_);
// RFC 2435 main JPEG header
*p++ = 0; // type-specific
p = put_be24(p, this->frame_sent_);
*p++ = this->jpeg_.type;
*p++ = 255; // Q >= 128: the quantization tables follow in the first packet
*p++ = static_cast<uint8_t>(this->jpeg_.width / 8);
*p++ = static_cast<uint8_t>(this->jpeg_.height / 8);
buf[pos++] = 0; // type-specific
buf[pos++] = static_cast<uint8_t>(this->frame_sent_ >> 16);
buf[pos++] = static_cast<uint8_t>(this->frame_sent_ >> 8);
buf[pos++] = static_cast<uint8_t>(this->frame_sent_);
buf[pos++] = this->jpeg_.type;
buf[pos++] = 255; // Q >= 128: the quantization tables follow in the first packet
buf[pos++] = static_cast<uint8_t>(this->jpeg_.width / 8);
buf[pos++] = static_cast<uint8_t>(this->jpeg_.height / 8);
uint8_t count = 0;
if (first_fragment) {
*p++ = 0; // MBZ
*p++ = 0; // 8-bit precision
put_be16(p, qtables_len);
buf[pos++] = 0; // MBZ
buf[pos++] = 0; // 8-bit precision
buf[pos++] = static_cast<uint8_t>(qtables_len >> 8);
buf[pos++] = static_cast<uint8_t>(qtables_len);
this->iov_[0] = {buf, header_len};
this->iov_[1] = {const_cast<uint8_t *>(this->jpeg_.qtable0), QTABLE_LEN};
this->iov_[2] = {const_cast<uint8_t *>(this->jpeg_.qtable1), QTABLE_LEN};
@@ -145,9 +145,11 @@ void RuntimeImage::draw_pixel(int x, int y, const Color &color) {
this->map_chroma_key(mapped_color);
uint16_t rgb565 = display::ColorUtil::color_to_565(mapped_color);
if (this->big_endian_) {
put_be16(this->buffer_ + pos, rgb565);
this->buffer_[pos + 0] = static_cast<uint8_t>((rgb565 >> 8) & 0xFF);
this->buffer_[pos + 1] = static_cast<uint8_t>(rgb565 & 0xFF);
} else {
put_le16(this->buffer_ + pos, rgb565);
this->buffer_[pos + 0] = static_cast<uint8_t>(rgb565 & 0xFF);
this->buffer_[pos + 1] = static_cast<uint8_t>((rgb565 >> 8) & 0xFF);
}
if (this->transparency_ == image::TRANSPARENCY_ALPHA_CHANNEL) {
const size_t alpha_pos = pos / 2 + this->buffer_width_ * this->buffer_height_ * 2;
@@ -48,16 +48,17 @@ bool SensirionI2CDevice::write_command_(uint16_t command, CommandLen command_len
temp[raw_idx++] = command & 0xFF;
} else {
// command is 2 bytes
put_be16(temp, command);
raw_idx = 2;
temp[raw_idx++] = command >> 8;
temp[raw_idx++] = command & 0xFF;
}
// add parameters followed by crc
// skipped if len == 0
for (size_t i = 0; i < data_len; i++) {
put_be16(temp + raw_idx, data[i]);
temp[raw_idx++] = data[i] >> 8;
temp[raw_idx++] = data[i] & 0xFF;
// Use MSB first since Sensirion devices use CRC-8 with MSB first
temp[raw_idx + 2] = crc8(temp + raw_idx, 2, 0xFF, CRC_POLYNOMIAL, true);
raw_idx += 3;
uint8_t crc = crc8(&temp[raw_idx - 2], 2, 0xFF, CRC_POLYNOMIAL, true);
temp[raw_idx++] = crc;
}
this->last_error_ = this->write(temp, raw_idx);
return this->last_error_ == i2c::ERROR_OK;
@@ -611,7 +611,7 @@ stm32_unique_ptr stm32_init(uart::UARTDevice *stream, const uint8_t flags, const
ESP_LOGD(TAG, "Only %d bytes sent in the PID, unknown/unsupported device", returned);
return make_stm32_with_deletor(nullptr);
}
stm->pid = encode_uint16(buf[1], buf[2]);
stm->pid = (buf[1] << 8) | buf[2];
if (returned > 2) {
ESP_LOGD(TAG, "This bootloader returns %d extra bytes in PID:", returned);
for (auto i = 2; i <= returned; i++) {
@@ -952,7 +952,7 @@ stm32_err_t stm32_crc_memory(const stm32_unique_ptr &stm, const uint32_t address
if (buf[4] != xor_bytes(buf, 4))
return STM32_ERR_UNKNOWN;
*crc = encode_uint32(buf[0], buf[1], buf[2], buf[3]);
*crc = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
}
return STM32_ERR_OK;
@@ -123,7 +123,8 @@ void HOT SSD1331::draw_absolute_pixel_internal(int x, int y, Color color) {
const uint32_t color565 = display::ColorUtil::color_to_565(color);
// where should the bits go in the big buffer array? math...
uint16_t pos = (x + y * this->get_width_internal()) * SSD1331_BYTESPERPIXEL;
put_be16(this->buffer_ + pos, color565);
this->buffer_[pos++] = (color565 >> 8) & 0xff;
this->buffer_[pos] = color565 & 0xff;
}
void SSD1331::fill(Color color) {
// If clipping is active, fall back to base implementation
@@ -155,7 +155,8 @@ void HOT SSD1351::draw_absolute_pixel_internal(int x, int y, Color color) {
const uint32_t color565 = display::ColorUtil::color_to_565(color);
// where should the bits go in the big buffer array? math...
uint16_t pos = (x + y * this->get_width_internal()) * SSD1351_BYTESPERPIXEL;
put_be16(this->buffer_ + pos, color565);
this->buffer_[pos++] = (color565 >> 8) & 0xff;
this->buffer_[pos] = color565 & 0xff;
}
void SSD1351::fill(Color color) {
// If clipping is active, fall back to base implementation
+48 -23
View File
@@ -61,7 +61,9 @@ ConfigurationResult SX126xCommands::configure(const RadioProfile &profile, std::
if (profile.tcxo_voltage != TCXO_CTRL_NONE) {
uint32_t delay = profile.tcxo_delay >> 6;
buf[0] = profile.tcxo_voltage;
put_be24(buf + 1, delay);
buf[1] = (delay >> 16) & 0xFF;
buf[2] = (delay >> 8) & 0xFF;
buf[3] = (delay >> 0) & 0xFF;
this->write_opcode_(RADIO_SET_TCXOMODE, buf, 4);
buf[0] = 0x7F;
this->write_opcode_(RADIO_CALIBRATE, buf, 1);
@@ -97,7 +99,10 @@ ConfigurationResult SX126xCommands::configure(const RadioProfile &profile, std::
// set frequency
uint64_t freq = ((uint64_t) profile.frequency << 25) / XTAL_FREQ;
put_be32(buf, static_cast<uint32_t>(freq));
buf[0] = (uint8_t) ((freq >> 24) & 0xFF);
buf[1] = (uint8_t) ((freq >> 16) & 0xFF);
buf[2] = (uint8_t) ((freq >> 8) & 0xFF);
buf[3] = (uint8_t) (freq & 0xFF);
this->write_opcode_(RADIO_SET_RFFREQUENCY, buf, 4);
// configure pa
@@ -147,17 +152,23 @@ ConfigurationResult SX126xCommands::configure(const RadioProfile &profile, std::
// set modulation params
uint32_t bitrate = ((uint64_t) XTAL_FREQ * 32) / profile.bitrate;
uint32_t fdev = ((uint64_t) profile.deviation << 25) / XTAL_FREQ;
put_be24(buf, bitrate);
buf[0] = (bitrate >> 16) & 0xFF;
buf[1] = (bitrate >> 8) & 0xFF;
buf[2] = (bitrate >> 0) & 0xFF;
buf[3] = profile.shaping;
buf[4] = progmem_read_byte(&BW_FSK[profile.bandwidth - SX126X_BW_4800]);
put_be24(buf + 5, fdev);
buf[5] = (fdev >> 16) & 0xFF;
buf[6] = (fdev >> 8) & 0xFF;
buf[7] = (fdev >> 0) & 0xFF;
this->write_opcode_(RADIO_SET_MODULATIONPARAMS, buf, 8);
// set crc params
if (profile.crc_enable) {
put_be16(buf, profile.crc_initial);
buf[0] = profile.crc_initial >> 8;
buf[1] = profile.crc_initial & 0xFF;
this->write_register_(REG_CRC_INITIAL, buf, 2);
put_be16(buf, profile.crc_polynomial);
buf[0] = profile.crc_polynomial >> 8;
buf[1] = profile.crc_polynomial & 0xFF;
this->write_register_(REG_CRC_POLYNOMIAL, buf, 2);
}
@@ -192,7 +203,8 @@ void SX126xCommands::encode_packet_params(const RadioProfile &profile, AppliedPr
auto &buf = applied.packet_params;
const uint8_t payload_length = profile.max_packet_size();
if (profile.modulation == PACKET_TYPE_LORA) {
put_be16(buf.data(), profile.preamble_size);
buf[0] = (profile.preamble_size >> 8) & 0xFF;
buf[1] = (profile.preamble_size >> 0) & 0xFF;
buf[2] = (profile.payload_length > 0) ? 0x01 : 0x00;
buf[3] = payload_length;
buf[4] = (profile.crc_enable) ? 0x01 : 0x00;
@@ -200,7 +212,8 @@ void SX126xCommands::encode_packet_params(const RadioProfile &profile, AppliedPr
applied.packet_params_size = 6;
} else {
uint16_t preamble_size = profile.preamble_size * 8;
put_be16(buf.data(), preamble_size);
buf[0] = (preamble_size >> 8) & 0xFF;
buf[1] = (preamble_size >> 0) & 0xFF;
buf[2] = (profile.preamble_detect > 0) ? ((profile.preamble_detect - 1) | 0x04) : 0x00;
buf[3] = profile.sync_size * 8;
buf[4] = 0x00;
@@ -246,20 +259,20 @@ void SX126xCommands::calibrate_image(uint32_t frequency) {
}
}
// The IRQ mask also routes to DIO1; DIO2 and DIO3 stay unused.
void SX126xCommands::set_dio_irq_params_(uint16_t irq) {
uint8_t buf[8];
put_be16(buf, irq);
put_be16(buf + 2, irq);
put_be16(buf + 4, IRQ_RADIO_NONE);
put_be16(buf + 6, IRQ_RADIO_NONE);
this->write_opcode_(RADIO_SET_DIOIRQPARAMS, buf, 8);
}
void SX126xCommands::receive() {
this->set_dio_irq_params_(IRQ_RX_DONE | IRQ_RX_TX_TIMEOUT | IRQ_CRC_ERROR);
uint8_t buf[8];
uint8_t buf[3];
// configure irq params
uint16_t irq = IRQ_RX_DONE | IRQ_RX_TX_TIMEOUT | IRQ_CRC_ERROR;
buf[0] = (irq >> 8) & 0xFF;
buf[1] = (irq >> 0) & 0xFF;
buf[2] = (irq >> 8) & 0xFF;
buf[3] = (irq >> 0) & 0xFF;
buf[4] = (IRQ_RADIO_NONE >> 8) & 0xFF;
buf[5] = (IRQ_RADIO_NONE >> 0) & 0xFF;
buf[6] = (IRQ_RADIO_NONE >> 8) & 0xFF;
buf[7] = (IRQ_RADIO_NONE >> 0) & 0xFF;
this->write_opcode_(RADIO_SET_DIOIRQPARAMS, buf, 8);
// set timeout to 0
buf[0] = 0x00;
@@ -273,12 +286,24 @@ void SX126xCommands::receive() {
}
void SX126xCommands::transmit(uint32_t timeout_ms) {
this->set_dio_irq_params_(IRQ_TX_DONE | IRQ_RX_TX_TIMEOUT);
uint8_t buf[8];
uint8_t buf[3];
// configure irq params
uint16_t irq = IRQ_TX_DONE | IRQ_RX_TX_TIMEOUT;
buf[0] = (irq >> 8) & 0xFF;
buf[1] = (irq >> 0) & 0xFF;
buf[2] = (irq >> 8) & 0xFF;
buf[3] = (irq >> 0) & 0xFF;
buf[4] = (IRQ_RADIO_NONE >> 8) & 0xFF;
buf[5] = (IRQ_RADIO_NONE >> 0) & 0xFF;
buf[6] = (IRQ_RADIO_NONE >> 8) & 0xFF;
buf[7] = (IRQ_RADIO_NONE >> 0) & 0xFF;
this->write_opcode_(RADIO_SET_DIOIRQPARAMS, buf, 8);
const uint32_t ticks = timeout_ms * 64;
put_be24(buf, ticks);
buf[0] = ticks >> 16;
buf[1] = ticks >> 8;
buf[2] = ticks;
this->write_opcode_(RADIO_SET_TX, buf, 3);
}
@@ -41,7 +41,6 @@ class SX126xCommands {
private:
void read_opcode_(uint8_t opcode, uint8_t *data, uint8_t size);
void write_opcode_(uint8_t opcode, const uint8_t *data, uint8_t size);
void set_dio_irq_params_(uint16_t irq);
void read_register_(uint16_t reg, uint8_t *data, uint8_t size);
void write_register_(uint16_t reg, const uint8_t *data, uint8_t size);
static void encode_packet_params(const RadioProfile &profile, AppliedProfile &applied);
+93 -312
View File
@@ -1,27 +1,12 @@
#include "sx127x.h"
#include "esphome/core/application.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include "esphome/core/progmem.h"
#include <cmath>
#include <utility>
namespace esphome::sx127x {
ESPHOME_LOG_TAG(TAG, "sx127x");
static const uint32_t FXOSC = 32000000u;
static constexpr uint32_t TRANSMIT_TIMEOUT_MS = 4000;
static constexpr uint32_t MAX_TRANSMIT_TIMEOUT_MS = 262143; // the same range as SX126x
static constexpr uint32_t MODE_TIMEOUT_MS = 20;
static constexpr uint32_t RECONFIGURE_INTERVAL_ID = 0;
static constexpr uint32_t RECONFIGURE_INTERVAL_MS = 1000;
// Indexed by SX127xError
PROGMEM_STRING_TABLE(SX127xErrorStrings, "none", "timeout", "invalid parameters", "radio not ready", "radio busy",
"cancelled");
static const LogString *set_mode_failure() { return LOG_STR("Set mode failure"); }
static constexpr uint16_t RAMP[16] PROGMEM = {3400, 2000, 1000, 500, 250, 125, 100, 62, 50, 40, 31, 25, 20, 15, 12, 10};
// Aligned 32 bit loads from flash are safe on ESP8266, so this table is read directly
static constexpr uint32_t BW_HZ[22] PROGMEM = {2604, 3125, 3906, 5208, 6250, 7812, 10416, 12500,
@@ -71,72 +56,26 @@ void SX127x::write_fifo_(const uint8_t *data, size_t len) {
this->disable();
}
void IRAM_ATTR SX127x::gpio_intr(SX127x *arg) { arg->enable_loop_soon_any_context(); }
void SX127x::setup() {
// setup reset
this->rst_pin_->setup();
// setup dio0
if (this->dio0_pin_ != nullptr) {
if (this->dio0_pin_) {
this->dio0_pin_->setup();
if (this->dio0_pin_->is_internal()) {
static_cast<InternalGPIOPin *>(this->dio0_pin_)
->attach_interrupt(&SX127x::gpio_intr, this, gpio::INTERRUPT_RISING_EDGE);
}
this->dio0_pin_->attach_interrupt(&SX127x::gpio_intr, this, gpio::INTERRUPT_RISING_EDGE);
}
// start spi
this->spi_setup();
// configure rf
const LogString *reason = this->configure_radio_();
if (reason != nullptr) {
this->mark_failed(reason);
return;
}
this->state_ = RadioState::RADIO_STATE_IDLE;
// Sized once so later packet reads do not reallocate
this->packet_.reserve(this->get_max_packet_size());
this->configure();
}
void SX127x::configure() {
// Nothing to configure before setup() or after a failed setup
if (!this->is_ready()) {
return;
}
if (this->is_transmitting()) {
ESP_LOGW(TAG, "Radio operation in progress, configuration ignored");
return;
}
const LogString *reason = this->configure_radio_();
if (reason != nullptr) {
this->fail_(reason);
return;
}
this->state_ = RadioState::RADIO_STATE_IDLE;
if (this->reconfigure_pending_) {
this->reconfigure_pending_ = false;
this->cancel_interval(RECONFIGURE_INTERVAL_ID);
}
this->status_clear_warning();
this->enable_loop();
}
void SX127x::fail_(const LogString *reason) {
this->state_ = RadioState::RADIO_STATE_NEEDS_CONFIGURATION;
// Nothing else configures the radio again
if (!this->reconfigure_pending_) {
this->reconfigure_pending_ = true;
this->set_interval(RECONFIGURE_INTERVAL_ID, RECONFIGURE_INTERVAL_MS, [this]() { this->configure(); });
}
// Last: a log listener may call configure(), which cancels the retry
this->status_set_warning(reason);
}
const LogString *SX127x::configure_radio_() {
// Until this succeeds; a held packet is discarded
this->state_ = RadioState::RADIO_STATE_NEEDS_CONFIGURATION;
this->applied_ = {this->frequency_, this->payload_length_, this->modulation_, this->packet_mode_, this->rx_start_};
// toggle chip reset
this->rst_pin_->digital_write(false);
delayMicroseconds(1000);
@@ -145,13 +84,12 @@ const LogString *SX127x::configure_radio_() {
// check silicon version to make sure hw is ok
if (this->read_register_(REG_VERSION) != 0x12) {
return LOG_STR("Unsupported chip version");
this->mark_failed(LOG_STR("Unsupported chip version"));
return;
}
// enter sleep mode
if (!this->set_mode_(MOD_FSK, MODE_SLEEP)) {
return set_mode_failure();
}
this->set_mode_(MOD_FSK, MODE_SLEEP);
// set freq
uint64_t frf = ((uint64_t) this->frequency_ << 19) / FXOSC;
@@ -160,27 +98,21 @@ const LogString *SX127x::configure_radio_() {
this->write_register_(REG_FRF_LSB, (uint8_t) ((frf >> 0) & 0xFF));
// enter standby mode
if (!this->set_mode_(MOD_FSK, MODE_STDBY)) {
return set_mode_failure();
}
this->set_mode_(MOD_FSK, MODE_STDBY);
// run image cal
const LogString *reason = this->image_cal_();
if (reason != nullptr) {
return reason;
}
this->run_image_cal();
// go back to sleep
if (!this->set_mode_(this->modulation_, MODE_SLEEP)) {
return set_mode_failure();
}
this->set_mode_sleep();
// config pa
if (this->pa_pin_ == PA_PIN_BOOST) {
this->pa_power_ = clamp(this->pa_power_, (uint8_t) 2, (uint8_t) 17);
this->pa_power_ = std::max(this->pa_power_, (uint8_t) 2);
this->pa_power_ = std::min(this->pa_power_, (uint8_t) 17);
this->write_register_(REG_PA_CONFIG, (this->pa_power_ - 2) | this->pa_pin_ | PA_MAX_POWER);
} else {
this->pa_power_ = clamp_at_most(this->pa_power_, (uint8_t) 14);
this->pa_power_ = std::min(this->pa_power_, (uint8_t) 14);
this->write_register_(REG_PA_CONFIG, (this->pa_power_ - 0) | this->pa_pin_ | PA_MAX_POWER);
}
if (this->modulation_ != MOD_LORA) {
@@ -197,10 +129,11 @@ const LogString *SX127x::configure_radio_() {
}
// switch to rx or sleep
if (!this->restore_()) {
return set_mode_failure();
if (this->rx_start_) {
this->set_mode_rx();
} else {
this->set_mode_sleep();
}
return nullptr;
}
void SX127x::configure_fsk_ook_() {
@@ -319,144 +252,70 @@ void SX127x::configure_lora_() {
}
size_t SX127x::get_max_packet_size() {
if (this->applied_.payload_length > 0) {
return this->applied_.payload_length;
if (this->payload_length_ > 0) {
return this->payload_length_;
}
if (this->applied_.modulation == MOD_LORA) {
if (this->modulation_ == MOD_LORA) {
return SX127X_MAX_PACKET_SIZE;
}
return 64;
}
SX127xError SX127x::transmit_packet(const uint8_t *data, size_t len) {
SX127xError result = this->start_transmit_(nullptr, data, len, TRANSMIT_TIMEOUT_MS);
if (result == SX127xError::SX127X_ERROR_NONE) {
// Without a listener this send cannot be cancelled or replaced
result = SX127xError::SX127X_ERROR_NOT_READY;
while (this->is_transmitting() && !this->poll_transmit_(millis(), result)) {
App.feed_wdt();
}
}
if (result != SX127xError::SX127X_ERROR_NONE) {
ESP_LOGW(
TAG, "Packet send failed: %s",
LOG_STR_ARG(SX127xErrorStrings::get_log_str(static_cast<uint8_t>(result), SX127xErrorStrings::LAST_INDEX)));
}
return result;
}
SX127xError SX127x::start_transmit_async(SX127xTransmitListener *listener, const uint8_t *data, size_t len,
uint32_t timeout_ms) {
if (listener == nullptr || timeout_ms == 0 || timeout_ms > MAX_TRANSMIT_TIMEOUT_MS) {
return SX127xError::SX127X_ERROR_INVALID_PARAMS;
}
return this->start_transmit_(listener, data, len, timeout_ms);
}
SX127xError SX127x::start_transmit_(SX127xTransmitListener *listener, const uint8_t *data, size_t len,
uint32_t timeout_ms) {
// Callers such as a template number's on_value can run before setup() or after a failed setup
if (!this->is_ready() || this->state_ == RadioState::RADIO_STATE_NEEDS_CONFIGURATION) {
if (!this->is_ready()) {
ESP_LOGW(TAG, "Radio not ready, packet dropped");
return SX127xError::SX127X_ERROR_NOT_READY;
}
if (this->state_ != RadioState::RADIO_STATE_IDLE) {
return SX127xError::SX127X_ERROR_BUSY;
if (this->payload_length_ > 0 && this->payload_length_ != len) {
ESP_LOGE(TAG, "Packet size does not match config");
return SX127xError::INVALID_PARAMS;
}
if (data == nullptr || len == 0 || len > this->get_max_packet_size() ||
(this->applied_.payload_length > 0 && this->applied_.payload_length != len)) {
return SX127xError::SX127X_ERROR_INVALID_PARAMS;
if (len == 0 || len > this->get_max_packet_size()) {
ESP_LOGE(TAG, "Packet size out of range");
return SX127xError::INVALID_PARAMS;
}
if (this->dio0_pin_ == nullptr) {
ESP_LOGE(TAG, "DIO0 pin not configured, cannot wait for transmit completion");
return SX127xError::SX127X_ERROR_INVALID_PARAMS;
return SX127xError::INVALID_PARAMS;
}
if (!this->set_mode_(this->applied_.modulation, MODE_STDBY)) {
this->fail_(set_mode_failure());
return SX127xError::SX127X_ERROR_NOT_READY;
}
// A packet received before standby stays in the FIFO for loop()
if (this->packet_waiting_()) {
this->state_ = RadioState::RADIO_STATE_HOLDING_RX;
this->enable_loop();
return SX127xError::SX127X_ERROR_BUSY;
}
if (this->applied_.modulation == MOD_LORA) {
if (this->applied_.payload_length == 0) {
SX127xError ret = SX127xError::NONE;
if (this->modulation_ == MOD_LORA) {
this->set_mode_standby();
if (this->payload_length_ == 0) {
this->write_register_(REG_PAYLOAD_LENGTH, len);
}
this->write_register_(REG_IRQ_FLAGS, 0xFF);
this->write_register_(REG_FIFO_ADDR_PTR, 0);
} else if (this->applied_.payload_length == 0) {
this->write_register_(REG_FIFO, len);
}
this->write_fifo_(data, len);
if (!this->enter_tx_()) {
this->fail_(set_mode_failure());
return SX127xError::SX127X_ERROR_NOT_READY;
}
this->tx_ = {listener, millis(), timeout_ms};
this->state_ = RadioState::RADIO_STATE_TRANSMITTING;
this->enable_loop();
return SX127xError::SX127X_ERROR_NONE;
}
bool SX127x::poll_transmit_(uint32_t now, SX127xError &result) {
if (!this->is_transmitting()) {
return false;
}
// DIO0 is TX_DONE in LoRa, and PacketSent in FSK and OOK while transmitting
if (this->dio0_pin_->digital_read()) {
result = SX127xError::SX127X_ERROR_NONE;
} else if (static_cast<int32_t>(now - this->tx_.started_ms) >= static_cast<int32_t>(this->tx_.timeout_ms)) {
// Signed, as the cached loop time can precede the start
result = SX127xError::SX127X_ERROR_TIMEOUT;
this->write_fifo_(data, len);
this->set_mode_tx();
} else {
return false;
this->set_mode_standby();
if (this->payload_length_ == 0) {
this->write_register_(REG_FIFO, len);
}
this->write_fifo_(data, len);
this->set_mode_tx();
}
result = this->finish_transmit_(result);
return true;
}
bool SX127x::cancel_transmit_async(SX127xTransmitListener *listener) {
if (!this->is_transmitting() || listener == nullptr || listener != this->tx_.listener) {
return false;
// wait until transmit completes, typically the delay will be less than 100 ms
uint32_t start = millis();
while (!this->dio0_pin_->digital_read()) {
App.feed_wdt();
if (millis() - start > 4000) {
ESP_LOGE(TAG, "Transmit packet failure");
ret = SX127xError::TIMEOUT;
break;
}
}
this->finish_transmit_(SX127xError::SX127X_ERROR_CANCELLED);
return true;
}
// The only place a send ends; state is committed before the listener runs
SX127xError SX127x::finish_transmit_(SX127xError result) {
SX127xTransmitListener *listener = std::exchange(this->tx_.listener, nullptr);
if (this->restore_()) {
this->state_ = RadioState::RADIO_STATE_IDLE;
if (this->rx_start_) {
this->set_mode_rx();
} else {
this->fail_(set_mode_failure());
this->set_mode_sleep();
}
if (listener != nullptr) {
listener->on_transmit_complete(result);
}
return result;
}
bool SX127x::restore_() {
// Via standby: the chip ignores RX while a packet is still going out
if (!this->set_mode_(this->applied_.modulation, MODE_STDBY)) {
return false;
}
if (this->applied_.modulation == MOD_LORA) {
this->write_register_(REG_IRQ_FLAGS, 0xFF);
}
return this->applied_.rx_start ? this->enter_rx_() : this->set_mode_(this->applied_.modulation, MODE_SLEEP);
}
bool SX127x::packet_waiting_() {
if (this->applied_.modulation == MOD_LORA) {
const uint8_t flags = this->read_register_(REG_IRQ_FLAGS);
return (flags & RX_DONE) != 0 && (flags & PAYLOAD_CRC_ERROR) == 0;
}
return this->applied_.packet_mode && (this->read_register_(REG_IRQ_FLAGS2) & PAYLOAD_READY) != 0;
return ret;
}
void SX127x::call_listeners_(const std::vector<uint8_t> &packet, float rssi, float snr) {
@@ -467,81 +326,43 @@ void SX127x::call_listeners_(const std::vector<uint8_t> &packet, float rssi, flo
}
void SX127x::loop() {
switch (this->state_) {
case RadioState::RADIO_STATE_TRANSMITTING: {
SX127xError result;
this->poll_transmit_(App.get_loop_component_start_time(), result);
return;
}
case RadioState::RADIO_STATE_HOLDING_RX:
this->receive_();
return;
case RadioState::RADIO_STATE_IDLE:
if (this->dio0_pin_ == nullptr) {
this->disable_loop();
return;
}
// DIO0's interrupt wakes the loop
if (this->dio0_pin_->is_internal()) {
this->disable_loop();
}
if (this->dio0_pin_->digital_read()) {
this->receive_();
}
return;
default:
// configure() wakes the loop
this->disable_loop();
return;
this->disable_loop();
if (this->dio0_pin_ == nullptr || !this->dio0_pin_->digital_read()) {
return;
}
}
void SX127x::receive_() {
const bool holding = this->state_ == RadioState::RADIO_STATE_HOLDING_RX;
bool received = false;
float rssi = 0.0f;
float snr = NAN; // FSK and OOK have no SNR
if (this->applied_.modulation == MOD_LORA) {
if (this->modulation_ == MOD_LORA) {
uint8_t status = this->read_register_(REG_IRQ_FLAGS);
this->write_register_(REG_IRQ_FLAGS, 0xFF);
if ((status & RX_DONE) != 0 && (status & PAYLOAD_CRC_ERROR) == 0) {
if ((status & PAYLOAD_CRC_ERROR) == 0) {
uint8_t bytes = this->read_register_(REG_NB_RX_BYTES);
uint8_t addr = this->read_register_(REG_FIFO_RX_CURR_ADDR);
uint8_t raw_rssi = this->read_register_(REG_PKT_RSSI_VALUE);
int8_t raw_snr = (int8_t) this->read_register_(REG_PKT_SNR_VALUE);
uint8_t rssi = this->read_register_(REG_PKT_RSSI_VALUE);
int8_t snr = (int8_t) this->read_register_(REG_PKT_SNR_VALUE);
this->packet_.resize(bytes);
this->write_register_(REG_FIFO_ADDR_PTR, addr);
this->read_fifo_(this->packet_);
rssi = (float) raw_rssi - (this->applied_.frequency > 700000000 ? RSSI_OFFSET_HF : RSSI_OFFSET_LF);
snr = (float) raw_snr / 4;
received = true;
if (this->frequency_ > 700000000) {
this->call_listeners_(this->packet_, (float) rssi - RSSI_OFFSET_HF, (float) snr / 4);
} else {
this->call_listeners_(this->packet_, (float) rssi - RSSI_OFFSET_LF, (float) snr / 4);
}
}
} else if (this->applied_.packet_mode && (this->read_register_(REG_IRQ_FLAGS2) & PAYLOAD_READY) != 0) {
uint8_t payload_length = this->applied_.payload_length;
} else if (this->packet_mode_) {
uint8_t payload_length = this->payload_length_;
if (payload_length == 0) {
payload_length = this->read_register_(REG_FIFO);
}
this->packet_.resize(payload_length);
this->read_fifo_(this->packet_);
received = true;
}
if (holding) {
if (this->restore_()) {
this->state_ = RadioState::RADIO_STATE_IDLE;
} else {
this->fail_(set_mode_failure());
}
}
if (received) {
this->call_listeners_(this->packet_, rssi, snr);
this->call_listeners_(this->packet_, 0.0f, 0.0f);
}
}
const LogString *SX127x::image_cal_() {
if (this->applied_.modulation == MOD_LORA) {
if (!this->set_mode_(MOD_FSK, MODE_SLEEP) || !this->set_mode_(MOD_FSK, MODE_STDBY)) {
return set_mode_failure();
}
void SX127x::run_image_cal() {
if (this->modulation_ == MOD_LORA) {
this->set_mode_(MOD_FSK, MODE_SLEEP);
this->set_mode_(MOD_FSK, MODE_STDBY);
}
if (this->auto_cal_) {
this->write_register_(REG_IMAGE_CAL, IMAGE_CAL_START | AUTO_IMAGE_CAL_ON | TEMP_THRESHOLD_10C);
@@ -551,29 +372,17 @@ const LogString *SX127x::image_cal_() {
uint32_t start = millis();
while (this->read_register_(REG_IMAGE_CAL) & IMAGE_CAL_RUNNING) {
if (millis() - start > 20) {
return LOG_STR("Image cal failure");
this->mark_failed(LOG_STR("Image cal failure"));
break;
}
}
if (this->applied_.modulation == MOD_LORA) {
if (!this->set_mode_(this->applied_.modulation, MODE_SLEEP) ||
!this->set_mode_(this->applied_.modulation, MODE_STDBY)) {
return set_mode_failure();
}
}
return nullptr;
}
void SX127x::run_image_cal() {
if (!this->can_change_mode_()) {
return;
}
const LogString *reason = this->image_cal_();
if (reason != nullptr) {
this->fail_(reason);
if (this->modulation_ == MOD_LORA) {
this->set_mode_(this->modulation_, MODE_SLEEP);
this->set_mode_(this->modulation_, MODE_STDBY);
}
}
bool SX127x::set_mode_(uint8_t modulation, uint8_t mode) {
void SX127x::set_mode_(uint8_t modulation, uint8_t mode) {
uint32_t start = millis();
this->write_register_(REG_OP_MODE, modulation | mode);
while (true) {
@@ -582,62 +391,34 @@ bool SX127x::set_mode_(uint8_t modulation, uint8_t mode) {
if (mode == MODE_SLEEP) {
this->write_register_(REG_OP_MODE, modulation | mode);
}
return true;
break;
}
if (millis() - start > MODE_TIMEOUT_MS) {
return false;
if (millis() - start > 20) {
this->mark_failed(LOG_STR("Set mode failure"));
return;
}
}
}
bool SX127x::enter_rx_() {
if (this->applied_.modulation == MOD_LORA) {
void SX127x::set_mode_rx() {
this->set_mode_(this->modulation_, MODE_RX);
if (this->modulation_ == MOD_LORA) {
this->write_register_(REG_IRQ_FLAGS_MASK, 0x00);
this->write_register_(REG_DIO_MAPPING1, DIO0_MAPPING_00);
}
return this->set_mode_(this->applied_.modulation, MODE_RX);
}
bool SX127x::enter_tx_() {
if (this->applied_.modulation == MOD_LORA) {
void SX127x::set_mode_tx() {
this->set_mode_(this->modulation_, MODE_TX);
if (this->modulation_ == MOD_LORA) {
this->write_register_(REG_IRQ_FLAGS_MASK, 0x00);
this->write_register_(REG_DIO_MAPPING1, DIO0_MAPPING_01);
}
return this->set_mode_(this->applied_.modulation, MODE_TX);
}
bool SX127x::can_change_mode_() {
if (this->state_ == RadioState::RADIO_STATE_IDLE) {
return true;
}
ESP_LOGW(TAG, "Radio unavailable, mode change ignored");
return false;
}
void SX127x::set_mode_standby() { this->set_mode_(this->modulation_, MODE_STDBY); }
void SX127x::change_mode_(uint8_t mode) {
if (!this->can_change_mode_()) {
return;
}
bool ok;
if (mode == MODE_RX) {
ok = this->enter_rx_();
} else if (mode == MODE_TX) {
ok = this->enter_tx_();
} else {
ok = this->set_mode_(this->applied_.modulation, mode);
}
if (!ok) {
this->fail_(set_mode_failure());
}
}
void SX127x::set_mode_rx() { this->change_mode_(MODE_RX); }
void SX127x::set_mode_tx() { this->change_mode_(MODE_TX); }
void SX127x::set_mode_standby() { this->change_mode_(MODE_STDBY); }
void SX127x::set_mode_sleep() { this->change_mode_(MODE_SLEEP); }
void SX127x::set_mode_sleep() { this->set_mode_(this->modulation_, MODE_SLEEP); }
void SX127x::dump_config() {
ESP_LOGCONFIG(TAG, "SX127x:");
+7 -79
View File
@@ -36,35 +36,10 @@ enum SX127xBw : uint8_t {
SX127X_BW_500_0,
};
enum class SX127xError {
SX127X_ERROR_NONE = 0,
SX127X_ERROR_TIMEOUT,
SX127X_ERROR_INVALID_PARAMS,
SX127X_ERROR_NOT_READY,
SX127X_ERROR_BUSY,
SX127X_ERROR_CANCELLED,
};
class SX127xTransmitListener {
public:
virtual void on_transmit_complete(SX127xError result) = 0;
};
// Driver state, not the chip's mode
enum class RadioState : uint8_t {
// Before setup or after a failed mode change; configure() is retried every second
RADIO_STATE_NEEDS_CONFIGURATION,
// Receiving or sleeping as configured, or sending after the TX mode action (untracked)
RADIO_STATE_IDLE,
// A send is on air
RADIO_STATE_TRANSMITTING,
// A send found a received packet waiting; loop() delivers it
RADIO_STATE_HOLDING_RX,
};
enum class SX127xError { NONE = 0, TIMEOUT, INVALID_PARAMS, SX127X_ERROR_NOT_READY };
class SX127xListener {
public:
// Called from loop(); the packet is only valid until this returns
virtual void on_packet(const std::vector<uint8_t> &packet, float rssi, float snr) = 0;
};
@@ -85,9 +60,8 @@ class SX127x final : public Component,
void set_coding_rate(uint8_t coding_rate) { this->coding_rate_ = coding_rate; }
void set_crc_enable(bool crc_enable) { this->crc_enable_ = crc_enable; }
void set_deviation(uint32_t deviation) { this->deviation_ = deviation; }
void set_dio0_pin(GPIOPin *dio0_pin) { this->dio0_pin_ = dio0_pin; }
void set_dio0_pin(InternalGPIOPin *dio0_pin) { this->dio0_pin_ = dio0_pin; }
void set_frequency(uint32_t frequency) { this->frequency_ = frequency; }
// Ignored unless the radio is idle
void set_mode_rx();
void set_mode_tx();
void set_mode_standby();
@@ -102,68 +76,26 @@ class SX127x final : public Component,
void set_preamble_polarity(uint8_t preamble_polarity) { this->preamble_polarity_ = preamble_polarity; }
void set_preamble_size(uint16_t preamble_size) { this->preamble_size_ = preamble_size; }
void set_preamble_detect(uint8_t preamble_detect) { this->preamble_detect_ = preamble_detect; }
void set_rst_pin(GPIOPin *rst_pin) { this->rst_pin_ = rst_pin; }
void set_rst_pin(InternalGPIOPin *rst_pin) { this->rst_pin_ = rst_pin; }
void set_rx_floor(float floor) { this->rx_floor_ = floor; }
void set_rx_start(bool start) { this->rx_start_ = start; }
void set_shaping(uint8_t shaping) { this->shaping_ = shaping; }
void set_spreading_factor(uint8_t spreading_factor) { this->spreading_factor_ = spreading_factor; }
void set_sync_value(const std::vector<uint8_t> &sync_value) { this->sync_value_ = sync_value; }
void run_image_cal();
// Ignored while a send is on air; discards a held packet
void configure();
SX127xError transmit_packet(const uint8_t *data, size_t len);
SX127xError transmit_packet(const std::vector<uint8_t> &packet) {
return this->transmit_packet(packet.data(), packet.size());
}
// On SX127X_ERROR_NONE, the listener is called once from loop()
[[nodiscard]] SX127xError start_transmit_async(SX127xTransmitListener *listener, const uint8_t *data, size_t len,
uint32_t timeout_ms = 4000);
[[nodiscard]] SX127xError start_transmit_async(SX127xTransmitListener *listener, const std::vector<uint8_t> &packet,
uint32_t timeout_ms = 4000) {
return this->start_transmit_async(listener, packet.data(), packet.size(), timeout_ms);
}
// Completes the send with SX127X_ERROR_CANCELLED; false if the listener has none
bool cancel_transmit_async(SX127xTransmitListener *listener);
bool is_transmitting() const { return this->state_ == RadioState::RADIO_STATE_TRANSMITTING; }
void register_listener(SX127xListener *listener) { this->listeners_.push_back(listener); }
Trigger<std::vector<uint8_t>, float, float> *get_packet_trigger() { return &this->packet_trigger_; }
protected:
// Settings as last applied by configure(), used by sends and reception
struct AppliedSettings {
uint32_t frequency{0};
uint32_t payload_length{0};
uint8_t modulation{0};
bool packet_mode{false};
bool rx_start{false};
};
struct TxOperation {
SX127xTransmitListener *listener{nullptr};
uint32_t started_ms{0};
uint32_t timeout_ms{0};
};
static void IRAM_ATTR gpio_intr(SX127x *arg) { arg->enable_loop_soon_any_context(); }
// Each returns the failure reason, or nullptr
const LogString *configure_radio_();
const LogString *image_cal_();
static void gpio_intr(SX127x *arg);
void configure_fsk_ook_();
void configure_lora_();
// False if the chip did not enter the mode
bool set_mode_(uint8_t modulation, uint8_t mode);
bool enter_rx_();
bool enter_tx_();
bool can_change_mode_();
void change_mode_(uint8_t mode);
// Puts the radio back in RX or sleep after a send or a held packet
bool restore_();
// Retries configure() every second
void fail_(const LogString *reason);
bool packet_waiting_();
void receive_();
SX127xError start_transmit_(SX127xTransmitListener *listener, const uint8_t *data, size_t len, uint32_t timeout_ms);
// True once the send has ended, with its outcome in result
bool poll_transmit_(uint32_t now, SX127xError &result);
SX127xError finish_transmit_(SX127xError result);
void set_mode_(uint8_t modulation, uint8_t mode);
void write_fifo_(const uint8_t *data, size_t len);
void read_fifo_(std::vector<uint8_t> &packet);
void write_register_(uint8_t reg, uint8_t value);
@@ -173,10 +105,8 @@ class SX127x final : public Component,
std::vector<SX127xListener *> listeners_;
std::vector<uint8_t> packet_;
std::vector<uint8_t> sync_value_;
AppliedSettings applied_;
TxOperation tx_;
GPIOPin *dio0_pin_{nullptr};
GPIOPin *rst_pin_{nullptr};
InternalGPIOPin *dio0_pin_{nullptr};
InternalGPIOPin *rst_pin_{nullptr};
SX127xBw afc_bandwidth_{SX127X_BW_50_0};
SX127xBw bandwidth_;
uint32_t bitrate_;
@@ -200,8 +130,6 @@ class SX127x final : public Component,
bool crc_enable_{false};
bool packet_mode_{false};
bool rx_start_{false};
bool reconfigure_pending_{false};
RadioState state_{RadioState::RADIO_STATE_NEEDS_CONFIGURATION};
};
} // namespace esphome::sx127x
-6
View File
@@ -46,7 +46,6 @@ enum SX127xReg : uint8_t {
REG_PAYLOAD_LENGTH_LSB = 0x32,
REG_FIFO_THRESH = 0x35,
REG_IMAGE_CAL = 0x3B,
REG_IRQ_FLAGS2 = 0x3F,
// LoRa registers
REG_FIFO_ADDR_PTR = 0x0D,
REG_FIFO_TX_BASE_ADDR = 0x0E,
@@ -261,11 +260,6 @@ enum SX127xIrqFlags : uint8_t {
CAD_DETECTED = 0x01,
};
enum SX127xIrqFlags2 : uint8_t {
PACKET_SENT = 0x08,
PAYLOAD_READY = 0x04,
};
enum SX127xModemCfg1 : uint8_t {
BW_7_8 = 0x00,
BW_10_4 = 0x10,
@@ -1,7 +1,6 @@
#include "esphome/core/log.h"
#include "esphome/core/application.h"
#include "uart_transport.h"
#include "esphome/core/helpers.h"
namespace esphome::uart {
@@ -24,7 +23,7 @@ void UARTTransport::loop() {
if (this->rx_started_ && this->receive_buffer_.size() > 6) {
auto len = this->receive_buffer_.size();
auto crc = crc16(this->receive_buffer_.data(), len - 2);
if (crc != encode_value_le<uint16_t>(this->receive_buffer_.data() + len - 2)) {
if (crc != (this->receive_buffer_[len - 2] | (this->receive_buffer_[len - 1] << 8))) {
ESP_LOGD(TAG, "CRC mismatch, discarding packet");
this->rx_started_ = false;
this->receive_buffer_.clear();
+4 -4
View File
@@ -45,9 +45,9 @@ void VBus::loop() {
this->buffer_.push_back(c);
if (this->buffer_.size() == 7) {
this->protocol_ = this->buffer_[4];
this->source_ = encode_value_le<uint16_t>(this->buffer_.data() + 2);
this->dest_ = encode_value_le<uint16_t>(this->buffer_.data());
this->command_ = encode_value_le<uint16_t>(this->buffer_.data() + 5);
this->source_ = (this->buffer_[3] << 8) + this->buffer_[2];
this->dest_ = (this->buffer_[1] << 8) + this->buffer_[0];
this->command_ = (this->buffer_[6] << 8) + this->buffer_[5];
}
if ((this->protocol_ == 0x20) && (this->buffer_.size() == 15)) {
this->state_ = 0;
@@ -56,7 +56,7 @@ void VBus::loop() {
return;
}
septet_spread(this->buffer_.data(), 7, 6, this->buffer_[13]);
uint16_t id = encode_value_le<uint16_t>(this->buffer_.data() + 7);
uint16_t id = (this->buffer_[8] << 8) + this->buffer_[7];
uint32_t value = encode_uint32(this->buffer_[12], this->buffer_[11], this->buffer_[10], this->buffer_[9]);
ESP_LOGV(TAG, "P1 C%04x %04x->%04x: %04x %04" PRIx32 " (%" PRIu32 ")", this->command_, this->source_,
this->dest_, id, value, value);
+1 -36
View File
@@ -220,34 +220,6 @@ EntityMatchResult UrlMatch::match_entity(EntityBase *entity) const {
}
#if !defined(USE_ESP32) && defined(USE_ARDUINO)
// BEGIN ESPAsyncWebServer 3.12.1 workaround: remove once a release containing upstream commit
// 880c97068abb0f0e63f803cd3c0cac84fa5cd7bb is out and we bump to it.
// 3.12.1 creates the SSE client before the head is ACKed and credits the head's ACK to its first queued messages,
// dropping or truncating them. Create the client once the head is ACKed instead, as 3.9.6 did.
class HeadAckedEventSourceResponse final : public AsyncEventSourceResponse {
public:
HeadAckedEventSourceResponse(DeferredUpdateEventSourceList *list, WebServer *ws)
: AsyncEventSourceResponse(nullptr), list_(list), ws_(ws) {}
void _respond(AsyncWebServerRequest *request) override {
String head;
this->_assembleHead(head, request->version());
request->client()->write(head.c_str(), this->_headLength);
}
// Every ACK until clientRelease() is the head's, and clientRelease() unhooks this. _state must stay
// RESPONSE_SETUP: past RESPONSE_WAIT_ACK the request would close its released (null) client after this returns.
size_t _ack(AsyncWebServerRequest *request, size_t len, uint32_t time) override {
this->_ackedLength += len;
if (this->_ackedLength >= this->_headLength)
this->list_->add_client_(this->ws_, request->clientRelease());
return 0;
}
private:
DeferredUpdateEventSourceList *list_;
WebServer *ws_;
};
// END ESPAsyncWebServer 3.12.1 workaround
// helper for allowing only unique entries in the queue
void __attribute__((flatten)) DeferredUpdateEventSource::deq_push_back_with_dedup_(
void *source, message_generator_t *message_generator) {
@@ -356,13 +328,7 @@ void DeferredUpdateEventSourceList::try_send_nodefer(const char *message, size_t
}
}
// BEGIN ESPAsyncWebServer 3.12.1 workaround (see HeadAckedEventSourceResponse): once removed, add_new_client creates
// the source as add_client_ does and ends with es->handleRequest(request); add_client_ goes away.
void DeferredUpdateEventSourceList::add_new_client(WebServer *ws, AsyncWebServerRequest *request) {
request->send(new HeadAckedEventSourceResponse(this, ws)); // NOLINT
}
void DeferredUpdateEventSourceList::add_client_(WebServer *ws, AsyncClient *client) {
DeferredUpdateEventSource *es = new DeferredUpdateEventSource(ws, ESPHOME_F("/events"));
this->push_back(es);
@@ -370,10 +336,9 @@ void DeferredUpdateEventSourceList::add_client_(WebServer *ws, AsyncClient *clie
es->onDisconnect([this, es](AsyncEventSourceClient *client) { this->on_client_disconnect_(es); });
new AsyncEventSourceClient(client, es); // NOLINT: owned by es
es->handleRequest(request);
ws->enable_loop_soon_any_context();
}
// END ESPAsyncWebServer 3.12.1 workaround
void DeferredUpdateEventSourceList::on_client_connect_(DeferredUpdateEventSource *source) {
WebServer *ws = source->web_server_;
@@ -171,12 +171,9 @@ class DeferredUpdateEventSource final : public AsyncEventSource {
};
class DeferredUpdateEventSourceList final : public std::list<DeferredUpdateEventSource *> {
friend class HeadAckedEventSourceResponse; // ESPAsyncWebServer 3.12.1 workaround, remove with it
protected:
void on_client_connect_(DeferredUpdateEventSource *source);
void on_client_disconnect_(DeferredUpdateEventSource *source);
void add_client_(WebServer *ws, AsyncClient *client); // ESPAsyncWebServer 3.12.1 workaround, remove with it
public:
/// Returns true if there are event sources remaining (including pending cleanup).
@@ -132,7 +132,7 @@ async def to_code(config: ConfigType) -> None:
)
cg.add_platformio_option("extra_scripts", ["pre:fix_rp2040_hash.py"])
# https://github.com/ESP32Async/ESPAsyncWebServer/blob/main/library.json
cg.add_library("ESP32Async/ESPAsyncWebServer", "3.12.1")
cg.add_library("ESP32Async/ESPAsyncWebServer", "3.9.6")
# The DNS server used for captive portals on ESP32; other platforms use the Arduino
+6 -3
View File
@@ -32,9 +32,12 @@ bool random_bytes(uint8_t *data, size_t len) {
#ifdef USE_NRF52
void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter)
// The top two bits of a random static address are set
put_be16(mac, NRF_FICR->DEVICEADDR[1] | 0xC000);
put_be32(mac + 2, NRF_FICR->DEVICEADDR[0]);
mac[0] = ((NRF_FICR->DEVICEADDR[1] & 0xFFFF) >> 8) | 0xC0;
mac[1] = NRF_FICR->DEVICEADDR[1] & 0xFFFF;
mac[2] = NRF_FICR->DEVICEADDR[0] >> 24;
mac[3] = NRF_FICR->DEVICEADDR[0] >> 16;
mac[4] = NRF_FICR->DEVICEADDR[0] >> 8;
mac[5] = NRF_FICR->DEVICEADDR[0];
}
#endif
} // namespace esphome
-2
View File
@@ -320,8 +320,6 @@
#define USE_NEXTION_TRIGGER_CUSTOM_SWITCH
#define USE_NEXTION_TRIGGER_CUSTOM_TEXT_SENSOR
#define USE_NEXTION_WAVEFORM
#define USE_NPM1300_DATA_PUBLISHER
#define USE_NPM1300_STATUS_PUBLISHER
#define USE_NUMBER
#define USE_OTA_STATE_LISTENER
#define USE_OUTPUT
+1 -2
View File
@@ -18,6 +18,7 @@ from pathlib import Path
import re
from typing import Any, NamedTuple
from urllib.parse import urlparse
from urllib.request import url2pathname
from esphome import loader, yaml_util
from esphome.components.external_components import ExternalSource, get_sources
@@ -200,8 +201,6 @@ def _esphome_vcs() -> _Source | None:
if commit:
return _Source(strip_url_credentials(url), commit)
if "dir_info" in info and url.startswith("file:"):
from urllib.request import url2pathname
# An editable or local install may be a fork or a patched clone
if (
source := _checkout_vcs(Path(url2pathname(urlparse(url).path)))
+1 -3
View File
@@ -17,6 +17,7 @@ import threading
import time
from typing import IO, TYPE_CHECKING
from urllib.parse import urlparse
from urllib.request import url2pathname
from esphome.helpers import ProgressBar, get_usable_cpu_count, rmtree
from esphome.net_retry import (
@@ -1362,9 +1363,6 @@ def local_path_from_url(url: str) -> Path:
Handles ``file:///home/me/x`` and ``file:///C:/x`` (no host), ``file://localhost/x``
and ``file://server/share/x`` (a UNC path).
"""
# urllib.request loads http.client and the email parser, which config validation does not need
from urllib.request import url2pathname
from esphome.core import EsphomeError
try:
+1 -2
View File
@@ -26,6 +26,7 @@ from pathlib import Path, PurePosixPath
import re
from typing import Any
from urllib.parse import urlsplit, urlunsplit
from urllib.request import url2pathname
from esphome import git
from esphome.core import CORE, EsphomeError, Library
@@ -960,8 +961,6 @@ def _node_key(
f"{scheme}:// library URL '{repository}' must be an absolute "
f"directory path, e.g. {scheme}:///path/to/lib"
)
from urllib.request import url2pathname
path = url2pathname(url_path)
return (name or PurePosixPath(url_path).name), "local", (path, None)
key = str(split_result.path).strip("/").removesuffix(".git")
+4 -4
View File
@@ -125,7 +125,7 @@ lib_deps =
ESP8266WiFi ; wifi (Arduino built-in)
Update ; ota (Arduino built-in)
ESP32Async/ESPAsyncTCP@2.0.0 ; async_tcp
ESP32Async/ESPAsyncWebServer@3.12.1 ; web_server_base
ESP32Async/ESPAsyncWebServer@3.9.6 ; web_server_base
makuna/NeoPixelBus@2.7.3 ; neopixelbus
ESP8266HTTPClient ; http_request (Arduino built-in)
ESP8266mDNS ; mdns (Arduino built-in)
@@ -217,7 +217,7 @@ lib_deps =
${common:arduino.lib_deps}
${common:idf-component-libs.lib_deps}
https://github.com/esphome-libs/RPAsyncTCP.git#1.3.2-esphome.1 ; async_tcp
ESP32Async/ESPAsyncWebServer@3.12.1 ; web_server_base
ESP32Async/ESPAsyncWebServer@3.9.6 ; web_server_base
WiFi ; wifi (arduino-pico built-in)
lwIP_CYW43 ; wifi (arduino-pico built-in, WiFi dependency)
HTTPClient ; http_request (arduino-pico built-in)
@@ -245,10 +245,10 @@ lib_compat_mode = soft
lib_deps =
${common.lib_deps_base}
${common:idf-component-libs.lib_deps}
ESP32Async/ESPAsyncWebServer@3.12.1 ; web_server_base
ESP32Async/ESPAsyncWebServer@3.9.6 ; web_server_base
esphome/wireguard@0.4.8 ; wireguard
esphome/noise-c@0.1.31 ; noise (api, ota)
ESP32Async/AsyncTCP@3.5.0 ; async_tcp
ESP32Async/AsyncTCP@3.4.5 ; async_tcp
DNSServer ; captive_portal
heman/AsyncMqttClient-esphome@2.0.0 ; mqtt
improv/Improv@1.2.7 ; improv_serial
+3
View File
@@ -25,6 +25,8 @@ CORE_BENCHMARKS_DIR: Path = Path(root_path) / "tests" / "benchmarks" / "core"
# allow benchmarks to compile on the host platform.
STUBS_DIR: Path = Path(root_path) / "tests" / "benchmarks" / "stubs"
HELPERS_DIR: Path = Path(root_path) / "tests" / "benchmarks" / "helpers"
BUILD_FLAGS = [
"-Os", # match firmware optimization level (detects inlining regressions)
"-g", # debug symbols for profiling
@@ -32,6 +34,7 @@ BUILD_FLAGS = [
"-fdata-sections", # required for dead-code stripping with -Os
"-DUSE_BENCHMARK", # disable WarnIfComponentBlockingGuard in finish()
f"-I{STUBS_DIR}", # stub headers for ESP32-only components
f"-I{HELPERS_DIR}", # shared test doubles such as fake_uart.h
]
@@ -0,0 +1,76 @@
#include <benchmark/benchmark.h>
#include "esphome/components/binary_sensor/binary_sensor.h"
#include "esphome/components/ld2450/ld2450.h"
#include "esphome/components/sensor/sensor.h"
#include "fake_uart.h"
namespace esphome::ld2450::benchmarks {
using esphome::benchmarks::FakeUART;
// Inner iteration count to amortize CodSpeed instrumentation overhead.
static constexpr int kInnerIterations = 2000;
static constexpr size_t FRAME_SIZE = 30;
// Periodic frames with one moving target at two positions
static constexpr uint8_t FRAME_A[FRAME_SIZE] = {0xAA, 0xFF, 0x03, 0x00, 0x0E, 0x03, 0xB1, 0x86, 0x10, 0x00,
0x40, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xCC};
static constexpr uint8_t FRAME_B[FRAME_SIZE] = {0xAA, 0xFF, 0x03, 0x00, 0x2A, 0x03, 0xC8, 0x86, 0x10, 0x00,
0x40, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xCC};
// --- loop() parsing one periodic frame, no entities attached ---
static void LD2450_PeriodicFrame(benchmark::State &state) {
FakeUART uart;
LD2450Component radar;
radar.set_uart_parent(&uart);
radar.set_link_timeout(60000);
// Bring the link up outside the timed loop
uart.load(FRAME_B, FRAME_SIZE);
radar.loop();
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
uart.load(FRAME_A, FRAME_SIZE);
radar.loop();
}
benchmark::DoNotOptimize(uart.available());
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(LD2450_PeriodicFrame);
// --- loop() parsing a moving target and publishing its sensors ---
static void LD2450_PeriodicFrameSensors(benchmark::State &state) {
FakeUART uart;
LD2450Component radar;
radar.set_uart_parent(&uart);
radar.set_link_timeout(60000);
sensor::Sensor x, y, speed, distance, angle, count;
binary_sensor::BinarySensor presence;
radar.set_move_x_sensor(0, &x);
radar.set_move_y_sensor(0, &y);
radar.set_move_speed_sensor(0, &speed);
radar.set_move_distance_sensor(0, &distance);
radar.set_move_angle_sensor(0, &angle);
radar.set_target_count_sensor(&count);
radar.set_target_binary_sensor(&presence);
uart.load(FRAME_B, FRAME_SIZE);
radar.loop();
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
uart.load((i & 1) ? FRAME_B : FRAME_A, FRAME_SIZE);
radar.loop();
}
benchmark::DoNotOptimize(x.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(LD2450_PeriodicFrameSensors);
} // namespace esphome::ld2450::benchmarks
@@ -0,0 +1,2 @@
sensor:
binary_sensor:
@@ -0,0 +1,63 @@
#include <benchmark/benchmark.h>
#include "esphome/components/modbus/modbus.h"
#include "fake_uart.h"
namespace esphome::modbus::benchmarks {
using esphome::benchmarks::FakeUART;
// Inner iteration count to amortize CodSpeed instrumentation overhead.
static constexpr int kInnerIterations = 2000;
static constexpr uint8_t ADDRESS = 1;
static constexpr uint16_t REGISTER_COUNT = 10;
// Read 10 holding registers from address 0, as an energy meter poll does
static constexpr uint8_t REQUEST_PDU[] = {0x03, 0x00, 0x00, 0x00, REGISTER_COUNT};
// Function 3, byte count 20, 10 registers
static constexpr uint8_t RESPONSE_PDU[] = {0x03, 0x14, 0x09, 0x1F, 0x00, 0x00, 0x01, 0xF4, 0x00, 0x00, 0x13,
0x88, 0x00, 0x32, 0x03, 0xE8, 0x00, 0x00, 0x00, 0x64, 0x12, 0x34};
class SumDevice : public ModbusClientDevice {
public:
using ModbusClientDevice::ModbusClientDevice;
void on_read_holding_registers(uint16_t start_address, std::span<const uint16_t> registers,
ResponseStatus status) override {
for (uint16_t value : registers)
this->sum += value;
}
uint32_t sum{0};
};
class NoDelayHub : public ModbusClientHub {
protected:
// No wait before a send, so every loop() can send the next poll
int32_t tx_delay_remaining() override { return 0; }
};
// --- One continuous poll cycle per loop(): receive, decode and resend ---
static void Modbus_ReadHoldingPollCycle(benchmark::State &state) {
const ModbusFrame response(ADDRESS, RESPONSE_PDU, sizeof(RESPONSE_PDU));
FakeUART uart;
uart.set_baud_rate(9600);
NoDelayHub hub;
hub.set_uart_parent(&uart);
hub.setup();
SumDevice device(&hub, ADDRESS);
hub.queue_pdu(ADDRESS, REQUEST_PDU, &device, {.continuous = true});
// The first loop() sends the poll; every send rewinds the response, so the device answers each one
hub.loop();
uart.load(response.data.data(), response.size());
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
hub.loop();
}
benchmark::DoNotOptimize(device.sum);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(Modbus_ReadHoldingPollCycle);
} // namespace esphome::modbus::benchmarks
@@ -0,0 +1,56 @@
#include <benchmark/benchmark.h>
#include "esphome/components/uart/uart.h"
#include "fake_uart.h"
namespace esphome::uart::benchmarks {
using esphome::benchmarks::FakeUART;
// Inner iteration count to amortize CodSpeed instrumentation overhead.
static constexpr int kInnerIterations = 2000;
// One second of a GPS module's NMEA output
static constexpr char NMEA_BURST[] = "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47\r\n"
"$GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A\r\n"
"$GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39\r\n"
"$GPGSV,2,1,08,01,40,083,46,02,17,308,41,12,07,344,39,14,22,228,45*75\r\n"
"$GPVTG,054.7,T,034.4,M,005.5,N,010.2,K*48\r\n";
// --- read_available(): drain a whole NMEA burst through a byte-sum callback ---
static void UART_ReadAvailable_NmeaBurst(benchmark::State &state) {
FakeUART uart;
UARTDevice dev(&uart);
uint32_t sum = 0;
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
uart.load(reinterpret_cast<const uint8_t *>(NMEA_BURST), sizeof(NMEA_BURST) - 1);
dev.read_available([&](uint8_t b) { sum += b; });
}
benchmark::DoNotOptimize(sum);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(UART_ReadAvailable_NmeaBurst);
// --- discard_available(): drop a 256 byte backlog, two virtual calls per byte ---
static void UART_DiscardAvailable(benchmark::State &state) {
uint8_t backlog[256]{};
FakeUART uart;
UARTDevice dev(&uart);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
uart.load(backlog, sizeof(backlog));
dev.discard_available();
}
benchmark::DoNotOptimize(uart.available());
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(UART_DiscardAvailable);
} // namespace esphome::uart::benchmarks
@@ -0,0 +1,96 @@
#include <benchmark/benchmark.h>
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#include "esphome/core/line_reader.h"
namespace esphome::benchmarks {
// Inner iteration count to amortize CodSpeed instrumentation overhead.
static constexpr int kInnerIterations = 2000;
static constexpr char NMEA_GGA[] = "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47\r\n";
// A 30 byte frame with a 4 byte header and a 2 byte tail
static constexpr uint8_t FRAME_30[30] = {0xAA, 0xFF, 0x03, 0x00, 0x0E, 0x03, 0xB1, 0x86, 0x10, 0x00,
0x40, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xCC};
// Four A02YYUW frames among noise; the doubled 0xFF fails the checksum and resyncs onto the next frame
static constexpr uint8_t ULTRASONIC_NOISY[] = {0x12, 0xFF, 0x07, 0xA1, 0xA7, 0x34, 0xFF, 0xFF, 0x07, 0xA1, 0xA7,
0x00, 0xFF, 0x07, 0xA1, 0xA7, 0x56, 0xFF, 0x07, 0xA1, 0xA7};
// --- LineReader: one GGA sentence fed byte by byte ---
static void LineReader_NmeaLine(benchmark::State &state) {
LineReader<96> reader;
const auto *bytes = reinterpret_cast<const uint8_t *>(NMEA_GGA);
uint32_t lines = 0;
for (auto _ : state) {
benchmark::DoNotOptimize(bytes);
for (int i = 0; i < kInnerIterations; i++) {
for (size_t j = 0; j < sizeof(NMEA_GGA) - 1; j++) {
char *line = reader.feed(bytes[j]);
if (line == nullptr)
continue;
// Keeps the line copy and its NUL write
benchmark::DoNotOptimize(line);
lines++;
}
}
benchmark::DoNotOptimize(lines);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(LineReader_NmeaLine);
// --- FrameReader: a 30 byte frame behind a 4 byte header ---
static void FrameReader_30ByteFrame(benchmark::State &state) {
FrameReader<sizeof(FRAME_30), 0xAA, 0xFF, 0x03, 0x00> reader;
const uint8_t *bytes = FRAME_30;
uint32_t frames = 0;
for (auto _ : state) {
benchmark::DoNotOptimize(bytes);
for (int i = 0; i < kInnerIterations; i++) {
for (size_t j = 0; j < sizeof(FRAME_30); j++) {
if (reader.feed(bytes[j]) != nullptr)
frames++;
}
}
benchmark::DoNotOptimize(frames);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(FrameReader_30ByteFrame);
// --- FrameReader: 4 byte checksummed frames, skipping noise and resyncing on a bad checksum ---
static void FrameReader_UltrasonicNoisy(benchmark::State &state) {
FrameReader<4, 0xFF> reader;
const uint8_t *bytes = ULTRASONIC_NOISY;
uint32_t frames = 0;
for (auto _ : state) {
benchmark::DoNotOptimize(bytes);
for (int i = 0; i < kInnerIterations; i++) {
for (size_t j = 0; j < sizeof(ULTRASONIC_NOISY); j++) {
const uint8_t *frame = reader.feed(bytes[j]);
if (frame == nullptr)
continue;
if (frame[3] == sum_bytes(frame, 3)) {
frames++;
} else {
reader.resync();
}
}
}
benchmark::DoNotOptimize(frames);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(FrameReader_UltrasonicNoisy);
} // namespace esphome::benchmarks
+42
View File
@@ -0,0 +1,42 @@
#pragma once
#include <cstdint>
#include <cstring>
#include "esphome/components/uart/uart_component.h"
namespace esphome::benchmarks {
// Serves a fixed byte stream as received data. Every write rewinds it, so the stream answers each request.
class FakeUART : public uart::UARTComponent {
public:
void load(const uint8_t *data, size_t len) {
this->data_ = data;
this->len_ = len;
this->pos_ = 0;
}
void write_array(const uint8_t *data, size_t len) override { this->pos_ = 0; }
bool peek_byte(uint8_t *data) override {
if (this->pos_ >= this->len_)
return false;
*data = this->data_[this->pos_];
return true;
}
bool read_array(uint8_t *data, size_t len) override {
if (len > this->len_ - this->pos_)
return false;
std::memcpy(data, this->data_ + this->pos_, len);
this->pos_ += len;
return true;
}
size_t available() override { return this->len_ - this->pos_; }
uart::UARTFlushResult flush() override { return uart::UARTFlushResult::UART_FLUSH_RESULT_ASSUMED_SUCCESS; }
void check_logger_conflict() override {}
protected:
const uint8_t *data_{nullptr};
size_t len_{0};
size_t pos_{0};
};
} // namespace esphome::benchmarks
Whitespace-only changes.
@@ -1,20 +0,0 @@
"""LibreTiny always gets the xPortGetCoreID stand-in, whatever its log level."""
from collections.abc import Callable
from pathlib import Path
from esphome.core import CORE
def test_libretiny_adds_core_id_flag(
generate_main: Callable[[str | Path], str], tmp_path: Path
) -> None:
config = tmp_path / "test.yaml"
config.write_text(
"esphome:\n name: test\n\n"
"bk72xx:\n board: generic-bk7231n-qfn32-tuya\n\n"
"wifi:\n ssid: test\n password: testtest12\n\n"
"async_tcp:\n"
)
generate_main(config)
assert "-DxPortGetCoreID=int" in CORE.build_flags
Whitespace-only changes.
@@ -1,114 +0,0 @@
"""Tests for the npm1300 register encoders and validators."""
import pytest
from esphome import config_validation as cv
from esphome.components.const import CONF_ENABLED
from esphome.components.npm1300 import (
CHARGER_SCHEMA,
NPM1300_UNSET,
OUTPUT_VOLTAGE,
VBUS_CURRENT_LIMIT,
_charger_config,
_output_config,
_termination_voltage_code,
_vbus_current_limit_code,
)
from esphome.const import CONF_MODE, CONF_VOLTAGE
from esphome.cpp_generator import StructInitializer
from esphome.types import ConfigType
def _fields(init: StructInitializer) -> dict[str, str]:
return {key: str(value) for key, value in init.args.items()}
def _charger(config: ConfigType) -> dict[str, str]:
return _fields(_charger_config(CHARGER_SCHEMA(config)))
@pytest.mark.parametrize(
("current", "code"), [("32mA", 16), ("150mA", 75), ("800mA", 400)]
)
def test_charge_current_code(current: str, code: int) -> None:
assert _charger({"charge_current": current})["current"] == str(code)
@pytest.mark.parametrize("current", ["30mA", "802mA", "151mA"])
def test_charge_current_rejected(current: str) -> None:
with pytest.raises(cv.Invalid):
CHARGER_SCHEMA({"charge_current": current})
@pytest.mark.parametrize(
("voltage", "code"),
[(3.5, 0), (3.65, 3), (4.0, 4), (4.2, 8), (4.45, 13)],
)
def test_termination_voltage_code(voltage: float, code: int) -> None:
assert _termination_voltage_code(voltage) == code
@pytest.mark.parametrize("voltage", ["3.7V", "3.95V", "4.5V"])
def test_termination_voltage_gap_rejected(voltage: str) -> None:
with pytest.raises(cv.Invalid):
CHARGER_SCHEMA({"charge_current": "100mA", "termination_voltage": voltage})
def test_warm_termination_defaults_to_termination() -> None:
fields = _charger({"charge_current": "100mA", "termination_voltage": "4.1V"})
assert fields["termination_voltage"] == "6"
assert fields["warm_termination_voltage"] == "6"
def test_warm_termination_code() -> None:
fields = _charger(
{
"charge_current": "100mA",
"termination_voltage": "4.2V",
"warm_termination_voltage": "3.6V",
}
)
assert fields["termination_voltage"] == "8"
assert fields["warm_termination_voltage"] == "2"
@pytest.mark.parametrize(("voltage", "code"), [("1.0V", 0), ("1.8V", 8), ("3.3V", 23)])
def test_output_voltage_code(voltage: str, code: int) -> None:
config = {CONF_VOLTAGE: OUTPUT_VOLTAGE(voltage)}
assert _fields(_output_config(config))["voltage"] == str(code)
@pytest.mark.parametrize("voltage", ["0.9V", "3.4V", "1.85V"])
def test_output_voltage_rejected(voltage: str) -> None:
with pytest.raises(cv.Invalid):
OUTPUT_VOLTAGE(voltage)
@pytest.mark.parametrize("config", [None, {}])
def test_unset_output_fields(config: ConfigType | None) -> None:
unset = str(NPM1300_UNSET)
assert _fields(_output_config(config)) == {
"voltage": unset,
"ldo_mode": unset,
"enabled": unset,
}
def test_output_mode_and_enabled() -> None:
fields = _fields(_output_config({CONF_MODE: "load_switch", CONF_ENABLED: True}))
assert fields["ldo_mode"] == "0"
assert fields["enabled"] == "1"
assert fields["voltage"] == str(NPM1300_UNSET)
@pytest.mark.parametrize(
("limit", "code"), [("100mA", 1), ("300mA", 3), ("500mA", 5), ("1.5A", 15)]
)
def test_vbus_current_limit_code(limit: str, code: int) -> None:
assert _vbus_current_limit_code(VBUS_CURRENT_LIMIT(limit)) == code
@pytest.mark.parametrize("limit", ["50mA", "1600mA", "550mA"])
def test_vbus_current_limit_rejected(limit: str) -> None:
with pytest.raises(cv.Invalid):
VBUS_CURRENT_LIMIT(limit)
-6
View File
@@ -1,6 +0,0 @@
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
# touchscreen.h includes display.h
manifest.dependencies = manifest.dependencies + ["display"]
-50
View File
@@ -1,50 +0,0 @@
#pragma once
#include <algorithm>
#include <cstring>
#include <map>
#include <vector>
#include "esphome/components/cst3240/touchscreen/cst3240_touchscreen.h"
#include "esphome/core/helpers.h"
namespace esphome::cst3240::testing {
struct Write {
uint16_t reg;
size_t size;
};
// Answers 16-bit register reads from a map; every write succeeds and is recorded.
class RegisterBus final : public i2c::I2CBus {
public:
std::map<uint16_t, std::vector<uint8_t>> registers;
std::vector<Write> writes;
i2c::ErrorCode write_readv(uint8_t address, const uint8_t *data, size_t size, uint8_t *out,
size_t out_size) override {
if (size < 2)
return i2c::ERROR_NOT_ACKNOWLEDGED;
const uint16_t reg = encode_uint16(data[0], data[1]);
if (out_size == 0) {
this->writes.push_back({reg, size});
return i2c::ERROR_OK;
}
auto &value = this->registers[reg];
value.resize(std::max(value.size(), out_size));
std::memcpy(out, value.data(), out_size);
return i2c::ERROR_OK;
}
// Lists `count` fingers with ids 0..count-1, each with the given event bits.
void set_report(uint8_t count, uint8_t sync = cstxxx::SYNC_BYTE, uint8_t event = TOUCH_EVENT_PRESSED) {
std::vector<uint8_t> data(CST3240_REPORT_SIZE);
for (uint8_t i = 0; i < std::min(count, CST3240_MAX_TOUCHES); i++)
data[i * 5 + (i == 0 ? 0 : 2)] = i << 4 | event;
data[cstxxx::FINGER_COUNT_IDX] = count;
data[cstxxx::SYNC_IDX] = sync;
this->registers[cstxxx::REG_TOUCH_DATA] = data;
}
};
} // namespace esphome::cst3240::testing
-18
View File
@@ -1,18 +0,0 @@
display:
- platform: ssd1306_i2c
i2c_id: i2c_bus
id: cst3240_ssd1306_i2c_display
model: SSD1306_128X64
reset_pin: ${display_reset_pin}
pages:
- id: cst3240_page1
lambda: |-
it.rectangle(0, 0, it.get_width(), it.get_height());
touchscreen:
- platform: cst3240
i2c_id: i2c_bus
id: cst3240_touchscreen
display: cst3240_ssd1306_i2c_display
interrupt_pin: ${interrupt_pin}
reset_pin: ${reset_pin}
@@ -1,8 +0,0 @@
substitutions:
display_reset_pin: "4"
interrupt_pin: "20"
reset_pin: "21"
packages:
i2c: !include ../../test_build_components/common/i2c/esp32-idf.yaml
cst3240: !include common.yaml
@@ -1,103 +0,0 @@
#include <gtest/gtest.h>
#include "esphome/components/cst3240/touchscreen/cst3240_touchscreen.h"
#include "esphome/core/gpio.h"
#include "../common.h"
namespace esphome::cst3240::testing {
class TestableCST3240 : public CST3240Touchscreen {
public:
using CST3240Touchscreen::chip_id_;
using CST3240Touchscreen::is_touched_;
using CST3240Touchscreen::setup_complete_;
using CST3240Touchscreen::skip_update_;
using CST3240Touchscreen::update_touches;
using CST3240Touchscreen::x_raw_max_;
using CST3240Touchscreen::y_raw_max_;
};
class CST3240Test : public ::testing::Test {
protected:
void SetUp() override {
this->bus_.registers[cstxxx::REG_CHIP_INFO] = {0x01, 0x00, 0x40, 0x32};
this->bus_.registers[cstxxx::REG_RESOLUTION] = {0x40, 0x01, 0xF0, 0x00};
this->hub_.set_i2c_bus(&this->bus_);
this->hub_.setup();
this->bus_.writes.clear();
}
void update_() {
this->hub_.skip_update_ = false;
this->hub_.is_touched_ = false;
this->hub_.update_touches();
}
bool cleared_() const {
return this->bus_.writes.size() == 1 && this->bus_.writes[0].reg == cstxxx::REG_TOUCH_DATA &&
this->bus_.writes[0].size == 2u + CST3240_REPORT_SIZE;
}
RegisterBus bus_;
TestableCST3240 hub_;
};
TEST_F(CST3240Test, SetupReadsTheChipAndResolutionWithoutAFirmwareCheck) {
EXPECT_TRUE(this->hub_.setup_complete_);
EXPECT_FALSE(this->hub_.is_failed());
EXPECT_EQ(this->hub_.chip_id_, CST3240_CHIP_ID);
EXPECT_EQ(this->hub_.x_raw_max_, 320);
EXPECT_EQ(this->hub_.y_raw_max_, 240);
}
TEST_F(CST3240Test, ReportWithoutTheSyncByteIsSkippedAndCleared) {
this->bus_.set_report(1, 0x55);
this->update_();
EXPECT_TRUE(this->hub_.skip_update_);
EXPECT_FALSE(this->hub_.is_touched_);
EXPECT_TRUE(this->cleared_());
}
TEST_F(CST3240Test, IdleBlockIsNotRewritten) {
this->bus_.set_report(0, 0);
this->update_();
EXPECT_TRUE(this->hub_.skip_update_);
EXPECT_TRUE(this->bus_.writes.empty());
}
TEST_F(CST3240Test, ReleasedRecordIsNotATouch) {
this->bus_.set_report(1, cstxxx::SYNC_BYTE, 0);
this->update_();
EXPECT_FALSE(this->hub_.skip_update_);
EXPECT_FALSE(this->hub_.is_touched_);
EXPECT_TRUE(this->hub_.get_touches().empty());
}
TEST_F(CST3240Test, PollingClearsTheReport) {
this->bus_.set_report(1);
this->update_();
EXPECT_TRUE(this->hub_.is_touched_);
EXPECT_TRUE(this->cleared_());
}
TEST_F(CST3240Test, InterruptAcknowledgesTheReport) {
InternalGPIOPin pin;
this->hub_.set_interrupt_pin(&pin);
this->bus_.set_report(1);
this->update_();
ASSERT_EQ(this->bus_.writes.size(), 2u);
EXPECT_EQ(this->bus_.writes[0].reg, cstxxx::REG_FINGER_COUNT);
EXPECT_EQ(this->bus_.writes[1].reg, cstxxx::REG_TOUCH_DATA);
EXPECT_EQ(this->bus_.writes[1].size, 3u);
}
TEST_F(CST3240Test, ReportsUpToFiveFingers) {
this->bus_.set_report(5);
this->update_();
EXPECT_EQ(this->hub_.get_touches().size(), 5u);
this->bus_.set_report(6);
this->update_();
EXPECT_FALSE(this->hub_.is_touched_);
}
} // namespace esphome::cst3240::testing
@@ -1,71 +0,0 @@
#include <gtest/gtest.h>
#include <vector>
#include "esphome/components/i2c/i2c.h"
namespace esphome::i2c::testing {
// A bus that only implements write_readv(), like external buses, so write_prefixed() takes the default path
class JoiningBus : public I2CBus {
public:
std::vector<uint8_t> written;
ErrorCode write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
size_t read_count) override {
this->written.assign(write_buffer, write_buffer + write_count);
return ERROR_OK;
}
};
// A bus that takes the two parts separately, like the built-in buses
class GatherBus final : public JoiningBus {
public:
std::vector<uint8_t> prefix;
std::vector<uint8_t> data;
const uint8_t *data_ptr{nullptr};
ErrorCode write_prefixed(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *data,
size_t len) override {
this->prefix.assign(prefix, prefix + prefix_len);
this->data.assign(data, data + len);
this->data_ptr = data;
return ERROR_OK;
}
};
static std::vector<uint8_t> pattern(size_t len) {
std::vector<uint8_t> bytes(len);
for (size_t i = 0; i < len; i++)
bytes[i] = static_cast<uint8_t>(i * 7 + 1);
return bytes;
}
TEST(I2CWritePrefixed, DefaultJoinsPrefixAndDataForShortAndLongWrites) {
// 18 data bytes fit the stack buffer with a 2-byte prefix; 300 need the heap fallback
for (size_t len : {0, 1, 18, 19, 300}) {
JoiningBus bus;
const uint8_t prefix[2] = {0xAB, 0xCD};
const std::vector<uint8_t> data = pattern(len);
EXPECT_EQ(bus.write_prefixed(0x10, prefix, sizeof(prefix), data.data(), data.size()), ERROR_OK);
std::vector<uint8_t> expected{0xAB, 0xCD};
expected.insert(expected.end(), data.begin(), data.end());
EXPECT_EQ(bus.written, expected) << "length " << len;
}
}
TEST(I2CWritePrefixed, WriteRegisterPassesTheRegisterAsPrefixWithoutCopyingTheData) {
GatherBus bus;
I2CDevice device;
device.set_i2c_bus(&bus);
device.set_i2c_address(0x10);
const std::vector<uint8_t> data = pattern(64);
EXPECT_EQ(device.write_register(0x5E, data.data(), data.size()), ERROR_OK);
EXPECT_EQ(bus.prefix, std::vector<uint8_t>{0x5E});
EXPECT_EQ(bus.data, data);
EXPECT_EQ(bus.data_ptr, data.data());
EXPECT_EQ(device.write_register16(0x1234, data.data(), data.size()), ERROR_OK);
EXPECT_EQ(bus.prefix, (std::vector<uint8_t>{0x12, 0x34}));
EXPECT_EQ(bus.data_ptr, data.data());
}
} // namespace esphome::i2c::testing
-84
View File
@@ -1,84 +0,0 @@
npm1300:
id: pmic
i2c_id: i2c_bus
vbus_current_limit: 500mA
thermistor_resistance: 10kOhm
thermistor_beta: 3380
charger:
charge_current: 150mA
termination_voltage: 4.2V
warm_termination_voltage: 4.0V
termination_current: 20%
trickle_voltage: 2.5V
discharge_current_limit: 1000mA
recharge: true
buck2:
voltage: 3.3V
ldo1:
voltage: 3.3V
mode: ldo
enabled: true
ldo2:
mode: load_switch
enabled: false
sensor:
- platform: npm1300
battery_voltage:
name: Battery Voltage
battery_current:
name: Battery Current
battery_temperature:
name: Battery Temperature
die_temperature:
name: PMIC Temperature
system_voltage:
name: System Voltage
vbus_voltage:
name: VBUS Voltage
vbus_current_limit:
name: VBUS Current Limit
binary_sensor:
- platform: npm1300
vbus_present:
name: VBUS Present
vbus_current_limit_active:
name: VBUS Current Limit Active
charging:
name: Charging
charge_complete:
name: Charge Complete
charger_error:
name: Charger Error
text_sensor:
- platform: npm1300
charger_status:
name: Charger Status
switch:
- platform: npm1300
charger:
name: Charger
buck1:
name: BUCK1
ldo1:
name: LDO1
ldo2:
name: LDO2
button:
- platform: template
name: Ship Mode
on_press:
- npm1300.enter_ship_mode: pmic
- platform: template
name: Hibernate
on_press:
- npm1300.hibernate:
id: pmic
duration: 1h
- npm1300.hibernate:
id: pmic
duration: !lambda return 60000;
@@ -1,3 +0,0 @@
packages:
i2c: !include ../../test_build_components/common/i2c/esp32-idf.yaml
npm1300: !include common.yaml
-3
View File
@@ -1,3 +0,0 @@
packages:
i2c: !include ../../test_build_components/common/i2c/host.yaml
npm1300: !include common.yaml
@@ -1,3 +0,0 @@
packages:
i2c: !include ../../test_build_components/common/i2c/nrf52.yaml
npm1300: !include common.yaml
-16
View File
@@ -1,16 +0,0 @@
"""Build the SX127x C++ tests against a software SPI bus, with real logger callbacks."""
import esphome.codegen as cg
from esphome.components.logger import request_log_listener
from esphome.types import ConfigType
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
async def to_code(config: ConfigType) -> None:
request_log_listener()
# The tests build a software SPI bus in C++, which no configured bus asks for
cg.add_define("USE_SPI_SOFTWARE")
manifest.multi_conf = False
manifest.to_code = to_code
@@ -1,347 +0,0 @@
#include "sx127x_test_helpers.h"
#include <cmath>
#include <tuple>
namespace esphome::sx127x::testing {
static std::vector<uint8_t> expected_fifo(const RadioHardware &hw, bool lora, bool fixed) {
std::vector<uint8_t> fifo;
if (!lora && !fixed) {
fifo.push_back(hw.packet.size()); // A variable length FSK packet starts with its length
}
fifo.insert(fifo.end(), hw.packet.begin(), hw.packet.end());
return fifo;
}
class SX127xAsyncModes : public ::testing::TestWithParam<std::tuple<bool, bool, bool>> {};
TEST_P(SX127xAsyncModes, ReturnsBeforeCompletionAndRestoresMode) {
const auto [lora, rx, fixed] = GetParam();
RadioHardware hw;
TransmitListener listener;
hw.configure(lora, rx, fixed);
ASSERT_FALSE(hw.radio.is_failed());
hw.auto_complete = false;
ASSERT_EQ(hw.radio.start_transmit_async(&listener, hw.packet, 1234), SX127xError::SX127X_ERROR_NONE);
EXPECT_TRUE(hw.radio.is_transmitting());
EXPECT_EQ(hw.mode(), MODE_TX);
ASSERT_EQ(hw.sent.size(), 1u);
EXPECT_EQ(hw.sent[0], expected_fifo(hw, lora, fixed));
hw.radio.loop();
EXPECT_TRUE(listener.results.empty());
hw.complete_send();
hw.radio.loop();
EXPECT_EQ(listener.results, std::vector<SX127xError>{SX127xError::SX127X_ERROR_NONE});
EXPECT_FALSE(hw.radio.is_transmitting());
EXPECT_EQ(hw.mode(), rx ? MODE_RX : MODE_SLEEP);
if (lora) {
EXPECT_EQ(hw.irq, 0); // TX_DONE is cleared, so DIO0 is low again
}
}
TEST_P(SX127xAsyncModes, BlockingSendWaitsForCompletion) {
const auto [lora, rx, fixed] = GetParam();
RadioHardware hw;
hw.configure(lora, rx, fixed);
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX127xError::SX127X_ERROR_NONE);
EXPECT_FALSE(hw.radio.is_transmitting());
ASSERT_EQ(hw.sent.size(), 1u);
EXPECT_EQ(hw.sent[0], expected_fifo(hw, lora, fixed));
EXPECT_EQ(hw.mode(), rx ? MODE_RX : MODE_SLEEP);
}
INSTANTIATE_TEST_SUITE_P(Modes, SX127xAsyncModes,
::testing::Combine(::testing::Bool(), ::testing::Bool(), ::testing::Bool()));
// Modulation and fixed length; only a receiving radio has a packet waiting
class SX127xHeldPacket : public ::testing::TestWithParam<std::tuple<bool, bool>> {};
TEST_P(SX127xHeldPacket, PacketWaitingWhenASendStartsIsDeliveredFirst) {
const auto [lora, fixed] = GetParam();
const bool rx = true;
RadioHardware hw;
PacketListener packets;
TransmitListener listener;
hw.radio.register_listener(&packets);
hw.configure(lora, rx, fixed);
hw.receive({0x44, 0x55, 0x66});
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX127xError::SX127X_ERROR_BUSY);
EXPECT_TRUE(hw.sent.empty());
hw.radio.set_mode_sleep(); // Ignored while the packet is held
EXPECT_EQ(hw.mode(), MODE_STDBY);
hw.radio.loop();
ASSERT_EQ(packets.packets.size(), 1u);
EXPECT_EQ(packets.packets[0], (std::vector<uint8_t>{0x44, 0x55, 0x66}));
EXPECT_TRUE(hw.receiving());
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX127xError::SX127X_ERROR_NONE);
hw.radio.loop();
EXPECT_EQ(listener.results, std::vector<SX127xError>{SX127xError::SX127X_ERROR_NONE});
EXPECT_EQ(hw.sent.size(), 1u);
}
INSTANTIATE_TEST_SUITE_P(Modes, SX127xHeldPacket, ::testing::Combine(::testing::Bool(), ::testing::Bool()));
TEST(SX127xAsync, OneSendAtATime) {
RadioHardware hw;
TransmitListener first, second;
hw.configure(true, true);
hw.auto_complete = false;
ASSERT_EQ(hw.radio.start_transmit_async(&first, hw.packet), SX127xError::SX127X_ERROR_NONE);
EXPECT_EQ(hw.radio.start_transmit_async(&second, hw.packet), SX127xError::SX127X_ERROR_BUSY);
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX127xError::SX127X_ERROR_BUSY);
hw.radio.set_mode_rx();
hw.radio.run_image_cal();
hw.radio.configure();
EXPECT_EQ(hw.mode(), MODE_TX);
EXPECT_EQ(hw.sent.size(), 1u);
hw.complete_send();
hw.radio.loop();
EXPECT_EQ(first.results, std::vector<SX127xError>{SX127xError::SX127X_ERROR_NONE});
EXPECT_TRUE(second.results.empty());
}
TEST(SX127xAsync, SendWithoutCompletionTimesOut) {
RadioHardware hw;
TransmitListener listener;
hw.configure(true, true);
hw.auto_complete = false;
const uint32_t start = millis();
ASSERT_EQ(hw.radio.start_transmit_async(&listener, hw.packet, 1000), SX127xError::SX127X_ERROR_NONE);
{
LoopBlockingGuard clock{nullptr, nullptr, start + 500};
hw.radio.loop();
}
EXPECT_TRUE(listener.results.empty());
{
LoopBlockingGuard clock{nullptr, nullptr, start + 1100};
hw.radio.loop();
}
EXPECT_EQ(listener.results, std::vector<SX127xError>{SX127xError::SX127X_ERROR_TIMEOUT});
EXPECT_FALSE(hw.radio.status_has_warning());
EXPECT_TRUE(hw.receiving());
}
// The chip leaves a send that is still going out for standby or sleep, but not for RX
class SX127xCancel : public ::testing::TestWithParam<std::tuple<bool, bool>> {};
TEST_P(SX127xCancel, CancelEndsOnlyTheListenersOwnSend) {
const auto [lora, rx] = GetParam();
RadioHardware hw;
TransmitListener owner, other;
hw.configure(lora, rx);
hw.auto_complete = false;
ASSERT_EQ(hw.radio.start_transmit_async(&owner, hw.packet), SX127xError::SX127X_ERROR_NONE);
EXPECT_FALSE(hw.radio.cancel_transmit_async(&other));
EXPECT_FALSE(hw.radio.cancel_transmit_async(nullptr));
EXPECT_TRUE(hw.radio.cancel_transmit_async(&owner));
EXPECT_EQ(owner.results, std::vector<SX127xError>{SX127xError::SX127X_ERROR_CANCELLED});
EXPECT_FALSE(hw.radio.is_transmitting());
EXPECT_FALSE(hw.radio.status_has_warning());
EXPECT_EQ(hw.mode(), rx ? MODE_RX : MODE_SLEEP);
EXPECT_FALSE(hw.radio.cancel_transmit_async(&owner));
hw.radio.loop();
EXPECT_EQ(owner.results.size(), 1u);
EXPECT_TRUE(other.results.empty());
}
INSTANTIATE_TEST_SUITE_P(Modes, SX127xCancel, ::testing::Combine(::testing::Bool(), ::testing::Bool()));
TEST(SX127xAsync, CompletionMayStartTheNextSend) {
RadioHardware hw;
TransmitListener listener;
hw.configure(true, true);
listener.on_complete = [&](SX127xError result) {
if (listener.results.size() == 1) {
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX127xError::SX127X_ERROR_NONE);
}
};
ASSERT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX127xError::SX127X_ERROR_NONE);
hw.radio.loop();
EXPECT_TRUE(hw.radio.is_transmitting());
hw.radio.loop();
EXPECT_EQ(listener.results.size(), 2u);
EXPECT_EQ(hw.sent.size(), 2u);
EXPECT_TRUE(hw.receiving());
}
TEST(SX127xAsync, PacketListenerMaySend) {
RadioHardware hw;
PacketListener packets;
hw.radio.register_listener(&packets);
hw.configure(true, true);
packets.on_receive = [&]() { EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX127xError::SX127X_ERROR_NONE); };
hw.receive({0x01, 0x02});
hw.radio.loop();
EXPECT_EQ(packets.packets.size(), 1u);
EXPECT_EQ(hw.sent.size(), 1u);
EXPECT_TRUE(hw.receiving());
}
TEST(SX127xAsync, InvalidRequestsAreRefused) {
RadioHardware hw;
TransmitListener listener;
hw.configure(true, true, true);
EXPECT_EQ(hw.radio.start_transmit_async(nullptr, hw.packet), SX127xError::SX127X_ERROR_INVALID_PARAMS);
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet, 0), SX127xError::SX127X_ERROR_INVALID_PARAMS);
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet, 262144), SX127xError::SX127X_ERROR_INVALID_PARAMS);
EXPECT_EQ(hw.radio.start_transmit_async(&listener, nullptr, 3), SX127xError::SX127X_ERROR_INVALID_PARAMS);
EXPECT_EQ(hw.radio.transmit_packet(hw.packet.data(), 0), SX127xError::SX127X_ERROR_INVALID_PARAMS);
EXPECT_EQ(hw.radio.transmit_packet(hw.packet.data(), 2), SX127xError::SX127X_ERROR_INVALID_PARAMS);
EXPECT_TRUE(hw.sent.empty());
EXPECT_TRUE(listener.results.empty());
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX127xError::SX127X_ERROR_NONE);
}
TEST(SX127xAsync, SendWithoutDio0IsRefused) {
RadioHardware hw;
hw.radio.set_dio0_pin(nullptr);
hw.configure(true, true);
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX127xError::SX127X_ERROR_INVALID_PARAMS);
EXPECT_TRUE(hw.sent.empty());
}
TEST(SX127xReceive, LoRaPacketHasRssiAndSnr) {
RadioHardware hw;
PacketListener packets;
hw.radio.register_listener(&packets);
hw.configure(true, true);
hw.receive({0x01, 0x02, 0x03, 0x04});
hw.radio.loop();
ASSERT_EQ(packets.packets.size(), 1u);
EXPECT_EQ(packets.packets[0], (std::vector<uint8_t>{0x01, 0x02, 0x03, 0x04}));
EXPECT_FLOAT_EQ(packets.rssi, 100.0f - 164.0f);
EXPECT_FLOAT_EQ(packets.snr, 5.0f);
EXPECT_EQ(hw.irq, 0);
}
TEST(SX127xReceive, FskPacketHasNoSnr) {
RadioHardware hw;
PacketListener packets;
hw.radio.register_listener(&packets);
hw.configure(false, true);
hw.receive({0x01, 0x02, 0x03, 0x04});
hw.radio.loop();
ASSERT_EQ(packets.packets.size(), 1u);
EXPECT_EQ(packets.packets[0], (std::vector<uint8_t>{0x01, 0x02, 0x03, 0x04}));
EXPECT_TRUE(std::isnan(packets.snr));
}
TEST(SX127xReceive, PacketThatFailedItsCrcIsDroppedAndDoesNotHoldUpASend) {
RadioHardware hw;
PacketListener packets;
hw.radio.register_listener(&packets);
hw.configure(true, true);
hw.receive({0x01}, true);
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX127xError::SX127X_ERROR_NONE);
hw.radio.loop();
EXPECT_TRUE(packets.packets.empty());
}
// The TX mode action sends whatever the FIFO holds without tracking it; its completion
// is not taken for a received packet
TEST(SX127xReceive, RawTxModeIsNotAPacket) {
for (const bool lora : {true, false}) {
RadioHardware hw;
PacketListener packets;
hw.radio.register_listener(&packets);
hw.configure(lora, true);
hw.radio.set_mode_tx();
EXPECT_EQ(hw.mode(), MODE_TX);
EXPECT_TRUE(hw.dio0.digital_read());
hw.radio.loop();
EXPECT_TRUE(packets.packets.empty()) << (lora ? "LoRa" : "FSK");
hw.radio.set_mode_rx();
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX127xError::SX127X_ERROR_NONE);
}
}
TEST(SX127xRecovery, FailedModeChangeIsReconfiguredWithoutBeingAsked) {
RadioHardware hw;
hw.configure(true, true);
hw.stuck = true;
hw.radio.set_mode_standby();
EXPECT_FALSE(hw.radio.is_failed());
EXPECT_TRUE(hw.radio.status_has_warning());
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX127xError::SX127X_ERROR_NOT_READY);
hw.radio.set_mode_sleep(); // Ignored until configured again
hw.stuck = false;
EXPECT_EQ(hw.mode(), MODE_RX);
run_scheduler(1100);
EXPECT_FALSE(hw.radio.status_has_warning());
EXPECT_TRUE(hw.receiving());
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX127xError::SX127X_ERROR_NONE);
// Once configured, the retry stops
hw.radio.set_mode_sleep();
run_scheduler(1100);
EXPECT_EQ(hw.mode(), MODE_SLEEP);
}
TEST(SX127xRecovery, FailedSendStartIsReconfiguredWithoutBeingAsked) {
RadioHardware hw;
TransmitListener listener;
hw.configure(true, true);
hw.stuck = true;
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX127xError::SX127X_ERROR_NOT_READY);
EXPECT_FALSE(hw.radio.is_transmitting());
EXPECT_TRUE(listener.results.empty());
hw.stuck = false;
run_scheduler(1100);
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX127xError::SX127X_ERROR_NONE);
}
TEST(SX127xRecovery, UnsupportedChipFailsSetup) {
RadioHardware hw;
hw.version = 0x22;
hw.configure(true, true);
EXPECT_TRUE(hw.radio.is_failed());
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX127xError::SX127X_ERROR_NOT_READY);
}
TEST(SX127xRecovery, NothingHappensBeforeSetup) {
RadioHardware hw;
unsigned resets = 0;
hw.rst.on_write = [&](bool high) { resets += high ? 0 : 1; };
hw.radio.configure();
hw.radio.set_mode_rx();
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX127xError::SX127X_ERROR_NOT_READY);
EXPECT_EQ(resets, 0u);
EXPECT_EQ(hw.mode(), MODE_STDBY);
}
} // namespace esphome::sx127x::testing
namespace esphome::sx127x::testing {
// configure() is refused during a send, so settings changed then are not used until it succeeds
TEST(SX127xSettings, SettingsChangedDuringASendWaitForConfigure) {
RadioHardware hw;
TransmitListener listener;
PacketListener packets;
hw.radio.register_listener(&packets);
hw.configure(false, true, true);
hw.auto_complete = false;
ASSERT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX127xError::SX127X_ERROR_NONE);
hw.radio.set_payload_length(4);
hw.radio.set_rx_start(false);
hw.radio.set_modulation(MOD_LORA);
hw.radio.configure(); // Refused: a send is on air
hw.complete_send();
hw.radio.loop();
EXPECT_EQ(listener.results, std::vector<SX127xError>{SX127xError::SX127X_ERROR_NONE});
EXPECT_TRUE(hw.receiving()); // Still the applied rx_start
EXPECT_FALSE(hw.lora());
EXPECT_EQ(hw.radio.get_max_packet_size(), 3u);
const std::vector<uint8_t> four{0x01, 0x02, 0x03, 0x04};
EXPECT_EQ(hw.radio.transmit_packet(four), SX127xError::SX127X_ERROR_INVALID_PARAMS);
hw.receive({0x07, 0x08, 0x09});
hw.radio.loop();
ASSERT_EQ(packets.packets.size(), 1u);
EXPECT_EQ(packets.packets[0], (std::vector<uint8_t>{0x07, 0x08, 0x09}));
// Once applied, they are used
hw.radio.configure();
EXPECT_TRUE(hw.lora());
EXPECT_EQ(hw.mode(), MODE_SLEEP);
EXPECT_EQ(hw.radio.get_max_packet_size(), 4u);
}
} // namespace esphome::sx127x::testing
@@ -1,54 +0,0 @@
#include "sx127x_test_helpers.h"
#include "esphome/components/logger/logger.h"
#include <string>
namespace esphome::sx127x::testing {
// Runs a callback for each warning logged, as a logger on_message automation would
class LogCallback {
public:
LogCallback() : previous_(logger::global_logger) {
this->logger_.pre_setup();
this->logger_.set_log_level(ESPHOME_LOG_LEVEL_WARN);
this->logger_.add_log_callback(this,
[](void *instance, uint8_t level, const char *tag, const char *message, size_t len) {
auto *self = static_cast<LogCallback *>(instance);
if (self->callback_) {
self->callback_(std::string(message, len));
}
});
}
~LogCallback() { logger::global_logger = this->previous_; }
void set_callback(std::function<void(const std::string &)> callback) { this->callback_ = std::move(callback); }
private:
std::function<void(const std::string &)> callback_;
logger::Logger *previous_;
logger::Logger logger_{0};
};
// A configure() from the warning's log callback recovers the radio, and no retry is left
// behind to reset it again later
TEST(SX127xReentry, ConfigureFromTheFailureWarningLeavesNoRetry) {
RadioHardware hw;
LogCallback log;
hw.configure(true, true);
bool reentered = false;
log.set_callback([&](const std::string &message) {
if (!reentered && message.find("set Warning flag") != std::string::npos) {
reentered = true;
hw.stuck = false;
hw.radio.configure();
}
});
hw.stuck = true;
hw.radio.set_mode_standby();
ASSERT_TRUE(reentered);
EXPECT_FALSE(hw.radio.status_has_warning());
EXPECT_TRUE(hw.receiving());
hw.radio.set_mode_sleep();
run_scheduler(1100);
EXPECT_EQ(hw.mode(), MODE_SLEEP);
}
} // namespace esphome::sx127x::testing
@@ -1,330 +0,0 @@
#pragma once
#include <gtest/gtest.h>
#include <array>
#include <functional>
#include <vector>
#include "esphome/components/sx127x/sx127x.h"
#include "esphome/core/application.h"
namespace esphome::sx127x::testing {
class TestPin : public GPIOPin {
public:
void setup() override {}
void pin_mode(gpio::Flags flags) override {}
gpio::Flags get_flags() const override { return gpio::FLAG_NONE; }
size_t dump_summary(char *buffer, size_t len) const override { return snprintf(buffer, len, "test"); }
bool digital_read() override { return this->on_read ? this->on_read() : this->level; }
void digital_write(bool level) override {
this->level = level;
if (this->on_write) {
this->on_write(level);
}
}
bool level{false};
std::function<bool()> on_read;
std::function<void(bool)> on_write;
};
// An SX127x register file behind the real software SPI bus. The first byte of each
// transaction is the address, with bit 7 set for a write; FIFO reads and writes stream.
class RadioHardware {
public:
RadioHardware() {
this->reset_();
this->cs.level = true;
this->cs.on_write = [this](bool high) {
if (!high) {
this->selected_ = true;
this->pos_ = 0;
this->bit_ = 0;
this->byte_ = 0;
} else {
this->selected_ = false;
}
};
this->miso.on_read = [this]() {
EXPECT_TRUE(this->selected_);
if (this->bit_ == 0) {
this->reply_ = this->reply_byte_();
}
const bool bit = (this->reply_ >> (7 - this->bit_)) & 1;
this->byte_ = (this->byte_ << 1) | this->mosi.level;
if (++this->bit_ == 8) {
this->byte_done_(this->byte_);
this->byte_ = 0;
this->bit_ = 0;
this->pos_++;
}
return bit;
};
this->dio0.on_read = [this]() {
this->finish_pending_send_();
return this->dio0_level();
};
this->rst.on_write = [this](bool high) {
if (!high) {
this->reset_();
}
};
this->spi.set_clk(&this->clk);
this->spi.set_mosi(&this->mosi);
this->spi.set_miso(&this->miso);
// call() runs setup() and marks the bus set up, so it accepts devices
this->spi.call();
this->radio.set_spi_parent(&this->spi);
this->radio.set_cs_pin(&this->cs);
this->radio.set_dio0_pin(&this->dio0);
this->radio.set_rst_pin(&this->rst);
this->radio.set_frequency(433920000);
this->radio.set_pa_pin(PA_PIN_BOOST);
this->radio.set_pa_power(17);
this->radio.set_pa_ramp(PA_RAMP_40);
this->radio.set_spreading_factor(7);
this->radio.set_coding_rate(CODING_RATE_4_5);
this->radio.set_preamble_size(8);
this->radio.set_crc_enable(true);
this->radio.set_sync_value({0x12});
this->radio.set_rx_floor(-94); // FSK setup converts it to an int, so it must be set
}
~RadioHardware() {
// The configuration retry interval (id 0) must not outlive the radio
App.scheduler.cancel_interval(&this->radio, uint32_t{0});
this->radio.spi_teardown();
}
void configure(bool lora, bool rx, bool fixed = false) {
this->radio.set_modulation(lora ? MOD_LORA : MOD_FSK);
this->radio.set_bandwidth(lora ? SX127X_BW_125_0 : SX127X_BW_50_0);
this->radio.set_bitrate(4800);
this->radio.set_deviation(5000);
this->radio.set_packet_mode(true);
this->radio.set_rx_start(rx);
this->radio.set_payload_length(fixed ? 3 : 0);
this->radio.call(); // The normal component lifecycle runs setup().
}
bool lora() const { return (this->regs[REG_OP_MODE] & MOD_LORA) != 0; }
uint8_t mode() const { return this->regs[REG_OP_MODE] & MODE_MASK; }
bool receiving() const { return this->mode() == MODE_RX; }
// A packet arrives, as the chip reports it in its current modulation
void receive(const std::vector<uint8_t> &data, bool crc_error = false) {
this->rx_packet = data;
this->rx_pos_ = 0;
if (this->lora()) {
this->irq |= RX_DONE | (crc_error ? PAYLOAD_CRC_ERROR : 0);
} else if (!crc_error) {
this->payload_ready = true;
// A variable length FSK packet starts with its length
this->fsk_length_pending_ = (this->regs[REG_PACKET_CONFIG_1] & VARIABLE_LENGTH) != 0;
}
}
bool dio0_level() const {
if (this->lora()) {
const uint8_t mapping = this->regs[REG_DIO_MAPPING1] & DIO0_MAPPING_11;
return (this->irq & (mapping == DIO0_MAPPING_01 ? TX_DONE : RX_DONE)) != 0;
}
return this->mode() == MODE_TX ? this->packet_sent : this->payload_ready;
}
SX127x radio;
spi::SPIComponent spi;
TestPin cs, dio0, rst, clk, mosi, miso;
std::array<uint8_t, 128> regs{};
std::vector<uint8_t> rx_packet{0x11, 0x22, 0x33};
std::vector<uint8_t> packet{0x11, 0x22, 0x33};
std::vector<uint8_t> fifo; // bytes written since the last send
std::vector<std::vector<uint8_t>> sent;
uint8_t irq{0};
uint8_t version{0x12};
bool payload_ready{false};
bool packet_sent{false};
// The chip completes a send as soon as it enters TX
bool auto_complete{true};
// Writes to the mode register are ignored, so set_mode_() times out
bool stuck{false};
protected:
void reset_() {
this->regs.fill(0);
this->regs[REG_OP_MODE] = MODE_STDBY;
this->irq = 0;
this->payload_ready = false;
this->packet_sent = false;
this->fifo.clear();
}
uint8_t reply_byte_() {
if (this->pos_ == 0) {
return 0;
}
const uint8_t addr = this->addr_ & 0x7F;
if (this->addr_ & 0x80) {
return 0;
}
if (addr == REG_FIFO) {
if (this->fsk_length_pending_) {
this->fsk_length_pending_ = false;
return this->rx_packet.size();
}
const uint8_t value = this->rx_pos_ < this->rx_packet.size() ? this->rx_packet[this->rx_pos_] : 0;
this->rx_pos_++;
if (!this->lora() && this->rx_pos_ >= this->rx_packet.size()) {
this->payload_ready = false;
}
return value;
}
if (addr == REG_VERSION) {
return this->version;
}
if (addr == REG_IRQ_FLAGS2 || (addr == REG_IRQ_FLAGS && this->lora())) {
this->finish_pending_send_();
}
if (addr == REG_IRQ_FLAGS2) {
return (this->payload_ready ? PAYLOAD_READY : 0) | (this->packet_sent ? PACKET_SENT : 0);
}
if (this->lora()) {
switch (addr) {
case REG_IRQ_FLAGS:
return this->irq;
case REG_NB_RX_BYTES:
return this->rx_packet.size();
case REG_FIFO_RX_CURR_ADDR:
return 0;
case REG_PKT_RSSI_VALUE:
return 100;
case REG_PKT_SNR_VALUE:
return 20;
default:
break;
}
}
return this->regs[addr];
}
void byte_done_(uint8_t value) {
if (this->pos_ == 0) {
this->addr_ = value;
return;
}
if (!(this->addr_ & 0x80)) {
return;
}
const uint8_t addr = this->addr_ & 0x7F;
if (addr == REG_FIFO) {
this->fifo.push_back(value);
return;
}
if (addr == REG_OP_MODE) {
this->write_mode_(value);
return;
}
if (addr == REG_IRQ_FLAGS && this->lora()) {
this->irq &= ~value;
return;
}
if (addr == REG_FIFO_ADDR_PTR) {
this->rx_pos_ = 0;
}
this->regs[addr] = value;
}
void write_mode_(uint8_t value) {
if (this->stuck) {
return;
}
const uint8_t previous = this->mode();
const uint8_t mode = value & MODE_MASK;
// As on an SX1276, a send that is still going out can be stopped by standby or sleep only
if (previous == MODE_TX && !this->send_done_() && mode != MODE_STDBY && mode != MODE_SLEEP) {
return;
}
this->regs[REG_OP_MODE] = value;
if (previous == MODE_TX && mode != MODE_TX) {
this->packet_sent = false;
this->send_pending_ = false; // Stopped before it finished
}
if (mode == MODE_SLEEP) {
this->payload_ready = false;
}
if (mode == MODE_TX && previous != MODE_TX) {
this->sent.push_back(this->fifo);
this->fifo.clear();
// Completes on the next poll, not before the mode reads back as TX
this->send_pending_ = this->auto_complete;
}
}
bool send_done_() const { return this->lora() ? (this->irq & TX_DONE) != 0 : this->packet_sent; }
void finish_pending_send_() {
if (this->send_pending_ && this->mode() == MODE_TX) {
this->complete_send();
}
this->send_pending_ = false;
}
public:
// In LoRa the chip returns to standby by itself; in FSK it stays in TX
void complete_send() {
if (this->lora()) {
this->irq |= TX_DONE;
this->regs[REG_OP_MODE] = (this->regs[REG_OP_MODE] & ~MODE_MASK) | MODE_STDBY;
} else {
this->packet_sent = true;
}
}
protected:
size_t pos_{0};
size_t rx_pos_{0};
uint8_t addr_{0};
uint8_t bit_{0};
uint8_t byte_{0};
uint8_t reply_{0};
bool selected_{false};
bool fsk_length_pending_{false};
bool send_pending_{false};
};
class PacketListener : public SX127xListener {
public:
void on_packet(const std::vector<uint8_t> &packet, float rssi, float snr) override {
this->packets.push_back(packet);
this->rssi = rssi;
this->snr = snr;
if (this->on_receive) {
this->on_receive();
}
}
std::vector<std::vector<uint8_t>> packets;
float rssi{};
float snr{};
std::function<void()> on_receive;
};
class TransmitListener : public SX127xTransmitListener {
public:
void on_transmit_complete(SX127xError result) override {
this->results.push_back(result);
if (this->on_complete) {
this->on_complete(result);
}
}
std::vector<SX127xError> results;
std::function<void(SX127xError)> on_complete;
};
// Runs the scheduler for ms milliseconds of real time, as the main loop would
inline void run_scheduler(uint32_t ms) {
const uint32_t start = millis();
while (millis() - start < ms) {
App.scheduler.call(millis());
delay(5);
}
}
} // namespace esphome::sx127x::testing