1
0
mirror of https://github.com/esphome/esphome.git synced 2026-02-09 09:11:52 +00:00

Compare commits

..

1 Commits

Author SHA1 Message Date
J. Nick Koston
60298f67b8 [ms8607] Replace set_retry with set_timeout chain to avoid heap allocation
set_retry internally does a std::make_shared<RetryArgs>() heap allocation
on every invocation. Replace with a try_reset_() method that chains
set_timeout calls with manual backoff, preserving the same timing
(immediate, +5ms, +25ms).
2026-02-07 14:53:18 -06:00
7 changed files with 65 additions and 93 deletions

View File

@@ -4,7 +4,7 @@
namespace esphome::epaper_spi {
class EPaperSpectraE6 final : public EPaperBase {
class EPaperSpectraE6 : public EPaperBase {
public:
EPaperSpectraE6(const char *name, uint16_t width, uint16_t height, const uint8_t *init_sequence,
size_t init_sequence_length)

View File

@@ -6,7 +6,7 @@ namespace esphome::epaper_spi {
/**
* An epaper display that needs LUTs to be sent to it.
*/
class EpaperWaveshare final : public EPaperMono {
class EpaperWaveshare : public EPaperMono {
public:
EpaperWaveshare(const char *name, uint16_t width, uint16_t height, const uint8_t *init_sequence,
size_t init_sequence_length, const uint8_t *lut, size_t lut_length, const uint8_t *partial_lut,

View File

@@ -219,50 +219,39 @@ void Modbus::send(uint8_t address, uint8_t function_code, uint16_t start_address
return;
}
static constexpr size_t ADDR_SIZE = 1;
static constexpr size_t FC_SIZE = 1;
static constexpr size_t START_ADDR_SIZE = 2;
static constexpr size_t NUM_ENTITIES_SIZE = 2;
static constexpr size_t BYTE_COUNT_SIZE = 1;
static constexpr size_t MAX_PAYLOAD_SIZE = std::numeric_limits<uint8_t>::max();
static constexpr size_t CRC_SIZE = 2;
static constexpr size_t MAX_FRAME_SIZE =
ADDR_SIZE + FC_SIZE + START_ADDR_SIZE + NUM_ENTITIES_SIZE + BYTE_COUNT_SIZE + MAX_PAYLOAD_SIZE + CRC_SIZE;
uint8_t data[MAX_FRAME_SIZE];
size_t pos = 0;
data[pos++] = address;
data[pos++] = function_code;
std::vector<uint8_t> data;
data.push_back(address);
data.push_back(function_code);
if (this->role == ModbusRole::CLIENT) {
data[pos++] = start_address >> 8;
data[pos++] = start_address >> 0;
data.push_back(start_address >> 8);
data.push_back(start_address >> 0);
if (function_code != ModbusFunctionCode::WRITE_SINGLE_COIL &&
function_code != ModbusFunctionCode::WRITE_SINGLE_REGISTER) {
data[pos++] = number_of_entities >> 8;
data[pos++] = number_of_entities >> 0;
data.push_back(number_of_entities >> 8);
data.push_back(number_of_entities >> 0);
}
}
if (payload != nullptr) {
if (this->role == ModbusRole::SERVER || function_code == ModbusFunctionCode::WRITE_MULTIPLE_COILS ||
function_code == ModbusFunctionCode::WRITE_MULTIPLE_REGISTERS) { // Write multiple
data[pos++] = payload_len; // Byte count is required for write
data.push_back(payload_len); // Byte count is required for write
} else {
payload_len = 2; // Write single register or coil
}
for (int i = 0; i < payload_len; i++) {
data[pos++] = payload[i];
data.push_back(payload[i]);
}
}
auto crc = crc16(data, pos);
data[pos++] = crc >> 0;
data[pos++] = crc >> 8;
auto crc = crc16(data.data(), data.size());
data.push_back(crc >> 0);
data.push_back(crc >> 8);
if (this->flow_control_pin_ != nullptr)
this->flow_control_pin_->digital_write(true);
this->write_array(data, pos);
this->write_array(data);
this->flush();
if (this->flow_control_pin_ != nullptr)
@@ -272,7 +261,7 @@ void Modbus::send(uint8_t address, uint8_t function_code, uint16_t start_address
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char hex_buf[format_hex_pretty_size(MODBUS_MAX_LOG_BYTES)];
#endif
ESP_LOGV(TAG, "Modbus write: %s", format_hex_pretty_to(hex_buf, data, pos));
ESP_LOGV(TAG, "Modbus write: %s", format_hex_pretty_to(hex_buf, data.data(), data.size()));
}
// Helper function for lambdas

View File

@@ -72,53 +72,55 @@ void MS8607Component::setup() {
// I do not know why the device sometimes NACKs the reset command, but
// try 3 times in case it's a transitory issue on this boot
this->set_retry(
"reset", 5, 3,
[this](const uint8_t remaining_setup_attempts) {
ESP_LOGD(TAG, "Resetting both I2C addresses: 0x%02X, 0x%02X", this->address_,
this->humidity_device_->get_address());
// I believe sending the reset command to both addresses is preferable to
// skipping humidity if PT fails for some reason.
// However, only consider the reset successful if they both ACK
bool const pt_successful = this->write_bytes(MS8607_PT_CMD_RESET, nullptr, 0);
bool const h_successful = this->humidity_device_->write_bytes(MS8607_CMD_H_RESET, nullptr, 0);
// Backoff: executes at now, +5ms, +30ms
this->reset_attempts_remaining_ = 3;
this->reset_interval_ = 5;
this->try_reset_();
}
if (!(pt_successful && h_successful)) {
ESP_LOGE(TAG, "Resetting I2C devices failed");
if (!pt_successful && !h_successful) {
this->error_code_ = ErrorCode::PTH_RESET_FAILED;
} else if (!pt_successful) {
this->error_code_ = ErrorCode::PT_RESET_FAILED;
} else {
this->error_code_ = ErrorCode::H_RESET_FAILED;
}
void MS8607Component::try_reset_() {
ESP_LOGD(TAG, "Resetting both I2C addresses: 0x%02X, 0x%02X", this->address_, this->humidity_device_->get_address());
// I believe sending the reset command to both addresses is preferable to
// skipping humidity if PT fails for some reason.
// However, only consider the reset successful if they both ACK
bool const pt_successful = this->write_bytes(MS8607_PT_CMD_RESET, nullptr, 0);
bool const h_successful = this->humidity_device_->write_bytes(MS8607_CMD_H_RESET, nullptr, 0);
if (remaining_setup_attempts > 0) {
this->status_set_error();
} else {
this->mark_failed();
}
return RetryResult::RETRY;
}
if (!(pt_successful && h_successful)) {
ESP_LOGE(TAG, "Resetting I2C devices failed");
if (!pt_successful && !h_successful) {
this->error_code_ = ErrorCode::PTH_RESET_FAILED;
} else if (!pt_successful) {
this->error_code_ = ErrorCode::PT_RESET_FAILED;
} else {
this->error_code_ = ErrorCode::H_RESET_FAILED;
}
this->setup_status_ = SetupStatus::NEEDS_PROM_READ;
this->error_code_ = ErrorCode::NONE;
this->status_clear_error();
if (--this->reset_attempts_remaining_ > 0) {
uint32_t delay = this->reset_interval_;
this->reset_interval_ *= 5;
this->set_timeout("reset", delay, [this]() { this->try_reset_(); });
this->status_set_error();
} else {
this->mark_failed();
}
return;
}
// 15ms delay matches datasheet, Adafruit_MS8607 & SparkFun_PHT_MS8607_Arduino_Library
this->set_timeout("prom-read", 15, [this]() {
if (this->read_calibration_values_from_prom_()) {
this->setup_status_ = SetupStatus::SUCCESSFUL;
this->status_clear_error();
} else {
this->mark_failed();
return;
}
});
this->setup_status_ = SetupStatus::NEEDS_PROM_READ;
this->error_code_ = ErrorCode::NONE;
this->status_clear_error();
return RetryResult::DONE;
},
5.0f); // executes at now, +5ms, +25ms
// 15ms delay matches datasheet, Adafruit_MS8607 & SparkFun_PHT_MS8607_Arduino_Library
this->set_timeout("prom-read", 15, [this]() {
if (this->read_calibration_values_from_prom_()) {
this->setup_status_ = SetupStatus::SUCCESSFUL;
this->status_clear_error();
} else {
this->mark_failed();
return;
}
});
}
void MS8607Component::update() {

View File

@@ -44,6 +44,8 @@ class MS8607Component : public PollingComponent, public i2c::I2CDevice {
void set_humidity_device(MS8607HumidityDevice *humidity_device) { humidity_device_ = humidity_device; }
protected:
/// Attempt to reset both I2C devices, retrying with backoff on failure
void try_reset_();
/**
Read and store the Pressure & Temperature calibration settings from the PROM.
Intended to be called during setup(), this will set the `failure_reason_`
@@ -102,6 +104,8 @@ class MS8607Component : public PollingComponent, public i2c::I2CDevice {
enum class SetupStatus;
/// Current step in the multi-step & possibly delayed setup() process
SetupStatus setup_status_;
uint32_t reset_interval_{5};
uint8_t reset_attempts_remaining_{0};
};
} // namespace ms8607

View File

@@ -317,7 +317,6 @@ class EsphomeCommandWebSocket(CheckOriginMixin, tornado.websocket.WebSocketHandl
# Check if the proc was not forcibly closed
_LOGGER.info("Process exited with return code %s", returncode)
self.write_message({"event": "exit", "code": returncode})
self.close()
def on_close(self) -> None:
# Check if proc exists (if 'start' has been run)

View File

@@ -29,7 +29,7 @@ from esphome.dashboard.entries import (
bool_to_entry_state,
)
from esphome.dashboard.models import build_importable_device_dict
from esphome.dashboard.web_server import DashboardSubscriber, EsphomeCommandWebSocket
from esphome.dashboard.web_server import DashboardSubscriber
from esphome.zeroconf import DiscoveredImport
from .common import get_fixture_path
@@ -1654,25 +1654,3 @@ async def test_websocket_check_origin_multiple_trusted_domains(
assert data["event"] == "initial_state"
finally:
ws.close()
def test_proc_on_exit_calls_close() -> None:
"""Test _proc_on_exit sends exit event and closes the WebSocket."""
handler = Mock(spec=EsphomeCommandWebSocket)
handler._is_closed = False
EsphomeCommandWebSocket._proc_on_exit(handler, 0)
handler.write_message.assert_called_once_with({"event": "exit", "code": 0})
handler.close.assert_called_once()
def test_proc_on_exit_skips_when_already_closed() -> None:
"""Test _proc_on_exit does nothing when WebSocket is already closed."""
handler = Mock(spec=EsphomeCommandWebSocket)
handler._is_closed = True
EsphomeCommandWebSocket._proc_on_exit(handler, 0)
handler.write_message.assert_not_called()
handler.close.assert_not_called()