mirror of
https://github.com/esphome/esphome.git
synced 2026-11-15 09:36:04 +00:00
Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
55f15f45ed | ||
|
|
0f691dcca3 | ||
|
|
2d7a8ef338 | ||
|
|
db4c9ba24e | ||
|
|
acf4da7bc8 | ||
|
|
b6dbc9f2f0 | ||
|
|
170a3b7374 | ||
|
|
d53db6af87 | ||
|
|
2e5e080df1 | ||
|
|
0221318335 | ||
|
|
f2468415e4 | ||
|
|
b83255590a | ||
|
|
f738157382 | ||
|
|
85e7a22ee8 | ||
|
|
101ee872cb | ||
|
|
3b546cc5fa | ||
|
|
8acd9df0cf | ||
|
|
6f3270f318 | ||
|
|
822c0f6e49 | ||
|
|
fd76602635 | ||
|
|
0eee107373 | ||
|
|
2347e0dcef |
No files matched your search
@@ -149,7 +149,6 @@ esphome/components/cst226/* @clydebarrow
|
||||
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
|
||||
|
||||
@@ -9,6 +9,27 @@ ESPHOME_LOG_TAG(TAG, "airton.climate");
|
||||
// Distinct from the climate's own RESTORE_STATE_VERSION, which shares the entity's preference key
|
||||
static constexpr uint32_t RESTORE_SETTINGS_VERSION = 0x2E86A1F3UL;
|
||||
|
||||
using climate_ir::find_ir_code;
|
||||
using climate_ir::from_ir_code;
|
||||
using climate_ir::IRCode;
|
||||
using climate_ir::to_ir_code;
|
||||
|
||||
static constexpr uint8_t AIRTON_POWER_ON = 0b1000;
|
||||
// A received code that is not listed is ignored
|
||||
static constexpr IRCode MODES[] PROGMEM = {
|
||||
{climate::CLIMATE_MODE_COOL, AIRTON_POWER_ON | AIRTON_MODE_COOL},
|
||||
{climate::CLIMATE_MODE_DRY, AIRTON_POWER_ON | AIRTON_MODE_DRY},
|
||||
{climate::CLIMATE_MODE_HEAT, AIRTON_POWER_ON | AIRTON_MODE_HEAT},
|
||||
{climate::CLIMATE_MODE_HEAT_COOL, AIRTON_POWER_ON | AIRTON_MODE_AUTO},
|
||||
{climate::CLIMATE_MODE_FAN_ONLY, AIRTON_POWER_ON | AIRTON_MODE_FAN},
|
||||
};
|
||||
// Fan speeds 2 and 4 are only received
|
||||
static constexpr IRCode FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_AUTO, AIRTON_FAN_AUTO}, {climate::CLIMATE_FAN_LOW, AIRTON_FAN_1},
|
||||
{climate::CLIMATE_FAN_MEDIUM, AIRTON_FAN_3}, {climate::CLIMATE_FAN_HIGH, AIRTON_FAN_5},
|
||||
{climate::CLIMATE_FAN_LOW, AIRTON_FAN_2}, {climate::CLIMATE_FAN_HIGH, AIRTON_FAN_4},
|
||||
};
|
||||
|
||||
// From IRutils.h of IRremoteESP8266 library
|
||||
static uint8_t checksum(const uint8_t *frame) {
|
||||
return static_cast<uint8_t>(0x7F - sum_bytes(frame, AIRTON_STATE_FRAME_SIZE - 1)) ^ 0x2C;
|
||||
@@ -114,7 +135,9 @@ void AirtonClimate::transmit_state() {
|
||||
uint8_t remote_state[AIRTON_STATE_FRAME_SIZE] = {
|
||||
AIRTON_HEADER_BYTE0,
|
||||
AIRTON_HEADER_BYTE1,
|
||||
static_cast<uint8_t>(this->operation_mode_() | (this->fan_speed_() << 4)),
|
||||
static_cast<uint8_t>(
|
||||
this->operation_mode_() |
|
||||
(to_ir_code(FANS, this->fan_mode.value_or(climate::CLIMATE_FAN_AUTO), AIRTON_FAN_AUTO) << 4)),
|
||||
this->temperature_(),
|
||||
static_cast<uint8_t>(this->settings_.vertical_direction),
|
||||
this->operation_settings_(),
|
||||
@@ -139,48 +162,9 @@ void AirtonClimate::transmit_state() {
|
||||
}
|
||||
|
||||
uint8_t AirtonClimate::operation_mode_() {
|
||||
uint8_t operating_mode = 0b1000; // First bit is for power state
|
||||
switch (this->mode) {
|
||||
case climate::CLIMATE_MODE_COOL:
|
||||
operating_mode |= AIRTON_MODE_COOL;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_DRY:
|
||||
operating_mode |= AIRTON_MODE_DRY;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT:
|
||||
operating_mode |= AIRTON_MODE_HEAT;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT_COOL:
|
||||
operating_mode |= AIRTON_MODE_AUTO;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_FAN_ONLY:
|
||||
operating_mode |= AIRTON_MODE_FAN;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_OFF:
|
||||
default:
|
||||
operating_mode = 0b0111 & this->previous_mode_; // Set previous mode with power state bit off
|
||||
}
|
||||
this->previous_mode_ = operating_mode;
|
||||
return operating_mode;
|
||||
}
|
||||
|
||||
uint8_t AirtonClimate::fan_speed_() {
|
||||
uint8_t fan_speed;
|
||||
switch (this->fan_mode.value_or(climate::CLIMATE_FAN_AUTO)) {
|
||||
case climate::CLIMATE_FAN_LOW:
|
||||
fan_speed = AIRTON_FAN_1;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_MEDIUM:
|
||||
fan_speed = AIRTON_FAN_3;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_HIGH:
|
||||
fan_speed = AIRTON_FAN_5;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_AUTO:
|
||||
default:
|
||||
fan_speed = AIRTON_FAN_AUTO;
|
||||
}
|
||||
return fan_speed;
|
||||
// Off, or a mode not listed, repeats the previous mode with the power bit clear
|
||||
this->previous_mode_ = to_ir_code(MODES, this->mode, this->previous_mode_ & 0b0111);
|
||||
return this->previous_mode_;
|
||||
}
|
||||
|
||||
uint8_t AirtonClimate::temperature_() {
|
||||
@@ -217,47 +201,13 @@ void AirtonClimate::parse_state_frame_(const uint8_t *frame) {
|
||||
uint8_t mode = frame[2];
|
||||
// A later "off" repeats the mode the remote last sent, as the remote itself does
|
||||
this->previous_mode_ = mode & 0b00001111;
|
||||
if (mode & 0b00001000) { // The power bit
|
||||
switch (mode & 0b00000111) {
|
||||
case AIRTON_MODE_COOL:
|
||||
this->mode = climate::CLIMATE_MODE_COOL;
|
||||
break;
|
||||
case AIRTON_MODE_DRY:
|
||||
this->mode = climate::CLIMATE_MODE_DRY;
|
||||
break;
|
||||
case AIRTON_MODE_HEAT:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT;
|
||||
break;
|
||||
case AIRTON_MODE_AUTO:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT_COOL;
|
||||
break;
|
||||
case AIRTON_MODE_FAN:
|
||||
this->mode = climate::CLIMATE_MODE_FAN_ONLY;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (!(mode & AIRTON_POWER_ON)) {
|
||||
this->mode = climate::CLIMATE_MODE_OFF;
|
||||
} else {
|
||||
this->mode = from_ir_code(MODES, mode & 0b00001111, this->mode);
|
||||
}
|
||||
uint8_t fan_mode = (frame[2] & 0b01110000) >> 4;
|
||||
|
||||
switch (fan_mode) {
|
||||
case AIRTON_FAN_1:
|
||||
case AIRTON_FAN_2:
|
||||
this->fan_mode = climate::CLIMATE_FAN_LOW;
|
||||
break;
|
||||
case AIRTON_FAN_3:
|
||||
this->fan_mode = climate::CLIMATE_FAN_MEDIUM;
|
||||
break;
|
||||
case AIRTON_FAN_4:
|
||||
case AIRTON_FAN_5:
|
||||
this->fan_mode = climate::CLIMATE_FAN_HIGH;
|
||||
break;
|
||||
case AIRTON_FAN_AUTO:
|
||||
this->fan_mode = climate::CLIMATE_FAN_AUTO;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (const auto entry = find_ir_code(FANS, (frame[2] & 0b01110000) >> 4, true))
|
||||
this->fan_mode = static_cast<climate::ClimateFanMode>(entry->value);
|
||||
|
||||
this->target_temperature = (frame[3] & 0b00001111) + AIRTON_TEMP_MIN;
|
||||
|
||||
|
||||
@@ -117,7 +117,6 @@ class AirtonClimate : public climate_ir::ClimateIR {
|
||||
|
||||
void transmit_state() override;
|
||||
uint8_t operation_mode_();
|
||||
uint8_t fan_speed_();
|
||||
uint8_t temperature_();
|
||||
uint8_t operation_settings_();
|
||||
|
||||
|
||||
@@ -31,6 +31,23 @@ const uint8_t BALLU_SWING_VER = 0x07;
|
||||
const uint8_t BALLU_SWING_HOR = 0xe0;
|
||||
const uint8_t BALLU_POWER = 0x20;
|
||||
|
||||
using climate_ir::from_ir_code;
|
||||
using climate_ir::IRCode;
|
||||
using climate_ir::to_ir_code;
|
||||
|
||||
// A fan mode not listed sends no fan bits and a received mode not listed is ignored
|
||||
static constexpr IRCode MODES[] PROGMEM = {
|
||||
{climate::CLIMATE_MODE_AUTO, BALLU_AUTO}, {climate::CLIMATE_MODE_HEAT, BALLU_HEAT},
|
||||
{climate::CLIMATE_MODE_COOL, BALLU_COOL}, {climate::CLIMATE_MODE_DRY, BALLU_DRY},
|
||||
{climate::CLIMATE_MODE_FAN_ONLY, BALLU_FAN},
|
||||
};
|
||||
static constexpr IRCode FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_AUTO, BALLU_FAN_AUTO},
|
||||
{climate::CLIMATE_FAN_HIGH, BALLU_FAN_HIGH},
|
||||
{climate::CLIMATE_FAN_MEDIUM, BALLU_FAN_MED},
|
||||
{climate::CLIMATE_FAN_LOW, BALLU_FAN_LOW},
|
||||
};
|
||||
|
||||
void BalluClimate::transmit_state() {
|
||||
uint8_t remote_state[BALLU_STATE_LENGTH] = {0};
|
||||
|
||||
@@ -46,46 +63,8 @@ void BalluClimate::transmit_state() {
|
||||
remote_state[9] = (this->mode == climate::CLIMATE_MODE_OFF) ? 0 : BALLU_POWER;
|
||||
remote_state[11] = 0x1e;
|
||||
|
||||
// Fan speed
|
||||
switch (this->fan_mode.value_or(climate::CLIMATE_FAN_ON)) {
|
||||
case climate::CLIMATE_FAN_HIGH:
|
||||
remote_state[4] |= BALLU_FAN_HIGH;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_MEDIUM:
|
||||
remote_state[4] |= BALLU_FAN_MED;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_LOW:
|
||||
remote_state[4] |= BALLU_FAN_LOW;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_AUTO:
|
||||
remote_state[4] |= BALLU_FAN_AUTO;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// Mode
|
||||
switch (this->mode) {
|
||||
case climate::CLIMATE_MODE_AUTO:
|
||||
remote_state[6] |= BALLU_AUTO;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT:
|
||||
remote_state[6] |= BALLU_HEAT;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_COOL:
|
||||
remote_state[6] |= BALLU_COOL;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_DRY:
|
||||
remote_state[6] |= BALLU_DRY;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_FAN_ONLY:
|
||||
remote_state[6] |= BALLU_FAN;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_OFF:
|
||||
remote_state[6] |= BALLU_AUTO;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
remote_state[4] = to_ir_code(FANS, this->fan_mode.value_or(climate::CLIMATE_FAN_ON), 0);
|
||||
remote_state[6] = to_ir_code(MODES, this->mode, BALLU_AUTO);
|
||||
|
||||
// Checksum
|
||||
for (uint8_t i = 0; i < BALLU_STATE_LENGTH - 1; i++)
|
||||
@@ -149,25 +128,7 @@ bool BalluClimate::on_receive(remote_base::RemoteReceiveData data) {
|
||||
} else {
|
||||
auto mode = remote_state[6] & 0xe0;
|
||||
ESP_LOGV(TAG, "Mode: %02X", mode);
|
||||
switch (mode) {
|
||||
case BALLU_HEAT:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT;
|
||||
break;
|
||||
case BALLU_COOL:
|
||||
this->mode = climate::CLIMATE_MODE_COOL;
|
||||
break;
|
||||
case BALLU_DRY:
|
||||
this->mode = climate::CLIMATE_MODE_DRY;
|
||||
break;
|
||||
case BALLU_FAN:
|
||||
this->mode = climate::CLIMATE_MODE_FAN_ONLY;
|
||||
break;
|
||||
case BALLU_AUTO:
|
||||
this->mode = climate::CLIMATE_MODE_AUTO;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
this->mode = from_ir_code(MODES, mode, this->mode);
|
||||
}
|
||||
|
||||
// Set received temp
|
||||
@@ -180,21 +141,7 @@ bool BalluClimate::on_receive(remote_base::RemoteReceiveData data) {
|
||||
// Set received fan speed
|
||||
auto fan = remote_state[4] & 0xe0;
|
||||
ESP_LOGVV(TAG, "Fan: %02X", fan);
|
||||
switch (fan) {
|
||||
case BALLU_FAN_HIGH:
|
||||
this->fan_mode = climate::CLIMATE_FAN_HIGH;
|
||||
break;
|
||||
case BALLU_FAN_MED:
|
||||
this->fan_mode = climate::CLIMATE_FAN_MEDIUM;
|
||||
break;
|
||||
case BALLU_FAN_LOW:
|
||||
this->fan_mode = climate::CLIMATE_FAN_LOW;
|
||||
break;
|
||||
case BALLU_FAN_AUTO:
|
||||
default:
|
||||
this->fan_mode = climate::CLIMATE_FAN_AUTO;
|
||||
break;
|
||||
}
|
||||
this->fan_mode = from_ir_code(FANS, fan, climate::CLIMATE_FAN_AUTO);
|
||||
|
||||
// Set received swing status
|
||||
ESP_LOGVV(TAG, "Swing status: %02X %02X", remote_state[1] & BALLU_SWING_VER, remote_state[2] & BALLU_SWING_HOR);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -95,4 +95,19 @@ void ClimateIR::dump_config() {
|
||||
YESNO(this->modes_.count(climate::CLIMATE_MODE_HEAT_COOL)));
|
||||
}
|
||||
|
||||
int find_ir_code_index(const IRCode *table, size_t count, uint8_t key, bool match_code) {
|
||||
for (size_t i = 0; i < count; i++) {
|
||||
if (progmem_read_byte(match_code ? &table[i].code : &table[i].value) == key)
|
||||
return static_cast<int>(i);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
uint8_t lookup_ir_code(const IRCode *table, size_t count, uint8_t key, bool match_code, uint8_t fallback) {
|
||||
const int index = find_ir_code_index(table, count, key, match_code);
|
||||
if (index < 0)
|
||||
return fallback;
|
||||
return progmem_read_byte(match_code ? &table[index].value : &table[index].code);
|
||||
}
|
||||
|
||||
} // namespace esphome::climate_ir
|
||||
@@ -6,9 +6,42 @@
|
||||
#include "esphome/components/remote_base/remote_base.h"
|
||||
#include "esphome/components/remote_transmitter/remote_transmitter.h"
|
||||
#include "esphome/components/sensor/sensor.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/optional.h"
|
||||
|
||||
namespace esphome::climate_ir {
|
||||
|
||||
/// One entry of a PROGMEM table that maps a climate enum value to the unit's code.
|
||||
struct IRCode {
|
||||
uint8_t value; // a climate enum; they are all uint8_t
|
||||
uint8_t code;
|
||||
};
|
||||
|
||||
/// Index of the entry whose value (or, with match_code, code) is key, or -1. Reads the table from PROGMEM.
|
||||
int find_ir_code_index(const IRCode *table, size_t count, uint8_t key, bool match_code);
|
||||
|
||||
/// The entry whose value (or, with match_code, code) is key, read from PROGMEM.
|
||||
template<size_t N>
|
||||
ESPHOME_ALWAYS_INLINE optional<IRCode> find_ir_code(const IRCode (&table)[N], uint8_t key, bool match_code) {
|
||||
const int index = find_ir_code_index(table, N, key, match_code);
|
||||
if (index < 0)
|
||||
return {};
|
||||
return IRCode{progmem_read_byte(&table[index].value), progmem_read_byte(&table[index].code)};
|
||||
}
|
||||
|
||||
/// The code for value (or, with match_code, the value for code), or fallback when the table has no such entry.
|
||||
uint8_t lookup_ir_code(const IRCode *table, size_t count, uint8_t key, bool match_code, uint8_t fallback);
|
||||
|
||||
/// The code for value, or fallback when the table has no such value.
|
||||
template<size_t N> uint8_t to_ir_code(const IRCode (&table)[N], uint8_t value, uint8_t fallback) {
|
||||
return lookup_ir_code(table, N, value, false, fallback);
|
||||
}
|
||||
/// The value for code, or fallback when the table has no such code; pass the current state to keep it.
|
||||
template<typename T, size_t N> T from_ir_code(const IRCode (&table)[N], uint8_t code, T fallback) {
|
||||
static_assert(sizeof(T) == sizeof(uint8_t), "IRCode values are one byte");
|
||||
return static_cast<T>(lookup_ir_code(table, N, code, true, static_cast<uint8_t>(fallback)));
|
||||
}
|
||||
|
||||
/* A base for climate which works by sending (and receiving) IR codes
|
||||
|
||||
To send IR codes implement
|
||||
|
||||
@@ -112,6 +112,27 @@ const uint32_t TEMP_SHIFT = 8;
|
||||
|
||||
const uint16_t BITS = 28;
|
||||
|
||||
using climate_ir::find_ir_code;
|
||||
using climate_ir::IRCode;
|
||||
using climate_ir::to_ir_code;
|
||||
|
||||
// Mode commands sit in bits 12-15; the command that also powers the unit on clears the top one
|
||||
static constexpr uint8_t MODE_SHIFT = 12;
|
||||
static constexpr uint8_t MODE_NOT_POWER_ON = COMMAND_COOL >> MODE_SHIFT;
|
||||
// A mode not listed is sent as off
|
||||
static constexpr IRCode MODES[] PROGMEM = {
|
||||
{climate::CLIMATE_MODE_COOL, COMMAND_COOL >> MODE_SHIFT},
|
||||
{climate::CLIMATE_MODE_DRY, COMMAND_DRY >> MODE_SHIFT},
|
||||
{climate::CLIMATE_MODE_FAN_ONLY, COMMAND_FAN_ONLY >> MODE_SHIFT},
|
||||
{climate::CLIMATE_MODE_HEAT_COOL, COMMAND_AI >> MODE_SHIFT},
|
||||
{climate::CLIMATE_MODE_HEAT, COMMAND_HEAT >> MODE_SHIFT},
|
||||
};
|
||||
// F2 and F4 are only received
|
||||
static constexpr IRCode FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_AUTO, FAN_AUTO}, {climate::CLIMATE_FAN_HIGH, FAN_MAX}, {climate::CLIMATE_FAN_MEDIUM, FAN_MED},
|
||||
{climate::CLIMATE_FAN_LOW, FAN_MIN}, {climate::CLIMATE_FAN_LOW, FAN_F2}, {climate::CLIMATE_FAN_MEDIUM, FAN_F4},
|
||||
};
|
||||
|
||||
void LgIrClimate::transmit_state() {
|
||||
uint32_t remote_state = LG_HEADER;
|
||||
|
||||
@@ -144,27 +165,13 @@ void LgIrClimate::transmit_state() {
|
||||
this->transmit_(remote_state);
|
||||
return;
|
||||
} else { // Mode commands
|
||||
const bool climate_is_off = (this->mode_before_ == climate::CLIMATE_MODE_OFF);
|
||||
switch (this->mode) {
|
||||
case climate::CLIMATE_MODE_COOL:
|
||||
remote_state |= climate_is_off ? COMMAND_ON_COOL : COMMAND_COOL;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_DRY:
|
||||
remote_state |= climate_is_off ? COMMAND_ON_DRY : COMMAND_DRY;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_FAN_ONLY:
|
||||
remote_state |= climate_is_off ? COMMAND_ON_FAN_ONLY : COMMAND_FAN_ONLY;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT_COOL:
|
||||
remote_state |= climate_is_off ? COMMAND_ON_AI : COMMAND_AI;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT:
|
||||
remote_state |= climate_is_off ? COMMAND_ON_HEAT : COMMAND_HEAT;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_OFF:
|
||||
default:
|
||||
remote_state |= CommandSys::HEADER_SYS;
|
||||
remote_state |= CommandSys::COMMAND_OFF;
|
||||
if (const auto entry = find_ir_code(MODES, this->mode, false)) {
|
||||
const bool climate_is_off = (this->mode_before_ == climate::CLIMATE_MODE_OFF);
|
||||
remote_state |= static_cast<uint32_t>(climate_is_off ? entry->code & ~MODE_NOT_POWER_ON : entry->code)
|
||||
<< MODE_SHIFT;
|
||||
} else {
|
||||
remote_state |= CommandSys::HEADER_SYS;
|
||||
remote_state |= CommandSys::COMMAND_OFF;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,21 +182,7 @@ void LgIrClimate::transmit_state() {
|
||||
// Set fan speed
|
||||
if (this->mode !=
|
||||
climate::CLIMATE_MODE_OFF) { // https://github.com/esphome/esphome/pull/10875#issuecomment-5042765948
|
||||
switch (this->fan_mode.value_or(climate::CLIMATE_FAN_ON)) {
|
||||
case climate::CLIMATE_FAN_HIGH:
|
||||
remote_state |= FAN_MAX;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_MEDIUM:
|
||||
remote_state |= FAN_MED;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_LOW:
|
||||
remote_state |= FAN_MIN;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_AUTO:
|
||||
default:
|
||||
remote_state |= FAN_AUTO;
|
||||
break;
|
||||
}
|
||||
remote_state |= to_ir_code(FANS, this->fan_mode.value_or(climate::CLIMATE_FAN_AUTO), FAN_AUTO);
|
||||
}
|
||||
|
||||
uint8_t temp;
|
||||
@@ -294,52 +287,25 @@ bool LgIrClimate::on_receive(remote_base::RemoteReceiveData data) {
|
||||
}
|
||||
this->publish_state();
|
||||
return true;
|
||||
// Following commands also contain fan speed and temperature, so no 'return' in these cases
|
||||
case COMMAND_DRY:
|
||||
case COMMAND_ON_DRY:
|
||||
this->mode = climate::CLIMATE_MODE_DRY;
|
||||
default: {
|
||||
// Mode commands also contain fan speed and temperature, so no 'return' here
|
||||
const uint8_t command = (remote_state & COMMAND_HEADER_MASK) >> MODE_SHIFT;
|
||||
const auto mode = find_ir_code(MODES, command | MODE_NOT_POWER_ON, true);
|
||||
if (!mode.has_value()) {
|
||||
ESP_LOGD(TAG, "Got unknown command! Ignoring!");
|
||||
return false;
|
||||
}
|
||||
this->mode = static_cast<climate::ClimateMode>(mode->value);
|
||||
break;
|
||||
case COMMAND_FAN_ONLY:
|
||||
case COMMAND_ON_FAN_ONLY:
|
||||
this->mode = climate::CLIMATE_MODE_FAN_ONLY;
|
||||
break;
|
||||
case COMMAND_AI:
|
||||
case COMMAND_ON_AI:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT_COOL;
|
||||
break;
|
||||
case COMMAND_HEAT:
|
||||
case COMMAND_ON_HEAT:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT;
|
||||
break;
|
||||
case COMMAND_COOL:
|
||||
case COMMAND_ON_COOL:
|
||||
this->mode = climate::CLIMATE_MODE_COOL;
|
||||
break;
|
||||
default:
|
||||
ESP_LOGD(TAG, "Got unknown command! Ignoring!");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Decode fan speed
|
||||
switch (remote_state & FAN_SPEED_MASK) {
|
||||
case FAN_AUTO:
|
||||
this->fan_mode = climate::CLIMATE_FAN_AUTO;
|
||||
break;
|
||||
case FAN_MIN:
|
||||
case FAN_F2:
|
||||
this->fan_mode = climate::CLIMATE_FAN_LOW;
|
||||
break;
|
||||
case FAN_MED:
|
||||
case FAN_F4:
|
||||
this->fan_mode = climate::CLIMATE_FAN_MEDIUM;
|
||||
break;
|
||||
case FAN_MAX:
|
||||
this->fan_mode = climate::CLIMATE_FAN_HIGH;
|
||||
break;
|
||||
default:
|
||||
ESP_LOGD(TAG, "Got unknown fan speed! Ignoring!");
|
||||
return false;
|
||||
const auto fan = find_ir_code(FANS, remote_state & FAN_SPEED_MASK, true);
|
||||
if (!fan.has_value()) {
|
||||
ESP_LOGD(TAG, "Got unknown fan speed! Ignoring!");
|
||||
return false;
|
||||
}
|
||||
this->fan_mode = static_cast<climate::ClimateFanMode>(fan->value);
|
||||
|
||||
// Keep previous behavior
|
||||
if (this->mode == climate::CLIMATE_MODE_HEAT_COOL && !(this->advanced_commands_support_)) {
|
||||
|
||||
@@ -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,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
|
||||
@@ -17,6 +17,27 @@ static constexpr uint8_t DAIKIN_FRAME_TYPE_INDEX = 4;
|
||||
static constexpr uint8_t DAIKIN_FRAME_HEADER_SIZE = DAIKIN_FRAME_TYPE_INDEX + 1;
|
||||
static constexpr uint8_t DAIKIN_STATE_FRAME_OFFSET = 2 * DAIKIN_COMFORT_FRAME_SIZE;
|
||||
|
||||
using climate_ir::find_ir_code;
|
||||
using climate_ir::IRCode;
|
||||
using climate_ir::to_ir_code;
|
||||
|
||||
// Codes include the ON bit so the OFF entry never matches a running unit; an unlisted received code is ignored
|
||||
static constexpr IRCode MODES[] PROGMEM = {
|
||||
{climate::CLIMATE_MODE_OFF, DAIKIN_MODE_OFF},
|
||||
{climate::CLIMATE_MODE_COOL, DAIKIN_MODE_ON | DAIKIN_MODE_COOL},
|
||||
{climate::CLIMATE_MODE_DRY, DAIKIN_MODE_ON | DAIKIN_MODE_DRY},
|
||||
{climate::CLIMATE_MODE_HEAT, DAIKIN_MODE_ON | DAIKIN_MODE_HEAT},
|
||||
{climate::CLIMATE_MODE_HEAT_COOL, DAIKIN_MODE_ON | DAIKIN_MODE_AUTO},
|
||||
{climate::CLIMATE_MODE_FAN_ONLY, DAIKIN_MODE_ON | DAIKIN_MODE_FAN},
|
||||
};
|
||||
// Fan speeds 2 and 4 are only received
|
||||
static constexpr IRCode FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_AUTO, DAIKIN_FAN_AUTO}, {climate::CLIMATE_FAN_QUIET, DAIKIN_FAN_SILENT},
|
||||
{climate::CLIMATE_FAN_LOW, DAIKIN_FAN_1}, {climate::CLIMATE_FAN_MEDIUM, DAIKIN_FAN_3},
|
||||
{climate::CLIMATE_FAN_HIGH, DAIKIN_FAN_5}, {climate::CLIMATE_FAN_LOW, DAIKIN_FAN_2},
|
||||
{climate::CLIMATE_FAN_HIGH, DAIKIN_FAN_4},
|
||||
};
|
||||
|
||||
void DaikinClimate::setup() {
|
||||
climate_ir::ClimateIR::setup();
|
||||
// A boost preset restored from flash gets its timer too
|
||||
@@ -35,7 +56,7 @@ void DaikinClimate::transmit_state() {
|
||||
0x00, 0x00, 0x00, 0x06, 0x60, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00};
|
||||
|
||||
this->set_presets_(remote_state);
|
||||
remote_state[21] = this->operation_mode_();
|
||||
remote_state[21] = to_ir_code(MODES, this->mode, DAIKIN_MODE_OFF);
|
||||
remote_state[22] = this->temperature_();
|
||||
put_be16(remote_state + 24, this->fan_speed_());
|
||||
|
||||
@@ -67,52 +88,8 @@ void DaikinClimate::transmit_state() {
|
||||
transmit.perform();
|
||||
}
|
||||
|
||||
uint8_t DaikinClimate::operation_mode_() const {
|
||||
uint8_t operating_mode = DAIKIN_MODE_ON;
|
||||
switch (this->mode) {
|
||||
case climate::CLIMATE_MODE_COOL:
|
||||
operating_mode |= DAIKIN_MODE_COOL;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_DRY:
|
||||
operating_mode |= DAIKIN_MODE_DRY;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT:
|
||||
operating_mode |= DAIKIN_MODE_HEAT;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT_COOL:
|
||||
operating_mode |= DAIKIN_MODE_AUTO;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_FAN_ONLY:
|
||||
operating_mode |= DAIKIN_MODE_FAN;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_OFF:
|
||||
default:
|
||||
operating_mode = DAIKIN_MODE_OFF;
|
||||
break;
|
||||
}
|
||||
|
||||
return operating_mode;
|
||||
}
|
||||
|
||||
uint16_t DaikinClimate::fan_speed_() const {
|
||||
uint16_t fan_speed;
|
||||
switch (this->fan_mode.value_or(climate::CLIMATE_FAN_ON)) {
|
||||
case climate::CLIMATE_FAN_QUIET:
|
||||
fan_speed = DAIKIN_FAN_SILENT << 8;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_LOW:
|
||||
fan_speed = DAIKIN_FAN_1 << 8;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_MEDIUM:
|
||||
fan_speed = DAIKIN_FAN_3 << 8;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_HIGH:
|
||||
fan_speed = DAIKIN_FAN_5 << 8;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_AUTO:
|
||||
default:
|
||||
fan_speed = DAIKIN_FAN_AUTO << 8;
|
||||
}
|
||||
uint16_t fan_speed = to_ir_code(FANS, this->fan_mode.value_or(climate::CLIMATE_FAN_AUTO), DAIKIN_FAN_AUTO) << 8;
|
||||
|
||||
// If swing is enabled switch first 4 bits to 1111
|
||||
switch (this->swing_mode) {
|
||||
@@ -189,29 +166,12 @@ bool DaikinClimate::parse_state_frame_(const uint8_t frame[]) {
|
||||
// Temperature is given in degrees celsius * 2
|
||||
// only update for states that use the temperature
|
||||
uint8_t temperature = frame[6];
|
||||
if (mode & DAIKIN_MODE_ON) {
|
||||
switch (mode & 0xF0) {
|
||||
case DAIKIN_MODE_COOL:
|
||||
this->mode = climate::CLIMATE_MODE_COOL;
|
||||
this->target_temperature = static_cast<float>(temperature * 0.5f);
|
||||
break;
|
||||
case DAIKIN_MODE_DRY:
|
||||
this->mode = climate::CLIMATE_MODE_DRY;
|
||||
break;
|
||||
case DAIKIN_MODE_HEAT:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT;
|
||||
this->target_temperature = static_cast<float>(temperature * 0.5f);
|
||||
break;
|
||||
case DAIKIN_MODE_AUTO:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT_COOL;
|
||||
this->target_temperature = static_cast<float>(temperature * 0.5f);
|
||||
break;
|
||||
case DAIKIN_MODE_FAN:
|
||||
this->mode = climate::CLIMATE_MODE_FAN_ONLY;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (!(mode & DAIKIN_MODE_ON)) {
|
||||
this->mode = climate::CLIMATE_MODE_OFF;
|
||||
} else if (const auto entry = find_ir_code(MODES, mode & (0xF0 | DAIKIN_MODE_ON), true)) {
|
||||
this->mode = static_cast<climate::ClimateMode>(entry->value);
|
||||
if (this->mode != climate::CLIMATE_MODE_DRY && this->mode != climate::CLIMATE_MODE_FAN_ONLY)
|
||||
this->target_temperature = static_cast<float>(temperature * 0.5f);
|
||||
}
|
||||
uint8_t fan_mode = frame[8];
|
||||
uint8_t swing_mode = frame[9];
|
||||
@@ -224,25 +184,8 @@ bool DaikinClimate::parse_state_frame_(const uint8_t frame[]) {
|
||||
} else {
|
||||
this->swing_mode = climate::CLIMATE_SWING_OFF;
|
||||
}
|
||||
switch (fan_mode & 0xF0) {
|
||||
case DAIKIN_FAN_1:
|
||||
case DAIKIN_FAN_2:
|
||||
this->fan_mode = climate::CLIMATE_FAN_LOW;
|
||||
break;
|
||||
case DAIKIN_FAN_3:
|
||||
this->fan_mode = climate::CLIMATE_FAN_MEDIUM;
|
||||
break;
|
||||
case DAIKIN_FAN_4:
|
||||
case DAIKIN_FAN_5:
|
||||
this->fan_mode = climate::CLIMATE_FAN_HIGH;
|
||||
break;
|
||||
case DAIKIN_FAN_AUTO:
|
||||
this->fan_mode = climate::CLIMATE_FAN_AUTO;
|
||||
break;
|
||||
case DAIKIN_FAN_SILENT:
|
||||
this->fan_mode = climate::CLIMATE_FAN_QUIET;
|
||||
break;
|
||||
}
|
||||
if (const auto entry = find_ir_code(FANS, fan_mode & 0xF0, true))
|
||||
this->fan_mode = static_cast<climate::ClimateFanMode>(entry->value);
|
||||
|
||||
// Comfort lives in the first frame, recorded as pending until this frame proves the transmission valid
|
||||
// A comfort frame whose own state frame never came must not attach to a later transmission
|
||||
|
||||
@@ -72,7 +72,6 @@ class DaikinClimate final : public climate_ir::ClimateIR {
|
||||
void control(const climate::ClimateCall &call) override;
|
||||
// Transmit via IR the state of this climate controller.
|
||||
void transmit_state() override;
|
||||
uint8_t operation_mode_() const;
|
||||
uint16_t fan_speed_() const;
|
||||
uint8_t temperature_() const;
|
||||
void set_presets_(uint8_t *remote_state) const;
|
||||
|
||||
@@ -10,6 +10,28 @@ namespace esphome::daikin_arc {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "daikin.climate");
|
||||
|
||||
using climate_ir::find_ir_code;
|
||||
using climate_ir::from_ir_code;
|
||||
using climate_ir::IRCode;
|
||||
using climate_ir::to_ir_code;
|
||||
|
||||
// Codes include the ON bit so the OFF entry never matches a running unit; an unlisted received code is ignored
|
||||
static constexpr IRCode MODES[] PROGMEM = {
|
||||
{climate::CLIMATE_MODE_OFF, DAIKIN_MODE_OFF},
|
||||
{climate::CLIMATE_MODE_COOL, DAIKIN_MODE_ON | DAIKIN_MODE_COOL},
|
||||
{climate::CLIMATE_MODE_DRY, DAIKIN_MODE_ON | DAIKIN_MODE_DRY},
|
||||
{climate::CLIMATE_MODE_HEAT, DAIKIN_MODE_ON | DAIKIN_MODE_HEAT},
|
||||
{climate::CLIMATE_MODE_HEAT_COOL, DAIKIN_MODE_ON | DAIKIN_MODE_AUTO},
|
||||
{climate::CLIMATE_MODE_FAN_ONLY, DAIKIN_MODE_ON | DAIKIN_MODE_FAN},
|
||||
};
|
||||
// Fan speeds 2 and 4 and silent are only received
|
||||
static constexpr IRCode FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_AUTO, DAIKIN_FAN_AUTO}, {climate::CLIMATE_FAN_LOW, DAIKIN_FAN_1},
|
||||
{climate::CLIMATE_FAN_MEDIUM, DAIKIN_FAN_3}, {climate::CLIMATE_FAN_HIGH, DAIKIN_FAN_5},
|
||||
{climate::CLIMATE_FAN_LOW, DAIKIN_FAN_2}, {climate::CLIMATE_FAN_LOW, DAIKIN_FAN_SILENT},
|
||||
{climate::CLIMATE_FAN_HIGH, DAIKIN_FAN_4},
|
||||
};
|
||||
|
||||
void DaikinArcClimate::setup() {
|
||||
climate_ir::ClimateIR::setup();
|
||||
|
||||
@@ -82,7 +104,7 @@ void DaikinArcClimate::transmit_state() {
|
||||
/* OF 0x80 */
|
||||
};
|
||||
|
||||
remote_state[5] = this->operation_mode_() | 0x08;
|
||||
remote_state[5] = to_ir_code(MODES, this->mode, DAIKIN_MODE_OFF) | 0x08;
|
||||
remote_state[6] = this->temperature_();
|
||||
remote_state[7] = this->humidity_();
|
||||
if (remote_state[7] != this->last_humidity_ && this->mode != climate::CLIMATE_MODE_OFF) {
|
||||
@@ -126,49 +148,8 @@ void DaikinArcClimate::transmit_state() {
|
||||
transmit.perform();
|
||||
}
|
||||
|
||||
uint8_t DaikinArcClimate::operation_mode_() {
|
||||
uint8_t operating_mode = DAIKIN_MODE_ON;
|
||||
switch (this->mode) {
|
||||
case climate::CLIMATE_MODE_COOL:
|
||||
operating_mode |= DAIKIN_MODE_COOL;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_DRY:
|
||||
operating_mode |= DAIKIN_MODE_DRY;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT:
|
||||
operating_mode |= DAIKIN_MODE_HEAT;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT_COOL:
|
||||
operating_mode |= DAIKIN_MODE_AUTO;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_FAN_ONLY:
|
||||
operating_mode |= DAIKIN_MODE_FAN;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_OFF:
|
||||
default:
|
||||
operating_mode = DAIKIN_MODE_OFF;
|
||||
break;
|
||||
}
|
||||
|
||||
return operating_mode;
|
||||
}
|
||||
|
||||
uint16_t DaikinArcClimate::fan_speed_() {
|
||||
uint16_t fan_speed;
|
||||
switch (this->fan_mode.value_or(climate::CLIMATE_FAN_ON)) {
|
||||
case climate::CLIMATE_FAN_LOW:
|
||||
fan_speed = DAIKIN_FAN_1 << 8;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_MEDIUM:
|
||||
fan_speed = DAIKIN_FAN_3 << 8;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_HIGH:
|
||||
fan_speed = DAIKIN_FAN_5 << 8;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_AUTO:
|
||||
default:
|
||||
fan_speed = DAIKIN_FAN_AUTO << 8;
|
||||
}
|
||||
uint16_t fan_speed = to_ir_code(FANS, this->fan_mode.value_or(climate::CLIMATE_FAN_AUTO), DAIKIN_FAN_AUTO) << 8;
|
||||
|
||||
// If swing is enabled switch first 4 bits to 1111
|
||||
switch (this->swing_mode) {
|
||||
@@ -241,26 +222,10 @@ bool DaikinArcClimate::parse_state_frame_(const uint8_t frame[]) {
|
||||
ESP_LOGD(TAG, "FRAME %s", buf);
|
||||
|
||||
uint8_t mode = frame[5];
|
||||
if (mode & DAIKIN_MODE_ON) {
|
||||
switch (mode & 0xF0) {
|
||||
case DAIKIN_MODE_COOL:
|
||||
this->mode = climate::CLIMATE_MODE_COOL;
|
||||
break;
|
||||
case DAIKIN_MODE_DRY:
|
||||
this->mode = climate::CLIMATE_MODE_DRY;
|
||||
break;
|
||||
case DAIKIN_MODE_HEAT:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT;
|
||||
break;
|
||||
case DAIKIN_MODE_AUTO:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT_COOL;
|
||||
break;
|
||||
case DAIKIN_MODE_FAN:
|
||||
this->mode = climate::CLIMATE_MODE_FAN_ONLY;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (!(mode & DAIKIN_MODE_ON)) {
|
||||
this->mode = climate::CLIMATE_MODE_OFF;
|
||||
} else {
|
||||
this->mode = from_ir_code(MODES, mode & (0xF0 | DAIKIN_MODE_ON), this->mode);
|
||||
}
|
||||
uint8_t temperature = frame[6];
|
||||
if (!(temperature & 0xC0)) {
|
||||
@@ -279,23 +244,8 @@ bool DaikinArcClimate::parse_state_frame_(const uint8_t frame[]) {
|
||||
} else {
|
||||
this->swing_mode = climate::CLIMATE_SWING_OFF;
|
||||
}
|
||||
switch (fan_mode & 0xF0) {
|
||||
case DAIKIN_FAN_1:
|
||||
case DAIKIN_FAN_2:
|
||||
case DAIKIN_FAN_SILENT:
|
||||
this->fan_mode = climate::CLIMATE_FAN_LOW;
|
||||
break;
|
||||
case DAIKIN_FAN_3:
|
||||
this->fan_mode = climate::CLIMATE_FAN_MEDIUM;
|
||||
break;
|
||||
case DAIKIN_FAN_4:
|
||||
case DAIKIN_FAN_5:
|
||||
this->fan_mode = climate::CLIMATE_FAN_HIGH;
|
||||
break;
|
||||
case DAIKIN_FAN_AUTO:
|
||||
this->fan_mode = climate::CLIMATE_FAN_AUTO;
|
||||
break;
|
||||
}
|
||||
if (const auto entry = find_ir_code(FANS, fan_mode & 0xF0, true))
|
||||
this->fan_mode = static_cast<climate::ClimateFanMode>(entry->value);
|
||||
/*
|
||||
05 0 [1:3]MODE 1 [OFF TMR] [ON TMR] Power
|
||||
06-07 TEMP
|
||||
|
||||
@@ -64,7 +64,6 @@ class DaikinArcClimate final : public climate_ir::ClimateIR {
|
||||
void transmit_query_();
|
||||
void transmit_state() override;
|
||||
climate::ClimateTraits traits() override;
|
||||
uint8_t operation_mode_();
|
||||
uint16_t fan_speed_();
|
||||
uint8_t temperature_();
|
||||
uint8_t humidity_();
|
||||
|
||||
@@ -12,6 +12,26 @@ static constexpr uint8_t DAIKIN_BRC_HEADER_BYTE2 = 0x17;
|
||||
static constexpr uint8_t DAIKIN_BRC_HEADER_BYTE3 = 0x18;
|
||||
static constexpr uint8_t DAIKIN_BRC_FRAME_TYPE_STATE = 0x00;
|
||||
|
||||
using climate_ir::find_ir_code;
|
||||
using climate_ir::from_ir_code;
|
||||
using climate_ir::IRCode;
|
||||
using climate_ir::to_ir_code;
|
||||
|
||||
// Codes include the ON bit so the OFF entry never matches a running unit; an unlisted received code is ignored
|
||||
static constexpr IRCode MODES[] PROGMEM = {
|
||||
{climate::CLIMATE_MODE_OFF, DAIKIN_BRC_MODE_OFF},
|
||||
{climate::CLIMATE_MODE_COOL, DAIKIN_BRC_MODE_ON | DAIKIN_BRC_MODE_COOL},
|
||||
{climate::CLIMATE_MODE_DRY, DAIKIN_BRC_MODE_ON | DAIKIN_BRC_MODE_DRY},
|
||||
{climate::CLIMATE_MODE_HEAT, DAIKIN_BRC_MODE_ON | DAIKIN_BRC_MODE_HEAT},
|
||||
{climate::CLIMATE_MODE_HEAT_COOL, DAIKIN_BRC_MODE_ON | DAIKIN_BRC_MODE_AUTO},
|
||||
{climate::CLIMATE_MODE_FAN_ONLY, DAIKIN_BRC_MODE_ON | DAIKIN_BRC_MODE_FAN},
|
||||
};
|
||||
static constexpr IRCode FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_LOW, DAIKIN_BRC_FAN_1},
|
||||
{climate::CLIMATE_FAN_MEDIUM, DAIKIN_BRC_FAN_2},
|
||||
{climate::CLIMATE_FAN_HIGH, DAIKIN_BRC_FAN_3},
|
||||
};
|
||||
|
||||
void DaikinBrcClimate::control(const climate::ClimateCall &call) {
|
||||
this->mode_button_ = 0x00;
|
||||
if (call.get_mode().has_value()) {
|
||||
@@ -33,7 +53,7 @@ void DaikinBrcClimate::transmit_state() {
|
||||
|
||||
remote_state[12] = this->alt_mode_();
|
||||
remote_state[13] = this->mode_button_;
|
||||
remote_state[14] = this->operation_mode_();
|
||||
remote_state[14] = to_ir_code(MODES, this->mode, DAIKIN_BRC_MODE_OFF);
|
||||
remote_state[17] = this->temperature_();
|
||||
remote_state[18] = this->fan_speed_swing_();
|
||||
|
||||
@@ -82,48 +102,8 @@ uint8_t DaikinBrcClimate::alt_mode_() {
|
||||
return alt_mode;
|
||||
}
|
||||
|
||||
uint8_t DaikinBrcClimate::operation_mode_() {
|
||||
uint8_t operating_mode = DAIKIN_BRC_MODE_ON;
|
||||
switch (this->mode) {
|
||||
case climate::CLIMATE_MODE_COOL:
|
||||
operating_mode |= DAIKIN_BRC_MODE_COOL;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_DRY:
|
||||
operating_mode |= DAIKIN_BRC_MODE_DRY;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT:
|
||||
operating_mode |= DAIKIN_BRC_MODE_HEAT;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT_COOL:
|
||||
operating_mode |= DAIKIN_BRC_MODE_AUTO;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_FAN_ONLY:
|
||||
operating_mode |= DAIKIN_BRC_MODE_FAN;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_OFF:
|
||||
default:
|
||||
operating_mode = DAIKIN_BRC_MODE_OFF;
|
||||
break;
|
||||
}
|
||||
|
||||
return operating_mode;
|
||||
}
|
||||
|
||||
uint8_t DaikinBrcClimate::fan_speed_swing_() {
|
||||
uint16_t fan_speed;
|
||||
switch (this->fan_mode.value_or(climate::CLIMATE_FAN_ON)) {
|
||||
case climate::CLIMATE_FAN_LOW:
|
||||
fan_speed = DAIKIN_BRC_FAN_1;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_MEDIUM:
|
||||
fan_speed = DAIKIN_BRC_FAN_2;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_HIGH:
|
||||
fan_speed = DAIKIN_BRC_FAN_3;
|
||||
break;
|
||||
default:
|
||||
fan_speed = DAIKIN_BRC_FAN_1;
|
||||
}
|
||||
uint16_t fan_speed = to_ir_code(FANS, this->fan_mode.value_or(climate::CLIMATE_FAN_LOW), DAIKIN_BRC_FAN_1);
|
||||
|
||||
// If swing is enabled switch first 4 bits to 1111
|
||||
switch (this->swing_mode) {
|
||||
@@ -168,26 +148,10 @@ bool DaikinBrcClimate::parse_state_frame_(const uint8_t frame[]) {
|
||||
}
|
||||
|
||||
uint8_t mode = frame[7];
|
||||
if (mode & DAIKIN_BRC_MODE_ON) {
|
||||
switch (mode & 0xF0) {
|
||||
case DAIKIN_BRC_MODE_COOL:
|
||||
this->mode = climate::CLIMATE_MODE_COOL;
|
||||
break;
|
||||
case DAIKIN_BRC_MODE_DRY:
|
||||
this->mode = climate::CLIMATE_MODE_DRY;
|
||||
break;
|
||||
case DAIKIN_BRC_MODE_HEAT:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT;
|
||||
break;
|
||||
case DAIKIN_BRC_MODE_AUTO:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT_COOL;
|
||||
break;
|
||||
case DAIKIN_BRC_MODE_FAN:
|
||||
this->mode = climate::CLIMATE_MODE_FAN_ONLY;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (!(mode & DAIKIN_BRC_MODE_ON)) {
|
||||
this->mode = climate::CLIMATE_MODE_OFF;
|
||||
} else {
|
||||
this->mode = from_ir_code(MODES, mode & (0xF0 | DAIKIN_BRC_MODE_ON), this->mode);
|
||||
}
|
||||
|
||||
uint8_t temperature = frame[10];
|
||||
@@ -211,17 +175,8 @@ bool DaikinBrcClimate::parse_state_frame_(const uint8_t frame[]) {
|
||||
break;
|
||||
}
|
||||
|
||||
switch (fan_mode & 0xF0) {
|
||||
case DAIKIN_BRC_FAN_1:
|
||||
this->fan_mode = climate::CLIMATE_FAN_LOW;
|
||||
break;
|
||||
case DAIKIN_BRC_FAN_2:
|
||||
this->fan_mode = climate::CLIMATE_FAN_MEDIUM;
|
||||
break;
|
||||
case DAIKIN_BRC_FAN_3:
|
||||
this->fan_mode = climate::CLIMATE_FAN_HIGH;
|
||||
break;
|
||||
}
|
||||
if (const auto entry = find_ir_code(FANS, fan_mode & 0xF0, true))
|
||||
this->fan_mode = static_cast<climate::ClimateFanMode>(entry->value);
|
||||
this->publish_state();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -70,7 +70,6 @@ class DaikinBrcClimate final : public climate_ir::ClimateIR {
|
||||
// Transmit via IR the state of this climate controller.
|
||||
void transmit_state() override;
|
||||
uint8_t alt_mode_();
|
||||
uint8_t operation_mode_();
|
||||
uint8_t fan_speed_swing_();
|
||||
uint8_t temperature_();
|
||||
// Handle received IR Buffer
|
||||
|
||||
@@ -6,12 +6,33 @@ namespace esphome::delonghi {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "delonghi.climate");
|
||||
|
||||
using climate_ir::find_ir_code;
|
||||
using climate_ir::from_ir_code;
|
||||
using climate_ir::IRCode;
|
||||
using climate_ir::to_ir_code;
|
||||
|
||||
// A received code that is not listed is ignored
|
||||
static constexpr IRCode MODES[] PROGMEM = {
|
||||
{climate::CLIMATE_MODE_OFF, DELONGHI_MODE_OFF},
|
||||
{climate::CLIMATE_MODE_COOL, DELONGHI_MODE_ON | DELONGHI_MODE_COOL},
|
||||
{climate::CLIMATE_MODE_DRY, DELONGHI_MODE_ON | DELONGHI_MODE_DRY},
|
||||
{climate::CLIMATE_MODE_HEAT, DELONGHI_MODE_ON | DELONGHI_MODE_HEAT},
|
||||
{climate::CLIMATE_MODE_HEAT_COOL, DELONGHI_MODE_ON | DELONGHI_MODE_AUTO},
|
||||
{climate::CLIMATE_MODE_FAN_ONLY, DELONGHI_MODE_ON | DELONGHI_MODE_FAN},
|
||||
};
|
||||
static constexpr IRCode FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_AUTO, DELONGHI_FAN_AUTO},
|
||||
{climate::CLIMATE_FAN_LOW, DELONGHI_FAN_LOW},
|
||||
{climate::CLIMATE_FAN_MEDIUM, DELONGHI_FAN_MEDIUM},
|
||||
{climate::CLIMATE_FAN_HIGH, DELONGHI_FAN_HIGH},
|
||||
};
|
||||
|
||||
void DelonghiClimate::transmit_state() {
|
||||
uint8_t remote_state[DELONGHI_STATE_FRAME_SIZE] = {0};
|
||||
remote_state[0] = DELONGHI_ADDRESS;
|
||||
remote_state[1] = this->temperature_();
|
||||
remote_state[1] |= (this->fan_speed_()) << 5;
|
||||
remote_state[2] = this->operation_mode_();
|
||||
remote_state[1] |= to_ir_code(FANS, this->fan_mode.value_or(climate::CLIMATE_FAN_AUTO), DELONGHI_FAN_AUTO) << 5;
|
||||
remote_state[2] = to_ir_code(MODES, this->mode, DELONGHI_MODE_OFF);
|
||||
// Calculate checksum
|
||||
for (int i = 0; i < DELONGHI_STATE_FRAME_SIZE - 1; i++) {
|
||||
remote_state[DELONGHI_STATE_FRAME_SIZE - 1] += remote_state[i];
|
||||
@@ -30,51 +51,6 @@ void DelonghiClimate::transmit_state() {
|
||||
transmit.perform();
|
||||
}
|
||||
|
||||
uint8_t DelonghiClimate::operation_mode_() {
|
||||
uint8_t operating_mode = DELONGHI_MODE_ON;
|
||||
switch (this->mode) {
|
||||
case climate::CLIMATE_MODE_COOL:
|
||||
operating_mode |= DELONGHI_MODE_COOL;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_DRY:
|
||||
operating_mode |= DELONGHI_MODE_DRY;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT:
|
||||
operating_mode |= DELONGHI_MODE_HEAT;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT_COOL:
|
||||
operating_mode |= DELONGHI_MODE_AUTO;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_FAN_ONLY:
|
||||
operating_mode |= DELONGHI_MODE_FAN;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_OFF:
|
||||
default:
|
||||
operating_mode = DELONGHI_MODE_OFF;
|
||||
break;
|
||||
}
|
||||
return operating_mode;
|
||||
}
|
||||
|
||||
uint16_t DelonghiClimate::fan_speed_() {
|
||||
uint16_t fan_speed;
|
||||
switch (this->fan_mode.value_or(climate::CLIMATE_FAN_ON)) {
|
||||
case climate::CLIMATE_FAN_LOW:
|
||||
fan_speed = DELONGHI_FAN_LOW;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_MEDIUM:
|
||||
fan_speed = DELONGHI_FAN_MEDIUM;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_HIGH:
|
||||
fan_speed = DELONGHI_FAN_HIGH;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_AUTO:
|
||||
default:
|
||||
fan_speed = DELONGHI_FAN_AUTO;
|
||||
}
|
||||
return fan_speed;
|
||||
}
|
||||
|
||||
uint8_t DelonghiClimate::temperature_() {
|
||||
// Force special temperatures depending on the mode
|
||||
uint8_t temperature = 0b0001;
|
||||
@@ -102,26 +78,10 @@ bool DelonghiClimate::parse_state_frame_(const uint8_t frame[]) {
|
||||
return false;
|
||||
}
|
||||
uint8_t mode = frame[2] & 0x0F;
|
||||
if (mode & DELONGHI_MODE_ON) {
|
||||
switch (mode & 0x0E) {
|
||||
case DELONGHI_MODE_COOL:
|
||||
this->mode = climate::CLIMATE_MODE_COOL;
|
||||
break;
|
||||
case DELONGHI_MODE_DRY:
|
||||
this->mode = climate::CLIMATE_MODE_DRY;
|
||||
break;
|
||||
case DELONGHI_MODE_HEAT:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT;
|
||||
break;
|
||||
case DELONGHI_MODE_AUTO:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT_COOL;
|
||||
break;
|
||||
case DELONGHI_MODE_FAN:
|
||||
this->mode = climate::CLIMATE_MODE_FAN_ONLY;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (!(mode & DELONGHI_MODE_ON)) {
|
||||
this->mode = climate::CLIMATE_MODE_OFF;
|
||||
} else {
|
||||
this->mode = from_ir_code(MODES, mode, this->mode);
|
||||
}
|
||||
uint8_t temperature = frame[1] & 0x0F;
|
||||
if (this->mode == climate::CLIMATE_MODE_HEAT) {
|
||||
@@ -129,23 +89,8 @@ bool DelonghiClimate::parse_state_frame_(const uint8_t frame[]) {
|
||||
} else {
|
||||
this->target_temperature = temperature + DELONGHI_TEMP_OFFSET_COOL;
|
||||
}
|
||||
uint8_t fan_mode = frame[1] >> 5;
|
||||
switch (fan_mode) {
|
||||
case DELONGHI_FAN_LOW:
|
||||
this->fan_mode = climate::CLIMATE_FAN_LOW;
|
||||
break;
|
||||
case DELONGHI_FAN_MEDIUM:
|
||||
this->fan_mode = climate::CLIMATE_FAN_MEDIUM;
|
||||
break;
|
||||
case DELONGHI_FAN_HIGH:
|
||||
this->fan_mode = climate::CLIMATE_FAN_HIGH;
|
||||
break;
|
||||
case DELONGHI_FAN_AUTO:
|
||||
this->fan_mode = climate::CLIMATE_FAN_AUTO;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (const auto entry = find_ir_code(FANS, frame[1] >> 5, true))
|
||||
this->fan_mode = static_cast<climate::ClimateFanMode>(entry->value);
|
||||
this->publish_state();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -51,8 +51,6 @@ class DelonghiClimate final : public climate_ir::ClimateIR {
|
||||
protected:
|
||||
// Transmit via IR the state of this climate controller.
|
||||
void transmit_state() override;
|
||||
uint8_t operation_mode_();
|
||||
uint16_t fan_speed_();
|
||||
uint8_t temperature_();
|
||||
// Handle received IR Buffer
|
||||
bool on_receive(remote_base::RemoteReceiveData data) override;
|
||||
|
||||
@@ -50,34 +50,25 @@ static constexpr uint8_t STATE_TEMPLATE[STATE_MESSAGE_LENGTH] PROGMEM = {
|
||||
static constexpr uint8_t OFF_FRAME[STATE_MESSAGE_LENGTH_UTIL] PROGMEM = {0x00, 0x08, 0x08, BYTE3_POWER_OFF,
|
||||
255 - BYTE3_POWER_OFF};
|
||||
|
||||
struct Code {
|
||||
uint8_t value; // a climate enum, all of which are uint8_t
|
||||
uint8_t code;
|
||||
};
|
||||
static constexpr Code MODES[] PROGMEM = {
|
||||
using climate_ir::find_ir_code;
|
||||
using climate_ir::from_ir_code;
|
||||
using climate_ir::IRCode;
|
||||
using climate_ir::to_ir_code;
|
||||
|
||||
// A received mode that is not listed is ignored
|
||||
static constexpr IRCode MODES[] PROGMEM = {
|
||||
{climate::CLIMATE_MODE_HEAT_COOL, BYTE7_MODE_AUTO},
|
||||
{climate::CLIMATE_MODE_COOL, 0x80},
|
||||
{climate::CLIMATE_MODE_DRY, 0x40},
|
||||
{climate::CLIMATE_MODE_FAN_ONLY, 0xC0},
|
||||
{climate::CLIMATE_MODE_HEAT, 0x20},
|
||||
};
|
||||
static constexpr Code FANS[] PROGMEM = {
|
||||
static constexpr IRCode FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_AUTO, BYTE8_FAN_AUTO}, {climate::CLIMATE_FAN_HIGH, 0x80},
|
||||
{climate::CLIMATE_FAN_MEDIUM, 0x40}, {climate::CLIMATE_FAN_LOW, 0xC0},
|
||||
{climate::CLIMATE_FAN_QUIET, 0x20},
|
||||
};
|
||||
|
||||
// The entry whose value (or code) matches key. Entries are copied out of PROGMEM.
|
||||
template<size_t N> static optional<Code> find_entry(const Code (&table)[N], uint8_t key, bool match_code) {
|
||||
for (const Code &slot : table) {
|
||||
Code entry;
|
||||
progmem_memcpy(&entry, &slot, sizeof(entry));
|
||||
if ((match_code ? entry.code : entry.value) == key)
|
||||
return entry;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
// The temperature code is the 4-bit reversal of (F - TEMP_MIN) / TEMP_STEP; the mapping is its own inverse.
|
||||
static uint8_t reverse_nibble(uint8_t value) { return reverse_bits(value) >> 4; }
|
||||
|
||||
@@ -151,14 +142,11 @@ void FriedrichClimate::transmit_state() {
|
||||
temperature += temperature % 2;
|
||||
this->target_temperature = temperature;
|
||||
|
||||
const auto mode = find_entry(MODES, this->mode, false);
|
||||
const auto fan = find_entry(FANS, this->fan_mode.value_or(climate::CLIMATE_FAN_AUTO), false);
|
||||
|
||||
uint8_t frame[STATE_MESSAGE_LENGTH];
|
||||
progmem_memcpy(frame, STATE_TEMPLATE, sizeof(frame));
|
||||
frame[6] |= reverse_nibble((temperature - TEMP_MIN) / TEMP_STEP);
|
||||
frame[7] = mode.has_value() ? mode->code : BYTE7_MODE_AUTO;
|
||||
frame[8] = fan.has_value() ? fan->code : BYTE8_FAN_AUTO;
|
||||
frame[7] = to_ir_code(MODES, this->mode, BYTE7_MODE_AUTO);
|
||||
frame[8] = to_ir_code(FANS, this->fan_mode.value_or(climate::CLIMATE_FAN_AUTO), BYTE8_FAN_AUTO);
|
||||
if (this->swing_mode != climate::CLIMATE_SWING_OFF)
|
||||
frame[8] |= BYTE8_FAN_SWING;
|
||||
frame[STATE_MESSAGE_LENGTH - 1] = checksum_state(frame);
|
||||
@@ -209,7 +197,7 @@ bool FriedrichClimate::on_receive(remote_base::RemoteReceiveData src) {
|
||||
return false;
|
||||
|
||||
// Ignore frames with a mode this component does not expose (e.g. MIN_HEAT, COIL_DRY)
|
||||
const auto mode = find_entry(MODES, d[7], true);
|
||||
const auto mode = find_ir_code(MODES, d[7], true);
|
||||
if (!mode.has_value()) {
|
||||
ESP_LOGV(TAG, "Ignoring unknown mode 0x%02X", d[7]);
|
||||
return false;
|
||||
@@ -224,8 +212,7 @@ bool FriedrichClimate::on_receive(remote_base::RemoteReceiveData src) {
|
||||
this->target_temperature = TEMP_MIN + temp_index * TEMP_STEP;
|
||||
|
||||
this->swing_mode = (d[8] & BYTE8_FAN_SWING) ? climate::CLIMATE_SWING_VERTICAL : climate::CLIMATE_SWING_OFF;
|
||||
const auto fan = find_entry(FANS, d[8] & ~BYTE8_FAN_SWING, true);
|
||||
this->fan_mode = fan.has_value() ? static_cast<climate::ClimateFanMode>(fan->value) : climate::CLIMATE_FAN_AUTO;
|
||||
this->fan_mode = from_ir_code(FANS, d[8] & ~BYTE8_FAN_SWING, climate::CLIMATE_FAN_AUTO);
|
||||
|
||||
this->publish_state();
|
||||
return true;
|
||||
|
||||
@@ -7,6 +7,26 @@ namespace esphome::hitachi_ac344 {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "climate.hitachi_ac344");
|
||||
|
||||
using climate_ir::find_ir_code;
|
||||
using climate_ir::from_ir_code;
|
||||
using climate_ir::IRCode;
|
||||
using climate_ir::to_ir_code;
|
||||
|
||||
// A received code that is not listed is ignored
|
||||
static constexpr IRCode MODES[] PROGMEM = {
|
||||
{climate::CLIMATE_MODE_COOL, HITACHI_AC344_MODE_COOL},
|
||||
{climate::CLIMATE_MODE_DRY, HITACHI_AC344_MODE_DRY},
|
||||
{climate::CLIMATE_MODE_HEAT, HITACHI_AC344_MODE_HEAT},
|
||||
{climate::CLIMATE_MODE_HEAT_COOL, HITACHI_AC344_MODE_AUTO},
|
||||
{climate::CLIMATE_MODE_FAN_ONLY, HITACHI_AC344_MODE_FAN},
|
||||
};
|
||||
// The max speed is only received
|
||||
static constexpr IRCode FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_AUTO, HITACHI_AC344_FAN_AUTO}, {climate::CLIMATE_FAN_QUIET, HITACHI_AC344_FAN_MIN},
|
||||
{climate::CLIMATE_FAN_LOW, HITACHI_AC344_FAN_LOW}, {climate::CLIMATE_FAN_MEDIUM, HITACHI_AC344_FAN_MEDIUM},
|
||||
{climate::CLIMATE_FAN_HIGH, HITACHI_AC344_FAN_HIGH}, {climate::CLIMATE_FAN_HIGH, HITACHI_AC344_FAN_MAX},
|
||||
};
|
||||
|
||||
void set_bits(uint8_t *const dst, const uint8_t offset, const uint8_t nbits, const uint8_t data) {
|
||||
if (offset >= 8 || !nbits)
|
||||
return; // Short circuit as it won't change.
|
||||
@@ -166,49 +186,17 @@ void HitachiClimate::setup() {
|
||||
void HitachiClimate::transmit_state() { this->transmit_state_(HITACHI_AC344_BUTTON_POWER); }
|
||||
|
||||
void HitachiClimate::transmit_state_(uint8_t button) {
|
||||
switch (this->mode) {
|
||||
case climate::CLIMATE_MODE_COOL:
|
||||
set_mode_(HITACHI_AC344_MODE_COOL);
|
||||
break;
|
||||
case climate::CLIMATE_MODE_DRY:
|
||||
set_mode_(HITACHI_AC344_MODE_DRY);
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT:
|
||||
set_mode_(HITACHI_AC344_MODE_HEAT);
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT_COOL:
|
||||
set_mode_(HITACHI_AC344_MODE_AUTO);
|
||||
break;
|
||||
case climate::CLIMATE_MODE_FAN_ONLY:
|
||||
set_mode_(HITACHI_AC344_MODE_FAN);
|
||||
break;
|
||||
case climate::CLIMATE_MODE_OFF:
|
||||
set_power_(false);
|
||||
break;
|
||||
default:
|
||||
ESP_LOGW(TAG, "Unsupported mode: %s", LOG_STR_ARG(climate_mode_to_string(this->mode)));
|
||||
if (const auto entry = find_ir_code(MODES, this->mode, false)) {
|
||||
set_mode_(entry->code);
|
||||
} else if (this->mode == climate::CLIMATE_MODE_OFF) {
|
||||
set_power_(false);
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Unsupported mode: %s", LOG_STR_ARG(climate_mode_to_string(this->mode)));
|
||||
}
|
||||
|
||||
set_temp_(static_cast<uint8_t>(this->target_temperature));
|
||||
|
||||
switch (this->fan_mode.value_or(climate::CLIMATE_FAN_ON)) {
|
||||
case climate::CLIMATE_FAN_QUIET:
|
||||
set_fan_(HITACHI_AC344_FAN_MIN);
|
||||
break;
|
||||
case climate::CLIMATE_FAN_LOW:
|
||||
set_fan_(HITACHI_AC344_FAN_LOW);
|
||||
break;
|
||||
case climate::CLIMATE_FAN_MEDIUM:
|
||||
set_fan_(HITACHI_AC344_FAN_MEDIUM);
|
||||
break;
|
||||
case climate::CLIMATE_FAN_HIGH:
|
||||
set_fan_(HITACHI_AC344_FAN_HIGH);
|
||||
break;
|
||||
case climate::CLIMATE_FAN_ON:
|
||||
case climate::CLIMATE_FAN_AUTO:
|
||||
default:
|
||||
set_fan_(HITACHI_AC344_FAN_AUTO);
|
||||
}
|
||||
set_fan_(to_ir_code(FANS, this->fan_mode.value_or(climate::CLIMATE_FAN_AUTO), HITACHI_AC344_FAN_AUTO));
|
||||
|
||||
const bool swing_v = swing_vertical(this->swing_mode);
|
||||
const bool swing_h =
|
||||
@@ -254,28 +242,10 @@ bool HitachiClimate::parse_mode_(const uint8_t remote_state[]) {
|
||||
ESP_LOGV(TAG, "Power: %02X %02X", remote_state[HITACHI_AC344_POWER_BYTE], power);
|
||||
uint8_t mode = remote_state[HITACHI_AC344_MODE_BYTE] & 0xF;
|
||||
ESP_LOGV(TAG, "Mode: %02X %02X", remote_state[HITACHI_AC344_MODE_BYTE], mode);
|
||||
if (power == HITACHI_AC344_POWER_ON) {
|
||||
switch (mode) {
|
||||
case HITACHI_AC344_MODE_COOL:
|
||||
this->mode = climate::CLIMATE_MODE_COOL;
|
||||
break;
|
||||
case HITACHI_AC344_MODE_DRY:
|
||||
this->mode = climate::CLIMATE_MODE_DRY;
|
||||
break;
|
||||
case HITACHI_AC344_MODE_HEAT:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT;
|
||||
break;
|
||||
case HITACHI_AC344_MODE_AUTO:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT_COOL;
|
||||
break;
|
||||
case HITACHI_AC344_MODE_FAN:
|
||||
this->mode = climate::CLIMATE_MODE_FAN_ONLY;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (power != HITACHI_AC344_POWER_ON) {
|
||||
this->mode = climate::CLIMATE_MODE_OFF;
|
||||
} else {
|
||||
this->mode = from_ir_code(MODES, mode, this->mode);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -292,26 +262,8 @@ bool HitachiClimate::parse_temperature_(const uint8_t remote_state[]) {
|
||||
bool HitachiClimate::parse_fan_(const uint8_t remote_state[]) {
|
||||
uint8_t fan_mode = remote_state[HITACHI_AC344_FAN_BYTE] >> 4 & 0xF;
|
||||
ESP_LOGV(TAG, "Fan: %02X %02X", remote_state[HITACHI_AC344_FAN_BYTE], fan_mode);
|
||||
switch (fan_mode) {
|
||||
case HITACHI_AC344_FAN_MIN:
|
||||
this->fan_mode = climate::CLIMATE_FAN_QUIET;
|
||||
break;
|
||||
case HITACHI_AC344_FAN_LOW:
|
||||
this->fan_mode = climate::CLIMATE_FAN_LOW;
|
||||
break;
|
||||
case HITACHI_AC344_FAN_MEDIUM:
|
||||
this->fan_mode = climate::CLIMATE_FAN_MEDIUM;
|
||||
break;
|
||||
case HITACHI_AC344_FAN_HIGH:
|
||||
case HITACHI_AC344_FAN_MAX:
|
||||
this->fan_mode = climate::CLIMATE_FAN_HIGH;
|
||||
break;
|
||||
case HITACHI_AC344_FAN_AUTO:
|
||||
this->fan_mode = climate::CLIMATE_FAN_AUTO;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (const auto entry = find_ir_code(FANS, fan_mode, true))
|
||||
this->fan_mode = static_cast<climate::ClimateFanMode>(entry->value);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,26 @@ namespace esphome::hitachi_ac424 {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "climate.hitachi_ac424");
|
||||
|
||||
using climate_ir::find_ir_code;
|
||||
using climate_ir::from_ir_code;
|
||||
using climate_ir::IRCode;
|
||||
using climate_ir::to_ir_code;
|
||||
|
||||
// A received code that is not listed is ignored
|
||||
static constexpr IRCode MODES[] PROGMEM = {
|
||||
{climate::CLIMATE_MODE_COOL, HITACHI_AC424_MODE_COOL},
|
||||
{climate::CLIMATE_MODE_DRY, HITACHI_AC424_MODE_DRY},
|
||||
{climate::CLIMATE_MODE_HEAT, HITACHI_AC424_MODE_HEAT},
|
||||
{climate::CLIMATE_MODE_HEAT_COOL, HITACHI_AC424_MODE_AUTO},
|
||||
{climate::CLIMATE_MODE_FAN_ONLY, HITACHI_AC424_MODE_FAN},
|
||||
};
|
||||
// The min and max speeds are only received
|
||||
static constexpr IRCode FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_AUTO, HITACHI_AC424_FAN_AUTO}, {climate::CLIMATE_FAN_LOW, HITACHI_AC424_FAN_LOW},
|
||||
{climate::CLIMATE_FAN_MEDIUM, HITACHI_AC424_FAN_MEDIUM}, {climate::CLIMATE_FAN_HIGH, HITACHI_AC424_FAN_HIGH},
|
||||
{climate::CLIMATE_FAN_HIGH, HITACHI_AC424_FAN_MAX}, {climate::CLIMATE_FAN_LOW, HITACHI_AC424_FAN_MIN},
|
||||
};
|
||||
|
||||
void set_bits(uint8_t *const dst, const uint8_t offset, const uint8_t nbits, const uint8_t data) {
|
||||
if (offset >= 8 || !nbits)
|
||||
return; // Short circuit as it won't change.
|
||||
@@ -142,46 +162,17 @@ uint8_t HitachiClimate::get_button_() { return remote_state_[HITACHI_AC424_BUTTO
|
||||
void HitachiClimate::set_button_(uint8_t button) { remote_state_[HITACHI_AC424_BUTTON_BYTE] = button; }
|
||||
|
||||
void HitachiClimate::transmit_state() {
|
||||
switch (this->mode) {
|
||||
case climate::CLIMATE_MODE_COOL:
|
||||
set_mode_(HITACHI_AC424_MODE_COOL);
|
||||
break;
|
||||
case climate::CLIMATE_MODE_DRY:
|
||||
set_mode_(HITACHI_AC424_MODE_DRY);
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT:
|
||||
set_mode_(HITACHI_AC424_MODE_HEAT);
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT_COOL:
|
||||
set_mode_(HITACHI_AC424_MODE_AUTO);
|
||||
break;
|
||||
case climate::CLIMATE_MODE_FAN_ONLY:
|
||||
set_mode_(HITACHI_AC424_MODE_FAN);
|
||||
break;
|
||||
case climate::CLIMATE_MODE_OFF:
|
||||
set_power_(false);
|
||||
break;
|
||||
default:
|
||||
ESP_LOGW(TAG, "Unsupported mode: %s", LOG_STR_ARG(climate_mode_to_string(this->mode)));
|
||||
if (const auto entry = find_ir_code(MODES, this->mode, false)) {
|
||||
set_mode_(entry->code);
|
||||
} else if (this->mode == climate::CLIMATE_MODE_OFF) {
|
||||
set_power_(false);
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Unsupported mode: %s", LOG_STR_ARG(climate_mode_to_string(this->mode)));
|
||||
}
|
||||
|
||||
set_temp_(static_cast<uint8_t>(this->target_temperature));
|
||||
|
||||
switch (this->fan_mode.value_or(climate::CLIMATE_FAN_ON)) {
|
||||
case climate::CLIMATE_FAN_LOW:
|
||||
set_fan_(HITACHI_AC424_FAN_LOW);
|
||||
break;
|
||||
case climate::CLIMATE_FAN_MEDIUM:
|
||||
set_fan_(HITACHI_AC424_FAN_MEDIUM);
|
||||
break;
|
||||
case climate::CLIMATE_FAN_HIGH:
|
||||
set_fan_(HITACHI_AC424_FAN_HIGH);
|
||||
break;
|
||||
case climate::CLIMATE_FAN_ON:
|
||||
case climate::CLIMATE_FAN_AUTO:
|
||||
default:
|
||||
set_fan_(HITACHI_AC424_FAN_AUTO);
|
||||
}
|
||||
set_fan_(to_ir_code(FANS, this->fan_mode.value_or(climate::CLIMATE_FAN_AUTO), HITACHI_AC424_FAN_AUTO));
|
||||
|
||||
switch (this->swing_mode) {
|
||||
case climate::CLIMATE_SWING_BOTH:
|
||||
@@ -230,28 +221,10 @@ bool HitachiClimate::parse_mode_(const uint8_t remote_state[]) {
|
||||
ESP_LOGV(TAG, "Power: %02X %02X", remote_state[HITACHI_AC424_POWER_BYTE], power);
|
||||
uint8_t mode = remote_state[HITACHI_AC424_MODE_BYTE] & 0xF;
|
||||
ESP_LOGV(TAG, "Mode: %02X %02X", remote_state[HITACHI_AC424_MODE_BYTE], mode);
|
||||
if (power == HITACHI_AC424_POWER_ON) {
|
||||
switch (mode) {
|
||||
case HITACHI_AC424_MODE_COOL:
|
||||
this->mode = climate::CLIMATE_MODE_COOL;
|
||||
break;
|
||||
case HITACHI_AC424_MODE_DRY:
|
||||
this->mode = climate::CLIMATE_MODE_DRY;
|
||||
break;
|
||||
case HITACHI_AC424_MODE_HEAT:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT;
|
||||
break;
|
||||
case HITACHI_AC424_MODE_AUTO:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT_COOL;
|
||||
break;
|
||||
case HITACHI_AC424_MODE_FAN:
|
||||
this->mode = climate::CLIMATE_MODE_FAN_ONLY;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (power != HITACHI_AC424_POWER_ON) {
|
||||
this->mode = climate::CLIMATE_MODE_OFF;
|
||||
} else {
|
||||
this->mode = from_ir_code(MODES, mode, this->mode);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -268,24 +241,8 @@ bool HitachiClimate::parse_temperature_(const uint8_t remote_state[]) {
|
||||
bool HitachiClimate::parse_fan_(const uint8_t remote_state[]) {
|
||||
uint8_t fan_mode = remote_state[HITACHI_AC424_FAN_BYTE] >> 4 & 0xF;
|
||||
ESP_LOGV(TAG, "Fan: %02X %02X", remote_state[HITACHI_AC424_FAN_BYTE], fan_mode);
|
||||
switch (fan_mode) {
|
||||
case HITACHI_AC424_FAN_MIN:
|
||||
case HITACHI_AC424_FAN_LOW:
|
||||
this->fan_mode = climate::CLIMATE_FAN_LOW;
|
||||
break;
|
||||
case HITACHI_AC424_FAN_MEDIUM:
|
||||
this->fan_mode = climate::CLIMATE_FAN_MEDIUM;
|
||||
break;
|
||||
case HITACHI_AC424_FAN_HIGH:
|
||||
case HITACHI_AC424_FAN_MAX:
|
||||
this->fan_mode = climate::CLIMATE_FAN_HIGH;
|
||||
break;
|
||||
case HITACHI_AC424_FAN_AUTO:
|
||||
this->fan_mode = climate::CLIMATE_FAN_AUTO;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (const auto entry = find_ir_code(FANS, fan_mode, true))
|
||||
this->fan_mode = static_cast<climate::ClimateFanMode>(entry->value);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -21,19 +21,16 @@ constexpr uint8_t MISTRAL_POWER_ON = 0x20;
|
||||
constexpr uint8_t MISTRAL_TEMP_OFFSET = 0x9F;
|
||||
constexpr uint8_t MISTRAL_MODE_AUTO = 0x10;
|
||||
|
||||
// The tables live in flash, so entries are copied out before use
|
||||
struct ModeCode {
|
||||
climate::ClimateMode mode;
|
||||
uint8_t code;
|
||||
};
|
||||
static const ModeCode MODES[] PROGMEM = {
|
||||
// OFF sends the auto mode code and only clears the power byte
|
||||
static constexpr climate_ir::IRCode MODES[] PROGMEM = {
|
||||
{climate::CLIMATE_MODE_HEAT_COOL, MISTRAL_MODE_AUTO},
|
||||
{climate::CLIMATE_MODE_COOL, 0xC0},
|
||||
{climate::CLIMATE_MODE_DRY, 0x40},
|
||||
{climate::CLIMATE_MODE_FAN_ONLY, 0x80},
|
||||
{climate::CLIMATE_MODE_HEAT, 0x60},
|
||||
{climate::CLIMATE_MODE_HEAT_COOL, MISTRAL_MODE_AUTO},
|
||||
};
|
||||
|
||||
// Each fan speed sets two bytes; the table lives in flash, so entries are copied out before use
|
||||
struct FanCode {
|
||||
climate::ClimateFanMode fan;
|
||||
uint8_t byte1;
|
||||
@@ -78,7 +75,6 @@ static bool is_valid_frame(const uint8_t *frame) {
|
||||
}
|
||||
|
||||
void MistralIR::transmit_state() {
|
||||
const auto mode = find_entry(MODES, [this](const ModeCode &m) { return m.mode == this->mode; });
|
||||
const climate::ClimateFanMode fan_mode = this->fan_mode.value_or(climate::CLIMATE_FAN_AUTO);
|
||||
const FanCode fan =
|
||||
find_entry(FANS, [fan_mode](const FanCode &f) { return f.fan == fan_mode; }).value_or(load_entry(FANS[0]));
|
||||
@@ -88,7 +84,7 @@ void MistralIR::transmit_state() {
|
||||
progmem_memcpy(frame, FRAME_TEMPLATE, sizeof(frame));
|
||||
frame[1] = fan.byte1;
|
||||
frame[3] = this->mode == climate::CLIMATE_MODE_OFF ? MISTRAL_POWER_OFF : MISTRAL_POWER_ON;
|
||||
frame[4] = mode.has_value() ? mode->code : MISTRAL_MODE_AUTO;
|
||||
frame[4] = climate_ir::to_ir_code(MODES, this->mode, MISTRAL_MODE_AUTO);
|
||||
frame[5] = reverse_bits(static_cast<uint8_t>(MISTRAL_TEMP_OFFSET - temp));
|
||||
frame[6] = fan.byte6;
|
||||
frame[11] = compute_checksum(frame);
|
||||
@@ -116,12 +112,12 @@ bool MistralIR::on_receive(remote_base::RemoteReceiveData data) {
|
||||
return false;
|
||||
|
||||
// Decode everything before touching the state so an unknown code leaves it untouched
|
||||
const auto mode = find_entry(MODES, [frame](const ModeCode &m) { return m.code == frame[4]; });
|
||||
const auto mode = climate_ir::find_ir_code(MODES, frame[4], true);
|
||||
const auto fan = find_entry(FANS, [frame](const FanCode &f) { return f.byte1 == frame[1] && f.byte6 == frame[6]; });
|
||||
if (!mode.has_value() || !fan.has_value())
|
||||
return false;
|
||||
|
||||
this->mode = mode->mode;
|
||||
this->mode = static_cast<climate::ClimateMode>(mode->value);
|
||||
this->target_temperature =
|
||||
clamp<float>(MISTRAL_TEMP_OFFSET - reverse_bits(frame[5]), MISTRAL_TEMP_MIN, MISTRAL_TEMP_MAX);
|
||||
this->fan_mode = fan->fan;
|
||||
|
||||
@@ -29,6 +29,24 @@ using IRNoblexFan = enum IRNoblexFan {
|
||||
IR_NOBLEX_FAN_HIGH = 0b11,
|
||||
};
|
||||
|
||||
using climate_ir::find_ir_code;
|
||||
using climate_ir::from_ir_code;
|
||||
using climate_ir::IRCode;
|
||||
using climate_ir::to_ir_code;
|
||||
|
||||
// A mode not listed is sent as power off, and ignored when received
|
||||
static constexpr IRCode MODES[] PROGMEM = {
|
||||
{climate::CLIMATE_MODE_HEAT_COOL, IR_NOBLEX_MODE_AUTO}, {climate::CLIMATE_MODE_COOL, IR_NOBLEX_MODE_COOL},
|
||||
{climate::CLIMATE_MODE_DRY, IR_NOBLEX_MODE_DRY}, {climate::CLIMATE_MODE_FAN_ONLY, IR_NOBLEX_MODE_FAN},
|
||||
{climate::CLIMATE_MODE_HEAT, IR_NOBLEX_MODE_HEAT},
|
||||
};
|
||||
static constexpr IRCode FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_AUTO, IR_NOBLEX_FAN_AUTO},
|
||||
{climate::CLIMATE_FAN_LOW, IR_NOBLEX_FAN_LOW},
|
||||
{climate::CLIMATE_FAN_MEDIUM, IR_NOBLEX_FAN_MEDIUM},
|
||||
{climate::CLIMATE_FAN_HIGH, IR_NOBLEX_FAN_HIGH},
|
||||
};
|
||||
|
||||
// Transmit via IR the state of this climate controller.
|
||||
void NoblexClimate::transmit_state() {
|
||||
uint8_t remote_state[8] = {0x80, 0x10, 0x00, 0x0A, 0x50, 0x00, 0x20, 0x00}; // OFF, COOL, 24C, FAN_AUTO
|
||||
@@ -44,47 +62,18 @@ void NoblexClimate::transmit_state() {
|
||||
auto temp = (uint8_t) roundf(clamp<float>(this->target_temperature, NOBLEX_TEMP_MIN, NOBLEX_TEMP_MAX));
|
||||
remote_state[1] = reverse_bits(uint8_t((temp - NOBLEX_TEMP_MIN) & 0x0F));
|
||||
|
||||
switch (this->mode) {
|
||||
case climate::CLIMATE_MODE_HEAT_COOL:
|
||||
remote_state[0] |= (IRNoblexMode::IR_NOBLEX_MODE_AUTO << 5);
|
||||
if (const auto entry = find_ir_code(MODES, this->mode, false)) {
|
||||
remote_state[0] |= entry->code << 5;
|
||||
if (this->mode == climate::CLIMATE_MODE_HEAT_COOL)
|
||||
remote_state[1] = 0x90; // NOBLEX_TEMP_MAP 25C
|
||||
break;
|
||||
case climate::CLIMATE_MODE_COOL:
|
||||
remote_state[0] |= (IRNoblexMode::IR_NOBLEX_MODE_COOL << 5);
|
||||
break;
|
||||
case climate::CLIMATE_MODE_DRY:
|
||||
remote_state[0] |= (IRNoblexMode::IR_NOBLEX_MODE_DRY << 5);
|
||||
break;
|
||||
case climate::CLIMATE_MODE_FAN_ONLY:
|
||||
remote_state[0] |= (IRNoblexMode::IR_NOBLEX_MODE_FAN << 5);
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT:
|
||||
remote_state[0] |= (IRNoblexMode::IR_NOBLEX_MODE_HEAT << 5);
|
||||
break;
|
||||
case climate::CLIMATE_MODE_OFF:
|
||||
default:
|
||||
powered_on = false;
|
||||
this->powered_on_assumed = powered_on;
|
||||
remote_state[0] &= 0xEF;
|
||||
remote_state[2] = 0x00;
|
||||
break;
|
||||
} else {
|
||||
powered_on = false;
|
||||
this->powered_on_assumed = powered_on;
|
||||
remote_state[0] &= 0xEF;
|
||||
remote_state[2] = 0x00;
|
||||
}
|
||||
|
||||
switch (this->fan_mode.value_or(climate::CLIMATE_FAN_ON)) {
|
||||
case climate::CLIMATE_FAN_LOW:
|
||||
remote_state[0] |= (IRNoblexFan::IR_NOBLEX_FAN_LOW << 2);
|
||||
break;
|
||||
case climate::CLIMATE_FAN_MEDIUM:
|
||||
remote_state[0] |= (IRNoblexFan::IR_NOBLEX_FAN_MEDIUM << 2);
|
||||
break;
|
||||
case climate::CLIMATE_FAN_HIGH:
|
||||
remote_state[0] |= (IRNoblexFan::IR_NOBLEX_FAN_HIGH << 2);
|
||||
break;
|
||||
case climate::CLIMATE_FAN_AUTO:
|
||||
default:
|
||||
remote_state[0] |= (IRNoblexFan::IR_NOBLEX_FAN_AUTO << 2);
|
||||
break;
|
||||
}
|
||||
remote_state[0] |= to_ir_code(FANS, this->fan_mode.value_or(climate::CLIMATE_FAN_AUTO), IR_NOBLEX_FAN_AUTO) << 2;
|
||||
|
||||
switch (this->swing_mode) {
|
||||
case climate::CLIMATE_SWING_VERTICAL:
|
||||
@@ -236,25 +225,7 @@ bool NoblexClimate::on_receive(remote_base::RemoteReceiveData data) {
|
||||
if (powered_on_assumed) {
|
||||
auto mode = (this->remote_state_[0] & 0xE0) >> 5;
|
||||
ESP_LOGV(TAG, "Mode: %02X", mode);
|
||||
switch (mode) {
|
||||
case IRNoblexMode::IR_NOBLEX_MODE_AUTO:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT_COOL;
|
||||
break;
|
||||
case IRNoblexMode::IR_NOBLEX_MODE_COOL:
|
||||
this->mode = climate::CLIMATE_MODE_COOL;
|
||||
break;
|
||||
case IRNoblexMode::IR_NOBLEX_MODE_DRY:
|
||||
this->mode = climate::CLIMATE_MODE_DRY;
|
||||
break;
|
||||
case IRNoblexMode::IR_NOBLEX_MODE_FAN:
|
||||
this->mode = climate::CLIMATE_MODE_FAN_ONLY;
|
||||
break;
|
||||
case IRNoblexMode::IR_NOBLEX_MODE_HEAT:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
this->mode = from_ir_code(MODES, mode, this->mode);
|
||||
}
|
||||
|
||||
// Set received temp
|
||||
@@ -269,21 +240,7 @@ bool NoblexClimate::on_receive(remote_base::RemoteReceiveData data) {
|
||||
// Set received fan speed
|
||||
auto fan = (this->remote_state_[0] & 0x0C) >> 2;
|
||||
ESP_LOGV(TAG, "Fan: %02X", fan);
|
||||
switch (fan) {
|
||||
case IRNoblexFan::IR_NOBLEX_FAN_HIGH:
|
||||
this->fan_mode = climate::CLIMATE_FAN_HIGH;
|
||||
break;
|
||||
case IRNoblexFan::IR_NOBLEX_FAN_MEDIUM:
|
||||
this->fan_mode = climate::CLIMATE_FAN_MEDIUM;
|
||||
break;
|
||||
case IRNoblexFan::IR_NOBLEX_FAN_LOW:
|
||||
this->fan_mode = climate::CLIMATE_FAN_LOW;
|
||||
break;
|
||||
case IRNoblexFan::IR_NOBLEX_FAN_AUTO:
|
||||
default:
|
||||
this->fan_mode = climate::CLIMATE_FAN_AUTO;
|
||||
break;
|
||||
}
|
||||
this->fan_mode = from_ir_code(FANS, fan, climate::CLIMATE_FAN_AUTO);
|
||||
|
||||
// Set received swing status
|
||||
if (this->remote_state_[0] & 0x02) {
|
||||
|
||||
@@ -47,46 +47,28 @@ static bool is_powered_on(const uint8_t *state) {
|
||||
return get_field(state, POWER_1) == POWER_ON && get_field(state, POWER_2) == POWER_ON;
|
||||
}
|
||||
|
||||
struct Code {
|
||||
uint8_t value; // a climate enum, all of which are uint8_t
|
||||
uint8_t code;
|
||||
};
|
||||
// The first entry of each table is the fallback in both directions
|
||||
static constexpr Code MODES[] PROGMEM = {
|
||||
using climate_ir::from_ir_code;
|
||||
using climate_ir::IRCode;
|
||||
using climate_ir::to_ir_code;
|
||||
|
||||
// Codes not listed fall back to auto (mode and fan) and to swing off
|
||||
static constexpr IRCode MODES[] PROGMEM = {
|
||||
{climate::CLIMATE_MODE_HEAT_COOL, 0}, {climate::CLIMATE_MODE_COOL, 1}, {climate::CLIMATE_MODE_DRY, 2},
|
||||
{climate::CLIMATE_MODE_FAN_ONLY, 3}, {climate::CLIMATE_MODE_HEAT, 4},
|
||||
};
|
||||
static constexpr Code FANS[] PROGMEM = {
|
||||
static constexpr IRCode FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_AUTO, 0},
|
||||
{climate::CLIMATE_FAN_LOW, 2},
|
||||
{climate::CLIMATE_FAN_MEDIUM, 4},
|
||||
{climate::CLIMATE_FAN_HIGH, 5},
|
||||
};
|
||||
static constexpr Code SWINGS[] PROGMEM = {
|
||||
static constexpr IRCode SWINGS[] PROGMEM = {
|
||||
{climate::CLIMATE_SWING_OFF, 0b111},
|
||||
{climate::CLIMATE_SWING_VERTICAL, 0b010},
|
||||
{climate::CLIMATE_SWING_HORIZONTAL, 0b011},
|
||||
{climate::CLIMATE_SWING_BOTH, 0b100},
|
||||
};
|
||||
|
||||
// Returns the entry whose value (or code) matches key, else the first entry. Entries are copied out of PROGMEM.
|
||||
static Code find_entry(const Code *table, size_t count, uint8_t key, bool match_code) {
|
||||
Code entry{};
|
||||
for (size_t i = 0; i < count; i++) {
|
||||
progmem_memcpy(&entry, &table[i], sizeof(entry));
|
||||
if ((match_code ? entry.code : entry.value) == key)
|
||||
return entry;
|
||||
}
|
||||
progmem_memcpy(&entry, table, sizeof(entry));
|
||||
return entry;
|
||||
}
|
||||
template<size_t N> static uint8_t to_code(const Code (&table)[N], uint8_t value) {
|
||||
return find_entry(table, N, value, false).code;
|
||||
}
|
||||
template<typename T, size_t N> static T from_code(const Code (&table)[N], uint8_t code) {
|
||||
return static_cast<T>(find_entry(table, N, code, true).value);
|
||||
}
|
||||
|
||||
// Inverted count of the one bits in a section, skipping the two nibbles that hold the checksum itself.
|
||||
// See https://github.com/crankyoldgit/IRremoteESP8266/issues/1538#issuecomment-894645947
|
||||
static uint8_t section_checksum(const uint8_t *section) {
|
||||
@@ -123,13 +105,13 @@ void SamsungClimate::transmit_state() {
|
||||
|
||||
if (on) {
|
||||
progmem_memcpy(state, RESET_STATE, SAMSUNG_AC_STATE_LENGTH);
|
||||
set_field(state, MODE, to_code(MODES, this->mode));
|
||||
set_field(state, MODE, to_ir_code(MODES, this->mode, 0));
|
||||
} // else keep the last mode so the power off frame still carries a valid state
|
||||
|
||||
const uint8_t temp = clamp<uint8_t>(this->target_temperature, SAMSUNG_AC_TEMP_MIN, SAMSUNG_AC_TEMP_MAX);
|
||||
set_field(state, TEMP, temp - SAMSUNG_AC_TEMP_MIN);
|
||||
set_field(state, SWING, to_code(SWINGS, this->swing_mode));
|
||||
set_field(state, FAN, to_code(FANS, this->fan_mode.value_or(climate::CLIMATE_FAN_AUTO)));
|
||||
set_field(state, SWING, to_ir_code(SWINGS, this->swing_mode, 0b111));
|
||||
set_field(state, FAN, to_ir_code(FANS, this->fan_mode.value_or(climate::CLIMATE_FAN_AUTO), 0));
|
||||
set_field(state, POWER_1, on ? POWER_ON : 0);
|
||||
set_field(state, POWER_2, on ? POWER_ON : 0);
|
||||
|
||||
@@ -212,11 +194,11 @@ bool SamsungClimate::on_receive(remote_base::RemoteReceiveData data) {
|
||||
memcpy(state, frame, SAMSUNG_AC_SECTION_LENGTH);
|
||||
memcpy(state + SAMSUNG_AC_SECTION_LENGTH, frame + length - SAMSUNG_AC_SECTION_LENGTH, SAMSUNG_AC_SECTION_LENGTH);
|
||||
|
||||
this->swing_mode = from_code<climate::ClimateSwingMode>(SWINGS, get_field(state, SWING));
|
||||
this->swing_mode = from_ir_code(SWINGS, get_field(state, SWING), climate::CLIMATE_SWING_OFF);
|
||||
this->target_temperature = get_field(state, TEMP) + SAMSUNG_AC_TEMP_MIN;
|
||||
this->fan_mode = from_code<climate::ClimateFanMode>(FANS, get_field(state, FAN));
|
||||
this->mode =
|
||||
is_powered_on(state) ? from_code<climate::ClimateMode>(MODES, get_field(state, MODE)) : climate::CLIMATE_MODE_OFF;
|
||||
this->fan_mode = from_ir_code(FANS, get_field(state, FAN), climate::CLIMATE_FAN_AUTO);
|
||||
this->mode = is_powered_on(state) ? from_ir_code(MODES, get_field(state, MODE), climate::CLIMATE_MODE_HEAT_COOL)
|
||||
: climate::CLIMATE_MODE_OFF;
|
||||
|
||||
ESP_LOGD(TAG, "Received %u byte frame, power %s", length, ONOFF(is_powered_on(state)));
|
||||
this->publish_state();
|
||||
|
||||
@@ -6,70 +6,32 @@ namespace esphome::siemens_ira211 {
|
||||
|
||||
using namespace remote_base;
|
||||
|
||||
struct PresetMapping {
|
||||
climate::ClimatePreset preset;
|
||||
IRA211Mode mode;
|
||||
// Presets map to IRA211Mode and fan modes to IRA211Fan. Values the other side does not know fall back to comfort
|
||||
// and auto.
|
||||
static constexpr climate_ir::IRCode PRESETS[] PROGMEM = {
|
||||
{climate::CLIMATE_PRESET_COMFORT, static_cast<uint8_t>(IRA211Mode::IRA211_MODE_COMFORT)},
|
||||
{climate::CLIMATE_PRESET_ECO, static_cast<uint8_t>(IRA211Mode::IRA211_MODE_TIMER)},
|
||||
};
|
||||
static constexpr climate_ir::IRCode FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_AUTO, static_cast<uint8_t>(IRA211Fan::IRA211_FAN_AUTO)},
|
||||
{climate::CLIMATE_FAN_LOW, static_cast<uint8_t>(IRA211Fan::IRA211_FAN_LOW)},
|
||||
{climate::CLIMATE_FAN_MEDIUM, static_cast<uint8_t>(IRA211Fan::IRA211_FAN_MEDIUM)},
|
||||
{climate::CLIMATE_FAN_HIGH, static_cast<uint8_t>(IRA211Fan::IRA211_FAN_HIGH)},
|
||||
};
|
||||
|
||||
static const PresetMapping PRESETS[] PROGMEM = {
|
||||
{climate::CLIMATE_PRESET_COMFORT, IRA211Mode::IRA211_MODE_COMFORT},
|
||||
{climate::CLIMATE_PRESET_ECO, IRA211Mode::IRA211_MODE_TIMER},
|
||||
};
|
||||
|
||||
struct FanMapping {
|
||||
climate::ClimateFanMode fan_mode;
|
||||
IRA211Fan fan;
|
||||
};
|
||||
|
||||
static const FanMapping FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_AUTO, IRA211Fan::IRA211_FAN_AUTO},
|
||||
{climate::CLIMATE_FAN_LOW, IRA211Fan::IRA211_FAN_LOW},
|
||||
{climate::CLIMATE_FAN_MEDIUM, IRA211Fan::IRA211_FAN_MEDIUM},
|
||||
{climate::CLIMATE_FAN_HIGH, IRA211Fan::IRA211_FAN_HIGH},
|
||||
};
|
||||
|
||||
// The tables live in flash, so entries are copied out before use
|
||||
template<typename T> static T load_entry(const T &slot) {
|
||||
T entry;
|
||||
progmem_memcpy(&entry, &slot, sizeof(T));
|
||||
return entry;
|
||||
}
|
||||
|
||||
// The first entry of each table is the fallback for values the other side does not know
|
||||
static IRA211Mode to_ira211_mode(climate::ClimatePreset preset) {
|
||||
for (const auto &slot : PRESETS) {
|
||||
const auto entry = load_entry(slot);
|
||||
if (entry.preset == preset)
|
||||
return entry.mode;
|
||||
}
|
||||
return load_entry(PRESETS[0]).mode;
|
||||
return static_cast<IRA211Mode>(
|
||||
climate_ir::to_ir_code(PRESETS, preset, static_cast<uint8_t>(IRA211Mode::IRA211_MODE_COMFORT)));
|
||||
}
|
||||
|
||||
static climate::ClimatePreset to_climate_preset(IRA211Mode mode) {
|
||||
for (const auto &slot : PRESETS) {
|
||||
const auto entry = load_entry(slot);
|
||||
if (entry.mode == mode)
|
||||
return entry.preset;
|
||||
}
|
||||
return load_entry(PRESETS[0]).preset;
|
||||
return climate_ir::from_ir_code(PRESETS, static_cast<uint8_t>(mode), climate::CLIMATE_PRESET_COMFORT);
|
||||
}
|
||||
|
||||
static IRA211Fan to_ira211_fan(climate::ClimateFanMode fan_mode) {
|
||||
for (const auto &slot : FANS) {
|
||||
const auto entry = load_entry(slot);
|
||||
if (entry.fan_mode == fan_mode)
|
||||
return entry.fan;
|
||||
}
|
||||
return load_entry(FANS[0]).fan;
|
||||
return static_cast<IRA211Fan>(
|
||||
climate_ir::to_ir_code(FANS, fan_mode, static_cast<uint8_t>(IRA211Fan::IRA211_FAN_AUTO)));
|
||||
}
|
||||
|
||||
static climate::ClimateFanMode to_climate_fan_mode(IRA211Fan fan) {
|
||||
for (const auto &slot : FANS) {
|
||||
const auto entry = load_entry(slot);
|
||||
if (entry.fan == fan)
|
||||
return entry.fan_mode;
|
||||
}
|
||||
return load_entry(FANS[0]).fan_mode;
|
||||
return climate_ir::from_ir_code(FANS, static_cast<uint8_t>(fan), climate::CLIMATE_FAN_AUTO);
|
||||
}
|
||||
|
||||
void SiemensIRA211Climate::setup() {
|
||||
|
||||
@@ -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,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,123 +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); }
|
||||
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,355 +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;
|
||||
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 (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;
|
||||
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 = 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;
|
||||
buf[0] = (bitrate >> 16) & 0xFF;
|
||||
buf[1] = (bitrate >> 8) & 0xFF;
|
||||
buf[2] = (bitrate >> 0) & 0xFF;
|
||||
buf[3] = profile.shaping;
|
||||
buf[4] = progmem_read_byte(&BW_FSK[profile.bandwidth - SX126X_BW_4800]);
|
||||
buf[5] = (fdev >> 16) & 0xFF;
|
||||
buf[6] = (fdev >> 8) & 0xFF;
|
||||
buf[7] = (fdev >> 0) & 0xFF;
|
||||
this->write_opcode_(RADIO_SET_MODULATIONPARAMS, buf, 8);
|
||||
|
||||
// set crc params
|
||||
if (profile.crc_enable) {
|
||||
buf[0] = profile.crc_initial >> 8;
|
||||
buf[1] = profile.crc_initial & 0xFF;
|
||||
this->write_register_(REG_CRC_INITIAL, buf, 2);
|
||||
buf[0] = profile.crc_polynomial >> 8;
|
||||
buf[1] = profile.crc_polynomial & 0xFF;
|
||||
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) {
|
||||
buf[0] = (profile.preamble_size >> 8) & 0xFF;
|
||||
buf[1] = (profile.preamble_size >> 0) & 0xFF;
|
||||
buf[2] = (profile.payload_length > 0) ? 0x01 : 0x00;
|
||||
buf[3] = payload_length;
|
||||
buf[4] = (profile.crc_enable) ? 0x01 : 0x00;
|
||||
buf[5] = 0x00;
|
||||
applied.packet_params_size = 6;
|
||||
} else {
|
||||
uint16_t preamble_size = profile.preamble_size * 8;
|
||||
buf[0] = (preamble_size >> 8) & 0xFF;
|
||||
buf[1] = (preamble_size >> 0) & 0xFF;
|
||||
buf[2] = (profile.preamble_detect > 0) ? ((profile.preamble_detect - 1) | 0x04) : 0x00;
|
||||
buf[3] = profile.sync_size * 8;
|
||||
buf[4] = 0x00;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
void SX126xCommands::receive() {
|
||||
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 SX126xCommands::transmit(uint32_t timeout_ms) {
|
||||
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);
|
||||
|
||||
const uint32_t ticks = timeout_ms * 64;
|
||||
buf[0] = ticks >> 16;
|
||||
buf[1] = ticks >> 8;
|
||||
buf[2] = 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,49 +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 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,253 +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();
|
||||
}
|
||||
|
||||
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,149 +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(); }
|
||||
|
||||
// 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
|
||||
@@ -32,6 +32,24 @@ static constexpr remote_base::BitTimings TCL112_BIT_TIMINGS{
|
||||
.bit_mark = TCL112_BIT_MARK, .one_space = 1100, .zero_space = 350};
|
||||
const uint32_t TCL112_GAP = TCL112_HEADER_SPACE;
|
||||
|
||||
using climate_ir::find_ir_code;
|
||||
using climate_ir::from_ir_code;
|
||||
using climate_ir::IRCode;
|
||||
using climate_ir::to_ir_code;
|
||||
|
||||
// A mode not listed is sent as power off, and ignored when received
|
||||
static constexpr IRCode MODES[] PROGMEM = {
|
||||
{climate::CLIMATE_MODE_HEAT_COOL, TCL112_AUTO}, {climate::CLIMATE_MODE_COOL, TCL112_COOL},
|
||||
{climate::CLIMATE_MODE_HEAT, TCL112_HEAT}, {climate::CLIMATE_MODE_DRY, TCL112_DRY},
|
||||
{climate::CLIMATE_MODE_FAN_ONLY, TCL112_FAN},
|
||||
};
|
||||
static constexpr IRCode FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_AUTO, TCL112_FAN_AUTO},
|
||||
{climate::CLIMATE_FAN_HIGH, TCL112_FAN_HIGH},
|
||||
{climate::CLIMATE_FAN_MEDIUM, TCL112_FAN_MED},
|
||||
{climate::CLIMATE_FAN_LOW, TCL112_FAN_LOW},
|
||||
};
|
||||
|
||||
void Tcl112Climate::transmit_state() {
|
||||
uint8_t remote_state[TCL112_STATE_LENGTH] = {0};
|
||||
|
||||
@@ -46,31 +64,11 @@ void Tcl112Climate::transmit_state() {
|
||||
remote_state[8] = 0x40;
|
||||
|
||||
// Set mode
|
||||
switch (this->mode) {
|
||||
case climate::CLIMATE_MODE_HEAT_COOL:
|
||||
remote_state[6] &= 0xF0;
|
||||
remote_state[6] |= TCL112_AUTO;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_COOL:
|
||||
remote_state[6] &= 0xF0;
|
||||
remote_state[6] |= TCL112_COOL;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT:
|
||||
remote_state[6] &= 0xF0;
|
||||
remote_state[6] |= TCL112_HEAT;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_DRY:
|
||||
remote_state[6] &= 0xF0;
|
||||
remote_state[6] |= TCL112_DRY;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_FAN_ONLY:
|
||||
remote_state[6] &= 0xF0;
|
||||
remote_state[6] |= TCL112_FAN;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_OFF:
|
||||
default:
|
||||
remote_state[5] &= ~TCL112_POWER_MASK;
|
||||
break;
|
||||
if (const auto entry = find_ir_code(MODES, this->mode, false)) {
|
||||
remote_state[6] &= 0xF0;
|
||||
remote_state[6] |= entry->code;
|
||||
} else {
|
||||
remote_state[5] &= ~TCL112_POWER_MASK;
|
||||
}
|
||||
|
||||
// Set temperature
|
||||
@@ -88,22 +86,7 @@ void Tcl112Climate::transmit_state() {
|
||||
remote_state[7] |= ((uint8_t) TCL112_TEMP_MAX - half_degrees / 2);
|
||||
|
||||
// Set fan
|
||||
uint8_t selected_fan;
|
||||
switch (this->fan_mode.value_or(climate::CLIMATE_FAN_ON)) {
|
||||
case climate::CLIMATE_FAN_HIGH:
|
||||
selected_fan = TCL112_FAN_HIGH;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_MEDIUM:
|
||||
selected_fan = TCL112_FAN_MED;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_LOW:
|
||||
selected_fan = TCL112_FAN_LOW;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_AUTO:
|
||||
default:
|
||||
selected_fan = TCL112_FAN_AUTO;
|
||||
}
|
||||
remote_state[8] |= selected_fan;
|
||||
remote_state[8] |= to_ir_code(FANS, this->fan_mode.value_or(climate::CLIMATE_FAN_AUTO), TCL112_FAN_AUTO);
|
||||
|
||||
// Set swing
|
||||
if (this->swing_mode == climate::CLIMATE_SWING_VERTICAL) {
|
||||
@@ -169,47 +152,13 @@ bool Tcl112Climate::on_receive(remote_base::RemoteReceiveData data) {
|
||||
if ((remote_state[5] & TCL112_POWER_MASK) == 0) {
|
||||
this->mode = climate::CLIMATE_MODE_OFF;
|
||||
} else {
|
||||
auto mode = remote_state[6] & 0x0F;
|
||||
switch (mode) {
|
||||
case TCL112_HEAT:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT;
|
||||
break;
|
||||
case TCL112_COOL:
|
||||
this->mode = climate::CLIMATE_MODE_COOL;
|
||||
break;
|
||||
case TCL112_DRY:
|
||||
this->mode = climate::CLIMATE_MODE_DRY;
|
||||
break;
|
||||
case TCL112_FAN:
|
||||
this->mode = climate::CLIMATE_MODE_FAN_ONLY;
|
||||
break;
|
||||
case TCL112_AUTO:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT_COOL;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
this->mode = from_ir_code(MODES, remote_state[6] & 0x0F, this->mode);
|
||||
}
|
||||
auto temp = TCL112_TEMP_MAX - remote_state[7];
|
||||
if (remote_state[12] & TCL112_HALF_DEGREE)
|
||||
temp += .5f;
|
||||
this->target_temperature = temp;
|
||||
auto fan = remote_state[8] & 0x7;
|
||||
switch (fan) {
|
||||
case TCL112_FAN_HIGH:
|
||||
this->fan_mode = climate::CLIMATE_FAN_HIGH;
|
||||
break;
|
||||
case TCL112_FAN_MED:
|
||||
this->fan_mode = climate::CLIMATE_FAN_MEDIUM;
|
||||
break;
|
||||
case TCL112_FAN_LOW:
|
||||
this->fan_mode = climate::CLIMATE_FAN_LOW;
|
||||
break;
|
||||
case TCL112_FAN_AUTO:
|
||||
default:
|
||||
this->fan_mode = climate::CLIMATE_FAN_AUTO;
|
||||
break;
|
||||
}
|
||||
this->fan_mode = from_ir_code(FANS, remote_state[8] & 0x7, climate::CLIMATE_FAN_AUTO);
|
||||
if ((remote_state[8] & TCL112_VSWING_MASK) == TCL112_VSWING_MASK) {
|
||||
this->swing_mode = climate::CLIMATE_SWING_VERTICAL;
|
||||
} else {
|
||||
|
||||
@@ -57,6 +57,24 @@ 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;
|
||||
|
||||
using climate_ir::find_ir_code;
|
||||
using climate_ir::from_ir_code;
|
||||
using climate_ir::IRCode;
|
||||
using climate_ir::to_ir_code;
|
||||
|
||||
// Off is not listed: it is sent as a power toggle or state
|
||||
static constexpr IRCode MODES[] PROGMEM = {
|
||||
{climate::CLIMATE_MODE_HEAT_COOL, WHIRLPOOL_AUTO}, {climate::CLIMATE_MODE_HEAT, WHIRLPOOL_HEAT},
|
||||
{climate::CLIMATE_MODE_COOL, WHIRLPOOL_COOL}, {climate::CLIMATE_MODE_DRY, WHIRLPOOL_DRY},
|
||||
{climate::CLIMATE_MODE_FAN_ONLY, WHIRLPOOL_FAN},
|
||||
};
|
||||
static constexpr IRCode FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_AUTO, WHIRLPOOL_FAN_AUTO},
|
||||
{climate::CLIMATE_FAN_HIGH, WHIRLPOOL_FAN_HIGH},
|
||||
{climate::CLIMATE_FAN_MEDIUM, WHIRLPOOL_FAN_MED},
|
||||
{climate::CLIMATE_FAN_LOW, WHIRLPOOL_FAN_LOW},
|
||||
};
|
||||
|
||||
WhirlpoolClimate::WhirlpoolClimate()
|
||||
: climate_ir::ClimateIR(
|
||||
WHIRLPOOL_DG11J1_3A_TEMP_MIN, WHIRLPOOL_DG11J1_3A_TEMP_MAX, 1.0f, true, true,
|
||||
@@ -81,37 +99,13 @@ void WhirlpoolClimate::transmit_state() {
|
||||
remote_state[15] = 1;
|
||||
}
|
||||
this->powered_on_assumed = powered_on;
|
||||
switch (this->mode) {
|
||||
case climate::CLIMATE_MODE_HEAT_COOL:
|
||||
// set fan auto
|
||||
// set temp auto temp
|
||||
// set sleep false
|
||||
remote_state[3] = WHIRLPOOL_AUTO;
|
||||
remote_state[15] = 0x17;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT:
|
||||
remote_state[3] = WHIRLPOOL_HEAT;
|
||||
remote_state[15] = 6;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_COOL:
|
||||
remote_state[3] = WHIRLPOOL_COOL;
|
||||
remote_state[15] = 6;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_DRY:
|
||||
remote_state[3] = WHIRLPOOL_DRY;
|
||||
remote_state[15] = 6;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_FAN_ONLY:
|
||||
remote_state[3] = WHIRLPOOL_FAN;
|
||||
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;
|
||||
if (const auto entry = find_ir_code(MODES, this->mode, false)) {
|
||||
remote_state[3] = entry->code;
|
||||
// Auto also sets fan auto, auto temperature and sleep off
|
||||
remote_state[15] = this->mode == climate::CLIMATE_MODE_HEAT_COOL ? 0x17 : 6;
|
||||
} else if (this->mode == climate::CLIMATE_MODE_OFF && (this->is_hisense_arg_() || this->is_hitachi_hcra31newh_())) {
|
||||
// These remotes keep the cool code in the power-off frame
|
||||
remote_state[3] = WHIRLPOOL_COOL;
|
||||
}
|
||||
|
||||
const bool hisense_arg = this->is_hisense_arg_();
|
||||
@@ -127,19 +121,7 @@ void WhirlpoolClimate::transmit_state() {
|
||||
}
|
||||
|
||||
// Fan speed
|
||||
switch (this->fan_mode.value_or(climate::CLIMATE_FAN_ON)) {
|
||||
case climate::CLIMATE_FAN_HIGH:
|
||||
remote_state[2] |= WHIRLPOOL_FAN_HIGH;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_MEDIUM:
|
||||
remote_state[2] |= WHIRLPOOL_FAN_MED;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_LOW:
|
||||
remote_state[2] |= WHIRLPOOL_FAN_LOW;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
remote_state[2] |= to_ir_code(FANS, this->fan_mode.value_or(climate::CLIMATE_FAN_AUTO), WHIRLPOOL_FAN_AUTO);
|
||||
|
||||
// Swing
|
||||
ESP_LOGV(TAG, "send swing %s", this->send_swing_cmd_ ? LOG_STR_LITERAL("true") : LOG_STR_LITERAL("false"));
|
||||
@@ -328,25 +310,7 @@ bool WhirlpoolClimate::on_receive(remote_base::RemoteReceiveData data) {
|
||||
if (powered_on_assumed) {
|
||||
auto mode = remote_state[3] & 0x7;
|
||||
ESP_LOGV(TAG, "Mode: %02X", mode);
|
||||
switch (mode) {
|
||||
case WHIRLPOOL_HEAT:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT;
|
||||
break;
|
||||
case WHIRLPOOL_COOL:
|
||||
this->mode = climate::CLIMATE_MODE_COOL;
|
||||
break;
|
||||
case WHIRLPOOL_DRY:
|
||||
this->mode = climate::CLIMATE_MODE_DRY;
|
||||
break;
|
||||
case WHIRLPOOL_FAN:
|
||||
this->mode = climate::CLIMATE_MODE_FAN_ONLY;
|
||||
break;
|
||||
case WHIRLPOOL_AUTO:
|
||||
this->mode = climate::CLIMATE_MODE_HEAT_COOL;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
this->mode = from_ir_code(MODES, mode, this->mode);
|
||||
}
|
||||
|
||||
// Set received temp; Hisense ARG sends fixed values in auto and fan-only
|
||||
@@ -363,21 +327,7 @@ bool WhirlpoolClimate::on_receive(remote_base::RemoteReceiveData data) {
|
||||
// Set received fan speed
|
||||
auto fan = remote_state[2] & WHIRLPOOL_FAN_MASK;
|
||||
ESP_LOGVV(TAG, "Fan: %02X", fan);
|
||||
switch (fan) {
|
||||
case WHIRLPOOL_FAN_HIGH:
|
||||
this->fan_mode = climate::CLIMATE_FAN_HIGH;
|
||||
break;
|
||||
case WHIRLPOOL_FAN_MED:
|
||||
this->fan_mode = climate::CLIMATE_FAN_MEDIUM;
|
||||
break;
|
||||
case WHIRLPOOL_FAN_LOW:
|
||||
this->fan_mode = climate::CLIMATE_FAN_LOW;
|
||||
break;
|
||||
case WHIRLPOOL_FAN_AUTO:
|
||||
default:
|
||||
this->fan_mode = climate::CLIMATE_FAN_AUTO;
|
||||
break;
|
||||
}
|
||||
this->fan_mode = from_ir_code(FANS, fan, climate::CLIMATE_FAN_AUTO);
|
||||
|
||||
// Set received swing status
|
||||
if (hisense_arg) {
|
||||
|
||||
@@ -39,48 +39,40 @@ const uint32_t UNIT_MASK = 1 << UNIT_SHIFT;
|
||||
const uint32_t TEMP_MASK = 0xFF;
|
||||
const uint32_t TEMP_OFFSET_C = 16;
|
||||
|
||||
using climate_ir::find_ir_code;
|
||||
using climate_ir::from_ir_code;
|
||||
using climate_ir::IRCode;
|
||||
using climate_ir::to_ir_code;
|
||||
|
||||
// Codes are stored shifted down to one byte. A mode not listed is sent as power off, and ignored when received.
|
||||
static constexpr IRCode MODES[] PROGMEM = {
|
||||
{climate::CLIMATE_MODE_FAN_ONLY, MODE_FAN >> MODE_SHIFT},
|
||||
{climate::CLIMATE_MODE_DRY, MODE_DRY >> MODE_SHIFT},
|
||||
{climate::CLIMATE_MODE_HEAT, MODE_HEAT >> MODE_SHIFT},
|
||||
{climate::CLIMATE_MODE_COOL, MODE_COOL >> MODE_SHIFT},
|
||||
};
|
||||
// A received code that is not listed is ignored
|
||||
static constexpr IRCode FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_HIGH, FAN_HIGH >> FAN_SHIFT},
|
||||
{climate::CLIMATE_FAN_LOW, FAN_LOW >> FAN_SHIFT},
|
||||
{climate::CLIMATE_FAN_MEDIUM, FAN_MED >> FAN_SHIFT},
|
||||
};
|
||||
|
||||
void Whynter::transmit_state() {
|
||||
uint32_t remote_state = COMMAND_CODE;
|
||||
if (this->mode == climate::CLIMATE_MODE_HEAT_COOL)
|
||||
this->mode = climate::CLIMATE_MODE_COOL;
|
||||
switch (this->mode) {
|
||||
case climate::CLIMATE_MODE_FAN_ONLY:
|
||||
remote_state |= POWER_MASK;
|
||||
remote_state |= MODE_FAN;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_DRY:
|
||||
remote_state |= POWER_MASK;
|
||||
remote_state |= MODE_DRY;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT:
|
||||
remote_state |= POWER_MASK;
|
||||
remote_state |= MODE_HEAT;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_COOL:
|
||||
remote_state |= POWER_MASK;
|
||||
remote_state |= MODE_COOL;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_OFF:
|
||||
remote_state |= POWER_OFF;
|
||||
break;
|
||||
default:
|
||||
remote_state |= POWER_OFF;
|
||||
if (const auto entry = find_ir_code(MODES, this->mode, false)) {
|
||||
remote_state |= POWER_MASK;
|
||||
remote_state |= static_cast<uint32_t>(entry->code) << MODE_SHIFT;
|
||||
} else {
|
||||
remote_state |= POWER_OFF;
|
||||
}
|
||||
mode_before_ = this->mode;
|
||||
|
||||
switch (this->fan_mode.value_or(climate::CLIMATE_FAN_ON)) {
|
||||
case climate::CLIMATE_FAN_LOW:
|
||||
remote_state |= FAN_LOW;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_MEDIUM:
|
||||
remote_state |= FAN_MED;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_HIGH:
|
||||
remote_state |= FAN_HIGH;
|
||||
break;
|
||||
default:
|
||||
remote_state |= FAN_HIGH;
|
||||
}
|
||||
remote_state |=
|
||||
static_cast<uint32_t>(to_ir_code(FANS, this->fan_mode.value_or(climate::CLIMATE_FAN_HIGH), FAN_HIGH >> FAN_SHIFT))
|
||||
<< FAN_SHIFT;
|
||||
|
||||
if (fahrenheit_) {
|
||||
remote_state |= UNIT_MASK;
|
||||
@@ -123,15 +115,7 @@ bool Whynter::on_receive(remote_base::RemoteReceiveData data) {
|
||||
if ((remote_state & POWER_MASK) != POWER_MASK) {
|
||||
this->mode = climate::CLIMATE_MODE_OFF;
|
||||
} else {
|
||||
if ((remote_state & MODE_MASK) == MODE_FAN) {
|
||||
this->mode = climate::CLIMATE_MODE_FAN_ONLY;
|
||||
} else if ((remote_state & MODE_MASK) == MODE_DRY) {
|
||||
this->mode = climate::CLIMATE_MODE_DRY;
|
||||
} else if ((remote_state & MODE_MASK) == MODE_HEAT) {
|
||||
this->mode = climate::CLIMATE_MODE_HEAT;
|
||||
} else if ((remote_state & MODE_MASK) == MODE_COOL) {
|
||||
this->mode = climate::CLIMATE_MODE_COOL;
|
||||
}
|
||||
this->mode = from_ir_code(MODES, (remote_state & MODE_MASK) >> MODE_SHIFT, this->mode);
|
||||
|
||||
// Temperature
|
||||
if ((remote_state & UNIT_MASK) == UNIT_MASK) { // Fahrenheit
|
||||
@@ -141,13 +125,8 @@ bool Whynter::on_receive(remote_base::RemoteReceiveData data) {
|
||||
}
|
||||
|
||||
// Fan Speed
|
||||
if ((remote_state & FAN_MASK) == FAN_LOW) {
|
||||
this->fan_mode = climate::CLIMATE_FAN_LOW;
|
||||
} else if ((remote_state & FAN_MASK) == FAN_MED) {
|
||||
this->fan_mode = climate::CLIMATE_FAN_MEDIUM;
|
||||
} else if ((remote_state & FAN_MASK) == FAN_HIGH) {
|
||||
this->fan_mode = climate::CLIMATE_FAN_HIGH;
|
||||
}
|
||||
if (const auto entry = find_ir_code(FANS, (remote_state & FAN_MASK) >> FAN_SHIFT, true))
|
||||
this->fan_mode = static_cast<climate::ClimateFanMode>(entry->value);
|
||||
}
|
||||
this->publish_state();
|
||||
|
||||
|
||||
@@ -7,6 +7,24 @@ ESPHOME_LOG_TAG(TAG, "zhlt01.climate");
|
||||
|
||||
static constexpr uint8_t ZHLT01_MESSAGE_LENGTH = 12;
|
||||
|
||||
using climate_ir::find_ir_code;
|
||||
using climate_ir::from_ir_code;
|
||||
using climate_ir::IRCode;
|
||||
using climate_ir::to_ir_code;
|
||||
|
||||
static constexpr IRCode MODES[] PROGMEM = {
|
||||
{climate::CLIMATE_MODE_AUTO, AC1_MODE_AUTO}, {climate::CLIMATE_MODE_COOL, AC1_MODE_COOL},
|
||||
{climate::CLIMATE_MODE_HEAT, AC1_MODE_HEAT}, {climate::CLIMATE_MODE_DRY, AC1_MODE_DRY},
|
||||
{climate::CLIMATE_MODE_FAN_ONLY, AC1_MODE_FAN},
|
||||
};
|
||||
// A received fan code that is not listed is ignored
|
||||
static constexpr IRCode FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_AUTO, AC1_FAN_AUTO},
|
||||
{climate::CLIMATE_FAN_LOW, AC1_FAN1},
|
||||
{climate::CLIMATE_FAN_MEDIUM, AC1_FAN2},
|
||||
{climate::CLIMATE_FAN_HIGH, AC1_FAN3},
|
||||
};
|
||||
|
||||
void ZHLT01Climate::transmit_state() {
|
||||
uint8_t ir_message[ZHLT01_MESSAGE_LENGTH] = {0};
|
||||
|
||||
@@ -52,46 +70,12 @@ void ZHLT01Climate::transmit_state() {
|
||||
ir_message[7] |= AC1_FAN_SILENT;
|
||||
break;
|
||||
default:
|
||||
switch (this->fan_mode.value_or(climate::CLIMATE_FAN_ON)) {
|
||||
case climate::CLIMATE_FAN_LOW:
|
||||
ir_message[7] |= AC1_FAN1;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_MEDIUM:
|
||||
ir_message[7] |= AC1_FAN2;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_HIGH:
|
||||
ir_message[7] |= AC1_FAN3;
|
||||
break;
|
||||
case climate::CLIMATE_FAN_AUTO:
|
||||
ir_message[7] |= AC1_FAN_AUTO;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
ir_message[7] |= to_ir_code(FANS, this->fan_mode.value_or(climate::CLIMATE_FAN_AUTO), AC1_FAN_AUTO);
|
||||
}
|
||||
|
||||
// Byte 9 : AC Mode | Temperature
|
||||
// -- AC Mode
|
||||
switch (this->mode) {
|
||||
case climate::CLIMATE_MODE_AUTO:
|
||||
case climate::CLIMATE_MODE_HEAT_COOL:
|
||||
ir_message[9] = AC1_MODE_AUTO;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_COOL:
|
||||
ir_message[9] = AC1_MODE_COOL;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT:
|
||||
ir_message[9] = AC1_MODE_HEAT;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_DRY:
|
||||
ir_message[9] = AC1_MODE_DRY;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_FAN_ONLY:
|
||||
ir_message[9] = AC1_MODE_FAN;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
ir_message[9] = to_ir_code(MODES, this->mode, AC1_MODE_AUTO);
|
||||
|
||||
// -- Temperature
|
||||
ir_message[9] |= (uint8_t) (this->target_temperature - 16.0f);
|
||||
@@ -185,28 +169,12 @@ bool ZHLT01Climate::on_receive(remote_base::RemoteReceiveData data) {
|
||||
} else if ((ir_message[7] & 0xE1) == AC1_FAN_SILENT) {
|
||||
this->preset = climate::CLIMATE_PRESET_SLEEP;
|
||||
this->fan_mode = climate::CLIMATE_FAN_LOW;
|
||||
} else if ((ir_message[7] & 0xE1) == AC1_FAN_AUTO) {
|
||||
this->fan_mode = climate::CLIMATE_FAN_AUTO;
|
||||
} else if ((ir_message[7] & 0xE1) == AC1_FAN1) {
|
||||
this->fan_mode = climate::CLIMATE_FAN_LOW;
|
||||
} else if ((ir_message[7] & 0xE1) == AC1_FAN2) {
|
||||
this->fan_mode = climate::CLIMATE_FAN_MEDIUM;
|
||||
} else if ((ir_message[7] & 0xE1) == AC1_FAN3) {
|
||||
this->fan_mode = climate::CLIMATE_FAN_HIGH;
|
||||
} else if (const auto entry = find_ir_code(FANS, ir_message[7] & 0xE1, true)) {
|
||||
this->fan_mode = static_cast<climate::ClimateFanMode>(entry->value);
|
||||
}
|
||||
|
||||
// AC Mode
|
||||
if ((ir_message[9] & 0xE0) == AC1_MODE_COOL) {
|
||||
this->mode = climate::CLIMATE_MODE_COOL;
|
||||
} else if ((ir_message[9] & 0xE0) == AC1_MODE_HEAT) {
|
||||
this->mode = climate::CLIMATE_MODE_HEAT;
|
||||
} else if ((ir_message[9] & 0xE0) == AC1_MODE_DRY) {
|
||||
this->mode = climate::CLIMATE_MODE_DRY;
|
||||
} else if ((ir_message[9] & 0xE0) == AC1_MODE_FAN) {
|
||||
this->mode = climate::CLIMATE_MODE_FAN_ONLY;
|
||||
} else {
|
||||
this->mode = climate::CLIMATE_MODE_AUTO;
|
||||
}
|
||||
this->mode = from_ir_code(MODES, ir_message[9] & 0xE0, climate::CLIMATE_MODE_AUTO);
|
||||
|
||||
// Target Temperature
|
||||
this->target_temperature = (ir_message[9] & 0x1F) + 16.0f;
|
||||
|
||||
@@ -70,7 +70,6 @@
|
||||
#define USE_BUTTON
|
||||
#define USE_CAMERA
|
||||
#define USE_CANBUS_FD
|
||||
#define USE_CC1101_LONG_PACKET
|
||||
#define USE_CLIMATE
|
||||
#define USE_CLIMATE_VISUAL_OVERRIDES
|
||||
#define USE_CONTROLLER_REGISTRY
|
||||
|
||||
@@ -25,9 +25,6 @@ CORE_BENCHMARKS_DIR: Path = Path(root_path) / "tests" / "benchmarks" / "core"
|
||||
# allow benchmarks to compile on the host platform.
|
||||
STUBS_DIR: Path = Path(root_path) / "tests" / "benchmarks" / "stubs"
|
||||
|
||||
# Shared test doubles, reached by -I so only the benchmarks that include them pull in their headers
|
||||
HELPERS_DIR: Path = Path(root_path) / "tests" / "benchmarks" / "helpers"
|
||||
|
||||
BUILD_FLAGS = [
|
||||
"-Os", # match firmware optimization level (detects inlining regressions)
|
||||
"-g", # debug symbols for profiling
|
||||
@@ -35,7 +32,6 @@ BUILD_FLAGS = [
|
||||
"-fdata-sections", # required for dead-code stripping with -Os
|
||||
"-DUSE_BENCHMARK", # disable WarnIfComponentBlockingGuard in finish()
|
||||
f"-I{STUBS_DIR}", # stub headers for ESP32-only components
|
||||
f"-I{HELPERS_DIR}", # shared test doubles such as fake_uart.h
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include "esphome/components/binary_sensor/binary_sensor.h"
|
||||
#include "esphome/components/ld2450/ld2450.h"
|
||||
#include "esphome/components/sensor/sensor.h"
|
||||
#include "fake_uart.h"
|
||||
|
||||
namespace esphome::ld2450::benchmarks {
|
||||
|
||||
using esphome::benchmarks::FakeUART;
|
||||
|
||||
// Inner iteration count to amortize CodSpeed instrumentation overhead.
|
||||
static constexpr int kInnerIterations = 2000;
|
||||
static constexpr size_t FRAME_SIZE = 30;
|
||||
|
||||
// Periodic frames with one moving target at two positions
|
||||
static constexpr uint8_t FRAME_A[FRAME_SIZE] = {0xAA, 0xFF, 0x03, 0x00, 0x0E, 0x03, 0xB1, 0x86, 0x10, 0x00,
|
||||
0x40, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xCC};
|
||||
static constexpr uint8_t FRAME_B[FRAME_SIZE] = {0xAA, 0xFF, 0x03, 0x00, 0x2A, 0x03, 0xC8, 0x86, 0x10, 0x00,
|
||||
0x40, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xCC};
|
||||
|
||||
// --- loop() parsing one periodic frame, no entities attached ---
|
||||
|
||||
static void LD2450_PeriodicFrame(benchmark::State &state) {
|
||||
FakeUART uart;
|
||||
LD2450Component radar;
|
||||
radar.set_uart_parent(&uart);
|
||||
radar.set_link_timeout(60000);
|
||||
// Bring the link up outside the timed loop
|
||||
uart.load(FRAME_A, FRAME_SIZE);
|
||||
radar.loop();
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
uart.load(FRAME_A, FRAME_SIZE);
|
||||
radar.loop();
|
||||
}
|
||||
benchmark::DoNotOptimize(uart.available());
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(LD2450_PeriodicFrame);
|
||||
|
||||
// --- loop() parsing a moving target and publishing its sensors ---
|
||||
|
||||
static void LD2450_PeriodicFrameSensors(benchmark::State &state) {
|
||||
FakeUART uart;
|
||||
LD2450Component radar;
|
||||
radar.set_uart_parent(&uart);
|
||||
radar.set_link_timeout(60000);
|
||||
sensor::Sensor x, y, speed, distance, angle, count;
|
||||
binary_sensor::BinarySensor presence;
|
||||
radar.set_move_x_sensor(0, &x);
|
||||
radar.set_move_y_sensor(0, &y);
|
||||
radar.set_move_speed_sensor(0, &speed);
|
||||
radar.set_move_distance_sensor(0, &distance);
|
||||
radar.set_move_angle_sensor(0, &angle);
|
||||
radar.set_target_count_sensor(&count);
|
||||
radar.set_target_binary_sensor(&presence);
|
||||
uart.load(FRAME_A, FRAME_SIZE);
|
||||
radar.loop();
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
uart.load((i & 1) ? FRAME_B : FRAME_A, FRAME_SIZE);
|
||||
radar.loop();
|
||||
}
|
||||
benchmark::DoNotOptimize(x.state);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(LD2450_PeriodicFrameSensors);
|
||||
|
||||
} // namespace esphome::ld2450::benchmarks
|
||||
@@ -1,2 +0,0 @@
|
||||
sensor:
|
||||
binary_sensor:
|
||||
@@ -1,67 +0,0 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include "esphome/components/modbus/modbus.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "fake_uart.h"
|
||||
|
||||
namespace esphome::modbus::benchmarks {
|
||||
|
||||
using esphome::benchmarks::FakeUART;
|
||||
|
||||
// Inner iteration count to amortize CodSpeed instrumentation overhead.
|
||||
static constexpr int kInnerIterations = 2000;
|
||||
|
||||
static constexpr uint8_t ADDRESS = 1;
|
||||
static constexpr uint8_t REGISTER_COUNT = 10;
|
||||
// Read 10 holding registers from address 0, as an energy meter poll does
|
||||
static constexpr uint8_t REQUEST_PDU[] = {0x03, 0x00, 0x00, 0x00, REGISTER_COUNT};
|
||||
// Address + function + byte count + 20 data bytes + CRC
|
||||
static constexpr size_t RESPONSE_SIZE = 3 + REGISTER_COUNT * 2 + 2;
|
||||
|
||||
class SumDevice : public ModbusClientDevice {
|
||||
public:
|
||||
using ModbusClientDevice::ModbusClientDevice;
|
||||
void on_read_holding_registers(uint16_t start_address, std::span<const uint16_t> registers,
|
||||
ResponseStatus status) override {
|
||||
for (uint16_t value : registers)
|
||||
this->sum += value;
|
||||
}
|
||||
uint32_t sum{0};
|
||||
};
|
||||
|
||||
class NoDelayHub : public ModbusClientHub {
|
||||
protected:
|
||||
// No wait before a send, so every loop() can send the next poll
|
||||
int32_t tx_delay_remaining() override { return 0; }
|
||||
};
|
||||
|
||||
// --- One continuous poll cycle per loop(): receive and CRC check the response, decode it, requeue and resend ---
|
||||
|
||||
static void Modbus_ReadHoldingPollCycle(benchmark::State &state) {
|
||||
// Address 1, function 3, byte count 20, 10 registers; the CRC goes in the last two bytes
|
||||
uint8_t response[RESPONSE_SIZE] = {0x01, 0x03, 0x14, 0x09, 0x1F, 0x00, 0x00, 0x01, 0xF4, 0x00, 0x00, 0x13,
|
||||
0x88, 0x00, 0x32, 0x03, 0xE8, 0x00, 0x00, 0x00, 0x64, 0x12, 0x34};
|
||||
put_le16(&response[RESPONSE_SIZE - 2], crc16(response, RESPONSE_SIZE - 2));
|
||||
|
||||
FakeUART uart;
|
||||
uart.set_baud_rate(9600);
|
||||
NoDelayHub hub;
|
||||
hub.set_uart_parent(&uart);
|
||||
hub.setup();
|
||||
SumDevice device(&hub, ADDRESS);
|
||||
hub.queue_pdu(ADDRESS, REQUEST_PDU, &device, {.continuous = true});
|
||||
// The first loop() sends the poll; every send rewinds the response, so the device answers each one
|
||||
hub.loop();
|
||||
uart.load(response, RESPONSE_SIZE);
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
hub.loop();
|
||||
}
|
||||
benchmark::DoNotOptimize(device.sum);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(Modbus_ReadHoldingPollCycle);
|
||||
|
||||
} // namespace esphome::modbus::benchmarks
|
||||
@@ -1,57 +0,0 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include "esphome/components/uart/uart.h"
|
||||
#include "fake_uart.h"
|
||||
|
||||
namespace esphome::uart::benchmarks {
|
||||
|
||||
using esphome::benchmarks::FakeUART;
|
||||
|
||||
// Inner iteration count to amortize CodSpeed instrumentation overhead.
|
||||
static constexpr int kInnerIterations = 2000;
|
||||
|
||||
// One second of a GPS module's NMEA output
|
||||
static constexpr char NMEA_BURST[] = "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47\r\n"
|
||||
"$GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A\r\n"
|
||||
"$GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39\r\n"
|
||||
"$GPGSV,2,1,08,01,40,083,46,02,17,308,41,12,07,344,39,14,22,228,45*75\r\n"
|
||||
"$GPVTG,054.7,T,034.4,M,005.5,N,010.2,K*48\r\n";
|
||||
|
||||
// --- read_available(): drain a whole NMEA burst through a byte-sum callback ---
|
||||
|
||||
static void UART_ReadAvailable_NmeaBurst(benchmark::State &state) {
|
||||
FakeUART uart;
|
||||
UARTDevice dev(&uart);
|
||||
uint32_t sum = 0;
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
uart.load(reinterpret_cast<const uint8_t *>(NMEA_BURST), sizeof(NMEA_BURST) - 1);
|
||||
dev.read_available([&](uint8_t b) { sum += b; });
|
||||
}
|
||||
benchmark::DoNotOptimize(sum);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(UART_ReadAvailable_NmeaBurst);
|
||||
|
||||
// --- discard_available(): drop a 256 byte backlog ---
|
||||
|
||||
// Two virtual calls per byte, available() and read_byte(): this measures that per-byte call overhead
|
||||
static void UART_DiscardAvailable(benchmark::State &state) {
|
||||
uint8_t backlog[256]{};
|
||||
FakeUART uart;
|
||||
UARTDevice dev(&uart);
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
uart.load(backlog, sizeof(backlog));
|
||||
dev.discard_available();
|
||||
}
|
||||
benchmark::DoNotOptimize(uart.available());
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(UART_DiscardAvailable);
|
||||
|
||||
} // namespace esphome::uart::benchmarks
|
||||
@@ -1,93 +0,0 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include "esphome/core/frame_reader.h"
|
||||
#include "esphome/core/line_reader.h"
|
||||
|
||||
namespace esphome::benchmarks {
|
||||
|
||||
// Inner iteration count to amortize CodSpeed instrumentation overhead.
|
||||
static constexpr int kInnerIterations = 2000;
|
||||
|
||||
static constexpr char NMEA_GGA[] = "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47\r\n";
|
||||
|
||||
// A 30 byte frame with a 4 byte header and a 2 byte tail
|
||||
static constexpr uint8_t FRAME_30[30] = {0xAA, 0xFF, 0x03, 0x00, 0x0E, 0x03, 0xB1, 0x86, 0x10, 0x00,
|
||||
0x40, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xCC};
|
||||
|
||||
// Four A02YYUW distance frames among noise bytes; the doubled 0xFF fails the checksum and resyncs onto the
|
||||
// frame behind it. Ends on a whole frame, so every pass starts clean
|
||||
static constexpr uint8_t ULTRASONIC_NOISY[] = {0x12, 0xFF, 0x07, 0xA1, 0xA7, 0x34, 0xFF, 0xFF, 0x07, 0xA1, 0xA7,
|
||||
0x00, 0xFF, 0x07, 0xA1, 0xA7, 0x56, 0xFF, 0x07, 0xA1, 0xA7};
|
||||
|
||||
// --- LineReader: one GGA sentence fed byte by byte ---
|
||||
|
||||
static void LineReader_NmeaLine(benchmark::State &state) {
|
||||
LineReader<96> reader;
|
||||
const auto *bytes = reinterpret_cast<const uint8_t *>(NMEA_GGA);
|
||||
size_t total = 0;
|
||||
|
||||
for (auto _ : state) {
|
||||
benchmark::DoNotOptimize(bytes);
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
for (size_t j = 0; j < sizeof(NMEA_GGA) - 1; j++) {
|
||||
size_t len;
|
||||
if (reader.feed(bytes[j], len) != nullptr)
|
||||
total += len;
|
||||
}
|
||||
}
|
||||
benchmark::DoNotOptimize(total);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(LineReader_NmeaLine);
|
||||
|
||||
// --- FrameReader: a 30 byte frame behind a 4 byte header ---
|
||||
|
||||
static void FrameReader_30ByteFrame(benchmark::State &state) {
|
||||
FrameReader<sizeof(FRAME_30), 0xAA, 0xFF, 0x03, 0x00> reader;
|
||||
const uint8_t *bytes = FRAME_30;
|
||||
uint32_t frames = 0;
|
||||
|
||||
for (auto _ : state) {
|
||||
benchmark::DoNotOptimize(bytes);
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
for (size_t j = 0; j < sizeof(FRAME_30); j++) {
|
||||
if (reader.feed(bytes[j]) != nullptr)
|
||||
frames++;
|
||||
}
|
||||
}
|
||||
benchmark::DoNotOptimize(frames);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(FrameReader_30ByteFrame);
|
||||
|
||||
// --- FrameReader: 4 byte checksummed frames, skipping noise and resyncing on a bad checksum ---
|
||||
|
||||
static void FrameReader_UltrasonicNoisy(benchmark::State &state) {
|
||||
FrameReader<4, 0xFF> reader;
|
||||
const uint8_t *bytes = ULTRASONIC_NOISY;
|
||||
uint32_t frames = 0;
|
||||
|
||||
for (auto _ : state) {
|
||||
benchmark::DoNotOptimize(bytes);
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
for (size_t j = 0; j < sizeof(ULTRASONIC_NOISY); j++) {
|
||||
const uint8_t *frame = reader.feed(bytes[j]);
|
||||
if (frame == nullptr)
|
||||
continue;
|
||||
if (frame[3] == static_cast<uint8_t>(frame[0] + frame[1] + frame[2])) {
|
||||
frames++;
|
||||
} else {
|
||||
reader.resync();
|
||||
}
|
||||
}
|
||||
}
|
||||
benchmark::DoNotOptimize(frames);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(FrameReader_UltrasonicNoisy);
|
||||
|
||||
} // namespace esphome::benchmarks
|
||||
@@ -1,44 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
#include "esphome/components/uart/uart_component.h"
|
||||
|
||||
namespace esphome::benchmarks {
|
||||
|
||||
// Serves a fixed byte stream as received data. Every write rewinds it, so the stream answers each request.
|
||||
class FakeUART : public uart::UARTComponent {
|
||||
public:
|
||||
void load(const uint8_t *data, size_t len) {
|
||||
this->data_ = data;
|
||||
this->len_ = len;
|
||||
this->pos_ = 0;
|
||||
}
|
||||
void rewind() { this->pos_ = 0; }
|
||||
|
||||
void write_array(const uint8_t *data, size_t len) override { this->rewind(); }
|
||||
bool peek_byte(uint8_t *data) override {
|
||||
if (this->pos_ >= this->len_)
|
||||
return false;
|
||||
*data = this->data_[this->pos_];
|
||||
return true;
|
||||
}
|
||||
bool read_array(uint8_t *data, size_t len) override {
|
||||
if (len > this->len_ - this->pos_)
|
||||
return false;
|
||||
std::memcpy(data, this->data_ + this->pos_, len);
|
||||
this->pos_ += len;
|
||||
return true;
|
||||
}
|
||||
size_t available() override { return this->len_ - this->pos_; }
|
||||
uart::UARTFlushResult flush() override { return uart::UARTFlushResult::UART_FLUSH_RESULT_ASSUMED_SUCCESS; }
|
||||
void check_logger_conflict() override {}
|
||||
|
||||
protected:
|
||||
const uint8_t *data_{nullptr};
|
||||
size_t len_{0};
|
||||
size_t pos_{0};
|
||||
};
|
||||
|
||||
} // namespace esphome::benchmarks
|
||||
@@ -1,62 +0,0 @@
|
||||
"""Tests for cc1101 packet_length validation."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.components.cc1101 import _validate_packet_mode
|
||||
import esphome.config_validation as cv
|
||||
from esphome.core import Lambda
|
||||
|
||||
LENGTH_LAMBDA = Lambda("return x.size() < 3 ? 0 : x[2] + 12;")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config",
|
||||
[
|
||||
{"packet_mode": True, "gdo0_pin": 2, "packet_length": LENGTH_LAMBDA},
|
||||
{"packet_mode": True, "gdo0_pin": 2, "packet_length": 1024},
|
||||
{"packet_mode": True, "gdo0_pin": 2, "packet_length": 64, "crc_enable": True},
|
||||
{"packet_mode": False, "packet_length": 200, "crc_enable": True},
|
||||
],
|
||||
)
|
||||
def test_packet_length_valid(config: dict[str, Any]) -> None:
|
||||
"""Fixed lengths, a lambda, and CRC on packets that fit the FIFO are accepted."""
|
||||
assert _validate_packet_mode(config) is config
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("config", "message"),
|
||||
[
|
||||
(
|
||||
{"packet_mode": False, "packet_length": LENGTH_LAMBDA},
|
||||
"packet_mode is required when packet_length is a lambda",
|
||||
),
|
||||
(
|
||||
{"packet_mode": True, "gdo0_pin": 2},
|
||||
"packet_length is required when packet_mode is enabled",
|
||||
),
|
||||
(
|
||||
{
|
||||
"packet_mode": True,
|
||||
"gdo0_pin": 2,
|
||||
"packet_length": 65,
|
||||
"crc_enable": True,
|
||||
},
|
||||
"crc_enable is not supported",
|
||||
),
|
||||
(
|
||||
{
|
||||
"packet_mode": True,
|
||||
"gdo0_pin": 2,
|
||||
"packet_length": LENGTH_LAMBDA,
|
||||
"crc_enable": True,
|
||||
},
|
||||
"crc_enable is not supported",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_packet_length_invalid(config: dict[str, Any], message: str) -> None:
|
||||
"""Invalid packet_length combinations are rejected with a clear message."""
|
||||
with pytest.raises(cv.Invalid, match=message):
|
||||
_validate_packet_mode(config)
|
||||
@@ -1,18 +0,0 @@
|
||||
"""Validate the sync-word limit before firmware generation."""
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.components.sx126x import CONF_SYNC_VALUE, CONFIG_SCHEMA
|
||||
import esphome.config_validation as cv
|
||||
|
||||
|
||||
@pytest.mark.parametrize("size", [0, 1, 2, 8])
|
||||
def test_supported_sync_lengths(size: int) -> None:
|
||||
value = [0x14] * size
|
||||
assert CONFIG_SCHEMA.schema[CONF_SYNC_VALUE](value) == value
|
||||
|
||||
|
||||
@pytest.mark.parametrize("size", [9, 256])
|
||||
def test_oversized_sync_word(size: int) -> None:
|
||||
with pytest.raises(cv.Invalid, match="at most 8"):
|
||||
CONFIG_SCHEMA.schema[CONF_SYNC_VALUE]([0x14] * size)
|
||||
@@ -1,26 +0,0 @@
|
||||
packages:
|
||||
spi: !include ../../test_build_components/common/spi/esp32-idf.yaml
|
||||
|
||||
cc1101:
|
||||
# Above 255 bytes: infinite length mode, then fixed for the remainder
|
||||
- id: transceiver_long_fixed
|
||||
cs_pin: GPIO5
|
||||
gdo0_pin: GPIO4
|
||||
packet_mode: true
|
||||
packet_length: 1024
|
||||
on_packet:
|
||||
then:
|
||||
- lambda: 'ESP_LOGD("cc1101", "long packet %u bytes", x.size());'
|
||||
|
||||
# Length taken from the packet header
|
||||
- id: transceiver_long_lambda
|
||||
cs_pin: GPIO15
|
||||
gdo0_pin: GPIO2
|
||||
packet_mode: true
|
||||
packet_length: !lambda |-
|
||||
if (x.size() < 3) return 0;
|
||||
if (x[0] != 0x54) return -1;
|
||||
return x[2] + 12;
|
||||
on_packet:
|
||||
then:
|
||||
- lambda: 'ESP_LOGD("cc1101", "lambda packet %u bytes rssi %.1f", x.size(), rssi);'
|
||||
@@ -1,24 +0,0 @@
|
||||
packages:
|
||||
spi: !include ../../test_build_components/common/spi/rp2040-ard.yaml
|
||||
|
||||
cc1101:
|
||||
- id: transceiver_long_fixed
|
||||
cs_pin: GPIO5
|
||||
gdo0_pin: GPIO4
|
||||
packet_mode: true
|
||||
packet_length: 1024
|
||||
on_packet:
|
||||
then:
|
||||
- lambda: 'ESP_LOGD("cc1101", "long packet %u bytes", x.size());'
|
||||
|
||||
- id: transceiver_long_lambda
|
||||
cs_pin: GPIO15
|
||||
gdo0_pin: GPIO2
|
||||
packet_mode: true
|
||||
packet_length: !lambda |-
|
||||
if (x.size() < 3) return 0;
|
||||
if (x[0] != 0x54) return -1;
|
||||
return x[2] + 12;
|
||||
on_packet:
|
||||
then:
|
||||
- lambda: 'ESP_LOGD("cc1101", "lambda packet %u bytes rssi %.1f", x.size(), rssi);'
|
||||
@@ -1,7 +0,0 @@
|
||||
substitutions:
|
||||
cs_pin: GPIO5
|
||||
gdo0_pin: GPIO4
|
||||
|
||||
packages:
|
||||
spi: !include ../../test_build_components/common/spi/rp2040-ard.yaml
|
||||
cc1101: !include common.yaml
|
||||
@@ -0,0 +1,43 @@
|
||||
#include <gtest/gtest.h>
|
||||
#include "esphome/components/climate_ir/climate_ir.h"
|
||||
|
||||
namespace esphome::climate_ir::testing {
|
||||
|
||||
static constexpr IRCode FANS[] PROGMEM = {
|
||||
{climate::CLIMATE_FAN_AUTO, 0x10},
|
||||
{climate::CLIMATE_FAN_LOW, 0x20},
|
||||
{climate::CLIMATE_FAN_HIGH, 0x30},
|
||||
};
|
||||
|
||||
TEST(ClimateIRCodeTest, FindByValue) {
|
||||
const auto entry = find_ir_code(FANS, climate::CLIMATE_FAN_LOW, false);
|
||||
ASSERT_TRUE(entry.has_value());
|
||||
EXPECT_EQ(entry->value, climate::CLIMATE_FAN_LOW);
|
||||
EXPECT_EQ(entry->code, 0x20);
|
||||
}
|
||||
|
||||
TEST(ClimateIRCodeTest, FindByCode) {
|
||||
const auto entry = find_ir_code(FANS, 0x30, true);
|
||||
ASSERT_TRUE(entry.has_value());
|
||||
EXPECT_EQ(entry->value, climate::CLIMATE_FAN_HIGH);
|
||||
}
|
||||
|
||||
TEST(ClimateIRCodeTest, FindMissing) {
|
||||
EXPECT_FALSE(find_ir_code(FANS, climate::CLIMATE_FAN_MEDIUM, false).has_value());
|
||||
// A code that is also a listed value must not match when looking up codes
|
||||
EXPECT_FALSE(find_ir_code(FANS, climate::CLIMATE_FAN_LOW, true).has_value());
|
||||
}
|
||||
|
||||
TEST(ClimateIRCodeTest, ToCode) {
|
||||
EXPECT_EQ(to_ir_code(FANS, climate::CLIMATE_FAN_HIGH, 0x00), 0x30);
|
||||
EXPECT_EQ(to_ir_code(FANS, climate::CLIMATE_FAN_MEDIUM, 0x00), 0x00);
|
||||
}
|
||||
|
||||
TEST(ClimateIRCodeTest, FromCode) {
|
||||
EXPECT_EQ(from_ir_code(FANS, 0x20, climate::CLIMATE_FAN_AUTO), climate::CLIMATE_FAN_LOW);
|
||||
EXPECT_EQ(from_ir_code(FANS, 0x99, climate::CLIMATE_FAN_AUTO), climate::CLIMATE_FAN_AUTO);
|
||||
// The current state as the fallback leaves it unchanged on an unknown code
|
||||
EXPECT_EQ(from_ir_code(FANS, 0x99, climate::CLIMATE_FAN_MEDIUM), climate::CLIMATE_FAN_MEDIUM);
|
||||
}
|
||||
|
||||
} // namespace esphome::climate_ir::testing
|
||||
@@ -20,14 +20,7 @@ class FakePin final : public GPIOPin {
|
||||
bool level{false};
|
||||
};
|
||||
|
||||
// Fills a 16-bit register read: the firmware check code read gets a valid code, other registers zeros.
|
||||
inline void answer_setup_read(const uint8_t *data, size_t size, uint8_t *out, size_t out_size) {
|
||||
std::memset(out, 0, out_size);
|
||||
if (size == 2 && encode_uint16(data[0], data[1]) == cstxxx::REG_FW_CHECK_CODE && out_size == 4)
|
||||
out[2] = out[3] = 0xCA;
|
||||
}
|
||||
|
||||
// Answers the 8-bit status read with a set report and 16-bit setup reads through answer_setup_read().
|
||||
// Answers the 8-bit status read with a set report and 16-bit setup reads with zeros.
|
||||
class StatusBus final : public i2c::I2CBus {
|
||||
public:
|
||||
std::array<uint8_t, 28> status{};
|
||||
@@ -42,7 +35,7 @@ class StatusBus final : public i2c::I2CBus {
|
||||
if (size == 1 && data[0] == CST226_REG_STATUS) {
|
||||
std::memcpy(out, this->status.data(), std::min(out_size, this->status.size()));
|
||||
} else {
|
||||
answer_setup_read(data, size, out, out_size);
|
||||
std::memset(out, 0, out_size);
|
||||
}
|
||||
return i2c::ERROR_OK;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
#include "esphome/components/cst226/touchscreen/cst226_touchscreen.h"
|
||||
#include "../common.h"
|
||||
|
||||
@@ -17,45 +14,6 @@ TEST(CST226TouchscreenTest, SetupCompletes) {
|
||||
EXPECT_FALSE(hub.is_failed());
|
||||
}
|
||||
|
||||
// Records the writes that carry no read, and answers reads through answer_setup_read().
|
||||
class WriteLogBus final : public i2c::I2CBus {
|
||||
public:
|
||||
std::vector<std::vector<uint8_t>> writes;
|
||||
bool bad_check_code{false};
|
||||
|
||||
i2c::ErrorCode write_readv(uint8_t address, const uint8_t *data, size_t size, uint8_t *out,
|
||||
size_t out_size) override {
|
||||
if (out_size == 0) {
|
||||
this->writes.emplace_back(data, data + size);
|
||||
} else {
|
||||
answer_setup_read(data, size, out, out_size);
|
||||
if (this->bad_check_code)
|
||||
std::memset(out, 0, out_size);
|
||||
}
|
||||
return i2c::ERROR_OK;
|
||||
}
|
||||
};
|
||||
|
||||
TEST(CST226TouchscreenTest, SetupEntersCommandModeAndLeavesIt) {
|
||||
WriteLogBus bus;
|
||||
CST226Touchscreen hub;
|
||||
hub.set_i2c_bus(&bus);
|
||||
hub.setup();
|
||||
ASSERT_GE(bus.writes.size(), 2u);
|
||||
EXPECT_EQ(bus.writes.front(), (std::vector<uint8_t>{0xD1, 0x01}));
|
||||
EXPECT_EQ(bus.writes.back(), (std::vector<uint8_t>{0xD1, 0x09}));
|
||||
EXPECT_FALSE(hub.is_failed());
|
||||
}
|
||||
|
||||
TEST(CST226TouchscreenTest, SetupFailsOnAWrongCheckCode) {
|
||||
WriteLogBus bus;
|
||||
bus.bad_check_code = true;
|
||||
CST226Touchscreen hub;
|
||||
hub.set_i2c_bus(&bus);
|
||||
hub.setup();
|
||||
EXPECT_TRUE(hub.is_failed());
|
||||
}
|
||||
|
||||
TEST(CST226TouchscreenTest, SetupFailsWithoutTheChip) {
|
||||
StatusBus bus;
|
||||
bus.fail = true;
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "esphome/components/cstxxx/cstxxx.h"
|
||||
|
||||
namespace esphome::cstxxx::testing {
|
||||
|
||||
TEST(CSTxxxDecodeTouch, FirstRecordStartsTheReport) {
|
||||
const uint8_t report[report_size(1)] = {0x16, 0x12, 0x34, 0x56, 0x78, 0x01, SYNC_BYTE};
|
||||
auto touch = decode_touch(report, 0);
|
||||
EXPECT_EQ(touch.id, 1);
|
||||
EXPECT_EQ(touch.event, 0x06);
|
||||
EXPECT_EQ(touch.x, 0x125);
|
||||
EXPECT_EQ(touch.y, 0x346);
|
||||
EXPECT_EQ(touch.z, 0x78);
|
||||
}
|
||||
|
||||
TEST(CSTxxxDecodeTouch, LaterRecordsSkipTheStatusBytes) {
|
||||
uint8_t report[report_size(3)]{};
|
||||
report[FINGER_COUNT_IDX] = 3;
|
||||
report[SYNC_IDX] = SYNC_BYTE;
|
||||
const uint8_t third[5] = {0x26, 0xFF, 0x00, 0xF0, 0x05};
|
||||
std::copy(third, third + 5, report + 12);
|
||||
auto touch = decode_touch(report, 2);
|
||||
EXPECT_EQ(touch.id, 2);
|
||||
EXPECT_EQ(touch.x, 0xFFF);
|
||||
EXPECT_EQ(touch.y, 0x000);
|
||||
EXPECT_EQ(touch.z, 5);
|
||||
}
|
||||
|
||||
} // namespace esphome::cstxxx::testing
|
||||
@@ -1,16 +0,0 @@
|
||||
"""Enable real logger callbacks for radio reentrancy regression tests."""
|
||||
|
||||
import esphome.codegen as cg
|
||||
from esphome.components.logger import request_log_listener
|
||||
from esphome.types import ConfigType
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
request_log_listener()
|
||||
# The tests build a software SPI bus in C++, which no configured bus asks for
|
||||
cg.add_define("USE_SPI_SOFTWARE")
|
||||
|
||||
manifest.multi_conf = False
|
||||
manifest.to_code = to_code
|
||||
@@ -7,22 +7,3 @@ button:
|
||||
cold: true
|
||||
- sx126x.set_mode_sleep:
|
||||
cold: !lambda return id(sx126x_my_number).state > 1;
|
||||
|
||||
- platform: template
|
||||
name: "SX126x Async Send or Cancel"
|
||||
on_press:
|
||||
- lambda: |-
|
||||
class Listener : public sx126x::SX126xTransmitListener {
|
||||
public:
|
||||
void on_transmit_complete(sx126x::SX126xError result) override {
|
||||
ESP_LOGD("sx126x_test", "Async completion: %d", static_cast<int>(result));
|
||||
}
|
||||
};
|
||||
static Listener listener;
|
||||
if (id(sx126x_radio).is_transmitting()) {
|
||||
id(sx126x_radio).cancel_transmit_async(&listener);
|
||||
} else {
|
||||
const uint8_t data[] = {0x11, 0x22, 0x33};
|
||||
auto result = id(sx126x_radio).start_transmit_async(&listener, data, sizeof(data), 4000);
|
||||
ESP_LOGD("sx126x_test", "Async admission: %d", static_cast<int>(result));
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
sx126x:
|
||||
id: sx126x_radio
|
||||
dio1_pin: ${dio1_pin}
|
||||
cs_pin: ${cs_pin}
|
||||
busy_pin: ${busy_pin}
|
||||
|
||||
@@ -1,643 +0,0 @@
|
||||
#include "sx126x_test_helpers.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include <tuple>
|
||||
|
||||
namespace esphome::sx126x::testing {
|
||||
|
||||
class TransmitListener : public SX126xTransmitListener {
|
||||
public:
|
||||
void on_transmit_complete(SX126xError result) override {
|
||||
this->results.push_back(result);
|
||||
if (this->on_complete) {
|
||||
this->on_complete(result);
|
||||
}
|
||||
}
|
||||
std::vector<SX126xError> results;
|
||||
std::function<void(SX126xError)> on_complete;
|
||||
};
|
||||
|
||||
class ReceiveCallback : public SX126xListener {
|
||||
public:
|
||||
void on_packet(const std::vector<uint8_t> &packet, float rssi, float snr) override { this->on_packet_callback(); }
|
||||
std::function<void()> on_packet_callback;
|
||||
};
|
||||
|
||||
class SX126xAsyncModes : public ::testing::TestWithParam<std::tuple<bool, bool, bool>> {};
|
||||
|
||||
TEST_P(SX126xAsyncModes, ReturnsBeforeCompletionAndRestoresMode) {
|
||||
const auto [lora, rx, fixed] = GetParam();
|
||||
RadioHardware hw;
|
||||
TransmitListener listener;
|
||||
hw.configure(lora, rx, fixed);
|
||||
hw.auto_complete = false;
|
||||
hw.clear_trace();
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&listener, hw.packet, 1234), SX126xError::SX126X_ERROR_NONE);
|
||||
EXPECT_TRUE(hw.radio.is_transmitting());
|
||||
EXPECT_TRUE(listener.results.empty());
|
||||
EXPECT_EQ(hw.sends, 1u);
|
||||
const auto &tx = hw.transactions.back();
|
||||
EXPECT_EQ(tx, (std::vector<uint8_t>{RADIO_SET_TX, 0x01, 0x34, 0x80}));
|
||||
const auto fifo = std::find_if(hw.transactions.begin(), hw.transactions.end(),
|
||||
[](const auto &cmd) { return cmd[0] == RADIO_WRITE_BUFFER; });
|
||||
ASSERT_NE(fifo, hw.transactions.end());
|
||||
EXPECT_EQ(*fifo, (std::vector<uint8_t>{RADIO_WRITE_BUFFER, 0, 0x11, 0x22, 0x33}));
|
||||
hw.packet.assign(3, 0x99); // The driver must not retain the caller's payload.
|
||||
hw.irq = IRQ_TX_DONE;
|
||||
listener.on_complete = [&](SX126xError result) {
|
||||
EXPECT_FALSE(hw.radio.is_transmitting());
|
||||
EXPECT_EQ(hw.receiving, rx);
|
||||
EXPECT_TRUE(hw.cs.level);
|
||||
};
|
||||
hw.radio.loop();
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(listener.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_NONE}));
|
||||
}
|
||||
|
||||
TEST_P(SX126xAsyncModes, RejectsEveryFailedStartWithoutCallbackAndCanRetry) {
|
||||
const auto [lora, rx, fixed] = GetParam();
|
||||
RadioHardware reference;
|
||||
TransmitListener listener;
|
||||
reference.configure(lora, rx, fixed);
|
||||
reference.clear_trace();
|
||||
ASSERT_EQ(reference.radio.start_transmit_async(&listener, reference.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
const size_t count = reference.transactions.size();
|
||||
reference.radio.cancel_transmit_async(&listener);
|
||||
for (size_t fault = 1; fault <= count; fault++) {
|
||||
SCOPED_TRACE(fault);
|
||||
RadioHardware hw;
|
||||
TransmitListener result;
|
||||
hw.configure(lora, rx, fixed);
|
||||
hw.clear_trace();
|
||||
hw.fail_at = fault;
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&result, hw.packet), SX126xError::SX126X_ERROR_BUSY_TIMEOUT);
|
||||
EXPECT_TRUE(result.results.empty());
|
||||
EXPECT_FALSE(hw.radio.is_transmitting());
|
||||
EXPECT_TRUE(hw.cs.level);
|
||||
EXPECT_TRUE(hw.transactions[fault - 1].empty());
|
||||
EXPECT_EQ(hw.sends, 0u);
|
||||
EXPECT_EQ(hw.receiving, rx); // One-shot fault permits failed-start cleanup.
|
||||
hw.clear_trace();
|
||||
hw.radio.configure();
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&result, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(result.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_NONE}));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_P(SX126xAsyncModes, ReportsEveryCompletionAndCleanupFailureOnce) {
|
||||
const auto [lora, rx, fixed] = GetParam();
|
||||
RadioHardware reference;
|
||||
TransmitListener listener;
|
||||
reference.configure(lora, rx, fixed);
|
||||
ASSERT_EQ(reference.radio.start_transmit_async(&listener, reference.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
reference.clear_trace();
|
||||
reference.radio.loop();
|
||||
const size_t count = reference.transactions.size();
|
||||
for (size_t fault = 1; fault <= count; fault++) {
|
||||
SCOPED_TRACE(fault);
|
||||
RadioHardware hw;
|
||||
TransmitListener result;
|
||||
hw.configure(lora, rx, fixed);
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&result, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
hw.clear_trace();
|
||||
hw.fail_at = fault;
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(result.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_BUSY_TIMEOUT}));
|
||||
EXPECT_TRUE(hw.transactions[fault - 1].empty());
|
||||
EXPECT_TRUE(hw.cs.level);
|
||||
EXPECT_FALSE(hw.radio.is_transmitting());
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(result.results.size(), 1u);
|
||||
hw.clear_trace();
|
||||
hw.radio.configure();
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&result, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
hw.radio.loop();
|
||||
ASSERT_EQ(result.results.size(), 2u);
|
||||
EXPECT_EQ(result.results.back(), SX126xError::SX126X_ERROR_NONE);
|
||||
EXPECT_EQ(hw.receiving, rx);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_P(SX126xAsyncModes, BlockingAndAsyncUseTheSameCommandSequence) {
|
||||
const auto [lora, rx, fixed] = GetParam();
|
||||
RadioHardware blocking, async;
|
||||
TransmitListener listener;
|
||||
blocking.configure(lora, rx, fixed);
|
||||
async.configure(lora, rx, fixed);
|
||||
blocking.clear_trace();
|
||||
async.clear_trace();
|
||||
ASSERT_EQ(blocking.radio.transmit_packet(blocking.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
ASSERT_EQ(async.radio.start_transmit_async(&listener, async.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
async.radio.loop();
|
||||
EXPECT_EQ(blocking.transactions, async.transactions);
|
||||
EXPECT_EQ(listener.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_NONE}));
|
||||
EXPECT_EQ(blocking.receiving, async.receiving);
|
||||
}
|
||||
|
||||
INSTANTIATE_TEST_SUITE_P(LoRaAndFSKWithRxOrSleepAndFixedOrVariablePayload, SX126xAsyncModes,
|
||||
::testing::Combine(::testing::Bool(), ::testing::Bool(), ::testing::Bool()));
|
||||
|
||||
TEST(SX126xAsync, SoftwareDeadlineWithoutDioAndCachedTickBeforeStart) {
|
||||
RadioHardware hw;
|
||||
TransmitListener listener;
|
||||
hw.configure(true, true);
|
||||
hw.auto_complete = false;
|
||||
hw.dio.internal = true;
|
||||
const uint32_t before = millis();
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&listener, hw.packet, 50), SX126xError::SX126X_ERROR_NONE);
|
||||
const uint32_t after = millis();
|
||||
{
|
||||
LoopBlockingGuard clock{nullptr, nullptr, before - 1};
|
||||
hw.radio.call();
|
||||
EXPECT_TRUE(listener.results.empty()); // No unsigned underflow on the admitting loop tick.
|
||||
}
|
||||
{
|
||||
LoopBlockingGuard clock{nullptr, nullptr, after + 51};
|
||||
hw.radio.call(); // Still enabled despite no IRQ or ISR edge.
|
||||
}
|
||||
EXPECT_EQ(listener.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_TIMEOUT}));
|
||||
EXPECT_TRUE(hw.receiving);
|
||||
EXPECT_FALSE(hw.radio.is_transmitting());
|
||||
}
|
||||
|
||||
TEST(SX126xAsync, UnrelatedIrqIsNotSuccessAndTimeoutWinsOverTxDone) {
|
||||
RadioHardware hw;
|
||||
TransmitListener listener;
|
||||
hw.configure(true, true);
|
||||
hw.auto_complete = false;
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
{
|
||||
LoopBlockingGuard clock{nullptr, nullptr, millis()};
|
||||
hw.radio.loop();
|
||||
}
|
||||
EXPECT_TRUE(listener.results.empty());
|
||||
hw.irq = IRQ_TX_DONE | IRQ_RX_TX_TIMEOUT;
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(listener.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_TIMEOUT}));
|
||||
}
|
||||
|
||||
TEST(SX126xAsync, CancelRequiresOwnerAndCompletesSynchronouslyOnce) {
|
||||
RadioHardware hw;
|
||||
TransmitListener listener, other;
|
||||
hw.configure(true, true);
|
||||
hw.auto_complete = false;
|
||||
EXPECT_FALSE(hw.radio.cancel_transmit_async(&listener));
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
EXPECT_FALSE(hw.radio.cancel_transmit_async(nullptr));
|
||||
EXPECT_FALSE(hw.radio.cancel_transmit_async(&other));
|
||||
EXPECT_TRUE(hw.radio.cancel_transmit_async(&listener));
|
||||
EXPECT_EQ(listener.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_CANCELLED}));
|
||||
EXPECT_FALSE(hw.radio.cancel_transmit_async(&listener));
|
||||
hw.irq = IRQ_TX_DONE; // A late IRQ cannot deliver a second completion.
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(listener.results.size(), 1u);
|
||||
EXPECT_TRUE(hw.receiving);
|
||||
hw.irq = IRQ_TX_DONE; // Also cleared before a new send starts.
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&other, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
{
|
||||
LoopBlockingGuard clock{nullptr, nullptr, millis()};
|
||||
hw.radio.loop();
|
||||
}
|
||||
EXPECT_TRUE(other.results.empty());
|
||||
EXPECT_TRUE(hw.radio.cancel_transmit_async(&other));
|
||||
}
|
||||
|
||||
TEST(SX126xAsync, CompletionCallbackCanStartNextSend) {
|
||||
RadioHardware hw;
|
||||
TransmitListener first, second;
|
||||
hw.configure(true, true);
|
||||
hw.auto_complete = false;
|
||||
first.on_complete = [&](SX126xError result) {
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&second, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
};
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&first, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
hw.irq = IRQ_TX_DONE;
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(first.results.size(), 1u);
|
||||
EXPECT_TRUE(hw.radio.is_transmitting());
|
||||
EXPECT_TRUE(second.results.empty());
|
||||
hw.irq = IRQ_TX_DONE;
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(second.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_NONE}));
|
||||
}
|
||||
|
||||
static void expect_conflicting_calls_rejected(RadioHardware &hw, TransmitListener &listener) {
|
||||
const size_t count = hw.transactions.size();
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_BUSY);
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_BUSY);
|
||||
hw.radio.set_mode_rx();
|
||||
hw.radio.set_mode_tx();
|
||||
hw.radio.set_mode_standby(STDBY_XOSC);
|
||||
hw.radio.set_mode_sleep(true);
|
||||
hw.radio.configure();
|
||||
hw.radio.run_image_cal();
|
||||
EXPECT_EQ(hw.transactions.size(), count);
|
||||
}
|
||||
|
||||
TEST(SX126xAsync, PendingReceiveRejectsAdmissionWithoutDispatchOrAcknowledgment) {
|
||||
RadioHardware hw;
|
||||
TransmitListener listener;
|
||||
PacketListener receiver;
|
||||
hw.configure(true, true);
|
||||
hw.radio.register_listener(&receiver);
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_BUSY);
|
||||
EXPECT_TRUE(receiver.packets.empty());
|
||||
EXPECT_TRUE(listener.results.empty());
|
||||
EXPECT_EQ(hw.irq, IRQ_RX_DONE);
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(receiver.packets.size(), 1u);
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
expect_conflicting_calls_rejected(hw, listener);
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(listener.results.size(), 1u);
|
||||
}
|
||||
|
||||
TEST(SX126xAsync, ValidatesReadinessPayloadAndTimeoutWithoutSpi) {
|
||||
RadioHardware hw;
|
||||
TransmitListener listener;
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
EXPECT_TRUE(hw.transactions.empty());
|
||||
hw.configure(true, true, true);
|
||||
hw.clear_trace();
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(nullptr, hw.packet), SX126xError::SX126X_ERROR_INVALID_PARAMS);
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&listener, nullptr, 3), SX126xError::SX126X_ERROR_INVALID_PARAMS);
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet.data(), 0), SX126xError::SX126X_ERROR_INVALID_PARAMS);
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet.data(), 2), SX126xError::SX126X_ERROR_INVALID_PARAMS);
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet.data(), 256), SX126xError::SX126X_ERROR_INVALID_PARAMS);
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet, 0), SX126xError::SX126X_ERROR_INVALID_PARAMS);
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet, 262144), SX126xError::SX126X_ERROR_INVALID_PARAMS);
|
||||
EXPECT_TRUE(hw.transactions.empty());
|
||||
EXPECT_TRUE(listener.results.empty());
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&listener, hw.packet, 262143), SX126xError::SX126X_ERROR_NONE);
|
||||
EXPECT_EQ(hw.transactions.back(), (std::vector<uint8_t>{RADIO_SET_TX, 0xFF, 0xFF, 0xC0}));
|
||||
hw.radio.loop();
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&listener, hw.packet, 1), SX126xError::SX126X_ERROR_NONE);
|
||||
EXPECT_EQ(hw.transactions.back(), (std::vector<uint8_t>{RADIO_SET_TX, 0, 0, 64}));
|
||||
hw.radio.loop();
|
||||
}
|
||||
|
||||
TEST(SX126xAsync, PersistentBusyReportsFailedCleanupAndAllowsLaterRecovery) {
|
||||
RadioHardware hw;
|
||||
TransmitListener listener;
|
||||
hw.configure(true, true);
|
||||
hw.auto_complete = false;
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
hw.busy.on_read = []() { return true; };
|
||||
ASSERT_TRUE(hw.radio.cancel_transmit_async(&listener));
|
||||
EXPECT_EQ(listener.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_BUSY_TIMEOUT}));
|
||||
EXPECT_FALSE(hw.radio.is_transmitting());
|
||||
EXPECT_TRUE(hw.radio.status_has_warning());
|
||||
EXPECT_TRUE(hw.cs.level);
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
EXPECT_EQ(listener.results.size(), 1u); // Failed admission never invokes completion.
|
||||
hw.busy.on_read = []() { return false; };
|
||||
hw.radio.configure();
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
hw.irq = IRQ_TX_DONE;
|
||||
hw.radio.loop();
|
||||
ASSERT_EQ(listener.results.size(), 2u);
|
||||
EXPECT_EQ(listener.results.back(), SX126xError::SX126X_ERROR_NONE);
|
||||
EXPECT_TRUE(hw.receiving);
|
||||
EXPECT_FALSE(hw.radio.status_has_warning());
|
||||
}
|
||||
|
||||
TEST(SX126xAsync, CancellationCallbackMayStartAnotherSend) {
|
||||
RadioHardware hw;
|
||||
TransmitListener first, second;
|
||||
hw.configure(true, true);
|
||||
hw.auto_complete = false;
|
||||
first.on_complete = [&](SX126xError result) {
|
||||
EXPECT_EQ(result, SX126xError::SX126X_ERROR_CANCELLED);
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&second, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
};
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&first, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
EXPECT_TRUE(hw.radio.cancel_transmit_async(&first));
|
||||
EXPECT_TRUE(hw.radio.is_transmitting());
|
||||
EXPECT_FALSE(hw.radio.cancel_transmit_async(&first));
|
||||
hw.irq = IRQ_TX_DONE;
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(second.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_NONE}));
|
||||
}
|
||||
|
||||
TEST(SX126xAsync, RejectsAfterFailedSetupWithoutBusAccess) {
|
||||
RadioHardware hw;
|
||||
TransmitListener listener;
|
||||
hw.fail_at = 1;
|
||||
hw.configure(true, true);
|
||||
ASSERT_TRUE(hw.radio.is_failed());
|
||||
hw.clear_trace();
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
EXPECT_TRUE(hw.transactions.empty());
|
||||
EXPECT_TRUE(listener.results.empty());
|
||||
}
|
||||
|
||||
TEST(SX126xAsync, TwoRadiosHaveIndependentOwnersAndCompletion) {
|
||||
RadioHardware a, b;
|
||||
TransmitListener first, second;
|
||||
a.configure(true, true);
|
||||
b.configure(false, false);
|
||||
a.auto_complete = b.auto_complete = false;
|
||||
ASSERT_EQ(a.radio.start_transmit_async(&first, a.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
ASSERT_EQ(b.radio.start_transmit_async(&second, b.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
a.radio.cancel_transmit_async(&first);
|
||||
EXPECT_TRUE(b.radio.is_transmitting());
|
||||
EXPECT_TRUE(second.results.empty());
|
||||
b.irq = IRQ_TX_DONE;
|
||||
b.radio.loop();
|
||||
EXPECT_EQ(first.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_CANCELLED}));
|
||||
EXPECT_EQ(second.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_NONE}));
|
||||
}
|
||||
|
||||
TEST(SX126xAsync, BackToBackReceiveEchoPreservesBorrowedPacketForAllListeners) {
|
||||
class EchoListener : public SX126xListener {
|
||||
public:
|
||||
std::function<void(const std::vector<uint8_t> &)> callback;
|
||||
void on_packet(const std::vector<uint8_t> &packet, float rssi, float snr) override { callback(packet); }
|
||||
} echo;
|
||||
RadioHardware hw;
|
||||
TransmitListener tx;
|
||||
PacketListener observer;
|
||||
hw.configure(true, true);
|
||||
hw.auto_complete = false;
|
||||
hw.radio.register_listener(&echo);
|
||||
hw.radio.register_listener(&observer);
|
||||
const auto first = hw.packet;
|
||||
const std::vector<uint8_t> second(200, 0xA5);
|
||||
unsigned calls = 0;
|
||||
echo.callback = [&](const std::vector<uint8_t> &packet) {
|
||||
if (++calls == 1) {
|
||||
hw.packet = second; // Larger back-to-back RX could reallocate the driver's packet_.
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
const auto count = hw.transactions.size();
|
||||
hw.radio.loop(); // Explicit loop reentry must not overwrite the borrowed RX buffer either.
|
||||
// The send stops in standby and holds the new packet instead of overwriting the FIFO.
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&tx, packet), SX126xError::SX126X_ERROR_BUSY);
|
||||
ASSERT_EQ(hw.transactions.size(), count + 2);
|
||||
EXPECT_EQ(hw.transactions[count][0], RADIO_SET_STANDBY);
|
||||
EXPECT_EQ(hw.transactions.back()[0], RADIO_GET_IRQSTATUS);
|
||||
EXPECT_EQ(packet, first);
|
||||
} else {
|
||||
EXPECT_EQ(packet, second);
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&tx, packet), SX126xError::SX126X_ERROR_NONE);
|
||||
}
|
||||
};
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
hw.radio.loop();
|
||||
ASSERT_EQ(observer.packets.size(), 1u);
|
||||
EXPECT_EQ(observer.packets[0], first);
|
||||
EXPECT_TRUE(tx.results.empty());
|
||||
EXPECT_FALSE(hw.radio.is_transmitting());
|
||||
hw.radio.loop();
|
||||
ASSERT_EQ(observer.packets.size(), 2u);
|
||||
EXPECT_EQ(observer.packets[1], second);
|
||||
ASSERT_EQ(calls, 2u);
|
||||
auto fifo = std::find_if(hw.transactions.rbegin(), hw.transactions.rend(),
|
||||
[](const auto &cmd) { return !cmd.empty() && cmd[0] == RADIO_WRITE_BUFFER; });
|
||||
ASSERT_NE(fifo, hw.transactions.rend());
|
||||
EXPECT_EQ(std::vector<uint8_t>(fifo->begin() + 2, fifo->end()), second);
|
||||
hw.irq = IRQ_TX_DONE;
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(tx.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_NONE}));
|
||||
}
|
||||
|
||||
TEST(SX126xAsync, FailedReconfigurationRejectsAsyncUntilReconfigured) {
|
||||
RadioHardware hw;
|
||||
TransmitListener listener;
|
||||
hw.configure(true, true);
|
||||
hw.clear_trace();
|
||||
hw.fail_at = 3;
|
||||
hw.radio.configure();
|
||||
hw.clear_trace();
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
EXPECT_TRUE(hw.transactions.empty());
|
||||
EXPECT_TRUE(listener.results.empty());
|
||||
hw.radio.configure();
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(listener.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_NONE}));
|
||||
}
|
||||
|
||||
TEST(SX126xAsync, BlockingSendUsesIrqResultInsteadOfTreatingAnyDioAsSuccess) {
|
||||
RadioHardware hw;
|
||||
hw.configure(true, true);
|
||||
auto write = hw.cs.on_write;
|
||||
hw.cs.on_write = [&](bool high) {
|
||||
write(high);
|
||||
if (high && !hw.transactions.back().empty() && hw.transactions.back()[0] == RADIO_SET_TX) {
|
||||
hw.irq = IRQ_RX_TX_TIMEOUT;
|
||||
}
|
||||
};
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_TIMEOUT);
|
||||
EXPECT_TRUE(hw.receiving);
|
||||
}
|
||||
|
||||
TEST(SX126xAsync, FailedAdmissionRestoresReceivePollingWithoutAnotherTransmission) {
|
||||
RadioHardware hw;
|
||||
PacketListener rx;
|
||||
TransmitListener tx;
|
||||
hw.configure(true, true);
|
||||
hw.radio.register_listener(&rx);
|
||||
const auto configured_params = hw.packet_params;
|
||||
hw.dio.internal = true;
|
||||
hw.radio.call();
|
||||
ASSERT_TRUE(hw.radio.is_idle());
|
||||
hw.clear_trace();
|
||||
hw.fail_at = 3;
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&tx, hw.packet), SX126xError::SX126X_ERROR_BUSY_TIMEOUT);
|
||||
EXPECT_TRUE(tx.results.empty());
|
||||
EXPECT_TRUE(hw.radio.is_in_loop_state());
|
||||
EXPECT_TRUE(hw.receiving);
|
||||
EXPECT_EQ(hw.packet_params, configured_params);
|
||||
hw.clear_trace();
|
||||
hw.irq = IRQ_RX_DONE; // No simulated ISR edge: restoration must re-enable polling.
|
||||
hw.radio.call();
|
||||
ASSERT_EQ(rx.packets.size(), 1u);
|
||||
EXPECT_EQ(rx.packets[0], hw.packet);
|
||||
EXPECT_EQ(hw.sends, 0u);
|
||||
}
|
||||
|
||||
TEST_P(SX126xAsyncModes, ReceiveAtStandbyRejectsSendAndSurvivesReadFailure) {
|
||||
const auto [lora, rx, fixed] = GetParam();
|
||||
RadioHardware hw;
|
||||
PacketListener received;
|
||||
TransmitListener tx;
|
||||
hw.configure(lora, rx, fixed);
|
||||
hw.radio.call(); // Advance from setup into ESPHome loop scheduling.
|
||||
hw.radio.register_listener(&received);
|
||||
hw.clear_trace();
|
||||
auto write = hw.cs.on_write;
|
||||
bool inject = true;
|
||||
hw.cs.on_write = [&](bool high) {
|
||||
write(high);
|
||||
if (high && inject && !hw.transactions.back().empty() && hw.transactions.back()[0] == RADIO_SET_STANDBY) {
|
||||
inject = false;
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
}
|
||||
};
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&tx, hw.packet), SX126xError::SX126X_ERROR_BUSY);
|
||||
EXPECT_TRUE(tx.results.empty());
|
||||
EXPECT_TRUE(received.packets.empty());
|
||||
EXPECT_FALSE(hw.receiving);
|
||||
EXPECT_FALSE(hw.radio.is_transmitting());
|
||||
EXPECT_EQ(hw.irq, IRQ_RX_DONE);
|
||||
ASSERT_EQ(hw.transactions.size(), 2u);
|
||||
EXPECT_EQ(hw.transactions[0][0], RADIO_SET_STANDBY);
|
||||
EXPECT_EQ(hw.transactions[1][0], RADIO_GET_IRQSTATUS);
|
||||
const auto resets = hw.rst.writes;
|
||||
hw.radio.set_mode_rx();
|
||||
EXPECT_EQ(hw.rst.writes, resets);
|
||||
EXPECT_EQ(hw.transactions.size(), 2u);
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_BUSY);
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&tx, hw.packet), SX126xError::SX126X_ERROR_BUSY);
|
||||
EXPECT_FALSE(hw.radio.cancel_transmit_async(&tx));
|
||||
|
||||
hw.clear_trace();
|
||||
hw.fail_at = 2; // Packet metadata read fails after the held IRQ is read.
|
||||
hw.radio.loop();
|
||||
EXPECT_TRUE(hw.radio.is_in_loop_state());
|
||||
EXPECT_TRUE(received.packets.empty());
|
||||
EXPECT_EQ(hw.irq, IRQ_RX_DONE);
|
||||
EXPECT_FALSE(hw.receiving);
|
||||
hw.clear_trace();
|
||||
LoopBlockingGuard retry{nullptr, nullptr, App.get_loop_component_start_time() + 200};
|
||||
hw.radio.loop();
|
||||
hw.radio.loop();
|
||||
ASSERT_EQ(received.packets.size(), 1u);
|
||||
EXPECT_EQ(received.packets[0], hw.packet);
|
||||
EXPECT_EQ(hw.receiving, rx);
|
||||
EXPECT_EQ(hw.sends, 0u);
|
||||
EXPECT_TRUE(tx.results.empty());
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&tx, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(tx.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_NONE}));
|
||||
}
|
||||
|
||||
TEST_P(SX126xAsyncModes, FailedPreparationAndRestorationRequireSuccessfulConfiguration) {
|
||||
const auto [lora, rx, fixed] = GetParam();
|
||||
RadioHardware hw;
|
||||
TransmitListener listener;
|
||||
hw.configure(lora, rx, fixed);
|
||||
hw.clear_trace();
|
||||
const auto busy = hw.busy.on_read;
|
||||
hw.busy.on_read = [&]() { return hw.transactions.size() >= 3 || busy(); };
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_BUSY_TIMEOUT);
|
||||
EXPECT_TRUE(listener.results.empty());
|
||||
EXPECT_EQ(hw.sends, 0u);
|
||||
EXPECT_FALSE(hw.radio.is_transmitting());
|
||||
EXPECT_TRUE(hw.cs.level);
|
||||
ASSERT_EQ(hw.transactions.size(), 4u);
|
||||
EXPECT_TRUE(hw.transactions[2].empty()); // Failed preparation.
|
||||
EXPECT_TRUE(hw.transactions[3].empty()); // Failed restoration.
|
||||
hw.clear_trace();
|
||||
hw.busy.on_read = busy;
|
||||
hw.radio.set_mode_rx();
|
||||
hw.radio.loop();
|
||||
EXPECT_TRUE(hw.radio.is_idle());
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
EXPECT_TRUE(hw.transactions.empty());
|
||||
hw.fail_at = 1;
|
||||
hw.radio.configure();
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
hw.clear_trace();
|
||||
hw.radio.configure();
|
||||
EXPECT_TRUE(hw.radio.is_in_loop_state());
|
||||
EXPECT_EQ(hw.receiving, rx);
|
||||
EXPECT_TRUE(listener.results.empty());
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(listener.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_NONE}));
|
||||
}
|
||||
|
||||
TEST(SX126xAsync, ExplicitConfigurationCanRecoverAnUnreadableHeldPacket) {
|
||||
RadioHardware hw;
|
||||
TransmitListener listener;
|
||||
hw.configure(true, true);
|
||||
auto write = hw.cs.on_write;
|
||||
hw.cs.on_write = [&](bool high) {
|
||||
write(high);
|
||||
if (high && !hw.transactions.back().empty() && hw.transactions.back()[0] == RADIO_SET_STANDBY) {
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
}
|
||||
};
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_BUSY);
|
||||
hw.cs.on_write = write;
|
||||
hw.busy.on_read = []() { return true; };
|
||||
hw.radio.loop();
|
||||
const auto resets = hw.rst.writes;
|
||||
hw.radio.configure();
|
||||
EXPECT_GT(hw.rst.writes, resets);
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
hw.busy.on_read = []() { return false; };
|
||||
hw.radio.configure();
|
||||
EXPECT_TRUE(hw.receiving);
|
||||
EXPECT_TRUE(listener.results.empty());
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&listener, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(listener.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_NONE}));
|
||||
}
|
||||
|
||||
class SX126xReceiveActions : public ::testing::TestWithParam<unsigned> {};
|
||||
|
||||
TEST_P(SX126xReceiveActions, ModeAndConfigurationPreserveBorrowedPacket) {
|
||||
RadioHardware hw;
|
||||
ReceiveCallback action;
|
||||
PacketListener observer;
|
||||
hw.configure(true, true);
|
||||
hw.radio.register_listener(&action);
|
||||
hw.radio.register_listener(&observer);
|
||||
const auto original = hw.packet;
|
||||
const unsigned selected_action = GetParam();
|
||||
unsigned callbacks = 0;
|
||||
action.on_packet_callback = [&]() {
|
||||
callbacks++;
|
||||
hw.clear_trace();
|
||||
switch (selected_action) {
|
||||
case 0:
|
||||
hw.radio.set_mode_sleep();
|
||||
break;
|
||||
case 1:
|
||||
hw.radio.set_mode_sleep(true);
|
||||
break;
|
||||
case 2:
|
||||
hw.radio.set_rx_start(false);
|
||||
hw.radio.configure();
|
||||
break;
|
||||
case 3:
|
||||
hw.radio.set_mode_standby(STDBY_XOSC);
|
||||
break;
|
||||
case 4:
|
||||
hw.radio.set_mode_rx();
|
||||
break;
|
||||
case 5:
|
||||
hw.radio.run_image_cal();
|
||||
break;
|
||||
default:
|
||||
FAIL() << "Unknown action " << selected_action;
|
||||
}
|
||||
EXPECT_FALSE(hw.transactions.empty()); // The requested operation must actually reach the chip.
|
||||
EXPECT_EQ(hw.receiving, selected_action >= 4);
|
||||
const auto commands = hw.transactions.size();
|
||||
hw.packet.assign(19, 0x99);
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
hw.radio.loop(); // Recursive packet delivery is still forbidden, including after configure().
|
||||
EXPECT_EQ(hw.transactions.size(), commands);
|
||||
};
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(callbacks, 1u);
|
||||
ASSERT_EQ(observer.packets.size(), 1u);
|
||||
EXPECT_EQ(observer.packets.front(), original);
|
||||
EXPECT_EQ(hw.irq, IRQ_RX_DONE); // The next packet is left for a later loop.
|
||||
if (selected_action == 1) {
|
||||
TransmitListener tx;
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&tx, original), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
}
|
||||
}
|
||||
|
||||
INSTANTIATE_TEST_SUITE_P(SleepColdSleepConfigureStandbyRxAndCalibration, SX126xReceiveActions,
|
||||
::testing::Range(0u, 6u));
|
||||
|
||||
} // namespace esphome::sx126x::testing
|
||||
@@ -1,788 +0,0 @@
|
||||
#include "sx126x_test_helpers.h"
|
||||
#include <cmath>
|
||||
#include "esphome/core/application.h"
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
#ifdef USE_HOST
|
||||
#include <string>
|
||||
#include "esphome/components/logger/logger.h"
|
||||
#endif
|
||||
namespace esphome::sx126x::testing {
|
||||
class SX126xBusySetup : public ::testing::TestWithParam<std::tuple<bool, bool>> {};
|
||||
|
||||
TEST_P(SX126xBusySetup, StopsAtEveryConfigurationCommand) {
|
||||
const auto [lora, rx] = GetParam();
|
||||
RadioHardware reference;
|
||||
reference.configure(lora, rx);
|
||||
ASSERT_FALSE(reference.radio.is_failed());
|
||||
ASSERT_FALSE(reference.radio.status_has_warning());
|
||||
const size_t count = reference.transactions.size();
|
||||
ASSERT_GT(count, 10u);
|
||||
for (size_t fault = 1; fault <= count; fault++) {
|
||||
SCOPED_TRACE(fault);
|
||||
RadioHardware hardware;
|
||||
hardware.fail_at = fault;
|
||||
hardware.configure(lora, rx);
|
||||
hardware.expect_aborted(fault);
|
||||
EXPECT_TRUE(hardware.radio.is_failed());
|
||||
hardware.radio.dump_config(); // Also safe if the version read never happened.
|
||||
hardware.clear_trace();
|
||||
hardware.radio.configure();
|
||||
hardware.radio.set_mode_rx();
|
||||
hardware.radio.set_mode_tx();
|
||||
hardware.radio.set_mode_sleep();
|
||||
hardware.radio.set_mode_standby(STDBY_XOSC);
|
||||
hardware.radio.run_image_cal();
|
||||
hardware.radio.loop();
|
||||
EXPECT_EQ(hardware.radio.transmit_packet(hardware.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
EXPECT_TRUE(hardware.transactions.empty());
|
||||
}
|
||||
}
|
||||
|
||||
INSTANTIATE_TEST_SUITE_P(LoRaAndFSKWithRxOrSleep, SX126xBusySetup,
|
||||
::testing::Combine(::testing::Bool(), ::testing::Bool()));
|
||||
|
||||
class SX126xBusyTransmit : public ::testing::TestWithParam<std::tuple<bool, bool, bool>> {};
|
||||
|
||||
TEST_P(SX126xBusyTransmit, StopsAtEverySendAndCleanupCommandAndCanRetry) {
|
||||
const auto [lora, rx, fixed] = GetParam();
|
||||
RadioHardware reference;
|
||||
reference.configure(lora, rx, fixed);
|
||||
reference.clear_trace();
|
||||
ASSERT_EQ(reference.radio.transmit_packet(reference.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
const size_t count = reference.transactions.size();
|
||||
for (size_t fault = 1; fault <= count; fault++) {
|
||||
SCOPED_TRACE(fault);
|
||||
RadioHardware hardware;
|
||||
hardware.configure(lora, rx, fixed);
|
||||
hardware.clear_trace();
|
||||
hardware.fail_at = fault;
|
||||
EXPECT_EQ(hardware.radio.transmit_packet(hardware.packet.data(), hardware.packet.size()),
|
||||
SX126xError::SX126X_ERROR_BUSY_TIMEOUT);
|
||||
EXPECT_TRUE(hardware.transactions[fault - 1].empty());
|
||||
EXPECT_TRUE(hardware.cs.level);
|
||||
EXPECT_FALSE(hardware.radio.is_failed());
|
||||
hardware.clear_trace();
|
||||
hardware.radio.configure();
|
||||
EXPECT_EQ(hardware.radio.transmit_packet(hardware.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
EXPECT_FALSE(hardware.radio.status_has_warning());
|
||||
EXPECT_EQ(hardware.receiving, rx);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_P(SX126xBusyTransmit, RestoresEveryPreparationFailureWithoutAnotherTransmission) {
|
||||
const auto [lora, rx, fixed] = GetParam();
|
||||
RadioHardware reference;
|
||||
reference.configure(lora, rx, fixed);
|
||||
reference.clear_trace();
|
||||
ASSERT_EQ(reference.radio.transmit_packet(reference.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
size_t tx_command = 0;
|
||||
for (size_t i = 0; i < reference.transactions.size(); i++) {
|
||||
if (reference.transactions[i][0] == RADIO_SET_TX) {
|
||||
tx_command = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
ASSERT_NE(tx_command, 0u);
|
||||
for (size_t fault = 1; fault <= tx_command; fault++) {
|
||||
SCOPED_TRACE(fault);
|
||||
RadioHardware hw;
|
||||
PacketListener listener;
|
||||
hw.configure(lora, rx, fixed);
|
||||
hw.radio.register_listener(&listener);
|
||||
const auto configured_params = hw.packet_params;
|
||||
hw.clear_trace();
|
||||
hw.fail_at = fault;
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_BUSY_TIMEOUT);
|
||||
EXPECT_TRUE(hw.transactions[fault - 1].empty());
|
||||
EXPECT_TRUE(hw.cs.level);
|
||||
EXPECT_EQ(hw.ends, hw.transactions.size());
|
||||
EXPECT_EQ(hw.receiving, rx);
|
||||
EXPECT_EQ(hw.packet_params, configured_params);
|
||||
EXPECT_EQ(hw.irq, 0u);
|
||||
EXPECT_FALSE(hw.radio.status_has_warning());
|
||||
EXPECT_FALSE(hw.radio.is_failed());
|
||||
const auto sends = hw.sends;
|
||||
hw.clear_trace();
|
||||
if (rx) {
|
||||
if (!fixed) {
|
||||
hw.packet.resize(9, 0x55); // RX must accept a different length than the attempted TX.
|
||||
}
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
hw.radio.loop();
|
||||
ASSERT_EQ(listener.packets.size(), 1u);
|
||||
EXPECT_EQ(listener.packets[0], hw.packet);
|
||||
}
|
||||
EXPECT_EQ(hw.sends, sends);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_P(SX126xBusyTransmit, FailedRestorationRequiresConfigureBeforeReceiveRecovery) {
|
||||
const auto [lora, rx, fixed] = GetParam();
|
||||
RadioHardware reference;
|
||||
reference.configure(lora, rx, fixed);
|
||||
reference.clear_trace();
|
||||
ASSERT_EQ(reference.radio.transmit_packet(reference.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
size_t restoration = 0;
|
||||
bool sent = false;
|
||||
for (size_t i = 0; i < reference.transactions.size(); i++) {
|
||||
if (reference.transactions[i][0] == RADIO_SET_TX) {
|
||||
sent = true;
|
||||
}
|
||||
if (sent && reference.transactions[i][0] == RADIO_SET_STANDBY) {
|
||||
restoration = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
ASSERT_NE(restoration, 0u);
|
||||
for (size_t fault = restoration; fault <= reference.transactions.size(); fault++) {
|
||||
SCOPED_TRACE(fault);
|
||||
RadioHardware hw;
|
||||
PacketListener listener;
|
||||
hw.configure(lora, rx, fixed);
|
||||
hw.radio.register_listener(&listener);
|
||||
const auto configured_params = hw.packet_params;
|
||||
hw.clear_trace();
|
||||
hw.fail_at = fault;
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_BUSY_TIMEOUT);
|
||||
EXPECT_TRUE(hw.cs.level);
|
||||
EXPECT_TRUE(hw.radio.status_has_warning());
|
||||
EXPECT_FALSE(hw.radio.is_failed());
|
||||
const auto sends = hw.sends;
|
||||
hw.clear_trace(); // Clearing BUSY alone must not re-admit partial configuration.
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
hw.radio.loop();
|
||||
hw.radio.set_mode_rx();
|
||||
hw.radio.set_mode_tx();
|
||||
hw.radio.set_mode_standby(STDBY_XOSC);
|
||||
hw.radio.set_mode_sleep();
|
||||
hw.radio.run_image_cal();
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
EXPECT_TRUE(hw.transactions.empty());
|
||||
EXPECT_TRUE(listener.packets.empty());
|
||||
EXPECT_TRUE(hw.radio.status_has_warning());
|
||||
hw.irq = 0; // Hardware reset clears IRQs; the GPIO fake does not model reset.
|
||||
hw.radio.configure();
|
||||
EXPECT_FALSE(hw.radio.status_has_warning());
|
||||
EXPECT_EQ(hw.packet_params, configured_params);
|
||||
EXPECT_EQ(hw.receiving, rx);
|
||||
if (rx) {
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
hw.radio.loop();
|
||||
ASSERT_EQ(listener.packets.size(), 1u);
|
||||
EXPECT_EQ(listener.packets[0], hw.packet);
|
||||
}
|
||||
EXPECT_EQ(hw.sends, sends); // Recovery must not depend on sending another packet.
|
||||
}
|
||||
}
|
||||
|
||||
TEST(SX126xBusy, PersistentBusyDuringPreparationAndRestorationRequiresConfigure) {
|
||||
RadioHardware hw;
|
||||
PacketListener listener;
|
||||
hw.configure(true, true);
|
||||
hw.radio.register_listener(&listener);
|
||||
const auto configured_params = hw.packet_params;
|
||||
hw.clear_trace();
|
||||
auto normal_busy = hw.busy.on_read;
|
||||
hw.busy.on_read = [&]() { return hw.transactions.size() >= 3 || normal_busy(); };
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_BUSY_TIMEOUT);
|
||||
EXPECT_FALSE(hw.receiving);
|
||||
EXPECT_TRUE(hw.radio.status_has_warning());
|
||||
EXPECT_EQ(hw.sends, 0u);
|
||||
hw.busy.on_read = normal_busy;
|
||||
hw.clear_trace();
|
||||
hw.radio.set_mode_rx();
|
||||
hw.radio.run_image_cal();
|
||||
EXPECT_TRUE(hw.transactions.empty());
|
||||
EXPECT_TRUE(hw.radio.status_has_warning());
|
||||
hw.radio.configure();
|
||||
EXPECT_TRUE(hw.receiving);
|
||||
EXPECT_EQ(hw.packet_params, configured_params);
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
hw.radio.loop();
|
||||
ASSERT_EQ(listener.packets.size(), 1u);
|
||||
EXPECT_EQ(listener.packets[0], hw.packet);
|
||||
EXPECT_EQ(hw.sends, 0u);
|
||||
}
|
||||
|
||||
INSTANTIATE_TEST_SUITE_P(LoRaAndFSKWithRxOrSleepAndFixedOrVariablePayload, SX126xBusyTransmit,
|
||||
::testing::Combine(::testing::Bool(), ::testing::Bool(), ::testing::Bool()));
|
||||
|
||||
class SX126xBusyReceive : public ::testing::TestWithParam<bool> {};
|
||||
|
||||
TEST_P(SX126xBusyReceive, KeepsAPacketWhoseReadFailedAndRetries) {
|
||||
const bool lora = GetParam();
|
||||
for (size_t fault = 1; fault <= 5; fault++) {
|
||||
SCOPED_TRACE(fault);
|
||||
RadioHardware hardware;
|
||||
PacketListener listener;
|
||||
hardware.configure(lora, true);
|
||||
hardware.radio.register_listener(&listener);
|
||||
hardware.clear_trace();
|
||||
hardware.irq = IRQ_RX_DONE;
|
||||
hardware.fail_at = fault;
|
||||
hardware.radio.loop();
|
||||
hardware.expect_aborted(fault);
|
||||
EXPECT_TRUE(listener.packets.empty());
|
||||
EXPECT_TRUE(hardware.radio.status_has_warning());
|
||||
EXPECT_FALSE(hardware.radio.is_failed());
|
||||
// The flags may already be cleared; the packet is still read on the retry.
|
||||
hardware.clear_trace();
|
||||
LoopBlockingGuard retry{nullptr, nullptr, App.get_loop_component_start_time() + 200};
|
||||
hardware.radio.loop();
|
||||
ASSERT_EQ(listener.packets.size(), 1u);
|
||||
EXPECT_EQ(listener.packets[0], hardware.packet);
|
||||
EXPECT_FLOAT_EQ(listener.rssi, lora ? -40 : -42);
|
||||
if (lora) {
|
||||
EXPECT_FLOAT_EQ(listener.snr, 10);
|
||||
} else {
|
||||
EXPECT_TRUE(std::isnan(listener.snr));
|
||||
}
|
||||
EXPECT_FALSE(hardware.radio.status_has_warning());
|
||||
}
|
||||
}
|
||||
|
||||
INSTANTIATE_TEST_SUITE_P(LoRaAndFSK, SX126xBusyReceive, ::testing::Bool());
|
||||
|
||||
// A packet whose flags were cleared before its read failed, then held by a send, survives a
|
||||
// second failed read
|
||||
TEST(SX126xBusy, HeldPacketSurvivesASecondFailedRead) {
|
||||
RadioHardware hw;
|
||||
PacketListener listener;
|
||||
hw.configure(true, true);
|
||||
hw.radio.register_listener(&listener);
|
||||
hw.clear_trace();
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
hw.fail_at = 3; // the first read after the flags were cleared
|
||||
hw.radio.loop();
|
||||
ASSERT_EQ(hw.irq, 0);
|
||||
ASSERT_TRUE(listener.packets.empty());
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_BUSY);
|
||||
hw.clear_trace();
|
||||
hw.fail_at = 2; // the held packet's read
|
||||
LoopBlockingGuard first{nullptr, nullptr, App.get_loop_component_start_time() + 200};
|
||||
hw.radio.loop();
|
||||
ASSERT_TRUE(listener.packets.empty());
|
||||
hw.clear_trace();
|
||||
LoopBlockingGuard second{nullptr, nullptr, App.get_loop_component_start_time() + 200};
|
||||
hw.radio.loop();
|
||||
ASSERT_EQ(listener.packets.size(), 1u);
|
||||
EXPECT_EQ(listener.packets[0], hw.packet);
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
}
|
||||
|
||||
TEST(SX126xBusy, KeepsPollingAnUnclearedInterruptAfterBusyTimeout) {
|
||||
RadioHardware hardware;
|
||||
PacketListener listener;
|
||||
hardware.configure(true, true);
|
||||
hardware.radio.register_listener(&listener);
|
||||
hardware.dio.internal = true; // No new ISR edge while the pending IRQ stays high.
|
||||
hardware.clear_trace();
|
||||
hardware.fail_at = 1;
|
||||
hardware.irq = IRQ_RX_DONE;
|
||||
hardware.radio.call();
|
||||
EXPECT_TRUE(listener.packets.empty());
|
||||
hardware.clear_trace();
|
||||
LoopBlockingGuard retry{nullptr, nullptr, App.get_loop_component_start_time() + 200};
|
||||
hardware.radio.call();
|
||||
EXPECT_EQ(listener.packets.size(), 1u);
|
||||
}
|
||||
|
||||
TEST(SX126xBusy, AssertsChipSelectBeforeWaitingForWakeup) {
|
||||
RadioHardware hardware;
|
||||
hardware.configure(true, true);
|
||||
hardware.clear_trace();
|
||||
hardware.busy.level = true; // The CS callback releases BUSY only after selecting the chip.
|
||||
EXPECT_EQ(hardware.radio.transmit_packet(hardware.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
EXPECT_TRUE(hardware.cs.level);
|
||||
EXPECT_EQ(hardware.ends, hardware.transactions.size());
|
||||
}
|
||||
|
||||
TEST(SX126xBusy, RejectsSendBeforeSetupWithoutTouchingPins) {
|
||||
RadioHardware hardware;
|
||||
EXPECT_EQ(hardware.radio.transmit_packet(hardware.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
EXPECT_TRUE(hardware.transactions.empty());
|
||||
EXPECT_EQ(hardware.busy.reads, 0u);
|
||||
EXPECT_EQ(hardware.dio.reads, 0u);
|
||||
}
|
||||
|
||||
TEST(SX126xBusy, UnsupportedVersionFailsSetup) {
|
||||
RadioHardware hardware;
|
||||
hardware.supported_version = false;
|
||||
hardware.configure(true, true);
|
||||
EXPECT_TRUE(hardware.radio.is_failed());
|
||||
}
|
||||
|
||||
TEST(SX126xBusy, RuntimeVersionFailureRequiresConfigureWithoutPermanentlyFailing) {
|
||||
RadioHardware hardware;
|
||||
hardware.configure(true, true);
|
||||
hardware.supported_version = false;
|
||||
hardware.radio.configure();
|
||||
EXPECT_FALSE(hardware.radio.is_failed());
|
||||
EXPECT_TRUE(hardware.radio.status_has_warning());
|
||||
hardware.clear_trace();
|
||||
EXPECT_EQ(hardware.radio.transmit_packet(hardware.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
EXPECT_TRUE(hardware.transactions.empty());
|
||||
hardware.supported_version = true;
|
||||
hardware.radio.configure();
|
||||
EXPECT_FALSE(hardware.radio.status_has_warning());
|
||||
EXPECT_EQ(hardware.radio.transmit_packet(hardware.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
}
|
||||
|
||||
TEST(SX126xBusy, FailedReconfigurationRequiresSuccessfulConfigureBeforeOperations) {
|
||||
RadioHardware reference;
|
||||
reference.configure(true, true);
|
||||
const size_t count = reference.transactions.size();
|
||||
for (size_t fault = 1; fault <= count; fault++) {
|
||||
SCOPED_TRACE(fault);
|
||||
RadioHardware hw;
|
||||
PacketListener listener;
|
||||
hw.configure(true, true);
|
||||
hw.radio.register_listener(&listener);
|
||||
hw.clear_trace();
|
||||
hw.fail_at = fault;
|
||||
hw.radio.configure();
|
||||
EXPECT_FALSE(hw.radio.is_failed());
|
||||
hw.clear_trace();
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
hw.radio.loop();
|
||||
hw.radio.set_mode_rx();
|
||||
hw.radio.set_mode_tx();
|
||||
hw.radio.set_mode_standby(STDBY_XOSC);
|
||||
hw.radio.set_mode_sleep();
|
||||
hw.radio.run_image_cal();
|
||||
EXPECT_TRUE(hw.transactions.empty());
|
||||
EXPECT_TRUE(listener.packets.empty());
|
||||
hw.radio.configure();
|
||||
hw.irq = 0;
|
||||
EXPECT_FALSE(hw.radio.status_has_warning());
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(SX126xBusy, RetryClearsStaleTxDoneBeforeWaitingForDelayedCompletion) {
|
||||
RadioHardware reference;
|
||||
reference.configure(true, true);
|
||||
reference.clear_trace();
|
||||
reference.radio.transmit_packet(reference.packet);
|
||||
size_t cleanup = 0;
|
||||
bool sent = false;
|
||||
for (size_t i = 0; i < reference.transactions.size(); i++) {
|
||||
if (reference.transactions[i][0] == RADIO_SET_TX) {
|
||||
sent = true;
|
||||
}
|
||||
if (sent && reference.transactions[i][0] == RADIO_CLR_IRQSTATUS) {
|
||||
cleanup = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
ASSERT_NE(cleanup, 0u);
|
||||
RadioHardware hw;
|
||||
hw.configure(true, true);
|
||||
hw.clear_trace();
|
||||
hw.fail_at = cleanup;
|
||||
ASSERT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_BUSY_TIMEOUT);
|
||||
EXPECT_EQ(hw.irq & IRQ_TX_DONE, 0); // Shared restoration retries the failed IRQ clear.
|
||||
hw.irq = IRQ_TX_DONE; // A stale flag must still not finish the next TX.
|
||||
hw.clear_trace();
|
||||
hw.auto_complete = false;
|
||||
unsigned polls = 0;
|
||||
hw.dio.on_read = [&]() {
|
||||
if (++polls == 5) {
|
||||
hw.irq |= IRQ_TX_DONE;
|
||||
}
|
||||
return hw.irq != 0;
|
||||
};
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
EXPECT_EQ(polls, 5u);
|
||||
EXPECT_TRUE(hw.receiving);
|
||||
}
|
||||
|
||||
} // namespace esphome::sx126x::testing
|
||||
|
||||
namespace esphome::sx126x::testing {
|
||||
template<typename T>
|
||||
concept RawSpiAccessible = requires(T &device) { device.transfer_byte(0); };
|
||||
template<typename T>
|
||||
concept ManualSelectionAccessible = requires(T &device) {
|
||||
device.enable();
|
||||
device.disable();
|
||||
};
|
||||
static_assert(!RawSpiAccessible<SX126x>);
|
||||
static_assert(!RawSpiAccessible<SX126xSpiDevice>);
|
||||
static_assert(!ManualSelectionAccessible<SX126x>);
|
||||
static_assert(!ManualSelectionAccessible<SX126xSpiDevice>);
|
||||
// The radio runs every command sequence and state change. Without component status or
|
||||
// listeners it cannot run user code mid-operation; SX126x::apply_() does that afterwards.
|
||||
static_assert(!std::is_base_of_v<Component, SX126xRadio>);
|
||||
} // namespace esphome::sx126x::testing
|
||||
|
||||
namespace esphome::sx126x::testing {
|
||||
TEST(SX126xBusy, FailedModeChangeCannotBeClearedByAnotherModeCommand) {
|
||||
for (size_t fault = 1; fault <= 3; fault++) {
|
||||
RadioHardware hw;
|
||||
hw.configure(true, true);
|
||||
hw.clear_trace();
|
||||
hw.fail_at = fault;
|
||||
hw.radio.set_mode_rx();
|
||||
EXPECT_TRUE(hw.radio.status_has_warning());
|
||||
hw.clear_trace();
|
||||
hw.radio.set_mode_standby(STDBY_XOSC);
|
||||
hw.radio.run_image_cal();
|
||||
EXPECT_TRUE(hw.transactions.empty());
|
||||
EXPECT_TRUE(hw.radio.status_has_warning());
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
hw.radio.configure();
|
||||
EXPECT_FALSE(hw.radio.status_has_warning());
|
||||
EXPECT_TRUE(hw.receiving);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(SX126xBusy, ConfigurationCannotReenterSendPreparationOrRestoration) {
|
||||
RadioHardware hw;
|
||||
hw.configure(true, true);
|
||||
hw.radio.call(); // Advance from setup into ESPHome loop scheduling.
|
||||
hw.clear_trace();
|
||||
auto write = hw.cs.on_write;
|
||||
unsigned guarded = 0;
|
||||
hw.cs.on_write = [&](bool high) {
|
||||
write(high);
|
||||
if (!high || hw.transactions.back().empty() || hw.transactions.back()[0] != RADIO_SET_STANDBY) {
|
||||
return;
|
||||
}
|
||||
guarded++;
|
||||
const auto commands = hw.transactions.size();
|
||||
hw.radio.configure();
|
||||
hw.radio.set_mode_rx();
|
||||
hw.radio.loop();
|
||||
EXPECT_TRUE(hw.radio.is_in_loop_state());
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_BUSY);
|
||||
EXPECT_EQ(hw.transactions.size(), commands);
|
||||
};
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
EXPECT_EQ(guarded, 2u);
|
||||
EXPECT_TRUE(hw.radio.is_in_loop_state());
|
||||
EXPECT_TRUE(hw.receiving);
|
||||
}
|
||||
} // namespace esphome::sx126x::testing
|
||||
|
||||
namespace esphome::sx126x::testing {
|
||||
TEST(SX126xBusy, InvalidPayloadDoesNotEnterAnOperation) {
|
||||
RadioHardware hw;
|
||||
hw.configure(true, true);
|
||||
hw.clear_trace();
|
||||
EXPECT_EQ(hw.radio.transmit_packet(nullptr, 3), SX126xError::SX126X_ERROR_INVALID_PARAMS);
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet.data(), 0), SX126xError::SX126X_ERROR_INVALID_PARAMS);
|
||||
EXPECT_TRUE(hw.transactions.empty());
|
||||
EXPECT_TRUE(hw.receiving);
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
}
|
||||
|
||||
TEST(SX126xBusy, ColdSleepIsWokenByAModeCommandAndWarmSleepRetainsIt) {
|
||||
RadioHardware hw;
|
||||
hw.configure(true, true);
|
||||
hw.radio.set_mode_sleep(false);
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
hw.radio.set_mode_sleep(true);
|
||||
hw.clear_trace();
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
// Sleeping again leaves it asleep
|
||||
hw.radio.set_mode_sleep(false);
|
||||
EXPECT_TRUE(hw.transactions.empty());
|
||||
// Any other mode command applies the lost configuration first
|
||||
hw.radio.set_mode_rx();
|
||||
EXPECT_FALSE(hw.transactions.empty());
|
||||
EXPECT_TRUE(hw.receiving);
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
}
|
||||
|
||||
// Runs the scheduler for ms milliseconds of real time, as the main loop would
|
||||
static void run_scheduler(uint32_t ms) {
|
||||
const uint32_t start = millis();
|
||||
while (millis() - start < ms) {
|
||||
App.scheduler.call(millis());
|
||||
delay(5);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(SX126xBusy, FailedModeChangeIsReconfiguredWithoutBeingAsked) {
|
||||
RadioHardware hw;
|
||||
hw.configure(true, true);
|
||||
hw.clear_trace();
|
||||
hw.fail_at = 1;
|
||||
hw.radio.set_mode_rx();
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
run_scheduler(1100);
|
||||
EXPECT_FALSE(hw.radio.status_has_warning());
|
||||
EXPECT_TRUE(hw.receiving);
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
// Once configured, the retry stops
|
||||
hw.clear_trace();
|
||||
run_scheduler(1100);
|
||||
EXPECT_TRUE(hw.transactions.empty());
|
||||
}
|
||||
|
||||
TEST(SX126xBusy, ColdSleepIsNotReconfiguredWithoutBeingAsked) {
|
||||
RadioHardware hw;
|
||||
hw.configure(true, true);
|
||||
hw.radio.set_mode_sleep(true);
|
||||
hw.clear_trace();
|
||||
run_scheduler(1100);
|
||||
EXPECT_TRUE(hw.transactions.empty());
|
||||
}
|
||||
|
||||
TEST(SX126xBusy, ConfigureBeforeSetupDoesNothing) {
|
||||
RadioHardware hw;
|
||||
hw.radio.configure();
|
||||
EXPECT_TRUE(hw.transactions.empty());
|
||||
EXPECT_EQ(hw.rst.writes, 0u);
|
||||
hw.configure(true, true);
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
}
|
||||
|
||||
// The TX mode command sends whatever the FIFO holds without tracking it; its TX_DONE is
|
||||
// cleared as a flag without a packet, and a send still works afterwards
|
||||
TEST(SX126xBusy, RawTxModeLeavesTheRadioUsable) {
|
||||
RadioHardware hw;
|
||||
PacketListener listener;
|
||||
hw.configure(true, true);
|
||||
hw.radio.register_listener(&listener);
|
||||
hw.radio.set_mode_tx();
|
||||
ASSERT_EQ(hw.irq & IRQ_TX_DONE, IRQ_TX_DONE);
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(hw.irq, 0);
|
||||
EXPECT_TRUE(listener.packets.empty());
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
}
|
||||
|
||||
TEST(SX126xBusy, PacketThatFailedItsCrcDoesNotHoldUpASend) {
|
||||
RadioHardware hw;
|
||||
hw.configure(true, true);
|
||||
hw.irq = IRQ_RX_DONE | IRQ_CRC_ERROR;
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
}
|
||||
|
||||
TEST(SX126xBusy, PacketCompletingDuringAReadIsReadNext) {
|
||||
RadioHardware hw;
|
||||
PacketListener listener;
|
||||
hw.configure(true, true);
|
||||
hw.radio.register_listener(&listener);
|
||||
bool second = false;
|
||||
hw.on_command = [&](uint8_t opcode) {
|
||||
if (opcode == RADIO_READ_BUFFER && !second) {
|
||||
second = true;
|
||||
hw.irq |= IRQ_RX_DONE;
|
||||
}
|
||||
};
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(listener.packets.size(), 1u);
|
||||
EXPECT_EQ(hw.irq & IRQ_RX_DONE, IRQ_RX_DONE); // DIO1 stays high for the second packet
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(listener.packets.size(), 2u);
|
||||
}
|
||||
|
||||
TEST(SX126xBusy, UnavailableLoopStopsAndConfigurationResumesReceiveWithoutAnInterrupt) {
|
||||
for (bool internal : {false, true}) {
|
||||
for (unsigned cause = 0; cause < 3; cause++) {
|
||||
SCOPED_TRACE(internal);
|
||||
SCOPED_TRACE(cause);
|
||||
RadioHardware hw;
|
||||
PacketListener received;
|
||||
hw.configure(true, true);
|
||||
hw.radio.register_listener(&received);
|
||||
// Set after setup: the fake pin cannot attach a hardware interrupt.
|
||||
hw.dio.internal = internal;
|
||||
hw.clear_trace();
|
||||
if (cause == 0) {
|
||||
hw.radio.set_mode_sleep(true);
|
||||
} else if (cause == 1) {
|
||||
hw.fail_at = 1;
|
||||
hw.radio.configure();
|
||||
} else {
|
||||
hw.fail_at = 1;
|
||||
hw.radio.set_mode_rx();
|
||||
}
|
||||
hw.clear_trace();
|
||||
hw.radio.call();
|
||||
ASSERT_TRUE(hw.radio.is_idle());
|
||||
EXPECT_TRUE(hw.transactions.empty());
|
||||
EXPECT_EQ(hw.dio.reads, 0u);
|
||||
hw.radio.configure();
|
||||
ASSERT_TRUE(hw.radio.is_in_loop_state());
|
||||
hw.irq = IRQ_RX_DONE; // No ISR edge: configure() must resume polling itself.
|
||||
hw.radio.call();
|
||||
ASSERT_EQ(received.packets.size(), 1u);
|
||||
EXPECT_EQ(received.packets[0], hw.packet);
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace esphome::sx126x::testing
|
||||
|
||||
namespace esphome::sx126x::testing {
|
||||
TEST(SX126xProfile, SettersDoNotChangeAppliedPacketOrRestorationPolicy) {
|
||||
RadioHardware hw;
|
||||
hw.configure(true, true);
|
||||
hw.radio.set_payload_length(2);
|
||||
hw.radio.set_rx_start(false);
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
EXPECT_TRUE(hw.receiving);
|
||||
hw.radio.configure();
|
||||
EXPECT_EQ(hw.radio.get_max_packet_size(), 2u);
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_INVALID_PARAMS);
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet.data(), 2), SX126xError::SX126X_ERROR_NONE);
|
||||
EXPECT_FALSE(hw.receiving);
|
||||
}
|
||||
|
||||
TEST(SX126xProfile, RejectsOversizedSyncValueBeforeResetOrSpi) {
|
||||
RadioHardware hw;
|
||||
hw.configure(true, true);
|
||||
hw.radio.set_sync_value(std::vector<uint8_t>(9, 1));
|
||||
hw.clear_trace();
|
||||
const auto reset_writes = hw.rst.writes;
|
||||
hw.radio.configure();
|
||||
EXPECT_EQ(hw.rst.writes, reset_writes);
|
||||
EXPECT_TRUE(hw.transactions.empty());
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
hw.radio.set_sync_value({0x14, 0x24});
|
||||
hw.radio.configure();
|
||||
EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
}
|
||||
} // namespace esphome::sx126x::testing
|
||||
|
||||
#ifdef USE_HOST
|
||||
namespace esphome::sx126x::testing {
|
||||
template<typename F> static std::string capture_radio_logs(F action) {
|
||||
const auto previous_baud_rate = logger::global_logger->get_baud_rate();
|
||||
::testing::internal::CaptureStdout();
|
||||
logger::global_logger->set_baud_rate(115200);
|
||||
action();
|
||||
logger::global_logger->set_baud_rate(previous_baud_rate);
|
||||
return ::testing::internal::GetCapturedStdout();
|
||||
}
|
||||
|
||||
TEST(SX126xDiagnostics, BlockingRejectionsExplainWhyNoPacketWasSent) {
|
||||
RadioHardware hw;
|
||||
auto output = capture_radio_logs(
|
||||
[&]() { EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_NOT_READY); });
|
||||
EXPECT_NE(output.find("Packet send failed: radio not ready"), std::string::npos);
|
||||
hw.configure(true, true, true);
|
||||
hw.clear_trace();
|
||||
output = capture_radio_logs(
|
||||
[&]() { EXPECT_EQ(hw.radio.transmit_packet(hw.packet.data(), 2), SX126xError::SX126X_ERROR_INVALID_PARAMS); });
|
||||
EXPECT_NE(output.find("Packet send failed: invalid payload"), std::string::npos);
|
||||
EXPECT_TRUE(hw.transactions.empty());
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
output =
|
||||
capture_radio_logs([&]() { EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_BUSY); });
|
||||
EXPECT_NE(output.find("Packet send failed: radio busy"), std::string::npos);
|
||||
EXPECT_EQ(hw.irq, IRQ_RX_DONE);
|
||||
EXPECT_EQ(hw.sends, 0u);
|
||||
hw.radio.loop(); // Deliver the held packet, which also clears its IRQ.
|
||||
EXPECT_EQ(hw.irq, 0u);
|
||||
hw.clear_trace();
|
||||
hw.fail_at = 1;
|
||||
output = capture_radio_logs(
|
||||
[&]() { EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_BUSY_TIMEOUT); });
|
||||
EXPECT_NE(output.find("Packet send failed: bus timeout"), std::string::npos);
|
||||
EXPECT_EQ(hw.sends, 0u);
|
||||
}
|
||||
|
||||
TEST(SX126xDiagnostics, AsyncAdmissionLeavesRejectionReportingToItsCaller) {
|
||||
class Completion final : public SX126xTransmitListener {
|
||||
public:
|
||||
void on_transmit_complete(SX126xError result) override { ADD_FAILURE() << "Rejected send completed"; }
|
||||
} completion;
|
||||
RadioHardware hw;
|
||||
const auto output = capture_radio_logs([&]() {
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&completion, hw.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
hw.configure(true, true, true);
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&completion, hw.packet.data(), 2),
|
||||
SX126xError::SX126X_ERROR_INVALID_PARAMS);
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&completion, hw.packet), SX126xError::SX126X_ERROR_BUSY);
|
||||
});
|
||||
EXPECT_EQ(output.find("Packet send failed"), std::string::npos);
|
||||
EXPECT_EQ(hw.sends, 0u);
|
||||
}
|
||||
|
||||
TEST(SX126xDiagnostics, FailedSetupPrintsRequestedConfiguration) {
|
||||
RadioHardware hw;
|
||||
hw.fail_at = 1;
|
||||
hw.radio.set_pa_power(10);
|
||||
hw.configure(true, true, true);
|
||||
ASSERT_TRUE(hw.radio.is_failed());
|
||||
const auto output = capture_radio_logs([&]() { hw.radio.dump_config(); });
|
||||
EXPECT_NE(output.find("Ready for operation: NO"), std::string::npos);
|
||||
EXPECT_NE(output.find("Requested configuration:"), std::string::npos);
|
||||
EXPECT_NE(output.find("Frequency: 915000000 Hz"), std::string::npos);
|
||||
EXPECT_NE(output.find("PA Power: 10 dBm"), std::string::npos);
|
||||
EXPECT_NE(output.find("Payload Length: 3"), std::string::npos);
|
||||
EXPECT_NE(output.find("Sync Value: 0x1424"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(SX126xDiagnostics, StagedConfigurationIsLabelledAndDoesNotAlterAppliedSettings) {
|
||||
RadioHardware hw;
|
||||
hw.configure(true, true, true);
|
||||
hw.radio.set_frequency(868000000);
|
||||
hw.radio.set_payload_length(2);
|
||||
auto output = capture_radio_logs([&]() { hw.radio.dump_config(); });
|
||||
EXPECT_NE(output.find("Ready for operation: YES"), std::string::npos);
|
||||
EXPECT_NE(output.find("Requested configuration:"), std::string::npos);
|
||||
EXPECT_NE(output.find("Frequency: 868000000 Hz"), std::string::npos);
|
||||
EXPECT_NE(output.find("Payload Length: 2"), std::string::npos);
|
||||
EXPECT_EQ(hw.radio.get_max_packet_size(), 3u);
|
||||
hw.clear_trace();
|
||||
hw.fail_at = 1;
|
||||
hw.radio.configure();
|
||||
output = capture_radio_logs([&]() { hw.radio.dump_config(); });
|
||||
EXPECT_NE(output.find("Ready for operation: NO"), std::string::npos);
|
||||
EXPECT_NE(output.find("Frequency: 868000000 Hz"), std::string::npos);
|
||||
EXPECT_EQ(hw.radio.get_max_packet_size(), 3u);
|
||||
}
|
||||
class SX126xTimeoutDiagnostics : public ::testing::TestWithParam<bool> {};
|
||||
|
||||
TEST_P(SX126xTimeoutDiagnostics, BlockingTimeoutLogsFailureAfterRestoration) {
|
||||
RadioHardware hw;
|
||||
hw.configure(true, true);
|
||||
hw.auto_complete = false;
|
||||
if (GetParam()) {
|
||||
hw.dio.on_read = [&]() {
|
||||
if (hw.sends > 0) {
|
||||
hw.irq = IRQ_RX_TX_TIMEOUT;
|
||||
}
|
||||
return hw.irq != 0;
|
||||
};
|
||||
}
|
||||
const auto output =
|
||||
capture_radio_logs([&]() { EXPECT_EQ(hw.radio.transmit_packet(hw.packet), SX126xError::SX126X_ERROR_TIMEOUT); });
|
||||
EXPECT_NE(output.find("Packet send failed: timeout"), std::string::npos);
|
||||
EXPECT_TRUE(hw.receiving);
|
||||
EXPECT_FALSE(hw.radio.is_transmitting());
|
||||
EXPECT_FALSE(hw.radio.status_has_warning()); // Restoration itself succeeded.
|
||||
}
|
||||
|
||||
INSTANTIATE_TEST_SUITE_P(SoftwareDeadlineAndRadioTimeout, SX126xTimeoutDiagnostics, ::testing::Bool());
|
||||
|
||||
TEST(SX126xDiagnostics, AsyncTimeoutLeavesCompletionReportingToItsCaller) {
|
||||
struct Completion final : SX126xTransmitListener {
|
||||
void on_transmit_complete(SX126xError result) override {
|
||||
this->count++;
|
||||
EXPECT_EQ(result, SX126xError::SX126X_ERROR_TIMEOUT);
|
||||
}
|
||||
unsigned count{0};
|
||||
} completion;
|
||||
RadioHardware hw;
|
||||
hw.configure(true, true);
|
||||
const auto output = capture_radio_logs([&]() {
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&completion, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
hw.irq = IRQ_RX_TX_TIMEOUT;
|
||||
hw.radio.loop();
|
||||
});
|
||||
EXPECT_EQ(completion.count, 1u);
|
||||
EXPECT_EQ(output.find("Packet send failed"), std::string::npos);
|
||||
}
|
||||
|
||||
} // namespace esphome::sx126x::testing
|
||||
#endif
|
||||
@@ -1,182 +0,0 @@
|
||||
#include "sx126x_test_helpers.h"
|
||||
#include "esphome/components/logger/logger.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
|
||||
namespace esphome::sx126x::testing {
|
||||
|
||||
class RadioLogCallback {
|
||||
public:
|
||||
RadioLogCallback() : previous_(logger::global_logger) {
|
||||
this->logger_.pre_setup();
|
||||
this->logger_.set_log_level(ESPHOME_LOG_LEVEL_WARN);
|
||||
this->logger_.add_log_callback(this,
|
||||
[](void *instance, uint8_t level, const char *tag, const char *message, size_t len) {
|
||||
auto *self = static_cast<RadioLogCallback *>(instance);
|
||||
if (self->callback_) {
|
||||
self->callback_(std::string(message, len));
|
||||
}
|
||||
});
|
||||
}
|
||||
~RadioLogCallback() { logger::global_logger = this->previous_; }
|
||||
void set_callback(std::function<void(const std::string &)> callback) { this->callback_ = std::move(callback); }
|
||||
|
||||
private:
|
||||
std::function<void(const std::string &)> callback_;
|
||||
logger::Logger *previous_;
|
||||
logger::Logger logger_{0};
|
||||
};
|
||||
|
||||
struct ReentryCompletion final : SX126xTransmitListener {
|
||||
void on_transmit_complete(SX126xError result) override { this->results.push_back(result); }
|
||||
std::vector<SX126xError> results;
|
||||
};
|
||||
|
||||
// Setup reports why it failed, not a generic reason
|
||||
TEST(SX126xReentry, FailedSetupKeepsItsReason) {
|
||||
RadioLogCallback log;
|
||||
std::vector<std::string> messages;
|
||||
log.set_callback([&](const std::string &message) { messages.push_back(message); });
|
||||
RadioHardware hw;
|
||||
hw.supported_version = false;
|
||||
hw.configure(true, true);
|
||||
ASSERT_TRUE(hw.radio.is_failed());
|
||||
bool found = false;
|
||||
for (const auto &message : messages)
|
||||
found |= message.find("set Error flag: Unsupported chip version") != std::string::npos;
|
||||
EXPECT_TRUE(found);
|
||||
}
|
||||
|
||||
// Status logging is the only user code that can run inside a radio operation. It runs only
|
||||
// after the operation has committed its state, so a callback sees either a running send or a
|
||||
// released radio, and the interrupted operation touches nothing after the callback returns.
|
||||
|
||||
TEST(SX126xReentry, SuccessfulStartRunsNoUserCode) {
|
||||
RadioHardware hw;
|
||||
RadioLogCallback log;
|
||||
ReentryCompletion outer, nested;
|
||||
hw.configure(true, true);
|
||||
hw.auto_complete = false;
|
||||
hw.radio.status_set_warning(LOG_STR("Previous communication failure"));
|
||||
hw.irq = IRQ_TX_DONE; // A stale IRQ must not complete the new send either.
|
||||
unsigned callbacks = 0;
|
||||
log.set_callback([&](const std::string &message) {
|
||||
if (message.find("cleared Warning flag") != std::string::npos) {
|
||||
callbacks++;
|
||||
EXPECT_FALSE(hw.radio.is_transmitting()); // Only the completion clears the warning.
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&nested, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
}
|
||||
});
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&outer, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
EXPECT_EQ(callbacks, 0u);
|
||||
EXPECT_TRUE(outer.results.empty());
|
||||
LoopBlockingGuard clock{nullptr, nullptr, millis()};
|
||||
hw.radio.loop();
|
||||
EXPECT_TRUE(outer.results.empty()); // The stale IRQ was cleared before the send.
|
||||
hw.irq = IRQ_TX_DONE;
|
||||
hw.radio.loop();
|
||||
ASSERT_EQ(callbacks, 1u);
|
||||
EXPECT_EQ(outer.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_NONE}));
|
||||
EXPECT_TRUE(nested.results.empty());
|
||||
EXPECT_TRUE(hw.radio.is_transmitting());
|
||||
EXPECT_EQ(hw.sends, 2u);
|
||||
ASSERT_TRUE(hw.radio.cancel_transmit_async(&nested));
|
||||
EXPECT_EQ(nested.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_CANCELLED}));
|
||||
EXPECT_EQ(outer.results.size(), 1u);
|
||||
}
|
||||
|
||||
class SX126xStartReentry : public ::testing::TestWithParam<bool> {};
|
||||
|
||||
TEST_P(SX126xStartReentry, WarningCallbackAfterFailedStartSeesReleasedRadio) {
|
||||
const bool cold_sleep = GetParam();
|
||||
RadioHardware hw;
|
||||
RadioLogCallback log;
|
||||
ReentryCompletion outer, nested;
|
||||
hw.configure(true, true);
|
||||
hw.auto_complete = false;
|
||||
hw.radio.status_set_warning(LOG_STR("Previous communication failure"));
|
||||
hw.clear_trace();
|
||||
hw.fail_at = 3; // Preparation fails; restoration succeeds and clears the warning.
|
||||
unsigned callbacks = 0;
|
||||
size_t commands_after_callback = 0;
|
||||
log.set_callback([&](const std::string &message) {
|
||||
if (message.find("cleared Warning flag") != std::string::npos) {
|
||||
callbacks++;
|
||||
EXPECT_FALSE(hw.radio.is_transmitting());
|
||||
EXPECT_EQ(hw.receiving, true); // Restoration finished before the callback.
|
||||
if (cold_sleep) {
|
||||
hw.radio.set_mode_sleep(true);
|
||||
} else {
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&nested, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
}
|
||||
commands_after_callback = hw.transactions.size();
|
||||
}
|
||||
});
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&outer, hw.packet), SX126xError::SX126X_ERROR_BUSY_TIMEOUT);
|
||||
ASSERT_EQ(callbacks, 1u);
|
||||
EXPECT_EQ(hw.transactions.size(), commands_after_callback); // The failed start touched nothing after it.
|
||||
EXPECT_TRUE(outer.results.empty()); // A rejected start never completes.
|
||||
if (cold_sleep) {
|
||||
EXPECT_FALSE(hw.radio.is_transmitting());
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&outer, hw.packet), SX126xError::SX126X_ERROR_NOT_READY);
|
||||
EXPECT_EQ(hw.sends, 0u);
|
||||
return;
|
||||
}
|
||||
EXPECT_TRUE(hw.radio.is_transmitting());
|
||||
EXPECT_EQ(hw.sends, 1u);
|
||||
hw.irq = IRQ_TX_DONE;
|
||||
hw.radio.loop();
|
||||
EXPECT_EQ(nested.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_NONE}));
|
||||
EXPECT_TRUE(outer.results.empty());
|
||||
}
|
||||
|
||||
INSTANTIATE_TEST_SUITE_P(NestedSendOrColdSleep, SX126xStartReentry, ::testing::Bool());
|
||||
|
||||
class SX126xPollingReentry : public ::testing::TestWithParam<std::tuple<unsigned, bool>> {};
|
||||
|
||||
TEST_P(SX126xPollingReentry, WarningCallbackCannotCancelOrDisturbAFinishedSend) {
|
||||
const auto [failed_command, reuse_listener] = GetParam();
|
||||
RadioHardware hw;
|
||||
RadioLogCallback log;
|
||||
ReentryCompletion first, second;
|
||||
auto *replacement = reuse_listener ? &first : &second;
|
||||
hw.configure(true, true);
|
||||
hw.auto_complete = false;
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&first, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
hw.clear_trace();
|
||||
hw.fail_at = failed_command; // 0: success, 1: IRQ read fails, 2: IRQ clear fails.
|
||||
hw.irq = IRQ_TX_DONE;
|
||||
hw.radio.status_set_warning(LOG_STR("Previous communication failure"));
|
||||
unsigned callbacks = 0;
|
||||
size_t commands_after_replacement = 0;
|
||||
log.set_callback([&](const std::string &message) {
|
||||
if (callbacks == 0 && message.find("cleared Warning flag") != std::string::npos) {
|
||||
callbacks++;
|
||||
EXPECT_TRUE(first.results.empty()); // Status is reported before the completion.
|
||||
EXPECT_FALSE(hw.radio.cancel_transmit_async(&first)); // Already finished: no second completion.
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(replacement, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
commands_after_replacement = hw.transactions.size();
|
||||
}
|
||||
});
|
||||
{
|
||||
LoopBlockingGuard clock{nullptr, nullptr, millis()};
|
||||
hw.radio.loop();
|
||||
}
|
||||
ASSERT_EQ(callbacks, 1u);
|
||||
const auto expected = failed_command == 0 ? SX126xError::SX126X_ERROR_NONE : SX126xError::SX126X_ERROR_BUSY_TIMEOUT;
|
||||
EXPECT_EQ(first.results, (std::vector<SX126xError>{expected}));
|
||||
EXPECT_TRUE(second.results.empty());
|
||||
EXPECT_TRUE(hw.radio.is_transmitting());
|
||||
EXPECT_EQ(hw.transactions.size(), commands_after_replacement); // No stale IRQ clear or restoration.
|
||||
hw.irq = IRQ_TX_DONE;
|
||||
hw.radio.loop();
|
||||
ASSERT_EQ(replacement->results.size(), reuse_listener ? 2u : 1u);
|
||||
EXPECT_EQ(replacement->results.back(), SX126xError::SX126X_ERROR_NONE);
|
||||
EXPECT_FALSE(hw.radio.is_transmitting());
|
||||
}
|
||||
|
||||
INSTANTIATE_TEST_SUITE_P(ReadSuccessReadFailureAndClearFailure, SX126xPollingReentry,
|
||||
::testing::Combine(::testing::Values(0u, 1u, 2u), ::testing::Bool()));
|
||||
|
||||
} // namespace esphome::sx126x::testing
|
||||
@@ -1,127 +0,0 @@
|
||||
#include "sx126x_test_helpers.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include <tuple>
|
||||
|
||||
namespace esphome::sx126x::testing {
|
||||
|
||||
struct RejectedCompletion final : SX126xTransmitListener {
|
||||
void on_transmit_complete(SX126xError result) override { ADD_FAILURE() << "Rejected transmission completed"; }
|
||||
};
|
||||
|
||||
class SX126xReceiveRetry : public ::testing::TestWithParam<std::tuple<bool, unsigned, bool>> {};
|
||||
|
||||
TEST_P(SX126xReceiveRetry, PersistentBusyIsRateLimitedAndRecoversWithoutNewEdge) {
|
||||
const auto [held_receive, failed_command, rollover] = GetParam();
|
||||
RadioHardware hw;
|
||||
PacketListener listener;
|
||||
RejectedCompletion tx;
|
||||
hw.configure(true, true);
|
||||
hw.radio.register_listener(&listener);
|
||||
hw.radio.call();
|
||||
hw.dio.internal = true;
|
||||
if (held_receive) {
|
||||
auto write = hw.cs.on_write;
|
||||
hw.cs.on_write = [&](bool high) {
|
||||
write(high);
|
||||
if (high && !hw.transactions.back().empty() && hw.transactions.back()[0] == RADIO_SET_STANDBY) {
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
}
|
||||
};
|
||||
EXPECT_EQ(hw.radio.start_transmit_async(&tx, hw.packet), SX126xError::SX126X_ERROR_BUSY);
|
||||
hw.cs.on_write = write;
|
||||
}
|
||||
hw.clear_trace();
|
||||
hw.irq = IRQ_RX_DONE;
|
||||
hw.fail_at = failed_command;
|
||||
const uint32_t start = rollover ? 0xFFFFFFF0u : 1000;
|
||||
{
|
||||
LoopBlockingGuard clock{nullptr, nullptr, start};
|
||||
hw.radio.call();
|
||||
}
|
||||
hw.expect_aborted(failed_command);
|
||||
EXPECT_EQ(hw.irq, IRQ_RX_DONE);
|
||||
const auto normal_busy = hw.busy.on_read;
|
||||
hw.busy.on_read = []() { return true; };
|
||||
for (uint32_t elapsed = 1; elapsed < 200; elapsed++) {
|
||||
LoopBlockingGuard clock{nullptr, nullptr, start + elapsed};
|
||||
hw.radio.call();
|
||||
}
|
||||
EXPECT_EQ(hw.transactions.size(), failed_command); // No SPI/BUSY waits inside the retry interval.
|
||||
{
|
||||
LoopBlockingGuard clock{nullptr, nullptr, start + 200};
|
||||
hw.radio.call();
|
||||
}
|
||||
ASSERT_EQ(hw.transactions.size(), failed_command + 1);
|
||||
EXPECT_TRUE(hw.transactions.back().empty());
|
||||
EXPECT_TRUE(hw.radio.is_in_loop_state());
|
||||
EXPECT_TRUE(hw.cs.level);
|
||||
EXPECT_EQ(hw.irq, IRQ_RX_DONE);
|
||||
EXPECT_TRUE(listener.packets.empty());
|
||||
hw.busy.on_read = normal_busy;
|
||||
hw.fail_at = 0;
|
||||
{
|
||||
LoopBlockingGuard clock{nullptr, nullptr, start + 399};
|
||||
hw.radio.call();
|
||||
EXPECT_EQ(hw.transactions.size(), failed_command + 1);
|
||||
}
|
||||
{
|
||||
LoopBlockingGuard clock{nullptr, nullptr, start + 400};
|
||||
hw.radio.call();
|
||||
}
|
||||
ASSERT_EQ(listener.packets.size(), 1u);
|
||||
EXPECT_EQ(listener.packets.front(), hw.packet);
|
||||
EXPECT_FALSE(hw.radio.status_has_warning());
|
||||
EXPECT_TRUE(hw.receiving);
|
||||
EXPECT_EQ(hw.sends, 0u);
|
||||
hw.radio.call();
|
||||
EXPECT_EQ(listener.packets.size(), 1u);
|
||||
}
|
||||
|
||||
INSTANTIATE_TEST_SUITE_P(IdleAndHeldRxWithIrqAndPacketFailuresAcrossRollover, SX126xReceiveRetry,
|
||||
::testing::Combine(::testing::Bool(), ::testing::Values(1u, 2u), ::testing::Bool()));
|
||||
|
||||
TEST(SX126xReceiveRetry, SuccessfulConfigurationClearsBackoffAndOtherRadiosRemainIndependent) {
|
||||
RadioHardware failed, other;
|
||||
PacketListener recovered, unaffected;
|
||||
failed.configure(true, true);
|
||||
other.configure(true, true);
|
||||
failed.radio.register_listener(&recovered);
|
||||
other.radio.register_listener(&unaffected);
|
||||
failed.clear_trace();
|
||||
failed.fail_at = 1;
|
||||
failed.irq = IRQ_RX_DONE;
|
||||
LoopBlockingGuard clock{nullptr, nullptr, 1000};
|
||||
failed.radio.loop();
|
||||
other.irq = IRQ_RX_DONE;
|
||||
other.radio.loop();
|
||||
ASSERT_EQ(unaffected.packets.size(), 1u);
|
||||
EXPECT_TRUE(recovered.packets.empty());
|
||||
failed.clear_trace();
|
||||
failed.radio.configure();
|
||||
failed.irq = IRQ_RX_DONE;
|
||||
failed.radio.loop();
|
||||
ASSERT_EQ(recovered.packets.size(), 1u); // Explicit recovery does not wait for the old retry deadline.
|
||||
}
|
||||
|
||||
TEST(SX126xReceiveRetry, ReceiveBackoffDoesNotDelayTransmitCompletion) {
|
||||
struct Completion final : SX126xTransmitListener {
|
||||
void on_transmit_complete(SX126xError result) override { this->results.push_back(result); }
|
||||
std::vector<SX126xError> results;
|
||||
} tx;
|
||||
RadioHardware hw;
|
||||
hw.configure(true, true);
|
||||
hw.clear_trace();
|
||||
hw.fail_at = 1;
|
||||
hw.irq = IRQ_TX_DONE; // Failed read of an unrelated stale IRQ starts the RX retry gate.
|
||||
LoopBlockingGuard clock{nullptr, nullptr, millis()};
|
||||
hw.radio.loop();
|
||||
EXPECT_TRUE(hw.radio.status_has_warning());
|
||||
hw.clear_trace();
|
||||
hw.irq = 0;
|
||||
ASSERT_EQ(hw.radio.start_transmit_async(&tx, hw.packet), SX126xError::SX126X_ERROR_NONE);
|
||||
hw.radio.loop(); // Same cached tick, before the RX retry gate opens.
|
||||
EXPECT_EQ(tx.results, (std::vector<SX126xError>{SX126xError::SX126X_ERROR_NONE}));
|
||||
EXPECT_TRUE(hw.receiving);
|
||||
}
|
||||
|
||||
} // namespace esphome::sx126x::testing
|
||||
@@ -1,237 +0,0 @@
|
||||
#pragma once
|
||||
#include <gtest/gtest.h>
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
#include "esphome/components/sx126x/sx126x.h"
|
||||
namespace esphome::sx126x::testing {
|
||||
class TestPin : public GPIOPin {
|
||||
public:
|
||||
void setup() override {}
|
||||
void pin_mode(gpio::Flags flags) override {}
|
||||
gpio::Flags get_flags() const override { return gpio::FLAG_NONE; }
|
||||
size_t dump_summary(char *buffer, size_t len) const override { return snprintf(buffer, len, "test"); }
|
||||
bool digital_read() override {
|
||||
this->reads++;
|
||||
return this->on_read ? this->on_read() : this->level;
|
||||
}
|
||||
void digital_write(bool level) override {
|
||||
this->writes++;
|
||||
this->level = level;
|
||||
if (this->on_write) {
|
||||
this->on_write(level);
|
||||
}
|
||||
}
|
||||
bool is_internal() override { return this->internal; }
|
||||
|
||||
bool level{false};
|
||||
bool internal{false};
|
||||
unsigned reads{0};
|
||||
unsigned writes{0};
|
||||
std::function<bool()> on_read;
|
||||
std::function<void(bool)> on_write;
|
||||
};
|
||||
|
||||
// Exercise the real software SPI adapter and driver through GPIO pins. Each CS
|
||||
// assertion starts a command; BUSY can reject any one of those commands.
|
||||
class RadioHardware {
|
||||
public:
|
||||
RadioHardware() {
|
||||
this->cs.level = true;
|
||||
this->cs.on_write = [this](bool high) {
|
||||
if (!high) {
|
||||
EXPECT_FALSE(this->selected_);
|
||||
this->selected_ = true;
|
||||
this->transactions.emplace_back();
|
||||
this->bit_ = 0;
|
||||
this->byte_ = 0;
|
||||
this->busy.level = this->transactions.size() == this->fail_at;
|
||||
} else if (this->selected_) {
|
||||
this->selected_ = false;
|
||||
this->ends++;
|
||||
const auto &command = this->transactions.back();
|
||||
if (command.empty()) {
|
||||
return;
|
||||
}
|
||||
switch (command[0]) {
|
||||
case RADIO_SET_PACKETPARAMS:
|
||||
this->packet_params = command;
|
||||
break;
|
||||
case RADIO_CLR_IRQSTATUS:
|
||||
this->irq &= ~((uint16_t(command[1]) << 8) | command[2]);
|
||||
break;
|
||||
case RADIO_SET_TX:
|
||||
this->sends++;
|
||||
if (this->auto_complete) {
|
||||
this->irq |= IRQ_TX_DONE;
|
||||
}
|
||||
break;
|
||||
case RADIO_SET_RX:
|
||||
this->receiving = true;
|
||||
break;
|
||||
case RADIO_SET_SLEEP:
|
||||
case RADIO_SET_STANDBY:
|
||||
this->receiving = false;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (this->on_command) {
|
||||
this->on_command(command[0]);
|
||||
}
|
||||
}
|
||||
};
|
||||
this->busy.on_read = [this]() {
|
||||
EXPECT_TRUE(this->selected_); // NSS must wake the chip before waiting.
|
||||
return this->busy.level;
|
||||
};
|
||||
this->miso.on_read = [this]() {
|
||||
EXPECT_TRUE(this->selected_);
|
||||
EXPECT_FALSE(this->busy.level); // No clocks/data may follow a BUSY timeout.
|
||||
auto &command = this->transactions.back();
|
||||
const bool bit = (this->reply_byte_(command) >> (7 - this->bit_)) & 1;
|
||||
this->byte_ = (this->byte_ << 1) | this->mosi.level;
|
||||
if (++this->bit_ == 8) {
|
||||
command.push_back(this->byte_);
|
||||
this->byte_ = 0;
|
||||
this->bit_ = 0;
|
||||
}
|
||||
return bit;
|
||||
};
|
||||
this->dio.on_read = [this]() { return this->irq != 0; };
|
||||
this->rst.on_write = [this](bool high) {
|
||||
if (!high) {
|
||||
this->irq = 0;
|
||||
}
|
||||
};
|
||||
this->spi.set_clk(&this->clk);
|
||||
this->spi.set_mosi(&this->mosi);
|
||||
this->spi.set_miso(&this->miso);
|
||||
// call() runs setup() and marks the bus set up, so it accepts devices
|
||||
this->spi.call();
|
||||
this->radio.set_spi_parent(&this->spi);
|
||||
this->radio.set_cs_pin(&this->cs);
|
||||
this->radio.set_busy_pin(&this->busy);
|
||||
this->radio.set_dio1_pin(&this->dio);
|
||||
this->radio.set_rst_pin(&this->rst);
|
||||
this->radio.set_frequency(915000000);
|
||||
this->radio.set_tcxo_voltage(TCXO_CTRL_1_8V);
|
||||
this->radio.set_rf_switch(true);
|
||||
this->radio.set_crc_enable(true);
|
||||
this->radio.set_sync_value({0x14, 0x24});
|
||||
}
|
||||
~RadioHardware() {
|
||||
// The configuration retry interval (id 0) must not outlive the radio
|
||||
App.scheduler.cancel_interval(&this->radio, uint32_t{0});
|
||||
this->radio.spi_teardown();
|
||||
}
|
||||
|
||||
void configure(bool lora, bool rx, bool fixed = false) {
|
||||
this->radio.set_modulation(lora ? PACKET_TYPE_LORA : PACKET_TYPE_GFSK);
|
||||
this->radio.set_bandwidth(lora ? SX126X_BW_125000 : SX126X_BW_4800);
|
||||
this->radio.set_bitrate(4800);
|
||||
this->radio.set_rx_start(rx);
|
||||
this->radio.set_payload_length(fixed ? 3 : 0);
|
||||
this->radio.call(); // The normal component lifecycle runs setup().
|
||||
}
|
||||
|
||||
void clear_trace() {
|
||||
this->transactions.clear();
|
||||
this->ends = 0;
|
||||
this->fail_at = 0;
|
||||
this->busy.level = false;
|
||||
this->dio.reads = 0;
|
||||
}
|
||||
|
||||
void expect_aborted(size_t command) {
|
||||
ASSERT_EQ(this->transactions.size(), command);
|
||||
EXPECT_TRUE(this->transactions.back().empty());
|
||||
EXPECT_EQ(this->ends, command);
|
||||
EXPECT_TRUE(this->cs.level);
|
||||
}
|
||||
|
||||
SX126x radio;
|
||||
spi::SPIComponent spi;
|
||||
TestPin cs, busy, dio, rst, clk, mosi, miso;
|
||||
std::vector<std::vector<uint8_t>> transactions;
|
||||
std::vector<uint8_t> packet{0x11, 0x22, 0x33};
|
||||
std::vector<uint8_t> packet_params;
|
||||
size_t fail_at{0};
|
||||
size_t ends{0};
|
||||
unsigned sends{0};
|
||||
uint16_t irq{0};
|
||||
// Called as each command ends, with its opcode
|
||||
std::function<void(uint8_t)> on_command;
|
||||
bool receiving{false};
|
||||
bool auto_complete{true};
|
||||
bool supported_version{true};
|
||||
|
||||
protected:
|
||||
uint8_t reply_byte_(const std::vector<uint8_t> &command) {
|
||||
if (command.empty()) {
|
||||
return 0;
|
||||
}
|
||||
const size_t pos = command.size();
|
||||
switch (command[0]) {
|
||||
case RADIO_READ_REGISTER:
|
||||
if (pos >= 4) {
|
||||
static constexpr char VERSION[16] = "SX1262";
|
||||
return this->supported_version ? VERSION[pos - 4] : 0;
|
||||
}
|
||||
break;
|
||||
case RADIO_GET_IRQSTATUS:
|
||||
if (pos == 2) {
|
||||
return this->irq >> 8;
|
||||
}
|
||||
if (pos == 3) {
|
||||
return this->irq & 0xFF;
|
||||
}
|
||||
break;
|
||||
case RADIO_GET_PACKETSTATUS:
|
||||
if (pos == 2) {
|
||||
return 80;
|
||||
}
|
||||
if (pos == 3) {
|
||||
return 40;
|
||||
}
|
||||
if (pos == 4) {
|
||||
return 84;
|
||||
}
|
||||
break;
|
||||
case RADIO_GET_RXBUFFERSTATUS:
|
||||
if (pos == 2) {
|
||||
return this->packet.size();
|
||||
}
|
||||
if (pos == 3) {
|
||||
return 7;
|
||||
}
|
||||
break;
|
||||
case RADIO_READ_BUFFER:
|
||||
if (pos >= 3) {
|
||||
EXPECT_EQ(command[1], 7);
|
||||
return this->packet[pos - 3];
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool selected_{false};
|
||||
uint8_t bit_{0};
|
||||
uint8_t byte_{0};
|
||||
};
|
||||
|
||||
class PacketListener : public SX126xListener {
|
||||
public:
|
||||
void on_packet(const std::vector<uint8_t> &packet, float rssi, float snr) override {
|
||||
this->packets.push_back(packet);
|
||||
this->rssi = rssi;
|
||||
this->snr = snr;
|
||||
}
|
||||
std::vector<std::vector<uint8_t>> packets;
|
||||
float rssi{};
|
||||
float snr{};
|
||||
};
|
||||
|
||||
} // namespace esphome::sx126x::testing
|
||||
Reference in new issue
Block a user