mirror of
https://github.com/esphome/esphome.git
synced 2026-11-16 18:16:04 +00:00
Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
365bea82ad | ||
|
|
090156a32e | ||
|
|
543151ab1c | ||
|
|
3b053f1a0c | ||
|
|
7bed89eafc | ||
|
|
04fe5cdac9 | ||
|
|
b35a450f5f | ||
|
|
bf6d3ca470 | ||
|
|
16f660b009 | ||
|
|
1e127efe8e | ||
|
|
cdd9944551 | ||
|
|
9e64b21eb4 | ||
|
|
6f7b62602e | ||
|
|
dd08b19bd5 | ||
|
|
b4e65d51bb | ||
|
|
da65beb404 | ||
|
|
859299b94c | ||
|
|
080bdbd53b | ||
|
|
49e696555e | ||
|
|
10a7992f5b | ||
|
|
cbf38abdb9 | ||
|
|
e5bf7c74e7 | ||
|
|
8cfc265b19 | ||
|
|
fa08c7a305 |
No files matched your search
+1
-8
@@ -146,11 +146,9 @@ 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
|
||||
esphome/components/cstxxx/* @clydebarrow @latonita
|
||||
esphome/components/ct_clamp/* @jesserockz
|
||||
esphome/components/current_based/* @djwmarcx
|
||||
esphome/components/cw2017/* @exciton
|
||||
@@ -468,7 +466,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
|
||||
@@ -651,9 +648,7 @@ esphome/components/sun_gtil2/* @Mat931
|
||||
esphome/components/switch/* @esphome/core
|
||||
esphome/components/switch/binary_sensor/* @ssieb
|
||||
esphome/components/sx126x/* @swoboda1337
|
||||
esphome/components/sx126x/packet_interface/* @clydebarrow
|
||||
esphome/components/sx127x/* @swoboda1337
|
||||
esphome/components/sx127x/packet_interface/* @clydebarrow
|
||||
esphome/components/sy6970/* @linkedupbits
|
||||
esphome/components/syslog/* @clydebarrow
|
||||
esphome/components/systa_bus/* @Mat931
|
||||
@@ -665,8 +660,6 @@ esphome/components/tca8418/* @zebble
|
||||
esphome/components/tca9548a/* @andreashergert1984
|
||||
esphome/components/tca9555/* @mobrembski
|
||||
esphome/components/tcl112/* @glmnet
|
||||
esphome/components/tcp/* @clydebarrow
|
||||
esphome/components/tcp/packet_interface/* @clydebarrow
|
||||
esphome/components/tcp_uart/* @Bascht74
|
||||
esphome/components/tee501/* @Stock-M
|
||||
esphome/components/teleinfo/* @0hax @FredM67
|
||||
@@ -748,7 +741,7 @@ esphome/components/web_server_idf/* @dentra
|
||||
esphome/components/weikai/* @DrCoolZic
|
||||
esphome/components/weikai_i2c/* @DrCoolZic
|
||||
esphome/components/weikai_spi/* @DrCoolZic
|
||||
esphome/components/whirlpool/* @arpena @glmnet @Rodrigoah
|
||||
esphome/components/whirlpool/* @arpena @glmnet
|
||||
esphome/components/whynter/* @aeonsablaze
|
||||
esphome/components/wiegand/* @ssieb
|
||||
esphome/components/wireguard/* @droscy @lhoracek @thomas0bernard
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
from typing import Any
|
||||
|
||||
from esphome import automation, pins
|
||||
from esphome.automation import maybe_simple_id
|
||||
import esphome.codegen as cg
|
||||
@@ -15,7 +13,6 @@ from esphome.const import (
|
||||
CONF_VALUE,
|
||||
CONF_WAIT_TIME,
|
||||
)
|
||||
from esphome.types import ConfigType
|
||||
|
||||
CODEOWNERS = ["@lygris", "@gabest11"]
|
||||
DEPENDENCIES = ["spi"]
|
||||
@@ -25,8 +22,6 @@ MULTI_CONF = True
|
||||
ns = cg.esphome_ns.namespace("cc1101")
|
||||
CC1101Component = ns.class_("CC1101Component", cg.Component, spi.SPIDevice)
|
||||
CC1101Listener = ns.class_("CC1101Listener")
|
||||
PACKET_TYPE = cg.std_vector.template(cg.uint8)
|
||||
RX_FIFO_SIZE = 64
|
||||
|
||||
# Config keys
|
||||
CONF_RX_ATTENUATION = "rx_attenuation"
|
||||
@@ -246,34 +241,20 @@ CONFIG_MAP = {
|
||||
cv.Optional(CONF_BS_POST_KI): cv.enum(BS_POST_KI, upper=False),
|
||||
cv.Optional(CONF_BS_POST_KP): cv.enum(BS_POST_KP, upper=False),
|
||||
cv.Optional(CONF_PACKET_MODE, default=False): cv.boolean,
|
||||
cv.Optional(CONF_PACKET_LENGTH): cv.uint8_t,
|
||||
cv.Optional(CONF_CRC_ENABLE, default=False): cv.boolean,
|
||||
cv.Optional(CONF_WHITENING, default=False): cv.boolean,
|
||||
}
|
||||
|
||||
|
||||
def _is_long_packet(packet_length: Any) -> bool:
|
||||
"""A packet_length that does not fit the RX FIFO, or is a lambda."""
|
||||
return cg.is_template(packet_length) or (packet_length or 0) > RX_FIFO_SIZE
|
||||
|
||||
|
||||
def _validate_packet_mode(config: ConfigType) -> ConfigType:
|
||||
packet_mode = config.get(CONF_PACKET_MODE, False)
|
||||
packet_length = config.get(CONF_PACKET_LENGTH)
|
||||
if packet_mode:
|
||||
def _validate_packet_mode(config):
|
||||
if config.get(CONF_PACKET_MODE, False):
|
||||
if CONF_GDO0_PIN not in config:
|
||||
raise cv.Invalid("gdo0_pin is required when packet_mode is enabled")
|
||||
if packet_length is None:
|
||||
if CONF_PACKET_LENGTH not in config:
|
||||
raise cv.Invalid("packet_length is required when packet_mode is enabled")
|
||||
elif cg.is_template(packet_length):
|
||||
raise cv.Invalid("packet_mode is required when packet_length is a lambda")
|
||||
if (
|
||||
packet_mode
|
||||
and _is_long_packet(packet_length)
|
||||
and config.get(CONF_CRC_ENABLE, False)
|
||||
):
|
||||
raise cv.Invalid(
|
||||
"crc_enable is not supported with packet_length > 64 or a lambda"
|
||||
)
|
||||
if config[CONF_PACKET_LENGTH] > 64:
|
||||
raise cv.Invalid("packet_length must be <= 64 (FIFO size)")
|
||||
return config
|
||||
|
||||
|
||||
@@ -282,9 +263,6 @@ CONFIG_SCHEMA = cv.All(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(CC1101Component),
|
||||
cv.Optional(CONF_GDO0_PIN): pins.internal_gpio_input_pin_schema,
|
||||
cv.Optional(CONF_PACKET_LENGTH): cv.templatable(
|
||||
cv.int_range(min=0, max=1024)
|
||||
),
|
||||
cv.Optional(CONF_ON_PACKET): automation.validate_automation(single=True),
|
||||
}
|
||||
)
|
||||
@@ -304,24 +282,11 @@ async def to_code(config):
|
||||
cg.add(getattr(var, f"set_{key}")(config[key]))
|
||||
|
||||
await cg.add_pin(var.set_gdo0_pin, config.get(CONF_GDO0_PIN))
|
||||
if (packet_length := config.get(CONF_PACKET_LENGTH)) is not None:
|
||||
# packet_mode can also be switched on at run time, so this does not check it
|
||||
if _is_long_packet(packet_length):
|
||||
cg.add_define("USE_CC1101_LONG_PACKET")
|
||||
if cg.is_template(packet_length):
|
||||
lambda_ = await cg.process_lambda(
|
||||
packet_length,
|
||||
[(PACKET_TYPE.operator("ref").operator("const"), "x")],
|
||||
return_type=cg.int32,
|
||||
)
|
||||
cg.add(var.set_packet_length_lambda(lambda_))
|
||||
else:
|
||||
cg.add(var.set_packet_length(packet_length))
|
||||
if CONF_ON_PACKET in config:
|
||||
await automation.build_automation(
|
||||
var.get_packet_trigger(),
|
||||
[
|
||||
(PACKET_TYPE, "x"),
|
||||
(cg.std_vector.template(cg.uint8), "x"),
|
||||
(cg.float_, "freq_offset"),
|
||||
(cg.float_, "rssi"),
|
||||
(cg.uint8, "lqi"),
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
#include "cc1101.h"
|
||||
#include "cc1101pa.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/progmem.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
@@ -16,15 +14,9 @@ namespace esphome::cc1101 {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "cc1101");
|
||||
static constexpr size_t TX_FIFO_SIZE = 64;
|
||||
static constexpr size_t RX_FIFO_SIZE = 64;
|
||||
// RX FIFO threshold for FIFO_THR = 7 in long packet mode
|
||||
static constexpr uint8_t RX_FIFO_THRESHOLD = 32;
|
||||
// The crystal takes about 150 us to start after CSn goes low
|
||||
static constexpr uint32_t WAKEUP_DELAY_US = 200;
|
||||
|
||||
static float freq_offset_hz(uint8_t freqest) { return static_cast<int8_t>(freqest) * (XTAL_FREQUENCY / (1 << 14)); }
|
||||
static float rssi_dbm(int8_t rssi) { return (rssi * RSSI_STEP) - RSSI_OFFSET; }
|
||||
|
||||
// MDMCFG2 MOD_FORMAT values
|
||||
PROGMEM_STRING_TABLE(ModulationStrings, "2-FSK", "GFSK", "UNUSED", "ASK/OOK", "4-FSK", "UNUSED", "UNUSED", "MSK");
|
||||
|
||||
@@ -122,6 +114,8 @@ CC1101Component::CC1101Component() {
|
||||
memset(this->pa_table_, 0, sizeof(this->pa_table_));
|
||||
}
|
||||
|
||||
void IRAM_ATTR CC1101Component::gpio_intr(CC1101Component *arg) { arg->enable_loop_soon_any_context(); }
|
||||
|
||||
void CC1101Component::setup() {
|
||||
this->spi_setup();
|
||||
|
||||
@@ -199,220 +193,7 @@ void CC1101Component::call_listeners_(const std::vector<uint8_t> &packet, float
|
||||
this->packet_trigger_.trigger(packet, freq_offset, rssi, lqi);
|
||||
}
|
||||
|
||||
float CC1101Component::symbol_rate_() const {
|
||||
return (((256.0f + this->state_.DRATE_M) * (1 << this->state_.DRATE_E)) / (1 << 28)) * XTAL_FREQUENCY;
|
||||
}
|
||||
|
||||
#ifdef USE_CC1101_LONG_PACKET
|
||||
bool CC1101Component::is_long_packet_mode_() const {
|
||||
return this->packet_mode_ && (this->packet_length_ > RX_FIFO_SIZE || this->packet_length_func_ != nullptr);
|
||||
}
|
||||
|
||||
void CC1101Component::arm_length_(uint16_t length) {
|
||||
// Over 255 bytes or unknown starts in infinite mode (datasheet section 15.2.2). PKTLEN must not be 0, so a
|
||||
// multiple of 256 stays in infinite mode and ends on the MCU byte count alone.
|
||||
this->packet_expected_length_ = length;
|
||||
this->state_.LENGTH_CONFIG = static_cast<uint8_t>(length > 0 && length < 256 ? LengthConfig::LENGTH_CONFIG_FIXED
|
||||
: LengthConfig::LENGTH_CONFIG_INFINITE);
|
||||
this->state_.PKTLEN = length % 256 == 0 ? 0xFF : static_cast<uint8_t>(length % 256);
|
||||
}
|
||||
|
||||
void CC1101Component::reset_long_packet_rx_() {
|
||||
this->packet_.clear();
|
||||
this->packet_last_byte_ms_ = 0;
|
||||
this->high_freq_.stop();
|
||||
this->arm_length_(this->packet_length_func_ != nullptr ? 0 : this->packet_length_);
|
||||
}
|
||||
|
||||
void CC1101Component::restart_long_packet_rx_() {
|
||||
this->enter_idle_();
|
||||
this->enter_rx_();
|
||||
this->disable_loop();
|
||||
}
|
||||
|
||||
void CC1101Component::maybe_switch_long_packet_to_fixed_() {
|
||||
const uint16_t expected = this->packet_expected_length_;
|
||||
if (this->state_.LENGTH_CONFIG == static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_FIXED) || expected == 0 ||
|
||||
expected % 256 == 0) {
|
||||
return;
|
||||
}
|
||||
const uint16_t received = this->packet_.size();
|
||||
if (expected - received >= 256) {
|
||||
return;
|
||||
}
|
||||
// PKTLEN keeps the (length % 256) set at the start, as in TI Design Note DN500 section 2.3
|
||||
this->state_.LENGTH_CONFIG = static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_FIXED);
|
||||
this->write_(Register::PKTCTRL0);
|
||||
ESP_LOGVV(TAG, "Switched long packet RX to fixed mode: received=%u expected=%u pktlen=%u", received, expected,
|
||||
this->state_.PKTLEN);
|
||||
}
|
||||
|
||||
void CC1101Component::finish_long_packet_() {
|
||||
this->packet_.resize(this->packet_expected_length_);
|
||||
this->read_(Register::FREQEST);
|
||||
this->read_(Register::LQI);
|
||||
const float freq_offset = freq_offset_hz(this->state_.FREQEST);
|
||||
const uint8_t lqi = this->state_.LQI & STATUS_LQI_MASK;
|
||||
// No CRC check: crc_enable is rejected for long packets, CRC_OK is only set after the last payload byte.
|
||||
// Restart RX before dispatching so a callback may change settings; swapping back keeps the reserved capacity
|
||||
// unless a callback reserved a larger buffer.
|
||||
std::vector<uint8_t> packet;
|
||||
packet.swap(this->packet_);
|
||||
this->restart_long_packet_rx_();
|
||||
this->call_listeners_(packet, freq_offset, rssi_dbm(this->long_packet_rssi_), lqi);
|
||||
if (packet.capacity() > this->packet_.capacity()) {
|
||||
packet.clear();
|
||||
this->packet_.swap(packet);
|
||||
}
|
||||
}
|
||||
|
||||
void CC1101Component::handle_long_packet_(uint8_t rx_bytes) {
|
||||
// Leave one byte in the FIFO unless it holds the rest of the packet (datasheet section 20)
|
||||
uint16_t to_read = rx_bytes > 0 ? rx_bytes - 1 : 0;
|
||||
if (this->packet_expected_length_ > 0) {
|
||||
const uint16_t remaining = this->packet_expected_length_ - this->packet_.size();
|
||||
if (remaining <= rx_bytes) {
|
||||
to_read = remaining;
|
||||
}
|
||||
}
|
||||
|
||||
if (to_read == 0) {
|
||||
if (this->packet_.empty()) {
|
||||
return;
|
||||
}
|
||||
// Discard a packet when no byte arrived for the air time of PACKET_IDLE_TIMEOUT_BYTES
|
||||
const uint32_t timeout_ms =
|
||||
std::max(static_cast<uint32_t>(std::ceil((8.0f * PACKET_IDLE_TIMEOUT_BYTES * 1000.0f) / this->symbol_rate_())),
|
||||
PACKET_IDLE_TIMEOUT_MIN_MS);
|
||||
if (App.get_loop_component_start_time() - this->packet_last_byte_ms_ > timeout_ms) {
|
||||
ESP_LOGW(TAG, "Packet receive timeout, discarding packet: received=%u expected=%u fifo=%u",
|
||||
static_cast<uint16_t>(this->packet_.size()), this->packet_expected_length_, rx_bytes);
|
||||
this->restart_long_packet_rx_();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const size_t old_size = this->packet_.size();
|
||||
if (old_size == 0) {
|
||||
// The RSSI register follows the live signal; sample it while the packet is still on air
|
||||
this->read_(Register::RSSI);
|
||||
this->long_packet_rssi_ = this->state_.RSSI;
|
||||
// The FIFO threshold signal does not fire for the bytes after the last threshold crossing; poll until done
|
||||
this->high_freq_.start();
|
||||
}
|
||||
// Read through an aligned buffer: for an unaligned target the ESP32 SPI driver allocates a bounce buffer
|
||||
alignas(4) uint8_t staged[RX_FIFO_SIZE];
|
||||
this->read_(Register::FIFO, staged, to_read);
|
||||
this->packet_.resize(old_size + to_read);
|
||||
std::memcpy(this->packet_.data() + old_size, staged, to_read);
|
||||
this->packet_last_byte_ms_ = App.get_loop_component_start_time();
|
||||
ESP_LOGVV(TAG, "Drained RX FIFO: read=%u received=%u expected=%u fifo=%u", to_read,
|
||||
static_cast<uint16_t>(this->packet_.size()), this->packet_expected_length_, rx_bytes);
|
||||
|
||||
if (this->packet_expected_length_ == 0 && this->packet_length_func_ != nullptr) {
|
||||
const int32_t length = this->packet_length_func_(this->packet_);
|
||||
if (length < 0) {
|
||||
ESP_LOGVV(TAG, "Packet length lambda discarded packet: received=%u", static_cast<uint16_t>(this->packet_.size()));
|
||||
this->restart_long_packet_rx_();
|
||||
return;
|
||||
}
|
||||
if (length > MAX_PACKET_LENGTH) {
|
||||
ESP_LOGW(TAG, "Packet length exceeds maximum, discarding packet: length=%" PRId32 " max=%u", length,
|
||||
MAX_PACKET_LENGTH);
|
||||
this->restart_long_packet_rx_();
|
||||
return;
|
||||
}
|
||||
if (length > 0) {
|
||||
this->arm_length_(static_cast<uint16_t>(length));
|
||||
// A packet shorter than the first FIFO drain is already complete; finish_long_packet_() truncates it
|
||||
if (this->packet_expected_length_ <= this->packet_.size()) {
|
||||
this->finish_long_packet_();
|
||||
return;
|
||||
}
|
||||
this->write_(Register::PKTLEN);
|
||||
this->write_(Register::PKTCTRL0);
|
||||
ESP_LOGVV(TAG, "Resolved packet length: received=%u expected=%u pktlen=%u",
|
||||
static_cast<uint16_t>(this->packet_.size()), this->packet_expected_length_, this->state_.PKTLEN);
|
||||
}
|
||||
}
|
||||
|
||||
// Only reachable while the length is still unknown; a known length caps every read
|
||||
if (this->packet_.size() > MAX_PACKET_LENGTH) {
|
||||
ESP_LOGW(TAG, "Packet length exceeds maximum, discarding packet: length=%u max=%u",
|
||||
static_cast<uint16_t>(this->packet_.size()), MAX_PACKET_LENGTH);
|
||||
this->restart_long_packet_rx_();
|
||||
return;
|
||||
}
|
||||
|
||||
this->maybe_switch_long_packet_to_fixed_();
|
||||
|
||||
if (this->packet_expected_length_ > 0 && this->packet_.size() >= this->packet_expected_length_) {
|
||||
this->finish_long_packet_();
|
||||
}
|
||||
}
|
||||
|
||||
void CC1101Component::loop_long_packet_() {
|
||||
if (this->sleeping_ || this->state_.PKT_FORMAT != static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO) ||
|
||||
this->gdo0_pin_ == nullptr) {
|
||||
this->high_freq_.stop();
|
||||
this->disable_loop();
|
||||
return;
|
||||
}
|
||||
// While GDO0 (RX FIFO threshold) is high, the FIFO holds at least RX_FIFO_THRESHOLD bytes, so drain without
|
||||
// reading RXBYTES. At high data rates RXBYTES changes between two reads, so waiting for two reads that agree
|
||||
// and retrying on the next loop pass lets the FIFO overflow. MARCSTATE does not change during RX.
|
||||
for (uint8_t i = 0; i < RX_FIFO_SIZE / RX_FIFO_THRESHOLD + 2 && this->gdo0_pin_->digital_read(); i++) {
|
||||
this->read_(Register::MARCSTATE);
|
||||
if (static_cast<State>(this->state_.MARC_STATE) == State::RXFIFO_OVERFLOW) {
|
||||
ESP_LOGW(TAG, "RX FIFO overflow, discarding packet: received=%u expected=%u",
|
||||
static_cast<uint16_t>(this->packet_.size()), this->packet_expected_length_);
|
||||
this->restart_long_packet_rx_();
|
||||
return;
|
||||
}
|
||||
this->handle_long_packet_(RX_FIFO_THRESHOLD);
|
||||
if (this->packet_.empty()) {
|
||||
return; // finished or discarded
|
||||
}
|
||||
}
|
||||
// Below the threshold the next crossing raises GDO0 again, and after the packet the count no longer changes,
|
||||
// so retrying on the next loop pass is safe here. RXBYTES can be misread while bytes arrive (TI SWRZ020), so
|
||||
// only trust two consecutive reads that agree.
|
||||
this->read_(Register::RXBYTES);
|
||||
uint8_t rx_bytes = this->state_.RXBYTES;
|
||||
bool stable = false;
|
||||
for (uint8_t retries = RXBYTES_STABLE_RETRIES; retries > 0 && !stable; retries--) {
|
||||
const uint8_t previous = rx_bytes;
|
||||
this->read_(Register::RXBYTES);
|
||||
rx_bytes = this->state_.RXBYTES;
|
||||
stable = rx_bytes == previous;
|
||||
}
|
||||
if (!stable) {
|
||||
return;
|
||||
}
|
||||
rx_bytes = this->state_.NUM_RXBYTES;
|
||||
// More than the FIFO holds can only be a misread; the staged drain buffer is FIFO sized
|
||||
if (this->state_.RXFIFO_OVERFLOW || rx_bytes > RX_FIFO_SIZE) {
|
||||
ESP_LOGW(TAG, "RX FIFO overflow, discarding packet: received=%u expected=%u fifo=%u",
|
||||
static_cast<uint16_t>(this->packet_.size()), this->packet_expected_length_, rx_bytes);
|
||||
this->restart_long_packet_rx_();
|
||||
return;
|
||||
}
|
||||
if (rx_bytes == 0 && this->packet_.empty() && !this->gdo0_pin_->digital_read()) {
|
||||
this->disable_loop();
|
||||
return;
|
||||
}
|
||||
this->handle_long_packet_(rx_bytes);
|
||||
}
|
||||
#endif
|
||||
|
||||
void CC1101Component::loop() {
|
||||
#ifdef USE_CC1101_LONG_PACKET
|
||||
if (this->is_long_packet_mode_()) {
|
||||
this->loop_long_packet_();
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
this->disable_loop();
|
||||
if (this->sleeping_ || this->state_.PKT_FORMAT != static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO) ||
|
||||
this->gdo0_pin_ == nullptr || !this->gdo0_pin_->digital_read()) {
|
||||
@@ -440,7 +221,7 @@ void CC1101Component::loop() {
|
||||
payload_length = this->state_.PKTLEN;
|
||||
expected_rx = payload_length;
|
||||
}
|
||||
if (payload_length == 0 || payload_length > RX_FIFO_SIZE || rx_bytes != expected_rx) {
|
||||
if (payload_length == 0 || payload_length > 64 || rx_bytes != expected_rx) {
|
||||
ESP_LOGW(TAG, "Invalid packet: rx_bytes %u, payload_length %u", rx_bytes, payload_length);
|
||||
this->enter_idle_();
|
||||
this->strobe_(Command::FRX);
|
||||
@@ -454,8 +235,8 @@ void CC1101Component::loop() {
|
||||
this->read_(Register::FREQEST);
|
||||
this->read_(Register::RSSI);
|
||||
this->read_(Register::LQI);
|
||||
float freq_offset = freq_offset_hz(this->state_.FREQEST);
|
||||
float rssi = rssi_dbm(this->state_.RSSI);
|
||||
float freq_offset = static_cast<int8_t>(this->state_.FREQEST) * (XTAL_FREQUENCY / (1 << 14));
|
||||
float rssi = (this->state_.RSSI * RSSI_STEP) - RSSI_OFFSET;
|
||||
bool crc_ok = (this->state_.LQI & STATUS_CRC_OK_MASK) != 0;
|
||||
uint8_t lqi = this->state_.LQI & STATUS_LQI_MASK;
|
||||
if (this->state_.CRC_EN == 0 || crc_ok) {
|
||||
@@ -475,7 +256,7 @@ void CC1101Component::loop() {
|
||||
void CC1101Component::dump_config() {
|
||||
int32_t freq = static_cast<int32_t>(this->state_.FREQ2 << 16 | this->state_.FREQ1 << 8 | this->state_.FREQ0) *
|
||||
XTAL_FREQUENCY / (1 << 16);
|
||||
float symbol_rate = this->symbol_rate_();
|
||||
float symbol_rate = (((256.0f + this->state_.DRATE_M) * (1 << this->state_.DRATE_E)) / (1 << 28)) * XTAL_FREQUENCY;
|
||||
float bw = XTAL_FREQUENCY / (8.0f * (4 + this->state_.CHANBW_M) * (1 << this->state_.CHANBW_E));
|
||||
ESP_LOGCONFIG(TAG,
|
||||
"CC1101:\n"
|
||||
@@ -490,20 +271,6 @@ void CC1101Component::dump_config() {
|
||||
LOG_STR_ARG(ModulationStrings::get_log_str(this->state_.MOD_FORMAT & 0x07, 0)), symbol_rate, bw,
|
||||
this->output_power_effective_);
|
||||
LOG_PIN(" CS Pin: ", this->cs_);
|
||||
LOG_PIN(" GDO0 Pin: ", this->gdo0_pin_);
|
||||
|
||||
if (this->packet_mode_) {
|
||||
#ifdef USE_CC1101_LONG_PACKET
|
||||
if (this->packet_length_func_ != nullptr) {
|
||||
ESP_LOGCONFIG(TAG, " Packet Length: lambda");
|
||||
} else
|
||||
#endif
|
||||
if (this->packet_length_ == 0) {
|
||||
ESP_LOGCONFIG(TAG, " Packet Length: variable");
|
||||
} else {
|
||||
ESP_LOGCONFIG(TAG, " Packet Length: %u", this->packet_length_);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CC1101Component::begin_tx() {
|
||||
@@ -549,14 +316,6 @@ void CC1101Component::reset() {
|
||||
void CC1101Component::set_idle() {
|
||||
ESP_LOGV(TAG, "Setting IDLE state");
|
||||
this->enter_idle_();
|
||||
#ifdef USE_CC1101_LONG_PACKET
|
||||
if (this->is_long_packet_mode_()) {
|
||||
// Drop a partial packet so a pending loop pass cannot finish it and re-enter RX
|
||||
this->strobe_(Command::FRX);
|
||||
this->reset_long_packet_rx_();
|
||||
this->disable_loop();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void CC1101Component::power_down() {
|
||||
@@ -634,18 +393,7 @@ void CC1101Component::enter_idle_() {
|
||||
}
|
||||
}
|
||||
|
||||
bool CC1101Component::enter_rx_() {
|
||||
#ifdef USE_CC1101_LONG_PACKET
|
||||
if (this->is_long_packet_mode_()) {
|
||||
// Every RX entry starts a fresh long packet; callers leave the chip in IDLE, where SFRX is allowed
|
||||
this->strobe_(Command::FRX);
|
||||
this->reset_long_packet_rx_();
|
||||
this->write_(Register::PKTLEN);
|
||||
this->write_(Register::PKTCTRL0);
|
||||
}
|
||||
#endif
|
||||
return this->enter_calibrated_(State::RX, Command::RX);
|
||||
}
|
||||
bool CC1101Component::enter_rx_() { return this->enter_calibrated_(State::RX, Command::RX); }
|
||||
|
||||
bool CC1101Component::enter_tx_() { return this->enter_calibrated_(State::TX, Command::TX); }
|
||||
|
||||
@@ -708,22 +456,12 @@ void CC1101Component::read_(Register reg, uint8_t *buffer, size_t length) {
|
||||
|
||||
CC1101Error CC1101Component::transmit_packet(const uint8_t *data, size_t len) {
|
||||
if (this->state_.PKT_FORMAT != static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO)) {
|
||||
ESP_LOGW(TAG, "Cannot transmit packet: packet mode is not FIFO");
|
||||
return CC1101Error::PARAMS;
|
||||
}
|
||||
#ifdef USE_CC1101_LONG_PACKET
|
||||
// Long packet TX needs chunked FIFO refills and is not implemented
|
||||
if (this->is_long_packet_mode_()) {
|
||||
ESP_LOGW(TAG, "Cannot transmit packet: long packet mode is RX-only");
|
||||
return CC1101Error::PARAMS;
|
||||
}
|
||||
#endif
|
||||
const bool variable = this->state_.LENGTH_CONFIG == static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_VARIABLE);
|
||||
// In variable length mode the FIFO also holds the length byte
|
||||
if (len + (variable ? 1 : 0) > TX_FIFO_SIZE) {
|
||||
ESP_LOGW(TAG,
|
||||
"Cannot transmit packet: long packet TX is not implemented, payload length %u exceeds TX FIFO limit %u",
|
||||
static_cast<unsigned>(len), static_cast<unsigned>(TX_FIFO_SIZE));
|
||||
ESP_LOGE(TAG, "Packet of %u bytes does not fit the TX FIFO", static_cast<unsigned>(len));
|
||||
return CC1101Error::PARAMS;
|
||||
}
|
||||
|
||||
@@ -1096,60 +834,19 @@ void CC1101Component::set_bs_post_kp(BsPostKp value) {
|
||||
}
|
||||
}
|
||||
|
||||
void CC1101Component::configure_packet_mode_() {
|
||||
#ifdef USE_CC1101_LONG_PACKET
|
||||
// Ends a long reception in progress, also when switching to a short packet mode
|
||||
this->high_freq_.stop();
|
||||
this->packet_.clear();
|
||||
#endif
|
||||
if (!this->packet_mode_) {
|
||||
this->state_.PKT_FORMAT = static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_ASYNC_SERIAL);
|
||||
this->state_.GDO0_CFG = 0x0D;
|
||||
} else {
|
||||
this->state_.PKT_FORMAT = static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO);
|
||||
this->state_.APPEND_STATUS = 0;
|
||||
#ifdef USE_CC1101_LONG_PACKET
|
||||
if (this->is_long_packet_mode_()) {
|
||||
// Threshold-only signal, reasserts after each partial FIFO drain
|
||||
this->state_.GDO0_CFG = 0x00;
|
||||
this->state_.FIFO_THR = 7;
|
||||
// Reserve once so receiving never allocates; a lambda may read one FIFO drain past MAX_PACKET_LENGTH
|
||||
this->packet_.reserve(this->packet_length_func_ != nullptr ? MAX_PACKET_LENGTH + RX_FIFO_SIZE
|
||||
: this->packet_length_);
|
||||
this->reset_long_packet_rx_();
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
this->state_.GDO0_CFG = 0x01;
|
||||
this->state_.FIFO_THR = 15;
|
||||
if (this->packet_length_ == 0) {
|
||||
this->state_.LENGTH_CONFIG = static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_VARIABLE);
|
||||
} else {
|
||||
this->state_.LENGTH_CONFIG = static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_FIXED);
|
||||
this->state_.PKTLEN = static_cast<uint8_t>(this->packet_length_);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this->initialized_) {
|
||||
this->write_(Register::PKTCTRL0);
|
||||
this->write_(Register::PKTCTRL1);
|
||||
this->write_(Register::PKTLEN);
|
||||
this->write_(Register::IOCFG0);
|
||||
this->write_(Register::FIFOTHR);
|
||||
}
|
||||
}
|
||||
|
||||
void CC1101Component::set_packet_mode(bool value) {
|
||||
this->packet_mode_ = value;
|
||||
#ifdef USE_CC1101_LONG_PACKET
|
||||
// Long packet RX must drop the FIFO along with a partial packet, so go through IDLE and restart RX
|
||||
if (this->initialized_ && this->is_long_packet_mode_()) {
|
||||
this->reconfigure_packet_length_();
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
this->configure_packet_mode_();
|
||||
this->state_.PKT_FORMAT =
|
||||
static_cast<uint8_t>(value ? PacketFormat::PACKET_FORMAT_FIFO : PacketFormat::PACKET_FORMAT_ASYNC_SERIAL);
|
||||
if (value) {
|
||||
// Configure GDO0 for FIFO status (asserts on RX FIFO threshold or end of packet)
|
||||
this->state_.GDO0_CFG = 0x01;
|
||||
// Set max RX FIFO threshold to ensure we only trigger on end-of-packet
|
||||
this->state_.FIFO_THR = 15;
|
||||
// Don't append status bytes to FIFO - we read from registers instead
|
||||
this->state_.APPEND_STATUS = 0;
|
||||
} else {
|
||||
// Configure GDO0 for serial data (async serial mode)
|
||||
this->state_.GDO0_CFG = 0x0D;
|
||||
}
|
||||
if (this->initialized_) {
|
||||
if (this->gdo0_pin_ != nullptr) {
|
||||
@@ -1159,41 +856,24 @@ void CC1101Component::set_packet_mode(bool value) {
|
||||
this->gdo0_pin_->detach_interrupt();
|
||||
}
|
||||
}
|
||||
this->write_(Register::PKTCTRL0);
|
||||
this->write_(Register::PKTCTRL1);
|
||||
this->write_(Register::IOCFG0);
|
||||
this->write_(Register::FIFOTHR);
|
||||
}
|
||||
}
|
||||
|
||||
void CC1101Component::set_packet_length(uint16_t value) {
|
||||
#ifndef USE_CC1101_LONG_PACKET
|
||||
if (value > RX_FIFO_SIZE) {
|
||||
ESP_LOGW(TAG, "Packet length %u needs a configured packet_length above %u", value,
|
||||
static_cast<unsigned>(RX_FIFO_SIZE));
|
||||
return;
|
||||
void CC1101Component::set_packet_length(uint8_t value) {
|
||||
if (value == 0) {
|
||||
this->state_.LENGTH_CONFIG = static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_VARIABLE);
|
||||
} else {
|
||||
this->state_.LENGTH_CONFIG = static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_FIXED);
|
||||
this->state_.PKTLEN = value;
|
||||
}
|
||||
#else
|
||||
this->packet_length_func_ = nullptr;
|
||||
#endif
|
||||
this->packet_length_ = value;
|
||||
this->reconfigure_packet_length_();
|
||||
}
|
||||
|
||||
#ifdef USE_CC1101_LONG_PACKET
|
||||
void CC1101Component::set_packet_length_lambda(packet_length_func_t func) {
|
||||
this->packet_length_func_ = func;
|
||||
this->reconfigure_packet_length_();
|
||||
}
|
||||
#endif
|
||||
|
||||
void CC1101Component::reconfigure_packet_length_() {
|
||||
// While asleep the writes wait for wake_up() and the radio stays asleep, like set_frequency()
|
||||
if (!this->initialized_ || this->sleeping_) {
|
||||
this->configure_packet_mode_();
|
||||
return;
|
||||
if (this->initialized_) {
|
||||
this->write_(Register::PKTCTRL0);
|
||||
this->write_(Register::PKTLEN);
|
||||
}
|
||||
// Like the other runtime setters: go through IDLE, and flush bytes of a reception in progress
|
||||
this->enter_idle_();
|
||||
this->strobe_(Command::FRX);
|
||||
this->configure_packet_mode_();
|
||||
this->enter_rx_();
|
||||
}
|
||||
|
||||
void CC1101Component::set_crc_enable(bool value) {
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/components/spi/spi.h"
|
||||
#include "esphome/core/automation.h"
|
||||
#include "cc1101defs.h"
|
||||
@@ -11,7 +10,6 @@
|
||||
namespace esphome::cc1101 {
|
||||
|
||||
enum class CC1101Error { NONE = 0, TIMEOUT, PARAMS, CRC_ERROR, FIFO_OVERFLOW, PLL_LOCK };
|
||||
using packet_length_func_t = int32_t (*)(const std::vector<uint8_t> &);
|
||||
|
||||
class CC1101Listener {
|
||||
public:
|
||||
@@ -88,10 +86,7 @@ class CC1101Component final : public Component,
|
||||
|
||||
// Packet mode settings
|
||||
void set_packet_mode(bool value);
|
||||
void set_packet_length(uint16_t value);
|
||||
#ifdef USE_CC1101_LONG_PACKET
|
||||
void set_packet_length_lambda(packet_length_func_t func);
|
||||
#endif
|
||||
void set_packet_length(uint8_t value);
|
||||
void set_crc_enable(bool value);
|
||||
void set_whitening(bool value);
|
||||
|
||||
@@ -106,7 +101,6 @@ class CC1101Component final : public Component,
|
||||
protected:
|
||||
uint16_t chip_id_{0};
|
||||
bool initialized_{false};
|
||||
bool packet_mode_{false};
|
||||
bool sleeping_{false};
|
||||
bool registers_dirty_{false};
|
||||
|
||||
@@ -118,38 +112,13 @@ class CC1101Component final : public Component,
|
||||
|
||||
// GDO pin for packet reception
|
||||
InternalGPIOPin *gdo0_pin_{nullptr};
|
||||
// Inline like App.get_loop_component_start_time(): on RP2040 an out-of-line IRAM_ATTR function in the same
|
||||
// file as that inline one fails with a section type conflict
|
||||
static void IRAM_ATTR gpio_intr(CC1101Component *arg) { arg->enable_loop_soon_any_context(); }
|
||||
static void gpio_intr(CC1101Component *arg);
|
||||
|
||||
// Packet handling
|
||||
void call_listeners_(const std::vector<uint8_t> &packet, float freq_offset, float rssi, uint8_t lqi);
|
||||
void configure_packet_mode_();
|
||||
void reconfigure_packet_length_();
|
||||
float symbol_rate_() const;
|
||||
#ifdef USE_CC1101_LONG_PACKET
|
||||
bool is_long_packet_mode_() const;
|
||||
void arm_length_(uint16_t length);
|
||||
void reset_long_packet_rx_();
|
||||
void restart_long_packet_rx_();
|
||||
void loop_long_packet_();
|
||||
void handle_long_packet_(uint8_t rx_bytes);
|
||||
void finish_long_packet_();
|
||||
void maybe_switch_long_packet_to_fixed_();
|
||||
#endif
|
||||
Trigger<std::vector<uint8_t>, float, float, uint8_t> packet_trigger_;
|
||||
std::vector<uint8_t> packet_;
|
||||
std::vector<CC1101Listener *> listeners_;
|
||||
#ifdef USE_CC1101_LONG_PACKET
|
||||
packet_length_func_t packet_length_func_{nullptr};
|
||||
uint32_t packet_last_byte_ms_{0};
|
||||
#endif
|
||||
uint16_t packet_length_{0};
|
||||
#ifdef USE_CC1101_LONG_PACKET
|
||||
uint16_t packet_expected_length_{0};
|
||||
int8_t long_packet_rssi_{0}; // raw RSSI register
|
||||
HighFrequencyLoopRequester high_freq_;
|
||||
#endif
|
||||
|
||||
// Low-level Helpers
|
||||
uint8_t strobe_(Command cmd);
|
||||
|
||||
@@ -15,11 +15,6 @@ static constexpr uint8_t PLL_LOCK_RETRIES = 3;
|
||||
static constexpr uint8_t STATUS_CRC_OK_MASK = 0x80;
|
||||
static constexpr uint8_t STATUS_LQI_MASK = 0x7F;
|
||||
|
||||
static constexpr uint16_t MAX_PACKET_LENGTH = 1024;
|
||||
static constexpr uint16_t PACKET_IDLE_TIMEOUT_BYTES = 64;
|
||||
static constexpr uint32_t PACKET_IDLE_TIMEOUT_MIN_MS = 5;
|
||||
static constexpr uint8_t RXBYTES_STABLE_RETRIES = 4;
|
||||
|
||||
static constexpr uint8_t BUS_BURST = 0x40;
|
||||
static constexpr uint8_t BUS_READ = 0x80;
|
||||
static constexpr uint8_t BUS_WRITE = 0x00;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -1,15 +1,36 @@
|
||||
from esphome.components import cstxxx
|
||||
from esphome import pins
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import i2c, touchscreen
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ID, CONF_INTERRUPT_PIN, CONF_RESET_PIN
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from .. import cst226_ns
|
||||
|
||||
AUTO_LOAD = ["cstxxx"]
|
||||
|
||||
CST226Touchscreen = cst226_ns.class_("CST226Touchscreen", cstxxx.CSTTouchscreen)
|
||||
CST226Touchscreen = cst226_ns.class_(
|
||||
"CST226Touchscreen",
|
||||
touchscreen.Touchscreen,
|
||||
i2c.I2CDevice,
|
||||
)
|
||||
|
||||
CST226ButtonListener = cst226_ns.class_("CST226ButtonListener")
|
||||
CONFIG_SCHEMA = cstxxx.cst_touchscreen_schema(CST226Touchscreen, 0x5A)
|
||||
CONFIG_SCHEMA = (
|
||||
touchscreen.touchscreen_schema("100ms")
|
||||
.extend(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(CST226Touchscreen),
|
||||
cv.Optional(CONF_INTERRUPT_PIN): pins.internal_gpio_input_pin_schema,
|
||||
cv.Optional(CONF_RESET_PIN): pins.gpio_output_pin_schema,
|
||||
}
|
||||
)
|
||||
.extend(i2c.i2c_device_schema(0x5A))
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
await cstxxx.new_cst_touchscreen(config)
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
await touchscreen.register_touchscreen(var, config)
|
||||
await i2c.register_i2c_device(var, config)
|
||||
|
||||
await cg.add_pin(var.set_interrupt_pin, config.get(CONF_INTERRUPT_PIN))
|
||||
await cg.add_pin(var.set_reset_pin, config.get(CONF_RESET_PIN))
|
||||
@@ -14,10 +14,6 @@ void CST226Touchscreen::setup() {
|
||||
}
|
||||
|
||||
void CST226Touchscreen::update_touches() {
|
||||
if (!this->setup_complete_) {
|
||||
this->skip_update_ = true;
|
||||
return;
|
||||
}
|
||||
uint8_t data[28];
|
||||
if (!this->status_comm_result(this->read_bytes(CST226_REG_STATUS, data, sizeof data))) {
|
||||
this->skip_update_ = true;
|
||||
@@ -28,39 +24,56 @@ void CST226Touchscreen::update_touches() {
|
||||
return;
|
||||
}
|
||||
this->update_button_state_(false);
|
||||
if (data[cstxxx::SYNC_IDX] != cstxxx::SYNC_BYTE || data[0] == cstxxx::SYNC_BYTE ||
|
||||
data[cstxxx::FINGER_COUNT_IDX] == 0x80) {
|
||||
if (data[6] != 0xAB || data[0] == 0xAB || data[5] == 0x80) {
|
||||
this->skip_update_ = true;
|
||||
return;
|
||||
}
|
||||
uint8_t num_of_touches = data[cstxxx::FINGER_COUNT_IDX] & 0x7F;
|
||||
uint8_t num_of_touches = data[5] & 0x7F;
|
||||
if (num_of_touches == 0 || num_of_touches > 5) {
|
||||
this->write_byte(CST226_REG_STATUS, cstxxx::SYNC_BYTE);
|
||||
this->write_byte(0, 0xAB);
|
||||
return;
|
||||
}
|
||||
|
||||
size_t index = 0;
|
||||
for (uint8_t i = 0; i != num_of_touches; i++) {
|
||||
auto touch = cstxxx::decode_touch(data, i);
|
||||
this->add_raw_touch_position_(touch.id, touch.x, touch.y, touch.z);
|
||||
ESP_LOGV(TAG, "Read touch %d: %d/%d", touch.id, touch.x, touch.y);
|
||||
uint8_t id = data[index] >> 4;
|
||||
int16_t x = (data[index + 1] << 4) | ((data[index + 3] >> 4) & 0x0F);
|
||||
int16_t y = (data[index + 2] << 4) | (data[index + 3] & 0x0F);
|
||||
int16_t z = data[index + 4];
|
||||
this->add_raw_touch_position_(id, x, y, z);
|
||||
ESP_LOGV(TAG, "Read touch %d: %d/%d", id, x, y);
|
||||
index += 5;
|
||||
if (i == 0)
|
||||
index += 2;
|
||||
}
|
||||
}
|
||||
|
||||
bool CST226Touchscreen::read16_(uint16_t addr, uint8_t *data, size_t len) {
|
||||
if (this->read_register16(addr, data, len) != i2c::ERROR_OK) {
|
||||
ESP_LOGE(TAG, "Read data from 0x%04X failed", addr);
|
||||
this->mark_failed();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
void CST226Touchscreen::continue_setup_() {
|
||||
this->setup_interrupt_pin_(gpio::INTERRUPT_FALLING_EDGE);
|
||||
if (!this->enter_command_mode_())
|
||||
uint8_t buffer[8];
|
||||
if (this->interrupt_pin_ != nullptr) {
|
||||
this->interrupt_pin_->setup();
|
||||
this->attach_interrupt_(this->interrupt_pin_, gpio::INTERRUPT_FALLING_EDGE);
|
||||
}
|
||||
if (!this->setup_check(this->write_byte_reg16(0xD1, 0xD1), LOG_STR("Write byte to 0xD1 failed")))
|
||||
return;
|
||||
delay(10);
|
||||
if (!this->check_firmware_())
|
||||
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;
|
||||
if (this->read16_(0xD204, buffer, 4)) {
|
||||
uint16_t chip_id = buffer[2] + (buffer[3] << 8);
|
||||
uint16_t project_id = buffer[0] + (buffer[1] << 8);
|
||||
ESP_LOGCONFIG(TAG, "Chip ID %X, project ID %x", chip_id, project_id);
|
||||
}
|
||||
if (this->x_raw_max_ == 0 || this->y_raw_max_ == 0) {
|
||||
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->read16_(0xD1F8, buffer, 4)) {
|
||||
this->x_raw_max_ = buffer[0] + (buffer[1] << 8);
|
||||
this->y_raw_max_ = buffer[2] + (buffer[3] << 8);
|
||||
if (this->swap_x_y_)
|
||||
std::swap(this->x_raw_max_, this->y_raw_max_);
|
||||
} else {
|
||||
@@ -68,10 +81,8 @@ void CST226Touchscreen::continue_setup_() {
|
||||
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_complete_ = true;
|
||||
}
|
||||
|
||||
void CST226Touchscreen::update_button_state_(bool state) {
|
||||
if (this->button_touched_ == state)
|
||||
return;
|
||||
@@ -85,10 +96,6 @@ void CST226Touchscreen::dump_config() {
|
||||
LOG_I2C_DEVICE(this);
|
||||
LOG_PIN(" Interrupt Pin: ", this->interrupt_pin_);
|
||||
LOG_PIN(" Reset Pin: ", this->reset_pin_);
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Chip ID: 0x%04X, Project ID: 0x%04X\n"
|
||||
" X/Y raw max: %d/%d",
|
||||
this->chip_id_, this->project_id_, this->x_raw_max_, this->y_raw_max_);
|
||||
}
|
||||
|
||||
} // namespace esphome::cst226
|
||||
@@ -1,12 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/components/cstxxx/cstxxx.h"
|
||||
#include "esphome/components/i2c/i2c.h"
|
||||
#include "esphome/components/touchscreen/touchscreen.h"
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace esphome::cst226 {
|
||||
|
||||
static const uint8_t CST226_REG_STATUS = 0x00;
|
||||
@@ -16,23 +15,28 @@ class CST226ButtonListener {
|
||||
virtual void update_button(bool state) = 0;
|
||||
};
|
||||
|
||||
class CST226Touchscreen final : public cstxxx::CSTTouchscreen {
|
||||
class CST226Touchscreen final : public touchscreen::Touchscreen, public i2c::I2CDevice {
|
||||
public:
|
||||
void setup() override;
|
||||
void update_touches() override;
|
||||
void dump_config() override;
|
||||
|
||||
void set_interrupt_pin(InternalGPIOPin *pin) { this->interrupt_pin_ = pin; }
|
||||
void set_reset_pin(GPIOPin *pin) { this->reset_pin_ = pin; }
|
||||
bool can_proceed() override { return this->setup_complete_ || this->is_failed(); }
|
||||
void register_button_listener(CST226ButtonListener *listener) { this->button_listeners_.push_back(listener); }
|
||||
|
||||
protected:
|
||||
bool read16_(uint16_t addr, uint8_t *data, size_t len);
|
||||
void continue_setup_();
|
||||
void update_button_state_(bool state);
|
||||
|
||||
bool button_touched_{};
|
||||
uint16_t chip_id_{};
|
||||
uint16_t project_id_{};
|
||||
InternalGPIOPin *interrupt_pin_{};
|
||||
GPIOPin *reset_pin_{};
|
||||
uint8_t chip_id_{};
|
||||
bool setup_complete_{};
|
||||
std::vector<CST226ButtonListener *> button_listeners_;
|
||||
bool button_touched_{};
|
||||
};
|
||||
|
||||
} // namespace esphome::cst226
|
||||
@@ -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,15 +1,37 @@
|
||||
from esphome.components import cstxxx
|
||||
from esphome import pins
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import i2c, touchscreen
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ID, CONF_INTERRUPT_PIN, CONF_RESET_PIN
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from .. import cst328_ns
|
||||
|
||||
AUTO_LOAD = ["cstxxx"]
|
||||
|
||||
CST328Touchscreen = cst328_ns.class_("CST328Touchscreen", cstxxx.CSTTouchscreen)
|
||||
CST328Touchscreen = cst328_ns.class_(
|
||||
"CST328Touchscreen",
|
||||
touchscreen.Touchscreen,
|
||||
i2c.I2CDevice,
|
||||
)
|
||||
|
||||
CST328ButtonListener = cst328_ns.class_("CST328ButtonListener")
|
||||
CONFIG_SCHEMA = cstxxx.cst_touchscreen_schema(CST328Touchscreen, 0x1A)
|
||||
|
||||
CONFIG_SCHEMA = (
|
||||
touchscreen.touchscreen_schema("100ms")
|
||||
.extend(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(CST328Touchscreen),
|
||||
cv.Optional(CONF_INTERRUPT_PIN): pins.internal_gpio_input_pin_schema,
|
||||
cv.Optional(CONF_RESET_PIN): pins.gpio_output_pin_schema,
|
||||
}
|
||||
)
|
||||
.extend(i2c.i2c_device_schema(0x1A))
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
await cstxxx.new_cst_touchscreen(config)
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
await touchscreen.register_touchscreen(var, config)
|
||||
await i2c.register_i2c_device(var, config)
|
||||
|
||||
await cg.add_pin(var.set_interrupt_pin, config.get(CONF_INTERRUPT_PIN))
|
||||
await cg.add_pin(var.set_reset_pin, config.get(CONF_RESET_PIN))
|
||||
@@ -5,8 +5,31 @@ namespace esphome::cst328 {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "cst328.touchscreen");
|
||||
|
||||
static constexpr uint32_t CST328_BEFORE_RESET_TIMEOUT = 50; // 50 ms from datasheet
|
||||
static constexpr uint32_t CST328_TRANSITION_TIMEOUT = 300; // 200 ms from datasheet, but typically much less
|
||||
static const uint32_t CST328_BEFORE_RESET_TIMEOUT = 50; // 50 ms from datasheet
|
||||
static const uint32_t CST328_TRANSITION_TIMEOUT = 300; // 200 ms from datasheet, but typically much less
|
||||
static const uint16_t CST328_FW_CRC = 0xCACA; // Expected firmware CRC value
|
||||
static const uint8_t CST328_SYNC_BYTE = 0xAB; // Sync byte used in communication
|
||||
|
||||
static const uint8_t ZERO_BYTE = 0;
|
||||
|
||||
#define I2C_WARN_ON_ERROR(x, log_tag, format, ...) \
|
||||
do { \
|
||||
i2c::ErrorCode err_rc_ = (x); \
|
||||
if (err_rc_ != i2c::ERROR_OK) { \
|
||||
ESP_LOGW(log_tag, "%s(%d): [error %d] " format, __FUNCTION__, __LINE__, err_rc_, ##__VA_ARGS__); \
|
||||
this->status_set_warning(format); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#define I2C_FAIL_ON_ERROR(x, log_tag, format, ...) \
|
||||
do { \
|
||||
i2c::ErrorCode err_rc_ = (x); \
|
||||
if (err_rc_ != i2c::ERROR_OK) { \
|
||||
ESP_LOGE(log_tag, "%s(%d): [error %d] " format, __FUNCTION__, __LINE__, err_rc_, ##__VA_ARGS__); \
|
||||
this->mark_failed(); \
|
||||
return; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
void CST328Touchscreen::setup() {
|
||||
ESP_LOGCONFIG(TAG, "Setting up CST328 Touchscreen...");
|
||||
@@ -27,36 +50,50 @@ void CST328Touchscreen::reset_device_() {
|
||||
void CST328Touchscreen::continue_setup_() {
|
||||
ESP_LOGV(TAG, "Continuing CST328 setup...");
|
||||
|
||||
if (!this->enter_command_mode_() || !this->check_firmware_())
|
||||
return;
|
||||
if (!this->setup_check(this->read_words_(cstxxx::REG_CHIP_INFO, this->project_id_, this->chip_id_),
|
||||
LOG_STR("Failed to read chip and project ID")))
|
||||
uint8_t data_byte{0};
|
||||
uint8_t buf[24]{};
|
||||
|
||||
I2C_FAIL_ON_ERROR(this->write_register16(CST_WM_DEBUG_INFO, buf, 0), TAG, "Failed to enter debug/info mode");
|
||||
I2C_FAIL_ON_ERROR(this->read_register16(CST_REG_FW_CRC_AND_BOOT_TIME, buf, 4), TAG,
|
||||
"Failed to read FW CRC and boot time");
|
||||
|
||||
uint16_t fw_crc = buf[2] + (buf[3] << 8);
|
||||
if (fw_crc != CST328_FW_CRC) {
|
||||
ESP_LOGE(TAG, "Error: Firmware CRC mismatch, expected 0x%04X but got 0x%04X", CST328_FW_CRC, fw_crc);
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
|
||||
I2C_FAIL_ON_ERROR(this->read_register16(CST_REG_CHIP_TYPE_AND_PROJECT_ID, buf, 4), TAG,
|
||||
"Failed to read chip and project ID");
|
||||
|
||||
this->chip_id_ = buf[2] + (buf[3] << 8);
|
||||
this->project_id_ = buf[0] + (buf[1] << 8);
|
||||
ESP_LOGD(TAG, "Chip ID %X, project ID %X", this->chip_id_, this->project_id_);
|
||||
uint16_t fw_version;
|
||||
if (!this->setup_check(this->read_words_(cstxxx::REG_FW_VERSION, this->fw_build_, fw_version),
|
||||
LOG_STR("Failed to read FW version")))
|
||||
return;
|
||||
this->fw_ver_major_ = fw_version >> 8;
|
||||
this->fw_ver_minor_ = fw_version & 0xFF;
|
||||
I2C_FAIL_ON_ERROR(this->read_register16(CST_REG_FW_REVISION, buf, 4), TAG, "Failed to read FW version");
|
||||
|
||||
this->fw_ver_major_ = buf[3];
|
||||
this->fw_ver_minor_ = buf[2];
|
||||
this->fw_build_ = buf[0] + (buf[1] << 8);
|
||||
ESP_LOGV(TAG, "FW version %d.%d.%d", this->fw_ver_major_, this->fw_ver_minor_, this->fw_build_);
|
||||
|
||||
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 (i2c::ERROR_OK == this->read_register16(CST_REG_X_Y_RESOLUTION, buf, 4)) {
|
||||
this->x_raw_max_ = buf[0] + (buf[1] << 8);
|
||||
this->y_raw_max_ = buf[2] + (buf[3] << 8);
|
||||
} else {
|
||||
this->x_raw_max_ = this->display_->get_native_width();
|
||||
this->y_raw_max_ = this->display_->get_native_height();
|
||||
}
|
||||
|
||||
uint8_t sync;
|
||||
bool ok = this->write_register16(cstxxx::REG_NORMAL_MODE, nullptr, 0) == i2c::ERROR_OK;
|
||||
ok &= this->read_byte_reg16(cstxxx::REG_TOUCH_DATA, &sync);
|
||||
ok &= this->write_byte_reg16(cstxxx::REG_TOUCH_DATA, cstxxx::SYNC_BYTE);
|
||||
this->status_comm_check(ok);
|
||||
I2C_WARN_ON_ERROR(this->write_register16(CST_WM_NORMAL, buf, 0), TAG, "Failed to enter normal mode");
|
||||
I2C_WARN_ON_ERROR(this->read_register16(CST_REG_TOUCH_INFORMATION, &data_byte, 1), TAG, "Failed to read sync");
|
||||
I2C_WARN_ON_ERROR(this->write_register16(CST_REG_TOUCH_INFORMATION, &CST328_SYNC_BYTE, 1), TAG,
|
||||
"Failed to write sync");
|
||||
|
||||
this->setup_interrupt_pin_(gpio::INTERRUPT_FALLING_EDGE);
|
||||
if (this->interrupt_pin_ != nullptr) {
|
||||
this->interrupt_pin_->setup();
|
||||
this->attach_interrupt_(this->interrupt_pin_, gpio::INTERRUPT_FALLING_EDGE);
|
||||
}
|
||||
|
||||
this->setup_complete_ = true;
|
||||
ESP_LOGV(TAG, "CST328 setup complete");
|
||||
@@ -105,15 +142,21 @@ void CST328Touchscreen::update_touches() {
|
||||
} else {
|
||||
this->update_button_state_(true);
|
||||
|
||||
uint8_t data_idx = 0;
|
||||
for (uint8_t i = 0; i < touch_cnt; i++) {
|
||||
auto touch = cstxxx::decode_touch(touch_data, i);
|
||||
this->add_raw_touch_position_(touch.id, touch.x, touch.y, touch.z);
|
||||
uint8_t id = touch_data[data_idx] >> 4;
|
||||
int16_t x = (touch_data[data_idx + 1] << 4) | ((touch_data[data_idx + 3] >> 4) & 0x0F);
|
||||
int16_t y = (touch_data[data_idx + 2] << 4) | (touch_data[data_idx + 3] & 0x0F);
|
||||
int16_t z = touch_data[data_idx + 4];
|
||||
|
||||
this->add_raw_touch_position_(id, x, y, z);
|
||||
data_idx += (i == 0) ? 7 : 5;
|
||||
}
|
||||
}
|
||||
|
||||
bool cleanup_error = false;
|
||||
cleanup_error |= !this->write_byte_reg16(cstxxx::REG_FINGER_COUNT, 0);
|
||||
cleanup_error |= !this->write_byte_reg16(cstxxx::REG_TOUCH_DATA, cstxxx::SYNC_BYTE);
|
||||
cleanup_error |= !this->write_byte_reg16(CST_REG_TOUCH_FINGER_NUMBER, ZERO_BYTE);
|
||||
cleanup_error |= !this->write_byte_reg16(CST_REG_TOUCH_INFORMATION, CST328_SYNC_BYTE);
|
||||
|
||||
if (cleanup_error) {
|
||||
ESP_LOGW(TAG, "Failed to clean up touch registers");
|
||||
|
||||
@@ -1,45 +1,61 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/components/cstxxx/cstxxx.h"
|
||||
#include "esphome/components/i2c/i2c.h"
|
||||
#include "esphome/components/touchscreen/touchscreen.h"
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/hal.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace esphome::cst328 {
|
||||
|
||||
static constexpr uint8_t CST328_TOUCH_MAX_POINTS = 5;
|
||||
static constexpr uint8_t CST328_TOUCH_DATA_SIZE = cstxxx::report_size(CST328_TOUCH_MAX_POINTS);
|
||||
static const uint8_t CST328_TOUCH_MAX_POINTS = 5;
|
||||
static const uint8_t CST328_TOUCH_DATA_SIZE = CST328_TOUCH_MAX_POINTS * 5 + 2;
|
||||
|
||||
static constexpr uint16_t CST_REG_TOUCH_INFORMATION = cstxxx::REG_TOUCH_DATA;
|
||||
static constexpr uint16_t CST_REG_FINGER_COUNT_IDX = cstxxx::FINGER_COUNT_IDX;
|
||||
static constexpr uint16_t CST_REG_X_Y_RESOLUTION = cstxxx::REG_RESOLUTION;
|
||||
static constexpr uint16_t CST_REG_FW_CRC_AND_BOOT_TIME = cstxxx::REG_FW_CHECK_CODE;
|
||||
static const uint16_t CST_REG_TOUCH_INFORMATION = 0xD000;
|
||||
static const uint16_t CST_REG_TOUCH_FINGER_NUMBER = 0xD005;
|
||||
|
||||
static const uint16_t CST_REG_FINGER_COUNT_IDX = CST_REG_TOUCH_FINGER_NUMBER - CST_REG_TOUCH_INFORMATION;
|
||||
|
||||
static const uint16_t CST_REG_X_Y_RESOLUTION = 0xD1F8;
|
||||
static const uint16_t CST_REG_FW_CRC_AND_BOOT_TIME = 0xD1FC;
|
||||
static const uint16_t CST_REG_CHIP_TYPE_AND_PROJECT_ID = 0xD204;
|
||||
static const uint16_t CST_REG_FW_REVISION = 0xD208;
|
||||
|
||||
static const uint16_t CST_WM_DEBUG_INFO = 0xD101;
|
||||
static const uint16_t CST_WM_NORMAL = 0xD109;
|
||||
|
||||
class CST328ButtonListener {
|
||||
public:
|
||||
virtual void update_button(bool state) = 0;
|
||||
};
|
||||
|
||||
class CST328Touchscreen : public cstxxx::CSTTouchscreen {
|
||||
class CST328Touchscreen : public touchscreen::Touchscreen, public i2c::I2CDevice {
|
||||
public:
|
||||
void setup() override;
|
||||
void register_button_listener(CST328ButtonListener *listener) { this->button_listeners_.push_back(listener); }
|
||||
void dump_config() override;
|
||||
|
||||
void set_interrupt_pin(InternalGPIOPin *pin) { this->interrupt_pin_ = pin; }
|
||||
void set_reset_pin(GPIOPin *pin) { this->reset_pin_ = pin; }
|
||||
|
||||
protected:
|
||||
void update_touches() override;
|
||||
void reset_device_();
|
||||
void continue_setup_();
|
||||
void update_button_state_(bool state);
|
||||
|
||||
bool button_touched_{};
|
||||
uint8_t fw_ver_major_{};
|
||||
uint8_t fw_ver_minor_{};
|
||||
InternalGPIOPin *interrupt_pin_{};
|
||||
GPIOPin *reset_pin_{};
|
||||
|
||||
std::vector<CST328ButtonListener *> button_listeners_;
|
||||
bool button_touched_{};
|
||||
|
||||
uint16_t chip_id_{};
|
||||
uint16_t project_id_{};
|
||||
uint8_t fw_ver_major_{};
|
||||
uint8_t fw_ver_minor_{};
|
||||
uint16_t fw_build_{};
|
||||
|
||||
bool setup_complete_{};
|
||||
};
|
||||
|
||||
} // namespace esphome::cst328
|
||||
@@ -1,14 +1,35 @@
|
||||
from esphome.components import cstxxx
|
||||
from esphome import pins
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import i2c, touchscreen
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ID, CONF_INTERRUPT_PIN, CONF_RESET_PIN
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from .. import cst9220_ns
|
||||
|
||||
AUTO_LOAD = ["cstxxx"]
|
||||
CST9220Touchscreen = cst9220_ns.class_(
|
||||
"CST9220Touchscreen",
|
||||
touchscreen.Touchscreen,
|
||||
i2c.I2CDevice,
|
||||
)
|
||||
|
||||
CST9220Touchscreen = cst9220_ns.class_("CST9220Touchscreen", cstxxx.CSTTouchscreen)
|
||||
|
||||
CONFIG_SCHEMA = cstxxx.cst_touchscreen_schema(CST9220Touchscreen, 0x5A)
|
||||
CONFIG_SCHEMA = (
|
||||
touchscreen.touchscreen_schema("100ms")
|
||||
.extend(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(CST9220Touchscreen),
|
||||
cv.Optional(CONF_INTERRUPT_PIN): pins.internal_gpio_input_pin_schema,
|
||||
cv.Optional(CONF_RESET_PIN): pins.gpio_output_pin_schema,
|
||||
}
|
||||
)
|
||||
.extend(i2c.i2c_device_schema(0x5A))
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
await cstxxx.new_cst_touchscreen(config)
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
await touchscreen.register_touchscreen(var, config)
|
||||
await i2c.register_i2c_device(var, config)
|
||||
|
||||
await cg.add_pin(var.set_interrupt_pin, config.get(CONF_INTERRUPT_PIN))
|
||||
await cg.add_pin(var.set_reset_pin, config.get(CONF_RESET_PIN))
|
||||
@@ -1,4 +1,7 @@
|
||||
#include "cst9220_touchscreen.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
#include <cinttypes>
|
||||
|
||||
namespace esphome::cst9220 {
|
||||
|
||||
@@ -13,29 +16,55 @@ void CST9220Touchscreen::setup() {
|
||||
}
|
||||
|
||||
void CST9220Touchscreen::continue_setup_() {
|
||||
this->setup_interrupt_pin_(gpio::INTERRUPT_FALLING_EDGE);
|
||||
uint8_t buffer[4];
|
||||
|
||||
if (!this->enter_command_mode_())
|
||||
return;
|
||||
delay(10);
|
||||
if (!this->check_firmware_())
|
||||
return;
|
||||
|
||||
// Read the panel resolution unless the user supplied calibration values.
|
||||
uint16_t x_max, y_max;
|
||||
if (this->read_words_(cstxxx::REG_RESOLUTION, x_max, y_max)) {
|
||||
if (this->x_raw_max_ == this->x_raw_min_)
|
||||
this->x_raw_max_ = x_max;
|
||||
if (this->y_raw_max_ == this->y_raw_min_)
|
||||
this->y_raw_max_ = y_max;
|
||||
if (this->interrupt_pin_ != nullptr) {
|
||||
this->interrupt_pin_->setup();
|
||||
this->attach_interrupt_(this->interrupt_pin_, gpio::INTERRUPT_FALLING_EDGE);
|
||||
}
|
||||
|
||||
if (!this->setup_check(this->read_words_(cstxxx::REG_CHIP_INFO, this->project_id_, this->chip_id_),
|
||||
LOG_STR("Failed to read chip ID")))
|
||||
// Enter command mode so the configuration registers can be read.
|
||||
if (this->write_register16(REG_CMD_MODE, buffer, 0) != i2c::ERROR_OK) {
|
||||
this->status_set_error(LOG_STR("Failed to enter command mode"));
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
delay(10);
|
||||
|
||||
// The firmware check code confirms that valid firmware is loaded.
|
||||
if (this->read_register16(REG_CHECKCODE, buffer, 4) != i2c::ERROR_OK) {
|
||||
this->status_set_error(LOG_STR("Failed to read check code"));
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
uint32_t checkcode = encode_uint32(buffer[3], buffer[2], buffer[1], buffer[0]);
|
||||
if ((checkcode & 0xFFFF0000) != 0xCACA0000) {
|
||||
ESP_LOGE(TAG, "Invalid firmware check code: 0x%08" PRIX32, checkcode);
|
||||
this->status_set_error(LOG_STR("Invalid firmware check code"));
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
|
||||
// Read the panel resolution unless the user supplied calibration values.
|
||||
if (this->read_register16(REG_RESOLUTION, buffer, 4) == i2c::ERROR_OK) {
|
||||
if (this->x_raw_max_ == this->x_raw_min_)
|
||||
this->x_raw_max_ = encode_value_le<uint16_t>(buffer);
|
||||
if (this->y_raw_max_ == this->y_raw_min_)
|
||||
this->y_raw_max_ = encode_value_le<uint16_t>(&buffer[2]);
|
||||
}
|
||||
|
||||
// Read the chip type and project id and validate the controller.
|
||||
if (this->read_register16(REG_CHIP_INFO, buffer, 4) != i2c::ERROR_OK) {
|
||||
this->status_set_error(LOG_STR("Failed to read chip ID"));
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
this->chip_id_ = encode_value_le<uint16_t>(&buffer[2]);
|
||||
this->project_id_ = encode_value_le<uint16_t>(buffer);
|
||||
if (this->chip_id_ != CST9220_CHIP_ID && this->chip_id_ != CST9217_CHIP_ID) {
|
||||
ESP_LOGE(TAG, "Unknown chip ID: 0x%04X", this->chip_id_);
|
||||
this->mark_failed(LOG_STR("Unknown chip ID"));
|
||||
this->status_set_error(LOG_STR("Unknown chip ID"));
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -55,7 +84,7 @@ void CST9220Touchscreen::update_touches() {
|
||||
// Only an actual I2C failure should skip the update; a successful read with no
|
||||
// touches is a real "all fingers lifted" state that must flow through so the
|
||||
// base class can generate the release event.
|
||||
if (!this->status_comm_result(this->read_register16(cstxxx::REG_TOUCH_DATA, data, sizeof(data)) == i2c::ERROR_OK)) {
|
||||
if (!this->status_comm_result(this->read_register16(REG_TOUCH_DATA, data, sizeof(data)) == i2c::ERROR_OK)) {
|
||||
this->skip_update_ = true;
|
||||
return;
|
||||
}
|
||||
@@ -63,23 +92,30 @@ void CST9220Touchscreen::update_touches() {
|
||||
// A valid report carries the marker at offset 6. Writing an acknowledge back makes the controller return
|
||||
// invalid frames during a long press, so none is written. An invalid frame keeps the previous points; while
|
||||
// a finger is down, read again shortly so a lost release frame does not leave the touch held.
|
||||
if (data[cstxxx::SYNC_IDX] != cstxxx::SYNC_BYTE) {
|
||||
if (data[6] != TOUCH_ACK) {
|
||||
this->skip_update_ = true;
|
||||
if (!this->touches_.empty())
|
||||
this->set_timeout(REREAD_TIMEOUT_ID, REREAD_DELAY_MS, [this] { this->store_.touched = true; });
|
||||
return;
|
||||
}
|
||||
|
||||
uint8_t num_touches = data[cstxxx::FINGER_COUNT_IDX] & 0x7F;
|
||||
uint8_t num_touches = data[5] & 0x7F;
|
||||
if (num_touches > CST9220_MAX_TOUCHES)
|
||||
num_touches = CST9220_MAX_TOUCHES;
|
||||
|
||||
for (uint8_t i = 0; i < num_touches; i++) {
|
||||
auto touch = cstxxx::decode_touch(data, i);
|
||||
if (touch.event != TOUCH_EVENT_DOWN)
|
||||
// The first point starts at offset 0; subsequent points are offset by the
|
||||
// two status bytes that follow it.
|
||||
const uint8_t *p = data + i * 5 + (i == 0 ? 0 : 2);
|
||||
uint8_t id = p[0] >> 4;
|
||||
uint8_t event = p[0] & 0x0F;
|
||||
if (event != TOUCH_EVENT_DOWN)
|
||||
continue;
|
||||
ESP_LOGV(TAG, "Read touch %d: %d/%d", touch.id, touch.x, touch.y);
|
||||
this->add_raw_touch_position_(touch.id, touch.x, touch.y);
|
||||
// p[3] is shared: high nibble holds the X LSBs, low nibble the Y LSBs.
|
||||
uint16_t x = (p[1] << 4) | (p[3] >> 4);
|
||||
uint16_t y = (p[2] << 4) | (p[3] & 0x0F);
|
||||
ESP_LOGV(TAG, "Read touch %d: %d/%d", id, x, y);
|
||||
this->add_raw_touch_position_(id, x, y);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/components/cstxxx/cstxxx.h"
|
||||
#include "esphome/components/i2c/i2c.h"
|
||||
#include "esphome/components/touchscreen/touchscreen.h"
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
@@ -9,26 +10,41 @@ namespace esphome::cst9220 {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "cst9220.touchscreen");
|
||||
|
||||
static constexpr uint8_t TOUCH_EVENT_DOWN = 0x06;
|
||||
// The CST92xx family uses 16-bit (big-endian) register addresses.
|
||||
static const uint16_t REG_TOUCH_DATA = 0xD000; // touch report
|
||||
static const uint16_t REG_CMD_MODE = 0xD101; // enter command mode
|
||||
static const uint16_t REG_CHECKCODE = 0xD1FC; // firmware check code
|
||||
static const uint16_t REG_RESOLUTION = 0xD1F8; // panel resolution
|
||||
static const uint16_t REG_CHIP_INFO = 0xD204; // chip type + project id
|
||||
|
||||
static constexpr uint16_t CST9220_CHIP_ID = 0x9220;
|
||||
static constexpr uint16_t CST9217_CHIP_ID = 0x9217;
|
||||
static const uint8_t TOUCH_ACK = 0xAB;
|
||||
static const uint8_t TOUCH_EVENT_DOWN = 0x06;
|
||||
|
||||
static constexpr uint8_t CST9220_MAX_TOUCHES = 5;
|
||||
static const uint16_t CST9220_CHIP_ID = 0x9220;
|
||||
static const uint16_t CST9217_CHIP_ID = 0x9217;
|
||||
|
||||
// Maximum simultaneous touch points reported by the family.
|
||||
static const uint8_t CST9220_MAX_TOUCHES = 5;
|
||||
// Report layout: 5 bytes per touch point plus 5 bytes of status/ack overhead.
|
||||
static constexpr size_t CST9220_DATA_LENGTH = CST9220_MAX_TOUCHES * 5 + 5;
|
||||
static const size_t CST9220_DATA_LENGTH = CST9220_MAX_TOUCHES * 5 + 5;
|
||||
|
||||
class CST9220Touchscreen : public cstxxx::CSTTouchscreen {
|
||||
class CST9220Touchscreen : public touchscreen::Touchscreen, public i2c::I2CDevice {
|
||||
public:
|
||||
void setup() override;
|
||||
void dump_config() override;
|
||||
|
||||
void set_interrupt_pin(InternalGPIOPin *pin) { this->interrupt_pin_ = pin; }
|
||||
void set_reset_pin(GPIOPin *pin) { this->reset_pin_ = pin; }
|
||||
|
||||
protected:
|
||||
void update_touches() override;
|
||||
void continue_setup_();
|
||||
|
||||
InternalGPIOPin *interrupt_pin_{};
|
||||
GPIOPin *reset_pin_{};
|
||||
uint16_t chip_id_{};
|
||||
uint16_t project_id_{};
|
||||
bool setup_complete_{};
|
||||
};
|
||||
|
||||
} // namespace esphome::cst9220
|
||||
@@ -1,42 +0,0 @@
|
||||
from esphome import pins
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import i2c, touchscreen
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ID, CONF_INTERRUPT_PIN, CONF_RESET_PIN
|
||||
from esphome.cpp_generator import MockObj, MockObjClass
|
||||
from esphome.types import ConfigType
|
||||
|
||||
CODEOWNERS = ["@clydebarrow", "@latonita"]
|
||||
DEPENDENCIES = ["i2c", "touchscreen"]
|
||||
DOMAIN = "cstxxx"
|
||||
|
||||
cstxxx_ns = cg.esphome_ns.namespace("cstxxx")
|
||||
CSTTouchscreen = cstxxx_ns.class_(
|
||||
"CSTTouchscreen", touchscreen.Touchscreen, i2c.I2CDevice
|
||||
)
|
||||
|
||||
|
||||
def cst_touchscreen_schema(touchscreen_class: MockObjClass, address: int) -> cv.Schema:
|
||||
"""Return the touchscreen schema of a Hynitron driver."""
|
||||
return (
|
||||
touchscreen.touchscreen_schema("100ms")
|
||||
.extend(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(touchscreen_class),
|
||||
cv.Optional(CONF_INTERRUPT_PIN): pins.internal_gpio_input_pin_schema,
|
||||
cv.Optional(CONF_RESET_PIN): pins.gpio_output_pin_schema,
|
||||
}
|
||||
)
|
||||
.extend(i2c.i2c_device_schema(address))
|
||||
)
|
||||
|
||||
|
||||
async def new_cst_touchscreen(config: ConfigType) -> MockObj:
|
||||
"""Create a Hynitron touchscreen and set its pins."""
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
await touchscreen.register_touchscreen(var, config)
|
||||
await i2c.register_i2c_device(var, config)
|
||||
|
||||
await cg.add_pin(var.set_interrupt_pin, config.get(CONF_INTERRUPT_PIN))
|
||||
await cg.add_pin(var.set_reset_pin, config.get(CONF_RESET_PIN))
|
||||
return var
|
||||
@@ -1,13 +0,0 @@
|
||||
#include "cstxxx.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome::cstxxx {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "cstxxx");
|
||||
|
||||
void CSTTouchscreen::fail_check_code_(uint16_t check_code) {
|
||||
ESP_LOGE(TAG, "Firmware check code 0x%04X", check_code);
|
||||
this->mark_failed(LOG_STR("Invalid firmware check code"));
|
||||
}
|
||||
|
||||
} // namespace esphome::cstxxx
|
||||
@@ -1,92 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include "esphome/components/i2c/i2c.h"
|
||||
#include "esphome/components/touchscreen/touchscreen.h"
|
||||
#include "esphome/core/gpio.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome::cstxxx {
|
||||
|
||||
static constexpr uint16_t REG_TOUCH_DATA = 0xD000;
|
||||
static constexpr uint16_t REG_FINGER_COUNT = 0xD005;
|
||||
static constexpr uint16_t REG_COMMAND_MODE = 0xD101;
|
||||
static constexpr uint16_t REG_NORMAL_MODE = 0xD109;
|
||||
static constexpr uint16_t REG_RESOLUTION = 0xD1F8;
|
||||
static constexpr uint16_t REG_FW_CHECK_CODE = 0xD1FC;
|
||||
static constexpr uint16_t REG_CHIP_INFO = 0xD204;
|
||||
static constexpr uint16_t REG_FW_VERSION = 0xD208;
|
||||
|
||||
static constexpr uint8_t FINGER_COUNT_IDX = REG_FINGER_COUNT - REG_TOUCH_DATA;
|
||||
static constexpr uint8_t SYNC_IDX = FINGER_COUNT_IDX + 1;
|
||||
static constexpr uint8_t SYNC_BYTE = 0xAB;
|
||||
static constexpr uint16_t FW_CHECK_CODE = 0xCACA;
|
||||
|
||||
/// Bytes of a touch report holding `points` records; two status bytes follow the first record.
|
||||
constexpr size_t report_size(uint8_t points) { return points * 5 + 2; }
|
||||
|
||||
struct TouchRecord {
|
||||
uint8_t id;
|
||||
uint8_t event;
|
||||
uint16_t x;
|
||||
uint16_t y;
|
||||
uint8_t z;
|
||||
};
|
||||
|
||||
/// Decodes record `index` of a touch report.
|
||||
inline TouchRecord decode_touch(const uint8_t *report, uint8_t index) {
|
||||
const uint8_t *r = report + index * 5 + (index == 0 ? 0 : 2);
|
||||
return {static_cast<uint8_t>(r[0] >> 4), static_cast<uint8_t>(r[0] & 0x0F),
|
||||
static_cast<uint16_t>(r[1] << 4 | r[3] >> 4), static_cast<uint16_t>(r[2] << 4 | (r[3] & 0x0F)), r[4]};
|
||||
}
|
||||
|
||||
class CSTTouchscreen : public touchscreen::Touchscreen, public i2c::I2CDevice {
|
||||
public:
|
||||
void set_interrupt_pin(InternalGPIOPin *pin) { this->interrupt_pin_ = pin; }
|
||||
void set_reset_pin(GPIOPin *pin) { this->reset_pin_ = pin; }
|
||||
|
||||
protected:
|
||||
/// Sets up the interrupt pin, if configured, to fire on `type`.
|
||||
void setup_interrupt_pin_(gpio::InterruptType type) {
|
||||
if (this->interrupt_pin_ == nullptr)
|
||||
return;
|
||||
this->interrupt_pin_->setup();
|
||||
this->attach_interrupt_(this->interrupt_pin_, type);
|
||||
}
|
||||
/// Reads two little-endian words starting at `reg`.
|
||||
bool ESPHOME_ALWAYS_INLINE read_words_(uint16_t reg, uint16_t &low, uint16_t &high) {
|
||||
uint16_t words[2];
|
||||
if (this->read_register16(reg, reinterpret_cast<uint8_t *>(words), sizeof(words)) != i2c::ERROR_OK)
|
||||
return false;
|
||||
low = convert_little_endian(words[0]);
|
||||
high = convert_little_endian(words[1]);
|
||||
return true;
|
||||
}
|
||||
/// Enters command mode, marking the component failed if the write fails.
|
||||
bool enter_command_mode_() {
|
||||
return this->setup_check(this->write_register16(REG_COMMAND_MODE, nullptr, 0) == i2c::ERROR_OK,
|
||||
LOG_STR("Failed to enter command mode"));
|
||||
}
|
||||
/// Checks the firmware check code, marking the component failed if it is unreadable or wrong.
|
||||
bool check_firmware_() {
|
||||
uint16_t boot_time, check_code;
|
||||
if (!this->setup_check(this->read_words_(REG_FW_CHECK_CODE, boot_time, check_code)))
|
||||
return false;
|
||||
if (check_code == FW_CHECK_CODE)
|
||||
return true;
|
||||
this->fail_check_code_(check_code);
|
||||
return false;
|
||||
}
|
||||
/// Logs a wrong firmware check code and marks the component failed.
|
||||
void fail_check_code_(uint16_t check_code);
|
||||
|
||||
InternalGPIOPin *interrupt_pin_{};
|
||||
GPIOPin *reset_pin_{};
|
||||
bool setup_complete_{};
|
||||
};
|
||||
|
||||
} // namespace esphome::cstxxx
|
||||
@@ -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)
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ void Duco::close_request(DucoDevice *device) {
|
||||
bool Duco::parse_byte_(uint8_t byte) {
|
||||
const size_t at = this->rx_size_;
|
||||
if (at >= MAX_FRAME_SIZE) {
|
||||
ESP_LOGW(TAG, "Message longer than %u bytes dropped", static_cast<unsigned>(MAX_FRAME_SIZE));
|
||||
ESP_LOGV(TAG, "Message longer than %u bytes dropped", static_cast<unsigned>(MAX_FRAME_SIZE));
|
||||
return false;
|
||||
}
|
||||
const uint8_t prev = at > 0 ? this->rx_buffer_[at - 1] : 0;
|
||||
@@ -178,17 +178,16 @@ void Duco::send(DucoDevice *device, uint8_t function, std::initializer_list<uint
|
||||
ESP_LOGV_HEX(TAG, frame + 2, size + 5, sizeof(frame), "Sent %s");
|
||||
}
|
||||
|
||||
const LogString *node_type_name(uint8_t type) {
|
||||
const bool bs = (type & NODE_TYPE_BS) != 0;
|
||||
switch (type & ~NODE_TYPE_BS) {
|
||||
static const LogString *node_type_name(uint8_t type) {
|
||||
switch (type) {
|
||||
case 8:
|
||||
return LOG_STR("UCBAT");
|
||||
case 9:
|
||||
return LOG_STR("UC");
|
||||
case 10:
|
||||
return bs ? LOG_STR("BSRH") : LOG_STR("UCRH");
|
||||
return LOG_STR("UCRH");
|
||||
case 12:
|
||||
return bs ? LOG_STR("BSCO2") : LOG_STR("UCCO2");
|
||||
return LOG_STR("UCCO2");
|
||||
case 13:
|
||||
return LOG_STR("VLV");
|
||||
case 17:
|
||||
@@ -231,9 +230,8 @@ void DucoDiscovery::receive_response(const DucoMessage &message) {
|
||||
if (message.size >= 1 && this->next_node_ < NODE_COUNT) {
|
||||
if (message.data[0] != 0) {
|
||||
ESP_LOGV(TAG, "Found node %u: type %u", this->next_node_, message.data[0]);
|
||||
this->node_types_[this->next_node_] = node_type_byte(message);
|
||||
}
|
||||
this->next_node_++;
|
||||
this->node_types_[this->next_node_++] = message.data[0];
|
||||
this->attempts_ = 0;
|
||||
}
|
||||
}
|
||||
@@ -243,7 +241,7 @@ void DucoDiscovery::dump_config() {
|
||||
for (uint8_t node = 0; node < NODE_COUNT; node++) {
|
||||
const uint8_t type = this->node_types_[node];
|
||||
if (type != 0) {
|
||||
ESP_LOGCONFIG(TAG, " Node %u: type %u (%s)", node, type & ~NODE_TYPE_BS, LOG_STR_ARG(node_type_name(type)));
|
||||
ESP_LOGCONFIG(TAG, " Node %u: type %u (%s)", node, type, LOG_STR_ARG(node_type_name(type)));
|
||||
}
|
||||
}
|
||||
if (this->next_node_ < NODE_COUNT) {
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
#include "esphome/components/uart/uart.h"
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
#ifdef USE_TIME
|
||||
#include "esphome/components/time/real_time_clock.h"
|
||||
@@ -18,13 +17,6 @@ namespace esphome::duco {
|
||||
static constexpr uint8_t FUNCTION_NODE = 0x0c; // discovery, status and mode of a node
|
||||
static constexpr uint8_t FUNCTION_NODE_DATA = 0x10; // a block of a node's data (sensors, serial number)
|
||||
static constexpr uint8_t FUNCTION_PARAMETER = 0x24; // read or write a box parameter, set the clock
|
||||
static constexpr uint8_t FUNCTION_ERRORS = 0x30; // the active errors of a node
|
||||
|
||||
/// Set in a node type byte for a node on network type 3 (BS); the node type codes stay below it.
|
||||
static constexpr uint8_t NODE_TYPE_BS = 0x80;
|
||||
|
||||
/// The name of a node type byte.
|
||||
const LogString *node_type_name(uint8_t type);
|
||||
|
||||
/// A received message; data points into the receive buffer and is valid only during the callback.
|
||||
struct DucoMessage {
|
||||
@@ -33,11 +25,6 @@ struct DucoMessage {
|
||||
uint8_t size;
|
||||
};
|
||||
|
||||
/// The node type byte of a non-empty node answer; a one-byte answer has no network type.
|
||||
inline uint8_t node_type_byte(const DucoMessage &message) {
|
||||
return message.data[0] | (message.size >= 2 && message.data[1] == 3 ? NODE_TYPE_BS : 0);
|
||||
}
|
||||
|
||||
class DucoDevice;
|
||||
|
||||
/// The open request of one device: the answer to it is function + 2 with the same message id.
|
||||
@@ -66,9 +53,8 @@ class Duco : public uart::UARTDevice, public Component {
|
||||
void send(DucoDevice *device, uint8_t function, std::initializer_list<uint8_t> data);
|
||||
|
||||
protected:
|
||||
// The longest answer to a request sent here is 39 bytes (box serial number), the longest request 9.
|
||||
// An error answer is 1 + 5 bytes per error, so one with more than eight errors is dropped.
|
||||
static constexpr size_t MAX_FRAME_SIZE = 48;
|
||||
// The longest answer to a request sent here is 25 bytes (node status), the longest request 9
|
||||
static constexpr size_t MAX_FRAME_SIZE = 32;
|
||||
static constexpr size_t MAX_REQUEST_DATA = 9;
|
||||
|
||||
bool parse_byte_(uint8_t byte);
|
||||
@@ -103,7 +89,7 @@ class DucoDiscovery : public DucoDevice {
|
||||
protected:
|
||||
static constexpr uint8_t NODE_COUNT = 0x45;
|
||||
|
||||
std::array<uint8_t, NODE_COUNT> node_types_{}; // node type bytes, 0 when no node answered at that address
|
||||
std::array<uint8_t, NODE_COUNT> node_types_{}; // 0 when no node answered at that address
|
||||
uint8_t next_node_{0};
|
||||
uint8_t attempts_{0};
|
||||
};
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import text_sensor
|
||||
from esphome.components.const import CONF_SERIAL_NUMBER
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ADDRESS, CONF_VERSION
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from .. import (
|
||||
@@ -16,71 +13,15 @@ from .. import (
|
||||
DEPENDENCIES = ["duco"]
|
||||
CODEOWNERS = ["@kokx"]
|
||||
|
||||
DucoTextSensor = duco_ns.class_("DucoTextSensor", DucoDevice, text_sensor.TextSensor)
|
||||
DucoTextReading = duco_ns.enum("DucoTextReading", is_class=True)
|
||||
DucoSerial = duco_ns.class_("DucoSerial", DucoDevice, text_sensor.TextSensor)
|
||||
|
||||
CONF_ERROR = "error"
|
||||
CONF_UPTIME = "uptime"
|
||||
CONF_NODE_TYPE = "node_type"
|
||||
|
||||
# key: (what is read, lowest address, update interval); address 0 of a serial number is the box itself
|
||||
TEXT_SENSORS = {
|
||||
CONF_SERIAL_NUMBER: (DucoTextReading.DUCO_TEXT_READING_SERIAL_NUMBER, 0, "300s"),
|
||||
CONF_VERSION: (DucoTextReading.DUCO_TEXT_READING_VERSION, 1, "300s"),
|
||||
CONF_ERROR: (DucoTextReading.DUCO_TEXT_READING_ERROR, 1, "60s"),
|
||||
CONF_UPTIME: (DucoTextReading.DUCO_TEXT_READING_UPTIME, 1, "60s"),
|
||||
CONF_NODE_TYPE: (DucoTextReading.DUCO_TEXT_READING_NODE_TYPE, 1, "300s"),
|
||||
}
|
||||
|
||||
|
||||
def _schema(min_address: int, update_interval: str) -> cv.Schema:
|
||||
return (
|
||||
text_sensor.text_sensor_schema(DucoTextSensor)
|
||||
.extend(
|
||||
{
|
||||
cv.Optional(CONF_ADDRESS, default=min_address): cv.int_range(
|
||||
min=min_address, max=0x44
|
||||
),
|
||||
}
|
||||
)
|
||||
.extend(cv.polling_component_schema(update_interval))
|
||||
)
|
||||
|
||||
|
||||
_SCHEMAS = {
|
||||
key: _schema(min_address, update_interval)
|
||||
for key, (_, min_address, update_interval) in TEXT_SENSORS.items()
|
||||
}
|
||||
|
||||
CONFIG_SCHEMA = cv.Any(
|
||||
_SCHEMAS[CONF_SERIAL_NUMBER].extend(DUCO_COMPONENT_SCHEMA),
|
||||
cv.All(
|
||||
DUCO_COMPONENT_SCHEMA.extend(
|
||||
{
|
||||
cv.Optional(key): cv.ensure_list(schema)
|
||||
for key, schema in _SCHEMAS.items()
|
||||
}
|
||||
),
|
||||
cv.has_at_least_one_key(*TEXT_SENSORS),
|
||||
),
|
||||
CONFIG_SCHEMA = (
|
||||
text_sensor.text_sensor_schema(DucoSerial)
|
||||
.extend(cv.polling_component_schema("300s"))
|
||||
.extend(DUCO_COMPONENT_SCHEMA)
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
if CONF_ADDRESS in config:
|
||||
var = await text_sensor.new_text_sensor(
|
||||
config,
|
||||
TEXT_SENSORS[CONF_SERIAL_NUMBER][0],
|
||||
config[CONF_ADDRESS],
|
||||
)
|
||||
await register_duco_device(var, config, config[CONF_DUCO_ID])
|
||||
return
|
||||
|
||||
if config.get(CONF_ERROR):
|
||||
cg.add_define("USE_DUCO_ERROR_TEXT_SENSOR")
|
||||
for key, (reading, _, _) in TEXT_SENSORS.items():
|
||||
for entity_config in config.get(key, []):
|
||||
var = await text_sensor.new_text_sensor(
|
||||
entity_config, reading, entity_config[CONF_ADDRESS]
|
||||
)
|
||||
await register_duco_device(var, entity_config, config[CONF_DUCO_ID])
|
||||
var = await text_sensor.new_text_sensor(config)
|
||||
await register_duco_device(var, config, config[CONF_DUCO_ID])
|
||||
@@ -0,0 +1,17 @@
|
||||
#include "serial.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace esphome::duco {
|
||||
|
||||
void DucoSerial::update() { this->parent_->send(this, FUNCTION_NODE_DATA, {0x01, 0x01, 0x00, 0x1a, 0x10}); }
|
||||
|
||||
void DucoSerial::receive_response(const DucoMessage &message) {
|
||||
if (message.size > 2) {
|
||||
// The serial number starts at byte 2 and is padded with zeros
|
||||
const char *serial = reinterpret_cast<const char *>(message.data + 2);
|
||||
this->publish_state(serial, strnlen(serial, message.size - 2));
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace esphome::duco
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/components/text_sensor/text_sensor.h"
|
||||
|
||||
#include "../duco.h"
|
||||
|
||||
namespace esphome::duco {
|
||||
|
||||
class DucoSerial : public DucoDevice, public text_sensor::TextSensor {
|
||||
public:
|
||||
void update() override;
|
||||
void receive_response(const DucoMessage &message) override;
|
||||
};
|
||||
|
||||
} // namespace esphome::duco
|
||||
@@ -1,187 +0,0 @@
|
||||
#include "text_sensor.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/progmem.h"
|
||||
|
||||
namespace esphome::duco {
|
||||
|
||||
#ifdef USE_DUCO_ERROR_TEXT_SENSOR
|
||||
// Only built when an error text sensor is configured; the tables are about 3 kB of flash
|
||||
ESPHOME_LOG_TAG(TAG, "duco.text_sensor");
|
||||
static constexpr size_t MAX_ERROR_TEXT_LENGTH = 255;
|
||||
|
||||
PROGMEM_STRING_TABLE(ErrorCodes, "E01.04.01", "E03.01.01", "E03.01.02", "E03.01.03", "E03.01.04", "E03.01.05",
|
||||
"E03.01.06", "E04.01.01", "E04.01.02", "E04.01.03", "E04.01.04", "E04.01.05", "E04.01.06",
|
||||
"E06.01.01", "E06.01.02", "E06.01.03", "E06.01.04", "E06.01.05", "E06.01.06", "E16.01.01",
|
||||
"E16.01.02", "E16.01.03", "E16.01.04", "E16.01.05", "E16.01.06", "E28.04.01", "E29.01.01",
|
||||
"E29.01.02", "E29.01.03", "E29.01.04", "E29.01.05", "E29.01.06", "E30.01.01", "E30.01.02",
|
||||
"E30.01.03", "E30.01.04", "E30.01.05", "E30.01.06", "E31.19.01", "E32.10.01", "E33.10.01",
|
||||
"E35.17.01", "E35.17.02", "E35.17.03", "E36.24.01", "E36.24.02", "E37.17.01", "E37.17.02",
|
||||
"E37.17.03", "E40.17.01", "E40.17.02", "E40.17.03", "E42.22.01", "E42.22.02", "E43.23.01",
|
||||
"E43.23.02", "E44.06.01", "E44.06.02");
|
||||
PROGMEM_STRING_TABLE(
|
||||
ErrorDescriptions, "No response from the extractor fan.", "ODA temperature sensor value is too low.",
|
||||
"ODA temperature sensor value is too high.", "ODA temperature sensor cannot be read.",
|
||||
"ODA temperature sensor value is unchanged for too long.", "ODA temperature sensor is short-circuited.",
|
||||
"ODA temperature sensor has a bad connection.", "ETA temperature sensor value is too low.",
|
||||
"ETA temperature sensor value is too high.", "ETA temperature sensor cannot be read.",
|
||||
"ETA temperature sensor value is unchanged for too long.", "ETA temperature sensor is short-circuited.",
|
||||
"ETA temperature sensor has a bad connection.", "EHA temperature sensor value is too low.",
|
||||
"EHA temperature sensor value is too high.", "EHA temperature sensor cannot be read.",
|
||||
"EHA temperature sensor value is unchanged for too long.", "EHA temperature sensor is short-circuited.",
|
||||
"EHA temperature sensor has a bad connection.", "Extract air pressure sensor value is too low.",
|
||||
"Extract air pressure sensor value is too high.", "Extract air pressure sensor cannot be read.",
|
||||
"Extract air pressure sensor value is unchanged for too long.", "Extract air pressure sensor is short-circuited.",
|
||||
"Extract air pressure sensor has a bad connection.", "No response from the supply fan.",
|
||||
"Supply air pressure sensor value is too low.", "Supply air pressure sensor value is too high.",
|
||||
"Supply air pressure sensor cannot be read.", "Supply air pressure sensor value is unchanged for too long.",
|
||||
"Supply air pressure sensor is short-circuited.", "Supply air pressure sensor has a bad connection.",
|
||||
"SUP temperature sensor value is too low.", "SUP temperature sensor value is too high.",
|
||||
"SUP temperature sensor cannot be read.", "SUP temperature sensor value is unchanged for too long.",
|
||||
"SUP temperature sensor is short-circuited.", "SUP temperature sensor has a bad connection.",
|
||||
"Filters need replacement.", "Outdoor temperature is too low; ventilation is off for 8 hours.",
|
||||
"Outdoor temperature is too low; ventilation is permanently off.", "Temperature sensor value is too low.",
|
||||
"Temperature sensor value is too high.", "Temperature sensor cannot be read.",
|
||||
"Connection to the weather station has been lost.", "Connection to the outdoor temperature sensor has been lost.",
|
||||
"CO2 sensor value is too low.", "CO2 sensor value is too high.", "CO2 sensor cannot be read.",
|
||||
"Humidity sensor value is too low.", "Humidity sensor value is too high.", "Humidity sensor cannot be read.",
|
||||
"Too many valves are connected.", "Too few valves are connected; at least two are required.",
|
||||
"Flow adjustment has not happened or failed.", "The requested flow rate cannot be achieved.",
|
||||
"No connection to the Duco Pre-Heater.", "A Duco Pre-Heater is connected but not configured.",
|
||||
"Unknown DUCO error");
|
||||
static_assert(ErrorCodes::COUNT + 1 == ErrorDescriptions::COUNT);
|
||||
|
||||
// One line per error, with its description or only its code. Returns the text length, or 0 if it does not fit
|
||||
// in MAX_ERROR_TEXT_LENGTH; text holds one byte more than that so a cut off text is told apart from a full one.
|
||||
static size_t format_errors(const uint8_t *records, uint8_t count, char *text, size_t size, bool descriptions) {
|
||||
size_t pos = 0;
|
||||
for (uint8_t index = 0; index < count; index++) {
|
||||
const uint8_t *record = records + index * 5;
|
||||
const size_t code_start = pos;
|
||||
pos = buf_append_printf(text, size, pos, "E%02u.%02u.%02u", record[1], record[2], record[3]);
|
||||
if (descriptions && pos < size) {
|
||||
const int16_t description_index = progmem_string_table_find<ErrorCodes>(text + code_start, pos - code_start);
|
||||
pos = buf_append_str(text, size, pos, " ");
|
||||
pos = buf_append_str_p(text, size, pos,
|
||||
reinterpret_cast<ESPHOME_PGM_P>(
|
||||
ErrorDescriptions::get_progmem_str(description_index, ErrorDescriptions::LAST_INDEX)));
|
||||
}
|
||||
pos = buf_append_str(text, size, pos, "\n");
|
||||
}
|
||||
return pos <= MAX_ERROR_TEXT_LENGTH ? pos : 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
void DucoTextSensor::update() {
|
||||
switch (this->reading_) {
|
||||
case DucoTextReading::DUCO_TEXT_READING_SERIAL_NUMBER:
|
||||
// Address 0 selects the separate box serial; nodes use a different data block (main board is node 1)
|
||||
if (this->address_ == 0) {
|
||||
this->parent_->send(this, FUNCTION_NODE_DATA, {0x01, 0x01, 0x00, 0x1a, 0x10});
|
||||
} else {
|
||||
this->parent_->send(this, FUNCTION_NODE_DATA, {0x01, this->address_, 0x00, 0x08, 0x06});
|
||||
}
|
||||
break;
|
||||
case DucoTextReading::DUCO_TEXT_READING_VERSION:
|
||||
this->parent_->send(this, FUNCTION_NODE_DATA, {0x01, this->address_, 0x00, 0x00, 0x04});
|
||||
break;
|
||||
case DucoTextReading::DUCO_TEXT_READING_ERROR:
|
||||
#ifdef USE_DUCO_ERROR_TEXT_SENSOR
|
||||
this->parent_->send(this, FUNCTION_ERRORS, {this->address_, 0x00, 0x00, 0x04});
|
||||
#endif
|
||||
break;
|
||||
case DucoTextReading::DUCO_TEXT_READING_UPTIME:
|
||||
this->parent_->send(this, FUNCTION_NODE_DATA, {0x01, this->address_, 0x00, 0x49, 0x04});
|
||||
break;
|
||||
case DucoTextReading::DUCO_TEXT_READING_NODE_TYPE:
|
||||
this->parent_->send(this, FUNCTION_NODE, {0x01, this->address_});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void DucoTextSensor::receive_response(const DucoMessage &message) {
|
||||
switch (this->reading_) {
|
||||
case DucoTextReading::DUCO_TEXT_READING_SERIAL_NUMBER:
|
||||
this->publish_serial_number_(message);
|
||||
break;
|
||||
case DucoTextReading::DUCO_TEXT_READING_VERSION:
|
||||
this->publish_version_(message);
|
||||
break;
|
||||
case DucoTextReading::DUCO_TEXT_READING_ERROR:
|
||||
#ifdef USE_DUCO_ERROR_TEXT_SENSOR
|
||||
this->publish_errors_(message);
|
||||
#endif
|
||||
break;
|
||||
case DucoTextReading::DUCO_TEXT_READING_UPTIME:
|
||||
this->publish_uptime_(message);
|
||||
break;
|
||||
case DucoTextReading::DUCO_TEXT_READING_NODE_TYPE:
|
||||
if (message.size >= 1)
|
||||
this->publish_state(reinterpret_cast<ProgmemStr>(node_type_name(node_type_byte(message))));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void DucoTextSensor::publish_serial_number_(const DucoMessage &message) {
|
||||
if (message.size <= 2)
|
||||
return;
|
||||
// The serial number starts at byte 2 and is padded with zeros
|
||||
const char *serial = reinterpret_cast<const char *>(message.data + 2);
|
||||
const auto serial_length = strnlen(serial, message.size - 2);
|
||||
if (serial_length == 0 || !std::all_of(serial, serial + serial_length, [](char character) {
|
||||
return std::isprint(static_cast<unsigned char>(character));
|
||||
})) {
|
||||
return;
|
||||
}
|
||||
this->publish_state(serial, serial_length);
|
||||
}
|
||||
|
||||
void DucoTextSensor::publish_version_(const DucoMessage &message) {
|
||||
if (message.size < 7)
|
||||
return;
|
||||
const unsigned major = encode_uint16(message.data[3], message.data[2]);
|
||||
const unsigned minor = message.data[4], patch = message.data[6], build = message.data[5];
|
||||
char version[20];
|
||||
snprintf(version, sizeof(version), "%u.%u.%u.%u", major, minor, patch, build);
|
||||
this->publish_state(version);
|
||||
}
|
||||
|
||||
#ifdef USE_DUCO_ERROR_TEXT_SENSOR
|
||||
void DucoTextSensor::publish_errors_(const DucoMessage &message) {
|
||||
if (message.size == 0 || message.data[0] == 0) {
|
||||
this->publish_state("No errors");
|
||||
return;
|
||||
}
|
||||
const uint8_t error_count = message.data[0];
|
||||
if (message.size < 1 + static_cast<size_t>(error_count) * 5) {
|
||||
ESP_LOGW(TAG, "Error answer for %u errors has only %u bytes", error_count, message.size);
|
||||
return;
|
||||
}
|
||||
|
||||
char text[MAX_ERROR_TEXT_LENGTH + 2];
|
||||
size_t length = format_errors(message.data + 1, error_count, text, sizeof(text), true);
|
||||
if (length == 0) // the descriptions do not fit, the codes always do
|
||||
length = format_errors(message.data + 1, error_count, text, sizeof(text), false);
|
||||
this->publish_state(text, length);
|
||||
}
|
||||
#endif
|
||||
|
||||
void DucoTextSensor::publish_uptime_(const DucoMessage &message) {
|
||||
if (message.size < 10)
|
||||
return;
|
||||
const unsigned uptime_minutes = encode_uint16(message.data[9], message.data[8]);
|
||||
const unsigned days = uptime_minutes / 1440;
|
||||
const unsigned hours = uptime_minutes % 1440 / 60;
|
||||
const unsigned minutes = uptime_minutes % 60;
|
||||
char formatted[24];
|
||||
snprintf(formatted, sizeof(formatted), "%ud %uh %um", days, hours, minutes);
|
||||
this->publish_state(formatted);
|
||||
}
|
||||
|
||||
} // namespace esphome::duco
|
||||
@@ -1,38 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/components/text_sensor/text_sensor.h"
|
||||
|
||||
#include "../duco.h"
|
||||
|
||||
namespace esphome::duco {
|
||||
|
||||
/// What a text sensor reads.
|
||||
enum class DucoTextReading : uint8_t {
|
||||
DUCO_TEXT_READING_SERIAL_NUMBER,
|
||||
DUCO_TEXT_READING_VERSION,
|
||||
DUCO_TEXT_READING_ERROR,
|
||||
DUCO_TEXT_READING_UPTIME,
|
||||
DUCO_TEXT_READING_NODE_TYPE,
|
||||
};
|
||||
|
||||
class DucoTextSensor : public DucoDevice, public text_sensor::TextSensor {
|
||||
public:
|
||||
/// address is the node address; a serial number at address 0 is the box itself.
|
||||
DucoTextSensor(DucoTextReading reading, uint8_t address) : reading_(reading), address_(address) {}
|
||||
|
||||
void update() override;
|
||||
void receive_response(const DucoMessage &message) override;
|
||||
|
||||
protected:
|
||||
void publish_serial_number_(const DucoMessage &message);
|
||||
void publish_version_(const DucoMessage &message);
|
||||
#ifdef USE_DUCO_ERROR_TEXT_SENSOR
|
||||
void publish_errors_(const DucoMessage &message);
|
||||
#endif
|
||||
void publish_uptime_(const DucoMessage &message);
|
||||
|
||||
DucoTextReading reading_;
|
||||
uint8_t address_;
|
||||
};
|
||||
|
||||
} // namespace esphome::duco
|
||||
@@ -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
|
||||
|
||||
@@ -10,7 +10,7 @@ from esphome.components.const import CONF_PROVIDER, CONF_REMOTE_ID
|
||||
from esphome.components.packet_interface import (
|
||||
CONF_PACKET_INTERFACE,
|
||||
final_validate_interface,
|
||||
interface_has_layer,
|
||||
interface_layers,
|
||||
interface_packet_size,
|
||||
)
|
||||
from esphome.components.packet_interface.layers import CONF_SESSION
|
||||
@@ -103,13 +103,11 @@ CONFIG_SCHEMA = cv.Schema(
|
||||
|
||||
def _final_validate(config: ConfigType) -> ConfigType:
|
||||
"""With a session layer, which clears the states when the peer is lost, nothing would refresh an unchanged state."""
|
||||
if CONF_TIMEOUT in config and interface_has_layer(
|
||||
config[CONF_PACKET_INTERFACE], CONF_SESSION
|
||||
):
|
||||
layers = interface_layers(config[CONF_PACKET_INTERFACE])
|
||||
if CONF_TIMEOUT in config and CONF_SESSION in layers:
|
||||
raise cv.Invalid(
|
||||
f"Not allowed with a '{CONF_SESSION}' layer, or a link that does its job, which already clears the "
|
||||
"states when the other device cannot be reached; unchanged states may never be sent again, so they "
|
||||
"would time out on a working link",
|
||||
f"Not allowed with a '{CONF_SESSION}' layer, which already clears the states when the other device "
|
||||
"cannot be reached; unchanged states may never be sent again, so they would time out on a working link",
|
||||
path=[CONF_TIMEOUT],
|
||||
)
|
||||
return config
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -7,8 +7,6 @@
|
||||
#include "esphome/core/automation.h"
|
||||
#include "esphome/components/network/ip_address.h"
|
||||
|
||||
#include <atomic>
|
||||
|
||||
#ifdef USE_ETHERNET
|
||||
|
||||
#ifdef USE_ESP32
|
||||
@@ -368,9 +366,6 @@ class EthernetComponent final : public Component {
|
||||
|
||||
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
|
||||
StaticVector<EthernetIPStateListener *, ESPHOME_ETHERNET_IP_STATE_LISTENERS> ip_state_listeners_;
|
||||
#ifdef USE_ESP32
|
||||
std::atomic<uint8_t> ip_state_pending_{0};
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef USE_ETHERNET_CONNECT_TRIGGER
|
||||
|
||||
@@ -129,14 +129,6 @@ void EthernetComponent::log_error_and_mark_failed_(esp_err_t err, const char *me
|
||||
void EthernetComponent::loop() {
|
||||
const uint32_t now = App.get_loop_component_start_time();
|
||||
|
||||
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
|
||||
// The IP events arrive on the event task; the listeners publish states, so notify them here
|
||||
if (this->ip_state_pending_.load(std::memory_order_acquire) != 0) {
|
||||
this->ip_state_pending_.store(0, std::memory_order_relaxed);
|
||||
this->notify_ip_state_listeners_();
|
||||
}
|
||||
#endif
|
||||
|
||||
switch (this->state_) {
|
||||
case EthernetComponentState::STOPPED:
|
||||
if (this->started_) {
|
||||
@@ -778,8 +770,7 @@ void EthernetComponent::eth_event_handler(void *arg, esp_event_base_t event_base
|
||||
event_name = "ETH connected";
|
||||
// For static IP configurations, GOT_IP event may not fire, so notify IP listeners here
|
||||
#if defined(USE_ETHERNET_IP_STATE_LISTENERS) && defined(USE_ETHERNET_MANUAL_IP)
|
||||
global_eth_component->ip_state_pending_.store(1, std::memory_order_release);
|
||||
global_eth_component->enable_loop_soon_any_context();
|
||||
global_eth_component->notify_ip_state_listeners_();
|
||||
#endif
|
||||
#if USE_NETWORK_IPV6
|
||||
// Start SLAAC on link-up, not after the DHCPv4 lease. This also restores the
|
||||
@@ -807,9 +798,6 @@ void EthernetComponent::got_ip_event_handler(void *arg, esp_event_base_t event_b
|
||||
const esp_netif_ip_info_t *ip_info = &event->ip_info;
|
||||
ESP_LOGV(TAG, "[Ethernet event] ETH Got IP " IPSTR, IP2STR(&ip_info->ip));
|
||||
global_eth_component->got_ipv4_address_ = true;
|
||||
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
|
||||
global_eth_component->ip_state_pending_.store(1, std::memory_order_release);
|
||||
#endif
|
||||
#if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
|
||||
global_eth_component->connected_ = global_eth_component->ipv6_count_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT;
|
||||
global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
|
||||
@@ -817,6 +805,9 @@ void EthernetComponent::got_ip_event_handler(void *arg, esp_event_base_t event_b
|
||||
global_eth_component->connected_ = true;
|
||||
global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
|
||||
#endif /* USE_NETWORK_IPV6 */
|
||||
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
|
||||
global_eth_component->notify_ip_state_listeners_();
|
||||
#endif
|
||||
}
|
||||
|
||||
#if USE_NETWORK_IPV6
|
||||
@@ -828,9 +819,6 @@ void EthernetComponent::got_ip6_event_handler(void *arg, esp_event_base_t event_
|
||||
// after a link flap fires another event for the same address.
|
||||
struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
|
||||
global_eth_component->ipv6_count_ = esp_netif_get_all_ip6(global_eth_component->eth_netif_, if_ip6s);
|
||||
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
|
||||
global_eth_component->ip_state_pending_.store(1, std::memory_order_release);
|
||||
#endif
|
||||
#if (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
|
||||
global_eth_component->connected_ =
|
||||
global_eth_component->got_ipv4_address_ && (global_eth_component->ipv6_count_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT);
|
||||
@@ -839,6 +827,9 @@ void EthernetComponent::got_ip6_event_handler(void *arg, esp_event_base_t event_
|
||||
global_eth_component->connected_ = global_eth_component->got_ipv4_address_;
|
||||
global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
|
||||
#endif
|
||||
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
|
||||
global_eth_component->notify_ip_state_listeners_();
|
||||
#endif
|
||||
}
|
||||
#endif /* USE_NETWORK_IPV6 */
|
||||
|
||||
|
||||
@@ -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,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
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
@@ -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),
|
||||
),
|
||||
)
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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",
|
||||
)
|
||||
@@ -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),
|
||||
),
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
from collections.abc import Callable, Iterator
|
||||
from collections.abc import Callable
|
||||
import importlib
|
||||
import pkgutil
|
||||
from typing import Any
|
||||
@@ -6,7 +6,7 @@ from typing import Any
|
||||
import esphome.codegen as cg
|
||||
from esphome.components.const import CONF_MAX_PACKET_SIZE
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ID, CONF_TIMEOUT
|
||||
from esphome.const import CONF_ID
|
||||
from esphome.core import CORE, ID
|
||||
from esphome.cpp_generator import MockObj, MockObjClass
|
||||
import esphome.final_validate as fv
|
||||
@@ -19,20 +19,16 @@ from .layers import (
|
||||
CONF_ADDRESSING,
|
||||
CONF_DESTINATION,
|
||||
CONF_PEERS,
|
||||
CONF_RELIABILITY,
|
||||
CONF_SESSION,
|
||||
STACK_ORDER,
|
||||
PacketInterface,
|
||||
build_stack,
|
||||
check_packet_sizes,
|
||||
check_session,
|
||||
check_single_peer,
|
||||
layer_needing_session,
|
||||
packet_interface_ns,
|
||||
stack_auto_load,
|
||||
stack_schema,
|
||||
)
|
||||
from .layers.hdlc_reliability import DEFAULT_TIMEOUT, check_ack_delay
|
||||
|
||||
CODEOWNERS = ["@clydebarrow"]
|
||||
DOMAIN = "packet_interface"
|
||||
@@ -44,9 +40,6 @@ CONF_PACKET_INTERFACE = "packet_interface"
|
||||
for module_info in pkgutil.iter_modules(layers.__path__):
|
||||
importlib.import_module(f".layers.{module_info.name}", package=__package__)
|
||||
|
||||
# The layer keys that each link class does itself, by class name
|
||||
_PROVIDED_LAYERS: dict[str, tuple[str, ...]] = {}
|
||||
|
||||
LINK_LAYER_SCHEMAS = {
|
||||
cv.Optional(CONF_ADDRESSING): ADDRESSING.schema(),
|
||||
**stack_schema(),
|
||||
@@ -55,7 +48,6 @@ LINK_LAYER_SCHEMAS = {
|
||||
__all__ = [
|
||||
"CONF_MAX_PACKET_SIZE",
|
||||
"CONF_PACKET_INTERFACE",
|
||||
"interface_has_layer",
|
||||
"interface_layers",
|
||||
"interface_packet_size",
|
||||
"PacketInterface",
|
||||
@@ -150,14 +142,6 @@ def interface_packet_size(interface_id: ID) -> int:
|
||||
return check_packet_sizes(layers_config, size)
|
||||
|
||||
|
||||
def interface_has_layer(interface_id: ID, key: str) -> bool:
|
||||
"""During final validation, whether the packet interface with this id has the layer, configured or done by its link."""
|
||||
link, layers_config = _find_interface(interface_id, fv.full_config.get())
|
||||
return key in layers_config or key in _PROVIDED_LAYERS.get(
|
||||
str(link[CONF_ID].type), ()
|
||||
)
|
||||
|
||||
|
||||
def final_validate_interface(key: str) -> Callable[[ConfigType], ConfigType]:
|
||||
"""Final validation for an application: a link with peers must be used through one of the peers."""
|
||||
|
||||
@@ -174,73 +158,25 @@ def final_validate_interface(key: str) -> Callable[[ConfigType], ConfigType]:
|
||||
return validator
|
||||
|
||||
|
||||
def _check_provided_session(config: ConfigType) -> ConfigType:
|
||||
"""A link's own session does not send packets through the layers, so none can need them from the peer."""
|
||||
if key := layer_needing_session(config):
|
||||
raise cv.Invalid(
|
||||
f"This '{key}' needs packets from the peer, which this link does not send through its layers, "
|
||||
"so it cannot be used on this link",
|
||||
path=[key],
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
def reliability_layers(config: ConfigType) -> Iterator[tuple[list, ConfigType]]:
|
||||
"""The reliability layers on a link and in its peers, each with its path in the link's configuration."""
|
||||
if (layer := config.get(CONF_RELIABILITY)) is not None:
|
||||
yield [CONF_RELIABILITY], layer
|
||||
for index, peer in enumerate(config.get(CONF_ADDRESSING, {}).get(CONF_PEERS, [])):
|
||||
if (layer := peer.get(CONF_RELIABILITY)) is not None:
|
||||
yield [CONF_ADDRESSING, CONF_PEERS, index, CONF_RELIABILITY], layer
|
||||
|
||||
|
||||
def _check_default_ack_delays(config: ConfigType) -> ConfigType:
|
||||
"""A reliability layer without a timeout uses the default one on this link."""
|
||||
for path, layer in reliability_layers(config):
|
||||
if CONF_TIMEOUT not in layer:
|
||||
try:
|
||||
check_ack_delay(layer, DEFAULT_TIMEOUT)
|
||||
except cv.Invalid as err:
|
||||
err.prepend(path)
|
||||
raise
|
||||
return config
|
||||
|
||||
|
||||
def packet_interface_schema(
|
||||
class_: MockObjClass,
|
||||
default_max_packet_size: int,
|
||||
max_packet_size_limit: int = 4096,
|
||||
provides: tuple[str, ...] = (),
|
||||
chooses_reliability_timeout: bool = False,
|
||||
) -> cv.Schema:
|
||||
"""Schema for a link platform; provides names the layer keys, such as reliability, that the link does itself.
|
||||
|
||||
chooses_reliability_timeout is for a link that works out a reliability timeout of its own, when none is set.
|
||||
"""
|
||||
if provides:
|
||||
_PROVIDED_LAYERS[str(class_)] = provides
|
||||
link_layers = {
|
||||
key: (
|
||||
cv.invalid(f"This link provides '{key}' itself, so it cannot be configured")
|
||||
if key in provides
|
||||
else schema
|
||||
"""Schema for a link platform, with the layers that can be stacked on it."""
|
||||
return (
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(class_),
|
||||
cv.Optional(
|
||||
CONF_MAX_PACKET_SIZE, default=default_max_packet_size
|
||||
): cv.int_range(16, max_packet_size_limit),
|
||||
**LINK_LAYER_SCHEMAS,
|
||||
}
|
||||
)
|
||||
for key, schema in LINK_LAYER_SCHEMAS.items()
|
||||
}
|
||||
schema = cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(class_),
|
||||
cv.Optional(
|
||||
CONF_MAX_PACKET_SIZE, default=default_max_packet_size
|
||||
): cv.int_range(16, max_packet_size_limit),
|
||||
**link_layers,
|
||||
}
|
||||
).extend(cv.COMPONENT_SCHEMA)
|
||||
if CONF_SESSION in provides:
|
||||
schema = schema.add_extra(_check_provided_session)
|
||||
if not chooses_reliability_timeout:
|
||||
schema = schema.add_extra(_check_default_ack_delays)
|
||||
return schema.add_extra(_validate_layers)
|
||||
.extend(cv.COMPONENT_SCHEMA)
|
||||
.add_extra(_validate_layers)
|
||||
)
|
||||
|
||||
|
||||
async def new_packet_interface(config: ConfigType, *args: Any) -> MockObj:
|
||||
|
||||
@@ -88,12 +88,8 @@ bool BasicFragmentation::send_(const PacketBuffer &data, const PacketMetaData &m
|
||||
header[1] = index | (index + 1 == fragments ? LAST_FRAGMENT : 0);
|
||||
PacketBuffer body(this->tx_buffer_, length);
|
||||
if (!this->lower_->send_to_interface(PacketBuffer(header, HEADER_SIZE, &body, nullptr, 0), meta_data)) {
|
||||
if (index == 0) {
|
||||
ESP_LOGV(TAG, "%s: Fragment 0 of %zu not accepted", this->name_, fragments);
|
||||
} else {
|
||||
// The peer drops the part already sent when the next packet starts
|
||||
ESP_LOGW(TAG, "%s: Packet cut short, fragment %zu of %zu not accepted", this->name_, index, fragments);
|
||||
}
|
||||
// The peer drops the part already sent when the next packet starts
|
||||
ESP_LOGV(TAG, "%s: Fragment %zu of %zu not accepted", this->name_, index, fragments);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,7 +161,7 @@ bool HdlcReliability::send_supervisory_(uint8_t type) {
|
||||
// components run between frames: on a radio, sending blocks, and the peer's frames are received in between. If the
|
||||
// lower layer refuses the frame, it is sent again shortly.
|
||||
bool HdlcReliability::send_pending_() {
|
||||
if (this->vn_ == this->vs_ || (this->resend_held_ && this->vn_ != this->va_))
|
||||
if (this->vn_ == this->vs_)
|
||||
return true;
|
||||
uint8_t control = (this->vn_ << 1) | (this->vr_ << 5);
|
||||
if (!this->send_frame_(control, this->slot_(this->vn_), this->tx_lengths_[this->slot_index_(this->vn_)])) {
|
||||
@@ -178,15 +178,6 @@ bool HdlcReliability::send_pending_() {
|
||||
}
|
||||
|
||||
void HdlcReliability::resend_outstanding_() {
|
||||
this->resend_held_ = false;
|
||||
this->vn_ = this->va_;
|
||||
this->send_pending_();
|
||||
}
|
||||
|
||||
// Resending the whole queue after every timeout lets two peers whose acknowledgements were lost keep sending long
|
||||
// bursts that collide again. The peer answers the oldest frame with its N(R), which also covers frames it already has.
|
||||
void HdlcReliability::resend_oldest_() {
|
||||
this->resend_held_ = true;
|
||||
this->vn_ = this->va_;
|
||||
this->send_pending_();
|
||||
}
|
||||
@@ -222,8 +213,8 @@ void HdlcReliability::on_timeout_() {
|
||||
return;
|
||||
}
|
||||
this->retries_++;
|
||||
ESP_LOGV(TAG, "%s: Timeout, resending frame %u, %u unacknowledged", this->name_, this->va_, this->outstanding_());
|
||||
this->resend_oldest_();
|
||||
ESP_LOGV(TAG, "%s: Timeout, resending %u frames", this->name_, this->outstanding_());
|
||||
this->resend_outstanding_();
|
||||
this->start_timer_();
|
||||
}
|
||||
|
||||
@@ -237,7 +228,6 @@ void HdlcReliability::start_reset_() {
|
||||
this->vr_ = 0;
|
||||
this->retries_ = 0;
|
||||
this->rej_sent_ = false;
|
||||
this->resend_held_ = false;
|
||||
this->ack_sent_();
|
||||
this->cancel_timeout(RETRANSMIT_TIMER_ID);
|
||||
this->request_loop_();
|
||||
@@ -272,11 +262,6 @@ void HdlcReliability::process_ack_(uint8_t nr) {
|
||||
this->head_ = (this->head_ + acked) % this->max_queue_length_;
|
||||
this->va_ = nr;
|
||||
this->retries_ = 0;
|
||||
if (this->resend_held_) {
|
||||
this->resend_held_ = false;
|
||||
if (this->vn_ != this->vs_)
|
||||
this->request_loop_();
|
||||
}
|
||||
if (this->outstanding_() == 0) {
|
||||
this->cancel_timeout(RETRANSMIT_TIMER_ID);
|
||||
} else {
|
||||
@@ -298,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);
|
||||
|
||||
@@ -17,8 +17,7 @@ namespace esphome::packet_interface {
|
||||
* - SABM resets both peers' sequence numbers, and UA answers it.
|
||||
*
|
||||
* Each frame is the HDLC control byte, the payload, then a CRC-16 of both in little endian order.
|
||||
* After the timeout the oldest unacknowledged frame is resent, and the rest follow once the peer answers it, so
|
||||
* a lost acknowledgement costs one frame of airtime. After max_retries the link is reset.
|
||||
* Unacknowledged frames are resent after the timeout; after max_retries the link is reset.
|
||||
*/
|
||||
class HdlcReliability : public PacketInterface {
|
||||
public:
|
||||
@@ -64,7 +63,6 @@ class HdlcReliability : public PacketInterface {
|
||||
bool send_supervisory_(uint8_t type);
|
||||
bool send_pending_();
|
||||
void resend_outstanding_();
|
||||
void resend_oldest_();
|
||||
void retry_send_();
|
||||
/// An RR is owed: at once, or after the ack delay unless an I-frame carries it first.
|
||||
void owe_ack_(bool now);
|
||||
@@ -98,7 +96,6 @@ class HdlcReliability : public PacketInterface {
|
||||
bool ack_pending_ : 1 {false}; // an RR is owed
|
||||
bool ack_due_ : 1 {false}; // and should be sent now
|
||||
bool rej_sent_ : 1 {false};
|
||||
bool resend_held_ : 1 {false}; // only the oldest frame is resent until the peer acknowledges something
|
||||
bool peer_frame_seen_ : 1 {false}; // a numbered frame has arrived since the link came up
|
||||
bool oversize_warned_ : 1 {false};
|
||||
bool reset_wait_logged_ : 1 {false}; // the queue filled while waiting for this reset to be answered
|
||||
|
||||
@@ -176,24 +176,19 @@ def stack_schema() -> dict:
|
||||
return {cv.Optional(kind.key): kind.schema() for kind in STACK_ORDER}
|
||||
|
||||
|
||||
def layer_needing_session(config: ConfigType) -> str | None:
|
||||
"""The key of the first layer in this stack that needs packets back from the peer, if any."""
|
||||
def check_session(config: ConfigType) -> None:
|
||||
"""Layers that need packets back from the peer need a session layer, whose keep-alives send them."""
|
||||
if CONF_SESSION in config:
|
||||
return
|
||||
for kind in STACK_ORDER:
|
||||
if (layer := config.get(kind.key)) is not None and kind.get_type(
|
||||
layer
|
||||
).needs_session(layer):
|
||||
return kind.key
|
||||
return None
|
||||
|
||||
|
||||
def check_session(config: ConfigType) -> None:
|
||||
"""Layers that need packets back from the peer need a session layer, whose keep-alives send them."""
|
||||
if CONF_SESSION not in config and (key := layer_needing_session(config)):
|
||||
raise cv.Invalid(
|
||||
f"This '{key}' needs packets from the peer, so it needs a '{CONF_SESSION}' layer, whose "
|
||||
"keep-alives make sure they are sent",
|
||||
path=[key],
|
||||
)
|
||||
raise cv.Invalid(
|
||||
f"This '{kind.key}' needs packets from the peer, so it needs a '{CONF_SESSION}' layer, whose "
|
||||
"keep-alives make sure they are sent",
|
||||
path=[kind.key],
|
||||
)
|
||||
|
||||
|
||||
def check_single_peer(config: ConfigType, destination: int) -> None:
|
||||
|
||||
@@ -22,25 +22,18 @@ CONF_MAX_RETRIES = "max_retries"
|
||||
# The control byte and the CRC-16
|
||||
FRAME_OVERHEAD = 3
|
||||
|
||||
# Unless the link works out a longer one from how long its packets take, as a radio link does
|
||||
DEFAULT_TIMEOUT = cv.TimePeriodMilliseconds(milliseconds=200)
|
||||
|
||||
HdlcReliability = packet_interface_ns.class_("HdlcReliability", PacketInterface)
|
||||
|
||||
|
||||
def check_ack_delay(config: ConfigType, timeout: cv.TimePeriod) -> None:
|
||||
"""The peer, configured the same, must hear the acknowledgement before its timeout."""
|
||||
if config[CONF_ACK_DELAY].total_milliseconds >= timeout.total_milliseconds:
|
||||
raise cv.Invalid(
|
||||
f"Must be shorter than '{CONF_TIMEOUT}', which is {timeout.total_milliseconds}ms",
|
||||
path=[CONF_ACK_DELAY],
|
||||
)
|
||||
|
||||
|
||||
def _ack_delay_within_timeout(config: ConfigType) -> ConfigType:
|
||||
# Without a timeout, the link checks against the one it chooses
|
||||
if (timeout := config.get(CONF_TIMEOUT)) is not None:
|
||||
check_ack_delay(config, timeout)
|
||||
"""The peer, configured the same, must hear the acknowledgement before its timeout."""
|
||||
if (
|
||||
config[CONF_ACK_DELAY].total_milliseconds
|
||||
>= config[CONF_TIMEOUT].total_milliseconds
|
||||
):
|
||||
raise cv.Invalid(
|
||||
f"Must be shorter than '{CONF_TIMEOUT}'", path=[CONF_ACK_DELAY]
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
@@ -49,7 +42,7 @@ HDLC_SCHEMA = cv.All(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(HdlcReliability),
|
||||
# Retransmitting more often than the main loop runs would exhaust the retries at once
|
||||
cv.Optional(CONF_TIMEOUT): cv.All(
|
||||
cv.Optional(CONF_TIMEOUT, default="200ms"): cv.All(
|
||||
cv.positive_time_period_milliseconds,
|
||||
cv.Range(min=cv.TimePeriod(milliseconds=50)),
|
||||
),
|
||||
@@ -83,7 +76,7 @@ async def build_hdlc(
|
||||
psram=True,
|
||||
)
|
||||
var = cg.new_Pvariable(config[CONF_ID], lower, tx_slots, queue_length)
|
||||
cg.add(var.set_ack_timeout(config.get(CONF_TIMEOUT, DEFAULT_TIMEOUT)))
|
||||
cg.add(var.set_ack_timeout(config[CONF_TIMEOUT]))
|
||||
cg.add(var.set_ack_delay(config[CONF_ACK_DELAY]))
|
||||
cg.add(var.set_max_retries(config[CONF_MAX_RETRIES]))
|
||||
await cg.register_component(var, config)
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace esphome::packet_interface {
|
||||
|
||||
/**
|
||||
* Decides whether a half-duplex radio link may send while its radio reports that it is receiving a packet.
|
||||
*
|
||||
* Sending is refused while the radio is busy, so the packet being received is not lost. A busy period starts when a
|
||||
* send first finds the radio busy, and ends when a send finds it free or end_busy() is called. Once a busy period has
|
||||
* lasted max_busy_ms, sends go ahead, so a busy flag that never clears cannot stop sending for good, however often
|
||||
* sends are tried. Code generation sets max_busy_ms from the time the radio takes to receive the largest packet.
|
||||
*
|
||||
* On a link whose peer replies, sending also takes turns: after a send, a send in a later loop pass waits up to
|
||||
* turnaround_ms, the time the peer takes to start a reply and the radio to notice it, unless a packet arrives first.
|
||||
* Without this, the next frame of a burst goes out on top of the peer's acknowledgement. Sends in the same loop pass,
|
||||
* such as the fragments of one packet, are not held back.
|
||||
*/
|
||||
class ListenBeforeTalk {
|
||||
public:
|
||||
static constexpr uint32_t DEFAULT_MAX_BUSY_MS = 2000;
|
||||
|
||||
void set_max_busy(uint32_t max_busy_ms) { this->max_busy_ms_ = max_busy_ms; }
|
||||
uint32_t get_max_busy() const { return this->max_busy_ms_; }
|
||||
void set_turnaround(uint32_t turnaround_ms) { this->turnaround_ms_ = turnaround_ms; }
|
||||
|
||||
/// True if a packet may be sent at \p now, in the loop pass that started at \p pass; \p busy says whether the
|
||||
/// radio is receiving.
|
||||
bool may_send(bool busy, uint32_t now, uint32_t pass) {
|
||||
if (!busy) {
|
||||
this->busy_ = false;
|
||||
return !this->turn_held_ || pass == this->sent_pass_ || now - this->sent_ms_ >= this->turnaround_ms_;
|
||||
}
|
||||
if (!this->busy_) {
|
||||
this->busy_ = true;
|
||||
this->busy_since_ms_ = now;
|
||||
}
|
||||
return now - this->busy_since_ms_ >= this->max_busy_ms_;
|
||||
}
|
||||
/// Ends the busy period, when the radio is seen to be free other than by a send.
|
||||
void end_busy() { this->busy_ = false; }
|
||||
/// A packet was sent, ending at \p now, in the loop pass that started at \p pass.
|
||||
void sent(uint32_t now, uint32_t pass) {
|
||||
this->turn_held_ = this->turnaround_ms_ != 0;
|
||||
this->sent_ms_ = now;
|
||||
this->sent_pass_ = pass;
|
||||
}
|
||||
/// A packet arrived, so the peer has taken its turn.
|
||||
void received() { this->turn_held_ = false; }
|
||||
/// How long the current busy period has lasted at \p now.
|
||||
uint32_t busy_for(uint32_t now) const { return now - this->busy_since_ms_; }
|
||||
|
||||
protected:
|
||||
uint32_t busy_since_ms_{0};
|
||||
uint32_t max_busy_ms_{DEFAULT_MAX_BUSY_MS};
|
||||
uint32_t sent_ms_{0};
|
||||
uint32_t sent_pass_{0};
|
||||
uint32_t turnaround_ms_{0};
|
||||
bool busy_{false};
|
||||
bool turn_held_{false};
|
||||
};
|
||||
|
||||
} // namespace esphome::packet_interface
|
||||
@@ -1,70 +0,0 @@
|
||||
#include "radio_link.h"
|
||||
#include <cinttypes>
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome::packet_interface {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "packet_interface.radio");
|
||||
|
||||
bool RadioLinkBase::check_size_(size_t size) const {
|
||||
if (size <= this->max_packet_size_)
|
||||
return true;
|
||||
ESP_LOGW(TAG, "Packet of %zu bytes is larger than %zu", size, this->max_packet_size_);
|
||||
return false;
|
||||
}
|
||||
|
||||
bool RadioLinkBase::may_send_(bool busy) {
|
||||
if (busy)
|
||||
this->enable_loop();
|
||||
return this->listen_before_talk_.may_send(busy, this->current_time_ms(), App.get_loop_component_start_time());
|
||||
}
|
||||
|
||||
bool RadioLinkBase::sent_(bool sent, bool busy) {
|
||||
if (busy) {
|
||||
uint32_t busy_ms = this->listen_before_talk_.busy_for(this->current_time_ms());
|
||||
// The radio listens again, and a reception that starts now must be waited for afresh
|
||||
this->listen_before_talk_.end_busy();
|
||||
// The limit is longer than any packet takes, so the radio's busy indication is stuck or the channel is jammed
|
||||
ESP_LOGW(TAG, "Radio busy for %" PRIu32 "ms, %s", busy_ms,
|
||||
sent ? LOG_STR_LITERAL("sent anyway") : LOG_STR_LITERAL("tried to send anyway, which failed"));
|
||||
}
|
||||
if (sent)
|
||||
this->listen_before_talk_.sent(this->current_time_ms(), App.get_loop_component_start_time());
|
||||
return sent;
|
||||
}
|
||||
|
||||
bool RadioLinkBase::skip_empty_() const {
|
||||
ESP_LOGV(TAG, "Empty packet not sent");
|
||||
return true;
|
||||
}
|
||||
|
||||
void RadioLinkBase::radio_not_ready_(bool failed) {
|
||||
if (!failed || this->failed_warned_)
|
||||
return;
|
||||
this->failed_warned_ = true;
|
||||
ESP_LOGW(TAG, "%s: The radio failed to set up, so nothing can be sent", this->name_);
|
||||
}
|
||||
|
||||
void RadioLinkBase::radio_free_() {
|
||||
this->listen_before_talk_.end_busy();
|
||||
this->disable_loop();
|
||||
}
|
||||
|
||||
void RadioLinkBase::receive_(const std::vector<uint8_t> &packet, float rssi, float snr) {
|
||||
// The radio takes packets up to its own limit, so a larger one is from a device configured differently
|
||||
if (packet.size() > this->max_packet_size_) {
|
||||
ESP_LOGV(TAG, "%s: Packet of %zu bytes is larger than %zu, dropped", this->name_, packet.size(),
|
||||
this->max_packet_size_);
|
||||
this->note_received_(false);
|
||||
return;
|
||||
}
|
||||
this->note_received_(true);
|
||||
this->listen_before_talk_.received();
|
||||
PacketMetaData meta_data;
|
||||
meta_data.rssi = rssi;
|
||||
meta_data.snr = snr;
|
||||
this->on_receive_from_interface_(PacketBuffer(packet.data(), packet.size()), meta_data);
|
||||
}
|
||||
|
||||
} // namespace esphome::packet_interface
|
||||
@@ -1,101 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "esphome/components/packet_interface/listen_before_talk.h"
|
||||
#include "esphome/components/packet_interface/packet_interface.h"
|
||||
#include "esphome/core/hal.h"
|
||||
|
||||
namespace esphome::packet_interface {
|
||||
|
||||
/// The parts of RadioLink that do not depend on the radio.
|
||||
class RadioLinkBase : public PacketInterface {
|
||||
public:
|
||||
void set_max_busy(uint32_t max_busy_ms) { this->listen_before_talk_.set_max_busy(max_busy_ms); }
|
||||
void set_turnaround(uint32_t turnaround_ms) { this->listen_before_talk_.set_turnaround(turnaround_ms); }
|
||||
|
||||
protected:
|
||||
explicit RadioLinkBase(size_t max_packet_size) : PacketInterface(max_packet_size) {}
|
||||
/// The time now, not the loop's start: earlier sends in the same loop pass may have waited seconds for the radio.
|
||||
virtual uint32_t current_time_ms() const { return millis(); }
|
||||
/// False if a packet of this size is too large.
|
||||
bool check_size_(size_t size) const;
|
||||
/// False if sending must wait, as the radio is busy or the peer may be about to reply; starts loop() to watch a
|
||||
/// busy radio.
|
||||
bool may_send_(bool busy);
|
||||
/**
|
||||
* Returns \p sent, after ending the busy period and warning if the packet was sent over a radio that seemed busy.
|
||||
* Called only once the radio has the packet, as a log line can run an automation that sends again and overwrites
|
||||
* the buffer it came from.
|
||||
*/
|
||||
bool sent_(bool sent, bool busy);
|
||||
/// Returns true for an empty packet, which the radios cannot send, so there is nothing to retry.
|
||||
bool skip_empty_() const;
|
||||
/// Warns once when a send finds the radio failed; until its setup has run, sends are refused quietly.
|
||||
void radio_not_ready_(bool failed);
|
||||
/// Ends the busy period when loop() finds the radio free.
|
||||
void radio_free_();
|
||||
void receive_(const std::vector<uint8_t> &packet, float rssi, float snr);
|
||||
|
||||
// First, so it fills the spare byte at the end of PacketInterface
|
||||
bool failed_warned_{false};
|
||||
ListenBeforeTalk listen_before_talk_;
|
||||
};
|
||||
|
||||
/**
|
||||
* A packet interface link over a packet radio: each packet is one radio packet, with the RSSI and SNR of received
|
||||
* packets in the metadata. Sending waits for the radio to finish transmitting. A radio cannot hear while it sends, so
|
||||
* sending is refused while the radio is receiving a packet. A reliability layer sends the packet again shortly, and
|
||||
* entity_transport after a delay; other callers drop it, logging at debug level at most. While a busy period lasts,
|
||||
* loop() watches the radio and ends the period as soon as the radio is free, so a later reception starts a new one.
|
||||
*
|
||||
* Radio provides is_receiving(), register_listener(Listener *) and transmit_packet(const uint8_t *, size_t), which
|
||||
* returns an Error whose value 0 means success. Listener declares on_packet(packet, rssi, snr). MaxPacketSize is the
|
||||
* radio's limit.
|
||||
*/
|
||||
template<typename Radio, typename Listener, typename Error, size_t MaxPacketSize>
|
||||
class RadioLink : public RadioLinkBase, public Listener {
|
||||
public:
|
||||
RadioLink(Radio *radio, size_t max_packet_size) : RadioLinkBase(max_packet_size), radio_(radio) {}
|
||||
|
||||
void setup() override {
|
||||
this->radio_->register_listener(this);
|
||||
this->disable_loop();
|
||||
}
|
||||
// Runs only during a busy period; a busy flag that never clears keeps it running. A radio that failed meanwhile
|
||||
// is not read again, as reading it may wait on the radio every time
|
||||
void loop() override {
|
||||
if (!this->radio_->is_ready() || !this->radio_->is_receiving())
|
||||
this->radio_free_();
|
||||
}
|
||||
|
||||
bool send_to_interface(const PacketBuffer &data, const PacketMetaData &meta_data) override {
|
||||
// The radio is set up after the layers above, which may send from their own setup
|
||||
if (!this->radio_->is_ready()) {
|
||||
this->radio_not_ready_(this->radio_->is_failed());
|
||||
return false;
|
||||
}
|
||||
size_t size = data.size();
|
||||
if (size == 0)
|
||||
return this->skip_empty_();
|
||||
bool busy = this->radio_->is_receiving();
|
||||
if (!this->check_size_(size) || !this->may_send_(busy))
|
||||
return false;
|
||||
if (data.is_contiguous()) {
|
||||
auto span = data.as_span();
|
||||
return this->sent_(this->radio_->transmit_packet(span.data(), span.size()) == Error{}, busy);
|
||||
}
|
||||
uint8_t buf[MaxPacketSize];
|
||||
data.copy_to(buf, size);
|
||||
return this->sent_(this->radio_->transmit_packet(buf, size) == Error{}, busy);
|
||||
}
|
||||
|
||||
void on_packet(const std::vector<uint8_t> &packet, float rssi, float snr) override {
|
||||
this->receive_(packet, rssi, snr);
|
||||
}
|
||||
|
||||
protected:
|
||||
Radio *radio_;
|
||||
};
|
||||
|
||||
} // namespace esphome::packet_interface
|
||||
@@ -1,311 +0,0 @@
|
||||
"""Shared code generation for the packet interface links over packet radios, such as the SX126x and SX127x."""
|
||||
|
||||
from collections.abc import Callable, Iterator
|
||||
import logging
|
||||
import math
|
||||
|
||||
import esphome.codegen as cg
|
||||
from esphome.components.const import CONF_MAX_PACKET_SIZE
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_FRAGMENTATION, CONF_ID, CONF_TIMEOUT
|
||||
from esphome.core import CORE
|
||||
from esphome.cpp_generator import MockObjClass
|
||||
import esphome.final_validate as fv
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from . import new_packet_interface, packet_interface_schema, reliability_layers
|
||||
from .layers import (
|
||||
ADDRESSING,
|
||||
CONF_ADDRESSING,
|
||||
CONF_PEERS,
|
||||
CONF_RELIABILITY,
|
||||
STACK_ORDER,
|
||||
)
|
||||
from .layers.basic_fragmentation import HEADER_SIZE as FRAGMENT_HEADER_SIZE
|
||||
from .layers.hdlc_reliability import (
|
||||
CONF_ACK_DELAY,
|
||||
CONF_MAX_QUEUE_LENGTH,
|
||||
DEFAULT_TIMEOUT,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# The largest packet a radio receives, from any device on the channel, given the radio's settings
|
||||
ReceiveLimit = Callable[[ConfigType], int]
|
||||
|
||||
# The radios' payload length register is 8 bits
|
||||
MAX_PACKET_SIZE = 255
|
||||
# The smallest max_packet_size that packet_interface_schema() takes
|
||||
MIN_PACKET_SIZE = 16
|
||||
|
||||
# Listen before talk holds a send back for at most the airtime of the largest packet, and never less than this
|
||||
MIN_MAX_BUSY_MS = 2000
|
||||
# Room for the preamble detection and the radio's own delays
|
||||
MARGIN = 1.25
|
||||
# The radio drivers stop waiting for a packet to be sent after this long
|
||||
TRANSMIT_TIMEOUT_MS = 4000
|
||||
# An acknowledgement, with room for the layers below the reliability layer, such as addressing and the rolling code
|
||||
ACK_PACKET_SIZE = 32
|
||||
# From the end of a packet to the start of the peer's reply: a loop pass to read the packet, one to answer it, and the
|
||||
# radio's start-up
|
||||
REPLY_START_MS = 50
|
||||
# A LoRa packet's explicit header is in its first 8 symbols
|
||||
LORA_HEADER_SYMBOLS = 8
|
||||
|
||||
|
||||
def _lora_symbol_s(radio: ConfigType) -> float:
|
||||
bandwidth_hz = (
|
||||
float(str(radio["bandwidth"]).removesuffix("kHz").replace("_", ".")) * 1000
|
||||
)
|
||||
return (1 << radio["spreading_factor"]) / bandwidth_hz
|
||||
|
||||
|
||||
def packet_airtime_ms(radio: ConfigType, size: int) -> float:
|
||||
"""The time a radio configured as in radio takes to send a packet of size bytes.
|
||||
|
||||
LoRa follows the Semtech formula for an explicit header; the low data rate optimization is assumed when a symbol
|
||||
takes more than 16 ms, as the drivers enable it. Other modulations count the preamble, sync word, length byte,
|
||||
payload and CRC at the bitrate, treating the preamble size as bytes, which gives the longer time.
|
||||
"""
|
||||
if str(radio["modulation"]) == "LORA":
|
||||
spreading_factor = radio["spreading_factor"]
|
||||
coding_rate = int(str(radio["coding_rate"])[-1]) - 4
|
||||
symbol_s = _lora_symbol_s(radio)
|
||||
low_data_rate = 1 if symbol_s > 0.016 else 0
|
||||
crc = 16 if radio.get("crc_enable", False) else 0
|
||||
payload_symbols = 8 + max(
|
||||
math.ceil(
|
||||
(8 * size - 4 * spreading_factor + 28 + crc)
|
||||
/ (4 * (spreading_factor - 2 * low_data_rate))
|
||||
)
|
||||
* (coding_rate + 4),
|
||||
0,
|
||||
)
|
||||
return (radio["preamble_size"] + 4.25 + payload_symbols) * symbol_s * 1000
|
||||
bytes_sent = (
|
||||
radio["preamble_size"] + len(radio.get("sync_value", [])) + 1 + size + 2
|
||||
)
|
||||
return bytes_sent * 8 / radio["bitrate"] * 1000
|
||||
|
||||
|
||||
def turnaround_ms(radio: ConfigType) -> int:
|
||||
"""How long, after sending, to wait for the peer's reply to start and for the radio to receive its header, so
|
||||
the peer's reply is not sent over.
|
||||
"""
|
||||
if str(radio["modulation"]) == "LORA":
|
||||
symbols = radio["preamble_size"] + 4.25 + LORA_HEADER_SYMBOLS
|
||||
header_ms = symbols * _lora_symbol_s(radio) * 1000
|
||||
else:
|
||||
header_bytes = radio["preamble_size"] + len(radio.get("sync_value", [])) + 1
|
||||
header_ms = header_bytes * 8 / radio["bitrate"] * 1000
|
||||
return math.ceil((header_ms + REPLY_START_MS) * MARGIN)
|
||||
|
||||
|
||||
def max_busy_ms(radio: ConfigType, max_packet_size: int) -> int:
|
||||
"""How long listen before talk may hold a send back, for packets of up to max_packet_size bytes."""
|
||||
return max(
|
||||
MIN_MAX_BUSY_MS, math.ceil(packet_airtime_ms(radio, max_packet_size) * MARGIN)
|
||||
)
|
||||
|
||||
|
||||
def _fits_transmit_time(radio: ConfigType, size: int) -> bool:
|
||||
return packet_airtime_ms(radio, size) * MARGIN <= TRANSMIT_TIMEOUT_MS
|
||||
|
||||
|
||||
def _largest_sendable(radio: ConfigType, limit: int) -> int | None:
|
||||
"""The largest max_packet_size, up to limit, whose packets the radio sends within the drivers' wait."""
|
||||
return next(
|
||||
(
|
||||
size
|
||||
for size in range(limit, MIN_PACKET_SIZE - 1, -1)
|
||||
if _fits_transmit_time(radio, size)
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def channel_packet_size(radio: ConfigType, receive_limit: int) -> int:
|
||||
"""The largest packet any device on the channel can send: no more than the radio receives, and no more than a
|
||||
device with these radio settings is allowed to send.
|
||||
"""
|
||||
return _largest_sendable(radio, receive_limit) or receive_limit
|
||||
|
||||
|
||||
def reliability_timeout_ms(
|
||||
radio: ConfigType, packet_size: int, ack_delay_ms: int
|
||||
) -> int:
|
||||
"""The shortest reliability timeout: before acknowledging, the peer may be sending, or receiving from another
|
||||
device, a packet of packet_size bytes.
|
||||
"""
|
||||
airtime = packet_airtime_ms(radio, packet_size) + packet_airtime_ms(
|
||||
radio, ACK_PACKET_SIZE
|
||||
)
|
||||
return math.ceil(airtime * MARGIN) + ack_delay_ms
|
||||
|
||||
|
||||
def _check_transmit_time(config: ConfigType, radio: ConfigType) -> None:
|
||||
"""The radio drivers give up on a packet that takes longer to send than they wait."""
|
||||
size = config[CONF_MAX_PACKET_SIZE]
|
||||
if _fits_transmit_time(radio, size):
|
||||
return
|
||||
largest = _largest_sendable(radio, size - 1)
|
||||
advice = (
|
||||
f"set '{CONF_MAX_PACKET_SIZE}' to {largest} or less"
|
||||
if largest is not None
|
||||
else "use faster radio settings"
|
||||
)
|
||||
raise cv.Invalid(
|
||||
f"With these radio settings a packet of {size} bytes takes {packet_airtime_ms(radio, size):.0f} ms to "
|
||||
f"send, longer than the radio waits for; {advice}",
|
||||
path=[CONF_MAX_PACKET_SIZE],
|
||||
)
|
||||
|
||||
|
||||
def _check_reliability_timeouts(
|
||||
config: ConfigType, radio: ConfigType, packet_size: int
|
||||
) -> None:
|
||||
"""A reliability timeout shorter than a packet and its acknowledgement take would send packets again too soon."""
|
||||
for path, layer in reliability_layers(config):
|
||||
if (timeout := layer.get(CONF_TIMEOUT)) is None:
|
||||
continue
|
||||
needed = reliability_timeout_ms(
|
||||
radio, packet_size, layer[CONF_ACK_DELAY].total_milliseconds
|
||||
)
|
||||
if timeout.total_milliseconds < needed:
|
||||
raise cv.Invalid(
|
||||
f"With these radio settings a packet and its acknowledgement can take {needed} ms, so this must be "
|
||||
f"at least {needed}ms; leave it out to use that",
|
||||
path=[*path, CONF_TIMEOUT],
|
||||
)
|
||||
|
||||
|
||||
def _stacks(config: ConfigType) -> Iterator[tuple[ConfigType, int]]:
|
||||
"""The link's stacks of layers, on the link or in each peer, each with the largest packet below it."""
|
||||
size = config[CONF_MAX_PACKET_SIZE]
|
||||
if (addressing := config.get(CONF_ADDRESSING)) is None:
|
||||
yield config, size
|
||||
return
|
||||
size = ADDRESSING.get_type(addressing).packet_size(addressing, size)
|
||||
yield from ((stack, size) for stack in addressing.get(CONF_PEERS, [config]))
|
||||
|
||||
|
||||
def _radio_packets_per_send(stack: ConfigType, size: int) -> int:
|
||||
"""How many radio packets one send through the stack can send one after another, each waited for in turn."""
|
||||
if (reliability := stack.get(CONF_RELIABILITY)) is not None:
|
||||
# It sends, and after a timeout sends again, every packet in its queue at once
|
||||
return reliability[CONF_MAX_QUEUE_LENGTH]
|
||||
if (fragmentation := stack.get(CONF_FRAGMENTATION)) is None:
|
||||
return 1
|
||||
for kind in STACK_ORDER:
|
||||
if kind.key == CONF_FRAGMENTATION:
|
||||
break
|
||||
if (layer := stack.get(kind.key)) is not None:
|
||||
size = kind.get_type(layer).packet_size(layer, size)
|
||||
fragment = size - FRAGMENT_HEADER_SIZE
|
||||
if fragment <= 0:
|
||||
return 1
|
||||
return math.ceil(fragmentation[CONF_MAX_PACKET_SIZE] / fragment)
|
||||
|
||||
|
||||
def _warn_long_sends(config: ConfigType, radio: ConfigType) -> None:
|
||||
"""The radio drivers wait for each packet to be sent, so a send of several packets holds up everything else."""
|
||||
airtime = packet_airtime_ms(radio, config[CONF_MAX_PACKET_SIZE])
|
||||
for stack, size in _stacks(config):
|
||||
count = _radio_packets_per_send(stack, size)
|
||||
if count > 1 and count * airtime > TRANSMIT_TIMEOUT_MS:
|
||||
_LOGGER.warning(
|
||||
"A send through '%s' can send %d radio packets in a row, holding up other components for about "
|
||||
"%.1f s while the radio sends them; reduce '%s' or the reliability '%s', or use faster radio "
|
||||
"settings",
|
||||
stack[CONF_ID].id,
|
||||
count,
|
||||
count * airtime / 1000,
|
||||
CONF_MAX_PACKET_SIZE,
|
||||
CONF_MAX_QUEUE_LENGTH,
|
||||
)
|
||||
|
||||
|
||||
def radio_link_schema(
|
||||
class_: MockObjClass, radio_id_key: str, radio_class: MockObjClass
|
||||
) -> cv.Schema:
|
||||
"""Schema for a radio link, referring to its radio by radio_id_key."""
|
||||
return packet_interface_schema(
|
||||
class_, MAX_PACKET_SIZE, MAX_PACKET_SIZE, chooses_reliability_timeout=True
|
||||
).extend({cv.GenerateID(radio_id_key): cv.use_id(radio_class)})
|
||||
|
||||
|
||||
def _two_way_layer(config: ConfigType) -> str | None:
|
||||
"""The first layer on the link or in a peer that keeps state for one peer, so needs packets back from it."""
|
||||
for stack in (config, *config.get(CONF_ADDRESSING, {}).get(CONF_PEERS, [])):
|
||||
for kind in STACK_ORDER:
|
||||
if (layer := stack.get(kind.key)) is not None and kind.get_type(
|
||||
layer
|
||||
).single_peer(layer):
|
||||
return kind.key
|
||||
return None
|
||||
|
||||
|
||||
def takes_turns(config: ConfigType) -> bool:
|
||||
"""Whether sends wait for the peer to reply: only a reliability layer's peer answers each packet at once."""
|
||||
return next(reliability_layers(config), None) is not None
|
||||
|
||||
|
||||
def radio_link_final_validate(
|
||||
radio_id_key: str,
|
||||
payload_length_key: str,
|
||||
rx_start_key: str,
|
||||
check: Callable[[ConfigType, ConfigType], None] | None = None,
|
||||
receive_limit: ReceiveLimit = lambda radio: MAX_PACKET_SIZE,
|
||||
) -> Callable[[ConfigType], ConfigType]:
|
||||
"""Final validation for a radio link: packets vary in length, the radio listens after sending when a layer needs
|
||||
replies, and check(link, radio) checks the rest.
|
||||
"""
|
||||
|
||||
def validator(config: ConfigType) -> ConfigType:
|
||||
radio = fv.get_declaring_config(config[radio_id_key])
|
||||
if radio[payload_length_key] != 0:
|
||||
raise cv.Invalid(
|
||||
f"Packets vary in length, so the radio's '{payload_length_key}' must be 0",
|
||||
path=[radio_id_key],
|
||||
)
|
||||
if not radio[rx_start_key] and (layer := _two_way_layer(config)) is not None:
|
||||
raise cv.Invalid(
|
||||
f"This '{layer}' needs packets from the peer, but the radio sleeps after sending unless "
|
||||
f"'{rx_start_key}' is true",
|
||||
path=[radio_id_key],
|
||||
)
|
||||
if check is not None:
|
||||
check(config, radio)
|
||||
_check_transmit_time(config, radio)
|
||||
_check_reliability_timeouts(
|
||||
config, radio, channel_packet_size(radio, receive_limit(radio))
|
||||
)
|
||||
_warn_long_sends(config, radio)
|
||||
return config
|
||||
|
||||
return validator
|
||||
|
||||
|
||||
async def new_radio_link(
|
||||
config: ConfigType,
|
||||
radio_id_key: str,
|
||||
receive_limit: ReceiveLimit = lambda radio: MAX_PACKET_SIZE,
|
||||
) -> None:
|
||||
"""Create a radio link, with timings worked out from the radio's settings and the largest packet on the channel."""
|
||||
radio_config = fv.get_declaring_config(config[radio_id_key], CORE.config)
|
||||
packet_size = channel_packet_size(radio_config, receive_limit(radio_config))
|
||||
# A reliability layer without a timeout gets one long enough for a packet and its acknowledgement
|
||||
for _, layer in reliability_layers(config):
|
||||
if CONF_TIMEOUT not in layer:
|
||||
needed = reliability_timeout_ms(
|
||||
radio_config, packet_size, layer[CONF_ACK_DELAY].total_milliseconds
|
||||
)
|
||||
layer[CONF_TIMEOUT] = cv.TimePeriodMilliseconds(
|
||||
milliseconds=max(DEFAULT_TIMEOUT.total_milliseconds, needed)
|
||||
)
|
||||
radio = await cg.get_variable(config[radio_id_key])
|
||||
var = await new_packet_interface(config, radio, config[CONF_MAX_PACKET_SIZE])
|
||||
cg.add(var.set_max_busy(max_busy_ms(radio_config, packet_size)))
|
||||
# Taking turns would hold up a run of one-way sends, and a reliability layer sends again what it refuses
|
||||
if takes_turns(config):
|
||||
cg.add(var.set_turnaround(turnaround_ms(radio_config)))
|
||||
@@ -46,8 +46,6 @@ class XxteaEncryption : public PacketInterface {
|
||||
void setup() override;
|
||||
void dump_config() override;
|
||||
bool send_to_interface(const PacketBuffer &data, const PacketMetaData &meta_data) override;
|
||||
// One encrypted packet per packet, so a fragmentation layer above sees the link's room
|
||||
size_t get_send_capacity() const override { return this->lower_->get_send_capacity(); }
|
||||
|
||||
void set_key(std::initializer_list<uint32_t> key);
|
||||
|
||||
|
||||
@@ -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,7 +48,7 @@ CONF_WHITENING_ENABLE = "whitening_enable"
|
||||
CONF_WHITENING_INITIAL = "whitening_initial"
|
||||
|
||||
sx126x_ns = cg.esphome_ns.namespace("sx126x")
|
||||
SX126x = sx126x_ns.class_("SX126x", cg.Component)
|
||||
SX126x = sx126x_ns.class_("SX126x", cg.Component, spi.SPIDevice)
|
||||
SX126xListener = sx126x_ns.class_("SX126xListener")
|
||||
SX126xBw = sx126x_ns.enum("SX126xBw")
|
||||
SX126xPacketType = sx126x_ns.enum("SX126xPacketType")
|
||||
@@ -217,9 +217,7 @@ CONFIG_SCHEMA = (
|
||||
cv.Required(CONF_RF_SWITCH): cv.boolean,
|
||||
cv.Optional(CONF_SHAPING, default="NONE"): cv.enum(SHAPING),
|
||||
cv.Optional(CONF_SPREADING_FACTOR, default=7): cv.int_range(min=6, max=12),
|
||||
cv.Optional(CONF_SYNC_VALUE, default=[]): cv.All(
|
||||
cv.ensure_list(cv.hex_uint8_t), cv.Length(max=8)
|
||||
),
|
||||
cv.Optional(CONF_SYNC_VALUE, default=[]): cv.ensure_list(cv.hex_uint8_t),
|
||||
cv.Optional(CONF_TCXO_VOLTAGE, default="NONE"): cv.enum(TCXO_VOLTAGE),
|
||||
cv.Optional(CONF_TCXO_DELAY, default="5ms"): cv.All(
|
||||
cv.positive_time_period_microseconds,
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
from esphome.components import packet_interface
|
||||
from esphome.components.packet_interface.radio_link import (
|
||||
new_radio_link,
|
||||
radio_link_final_validate,
|
||||
radio_link_schema,
|
||||
)
|
||||
import esphome.config_validation as cv
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from .. import (
|
||||
CONF_MODULATION,
|
||||
CONF_PAYLOAD_LENGTH,
|
||||
CONF_RX_START,
|
||||
CONF_SX126X_ID,
|
||||
CONF_SYNC_VALUE,
|
||||
SX126x,
|
||||
SX126xListener,
|
||||
sx126x_ns,
|
||||
)
|
||||
|
||||
CODEOWNERS = ["@clydebarrow"]
|
||||
DEPENDENCIES = ["sx126x"]
|
||||
|
||||
SX126xPacketInterface = sx126x_ns.class_(
|
||||
"SX126xPacketInterface", packet_interface.PacketInterface, SX126xListener
|
||||
)
|
||||
|
||||
CONFIG_SCHEMA = radio_link_schema(SX126xPacketInterface, CONF_SX126X_ID, SX126x)
|
||||
|
||||
|
||||
def _check_fsk(config: ConfigType, radio: ConfigType) -> None:
|
||||
"""Without LoRa, the radio can tell that a packet is arriving only from its sync word, which listen before talk
|
||||
needs.
|
||||
"""
|
||||
if radio[CONF_MODULATION] != "LORA" and not radio[CONF_SYNC_VALUE]:
|
||||
raise cv.Invalid(
|
||||
f"Without LoRa modulation the radio needs a '{CONF_SYNC_VALUE}', so that the link can tell when a packet "
|
||||
"is arriving and not send over it",
|
||||
path=[CONF_SX126X_ID],
|
||||
)
|
||||
|
||||
|
||||
FINAL_VALIDATE_SCHEMA = radio_link_final_validate(
|
||||
CONF_SX126X_ID, CONF_PAYLOAD_LENGTH, CONF_RX_START, _check_fsk
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
await new_radio_link(config, CONF_SX126X_ID)
|
||||
@@ -1,10 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/components/packet_interface/radio_link.h"
|
||||
#include "esphome/components/sx126x/sx126x.h"
|
||||
|
||||
namespace esphome::sx126x {
|
||||
|
||||
using SX126xPacketInterface = packet_interface::RadioLink<SX126x, SX126xListener, SX126xError, SX126X_MAX_PACKET_SIZE>;
|
||||
|
||||
} // namespace esphome::sx126x
|
||||
@@ -1,97 +0,0 @@
|
||||
#pragma once
|
||||
#include "sx126x_reg.h"
|
||||
#include <array>
|
||||
#include <span>
|
||||
#include <algorithm>
|
||||
|
||||
namespace esphome::sx126x {
|
||||
enum SX126xBw : uint8_t {
|
||||
// FSK
|
||||
SX126X_BW_4800,
|
||||
SX126X_BW_5800,
|
||||
SX126X_BW_7300,
|
||||
SX126X_BW_9700,
|
||||
SX126X_BW_11700,
|
||||
SX126X_BW_14600,
|
||||
SX126X_BW_19500,
|
||||
SX126X_BW_23400,
|
||||
SX126X_BW_29300,
|
||||
SX126X_BW_39000,
|
||||
SX126X_BW_46900,
|
||||
SX126X_BW_58600,
|
||||
SX126X_BW_78200,
|
||||
SX126X_BW_93800,
|
||||
SX126X_BW_117300,
|
||||
SX126X_BW_156200,
|
||||
SX126X_BW_187200,
|
||||
SX126X_BW_234300,
|
||||
SX126X_BW_312000,
|
||||
SX126X_BW_373600,
|
||||
SX126X_BW_467000,
|
||||
// LORA
|
||||
SX126X_BW_7810,
|
||||
SX126X_BW_10420,
|
||||
SX126X_BW_15630,
|
||||
SX126X_BW_20830,
|
||||
SX126X_BW_31250,
|
||||
SX126X_BW_41670,
|
||||
SX126X_BW_62500,
|
||||
SX126X_BW_125000,
|
||||
SX126X_BW_250000,
|
||||
SX126X_BW_500000,
|
||||
};
|
||||
|
||||
// Requested settings are separate from the last successfully applied profile.
|
||||
// Bounded sync storage makes profile snapshots allocation-free.
|
||||
struct RadioProfile {
|
||||
uint32_t bitrate{0};
|
||||
uint32_t deviation{0};
|
||||
uint32_t frequency{0};
|
||||
uint32_t tcxo_delay{0};
|
||||
uint16_t crc_polynomial{0};
|
||||
uint16_t crc_initial{0};
|
||||
uint16_t whitening_initial{0};
|
||||
uint16_t preamble_detect{0};
|
||||
uint16_t preamble_size{0};
|
||||
SX126xBw bandwidth{SX126X_BW_125000};
|
||||
uint8_t crc_size{0};
|
||||
uint8_t tcxo_voltage{0};
|
||||
uint8_t coding_rate{0};
|
||||
uint8_t modulation{PACKET_TYPE_LORA};
|
||||
uint8_t pa_ramp{0};
|
||||
uint8_t shaping{0};
|
||||
uint8_t spreading_factor{0};
|
||||
int8_t pa_power{0};
|
||||
uint8_t payload_length{0};
|
||||
bool sx1261{false};
|
||||
bool crc_enable{false};
|
||||
bool crc_inverted{false};
|
||||
bool whitening_enable{false};
|
||||
bool rx_start{false};
|
||||
bool rf_switch{false};
|
||||
std::array<uint8_t, 8> sync_value{};
|
||||
uint8_t sync_size{0};
|
||||
bool sync_valid{true};
|
||||
void set_sync_value(std::span<const uint8_t> bytes) {
|
||||
this->sync_valid = bytes.size() <= this->sync_value.size();
|
||||
if (!this->sync_valid) {
|
||||
return;
|
||||
}
|
||||
std::copy(bytes.begin(), bytes.end(), this->sync_value.begin());
|
||||
this->sync_size = bytes.size();
|
||||
}
|
||||
size_t max_packet_size() const { return this->payload_length > 0 ? this->payload_length : 255; }
|
||||
};
|
||||
|
||||
// The parts of the last successfully applied profile that runtime operations read.
|
||||
// SetPacketParams is encoded once; sends only change its payload length byte.
|
||||
struct AppliedProfile {
|
||||
uint32_t frequency{0};
|
||||
std::array<uint8_t, 9> packet_params{};
|
||||
uint8_t packet_params_size{0};
|
||||
uint8_t payload_length{0};
|
||||
uint8_t modulation{PACKET_TYPE_LORA};
|
||||
bool rx_start{false};
|
||||
size_t max_packet_size() const { return this->payload_length > 0 ? this->payload_length : 255; }
|
||||
};
|
||||
} // namespace esphome::sx126x
|
||||
@@ -2,217 +2,534 @@
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/progmem.h"
|
||||
|
||||
namespace esphome::sx126x {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "sx126x");
|
||||
static constexpr uint32_t TRANSMIT_TIMEOUT_MS = 4000;
|
||||
static constexpr uint32_t MAX_TRANSMIT_TIMEOUT_MS = 262143; // 24-bit SetTx timeout in 1/64 ms steps
|
||||
static constexpr uint32_t RECONFIGURE_INTERVAL_ID = 0;
|
||||
static constexpr uint32_t RECONFIGURE_INTERVAL_MS = 1000;
|
||||
static constexpr uint16_t RAMP[8] PROGMEM = {10, 20, 40, 80, 200, 800, 1700, 3400};
|
||||
// Aligned 32 bit loads from flash are safe on ESP8266, so this table is read directly
|
||||
static constexpr uint32_t BW_HZ[31] PROGMEM = {4800, 5800, 7300, 9700, 11700, 14600, 19500, 23400,
|
||||
29300, 39000, 46900, 58600, 78200, 93800, 117300, 156200,
|
||||
187200, 234300, 312000, 373600, 467000, 7810, 10420, 15630,
|
||||
20830, 31250, 41670, 62500, 125000, 250000, 500000};
|
||||
static constexpr uint8_t BW_LORA[10] PROGMEM = {LORA_BW_7810, LORA_BW_10420, LORA_BW_15630, LORA_BW_20830,
|
||||
LORA_BW_31250, LORA_BW_41670, LORA_BW_62500, LORA_BW_125000,
|
||||
LORA_BW_250000, LORA_BW_500000};
|
||||
static constexpr uint8_t BW_FSK[21] PROGMEM = {
|
||||
FSK_BW_4800, FSK_BW_5800, FSK_BW_7300, FSK_BW_9700, FSK_BW_11700, FSK_BW_14600, FSK_BW_19500,
|
||||
FSK_BW_23400, FSK_BW_29300, FSK_BW_39000, FSK_BW_46900, FSK_BW_58600, FSK_BW_78200, FSK_BW_93800,
|
||||
FSK_BW_117300, FSK_BW_156200, FSK_BW_187200, FSK_BW_234300, FSK_BW_312000, FSK_BW_373600, FSK_BW_467000};
|
||||
|
||||
// Indexed by SX126xError.
|
||||
PROGMEM_STRING_TABLE(SX126xErrorStrings, "none", "timeout", "invalid payload", "radio not ready", "bus timeout",
|
||||
"radio busy", "cancelled");
|
||||
static constexpr uint32_t RESET_DELAY_HIGH_US = 5000;
|
||||
static constexpr uint32_t RESET_DELAY_LOW_US = 2000;
|
||||
static constexpr uint32_t SWITCHING_DELAY_US = 1;
|
||||
static constexpr uint32_t TRANSMIT_TIMEOUT_MS = 4000;
|
||||
static constexpr uint32_t BUSY_TIMEOUT_MS = 20;
|
||||
|
||||
// OCP (Over Current Protection) values
|
||||
static constexpr uint8_t OCP_80MA = 0x18; // 80 mA max current
|
||||
static constexpr uint8_t OCP_140MA = 0x38; // 140 mA max current
|
||||
|
||||
// LoRa low data rate optimization threshold
|
||||
static constexpr float LOW_DATA_RATE_OPTIMIZE_THRESHOLD = 16.38f; // 16.38 ms
|
||||
|
||||
uint8_t SX126x::read_fifo_(uint8_t offset, std::vector<uint8_t> &packet) {
|
||||
this->enable();
|
||||
this->wait_busy_();
|
||||
this->transfer_byte(RADIO_READ_BUFFER);
|
||||
this->transfer_byte(offset);
|
||||
uint8_t status = this->transfer_byte(0x00);
|
||||
for (uint8_t &byte : packet) {
|
||||
byte = this->transfer_byte(0x00);
|
||||
}
|
||||
this->disable();
|
||||
return status;
|
||||
}
|
||||
|
||||
void SX126x::write_fifo_(uint8_t offset, const uint8_t *data, size_t len) {
|
||||
this->enable();
|
||||
this->wait_busy_();
|
||||
this->transfer_byte(RADIO_WRITE_BUFFER);
|
||||
this->transfer_byte(offset);
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
this->transfer_byte(data[i]);
|
||||
}
|
||||
this->disable();
|
||||
delayMicroseconds(SWITCHING_DELAY_US);
|
||||
}
|
||||
|
||||
uint8_t SX126x::read_opcode_(uint8_t opcode, uint8_t *data, uint8_t size) {
|
||||
this->enable();
|
||||
this->wait_busy_();
|
||||
this->transfer_byte(opcode);
|
||||
uint8_t status = this->transfer_byte(0x00);
|
||||
for (int32_t i = 0; i < size; i++) {
|
||||
data[i] = this->transfer_byte(0x00);
|
||||
}
|
||||
this->disable();
|
||||
return status;
|
||||
}
|
||||
|
||||
void SX126x::write_opcode_(uint8_t opcode, uint8_t *data, uint8_t size) {
|
||||
this->enable();
|
||||
this->wait_busy_();
|
||||
this->transfer_byte(opcode);
|
||||
for (int32_t i = 0; i < size; i++) {
|
||||
this->transfer_byte(data[i]);
|
||||
}
|
||||
this->disable();
|
||||
delayMicroseconds(SWITCHING_DELAY_US);
|
||||
}
|
||||
|
||||
void SX126x::read_register_(uint16_t reg, uint8_t *data, uint8_t size) {
|
||||
this->enable();
|
||||
this->wait_busy_();
|
||||
this->write_byte(RADIO_READ_REGISTER);
|
||||
this->write_byte((reg >> 8) & 0xFF);
|
||||
this->write_byte((reg >> 0) & 0xFF);
|
||||
this->write_byte(0x00);
|
||||
for (int32_t i = 0; i < size; i++) {
|
||||
data[i] = this->transfer_byte(0x00);
|
||||
}
|
||||
this->disable();
|
||||
}
|
||||
|
||||
void SX126x::write_register_(uint16_t reg, uint8_t *data, uint8_t size) {
|
||||
this->enable();
|
||||
this->wait_busy_();
|
||||
this->write_byte(RADIO_WRITE_REGISTER);
|
||||
this->write_byte((reg >> 8) & 0xFF);
|
||||
this->write_byte((reg >> 0) & 0xFF);
|
||||
for (int32_t i = 0; i < size; i++) {
|
||||
this->transfer_byte(data[i]);
|
||||
}
|
||||
this->disable();
|
||||
delayMicroseconds(SWITCHING_DELAY_US);
|
||||
}
|
||||
|
||||
void IRAM_ATTR SX126x::gpio_intr(SX126x *arg) { arg->enable_loop_soon_any_context(); }
|
||||
|
||||
void SX126x::setup() {
|
||||
// Sized once so later packet reads never reallocate; read_packet() sets the length.
|
||||
this->packet_.resize(SX126X_MAX_PACKET_SIZE);
|
||||
// setup pins
|
||||
GPIOPin *dio1 = this->radio_.get_dio1_pin();
|
||||
this->radio_.bus().get_busy_pin()->setup();
|
||||
this->radio_.get_rst_pin()->setup();
|
||||
dio1->setup();
|
||||
if (dio1->is_internal()) {
|
||||
static_cast<InternalGPIOPin *>(dio1)->attach_interrupt(&SX126x::gpio_intr, this, gpio::INTERRUPT_RISING_EDGE);
|
||||
this->busy_pin_->setup();
|
||||
this->rst_pin_->setup();
|
||||
this->dio1_pin_->setup();
|
||||
if (this->dio1_pin_->is_internal()) {
|
||||
static_cast<InternalGPIOPin *>(this->dio1_pin_)
|
||||
->attach_interrupt(&SX126x::gpio_intr, this, gpio::INTERRUPT_RISING_EDGE);
|
||||
}
|
||||
|
||||
// start spi
|
||||
this->radio_.bus().setup();
|
||||
this->spi_setup();
|
||||
|
||||
// configure rf; a failure is reported through mark_failed() only, with its own reason
|
||||
const RadioEffects effects = this->radio_.configure(this->requested_profile_, this->version_);
|
||||
if (effects.warning != nullptr) {
|
||||
this->mark_failed(effects.warning);
|
||||
return;
|
||||
}
|
||||
this->apply_(effects);
|
||||
}
|
||||
|
||||
void SX126x::apply_(const RadioEffects &effects) {
|
||||
// User code may only run once the radio has committed. A rejection during another
|
||||
// operation's command sequence carries no status or callbacks.
|
||||
ESPHOME_DEBUG_ASSERT(!this->radio_.busy() || (!effects.report && effects.listener == nullptr && !effects.received));
|
||||
if (effects.sleep_loop) {
|
||||
this->disable_loop();
|
||||
} else if (this->radio_.state() != RadioState::RADIO_STATE_NEEDS_CONFIGURATION) {
|
||||
this->enable_loop();
|
||||
}
|
||||
this->watch_configuration_();
|
||||
// The packet buffer is borrowed from the status report until listeners return;
|
||||
// loop() will not refill it meanwhile.
|
||||
if (effects.received) {
|
||||
this->rx_dispatching_ = true;
|
||||
}
|
||||
if (effects.report) {
|
||||
this->status_comm_result(effects.warning == nullptr, effects.warning);
|
||||
}
|
||||
if (effects.listener != nullptr) {
|
||||
effects.listener->on_transmit_complete(effects.result);
|
||||
}
|
||||
if (effects.received) {
|
||||
for (auto *listener : this->listeners_) {
|
||||
listener->on_packet(this->packet_, effects.rssi, effects.snr);
|
||||
}
|
||||
this->packet_trigger_.trigger(this->packet_, effects.rssi, effects.snr);
|
||||
this->rx_dispatching_ = false;
|
||||
}
|
||||
// configure rf
|
||||
this->configure();
|
||||
}
|
||||
|
||||
void SX126x::configure() {
|
||||
// Before setup() the bus is not set up, and after a failed setup the radio stays unused
|
||||
if (!this->is_ready()) {
|
||||
uint8_t buf[8];
|
||||
|
||||
// toggle chip reset
|
||||
this->rst_pin_->digital_write(true);
|
||||
delayMicroseconds(RESET_DELAY_HIGH_US);
|
||||
this->rst_pin_->digital_write(false);
|
||||
delayMicroseconds(RESET_DELAY_LOW_US);
|
||||
this->rst_pin_->digital_write(true);
|
||||
delayMicroseconds(RESET_DELAY_HIGH_US);
|
||||
|
||||
// wakeup
|
||||
this->read_opcode_(RADIO_GET_STATUS, nullptr, 0);
|
||||
|
||||
// config tcxo
|
||||
if (this->tcxo_voltage_ != TCXO_CTRL_NONE) {
|
||||
uint32_t delay = this->tcxo_delay_ >> 6;
|
||||
buf[0] = this->tcxo_voltage_;
|
||||
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);
|
||||
}
|
||||
|
||||
// clear errors
|
||||
buf[0] = 0x00;
|
||||
buf[1] = 0x00;
|
||||
this->write_opcode_(RADIO_CLR_ERROR, buf, 2);
|
||||
|
||||
// rf switch
|
||||
if (this->rf_switch_) {
|
||||
buf[0] = 0x01;
|
||||
this->write_opcode_(RADIO_SET_RFSWITCHMODE, buf, 1);
|
||||
}
|
||||
|
||||
// check silicon version to make sure hw is ok
|
||||
this->read_register_(REG_VERSION_STRING, (uint8_t *) this->version_, sizeof(this->version_));
|
||||
this->version_[sizeof(this->version_) - 1] = '\0';
|
||||
if (strncmp(this->version_, "SX126", 5) != 0 && strncmp(this->version_, "LLCC68", 6) != 0) {
|
||||
this->mark_failed(LOG_STR("Unsupported chip version"));
|
||||
return;
|
||||
}
|
||||
if (!this->radio_.can_configure()) {
|
||||
ESP_LOGW(TAG, "Radio operation in progress, configuration ignored");
|
||||
return;
|
||||
}
|
||||
this->cold_sleep_ = false;
|
||||
this->apply_(this->radio_.configure(this->requested_profile_, this->version_));
|
||||
}
|
||||
|
||||
// A failed command leaves the radio needing configuration, which nothing else would do, so a node
|
||||
// that only uses YAML would stay deaf. Cold sleep is asked for, so it waits for a mode command.
|
||||
void SX126x::watch_configuration_() {
|
||||
const bool needed = this->radio_.state() == RadioState::RADIO_STATE_NEEDS_CONFIGURATION && !this->cold_sleep_;
|
||||
if (needed == this->reconfigure_pending_) {
|
||||
return;
|
||||
}
|
||||
this->reconfigure_pending_ = needed;
|
||||
if (needed) {
|
||||
this->set_interval(RECONFIGURE_INTERVAL_ID, RECONFIGURE_INTERVAL_MS, [this]() { this->configure(); });
|
||||
} else {
|
||||
this->cancel_interval(RECONFIGURE_INTERVAL_ID);
|
||||
}
|
||||
}
|
||||
// setup packet type
|
||||
buf[0] = this->modulation_;
|
||||
this->write_opcode_(RADIO_SET_PACKETTYPE, buf, 1);
|
||||
|
||||
void SX126x::set_mode_rx() { this->change_mode_(ModeCommand::MODE_COMMAND_RX); }
|
||||
void SX126x::set_mode_tx() { this->change_mode_(ModeCommand::MODE_COMMAND_TX); }
|
||||
void SX126x::set_mode_standby(SX126xStandbyMode mode) { this->change_mode_(ModeCommand::MODE_COMMAND_STANDBY, mode); }
|
||||
void SX126x::set_mode_sleep(bool cold) {
|
||||
this->change_mode_(cold ? ModeCommand::MODE_COMMAND_COLD_SLEEP : ModeCommand::MODE_COMMAND_SLEEP);
|
||||
}
|
||||
void SX126x::run_image_cal() { this->change_mode_(ModeCommand::MODE_COMMAND_IMAGE_CAL); }
|
||||
// calibrate image
|
||||
this->run_image_cal();
|
||||
|
||||
void SX126x::change_mode_(ModeCommand command, uint8_t arg) {
|
||||
const bool sleep = command == ModeCommand::MODE_COMMAND_SLEEP || command == ModeCommand::MODE_COMMAND_COLD_SLEEP;
|
||||
if (this->cold_sleep_) {
|
||||
if (sleep) {
|
||||
return;
|
||||
// set frequency
|
||||
uint64_t freq = ((uint64_t) this->frequency_ << 25) / XTAL_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
|
||||
int8_t pa_power = this->pa_power_;
|
||||
if (this->sx1261_) {
|
||||
// the following values were taken from section 13.1.14.1 table 13-21
|
||||
// in rev 2.1 of the datasheet
|
||||
if (pa_power == 15) {
|
||||
uint8_t cfg[4] = {0x06, 0x00, 0x01, 0x01};
|
||||
this->write_opcode_(RADIO_SET_PACONFIG, cfg, 4);
|
||||
} else {
|
||||
uint8_t cfg[4] = {0x04, 0x00, 0x01, 0x01};
|
||||
this->write_opcode_(RADIO_SET_PACONFIG, cfg, 4);
|
||||
}
|
||||
// Cold sleep lost the configuration, so waking needs it applied again first
|
||||
this->configure();
|
||||
pa_power = std::max(pa_power, (int8_t) -3);
|
||||
pa_power = std::min(pa_power, (int8_t) 14);
|
||||
buf[0] = OCP_80MA;
|
||||
this->write_register_(REG_OCP, buf, 1);
|
||||
} else {
|
||||
// the following values were taken from section 13.1.14.1 table 13-21
|
||||
// in rev 2.1 of the datasheet
|
||||
uint8_t cfg[4] = {0x04, 0x07, 0x00, 0x01};
|
||||
this->write_opcode_(RADIO_SET_PACONFIG, cfg, 4);
|
||||
pa_power = std::max(pa_power, (int8_t) -3);
|
||||
pa_power = std::min(pa_power, (int8_t) 22);
|
||||
buf[0] = OCP_140MA;
|
||||
this->write_register_(REG_OCP, buf, 1);
|
||||
}
|
||||
if (!this->radio_.can_change_mode()) {
|
||||
ESP_LOGW(TAG, "Radio unavailable, mode change ignored");
|
||||
return;
|
||||
buf[0] = pa_power;
|
||||
buf[1] = this->pa_ramp_;
|
||||
this->write_opcode_(RADIO_SET_TXPARAMS, buf, 2);
|
||||
|
||||
// configure modem
|
||||
if (this->modulation_ == PACKET_TYPE_LORA) {
|
||||
// set modulation params
|
||||
float duration = 1000.0f * (1UL << this->spreading_factor_) / BW_HZ[this->bandwidth_];
|
||||
buf[0] = this->spreading_factor_;
|
||||
buf[1] = progmem_read_byte(&BW_LORA[this->bandwidth_ - SX126X_BW_7810]);
|
||||
buf[2] = this->coding_rate_;
|
||||
buf[3] = (duration > LOW_DATA_RATE_OPTIMIZE_THRESHOLD) ? 0x01 : 0x00;
|
||||
this->write_opcode_(RADIO_SET_MODULATIONPARAMS, buf, 4);
|
||||
|
||||
// set packet params and sync word
|
||||
this->set_packet_params_(this->get_max_packet_size());
|
||||
if (this->sync_value_.size() == 2) {
|
||||
this->write_register_(REG_LORA_SYNCWORD, this->sync_value_.data(), this->sync_value_.size());
|
||||
}
|
||||
} else {
|
||||
// set modulation params
|
||||
uint32_t bitrate = ((uint64_t) XTAL_FREQ * 32) / this->bitrate_;
|
||||
uint32_t fdev = ((uint64_t) this->deviation_ << 25) / XTAL_FREQ;
|
||||
buf[0] = (bitrate >> 16) & 0xFF;
|
||||
buf[1] = (bitrate >> 8) & 0xFF;
|
||||
buf[2] = (bitrate >> 0) & 0xFF;
|
||||
buf[3] = this->shaping_;
|
||||
buf[4] = progmem_read_byte(&BW_FSK[this->bandwidth_ - SX126X_BW_4800]);
|
||||
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 (this->crc_enable_) {
|
||||
buf[0] = this->crc_initial_ >> 8;
|
||||
buf[1] = this->crc_initial_ & 0xFF;
|
||||
this->write_register_(REG_CRC_INITIAL, buf, 2);
|
||||
buf[0] = this->crc_polynomial_ >> 8;
|
||||
buf[1] = this->crc_polynomial_ & 0xFF;
|
||||
this->write_register_(REG_CRC_POLYNOMIAL, buf, 2);
|
||||
}
|
||||
|
||||
// set whitening params
|
||||
if (this->whitening_enable_) {
|
||||
// according to the datasheet, section 12 table 12-1 "The user should not
|
||||
// change the value of the 7 MSB of this register"
|
||||
this->read_register_(REG_WHITENING_INITIAL, buf, 1);
|
||||
buf[0] = (buf[0] & 0xFE) | ((this->whitening_initial_ >> 8) & 0x01);
|
||||
buf[1] = this->whitening_initial_ & 0xFF;
|
||||
this->write_register_(REG_WHITENING_INITIAL, buf, 2);
|
||||
}
|
||||
|
||||
// set packet params and sync word
|
||||
this->set_packet_params_(this->get_max_packet_size());
|
||||
if (!this->sync_value_.empty()) {
|
||||
this->write_register_(REG_GFSK_SYNCWORD, this->sync_value_.data(), this->sync_value_.size());
|
||||
}
|
||||
}
|
||||
|
||||
// switch to rx or sleep
|
||||
if (this->rx_start_) {
|
||||
this->set_mode_rx();
|
||||
} else {
|
||||
this->set_mode_sleep();
|
||||
}
|
||||
this->cold_sleep_ = command == ModeCommand::MODE_COMMAND_COLD_SLEEP;
|
||||
this->apply_(this->radio_.change_mode(command, arg));
|
||||
}
|
||||
|
||||
size_t SX126x::get_max_packet_size() { return this->radio_.max_packet_size(); }
|
||||
size_t SX126x::get_max_packet_size() {
|
||||
if (this->payload_length_ > 0) {
|
||||
return this->payload_length_;
|
||||
}
|
||||
return SX126X_MAX_PACKET_SIZE;
|
||||
}
|
||||
|
||||
void SX126x::set_packet_params_(uint8_t payload_length) {
|
||||
uint8_t buf[9];
|
||||
if (this->modulation_ == PACKET_TYPE_LORA) {
|
||||
buf[0] = (this->preamble_size_ >> 8) & 0xFF;
|
||||
buf[1] = (this->preamble_size_ >> 0) & 0xFF;
|
||||
buf[2] = (this->payload_length_ > 0) ? 0x01 : 0x00;
|
||||
buf[3] = payload_length;
|
||||
buf[4] = (this->crc_enable_) ? 0x01 : 0x00;
|
||||
buf[5] = 0x00;
|
||||
this->write_opcode_(RADIO_SET_PACKETPARAMS, buf, 6);
|
||||
} else {
|
||||
uint16_t preamble_size = this->preamble_size_ * 8;
|
||||
buf[0] = (preamble_size >> 8) & 0xFF;
|
||||
buf[1] = (preamble_size >> 0) & 0xFF;
|
||||
buf[2] = (this->preamble_detect_ > 0) ? ((this->preamble_detect_ - 1) | 0x04) : 0x00;
|
||||
buf[3] = this->sync_value_.size() * 8;
|
||||
buf[4] = 0x00;
|
||||
buf[5] = (this->payload_length_ > 0) ? 0x00 : 0x01;
|
||||
buf[6] = payload_length;
|
||||
if (this->crc_enable_) {
|
||||
buf[7] = (this->crc_inverted_ ? 0x04 : 0x00) + (this->crc_size_ & 0x02);
|
||||
} else {
|
||||
buf[7] = 0x01;
|
||||
}
|
||||
buf[8] = (this->whitening_enable_) ? 0x01 : 0x00;
|
||||
this->write_opcode_(RADIO_SET_PACKETPARAMS, buf, 9);
|
||||
}
|
||||
}
|
||||
|
||||
SX126xError SX126x::transmit_packet(const uint8_t *data, size_t len) {
|
||||
SX126xError result = this->start_transmit_(nullptr, data, len, TRANSMIT_TIMEOUT_MS);
|
||||
if (result == SX126xError::SX126X_ERROR_NONE) {
|
||||
// Wait for this send's own completion. A send without a listener cannot be cancelled,
|
||||
// and no user code runs between these polls, so the send cannot be replaced.
|
||||
result = SX126xError::SX126X_ERROR_NOT_READY;
|
||||
while (this->radio_.is_transmitting()) {
|
||||
const RadioEffects effects = this->radio_.poll_transmit(millis());
|
||||
if (effects.finished) {
|
||||
result = effects.result;
|
||||
this->apply_(effects);
|
||||
break;
|
||||
}
|
||||
App.feed_wdt();
|
||||
}
|
||||
}
|
||||
if (result != SX126xError::SX126X_ERROR_NONE) {
|
||||
ESP_LOGW(
|
||||
TAG, "Packet send failed: %s",
|
||||
LOG_STR_ARG(SX126xErrorStrings::get_log_str(static_cast<uint8_t>(result), SX126xErrorStrings::LAST_INDEX)));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
SX126xError SX126x::start_transmit_async(SX126xTransmitListener *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 SX126xError::SX126X_ERROR_INVALID_PARAMS;
|
||||
}
|
||||
return this->start_transmit_(listener, data, len, timeout_ms);
|
||||
}
|
||||
|
||||
SX126xError SX126x::start_transmit_(SX126xTransmitListener *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()) {
|
||||
ESP_LOGW(TAG, "Radio not ready, packet dropped");
|
||||
return SX126xError::SX126X_ERROR_NOT_READY;
|
||||
}
|
||||
const RadioEffects effects = this->radio_.start_transmit(listener, data, len, timeout_ms);
|
||||
this->apply_(effects);
|
||||
return effects.result;
|
||||
if (this->payload_length_ > 0 && this->payload_length_ != len) {
|
||||
ESP_LOGE(TAG, "Packet size does not match config");
|
||||
return SX126xError::INVALID_PARAMS;
|
||||
}
|
||||
if (len == 0 || len > this->get_max_packet_size()) {
|
||||
ESP_LOGE(TAG, "Packet size out of range");
|
||||
return SX126xError::INVALID_PARAMS;
|
||||
}
|
||||
|
||||
SX126xError ret = SX126xError::NONE;
|
||||
this->set_mode_standby(STDBY_XOSC);
|
||||
if (this->payload_length_ == 0) {
|
||||
this->set_packet_params_(len);
|
||||
}
|
||||
this->write_fifo_(0x00, data, len);
|
||||
this->set_mode_tx();
|
||||
|
||||
// wait until transmit completes, typically the delay will be less than 100 ms
|
||||
uint32_t start = millis();
|
||||
while (!this->dio1_pin_->digital_read()) {
|
||||
App.feed_wdt();
|
||||
if (millis() - start > TRANSMIT_TIMEOUT_MS) {
|
||||
ESP_LOGE(TAG, "Transmit packet failure");
|
||||
ret = SX126xError::TIMEOUT;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t buf[2];
|
||||
buf[0] = 0xFF;
|
||||
buf[1] = 0xFF;
|
||||
this->write_opcode_(RADIO_CLR_IRQSTATUS, buf, 2);
|
||||
if (this->payload_length_ == 0) {
|
||||
this->set_packet_params_(this->get_max_packet_size());
|
||||
}
|
||||
if (this->rx_start_) {
|
||||
this->set_mode_rx();
|
||||
} else {
|
||||
this->set_mode_sleep();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool SX126x::cancel_transmit_async(SX126xTransmitListener *listener) {
|
||||
const RadioEffects effects = this->radio_.cancel_transmit(listener);
|
||||
if (!effects.finished) {
|
||||
return false;
|
||||
void SX126x::call_listeners_(const std::vector<uint8_t> &packet, float rssi, float snr) {
|
||||
for (auto &listener : this->listeners_) {
|
||||
listener->on_packet(packet, rssi, snr);
|
||||
}
|
||||
this->apply_(effects);
|
||||
return true;
|
||||
this->packet_trigger_.trigger(packet, rssi, snr);
|
||||
}
|
||||
|
||||
void SX126x::loop() {
|
||||
if (this->rx_dispatching_ || this->is_failed()) {
|
||||
if (this->dio1_pin_->is_internal()) {
|
||||
this->disable_loop();
|
||||
}
|
||||
if (!this->dio1_pin_->digital_read()) {
|
||||
return;
|
||||
}
|
||||
this->apply_(this->radio_.poll(App.get_loop_component_start_time(), this->packet_));
|
||||
|
||||
uint16_t status;
|
||||
uint8_t buf[3];
|
||||
uint8_t rssi;
|
||||
int8_t snr;
|
||||
this->read_opcode_(RADIO_GET_IRQSTATUS, buf, 2);
|
||||
this->write_opcode_(RADIO_CLR_IRQSTATUS, buf, 2);
|
||||
status = (buf[0] << 8) | buf[1];
|
||||
if ((status & IRQ_RX_DONE) == IRQ_RX_DONE) {
|
||||
if ((status & IRQ_CRC_ERROR) != IRQ_CRC_ERROR) {
|
||||
this->read_opcode_(RADIO_GET_PACKETSTATUS, buf, 3);
|
||||
if (this->modulation_ == PACKET_TYPE_LORA) {
|
||||
rssi = buf[0];
|
||||
snr = buf[1];
|
||||
} else {
|
||||
rssi = buf[2];
|
||||
snr = 0;
|
||||
}
|
||||
this->read_opcode_(RADIO_GET_RXBUFFERSTATUS, buf, 2);
|
||||
this->packet_.resize(buf[0]);
|
||||
this->read_fifo_(buf[1], this->packet_);
|
||||
this->call_listeners_(this->packet_, (float) rssi / -2.0f, (float) snr / 4.0f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SX126x::run_image_cal() {
|
||||
// the following values were taken from section 9.2.1 table 9-2
|
||||
// in rev 2.1 of the datasheet
|
||||
uint8_t buf[2] = {0, 0};
|
||||
if (this->frequency_ > 900000000) {
|
||||
buf[0] = 0xE1;
|
||||
buf[1] = 0xE9;
|
||||
} else if (this->frequency_ > 850000000) {
|
||||
buf[0] = 0xD7;
|
||||
buf[1] = 0xDB;
|
||||
} else if (this->frequency_ > 770000000) {
|
||||
buf[0] = 0xC1;
|
||||
buf[1] = 0xC5;
|
||||
} else if (this->frequency_ > 460000000) {
|
||||
buf[0] = 0x75;
|
||||
buf[1] = 0x81;
|
||||
} else if (this->frequency_ > 425000000) {
|
||||
buf[0] = 0x6B;
|
||||
buf[1] = 0x6F;
|
||||
}
|
||||
if (buf[0] > 0 && buf[1] > 0) {
|
||||
this->write_opcode_(RADIO_CALIBRATEIMAGE, buf, 2);
|
||||
}
|
||||
}
|
||||
|
||||
void SX126x::set_mode_rx() {
|
||||
uint8_t buf[8];
|
||||
|
||||
// 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;
|
||||
this->write_opcode_(RADIO_SET_LORASYMBTIMEOUT, buf, 1);
|
||||
|
||||
// switch to continuous mode rx
|
||||
buf[0] = 0xFF;
|
||||
buf[1] = 0xFF;
|
||||
buf[2] = 0xFF;
|
||||
this->write_opcode_(RADIO_SET_RX, buf, 3);
|
||||
}
|
||||
|
||||
void SX126x::set_mode_tx() {
|
||||
uint8_t buf[8];
|
||||
|
||||
// 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);
|
||||
|
||||
// switch to single mode tx
|
||||
buf[0] = 0x00;
|
||||
buf[1] = 0x00;
|
||||
buf[2] = 0x00;
|
||||
this->write_opcode_(RADIO_SET_TX, buf, 3);
|
||||
}
|
||||
|
||||
void SX126x::set_mode_sleep(bool cold) {
|
||||
// 0x04 = warm start (config retained), 0x00 = cold start (config lost, lowest power)
|
||||
uint8_t buf[1];
|
||||
buf[0] = cold ? 0x00 : 0x04;
|
||||
this->write_opcode_(RADIO_SET_SLEEP, buf, 1);
|
||||
}
|
||||
|
||||
void SX126x::set_mode_standby(SX126xStandbyMode mode) {
|
||||
uint8_t buf[1];
|
||||
buf[0] = mode;
|
||||
this->write_opcode_(RADIO_SET_STANDBY, buf, 1);
|
||||
}
|
||||
|
||||
void SX126x::wait_busy_() {
|
||||
// wait if the device is busy, the maximum delay is only be a few ms
|
||||
// with most commands taking only a few us
|
||||
uint32_t start = millis();
|
||||
while (this->busy_pin_->digital_read()) {
|
||||
if (millis() - start > BUSY_TIMEOUT_MS) {
|
||||
this->mark_failed(LOG_STR("Wait busy timeout"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SX126x::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "SX126x:\n Ready for operation: %s",
|
||||
YESNO(!this->is_failed() && this->radio_.state() == RadioState::RADIO_STATE_IDLE));
|
||||
LOG_PIN(" CS Pin: ", this->radio_.bus().get_cs_pin());
|
||||
LOG_PIN(" BUSY Pin: ", this->radio_.bus().get_busy_pin());
|
||||
LOG_PIN(" RST Pin: ", this->radio_.get_rst_pin());
|
||||
LOG_PIN(" DIO1 Pin: ", this->radio_.get_dio1_pin());
|
||||
ESP_LOGCONFIG(TAG, "SX126x:");
|
||||
LOG_PIN(" CS Pin: ", this->cs_);
|
||||
LOG_PIN(" BUSY Pin: ", this->busy_pin_);
|
||||
LOG_PIN(" RST Pin: ", this->rst_pin_);
|
||||
LOG_PIN(" DIO1 Pin: ", this->dio1_pin_);
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" HW Version: %15s\n"
|
||||
" Requested configuration:\n"
|
||||
" Frequency: %" PRIu32 " Hz\n"
|
||||
" Bandwidth: %" PRIu32 " Hz\n"
|
||||
" PA Power: %" PRId8 " dBm\n"
|
||||
" PA Ramp: %" PRIu16 " us\n"
|
||||
" Payload Length: %" PRIu8 "\n"
|
||||
" Payload Length: %" PRIu32 "\n"
|
||||
" CRC Enable: %s\n"
|
||||
" Rx Start: %s",
|
||||
this->version_, this->requested_profile_.frequency,
|
||||
SX126xCommands::bandwidth_hz(this->requested_profile_.bandwidth), this->requested_profile_.pa_power,
|
||||
SX126xCommands::ramp_us(this->requested_profile_.pa_ramp), this->requested_profile_.payload_length,
|
||||
TRUEFALSE(this->requested_profile_.crc_enable), TRUEFALSE(this->requested_profile_.rx_start));
|
||||
if (this->requested_profile_.modulation == PACKET_TYPE_GFSK) {
|
||||
this->version_, this->frequency_, BW_HZ[this->bandwidth_], this->pa_power_,
|
||||
progmem_read_uint16(&RAMP[this->pa_ramp_]), this->payload_length_, TRUEFALSE(this->crc_enable_),
|
||||
TRUEFALSE(this->rx_start_));
|
||||
if (this->modulation_ == PACKET_TYPE_GFSK) {
|
||||
const char *shaping = "NONE";
|
||||
if (this->requested_profile_.shaping == GAUSSIAN_BT_0_3) {
|
||||
if (this->shaping_ == GAUSSIAN_BT_0_3) {
|
||||
shaping = "GAUSSIAN_BT_0_3";
|
||||
} else if (this->requested_profile_.shaping == GAUSSIAN_BT_0_5) {
|
||||
} else if (this->shaping_ == GAUSSIAN_BT_0_5) {
|
||||
shaping = "GAUSSIAN_BT_0_5";
|
||||
} else if (this->requested_profile_.shaping == GAUSSIAN_BT_0_7) {
|
||||
} else if (this->shaping_ == GAUSSIAN_BT_0_7) {
|
||||
shaping = "GAUSSIAN_BT_0_7";
|
||||
} else if (this->requested_profile_.shaping == GAUSSIAN_BT_1_0) {
|
||||
} else if (this->shaping_ == GAUSSIAN_BT_1_0) {
|
||||
shaping = "GAUSSIAN_BT_1_0";
|
||||
}
|
||||
ESP_LOGCONFIG(TAG,
|
||||
@@ -222,15 +539,14 @@ void SX126x::dump_config() {
|
||||
" Preamble Size: %" PRIu16 "\n"
|
||||
" Preamble Detect: %" PRIu16 "\n"
|
||||
" Bitrate: %" PRIu32 "b/s",
|
||||
this->requested_profile_.deviation, shaping, this->requested_profile_.preamble_size,
|
||||
this->requested_profile_.preamble_detect, this->requested_profile_.bitrate);
|
||||
} else if (this->requested_profile_.modulation == PACKET_TYPE_LORA) {
|
||||
this->deviation_, shaping, this->preamble_size_, this->preamble_detect_, this->bitrate_);
|
||||
} else if (this->modulation_ == PACKET_TYPE_LORA) {
|
||||
const char *cr = "4/8";
|
||||
if (this->requested_profile_.coding_rate == LORA_CR_4_5) {
|
||||
if (this->coding_rate_ == LORA_CR_4_5) {
|
||||
cr = "4/5";
|
||||
} else if (this->requested_profile_.coding_rate == LORA_CR_4_6) {
|
||||
} else if (this->coding_rate_ == LORA_CR_4_6) {
|
||||
cr = "4/6";
|
||||
} else if (this->requested_profile_.coding_rate == LORA_CR_4_7) {
|
||||
} else if (this->coding_rate_ == LORA_CR_4_7) {
|
||||
cr = "4/7";
|
||||
}
|
||||
ESP_LOGCONFIG(TAG,
|
||||
@@ -238,17 +554,16 @@ void SX126x::dump_config() {
|
||||
" Spreading Factor: %" PRIu8 "\n"
|
||||
" Coding Rate: %s\n"
|
||||
" Preamble Size: %" PRIu16,
|
||||
this->requested_profile_.spreading_factor, cr, this->requested_profile_.preamble_size);
|
||||
this->spreading_factor_, cr, this->preamble_size_);
|
||||
}
|
||||
if (this->requested_profile_.sync_size != 0) {
|
||||
if (!this->sync_value_.empty()) {
|
||||
char hex_buf[17]; // 8 bytes max = 16 hex chars + null
|
||||
ESP_LOGCONFIG(
|
||||
TAG, " Sync Value: 0x%s",
|
||||
format_hex_to(hex_buf, this->requested_profile_.sync_value.data(), this->requested_profile_.sync_size));
|
||||
ESP_LOGCONFIG(TAG, " Sync Value: 0x%s",
|
||||
format_hex_to(hex_buf, this->sync_value_.data(), this->sync_value_.size()));
|
||||
}
|
||||
ESP_LOGCONFIG(TAG, " Whitening Enable: %s", TRUEFALSE(this->requested_profile_.whitening_enable));
|
||||
if (this->requested_profile_.whitening_enable) {
|
||||
ESP_LOGCONFIG(TAG, " Whitening Initial: 0x%03x", this->requested_profile_.whitening_initial);
|
||||
ESP_LOGCONFIG(TAG, " Whitening Enable: %s", TRUEFALSE(this->whitening_enable_));
|
||||
if (this->whitening_enable_) {
|
||||
ESP_LOGCONFIG(TAG, " Whitening Initial: 0x%03x", this->whitening_initial_);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,125 +1,157 @@
|
||||
#pragma once
|
||||
|
||||
#include "sx126x_radio.h"
|
||||
#include "esphome/components/spi/spi.h"
|
||||
#include "esphome/core/automation.h"
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "sx126x_reg.h"
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace esphome::sx126x {
|
||||
|
||||
static constexpr size_t SX126X_MAX_PACKET_SIZE = 255;
|
||||
|
||||
enum SX126xBw : uint8_t {
|
||||
// FSK
|
||||
SX126X_BW_4800,
|
||||
SX126X_BW_5800,
|
||||
SX126X_BW_7300,
|
||||
SX126X_BW_9700,
|
||||
SX126X_BW_11700,
|
||||
SX126X_BW_14600,
|
||||
SX126X_BW_19500,
|
||||
SX126X_BW_23400,
|
||||
SX126X_BW_29300,
|
||||
SX126X_BW_39000,
|
||||
SX126X_BW_46900,
|
||||
SX126X_BW_58600,
|
||||
SX126X_BW_78200,
|
||||
SX126X_BW_93800,
|
||||
SX126X_BW_117300,
|
||||
SX126X_BW_156200,
|
||||
SX126X_BW_187200,
|
||||
SX126X_BW_234300,
|
||||
SX126X_BW_312000,
|
||||
SX126X_BW_373600,
|
||||
SX126X_BW_467000,
|
||||
// LORA
|
||||
SX126X_BW_7810,
|
||||
SX126X_BW_10420,
|
||||
SX126X_BW_15630,
|
||||
SX126X_BW_20830,
|
||||
SX126X_BW_31250,
|
||||
SX126X_BW_41670,
|
||||
SX126X_BW_62500,
|
||||
SX126X_BW_125000,
|
||||
SX126X_BW_250000,
|
||||
SX126X_BW_500000,
|
||||
};
|
||||
|
||||
enum class SX126xError { NONE = 0, TIMEOUT, INVALID_PARAMS, SX126X_ERROR_NOT_READY };
|
||||
|
||||
class SX126xListener {
|
||||
public:
|
||||
// Called from loop(). The packet is borrowed until this returns; copy what you keep.
|
||||
// Listeners may send, change mode or configure. A send returns BUSY if another packet
|
||||
// is already waiting, which is then delivered by the next loop().
|
||||
virtual void on_packet(const std::vector<uint8_t> &packet, float rssi, float snr) = 0;
|
||||
};
|
||||
|
||||
class SX126x final : public Component {
|
||||
class SX126x final : public Component,
|
||||
public spi::SPIDevice<spi::BIT_ORDER_MSB_FIRST, spi::CLOCK_POLARITY_LOW, spi::CLOCK_PHASE_LEADING,
|
||||
spi::DATA_RATE_8MHZ> {
|
||||
public:
|
||||
void set_spi_parent(spi::SPIComponent *parent) { this->radio_.bus().set_spi_parent(parent); }
|
||||
void set_cs_pin(GPIOPin *pin) { this->radio_.bus().set_cs_pin(pin); }
|
||||
void set_data_rate(uint32_t rate) { this->radio_.bus().set_data_rate(rate); }
|
||||
void set_mode(spi::SPIMode mode) { this->radio_.bus().set_mode(mode); }
|
||||
void set_bit_order(spi::SPIBitOrder order) { this->radio_.bus().set_bit_order(order); }
|
||||
void set_release_device(bool release) { this->radio_.bus().set_release_device(release); }
|
||||
void set_write_only(bool write_only) { this->radio_.bus().set_write_only(write_only); }
|
||||
#ifdef USE_SPI_PSRAM_DMA
|
||||
void set_psram_dma(bool enable) { this->radio_.bus().set_psram_dma(enable); }
|
||||
#endif
|
||||
// Releases the SPI bus, as SPIDevice::spi_teardown() did before SX126x stopped being one
|
||||
void spi_teardown() { this->radio_.bus().teardown(); }
|
||||
size_t get_max_packet_size();
|
||||
float get_setup_priority() const override { return setup_priority::PROCESSOR; }
|
||||
void setup() override;
|
||||
void loop() override;
|
||||
void dump_config() override;
|
||||
void set_bandwidth(SX126xBw bandwidth) { this->requested_profile_.bandwidth = bandwidth; }
|
||||
void set_bitrate(uint32_t bitrate) { this->requested_profile_.bitrate = bitrate; }
|
||||
void set_busy_pin(GPIOPin *busy_pin) { this->radio_.bus().set_busy_pin(busy_pin); }
|
||||
void set_coding_rate(uint8_t coding_rate) { this->requested_profile_.coding_rate = coding_rate; }
|
||||
void set_crc_enable(bool crc_enable) { this->requested_profile_.crc_enable = crc_enable; }
|
||||
void set_crc_inverted(bool crc_inverted) { this->requested_profile_.crc_inverted = crc_inverted; }
|
||||
void set_crc_size(uint8_t crc_size) { this->requested_profile_.crc_size = crc_size; }
|
||||
void set_crc_polynomial(uint16_t crc_polynomial) { this->requested_profile_.crc_polynomial = crc_polynomial; }
|
||||
void set_crc_initial(uint16_t crc_initial) { this->requested_profile_.crc_initial = crc_initial; }
|
||||
void set_whitening_enable(bool whitening_enable) { this->requested_profile_.whitening_enable = whitening_enable; }
|
||||
void set_whitening_initial(uint16_t whitening_initial) {
|
||||
this->requested_profile_.whitening_initial = whitening_initial;
|
||||
}
|
||||
void set_deviation(uint32_t deviation) { this->requested_profile_.deviation = deviation; }
|
||||
void set_dio1_pin(GPIOPin *dio1_pin) { this->radio_.set_dio1_pin(dio1_pin); }
|
||||
void set_frequency(uint32_t frequency) { this->requested_profile_.frequency = frequency; }
|
||||
void set_sx1261(bool sx1261) { this->requested_profile_.sx1261 = sx1261; }
|
||||
// Mode changes are ignored with a warning unless the radio is idle and configured.
|
||||
void set_bandwidth(SX126xBw bandwidth) { this->bandwidth_ = bandwidth; }
|
||||
void set_bitrate(uint32_t bitrate) { this->bitrate_ = bitrate; }
|
||||
void set_busy_pin(GPIOPin *busy_pin) { this->busy_pin_ = busy_pin; }
|
||||
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_crc_inverted(bool crc_inverted) { this->crc_inverted_ = crc_inverted; }
|
||||
void set_crc_size(uint8_t crc_size) { this->crc_size_ = crc_size; }
|
||||
void set_crc_polynomial(uint16_t crc_polynomial) { this->crc_polynomial_ = crc_polynomial; }
|
||||
void set_crc_initial(uint16_t crc_initial) { this->crc_initial_ = crc_initial; }
|
||||
void set_whitening_enable(bool whitening_enable) { this->whitening_enable_ = whitening_enable; }
|
||||
void set_whitening_initial(uint16_t whitening_initial) { this->whitening_initial_ = whitening_initial; }
|
||||
void set_deviation(uint32_t deviation) { this->deviation_ = deviation; }
|
||||
void set_dio1_pin(GPIOPin *dio1_pin) { this->dio1_pin_ = dio1_pin; }
|
||||
void set_frequency(uint32_t frequency) { this->frequency_ = frequency; }
|
||||
void set_sx1261(bool sx1261) { this->sx1261_ = sx1261; }
|
||||
void set_mode_rx();
|
||||
void set_mode_tx();
|
||||
void set_mode_standby(SX126xStandbyMode mode);
|
||||
void set_mode_sleep(bool cold = false);
|
||||
void set_modulation(uint8_t modulation) { this->requested_profile_.modulation = modulation; }
|
||||
void set_pa_power(int8_t power) { this->requested_profile_.pa_power = power; }
|
||||
void set_pa_ramp(uint8_t ramp) { this->requested_profile_.pa_ramp = ramp; }
|
||||
void set_payload_length(uint8_t payload_length) { this->requested_profile_.payload_length = payload_length; }
|
||||
void set_preamble_detect(uint16_t preamble_detect) { this->requested_profile_.preamble_detect = preamble_detect; }
|
||||
void set_preamble_size(uint16_t preamble_size) { this->requested_profile_.preamble_size = preamble_size; }
|
||||
void set_rst_pin(GPIOPin *rst_pin) { this->radio_.set_rst_pin(rst_pin); }
|
||||
void set_rx_start(bool rx_start) { this->requested_profile_.rx_start = rx_start; }
|
||||
void set_rf_switch(bool rf_switch) { this->requested_profile_.rf_switch = rf_switch; }
|
||||
void set_shaping(uint8_t shaping) { this->requested_profile_.shaping = shaping; }
|
||||
void set_spreading_factor(uint8_t spreading_factor) { this->requested_profile_.spreading_factor = spreading_factor; }
|
||||
void set_sync_value(const std::vector<uint8_t> &sync_value) { this->requested_profile_.set_sync_value(sync_value); }
|
||||
void set_tcxo_voltage(uint8_t tcxo_voltage) { this->requested_profile_.tcxo_voltage = tcxo_voltage; }
|
||||
void set_tcxo_delay(uint32_t tcxo_delay) { this->requested_profile_.tcxo_delay = tcxo_delay; }
|
||||
void set_modulation(uint8_t modulation) { this->modulation_ = modulation; }
|
||||
void set_pa_power(int8_t power) { this->pa_power_ = power; }
|
||||
void set_pa_ramp(uint8_t ramp) { this->pa_ramp_ = ramp; }
|
||||
void set_payload_length(uint8_t payload_length) { this->payload_length_ = payload_length; }
|
||||
void set_preamble_detect(uint16_t preamble_detect) { this->preamble_detect_ = preamble_detect; }
|
||||
void set_preamble_size(uint16_t preamble_size) { this->preamble_size_ = preamble_size; }
|
||||
void set_rst_pin(GPIOPin *rst_pin) { this->rst_pin_ = rst_pin; }
|
||||
void set_rx_start(bool rx_start) { this->rx_start_ = rx_start; }
|
||||
void set_rf_switch(bool rf_switch) { this->rf_switch_ = rf_switch; }
|
||||
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 set_tcxo_voltage(uint8_t tcxo_voltage) { this->tcxo_voltage_ = tcxo_voltage; }
|
||||
void set_tcxo_delay(uint32_t tcxo_delay) { this->tcxo_delay_ = tcxo_delay; }
|
||||
void run_image_cal();
|
||||
// Mode changes and configuration are allowed during RX callbacks when the radio
|
||||
// is available; they never modify the borrowed packet buffer.
|
||||
void configure();
|
||||
SX126xError transmit_packet(const uint8_t *data, size_t len);
|
||||
SX126xError transmit_packet(const std::vector<uint8_t> &packet) {
|
||||
return this->transmit_packet(packet.data(), packet.size());
|
||||
}
|
||||
// Main-loop context only. SX126X_ERROR_NONE accepts one operation and promises one completion.
|
||||
// Data is copied into the chip FIFO before return; listener must outlive completion.
|
||||
// Pending RX rejects admission with BUSY and is delivered by a later loop().
|
||||
// Timeout: 1..262143 ms. SPI/BUSY waits are synchronous; airtime is asynchronous.
|
||||
[[nodiscard]] SX126xError start_transmit_async(SX126xTransmitListener *listener, const uint8_t *data, size_t len,
|
||||
uint32_t timeout_ms = 4000);
|
||||
[[nodiscard]] SX126xError start_transmit_async(SX126xTransmitListener *listener, const std::vector<uint8_t> &packet,
|
||||
uint32_t timeout_ms = 4000) {
|
||||
return this->start_transmit_async(listener, packet.data(), packet.size(), timeout_ms);
|
||||
}
|
||||
// Normal completion runs in loop(); cancellation completes synchronously in its caller.
|
||||
// The radio is released before callbacks, which may start another operation if recovery
|
||||
// succeeded. True accepts cancellation; the completion result reports cleanup failure.
|
||||
bool cancel_transmit_async(SX126xTransmitListener *listener);
|
||||
bool is_transmitting() const { return this->radio_.is_transmitting(); }
|
||||
void register_listener(SX126xListener *listener) { this->listeners_.push_back(listener); }
|
||||
// True while a packet is being received, or has been received and not yet read; sending would lose it.
|
||||
bool is_receiving() { return this->radio_.is_receiving(); }
|
||||
Trigger<std::vector<uint8_t>, float, float> *get_packet_trigger() { return &this->packet_trigger_; }
|
||||
|
||||
private:
|
||||
static void IRAM_ATTR gpio_intr(SX126x *arg) { arg->enable_loop_soon_any_context(); }
|
||||
void change_mode_(ModeCommand command, uint8_t arg = 0);
|
||||
// The only place that runs user code for a radio operation: loop scheduling, then status,
|
||||
// then the completion or packet listeners. SX126xRadio has already committed its state.
|
||||
void apply_(const RadioEffects &effects);
|
||||
void watch_configuration_();
|
||||
SX126xError start_transmit_(SX126xTransmitListener *listener, const uint8_t *data, size_t len, uint32_t timeout_ms);
|
||||
SX126xRadio radio_;
|
||||
RadioProfile requested_profile_;
|
||||
char version_[16]{};
|
||||
protected:
|
||||
static void gpio_intr(SX126x *arg);
|
||||
void configure_fsk_ook_();
|
||||
void configure_lora_();
|
||||
void set_packet_params_(uint8_t payload_length);
|
||||
uint8_t read_fifo_(uint8_t offset, std::vector<uint8_t> &packet);
|
||||
void write_fifo_(uint8_t offset, const uint8_t *data, size_t len);
|
||||
void write_opcode_(uint8_t opcode, uint8_t *data, uint8_t size);
|
||||
uint8_t read_opcode_(uint8_t opcode, uint8_t *data, uint8_t size);
|
||||
void write_register_(uint16_t reg, uint8_t *data, uint8_t size);
|
||||
void read_register_(uint16_t reg, uint8_t *data, uint8_t size);
|
||||
void call_listeners_(const std::vector<uint8_t> &packet, float rssi, float snr);
|
||||
void wait_busy_();
|
||||
Trigger<std::vector<uint8_t>, float, float> packet_trigger_;
|
||||
std::vector<SX126xListener *> listeners_;
|
||||
std::vector<uint8_t> packet_;
|
||||
bool rx_dispatching_{false};
|
||||
bool cold_sleep_{false};
|
||||
bool reconfigure_pending_{false};
|
||||
std::vector<uint8_t> sync_value_;
|
||||
GPIOPin *busy_pin_{nullptr};
|
||||
GPIOPin *dio1_pin_{nullptr};
|
||||
GPIOPin *rst_pin_{nullptr};
|
||||
uint32_t bitrate_{0};
|
||||
uint32_t deviation_{0};
|
||||
uint32_t frequency_{0};
|
||||
uint32_t payload_length_{0};
|
||||
uint32_t tcxo_delay_{0};
|
||||
uint16_t crc_polynomial_{0};
|
||||
uint16_t crc_initial_{0};
|
||||
uint16_t whitening_initial_{0};
|
||||
uint16_t preamble_detect_{0};
|
||||
uint16_t preamble_size_{0};
|
||||
char version_[16];
|
||||
SX126xBw bandwidth_{SX126X_BW_125000};
|
||||
uint8_t crc_size_{0};
|
||||
uint8_t tcxo_voltage_{0};
|
||||
uint8_t coding_rate_{0};
|
||||
uint8_t modulation_{PACKET_TYPE_LORA};
|
||||
uint8_t pa_ramp_{0};
|
||||
uint8_t shaping_{0};
|
||||
uint8_t spreading_factor_{0};
|
||||
int8_t pa_power_{0};
|
||||
bool sx1261_{false};
|
||||
bool crc_enable_{false};
|
||||
bool crc_inverted_{false};
|
||||
bool whitening_enable_{false};
|
||||
bool rx_start_{false};
|
||||
bool rf_switch_{false};
|
||||
};
|
||||
|
||||
} // namespace esphome::sx126x
|
||||
@@ -1,332 +0,0 @@
|
||||
#include "sx126x_commands.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
namespace esphome::sx126x {
|
||||
static constexpr uint16_t RAMP[8] PROGMEM = {10, 20, 40, 80, 200, 800, 1700, 3400};
|
||||
// Aligned 32 bit loads from flash are safe on ESP8266, so this table is read directly
|
||||
static constexpr uint32_t BW_HZ[31] PROGMEM = {4800, 5800, 7300, 9700, 11700, 14600, 19500, 23400,
|
||||
29300, 39000, 46900, 58600, 78200, 93800, 117300, 156200,
|
||||
187200, 234300, 312000, 373600, 467000, 7810, 10420, 15630,
|
||||
20830, 31250, 41670, 62500, 125000, 250000, 500000};
|
||||
static constexpr uint8_t BW_LORA[10] PROGMEM = {LORA_BW_7810, LORA_BW_10420, LORA_BW_15630, LORA_BW_20830,
|
||||
LORA_BW_31250, LORA_BW_41670, LORA_BW_62500, LORA_BW_125000,
|
||||
LORA_BW_250000, LORA_BW_500000};
|
||||
static constexpr uint8_t BW_FSK[21] PROGMEM = {
|
||||
FSK_BW_4800, FSK_BW_5800, FSK_BW_7300, FSK_BW_9700, FSK_BW_11700, FSK_BW_14600, FSK_BW_19500,
|
||||
FSK_BW_23400, FSK_BW_29300, FSK_BW_39000, FSK_BW_46900, FSK_BW_58600, FSK_BW_78200, FSK_BW_93800,
|
||||
FSK_BW_117300, FSK_BW_156200, FSK_BW_187200, FSK_BW_234300, FSK_BW_312000, FSK_BW_373600, FSK_BW_467000};
|
||||
|
||||
// OCP (Over Current Protection) values
|
||||
static constexpr uint8_t OCP_80MA = 0x18; // 80 mA max current
|
||||
static constexpr uint8_t OCP_140MA = 0x38; // 140 mA max current
|
||||
|
||||
// LoRa low data rate optimization threshold
|
||||
static constexpr float LOW_DATA_RATE_OPTIMIZE_THRESHOLD = 16.38f; // 16.38 ms
|
||||
|
||||
void SX126xCommands::read_opcode_(uint8_t opcode, uint8_t *data, uint8_t size) {
|
||||
const uint8_t header[] = {opcode, 0};
|
||||
this->spi_device_.read(header, {data, size});
|
||||
}
|
||||
|
||||
void SX126xCommands::write_opcode_(uint8_t opcode, const uint8_t *data, uint8_t size) {
|
||||
this->spi_device_.write({&opcode, 1}, {data, size});
|
||||
}
|
||||
|
||||
void SX126xCommands::read_register_(uint16_t reg, uint8_t *data, uint8_t size) {
|
||||
const uint8_t header[] = {RADIO_READ_REGISTER, static_cast<uint8_t>(reg >> 8), static_cast<uint8_t>(reg), 0};
|
||||
this->spi_device_.read(header, {data, size});
|
||||
}
|
||||
|
||||
void SX126xCommands::write_register_(uint16_t reg, const uint8_t *data, uint8_t size) {
|
||||
const uint8_t header[] = {RADIO_WRITE_REGISTER, static_cast<uint8_t>(reg >> 8), static_cast<uint8_t>(reg)};
|
||||
this->spi_device_.write(header, {data, size});
|
||||
}
|
||||
|
||||
ConfigurationResult SX126xCommands::configure(const RadioProfile &profile, std::span<char, 16> version,
|
||||
AppliedProfile &applied) {
|
||||
applied.frequency = profile.frequency;
|
||||
applied.payload_length = profile.payload_length;
|
||||
applied.modulation = profile.modulation;
|
||||
applied.rx_start = profile.rx_start;
|
||||
encode_packet_params(profile, applied);
|
||||
uint8_t buf[8];
|
||||
// wakeup
|
||||
this->read_opcode_(RADIO_GET_STATUS, nullptr, 0);
|
||||
|
||||
// config tcxo
|
||||
if (profile.tcxo_voltage != TCXO_CTRL_NONE) {
|
||||
uint32_t delay = profile.tcxo_delay >> 6;
|
||||
buf[0] = profile.tcxo_voltage;
|
||||
put_be24(buf + 1, delay);
|
||||
this->write_opcode_(RADIO_SET_TCXOMODE, buf, 4);
|
||||
buf[0] = 0x7F;
|
||||
this->write_opcode_(RADIO_CALIBRATE, buf, 1);
|
||||
}
|
||||
|
||||
// clear errors
|
||||
buf[0] = 0x00;
|
||||
buf[1] = 0x00;
|
||||
this->write_opcode_(RADIO_CLR_ERROR, buf, 2);
|
||||
|
||||
// rf switch
|
||||
if (profile.rf_switch) {
|
||||
buf[0] = 0x01;
|
||||
this->write_opcode_(RADIO_SET_RFSWITCHMODE, buf, 1);
|
||||
}
|
||||
|
||||
// check silicon version to make sure hw is ok
|
||||
this->read_register_(REG_VERSION_STRING, reinterpret_cast<uint8_t *>(version.data()), version.size());
|
||||
if (!this->spi_device_.ok()) {
|
||||
return ConfigurationResult::CONFIGURATION_RESULT_BUSY_TIMEOUT;
|
||||
}
|
||||
version[version.size() - 1] = '\0';
|
||||
if (strncmp(version.data(), "SX126", 5) != 0 && strncmp(version.data(), "LLCC68", 6) != 0) {
|
||||
return ConfigurationResult::CONFIGURATION_RESULT_UNSUPPORTED;
|
||||
}
|
||||
|
||||
// setup packet type
|
||||
buf[0] = profile.modulation;
|
||||
this->write_opcode_(RADIO_SET_PACKETTYPE, buf, 1);
|
||||
|
||||
// calibrate image
|
||||
this->calibrate_image(profile.frequency);
|
||||
|
||||
// set frequency
|
||||
uint64_t freq = ((uint64_t) profile.frequency << 25) / XTAL_FREQ;
|
||||
put_be32(buf, static_cast<uint32_t>(freq));
|
||||
this->write_opcode_(RADIO_SET_RFFREQUENCY, buf, 4);
|
||||
|
||||
// configure pa
|
||||
int8_t pa_power = profile.pa_power;
|
||||
if (profile.sx1261) {
|
||||
// the following values were taken from section 13.1.14.1 table 13-21
|
||||
// in rev 2.1 of the datasheet
|
||||
if (pa_power == 15) {
|
||||
uint8_t cfg[4] = {0x06, 0x00, 0x01, 0x01};
|
||||
this->write_opcode_(RADIO_SET_PACONFIG, cfg, 4);
|
||||
} else {
|
||||
uint8_t cfg[4] = {0x04, 0x00, 0x01, 0x01};
|
||||
this->write_opcode_(RADIO_SET_PACONFIG, cfg, 4);
|
||||
}
|
||||
pa_power = clamp(pa_power, (int8_t) -3, (int8_t) 14);
|
||||
buf[0] = OCP_80MA;
|
||||
this->write_register_(REG_OCP, buf, 1);
|
||||
} else {
|
||||
// the following values were taken from section 13.1.14.1 table 13-21
|
||||
// in rev 2.1 of the datasheet
|
||||
uint8_t cfg[4] = {0x04, 0x07, 0x00, 0x01};
|
||||
this->write_opcode_(RADIO_SET_PACONFIG, cfg, 4);
|
||||
pa_power = clamp(pa_power, (int8_t) -3, (int8_t) 22);
|
||||
buf[0] = OCP_140MA;
|
||||
this->write_register_(REG_OCP, buf, 1);
|
||||
}
|
||||
buf[0] = pa_power;
|
||||
buf[1] = profile.pa_ramp;
|
||||
this->write_opcode_(RADIO_SET_TXPARAMS, buf, 2);
|
||||
|
||||
// configure modem
|
||||
if (profile.modulation == PACKET_TYPE_LORA) {
|
||||
// set modulation params
|
||||
float duration = 1000.0f * (1UL << profile.spreading_factor) / BW_HZ[profile.bandwidth];
|
||||
buf[0] = profile.spreading_factor;
|
||||
buf[1] = progmem_read_byte(&BW_LORA[profile.bandwidth - SX126X_BW_7810]);
|
||||
buf[2] = profile.coding_rate;
|
||||
buf[3] = (duration > LOW_DATA_RATE_OPTIMIZE_THRESHOLD) ? 0x01 : 0x00;
|
||||
this->write_opcode_(RADIO_SET_MODULATIONPARAMS, buf, 4);
|
||||
|
||||
// set packet params and sync word
|
||||
this->write_opcode_(RADIO_SET_PACKETPARAMS, applied.packet_params.data(), applied.packet_params_size);
|
||||
if (profile.sync_size == 2) {
|
||||
this->write_register_(REG_LORA_SYNCWORD, profile.sync_value.data(), profile.sync_size);
|
||||
}
|
||||
} else {
|
||||
// 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[3] = profile.shaping;
|
||||
buf[4] = progmem_read_byte(&BW_FSK[profile.bandwidth - SX126X_BW_4800]);
|
||||
put_be24(buf + 5, fdev);
|
||||
this->write_opcode_(RADIO_SET_MODULATIONPARAMS, buf, 8);
|
||||
|
||||
// set crc params
|
||||
if (profile.crc_enable) {
|
||||
put_be16(buf, profile.crc_initial);
|
||||
this->write_register_(REG_CRC_INITIAL, buf, 2);
|
||||
put_be16(buf, profile.crc_polynomial);
|
||||
this->write_register_(REG_CRC_POLYNOMIAL, buf, 2);
|
||||
}
|
||||
|
||||
// set whitening params
|
||||
if (profile.whitening_enable) {
|
||||
// according to the datasheet, section 12 table 12-1 "The user should not
|
||||
// change the value of the 7 MSB of this register"
|
||||
this->read_register_(REG_WHITENING_INITIAL, buf, 1);
|
||||
buf[0] = (buf[0] & 0xFE) | ((profile.whitening_initial >> 8) & 0x01);
|
||||
buf[1] = profile.whitening_initial & 0xFF;
|
||||
this->write_register_(REG_WHITENING_INITIAL, buf, 2);
|
||||
}
|
||||
|
||||
// set packet params and sync word
|
||||
this->write_opcode_(RADIO_SET_PACKETPARAMS, applied.packet_params.data(), applied.packet_params_size);
|
||||
if (profile.sync_size != 0) {
|
||||
this->write_register_(REG_GFSK_SYNCWORD, profile.sync_value.data(), profile.sync_size);
|
||||
}
|
||||
}
|
||||
|
||||
// switch to rx or sleep
|
||||
if (profile.rx_start) {
|
||||
this->receive();
|
||||
} else {
|
||||
this->sleep();
|
||||
}
|
||||
return this->spi_device_.ok() ? ConfigurationResult::CONFIGURATION_RESULT_OK
|
||||
: ConfigurationResult::CONFIGURATION_RESULT_BUSY_TIMEOUT;
|
||||
}
|
||||
|
||||
void SX126xCommands::encode_packet_params(const RadioProfile &profile, AppliedProfile &applied) {
|
||||
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[2] = (profile.payload_length > 0) ? 0x01 : 0x00;
|
||||
buf[3] = payload_length;
|
||||
buf[4] = (profile.crc_enable) ? 0x01 : 0x00;
|
||||
buf[5] = 0x00;
|
||||
applied.packet_params_size = 6;
|
||||
} else {
|
||||
uint16_t preamble_size = profile.preamble_size * 8;
|
||||
put_be16(buf.data(), preamble_size);
|
||||
buf[2] = (profile.preamble_detect > 0) ? ((profile.preamble_detect - 1) | 0x04) : 0x00;
|
||||
buf[3] = profile.sync_size * 8;
|
||||
buf[4] = 0x00;
|
||||
buf[5] = (profile.payload_length > 0) ? 0x00 : 0x01;
|
||||
buf[6] = payload_length;
|
||||
if (profile.crc_enable) {
|
||||
buf[7] = (profile.crc_inverted ? 0x04 : 0x00) + (profile.crc_size & 0x02);
|
||||
} else {
|
||||
buf[7] = 0x01;
|
||||
}
|
||||
buf[8] = (profile.whitening_enable) ? 0x01 : 0x00;
|
||||
applied.packet_params_size = 9;
|
||||
}
|
||||
}
|
||||
|
||||
void SX126xCommands::set_packet_length(AppliedProfile &applied, uint8_t length) {
|
||||
applied.packet_params[applied.modulation == PACKET_TYPE_LORA ? 3 : 6] = length;
|
||||
this->write_opcode_(RADIO_SET_PACKETPARAMS, applied.packet_params.data(), applied.packet_params_size);
|
||||
}
|
||||
|
||||
void SX126xCommands::calibrate_image(uint32_t frequency) {
|
||||
// the following values were taken from section 9.2.1 table 9-2
|
||||
// in rev 2.1 of the datasheet
|
||||
uint8_t buf[2] = {0, 0};
|
||||
if (frequency > 900000000) {
|
||||
buf[0] = 0xE1;
|
||||
buf[1] = 0xE9;
|
||||
} else if (frequency > 850000000) {
|
||||
buf[0] = 0xD7;
|
||||
buf[1] = 0xDB;
|
||||
} else if (frequency > 770000000) {
|
||||
buf[0] = 0xC1;
|
||||
buf[1] = 0xC5;
|
||||
} else if (frequency > 460000000) {
|
||||
buf[0] = 0x75;
|
||||
buf[1] = 0x81;
|
||||
} else if (frequency > 425000000) {
|
||||
buf[0] = 0x6B;
|
||||
buf[1] = 0x6F;
|
||||
}
|
||||
if (buf[0] > 0 && buf[1] > 0) {
|
||||
this->write_opcode_(RADIO_CALIBRATEIMAGE, buf, 2);
|
||||
}
|
||||
}
|
||||
|
||||
// Only the dio1 interrupts are routed to DIO1; DIO2 and DIO3 stay unused.
|
||||
void SX126xCommands::set_dio_irq_params_(uint16_t flags, uint16_t dio1) {
|
||||
uint8_t buf[8];
|
||||
put_be16(buf, flags);
|
||||
put_be16(buf + 2, dio1);
|
||||
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() {
|
||||
// A valid header or sync word is flagged for SX126xRadio::is_receiving(), but not signalled on DIO1
|
||||
const uint16_t irq = IRQ_RX_DONE | IRQ_RX_TX_TIMEOUT | IRQ_CRC_ERROR;
|
||||
this->set_dio_irq_params_(irq | IRQ_HEADER_VALID | IRQ_SYNCWORD_VALID, irq);
|
||||
|
||||
uint8_t buf[3];
|
||||
|
||||
// set timeout to 0
|
||||
buf[0] = 0x00;
|
||||
this->write_opcode_(RADIO_SET_LORASYMBTIMEOUT, buf, 1);
|
||||
|
||||
// switch to continuous mode rx
|
||||
buf[0] = 0xFF;
|
||||
buf[1] = 0xFF;
|
||||
buf[2] = 0xFF;
|
||||
this->write_opcode_(RADIO_SET_RX, buf, 3);
|
||||
}
|
||||
|
||||
void SX126xCommands::transmit(uint32_t timeout_ms) {
|
||||
this->set_dio_irq_params_(IRQ_TX_DONE | IRQ_RX_TX_TIMEOUT, IRQ_TX_DONE | IRQ_RX_TX_TIMEOUT);
|
||||
|
||||
uint8_t buf[3];
|
||||
|
||||
const uint32_t ticks = timeout_ms * 64;
|
||||
put_be24(buf, ticks);
|
||||
this->write_opcode_(RADIO_SET_TX, buf, 3);
|
||||
}
|
||||
|
||||
void SX126xCommands::sleep(bool cold) {
|
||||
// 0x04 = warm start (config retained), 0x00 = cold start (config lost, lowest power)
|
||||
const uint8_t mode = cold ? 0x00 : 0x04;
|
||||
this->write_opcode_(RADIO_SET_SLEEP, &mode, 1);
|
||||
}
|
||||
|
||||
void SX126xCommands::standby(SX126xStandbyMode mode) {
|
||||
const uint8_t value = mode;
|
||||
this->write_opcode_(RADIO_SET_STANDBY, &value, 1);
|
||||
}
|
||||
|
||||
uint32_t SX126xCommands::bandwidth_hz(SX126xBw bw) { return BW_HZ[bw]; }
|
||||
uint16_t SX126xCommands::ramp_us(uint8_t ramp) { return progmem_read_uint16(&RAMP[ramp]); }
|
||||
|
||||
void SX126xCommands::clear_irqs(uint16_t mask) {
|
||||
const uint8_t data[] = {static_cast<uint8_t>(mask >> 8), static_cast<uint8_t>(mask)};
|
||||
this->write_opcode_(RADIO_CLR_IRQSTATUS, data, 2);
|
||||
}
|
||||
|
||||
uint16_t SX126xCommands::read_irq() {
|
||||
uint8_t data[2]{};
|
||||
this->read_opcode_(RADIO_GET_IRQSTATUS, data, 2);
|
||||
return (uint16_t(data[0]) << 8) | data[1];
|
||||
}
|
||||
|
||||
void SX126xCommands::write_fifo(const uint8_t *data, size_t size) {
|
||||
const uint8_t header[] = {RADIO_WRITE_BUFFER, 0};
|
||||
this->spi_device_.write(header, {data, size});
|
||||
}
|
||||
|
||||
void SX126xCommands::read_packet(uint8_t modulation, std::vector<uint8_t> &packet, float &rssi, float &snr) {
|
||||
uint8_t data[3]{};
|
||||
this->read_opcode_(RADIO_GET_PACKETSTATUS, data, 3);
|
||||
rssi = (modulation == PACKET_TYPE_LORA ? data[0] : data[2]) / -2.0f;
|
||||
// FSK packets report no SNR
|
||||
snr = modulation == PACKET_TYPE_LORA ? static_cast<int8_t>(data[1]) / 4.0f : NAN;
|
||||
this->read_opcode_(RADIO_GET_RXBUFFERSTATUS, data, 2);
|
||||
if (!this->spi_device_.ok()) {
|
||||
return; // The length and offset were not read.
|
||||
}
|
||||
packet.resize(data[0]);
|
||||
const uint8_t header[] = {RADIO_READ_BUFFER, data[1], 0};
|
||||
this->spi_device_.read(header, packet);
|
||||
}
|
||||
|
||||
} // namespace esphome::sx126x
|
||||
@@ -1,50 +0,0 @@
|
||||
#pragma once
|
||||
#include "radio_profile.h"
|
||||
#include "sx126x_spi_device.h"
|
||||
#include <vector>
|
||||
|
||||
namespace esphome::sx126x {
|
||||
enum class ConfigurationResult {
|
||||
CONFIGURATION_RESULT_OK,
|
||||
CONFIGURATION_RESULT_BUSY_TIMEOUT,
|
||||
CONFIGURATION_RESULT_UNSUPPORTED
|
||||
};
|
||||
|
||||
// Encodes chip commands. No ESPHome lifecycle, callbacks, or raw SPI access.
|
||||
// Commands record failure in the SPI device: callers start a sequence with begin()
|
||||
// and check ok() at its end, or before acting on a value that was read.
|
||||
class SX126xCommands {
|
||||
public:
|
||||
SX126xCommands() = default;
|
||||
SX126xCommands(const SX126xCommands &) = delete;
|
||||
SX126xCommands &operator=(const SX126xCommands &) = delete;
|
||||
SX126xSpiDevice &bus() { return this->spi_device_; }
|
||||
// Fills applied as it goes; only use it if the result is OK.
|
||||
[[nodiscard]] ConfigurationResult configure(const RadioProfile &profile, std::span<char, 16> version,
|
||||
AppliedProfile &applied);
|
||||
// Sets the payload length in the applied packet parameters and writes them.
|
||||
void set_packet_length(AppliedProfile &applied, uint8_t length);
|
||||
void calibrate_image(uint32_t frequency);
|
||||
void standby(SX126xStandbyMode mode);
|
||||
void receive();
|
||||
void transmit(uint32_t timeout_ms = 0);
|
||||
void sleep(bool cold = false);
|
||||
void clear_irqs(uint16_t mask = 0xFFFF);
|
||||
// Returns 0 if the read was skipped or failed.
|
||||
uint16_t read_irq();
|
||||
void write_fifo(const uint8_t *data, size_t size);
|
||||
// Leaves the packet unchanged if a read fails.
|
||||
void read_packet(uint8_t modulation, std::vector<uint8_t> &packet, float &rssi, float &snr);
|
||||
static uint32_t bandwidth_hz(SX126xBw bw);
|
||||
static uint16_t ramp_us(uint8_t ramp);
|
||||
|
||||
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 flags, uint16_t dio1);
|
||||
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);
|
||||
SX126xSpiDevice spi_device_;
|
||||
};
|
||||
} // namespace esphome::sx126x
|
||||
@@ -1,273 +0,0 @@
|
||||
#include "sx126x_radio.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include <utility>
|
||||
|
||||
namespace esphome::sx126x {
|
||||
|
||||
// No ESP_LOG calls in this file: log listeners are user code, see sx126x_radio.h.
|
||||
|
||||
static constexpr uint32_t RESET_DELAY_HIGH_US = 5000;
|
||||
static constexpr uint32_t RESET_DELAY_LOW_US = 2000;
|
||||
static constexpr uint32_t RECEIVE_RETRY_INTERVAL_MS = 200;
|
||||
|
||||
RadioEffects SX126xRadio::comm_report(bool ok) {
|
||||
RadioEffects effects;
|
||||
effects.report = true;
|
||||
effects.warning = ok ? nullptr : LOG_STR("Wait busy timeout");
|
||||
return effects;
|
||||
}
|
||||
|
||||
RadioEffects SX126xRadio::configure(const RadioProfile &requested, std::span<char, 16> version) {
|
||||
ESPHOME_DEBUG_ASSERT(this->can_configure());
|
||||
this->busy_ = true;
|
||||
this->rx_retry_pending_ = false;
|
||||
this->pending_irq_ = 0;
|
||||
RadioEffects effects;
|
||||
effects.report = true;
|
||||
effects.warning = this->apply_configuration_(requested, version);
|
||||
this->commit_(effects.warning == nullptr ? RadioState::RADIO_STATE_IDLE
|
||||
: RadioState::RADIO_STATE_NEEDS_CONFIGURATION);
|
||||
return effects;
|
||||
}
|
||||
|
||||
const LogString *SX126xRadio::apply_configuration_(const RadioProfile &requested, std::span<char, 16> version) {
|
||||
if (!requested.sync_valid) {
|
||||
return LOG_STR("Invalid sync value");
|
||||
}
|
||||
this->rst_pin_->digital_write(true);
|
||||
delayMicroseconds(RESET_DELAY_HIGH_US);
|
||||
this->rst_pin_->digital_write(false);
|
||||
delayMicroseconds(RESET_DELAY_LOW_US);
|
||||
this->rst_pin_->digital_write(true);
|
||||
delayMicroseconds(RESET_DELAY_HIGH_US);
|
||||
this->bus().begin();
|
||||
AppliedProfile applied;
|
||||
switch (this->commands_.configure(requested, version, applied)) {
|
||||
case ConfigurationResult::CONFIGURATION_RESULT_OK:
|
||||
this->applied_ = applied;
|
||||
return nullptr;
|
||||
case ConfigurationResult::CONFIGURATION_RESULT_UNSUPPORTED:
|
||||
return LOG_STR("Unsupported chip version");
|
||||
default:
|
||||
return LOG_STR("Wait busy timeout");
|
||||
}
|
||||
}
|
||||
|
||||
RadioEffects SX126xRadio::change_mode(ModeCommand command, uint8_t arg) {
|
||||
ESPHOME_DEBUG_ASSERT(this->can_change_mode());
|
||||
this->busy_ = true;
|
||||
this->bus().begin();
|
||||
switch (command) {
|
||||
case ModeCommand::MODE_COMMAND_RX:
|
||||
this->commands_.receive();
|
||||
break;
|
||||
case ModeCommand::MODE_COMMAND_TX:
|
||||
this->commands_.transmit();
|
||||
break;
|
||||
case ModeCommand::MODE_COMMAND_STANDBY:
|
||||
this->commands_.standby(static_cast<SX126xStandbyMode>(arg));
|
||||
break;
|
||||
case ModeCommand::MODE_COMMAND_SLEEP:
|
||||
case ModeCommand::MODE_COMMAND_COLD_SLEEP:
|
||||
this->commands_.sleep(command == ModeCommand::MODE_COMMAND_COLD_SLEEP);
|
||||
break;
|
||||
case ModeCommand::MODE_COMMAND_IMAGE_CAL:
|
||||
this->commands_.calibrate_image(this->applied_.frequency);
|
||||
break;
|
||||
}
|
||||
const bool ok = this->bus().ok();
|
||||
// Cold sleep loses the configuration, and a failed command leaves the chip state unknown.
|
||||
this->commit_(ok && command != ModeCommand::MODE_COMMAND_COLD_SLEEP ? RadioState::RADIO_STATE_IDLE
|
||||
: RadioState::RADIO_STATE_NEEDS_CONFIGURATION);
|
||||
return comm_report(ok);
|
||||
}
|
||||
|
||||
RadioEffects SX126xRadio::start_transmit(SX126xTransmitListener *listener, const uint8_t *data, size_t len,
|
||||
uint32_t timeout_ms) {
|
||||
RadioEffects effects;
|
||||
if (this->state_ == RadioState::RADIO_STATE_NEEDS_CONFIGURATION) {
|
||||
effects.result = SX126xError::SX126X_ERROR_NOT_READY;
|
||||
return effects;
|
||||
}
|
||||
if (this->busy_ || this->state_ != RadioState::RADIO_STATE_IDLE) {
|
||||
effects.result = SX126xError::SX126X_ERROR_BUSY;
|
||||
return effects;
|
||||
}
|
||||
const uint8_t fixed_length = this->applied_.payload_length;
|
||||
if (data == nullptr || len == 0 || len > this->max_packet_size() || (fixed_length != 0 && len != fixed_length)) {
|
||||
effects.result = SX126xError::SX126X_ERROR_INVALID_PARAMS;
|
||||
return effects;
|
||||
}
|
||||
this->busy_ = true;
|
||||
this->bus().begin();
|
||||
this->commands_.standby(STDBY_XOSC);
|
||||
// RX cannot advance in standby. Keep a packet that completed before standby intact for
|
||||
// poll(), before clearing IRQs or overwriting the shared FIFO. A failed read returns 0.
|
||||
// A packet that failed its CRC is not delivered, so it does not hold up the send.
|
||||
const uint16_t irq = this->commands_.read_irq() | this->pending_irq_;
|
||||
if ((irq & IRQ_RX_DONE) && !(irq & IRQ_CRC_ERROR)) {
|
||||
this->commit_(RadioState::RADIO_STATE_HOLDING_RX);
|
||||
effects.result = SX126xError::SX126X_ERROR_BUSY;
|
||||
return effects;
|
||||
}
|
||||
this->commands_.clear_irqs();
|
||||
this->pending_irq_ = 0;
|
||||
if (fixed_length == 0) {
|
||||
this->commands_.set_packet_length(this->applied_, len);
|
||||
}
|
||||
this->commands_.write_fifo(data, len);
|
||||
this->commands_.transmit(timeout_ms);
|
||||
if (!this->bus().ok()) {
|
||||
const bool restored = this->restore_();
|
||||
this->commit_(restored ? RadioState::RADIO_STATE_IDLE : RadioState::RADIO_STATE_NEEDS_CONFIGURATION);
|
||||
effects = comm_report(restored);
|
||||
effects.result = SX126xError::SX126X_ERROR_BUSY_TIMEOUT;
|
||||
return effects;
|
||||
}
|
||||
this->tx_ = {listener, millis(), timeout_ms};
|
||||
this->commit_(RadioState::RADIO_STATE_TRANSMITTING);
|
||||
// No status report on success, so no user code runs before the caller has the result.
|
||||
// The completion reports status instead.
|
||||
return effects;
|
||||
}
|
||||
|
||||
RadioEffects SX126xRadio::poll_transmit(uint32_t now) {
|
||||
if (this->busy_ || !this->is_transmitting()) {
|
||||
return {};
|
||||
}
|
||||
bool done = false;
|
||||
SX126xError outcome = SX126xError::SX126X_ERROR_NONE;
|
||||
if (this->dio1_pin_->digital_read()) {
|
||||
this->busy_ = true;
|
||||
this->bus().begin();
|
||||
const uint16_t status = this->commands_.read_irq();
|
||||
this->commands_.clear_irqs(status);
|
||||
this->busy_ = false;
|
||||
if (!this->bus().ok()) {
|
||||
outcome = SX126xError::SX126X_ERROR_BUSY_TIMEOUT;
|
||||
done = true;
|
||||
} else if (status & IRQ_RX_TX_TIMEOUT) {
|
||||
outcome = SX126xError::SX126X_ERROR_TIMEOUT;
|
||||
done = true;
|
||||
} else if (status & IRQ_TX_DONE) {
|
||||
done = true;
|
||||
}
|
||||
}
|
||||
// A cached loop tick can precede admission; signed subtraction also handles wraparound.
|
||||
if (!done && static_cast<int32_t>(now - this->tx_.started_ms) >= static_cast<int32_t>(this->tx_.timeout_ms)) {
|
||||
outcome = SX126xError::SX126X_ERROR_TIMEOUT;
|
||||
done = true;
|
||||
}
|
||||
return done ? this->finish_transmit_(outcome) : RadioEffects{};
|
||||
}
|
||||
|
||||
RadioEffects SX126xRadio::cancel_transmit(SX126xTransmitListener *listener) {
|
||||
if (this->busy_ || !this->is_transmitting() || listener == nullptr || listener != this->tx_.listener) {
|
||||
return {};
|
||||
}
|
||||
return this->finish_transmit_(SX126xError::SX126X_ERROR_CANCELLED);
|
||||
}
|
||||
|
||||
// The only place a send ends.
|
||||
RadioEffects SX126xRadio::finish_transmit_(SX126xError result) {
|
||||
this->busy_ = true;
|
||||
const bool restored = this->restore_();
|
||||
this->commit_(restored ? RadioState::RADIO_STATE_IDLE : RadioState::RADIO_STATE_NEEDS_CONFIGURATION);
|
||||
RadioEffects effects = comm_report(restored);
|
||||
effects.result = restored ? result : SX126xError::SX126X_ERROR_BUSY_TIMEOUT;
|
||||
effects.listener = std::exchange(this->tx_.listener, nullptr);
|
||||
effects.finished = true;
|
||||
return effects;
|
||||
}
|
||||
|
||||
bool SX126xRadio::restore_() {
|
||||
this->bus().begin();
|
||||
this->commands_.standby(STDBY_XOSC);
|
||||
this->commands_.clear_irqs();
|
||||
if (this->applied_.payload_length == 0) {
|
||||
this->commands_.set_packet_length(this->applied_, this->max_packet_size());
|
||||
}
|
||||
if (this->applied_.rx_start) {
|
||||
this->commands_.receive();
|
||||
} else {
|
||||
this->commands_.sleep();
|
||||
}
|
||||
return this->bus().ok();
|
||||
}
|
||||
|
||||
bool SX126xRadio::is_receiving() {
|
||||
if (this->state_ == RadioState::RADIO_STATE_HOLDING_RX) {
|
||||
return true;
|
||||
}
|
||||
// A radio that sleeps after sending is not listening, and reading it would wake it
|
||||
if (this->busy_ || this->state_ != RadioState::RADIO_STATE_IDLE || !this->applied_.rx_start) {
|
||||
return false;
|
||||
}
|
||||
// DIO1 signals a received packet that loop() has not read yet
|
||||
if (this->pending_irq_ != 0 || this->dio1_pin_->digital_read()) {
|
||||
return true;
|
||||
}
|
||||
this->busy_ = true;
|
||||
this->bus().begin();
|
||||
const uint16_t status = this->commands_.read_irq();
|
||||
this->busy_ = false;
|
||||
// A failed read counts as receiving, so the link holds the send and warns if the radio stays unreadable
|
||||
return !this->bus().ok() || (status & (IRQ_HEADER_VALID | IRQ_SYNCWORD_VALID)) != 0;
|
||||
}
|
||||
|
||||
RadioEffects SX126xRadio::poll(uint32_t now, std::vector<uint8_t> &packet) {
|
||||
if (this->busy_) {
|
||||
return {};
|
||||
}
|
||||
if (this->is_transmitting()) {
|
||||
return this->poll_transmit(now);
|
||||
}
|
||||
RadioEffects effects;
|
||||
if (this->state_ == RadioState::RADIO_STATE_NEEDS_CONFIGURATION) {
|
||||
effects.sleep_loop = true; // Polling cannot recover the radio; configure() can.
|
||||
return effects;
|
||||
}
|
||||
if (this->rx_retry_pending_ && now - this->rx_retry_started_ms_ < RECEIVE_RETRY_INTERVAL_MS) {
|
||||
return effects;
|
||||
}
|
||||
const bool holding = this->state_ == RadioState::RADIO_STATE_HOLDING_RX;
|
||||
if (!holding && this->pending_irq_ == 0 && !this->dio1_pin_->digital_read()) {
|
||||
effects.sleep_loop = this->dio1_pin_->is_internal(); // Its interrupt wakes the loop.
|
||||
return effects;
|
||||
}
|
||||
return this->receive_(holding, now, packet);
|
||||
}
|
||||
|
||||
RadioEffects SX126xRadio::receive_(bool holding, uint32_t now, std::vector<uint8_t> &packet) {
|
||||
this->busy_ = true;
|
||||
this->bus().begin();
|
||||
// A packet whose read failed has had its flags cleared, so they are kept until it is read.
|
||||
const uint16_t status = this->commands_.read_irq() | this->pending_irq_;
|
||||
const bool received = (status & IRQ_RX_DONE) && !(status & IRQ_CRC_ERROR);
|
||||
if (!holding) {
|
||||
// Cleared before the read, so a packet that completes during the read raises DIO1 again.
|
||||
// A held packet keeps its IRQ until restoration.
|
||||
this->commands_.clear_irqs(status);
|
||||
}
|
||||
float rssi = 0, snr = 0;
|
||||
if (received) {
|
||||
this->commands_.read_packet(this->applied_.modulation, packet, rssi, snr);
|
||||
}
|
||||
const bool read = this->bus().ok();
|
||||
this->pending_irq_ = read ? 0 : status;
|
||||
// Do not spend a BUSY timeout on every loop while a read keeps failing.
|
||||
this->rx_retry_pending_ = !read;
|
||||
this->rx_retry_started_ms_ = now;
|
||||
RadioState next = this->state_;
|
||||
if (read && holding) {
|
||||
next = this->restore_() ? RadioState::RADIO_STATE_IDLE : RadioState::RADIO_STATE_NEEDS_CONFIGURATION;
|
||||
}
|
||||
this->commit_(next);
|
||||
RadioEffects effects = comm_report(read && next != RadioState::RADIO_STATE_NEEDS_CONFIGURATION);
|
||||
effects.received = read && received;
|
||||
effects.rssi = rssi;
|
||||
effects.snr = snr;
|
||||
return effects;
|
||||
}
|
||||
|
||||
} // namespace esphome::sx126x
|
||||
@@ -1,152 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "radio_profile.h"
|
||||
#include "sx126x_commands.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
namespace esphome::sx126x {
|
||||
|
||||
enum class SX126xError {
|
||||
SX126X_ERROR_NONE = 0,
|
||||
SX126X_ERROR_TIMEOUT,
|
||||
SX126X_ERROR_INVALID_PARAMS,
|
||||
SX126X_ERROR_NOT_READY,
|
||||
SX126X_ERROR_BUSY_TIMEOUT,
|
||||
SX126X_ERROR_BUSY,
|
||||
SX126X_ERROR_CANCELLED
|
||||
};
|
||||
|
||||
class SX126xTransmitListener {
|
||||
public:
|
||||
virtual void on_transmit_complete(SX126xError result) = 0;
|
||||
};
|
||||
|
||||
// Who may use the radio between operations. This is driver state, not the chip's mode.
|
||||
enum class RadioState : uint8_t {
|
||||
// Startup, cold sleep, or a failed configuration, mode command or restoration. Only
|
||||
// configure() is accepted; sends return NOT_READY and the loop sleeps. SX126x configures
|
||||
// again every second after a failure, and on the next mode command after cold sleep.
|
||||
RADIO_STATE_NEEDS_CONFIGURATION,
|
||||
// Available. The chip is receiving or sleeping, as configured, or after the TX mode command
|
||||
// sending whatever the FIFO holds. That send is not tracked: a send or mode command may cut
|
||||
// it short, and poll() clears its TX_DONE as a flag without a packet.
|
||||
RADIO_STATE_IDLE,
|
||||
// A send is on air. SPI is free between polls; only polling and cancellation are accepted.
|
||||
RADIO_STATE_TRANSMITTING,
|
||||
// Standby with a received packet left in the FIFO, found when a send entered standby.
|
||||
// The send was rejected with BUSY; the next poll() delivers the packet and restores the
|
||||
// radio. configure() may discard it to recover from repeated read failures.
|
||||
RADIO_STATE_HOLDING_RX,
|
||||
};
|
||||
|
||||
enum class ModeCommand : uint8_t {
|
||||
MODE_COMMAND_RX,
|
||||
MODE_COMMAND_TX,
|
||||
MODE_COMMAND_STANDBY,
|
||||
MODE_COMMAND_SLEEP,
|
||||
MODE_COMMAND_COLD_SLEEP,
|
||||
MODE_COMMAND_IMAGE_CAL,
|
||||
};
|
||||
|
||||
// What a radio operation leaves for its caller to do. The radio has already committed its
|
||||
// state; the caller reports status first, then calls the listener or delivers the packet.
|
||||
struct RadioEffects {
|
||||
SX126xError result{SX126xError::SX126X_ERROR_NONE};
|
||||
// The completion to notify when finished is set; null for a blocking send.
|
||||
SX126xTransmitListener *listener{nullptr};
|
||||
// With report set: the warning to set, or null to clear it.
|
||||
const LogString *warning{nullptr};
|
||||
float rssi{0};
|
||||
float snr{0};
|
||||
bool report{false};
|
||||
// A send ended, and result is its outcome.
|
||||
bool finished{false};
|
||||
// The packet buffer holds a packet to deliver.
|
||||
bool received{false};
|
||||
// Nothing to poll until the next DIO1 edge or configuration.
|
||||
bool sleep_loop{false};
|
||||
};
|
||||
|
||||
// Owns the radio state and every SPI command sequence.
|
||||
//
|
||||
// Status reports, completions and packet listeners can run user code, which may call back
|
||||
// into the driver. Every operation therefore does its SPI work with busy() set, commits the
|
||||
// next state, and returns RadioEffects; SX126x::apply_() then reports status and calls the
|
||||
// listeners. This class has no access to component status or listeners, so callbacks only
|
||||
// ever see a committed state. Do not log here either: log listeners are user code. busy()
|
||||
// covers re-entry during a sequence, for example from a GPIO pin that logs.
|
||||
//
|
||||
// Each sequence starts with bus().begin(); after a BUSY timeout the rest is skipped and
|
||||
// bus().ok() is false. A failed send preparation restores the radio in a new sequence. A
|
||||
// failed restoration needs configuration, and its result overrides the send result. A
|
||||
// successful send start reports nothing, so no user code runs before the caller has the
|
||||
// result. Every send ends in finish_transmit_(), exactly once.
|
||||
//
|
||||
// A failed receive read keeps the packet and retries after RECEIVE_RETRY_INTERVAL_MS, so a
|
||||
// stuck BUSY line does not cost a 20 ms wait on every loop.
|
||||
class SX126xRadio {
|
||||
public:
|
||||
SX126xRadio() = default;
|
||||
SX126xRadio(const SX126xRadio &) = delete;
|
||||
SX126xRadio &operator=(const SX126xRadio &) = delete;
|
||||
SX126xSpiDevice &bus() { return this->commands_.bus(); }
|
||||
void set_dio1_pin(GPIOPin *pin) { this->dio1_pin_ = pin; }
|
||||
void set_rst_pin(GPIOPin *pin) { this->rst_pin_ = pin; }
|
||||
GPIOPin *get_dio1_pin() const { return this->dio1_pin_; }
|
||||
GPIOPin *get_rst_pin() const { return this->rst_pin_; }
|
||||
RadioState state() const { return this->state_; }
|
||||
bool busy() const { return this->busy_; }
|
||||
bool is_transmitting() const { return this->state_ == RadioState::RADIO_STATE_TRANSMITTING; }
|
||||
// A held packet may be discarded: explicit reconfiguration is the recovery path.
|
||||
bool can_configure() const { return !this->busy_ && !this->is_transmitting(); }
|
||||
bool can_change_mode() const { return !this->busy_ && this->state_ == RadioState::RADIO_STATE_IDLE; }
|
||||
size_t max_packet_size() const { return this->applied_.max_packet_size(); }
|
||||
// True while a packet is being received, or has been received and not yet read, so a send would lose it.
|
||||
// Reads the chip only when the radio is idle and listening; any other state reports false, a failed read true.
|
||||
bool is_receiving();
|
||||
|
||||
// Requires can_configure(). Resets the chip and applies the requested profile.
|
||||
RadioEffects configure(const RadioProfile &requested, std::span<char, 16> version);
|
||||
// Requires can_change_mode(). Cold sleep and failed commands need configuration afterwards.
|
||||
RadioEffects change_mode(ModeCommand command, uint8_t arg);
|
||||
// Result SX126X_ERROR_NONE starts a send that finishes exactly once, through poll_transmit() or
|
||||
// cancel_transmit(). Any other result owes no completion.
|
||||
RadioEffects start_transmit(SX126xTransmitListener *listener, const uint8_t *data, size_t len, uint32_t timeout_ms);
|
||||
// Sets finished only when it ended the current send.
|
||||
RadioEffects poll_transmit(uint32_t now);
|
||||
// Sets finished only if listener owns the current send.
|
||||
RadioEffects cancel_transmit(SX126xTransmitListener *listener);
|
||||
// One loop step: polls a send, or reads a received packet into packet.
|
||||
RadioEffects poll(uint32_t now, std::vector<uint8_t> &packet);
|
||||
|
||||
private:
|
||||
struct TxOperation {
|
||||
SX126xTransmitListener *listener{nullptr};
|
||||
uint32_t started_ms{0};
|
||||
uint32_t timeout_ms{0};
|
||||
};
|
||||
void commit_(RadioState state) {
|
||||
this->state_ = state;
|
||||
this->busy_ = false;
|
||||
}
|
||||
static RadioEffects comm_report(bool ok);
|
||||
const LogString *apply_configuration_(const RadioProfile &requested, std::span<char, 16> version);
|
||||
bool restore_();
|
||||
RadioEffects finish_transmit_(SX126xError result);
|
||||
RadioEffects receive_(bool holding, uint32_t now, std::vector<uint8_t> &packet);
|
||||
SX126xCommands commands_;
|
||||
AppliedProfile applied_;
|
||||
TxOperation tx_;
|
||||
uint32_t rx_retry_started_ms_{0};
|
||||
uint16_t pending_irq_{0}; // flags of a received packet whose read failed after they were cleared
|
||||
GPIOPin *dio1_pin_{nullptr};
|
||||
GPIOPin *rst_pin_{nullptr};
|
||||
RadioState state_{RadioState::RADIO_STATE_NEEDS_CONFIGURATION};
|
||||
bool busy_{false};
|
||||
bool rx_retry_pending_{false};
|
||||
};
|
||||
|
||||
} // namespace esphome::sx126x
|
||||
@@ -1,45 +0,0 @@
|
||||
#include "sx126x_spi_device.h"
|
||||
#include "esphome/core/hal.h"
|
||||
|
||||
namespace esphome::sx126x {
|
||||
|
||||
static constexpr uint32_t BUSY_TIMEOUT_MS = 20;
|
||||
static constexpr uint32_t SWITCHING_DELAY_US = 1;
|
||||
|
||||
void SX126xSpiDevice::exchange_(std::span<const uint8_t> header, std::span<const uint8_t> tx, std::span<uint8_t> rx) {
|
||||
if (!this->ok_) {
|
||||
return;
|
||||
}
|
||||
// Selecting first wakes a sleeping radio. The guard releases CS even on timeout.
|
||||
Selection selected(this->device_);
|
||||
const uint32_t start = millis();
|
||||
while (this->busy_pin_->digital_read()) {
|
||||
if (millis() - start > BUSY_TIMEOUT_MS) {
|
||||
this->ok_ = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
for (auto byte : header) {
|
||||
this->device_.transfer_byte(byte);
|
||||
}
|
||||
for (auto byte : tx) {
|
||||
this->device_.transfer_byte(byte);
|
||||
}
|
||||
for (auto &byte : rx) {
|
||||
byte = this->device_.transfer_byte(0);
|
||||
}
|
||||
}
|
||||
|
||||
void SX126xSpiDevice::write(std::span<const uint8_t> header, std::span<const uint8_t> data) {
|
||||
this->exchange_(header, data, {});
|
||||
if (this->ok_) {
|
||||
// This delay belongs after CS is released, not in the selected interval.
|
||||
delayMicroseconds(SWITCHING_DELAY_US);
|
||||
}
|
||||
}
|
||||
|
||||
void SX126xSpiDevice::read(std::span<const uint8_t> header, std::span<uint8_t> data) {
|
||||
this->exchange_(header, {}, data);
|
||||
}
|
||||
|
||||
} // namespace esphome::sx126x
|
||||
@@ -1,63 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/components/spi/spi.h"
|
||||
#include <span>
|
||||
|
||||
namespace esphome::sx126x {
|
||||
|
||||
// Persistent radio device. read()/write() use exchange_() for one complete selected interval.
|
||||
// No raw SPI access escapes. Call only from the main loop; spans are borrowed until return.
|
||||
// Failures stick: after a BUSY timeout every exchange is skipped until the next begin(),
|
||||
// so a command sequence checks ok() once instead of after every command.
|
||||
class SX126xSpiDevice {
|
||||
public:
|
||||
SX126xSpiDevice() = default;
|
||||
SX126xSpiDevice(const SX126xSpiDevice &) = delete;
|
||||
SX126xSpiDevice &operator=(const SX126xSpiDevice &) = delete;
|
||||
void set_spi_parent(spi::SPIComponent *parent) { this->device_.set_spi_parent(parent); }
|
||||
void set_cs_pin(GPIOPin *pin) { this->device_.set_cs_pin(pin); }
|
||||
void set_data_rate(uint32_t rate) { this->device_.set_data_rate(rate); }
|
||||
void set_mode(spi::SPIMode mode) { this->device_.set_mode(mode); }
|
||||
void set_bit_order(spi::SPIBitOrder order) { this->device_.set_bit_order(order); }
|
||||
void set_release_device(bool release) { this->device_.set_release_device(release); }
|
||||
void set_write_only(bool write_only) { this->device_.set_write_only(write_only); }
|
||||
#ifdef USE_SPI_PSRAM_DMA
|
||||
void set_psram_dma(bool enable) { this->device_.set_psram_dma(enable); }
|
||||
#endif
|
||||
|
||||
void set_busy_pin(GPIOPin *pin) { this->busy_pin_ = pin; }
|
||||
GPIOPin *get_busy_pin() const { return this->busy_pin_; }
|
||||
GPIOPin *get_cs_pin() const { return this->device_.get_cs_pin(); }
|
||||
void setup() { this->device_.spi_setup(); }
|
||||
void teardown() { this->device_.spi_teardown(); }
|
||||
// Starts a command sequence with no recorded failure.
|
||||
void begin() { this->ok_ = true; }
|
||||
// False once any exchange since begin() timed out waiting for BUSY.
|
||||
bool ok() const { return this->ok_; }
|
||||
void write(std::span<const uint8_t> header, std::span<const uint8_t> data);
|
||||
// Leaves data unchanged when the exchange is skipped or times out.
|
||||
void read(std::span<const uint8_t> header, std::span<uint8_t> data);
|
||||
|
||||
private:
|
||||
class Device final : public spi::SPIDevice<spi::BIT_ORDER_MSB_FIRST, spi::CLOCK_POLARITY_LOW,
|
||||
spi::CLOCK_PHASE_LEADING, spi::DATA_RATE_8MHZ> {
|
||||
public:
|
||||
GPIOPin *get_cs_pin() const { return this->cs_; }
|
||||
};
|
||||
class Selection {
|
||||
public:
|
||||
explicit Selection(Device &device) : device_(device) { this->device_.enable(); }
|
||||
~Selection() { this->device_.disable(); }
|
||||
Selection(const Selection &) = delete;
|
||||
Selection &operator=(const Selection &) = delete;
|
||||
|
||||
private:
|
||||
Device &device_;
|
||||
};
|
||||
void exchange_(std::span<const uint8_t> header, std::span<const uint8_t> tx, std::span<uint8_t> rx);
|
||||
Device device_;
|
||||
GPIOPin *busy_pin_{nullptr};
|
||||
bool ok_{true};
|
||||
};
|
||||
|
||||
} // namespace esphome::sx126x
|
||||
@@ -1,72 +0,0 @@
|
||||
from esphome.components import packet_interface
|
||||
from esphome.components.packet_interface import CONF_MAX_PACKET_SIZE
|
||||
from esphome.components.packet_interface.radio_link import (
|
||||
MAX_PACKET_SIZE,
|
||||
new_radio_link,
|
||||
radio_link_final_validate,
|
||||
radio_link_schema,
|
||||
)
|
||||
import esphome.config_validation as cv
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from .. import (
|
||||
CONF_MODULATION,
|
||||
CONF_PACKET_MODE,
|
||||
CONF_PAYLOAD_LENGTH,
|
||||
CONF_RX_START,
|
||||
CONF_SX127X_ID,
|
||||
CONF_SYNC_VALUE,
|
||||
SX127x,
|
||||
SX127xListener,
|
||||
sx127x_ns,
|
||||
)
|
||||
|
||||
CODEOWNERS = ["@clydebarrow"]
|
||||
DEPENDENCIES = ["sx127x"]
|
||||
|
||||
# Outside LoRa mode the 64 byte FIFO also holds the length byte
|
||||
FSK_MAX_PACKET_SIZE = 63
|
||||
|
||||
SX127xPacketInterface = sx127x_ns.class_(
|
||||
"SX127xPacketInterface", packet_interface.PacketInterface, SX127xListener
|
||||
)
|
||||
|
||||
CONFIG_SCHEMA = radio_link_schema(SX127xPacketInterface, CONF_SX127X_ID, SX127x)
|
||||
|
||||
|
||||
def _check_fsk(config: ConfigType, radio: ConfigType) -> None:
|
||||
"""Without LoRa, the radio must send packets, not a continuous bit stream, and holds fewer bytes.
|
||||
|
||||
It can tell that a packet is arriving only from its sync word, which listen before talk needs.
|
||||
"""
|
||||
if radio[CONF_MODULATION] == "LORA":
|
||||
return
|
||||
if not radio.get(CONF_PACKET_MODE, False):
|
||||
raise cv.Invalid(
|
||||
f"Without LoRa modulation the radio's '{CONF_PACKET_MODE}' must be true, as a link sends packets",
|
||||
path=[CONF_SX127X_ID],
|
||||
)
|
||||
if not radio.get(CONF_SYNC_VALUE):
|
||||
raise cv.Invalid(
|
||||
f"Without LoRa modulation the radio needs a '{CONF_SYNC_VALUE}', so that the link can tell when a "
|
||||
"packet is arriving and not send over it",
|
||||
path=[CONF_SX127X_ID],
|
||||
)
|
||||
if config[CONF_MAX_PACKET_SIZE] > FSK_MAX_PACKET_SIZE:
|
||||
raise cv.Invalid(
|
||||
f"Without LoRa modulation the radio sends at most {FSK_MAX_PACKET_SIZE} bytes",
|
||||
path=[CONF_MAX_PACKET_SIZE],
|
||||
)
|
||||
|
||||
|
||||
def _receive_limit(radio: ConfigType) -> int:
|
||||
return MAX_PACKET_SIZE if radio[CONF_MODULATION] == "LORA" else FSK_MAX_PACKET_SIZE
|
||||
|
||||
|
||||
FINAL_VALIDATE_SCHEMA = radio_link_final_validate(
|
||||
CONF_SX127X_ID, CONF_PAYLOAD_LENGTH, CONF_RX_START, _check_fsk, _receive_limit
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
await new_radio_link(config, CONF_SX127X_ID, _receive_limit)
|
||||
@@ -1,10 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/components/packet_interface/radio_link.h"
|
||||
#include "esphome/components/sx127x/sx127x.h"
|
||||
|
||||
namespace esphome::sx127x {
|
||||
|
||||
using SX127xPacketInterface = packet_interface::RadioLink<SX127x, SX127xListener, SX127xError, SX127X_MAX_PACKET_SIZE>;
|
||||
|
||||
} // namespace esphome::sx127x
|
||||
@@ -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,
|
||||
@@ -62,86 +47,35 @@ void SX127x::read_fifo_(std::vector<uint8_t> &packet) {
|
||||
this->disable();
|
||||
}
|
||||
|
||||
// Burst write: the radio moves to the next register after each byte, except for REG_FIFO
|
||||
void SX127x::write_registers_(uint8_t reg, const uint8_t *data, size_t len) {
|
||||
void SX127x::write_fifo_(const uint8_t *data, size_t len) {
|
||||
this->enable();
|
||||
this->write_byte(reg | 0x80);
|
||||
this->write_array(data, len);
|
||||
this->write_byte(REG_FIFO | 0x80);
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
this->transfer_byte(data[i]);
|
||||
}
|
||||
this->disable();
|
||||
}
|
||||
|
||||
void SX127x::write_register16_(uint8_t msb_reg, uint16_t value) {
|
||||
uint8_t bytes[2];
|
||||
put_be16(bytes, value);
|
||||
this->write_registers_(msb_reg, bytes, sizeof(bytes));
|
||||
}
|
||||
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);
|
||||
@@ -150,42 +84,35 @@ 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;
|
||||
uint8_t frf_bytes[3];
|
||||
put_be24(frf_bytes, static_cast<uint32_t>(frf));
|
||||
this->write_registers_(REG_FRF_MSB, frf_bytes, sizeof(frf_bytes));
|
||||
this->write_register_(REG_FRF_MSB, (uint8_t) ((frf >> 16) & 0xFF));
|
||||
this->write_register_(REG_FRF_MID, (uint8_t) ((frf >> 8) & 0xFF));
|
||||
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) {
|
||||
@@ -202,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_() {
|
||||
@@ -213,12 +141,14 @@ void SX127x::configure_fsk_ook_() {
|
||||
this->write_register_(REG_RX_BW, progmem_read_byte(&BW_FSK_OOK[this->bandwidth_]));
|
||||
|
||||
// set fdev
|
||||
uint16_t fdev = clamp_at_most((this->deviation_ * 4096) / 250000, uint32_t{0x3FFF});
|
||||
this->write_register16_(REG_FDEV_MSB, fdev);
|
||||
uint32_t fdev = std::min((this->deviation_ * 4096) / 250000, (uint32_t) 0x3FFF);
|
||||
this->write_register_(REG_FDEV_MSB, (uint8_t) ((fdev >> 8) & 0xFF));
|
||||
this->write_register_(REG_FDEV_LSB, (uint8_t) ((fdev >> 0) & 0xFF));
|
||||
|
||||
// set bitrate
|
||||
uint16_t bitrate = (FXOSC + this->bitrate_ / 2) / this->bitrate_; // round up
|
||||
this->write_register16_(REG_BITRATE_MSB, bitrate);
|
||||
uint64_t bitrate = (FXOSC + this->bitrate_ / 2) / this->bitrate_; // round up
|
||||
this->write_register_(REG_BITRATE_MSB, (uint8_t) ((bitrate >> 8) & 0xFF));
|
||||
this->write_register_(REG_BITRATE_LSB, (uint8_t) ((bitrate >> 0) & 0xFF));
|
||||
|
||||
// configure rx and afc
|
||||
this->write_register_(REG_AFC_BW, progmem_read_byte(&BW_FSK_OOK[this->afc_bandwidth_]));
|
||||
@@ -238,7 +168,7 @@ void SX127x::configure_fsk_ook_() {
|
||||
this->write_register_(REG_PAYLOAD_LENGTH_LSB, this->payload_length_);
|
||||
this->write_register_(REG_PACKET_CONFIG_1, crc_mode | FIXED_LENGTH);
|
||||
} else {
|
||||
this->write_register_(REG_PAYLOAD_LENGTH_LSB, this->get_max_packet_size());
|
||||
this->write_register_(REG_PAYLOAD_LENGTH_LSB, this->get_max_packet_size() - 1);
|
||||
this->write_register_(REG_PACKET_CONFIG_1, crc_mode | VARIABLE_LENGTH);
|
||||
}
|
||||
this->write_register_(REG_PACKET_CONFIG_2, PACKET_MODE);
|
||||
@@ -267,7 +197,8 @@ void SX127x::configure_fsk_ook_() {
|
||||
} else {
|
||||
this->write_register_(REG_PREAMBLE_DETECT, PREAMBLE_DETECTOR_OFF);
|
||||
}
|
||||
this->write_register16_(REG_PREAMBLE_SIZE_MSB, this->preamble_size_);
|
||||
this->write_register_(REG_PREAMBLE_SIZE_MSB, this->preamble_size_ >> 8);
|
||||
this->write_register_(REG_PREAMBLE_SIZE_LSB, this->preamble_size_ & 0xFF);
|
||||
|
||||
// config sync generation and setup ook threshold
|
||||
uint8_t bitsync = this->bitsync_ ? BIT_SYNC_ON : BIT_SYNC_OFF;
|
||||
@@ -295,7 +226,8 @@ void SX127x::configure_lora_() {
|
||||
|
||||
// config preamble
|
||||
if (this->preamble_size_ >= 6) {
|
||||
this->write_register16_(REG_PREAMBLE_LEN_MSB, this->preamble_size_);
|
||||
this->write_register_(REG_PREAMBLE_LEN_MSB, this->preamble_size_ >> 8);
|
||||
this->write_register_(REG_PREAMBLE_LEN_LSB, this->preamble_size_ & 0xFF);
|
||||
}
|
||||
|
||||
// optimize detection
|
||||
@@ -320,167 +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;
|
||||
}
|
||||
// The 64 byte FIFO also holds the length byte
|
||||
return 63;
|
||||
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_registers_(REG_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::is_receiving() {
|
||||
if (this->state_ == RadioState::RADIO_STATE_HOLDING_RX) {
|
||||
return true;
|
||||
}
|
||||
// A radio that sleeps after sending is not listening
|
||||
if (this->state_ != RadioState::RADIO_STATE_IDLE || !this->applied_.rx_start || this->dio0_pin_ == nullptr) {
|
||||
return false;
|
||||
}
|
||||
const bool lora = this->applied_.modulation == MOD_LORA;
|
||||
// In receive mode DIO0 signals a received packet that loop() has not read yet. In LoRa it also signals TX_DONE
|
||||
// after the TX mode action.
|
||||
if (this->dio0_pin_->digital_read() && (!lora || (this->read_register_(REG_IRQ_FLAGS) & RX_DONE) != 0)) {
|
||||
return true;
|
||||
}
|
||||
if (!lora) {
|
||||
// Set from the sync word until the packet has been read; the preamble flag stays set when no sync word follows
|
||||
return (this->read_register_(REG_IRQ_FLAGS_1) & IRQ_FLAGS_1_SYNC_ADDRESS_MATCH) != 0;
|
||||
}
|
||||
return (this->read_register_(REG_MODEM_STAT) &
|
||||
(MODEM_STAT_SIGNAL_DETECTED | MODEM_STAT_SIGNAL_SYNCHRONIZED | MODEM_STAT_HEADER_VALID)) != 0;
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -491,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);
|
||||
@@ -575,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) {
|
||||
@@ -606,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:");
|
||||
|
||||
@@ -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,72 +76,27 @@ 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); }
|
||||
// True while a packet is being received, or has been received and not yet read; sending would lose it.
|
||||
bool is_receiving();
|
||||
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 write_registers_(uint8_t reg, const uint8_t *data, size_t len);
|
||||
void write_register16_(uint8_t msb_reg, uint16_t value);
|
||||
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);
|
||||
void call_listeners_(const std::vector<uint8_t> &packet, float rssi, float snr);
|
||||
@@ -176,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_;
|
||||
@@ -203,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
|
||||
@@ -46,8 +46,6 @@ enum SX127xReg : uint8_t {
|
||||
REG_PAYLOAD_LENGTH_LSB = 0x32,
|
||||
REG_FIFO_THRESH = 0x35,
|
||||
REG_IMAGE_CAL = 0x3B,
|
||||
REG_IRQ_FLAGS_1 = 0x3E,
|
||||
REG_IRQ_FLAGS2 = 0x3F,
|
||||
// LoRa registers
|
||||
REG_FIFO_ADDR_PTR = 0x0D,
|
||||
REG_FIFO_TX_BASE_ADDR = 0x0E,
|
||||
@@ -262,22 +260,6 @@ enum SX127xIrqFlags : uint8_t {
|
||||
CAD_DETECTED = 0x01,
|
||||
};
|
||||
|
||||
enum SX127xIrqFlags1 : uint8_t {
|
||||
IRQ_FLAGS_1_PREAMBLE_DETECT = 0x02,
|
||||
IRQ_FLAGS_1_SYNC_ADDRESS_MATCH = 0x01,
|
||||
};
|
||||
|
||||
enum SX127xModemStat : uint8_t {
|
||||
MODEM_STAT_SIGNAL_DETECTED = 0x01,
|
||||
MODEM_STAT_SIGNAL_SYNCHRONIZED = 0x02,
|
||||
MODEM_STAT_HEADER_VALID = 0x08,
|
||||
};
|
||||
|
||||
enum SX127xIrqFlags2 : uint8_t {
|
||||
PACKET_SENT = 0x08,
|
||||
PAYLOAD_READY = 0x04,
|
||||
};
|
||||
|
||||
enum SX127xModemCfg1 : uint8_t {
|
||||
BW_7_8 = 0x00,
|
||||
BW_10_4 = 0x10,
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
"""TCP links. The packet_interface platform carries packets over a TCP connection."""
|
||||
|
||||
CODEOWNERS = ["@clydebarrow"]
|
||||
DOMAIN = "tcp"
|
||||
@@ -1,132 +0,0 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import binary_sensor, packet_interface, socket
|
||||
from esphome.components.const import (
|
||||
CONF_ALLOWED_IPS,
|
||||
CONF_CONNECTED,
|
||||
CONF_HOST,
|
||||
CONF_RECONNECT_INTERVAL,
|
||||
CONF_ROLE,
|
||||
)
|
||||
from esphome.components.packet_interface import (
|
||||
CONF_MAX_PACKET_SIZE,
|
||||
new_packet_interface,
|
||||
packet_interface_schema,
|
||||
)
|
||||
from esphome.components.packet_interface.layers import (
|
||||
CONF_ADDRESSING,
|
||||
CONF_RELIABILITY,
|
||||
CONF_SESSION,
|
||||
)
|
||||
from esphome.components.packet_interface.layers.basic_session import CONF_KEEP_ALIVE
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
CONF_ID,
|
||||
CONF_PORT,
|
||||
CONF_TIMEOUT,
|
||||
DEVICE_CLASS_CONNECTIVITY,
|
||||
ENTITY_CATEGORY_DIAGNOSTIC,
|
||||
)
|
||||
from esphome.types import ConfigType
|
||||
|
||||
CODEOWNERS = ["@clydebarrow"]
|
||||
DEPENDENCIES = ["network"]
|
||||
|
||||
|
||||
def AUTO_LOAD(config: ConfigType | None = None) -> list[str]:
|
||||
"""The binary_sensor component only for the connected sensor; without a config, as tooling calls it, both."""
|
||||
if not config or CONF_CONNECTED in config:
|
||||
return ["socket", "binary_sensor"]
|
||||
return ["socket"]
|
||||
|
||||
|
||||
# Each packet and its 2 byte length must fit the socket link's 1024 byte send buffer
|
||||
MAX_PACKET_SIZE = 1022
|
||||
|
||||
tcp_ns = cg.esphome_ns.namespace("tcp")
|
||||
TcpPacketInterface = tcp_ns.class_(
|
||||
"TcpPacketInterface", packet_interface.PacketInterface
|
||||
)
|
||||
|
||||
|
||||
def _timeout(config: ConfigType) -> ConfigType:
|
||||
"""Default the timeout to three keep-alive intervals, and require it to be longer than one."""
|
||||
keep_alive = config[CONF_KEEP_ALIVE].total_milliseconds
|
||||
if (timeout := config.get(CONF_TIMEOUT)) is None:
|
||||
config[CONF_TIMEOUT] = cv.positive_time_period_milliseconds(
|
||||
f"{keep_alive * 3}ms"
|
||||
)
|
||||
elif timeout.total_milliseconds <= keep_alive:
|
||||
raise cv.Invalid("Must be longer than keep_alive", path=[CONF_TIMEOUT])
|
||||
return config
|
||||
|
||||
|
||||
BASE_SCHEMA = packet_interface_schema(
|
||||
TcpPacketInterface,
|
||||
MAX_PACKET_SIZE,
|
||||
MAX_PACKET_SIZE,
|
||||
# TCP resends what is lost, joins exactly two devices, and its connection state is the session
|
||||
provides=(CONF_ADDRESSING, CONF_RELIABILITY, CONF_SESSION),
|
||||
).extend(
|
||||
{
|
||||
cv.Required(CONF_PORT): cv.port,
|
||||
cv.Optional(
|
||||
CONF_RECONNECT_INTERVAL, default="5s"
|
||||
): cv.positive_time_period_milliseconds,
|
||||
cv.Optional(CONF_KEEP_ALIVE, default="10s"): cv.All(
|
||||
cv.positive_time_period_milliseconds,
|
||||
cv.Range(min=cv.TimePeriod(seconds=1), max=cv.TimePeriod(hours=1)),
|
||||
),
|
||||
# Nothing received for this long closes the connection; it must be longer than the peer's keep_alive
|
||||
cv.Optional(CONF_TIMEOUT): cv.All(
|
||||
cv.positive_time_period_milliseconds,
|
||||
cv.Range(max=cv.TimePeriod(hours=3)),
|
||||
),
|
||||
cv.Optional(CONF_CONNECTED): binary_sensor.binary_sensor_schema(
|
||||
device_class=DEVICE_CLASS_CONNECTIVITY,
|
||||
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
cv.typed_schema(
|
||||
{
|
||||
"client": cv.All(
|
||||
BASE_SCHEMA.extend({cv.Required(CONF_HOST): socket.ipv4_host}),
|
||||
_timeout,
|
||||
),
|
||||
"server": cv.All(
|
||||
BASE_SCHEMA.extend(
|
||||
{cv.Optional(CONF_ALLOWED_IPS): socket.IPV4_ALLOW_SCHEMA}
|
||||
),
|
||||
_timeout,
|
||||
),
|
||||
},
|
||||
key=CONF_ROLE,
|
||||
default_type="client",
|
||||
),
|
||||
# A client uses one socket; a server one listener and one accepted socket
|
||||
socket.consume_role_sockets("tcp.packet_interface"),
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
rx_buffer = cg.static_buffer(
|
||||
config[CONF_ID], cg.uint8, config[CONF_MAX_PACKET_SIZE]
|
||||
)
|
||||
var = await new_packet_interface(config, rx_buffer)
|
||||
if config[CONF_ROLE] == "server":
|
||||
socket.require_tcp_listener()
|
||||
cg.add(var.set_server(True))
|
||||
socket.add_ipv4_allow(
|
||||
var.set_allow, config.get(CONF_ALLOWED_IPS), config[CONF_ID]
|
||||
)
|
||||
else:
|
||||
socket.require_tcp_client_link()
|
||||
cg.add(var.set_host(config[CONF_HOST]))
|
||||
cg.add(var.set_port(config[CONF_PORT]))
|
||||
cg.add(var.set_reconnect_interval(config[CONF_RECONNECT_INTERVAL]))
|
||||
cg.add(var.set_keep_alive(config[CONF_KEEP_ALIVE]))
|
||||
cg.add(var.set_receive_timeout(config[CONF_TIMEOUT]))
|
||||
binary_sensors = binary_sensor.sub_binary_sensors(config)
|
||||
await binary_sensors(CONF_CONNECTED, var.set_connected_binary_sensor)
|
||||
@@ -1,182 +0,0 @@
|
||||
#include "tcp_packet_interface.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome::tcp {
|
||||
|
||||
using packet_interface::PacketBuffer;
|
||||
using packet_interface::PacketMetaData;
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "tcp.packet_interface");
|
||||
|
||||
// The packet length before each packet
|
||||
static constexpr size_t LENGTH_SIZE = 2;
|
||||
// A peer that sends without a pause must not hold the main loop here; a frame being read carries over to the next pass
|
||||
static constexpr uint8_t MAX_FRAMES_PER_LOOP = 8;
|
||||
|
||||
TcpPacketInterface::TcpPacketInterface(std::span<uint8_t> rx_buffer)
|
||||
: packet_interface::PacketInterface(rx_buffer.size()), rx_buffer_(rx_buffer) {
|
||||
this->capabilities_ = packet_interface::CAPABILITY_RELIABILITY | packet_interface::CAPABILITY_SESSION |
|
||||
packet_interface::CAPABILITY_ADDRESSING;
|
||||
}
|
||||
|
||||
void TcpPacketInterface::setup() {
|
||||
this->link_.begin(TAG);
|
||||
#ifdef USE_SOCKET_TCP_LISTENER
|
||||
this->listener_.begin(TAG);
|
||||
#endif
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
if (this->connected_binary_sensor_ != nullptr)
|
||||
this->connected_binary_sensor_->publish_initial_state(false);
|
||||
#endif
|
||||
}
|
||||
|
||||
void TcpPacketInterface::dump_config() {
|
||||
bool server = false;
|
||||
#ifdef USE_SOCKET_TCP_LISTENER
|
||||
server = this->server_;
|
||||
#endif
|
||||
ESP_LOGCONFIG(TAG,
|
||||
"TCP Packet Interface '%s':\n"
|
||||
" Role: %s\n"
|
||||
" Address: %s:%u\n"
|
||||
" Reconnect Interval: %" PRIu32 "ms\n"
|
||||
" Keep Alive: %" PRIu32 "ms\n"
|
||||
" Timeout: %" PRIu32 "ms\n"
|
||||
" Max Packet Size: %zu",
|
||||
this->name_, server ? LOG_STR_LITERAL("server") : LOG_STR_LITERAL("client"),
|
||||
server ? LOG_STR_LITERAL("*") : this->link_.host(), this->link_.port(),
|
||||
this->link_.reconnect_interval(), this->keep_alive_ms_, this->timeout_ms_, this->max_packet_size_);
|
||||
#ifdef USE_SOCKET_TCP_LISTENER
|
||||
this->listener_.dump_config();
|
||||
#endif
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
LOG_BINARY_SENSOR(" ", "Connected", this->connected_binary_sensor_);
|
||||
#endif
|
||||
}
|
||||
|
||||
void TcpPacketInterface::on_shutdown() {
|
||||
this->link_.close();
|
||||
#ifdef USE_SOCKET_TCP_LISTENER
|
||||
this->listener_.close();
|
||||
#endif
|
||||
}
|
||||
|
||||
void TcpPacketInterface::loop() {
|
||||
#ifdef USE_SOCKET_TCP_LISTENER
|
||||
if (this->server_) {
|
||||
// A new client is accepted only once the drop of the last has been reported
|
||||
this->listener_.poll(this->link_, !this->connected_);
|
||||
} else {
|
||||
this->link_.poll();
|
||||
}
|
||||
#else
|
||||
this->link_.poll();
|
||||
#endif
|
||||
if (this->link_.connected() != this->connected_)
|
||||
this->on_connection_(this->link_.connected());
|
||||
if (!this->connected_)
|
||||
return;
|
||||
this->read_();
|
||||
if (!this->connected_)
|
||||
return;
|
||||
uint32_t now = App.get_loop_component_start_time();
|
||||
if (now - this->last_rx_ms_ > this->timeout_ms_) {
|
||||
ESP_LOGW(TAG, "%s: Nothing received for %" PRIu32 "ms, closing the connection", this->name_, this->timeout_ms_);
|
||||
this->link_.close();
|
||||
this->link_.note_attempt();
|
||||
this->on_connection_(false);
|
||||
return;
|
||||
}
|
||||
if (now - this->last_tx_ms_ >= this->keep_alive_ms_)
|
||||
this->queue_frame_(nullptr, 0);
|
||||
this->flush_();
|
||||
}
|
||||
|
||||
void TcpPacketInterface::flush_() { this->tx_waiting_ = !this->link_.flush_tx(); }
|
||||
|
||||
size_t TcpPacketInterface::get_send_capacity() const {
|
||||
if (!this->tx_waiting_)
|
||||
return SIZE_MAX;
|
||||
return this->link_.tx_free() / (this->max_packet_size_ + LENGTH_SIZE);
|
||||
}
|
||||
|
||||
void TcpPacketInterface::on_connection_(bool connected) {
|
||||
ESP_LOGD(TAG, "%s: Connection %s", this->name_, connected ? LOG_STR_LITERAL("up") : LOG_STR_LITERAL("down"));
|
||||
this->connected_ = connected;
|
||||
this->tx_waiting_ = false;
|
||||
this->rx_have_ = 0;
|
||||
this->last_rx_ms_ = this->last_tx_ms_ = App.get_loop_component_start_time();
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
if (this->connected_binary_sensor_ != nullptr)
|
||||
this->connected_binary_sensor_->publish_state(connected);
|
||||
#endif
|
||||
this->session_callback_.call(connected);
|
||||
}
|
||||
|
||||
void TcpPacketInterface::read_() {
|
||||
for (uint8_t frames = 0; frames != MAX_FRAMES_PER_LOOP;) {
|
||||
ssize_t count;
|
||||
if (this->rx_have_ < LENGTH_SIZE) {
|
||||
count = this->link_.read(this->rx_header_ + this->rx_have_, LENGTH_SIZE - this->rx_have_);
|
||||
} else {
|
||||
count = this->link_.read(this->rx_buffer_.data() + this->rx_have_ - LENGTH_SIZE,
|
||||
this->rx_length_ + LENGTH_SIZE - this->rx_have_);
|
||||
}
|
||||
// Nothing more for now; a dropped link is seen on the next loop
|
||||
if (count <= 0)
|
||||
return;
|
||||
this->last_rx_ms_ = App.get_loop_component_start_time();
|
||||
this->rx_have_ += count;
|
||||
if (this->rx_have_ < LENGTH_SIZE)
|
||||
continue;
|
||||
if (this->rx_have_ == LENGTH_SIZE) {
|
||||
this->rx_length_ = encode_uint16(this->rx_header_[1], this->rx_header_[0]);
|
||||
if (this->rx_length_ > this->max_packet_size_) {
|
||||
// The stream cannot be resynchronised, so start a new connection
|
||||
ESP_LOGW(TAG, "%s: Packet of %u bytes is larger than %zu, closing the connection", this->name_,
|
||||
this->rx_length_, this->max_packet_size_);
|
||||
this->link_.close();
|
||||
this->link_.note_attempt();
|
||||
this->on_connection_(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (this->rx_have_ == this->rx_length_ + LENGTH_SIZE) {
|
||||
this->rx_have_ = 0;
|
||||
frames++;
|
||||
// A zero length packet is a keep-alive
|
||||
if (this->rx_length_ != 0)
|
||||
this->on_receive_from_interface_(PacketBuffer(this->rx_buffer_.data(), this->rx_length_), {});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool TcpPacketInterface::queue_frame_(const PacketBuffer *data, size_t size) {
|
||||
if (this->link_.tx_free() < size + LENGTH_SIZE)
|
||||
return false;
|
||||
uint8_t *tail = this->link_.tx_tail();
|
||||
tail[0] = static_cast<uint8_t>(size);
|
||||
tail[1] = static_cast<uint8_t>(size >> 8);
|
||||
if (data != nullptr)
|
||||
data->copy_to(tail + LENGTH_SIZE, size);
|
||||
this->link_.tx_commit(size + LENGTH_SIZE);
|
||||
this->last_tx_ms_ = App.get_loop_component_start_time();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TcpPacketInterface::send_to_interface(const PacketBuffer &data, const PacketMetaData &meta_data) {
|
||||
size_t size = data.size();
|
||||
if (size > this->max_packet_size_) {
|
||||
ESP_LOGW(TAG, "%s: Packet of %zu bytes is larger than %zu", this->name_, size, this->max_packet_size_);
|
||||
return false;
|
||||
}
|
||||
if (!this->connected_ || !this->queue_frame_(&data, size))
|
||||
return false;
|
||||
// A write that fails closes the link and discards what was queued, this packet included
|
||||
this->flush_();
|
||||
return this->link_.connected();
|
||||
}
|
||||
|
||||
} // namespace esphome::tcp
|
||||
@@ -1,93 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
|
||||
#include "esphome/components/packet_interface/packet_interface.h"
|
||||
#include "esphome/components/socket/tcp_client_link.h"
|
||||
#ifdef USE_SOCKET_TCP_LISTENER
|
||||
#include "esphome/components/socket/tcp_listener.h"
|
||||
#endif
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
#include "esphome/components/binary_sensor/binary_sensor.h"
|
||||
#endif
|
||||
|
||||
namespace esphome::tcp {
|
||||
|
||||
/**
|
||||
* A packet interface link over one TCP connection, as a client that connects to a host, or a server that accepts
|
||||
* one client at a time.
|
||||
*
|
||||
* Each packet is sent as a 2 byte length, little endian, then the packet. TCP delivers the stream in order and
|
||||
* resends what is lost, and the connection joins exactly two devices, so the link provides the reliability,
|
||||
* addressing and session capabilities itself. Its connection state is the session state.
|
||||
*
|
||||
* Each packet is written to the socket as it is sent, so the link takes packets as fast as the socket does and keeps
|
||||
* the default, unlimited, send capacity; a packet is refused only while the connection is down or the socket is full.
|
||||
*
|
||||
* A zero length packet is a keep-alive, sent when nothing else has been sent for keep_alive. TCP can take minutes to
|
||||
* notice a peer that has gone without closing the connection, so the link closes it, and reconnects or accepts again,
|
||||
* when nothing has been received for the timeout, which must be longer than the peer's keep-alive interval.
|
||||
*/
|
||||
class TcpPacketInterface : public packet_interface::PacketInterface {
|
||||
public:
|
||||
/// @param rx_buffer Holds the packet being received; its size is the largest packet, and it must outlive the link
|
||||
explicit TcpPacketInterface(std::span<uint8_t> rx_buffer);
|
||||
|
||||
void setup() override;
|
||||
void loop() override;
|
||||
void dump_config() override;
|
||||
void on_shutdown() override;
|
||||
bool send_to_interface(const packet_interface::PacketBuffer &data,
|
||||
const packet_interface::PacketMetaData &meta_data) override;
|
||||
/**
|
||||
* Unlimited while the socket takes what is sent. Once frames wait for it, how many more full frames fit. A socket
|
||||
* that stalls part way through a fragmented packet still cuts it short.
|
||||
*/
|
||||
size_t get_send_capacity() const override;
|
||||
|
||||
void set_host(const char *host) { this->link_.set_host(host); }
|
||||
void set_port(uint16_t port) { this->link_.set_port(port); }
|
||||
void set_reconnect_interval(uint32_t interval_ms) { this->link_.set_reconnect_interval(interval_ms); }
|
||||
void set_keep_alive(uint32_t keep_alive_ms) { this->keep_alive_ms_ = keep_alive_ms; }
|
||||
/// The connection is closed when nothing has been received for this long; the peer's keep_alive sets the pace.
|
||||
void set_receive_timeout(uint32_t timeout_ms) { this->timeout_ms_ = timeout_ms; }
|
||||
#ifdef USE_SOCKET_TCP_LISTENER
|
||||
void set_server(bool server) { this->server_ = server; }
|
||||
#ifdef USE_SOCKET_IPV4_ALLOW
|
||||
void set_allow(const socket::Ipv4AllowEntry *entries, size_t count) { this->listener_.set_allow(entries, count); }
|
||||
#endif
|
||||
#endif
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
SUB_BINARY_SENSOR(connected)
|
||||
#endif
|
||||
|
||||
bool is_connected() const { return this->connected_; }
|
||||
|
||||
protected:
|
||||
void on_connection_(bool connected);
|
||||
void read_();
|
||||
bool queue_frame_(const packet_interface::PacketBuffer *data, size_t size);
|
||||
void flush_();
|
||||
|
||||
socket::TcpClientLink link_;
|
||||
#ifdef USE_SOCKET_TCP_LISTENER
|
||||
socket::TcpListener listener_;
|
||||
#endif
|
||||
const std::span<uint8_t> rx_buffer_;
|
||||
uint32_t keep_alive_ms_{10000};
|
||||
uint32_t timeout_ms_{30000};
|
||||
uint32_t last_rx_ms_{0};
|
||||
uint32_t last_tx_ms_{0};
|
||||
uint16_t rx_length_{0};
|
||||
// Bytes of the current frame received so far, counting the 2 byte length
|
||||
uint16_t rx_have_{0};
|
||||
uint8_t rx_header_[2]{};
|
||||
bool connected_ : 1 {false};
|
||||
bool tx_waiting_ : 1 {false}; // frames are queued that the socket has not taken yet
|
||||
#ifdef USE_SOCKET_TCP_LISTENER
|
||||
bool server_ : 1 {false};
|
||||
#endif
|
||||
};
|
||||
|
||||
} // namespace esphome::tcp
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -5,15 +5,13 @@ from esphome.const import CONF_MODEL
|
||||
from esphome.types import ConfigType
|
||||
|
||||
AUTO_LOAD = ["climate_ir"]
|
||||
CODEOWNERS = ["@glmnet", "@arpena", "@Rodrigoah"]
|
||||
CODEOWNERS = ["@glmnet", "@arpena"]
|
||||
|
||||
whirlpool_ns = cg.esphome_ns.namespace("whirlpool")
|
||||
WhirlpoolClimate = whirlpool_ns.class_("WhirlpoolClimate", climate_ir.ClimateIR)
|
||||
|
||||
Model = whirlpool_ns.enum("Model")
|
||||
MODELS = Model.options(
|
||||
"DG11J1-3A", "DG11J1-91", "HISENSE_ARG", "HITACHI_HCRA31NEWH", prefix="MODEL_"
|
||||
)
|
||||
MODELS = Model.options("DG11J1-3A", "DG11J1-91", "HISENSE_ARG", prefix="MODEL_")
|
||||
|
||||
CONFIG_SCHEMA = climate_ir.climate_ir_with_receiver_schema(WhirlpoolClimate).extend(
|
||||
{
|
||||
@@ -28,5 +26,3 @@ async def to_code(config: ConfigType) -> None:
|
||||
# cv.enum keeps the YAML key as a str subclass; the MockObj value cannot be compared
|
||||
if config[CONF_MODEL] == "HISENSE_ARG":
|
||||
cg.add_define("USE_WHIRLPOOL_HISENSE_ARG")
|
||||
elif config[CONF_MODEL] == "HITACHI_HCRA31NEWH":
|
||||
cg.add_define("USE_WHIRLPOOL_HITACHI_HCRA31NEWH")
|
||||
@@ -2,8 +2,6 @@
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace esphome::whirlpool {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "whirlpool.climate");
|
||||
@@ -46,17 +44,6 @@ static constexpr uint8_t HISENSE_ARG_POWER_TOGGLE = 0x01; // byte 15
|
||||
static constexpr uint8_t HISENSE_ARG_SETTINGS_ONLY = 0x02; // byte 15
|
||||
static constexpr uint8_t HISENSE_ARG_FIXED_TEMP_STEP = 7; // auto and fan-only send 23 C
|
||||
|
||||
// Hitachi HCRA31NEWH model: power is a state in every frame
|
||||
static constexpr uint8_t HITACHI_BYTE10 = 0x20; // byte 10
|
||||
static constexpr uint8_t HITACHI_COOL = 0x02; // byte 15
|
||||
static constexpr uint8_t HITACHI_OFF = 0x01; // byte 15
|
||||
static constexpr uint8_t HITACHI_BYTE18_ON = 0x38; // byte 18
|
||||
static constexpr uint8_t HITACHI_BYTE18_OFF = 0x28; // byte 18
|
||||
static constexpr uint8_t HITACHI_BYTE19 = 0x08; // byte 19
|
||||
|
||||
// Header, 21 bytes of 8 bits, two dividers and the footer mark
|
||||
static constexpr uint32_t WHIRLPOOL_FRAME_TIMINGS = 2 + WHIRLPOOL_STATE_LENGTH * 16 + 2 * 2 + 1;
|
||||
|
||||
WhirlpoolClimate::WhirlpoolClimate()
|
||||
: climate_ir::ClimateIR(
|
||||
WHIRLPOOL_DG11J1_3A_TEMP_MIN, WHIRLPOOL_DG11J1_3A_TEMP_MAX, 1.0f, true, true,
|
||||
@@ -68,19 +55,19 @@ void WhirlpoolClimate::transmit_state() {
|
||||
this->last_transmit_time_ = millis(); // setting the time of the last transmission.
|
||||
uint8_t remote_state[WHIRLPOOL_STATE_LENGTH];
|
||||
memset(remote_state, 0, sizeof(remote_state));
|
||||
put_be16(remote_state, this->remote_id_());
|
||||
remote_state[0] = 0x83;
|
||||
remote_state[1] = 0x06;
|
||||
remote_state[6] = 0x80;
|
||||
remote_state[18] = 0x08;
|
||||
remote_state[18] = 0x08; // the same on every supported model
|
||||
|
||||
const bool powered_on = this->mode != climate::CLIMATE_MODE_OFF;
|
||||
// Hitachi sends power as a state instead of a toggle
|
||||
const bool power_toggle = !this->is_hitachi_hcra31newh_() && powered_on != this->powered_on_assumed;
|
||||
auto powered_on = this->mode != climate::CLIMATE_MODE_OFF;
|
||||
const bool power_toggle = powered_on != this->powered_on_assumed;
|
||||
if (power_toggle) {
|
||||
// Set power toggle command
|
||||
remote_state[2] = 4;
|
||||
remote_state[15] = 1;
|
||||
this->powered_on_assumed = powered_on;
|
||||
}
|
||||
this->powered_on_assumed = powered_on;
|
||||
switch (this->mode) {
|
||||
case climate::CLIMATE_MODE_HEAT_COOL:
|
||||
// set fan auto
|
||||
@@ -106,10 +93,6 @@ void WhirlpoolClimate::transmit_state() {
|
||||
remote_state[15] = 6;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_OFF:
|
||||
// These remotes keep the cool code in the power-off frame
|
||||
if (this->is_hisense_arg_() || this->is_hitachi_hcra31newh_())
|
||||
remote_state[3] = WHIRLPOOL_COOL;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
@@ -119,7 +102,6 @@ void WhirlpoolClimate::transmit_state() {
|
||||
// Temperature
|
||||
auto temp = (uint8_t) roundf(clamp(this->target_temperature, this->temperature_min_(), this->temperature_max_()));
|
||||
const auto temp_step = (uint8_t) (temp - this->temperature_min_());
|
||||
this->target_temperature = temp; // publish what the unit was sent
|
||||
if (hisense_arg && this->fixed_temp_mode_()) {
|
||||
remote_state[3] |= HISENSE_ARG_FIXED_TEMP_STEP << 4;
|
||||
} else {
|
||||
@@ -149,6 +131,7 @@ void WhirlpoolClimate::transmit_state() {
|
||||
remote_state[2] |= WHIRLPOOL_SWING_MASK;
|
||||
remote_state[8] = WHIRLPOOL_SWING_BYTE8;
|
||||
}
|
||||
this->encode_hisense_arg_(remote_state, power_toggle, temp_step);
|
||||
} else if (this->send_swing_cmd_) {
|
||||
if (this->swing_mode == climate::CLIMATE_SWING_VERTICAL || this->swing_mode == climate::CLIMATE_SWING_OFF) {
|
||||
remote_state[2] |= WHIRLPOOL_SWING_MASK;
|
||||
@@ -156,11 +139,6 @@ void WhirlpoolClimate::transmit_state() {
|
||||
}
|
||||
}
|
||||
|
||||
if (hisense_arg)
|
||||
this->encode_hisense_arg_(remote_state, power_toggle, temp_step);
|
||||
if (this->is_hitachi_hcra31newh_())
|
||||
this->encode_hitachi_hcra31newh_(remote_state);
|
||||
|
||||
// Checksum
|
||||
remote_state[13] = xor_bytes(&remote_state[2], 11, remote_state[13]);
|
||||
remote_state[20] = xor_bytes(&remote_state[14], 6, remote_state[20]);
|
||||
@@ -170,7 +148,6 @@ void WhirlpoolClimate::transmit_state() {
|
||||
// Send code
|
||||
auto transmit = this->transmitter_->transmit();
|
||||
auto *data = transmit.get_data();
|
||||
data->reserve(WHIRLPOOL_FRAME_TIMINGS);
|
||||
|
||||
data->set_carrier_frequency(38000);
|
||||
|
||||
@@ -203,6 +180,10 @@ void WhirlpoolClimate::encode_hisense_arg_(uint8_t *remote_state, bool power_tog
|
||||
remote_state[15] = power_toggle ? HISENSE_ARG_POWER_TOGGLE : HISENSE_ARG_SETTINGS_ONLY;
|
||||
|
||||
switch (this->mode) {
|
||||
case climate::CLIMATE_MODE_OFF:
|
||||
// The remote keeps the cool code in the power-off frame
|
||||
remote_state[3] = (remote_state[3] & 0xF0) | WHIRLPOOL_COOL;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_DRY:
|
||||
// The unit runs these fan speeds itself; the user's choice is kept for the next mode change
|
||||
remote_state[2] &= ~WHIRLPOOL_FAN_MASK;
|
||||
@@ -231,27 +212,6 @@ void WhirlpoolClimate::encode_hisense_arg_(uint8_t *remote_state, bool power_tog
|
||||
#endif
|
||||
}
|
||||
|
||||
void WhirlpoolClimate::encode_hitachi_hcra31newh_(uint8_t *remote_state) const {
|
||||
#ifdef USE_WHIRLPOOL_HITACHI_HCRA31NEWH
|
||||
remote_state[10] = HITACHI_BYTE10;
|
||||
remote_state[18] = HITACHI_BYTE18_ON;
|
||||
remote_state[19] = HITACHI_BYTE19;
|
||||
// The unit takes the whole state from every frame: only the off frame carries the power bit
|
||||
switch (this->mode) {
|
||||
case climate::CLIMATE_MODE_COOL:
|
||||
remote_state[15] = HITACHI_COOL;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_OFF:
|
||||
remote_state[2] |= WHIRLPOOL_POWER;
|
||||
remote_state[15] = HITACHI_OFF;
|
||||
remote_state[18] = HITACHI_BYTE18_OFF;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
bool WhirlpoolClimate::on_receive(remote_base::RemoteReceiveData data) {
|
||||
// Check if the esp isn't currently transmitting.
|
||||
if (millis() - this->last_transmit_time_ < 500) {
|
||||
@@ -274,8 +234,7 @@ bool WhirlpoolClimate::on_receive(remote_base::RemoteReceiveData data) {
|
||||
if (!data.expect_item(WHIRLPOOL_BIT_MARK, WHIRLPOOL_GAP))
|
||||
return false;
|
||||
}
|
||||
// The Hitachi remote always sends all 21 bytes; byte 18 holds its power state
|
||||
if (i == WHIRLPOOL_SECOND_DIVIDER && !data.is_valid() && !this->is_hitachi_hcra31newh_()) {
|
||||
if (i == WHIRLPOOL_SECOND_DIVIDER && !data.is_valid()) {
|
||||
// Remote control only sent 14 bytes, nothing more to read, not even the footer
|
||||
ESP_LOGV(TAG, "Remote control only sent %d bytes", i);
|
||||
skip_footer = true;
|
||||
@@ -302,18 +261,13 @@ bool WhirlpoolClimate::on_receive(remote_base::RemoteReceiveData data) {
|
||||
ESP_LOGV_HEX(TAG, remote_state, WHIRLPOOL_STATE_LENGTH, WHIRLPOOL_STATE_LENGTH, "Received: %s");
|
||||
|
||||
// verify header remote code
|
||||
if (encode_uint16(remote_state[0], remote_state[1]) != this->remote_id_())
|
||||
if (remote_state[0] != 0x83 || remote_state[1] != 0x06)
|
||||
return false;
|
||||
|
||||
// powr on/off button
|
||||
ESP_LOGV(TAG, "Power: %02X", (remote_state[2] & WHIRLPOOL_POWER));
|
||||
|
||||
if (this->is_hitachi_hcra31newh_()) {
|
||||
// Power is a state: byte 18 says whether the unit is off
|
||||
this->powered_on_assumed = remote_state[18] != HITACHI_BYTE18_OFF;
|
||||
if (!this->powered_on_assumed)
|
||||
this->mode = climate::CLIMATE_MODE_OFF;
|
||||
} else if ((remote_state[2] & WHIRLPOOL_POWER) == WHIRLPOOL_POWER) {
|
||||
if ((remote_state[2] & WHIRLPOOL_POWER) == WHIRLPOOL_POWER) {
|
||||
auto powered_on = this->mode != climate::CLIMATE_MODE_OFF;
|
||||
|
||||
if (powered_on) {
|
||||
@@ -355,7 +309,7 @@ bool WhirlpoolClimate::on_receive(remote_base::RemoteReceiveData data) {
|
||||
int temp = remote_state[3] & 0xF0;
|
||||
ESP_LOGVV(TAG, "Temperature Raw: %02X", temp);
|
||||
temp = (uint8_t) temp >> 4;
|
||||
temp = std::min(temp + static_cast<int>(this->temperature_min_()), static_cast<int>(this->temperature_max_()));
|
||||
temp += static_cast<int>(this->temperature_min_());
|
||||
ESP_LOGVV(TAG, "Temperature Climate: %u", temp);
|
||||
this->target_temperature = temp;
|
||||
}
|
||||
|
||||
@@ -6,10 +6,9 @@ namespace esphome::whirlpool {
|
||||
|
||||
/// Simple enum to represent models.
|
||||
enum Model {
|
||||
MODEL_DG11J1_3A = 0, /// Temperature range is from 18 to 32
|
||||
MODEL_DG11J1_91 = 1, /// Temperature range is from 16 to 30
|
||||
MODEL_HISENSE_ARG = 2, /// Hisense/BGH (Argentina), 16 to 30
|
||||
MODEL_HITACHI_HCRA31NEWH = 3, /// Hitachi with the HCRA31NEWH remote, 16 to 30
|
||||
MODEL_DG11J1_3A = 0, /// Temperature range is from 18 to 32
|
||||
MODEL_DG11J1_91 = 1, /// Temperature range is from 16 to 30
|
||||
MODEL_HISENSE_ARG = 2, /// Hisense/BGH (Argentina), 16 to 30
|
||||
};
|
||||
|
||||
// Temperature
|
||||
@@ -30,9 +29,7 @@ class WhirlpoolClimate final : public climate_ir::ClimateIR {
|
||||
|
||||
/// Override control to change settings of the climate device.
|
||||
void control(const climate::ClimateCall &call) override {
|
||||
// The toggle remotes flip swing on every press, so only send one when the mode really changes
|
||||
auto swing = call.get_swing_mode();
|
||||
this->send_swing_cmd_ = swing.has_value() && *swing != this->swing_mode;
|
||||
send_swing_cmd_ = call.get_swing_mode().has_value();
|
||||
climate_ir::ClimateIR::control(call);
|
||||
}
|
||||
|
||||
@@ -58,22 +55,10 @@ class WhirlpoolClimate final : public climate_ir::ClimateIR {
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
/// False when the model is compiled out, so the compiler drops the Hitachi branches.
|
||||
bool is_hitachi_hcra31newh_() const {
|
||||
#ifdef USE_WHIRLPOOL_HITACHI_HCRA31NEWH
|
||||
return this->model_ == MODEL_HITACHI_HCRA31NEWH;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
/// The remote ID sent in bytes 0 and 1.
|
||||
uint16_t remote_id_() const { return this->is_hitachi_hcra31newh_() ? 0xA959 : 0x8306; }
|
||||
/// Modes in which the Hisense ARG model sends a fixed temperature.
|
||||
bool fixed_temp_mode_() const;
|
||||
/// Add the Hisense ARG bytes on top of the common whirlpool frame.
|
||||
void encode_hisense_arg_(uint8_t *remote_state, bool power_toggle, uint8_t temp_step) const;
|
||||
/// Add the Hitachi HCRA31NEWH bytes on top of the common whirlpool frame.
|
||||
void encode_hitachi_hcra31newh_(uint8_t *remote_state) const;
|
||||
/// Set the time of the last transmission.
|
||||
uint32_t last_transmit_time_{};
|
||||
|
||||
|
||||
@@ -563,7 +563,7 @@ class WiFiComponent final : public Component {
|
||||
// (In most use cases you won't need these)
|
||||
/// Setup WiFi interface.
|
||||
void setup() override;
|
||||
#if defined(USE_ESP32) || defined(USE_LN882X) || defined(USE_BK72XX)
|
||||
#if defined(USE_LN882X) || defined(USE_BK72XX)
|
||||
void on_powerdown() override;
|
||||
#endif
|
||||
void start();
|
||||
|
||||
@@ -1635,21 +1635,6 @@ bool WiFiComponent::wifi_dpp_start_listen_() {
|
||||
void WiFiComponent::wifi_dpp_stop_listen_() { esp_supp_dpp_stop_listen(); }
|
||||
#endif
|
||||
|
||||
void WiFiComponent::on_powerdown() {
|
||||
// Leave the AP before esp_restart() or deep sleep stops Wi-Fi. esp_wifi_stop() while associated
|
||||
// makes the ESP32 retransmit its Disassociation up to the retry limit although the AP ACKs it
|
||||
// (32 copies with protected management frames), which some APs handle badly.
|
||||
// Upstream bug: https://github.com/espressif/esp-idf/issues/19443 - remove this once it is fixed
|
||||
// in the ESP-IDF versions we support.
|
||||
// Ask the driver: s_sta_connected lags until the main loop has handled the connect event.
|
||||
wifi_ap_record_t ap_info;
|
||||
if (esp_wifi_sta_get_ap_info(&ap_info) != ESP_OK)
|
||||
return;
|
||||
ESP_LOGD(TAG, "Disconnecting before powerdown");
|
||||
esp_wifi_disconnect();
|
||||
delay(100); // NOLINT: once per reboot or deep sleep, lets the disassociation go out
|
||||
}
|
||||
|
||||
bool WiFiComponent::wifi_disconnect_() { return esp_wifi_disconnect(); }
|
||||
|
||||
bssid_t WiFiComponent::wifi_bssid() {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -294,8 +294,6 @@ void Application::reboot() {
|
||||
for (auto &component : std::ranges::reverse_view(this->components_)) {
|
||||
component->on_shutdown();
|
||||
}
|
||||
// No teardown on a forced reboot, but still power hardware down (Wi-Fi leaves the AP)
|
||||
this->run_powerdown_hooks();
|
||||
arch_restart();
|
||||
}
|
||||
void Application::safe_reboot() {
|
||||
|
||||
Loaded 100 of 194 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user