mirror of
https://github.com/esphome/esphome.git
synced 2026-09-08 14:06:10 +00:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
96e5f98110 | ||
|
|
24ec7ca3a7 | ||
|
|
e9f25a55b0 | ||
|
|
f91486305f | ||
|
|
f191d5e0c3 | ||
|
|
227ca90aad | ||
|
|
1700a40b7c | ||
|
|
28588310e7 | ||
|
|
10a9baff74 | ||
|
|
a23f7bb569 | ||
|
|
53075e4139 | ||
|
|
5722ccba37 | ||
|
|
94e5c3839d | ||
|
|
574762f078 | ||
|
|
d34ffaf392 | ||
|
|
e6aa575f2e | ||
|
|
639ce609bf | ||
|
|
62eafc477d |
+1
-1
@@ -22,7 +22,7 @@ RUN \
|
||||
-r /requirements.txt
|
||||
|
||||
# Install the ESPHome Device Builder dashboard.
|
||||
RUN uv pip install --no-cache-dir esphome-device-builder==1.14.4
|
||||
RUN uv pip install --no-cache-dir esphome-device-builder==1.14.5
|
||||
|
||||
RUN \
|
||||
platformio settings set enable_telemetry No \
|
||||
|
||||
@@ -13,7 +13,7 @@ void Anova::dump_config() { LOG_CLIMATE("", "Anova BLE Cooker", this); }
|
||||
|
||||
void Anova::setup() {
|
||||
this->codec_ = make_unique<AnovaCodec>();
|
||||
this->current_request_ = 0;
|
||||
this->poll_step_ = PollStep::IDLE;
|
||||
}
|
||||
|
||||
void Anova::loop() {
|
||||
@@ -22,6 +22,15 @@ void Anova::loop() {
|
||||
this->disable_loop();
|
||||
}
|
||||
|
||||
void Anova::write_request_(AnovaPacket *pkt) {
|
||||
auto status =
|
||||
esp_ble_gattc_write_char(this->parent_->get_gattc_if(), this->parent_->get_conn_id(), this->char_handle_,
|
||||
pkt->length, pkt->data, ESP_GATT_WRITE_TYPE_NO_RSP, ESP_GATT_AUTH_REQ_NONE);
|
||||
if (status) {
|
||||
ESP_LOGW(TAG, "[%s] esp_ble_gattc_write_char failed, status=%d", this->parent_->address_str(), status);
|
||||
}
|
||||
}
|
||||
|
||||
void Anova::control(const ClimateCall &call) {
|
||||
auto mode_val = call.get_mode();
|
||||
if (mode_val.has_value()) {
|
||||
@@ -38,22 +47,11 @@ void Anova::control(const ClimateCall &call) {
|
||||
ESP_LOGW(TAG, "Unsupported mode: %d", mode);
|
||||
return;
|
||||
}
|
||||
auto status =
|
||||
esp_ble_gattc_write_char(this->parent_->get_gattc_if(), this->parent_->get_conn_id(), this->char_handle_,
|
||||
pkt->length, pkt->data, ESP_GATT_WRITE_TYPE_NO_RSP, ESP_GATT_AUTH_REQ_NONE);
|
||||
if (status) {
|
||||
ESP_LOGW(TAG, "[%s] esp_ble_gattc_write_char failed, status=%d", this->parent_->address_str(), status);
|
||||
}
|
||||
this->write_request_(pkt);
|
||||
}
|
||||
auto target_temp = call.get_target_temperature();
|
||||
if (target_temp.has_value()) {
|
||||
auto *pkt = this->codec_->get_set_target_temp_request(*target_temp);
|
||||
auto status =
|
||||
esp_ble_gattc_write_char(this->parent_->get_gattc_if(), this->parent_->get_conn_id(), this->char_handle_,
|
||||
pkt->length, pkt->data, ESP_GATT_WRITE_TYPE_NO_RSP, ESP_GATT_AUTH_REQ_NONE);
|
||||
if (status) {
|
||||
ESP_LOGW(TAG, "[%s] esp_ble_gattc_write_char failed, status=%d", this->parent_->address_str(), status);
|
||||
}
|
||||
this->write_request_(this->codec_->get_set_target_temp_request(*target_temp));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,6 +60,7 @@ void Anova::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_
|
||||
case ESP_GATTC_DISCONNECT_EVT: {
|
||||
this->current_temperature = NAN;
|
||||
this->target_temperature = NAN;
|
||||
this->poll_step_ = PollStep::IDLE;
|
||||
this->publish_state();
|
||||
break;
|
||||
}
|
||||
@@ -83,8 +82,8 @@ void Anova::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_
|
||||
}
|
||||
case ESP_GATTC_REG_FOR_NOTIFY_EVT: {
|
||||
this->node_state = espbt::ClientState::ESTABLISHED;
|
||||
this->current_request_ = 0;
|
||||
this->update();
|
||||
this->poll_step_ = PollStep::IDLE;
|
||||
this->update(); // begin the first poll cycle immediately
|
||||
break;
|
||||
}
|
||||
case ESP_GATTC_NOTIFY_EVT: {
|
||||
@@ -101,33 +100,30 @@ void Anova::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_
|
||||
this->mode = this->codec_->running_ ? climate::CLIMATE_MODE_HEAT : climate::CLIMATE_MODE_OFF;
|
||||
}
|
||||
if (this->codec_->has_unit()) {
|
||||
this->fahrenheit_ = (this->codec_->unit_ == 'f');
|
||||
ESP_LOGD(TAG, "Anova units is %s", this->fahrenheit_ ? "fahrenheit" : "celsius");
|
||||
this->current_request_++;
|
||||
ESP_LOGD(TAG, "Anova units is %s", (this->codec_->unit_ == 'f') ? "fahrenheit" : "celsius");
|
||||
}
|
||||
this->publish_state();
|
||||
|
||||
if (this->current_request_ > 1) {
|
||||
AnovaPacket *pkt = nullptr;
|
||||
switch (this->current_request_++) {
|
||||
case 2:
|
||||
pkt = this->codec_->get_read_target_temp_request();
|
||||
break;
|
||||
case 3:
|
||||
pkt = this->codec_->get_read_current_temp_request();
|
||||
break;
|
||||
default:
|
||||
this->current_request_ = 1;
|
||||
break;
|
||||
}
|
||||
if (pkt != nullptr) {
|
||||
auto status =
|
||||
esp_ble_gattc_write_char(this->parent_->get_gattc_if(), this->parent_->get_conn_id(), this->char_handle_,
|
||||
pkt->length, pkt->data, ESP_GATT_WRITE_TYPE_NO_RSP, ESP_GATT_AUTH_REQ_NONE);
|
||||
if (status) {
|
||||
ESP_LOGW(TAG, "[%s] esp_ble_gattc_write_char failed, status=%d", this->parent_->address_str(), status);
|
||||
}
|
||||
}
|
||||
// Advance the poll cycle to its next request based on the reply we got.
|
||||
switch (this->poll_step_) {
|
||||
case PollStep::SET_UNIT:
|
||||
this->poll_step_ = PollStep::STATUS;
|
||||
this->write_request_(this->codec_->get_read_device_status_request());
|
||||
break;
|
||||
case PollStep::STATUS:
|
||||
this->poll_step_ = PollStep::TARGET;
|
||||
this->write_request_(this->codec_->get_read_target_temp_request());
|
||||
break;
|
||||
case PollStep::TARGET:
|
||||
this->poll_step_ = PollStep::CURRENT;
|
||||
this->write_request_(this->codec_->get_read_current_temp_request());
|
||||
break;
|
||||
case PollStep::CURRENT:
|
||||
this->poll_step_ = PollStep::IDLE; // full cycle complete
|
||||
break;
|
||||
default:
|
||||
// A reply to an ad-hoc control() write, outside a managed cycle.
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -136,27 +132,26 @@ void Anova::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_
|
||||
}
|
||||
}
|
||||
|
||||
void Anova::set_unit_of_measurement(const char *unit) { this->fahrenheit_ = !strncmp(unit, "f", 1); }
|
||||
void Anova::set_unit_of_measurement(const char *unit) { this->want_fahrenheit_ = !strncmp(unit, "f", 1); }
|
||||
|
||||
void Anova::update() {
|
||||
if (this->node_state != espbt::ClientState::ESTABLISHED)
|
||||
return;
|
||||
|
||||
if (this->current_request_ < 2) {
|
||||
AnovaPacket *pkt;
|
||||
if (this->current_request_ == 0) {
|
||||
pkt = this->codec_->get_set_unit_request(this->fahrenheit_ ? 'f' : 'c');
|
||||
} else {
|
||||
pkt = this->codec_->get_read_device_status_request();
|
||||
}
|
||||
auto status =
|
||||
esp_ble_gattc_write_char(this->parent_->get_gattc_if(), this->parent_->get_conn_id(), this->char_handle_,
|
||||
pkt->length, pkt->data, ESP_GATT_WRITE_TYPE_NO_RSP, ESP_GATT_AUTH_REQ_NONE);
|
||||
if (status) {
|
||||
ESP_LOGW(TAG, "[%s] esp_ble_gattc_write_char failed, status=%d", this->parent_->address_str(), status);
|
||||
}
|
||||
this->current_request_++;
|
||||
if (this->poll_step_ != PollStep::IDLE) {
|
||||
// The previous cycle never finished within a full polling interval -- a
|
||||
// reply was missed or a write failed. Restart the cycle rather than stall;
|
||||
// the polling interval itself acts as the timeout. A late reply from the
|
||||
// abandoned cycle is harmless: state decoding happens on every notify
|
||||
// regardless of step, and each notify sends at most one follow-up request.
|
||||
ESP_LOGW(TAG, "[%s] Poll cycle incomplete (step %u); restarting cycle", this->parent_->address_str(),
|
||||
static_cast<uint8_t>(this->poll_step_));
|
||||
}
|
||||
// Re-assert the configured unit at the start of every poll cycle, then fall
|
||||
// through the status/temperature reads via the notification handler. Always
|
||||
// command the configured unit (want_fahrenheit_) -- never the last value the
|
||||
// device reported, or a drift to 'c' would lock itself in.
|
||||
this->poll_step_ = PollStep::SET_UNIT;
|
||||
this->write_request_(this->codec_->get_set_unit_request(this->want_fahrenheit_ ? 'f' : 'c'));
|
||||
}
|
||||
|
||||
} // namespace esphome::anova
|
||||
|
||||
@@ -37,11 +37,20 @@ class Anova final : public climate::Climate, public esphome::ble_client::BLEClie
|
||||
void set_unit_of_measurement(const char *unit);
|
||||
|
||||
protected:
|
||||
// A poll cycle re-asserts the configured unit, then reads device state.
|
||||
// Re-asserting every cycle prevents the cooker from silently reverting to
|
||||
// its default (Celsius); previously the unit was only set once on
|
||||
// connection, so a drift persisted (and corrupted the F/C interpretation of
|
||||
// subsequent readings) until the BLE link was re-established.
|
||||
enum class PollStep : uint8_t { SET_UNIT, STATUS, TARGET, CURRENT, IDLE };
|
||||
|
||||
void write_request_(AnovaPacket *pkt);
|
||||
|
||||
std::unique_ptr<AnovaCodec> codec_;
|
||||
void control(const climate::ClimateCall &call) override;
|
||||
uint16_t char_handle_;
|
||||
uint8_t current_request_;
|
||||
bool fahrenheit_;
|
||||
bool want_fahrenheit_{true}; // configured target unit; never overwritten by device replies
|
||||
PollStep poll_step_{PollStep::IDLE};
|
||||
};
|
||||
|
||||
} // namespace esphome::anova
|
||||
|
||||
@@ -9,6 +9,10 @@ namespace esphome::atm90e32 {
|
||||
|
||||
static const char *const TAG = "atm90e32";
|
||||
|
||||
static const LogString *offset_calibration_name(bool power_offsets) {
|
||||
return power_offsets ? LOG_STR("Power offset") : LOG_STR("Offset");
|
||||
}
|
||||
|
||||
static uint32_t pref_hash(const char *prefix, const char *name_space) {
|
||||
auto hash = fnv1_hash(prefix);
|
||||
return fnv1_hash_extend(hash, name_space);
|
||||
@@ -203,13 +207,12 @@ void ATM90E32Component::setup() {
|
||||
|
||||
// Initialize flash storage for power offset calibrations
|
||||
uint32_t po_hash = pref_hash("_power_offset_calibration_", cs);
|
||||
this->power_offset_pref_ = global_preferences->make_preference<PowerOffsetCalibration[3]>(po_hash, true);
|
||||
this->power_offset_pref_ = global_preferences->make_preference<OffsetCalibration[3]>(po_hash, true);
|
||||
bool migrated_power_offset = false;
|
||||
if (has_distinct_legacy_namespace) {
|
||||
uint32_t legacy_po_hash = pref_hash("_power_offset_calibration_", legacy_cs);
|
||||
auto legacy_power_offset_pref =
|
||||
global_preferences->make_preference<PowerOffsetCalibration[3]>(legacy_po_hash, true);
|
||||
PowerOffsetCalibration power_offset_data[3]{};
|
||||
auto legacy_power_offset_pref = global_preferences->make_preference<OffsetCalibration[3]>(legacy_po_hash, true);
|
||||
OffsetCalibration power_offset_data[3]{};
|
||||
int migration_status =
|
||||
migrate_legacy_pref_if_needed(this->power_offset_pref_, legacy_power_offset_pref, &power_offset_data);
|
||||
migrated_power_offset = migration_status > 0;
|
||||
@@ -224,20 +227,20 @@ void ATM90E32Component::setup() {
|
||||
global_preferences->sync();
|
||||
}
|
||||
|
||||
this->restore_offset_calibrations_();
|
||||
this->restore_power_offset_calibrations_();
|
||||
this->restore_offset_calibrations_(OffsetCalibrationType::OFFSET_CALIBRATION_TYPE_VOLTAGE_CURRENT);
|
||||
this->restore_offset_calibrations_(OffsetCalibrationType::OFFSET_CALIBRATION_TYPE_POWER);
|
||||
} else {
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] Power & Voltage/Current offset calibration is disabled. Using config file values.",
|
||||
cs);
|
||||
for (uint8_t phase = 0; phase < 3; ++phase) {
|
||||
this->write16_(this->voltage_offset_registers[phase],
|
||||
static_cast<uint16_t>(this->offset_phase_[phase].voltage_offset_));
|
||||
static_cast<uint16_t>(this->offset_phase_[phase].first_offset));
|
||||
this->write16_(this->current_offset_registers[phase],
|
||||
static_cast<uint16_t>(this->offset_phase_[phase].current_offset_));
|
||||
static_cast<uint16_t>(this->offset_phase_[phase].second_offset));
|
||||
this->write16_(this->power_offset_registers[phase],
|
||||
static_cast<uint16_t>(this->power_offset_phase_[phase].active_power_offset));
|
||||
static_cast<uint16_t>(this->power_offset_phase_[phase].first_offset));
|
||||
this->write16_(this->reactive_power_offset_registers[phase],
|
||||
static_cast<uint16_t>(this->power_offset_phase_[phase].reactive_power_offset));
|
||||
static_cast<uint16_t>(this->power_offset_phase_[phase].second_offset));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -317,8 +320,8 @@ void ATM90E32Component::log_calibration_status_() {
|
||||
cs);
|
||||
for (uint8_t phase = 0; phase < 3; ++phase) {
|
||||
ESP_LOGW(TAG, "[CALIBRATION][%s] | %c | %6d | %6d | %6d | %6d |", cs, 'A' + phase,
|
||||
this->config_offset_phase_[phase].voltage_offset_, this->offset_phase_[phase].voltage_offset_,
|
||||
this->config_offset_phase_[phase].current_offset_, this->offset_phase_[phase].current_offset_);
|
||||
this->config_offset_phase_[phase].first_offset, this->offset_phase_[phase].first_offset,
|
||||
this->config_offset_phase_[phase].second_offset, this->offset_phase_[phase].second_offset);
|
||||
}
|
||||
ESP_LOGW(TAG,
|
||||
"[CALIBRATION][%s] ===============================================================================", cs);
|
||||
@@ -335,10 +338,8 @@ void ATM90E32Component::log_calibration_status_() {
|
||||
cs);
|
||||
for (uint8_t phase = 0; phase < 3; ++phase) {
|
||||
ESP_LOGW(TAG, "[CALIBRATION][%s] | %c | %6d | %6d | %6d | %6d |", cs, 'A' + phase,
|
||||
this->config_power_offset_phase_[phase].active_power_offset,
|
||||
this->power_offset_phase_[phase].active_power_offset,
|
||||
this->config_power_offset_phase_[phase].reactive_power_offset,
|
||||
this->power_offset_phase_[phase].reactive_power_offset);
|
||||
this->config_power_offset_phase_[phase].first_offset, this->power_offset_phase_[phase].first_offset,
|
||||
this->config_power_offset_phase_[phase].second_offset, this->power_offset_phase_[phase].second_offset);
|
||||
}
|
||||
ESP_LOGW(TAG,
|
||||
"[CALIBRATION][%s] ===============================================================================", cs);
|
||||
@@ -372,7 +373,7 @@ void ATM90E32Component::log_calibration_status_() {
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] --------------------------------------------------------------", cs);
|
||||
for (uint8_t phase = 0; phase < 3; phase++) {
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase,
|
||||
this->offset_phase_[phase].voltage_offset_, this->offset_phase_[phase].current_offset_);
|
||||
this->offset_phase_[phase].first_offset, this->offset_phase_[phase].second_offset);
|
||||
}
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] ==============================================================\\n", cs);
|
||||
}
|
||||
@@ -385,8 +386,7 @@ void ATM90E32Component::log_calibration_status_() {
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
|
||||
for (uint8_t phase = 0; phase < 3; phase++) {
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase,
|
||||
this->power_offset_phase_[phase].active_power_offset,
|
||||
this->power_offset_phase_[phase].reactive_power_offset);
|
||||
this->power_offset_phase_[phase].first_offset, this->power_offset_phase_[phase].second_offset);
|
||||
}
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] =====================================================================\n", cs);
|
||||
}
|
||||
@@ -756,36 +756,68 @@ void ATM90E32Component::save_gain_calibration_to_memory_() {
|
||||
}
|
||||
}
|
||||
|
||||
void ATM90E32Component::save_offset_calibration_to_memory_() {
|
||||
void ATM90E32Component::finish_offset_calibration_(const OffsetCalibration (&previous)[3], bool previous_restored,
|
||||
bool previous_using_saved, OffsetCalibrationType type) {
|
||||
const bool power_offsets = type == OffsetCalibrationType::OFFSET_CALIBRATION_TYPE_POWER;
|
||||
const char *cs = this->get_calibration_id_();
|
||||
bool success = this->offset_pref_.save(&this->offset_phase_);
|
||||
global_preferences->sync();
|
||||
if (success) {
|
||||
this->using_saved_calibrations_ = true;
|
||||
this->restored_offset_calibration_ = true;
|
||||
for (bool &phase : this->offset_calibration_mismatch_)
|
||||
phase = false;
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] Offset calibration saved to memory.", cs);
|
||||
} else {
|
||||
this->using_saved_calibrations_ = false;
|
||||
ESP_LOGE(TAG, "[CALIBRATION][%s] Failed to save offset calibration to memory!", cs);
|
||||
}
|
||||
}
|
||||
const LogString *name = offset_calibration_name(power_offsets);
|
||||
OffsetCalibration(*offsets)[3] = power_offsets ? &this->power_offset_phase_ : &this->offset_phase_;
|
||||
ESPPreferenceObject *preference = power_offsets ? &this->power_offset_pref_ : &this->offset_pref_;
|
||||
bool *has_stored =
|
||||
power_offsets ? &this->has_stored_power_offset_calibration_ : &this->has_stored_offset_calibration_;
|
||||
bool *restored = power_offsets ? &this->restored_power_offset_calibration_ : &this->restored_offset_calibration_;
|
||||
bool *mismatches = power_offsets ? this->power_offset_calibration_mismatch_ : this->offset_calibration_mismatch_;
|
||||
|
||||
void ATM90E32Component::save_power_offset_calibration_to_memory_() {
|
||||
const char *cs = this->get_calibration_id_();
|
||||
bool success = this->power_offset_pref_.save(&this->power_offset_phase_);
|
||||
global_preferences->sync();
|
||||
if (success) {
|
||||
this->using_saved_calibrations_ = true;
|
||||
this->restored_power_offset_calibration_ = true;
|
||||
for (bool &phase : this->power_offset_calibration_mismatch_)
|
||||
phase = false;
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] Power offset calibration saved to memory.", cs);
|
||||
} else {
|
||||
this->using_saved_calibrations_ = false;
|
||||
ESP_LOGE(TAG, "[CALIBRATION][%s] Failed to save power offset calibration to memory!", cs);
|
||||
const bool writes_verified = this->verify_offset_writes_(type);
|
||||
bool saved = false;
|
||||
bool synced = false;
|
||||
if (writes_verified) {
|
||||
saved = preference->save(offsets);
|
||||
synced = global_preferences->sync();
|
||||
}
|
||||
|
||||
if (writes_verified && saved && synced) {
|
||||
this->using_saved_calibrations_ = true;
|
||||
*has_stored = true;
|
||||
*restored = true;
|
||||
for (uint8_t phase = 0; phase < 3; phase++)
|
||||
mismatches[phase] = false;
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] %s calibration saved to memory. %s calibration completed and verified.", cs,
|
||||
LOG_STR_ARG(name), LOG_STR_ARG(name));
|
||||
return;
|
||||
}
|
||||
|
||||
if (writes_verified) {
|
||||
ESP_LOGE(TAG, "[CALIBRATION][%s] Failed to save %s calibration to memory!", cs, LOG_STR_ARG(name));
|
||||
}
|
||||
|
||||
for (uint8_t phase = 0; phase < 3; phase++) {
|
||||
this->write_offsets_to_registers_(phase, previous[phase].first_offset, previous[phase].second_offset, type);
|
||||
}
|
||||
const bool rollback_verified = this->verify_offset_writes_(type);
|
||||
|
||||
bool rollback_persisted = false;
|
||||
if (writes_verified) {
|
||||
OffsetCalibration rollback[3]{};
|
||||
prepare_offset_rollback(previous, previous_restored, rollback);
|
||||
const bool rollback_saved = preference->save(&rollback);
|
||||
const bool rollback_synced = global_preferences->sync();
|
||||
rollback_persisted = rollback_saved && rollback_synced;
|
||||
if (!rollback_saved || !rollback_synced) {
|
||||
ESP_LOGE(TAG, "[CALIBRATION][%s] Failed to persist restored %s calibration values!", cs, LOG_STR_ARG(name));
|
||||
}
|
||||
}
|
||||
|
||||
*restored = previous_restored;
|
||||
if (rollback_persisted)
|
||||
*has_stored = previous_restored;
|
||||
this->using_saved_calibrations_ = previous_using_saved;
|
||||
if (!rollback_verified) {
|
||||
ESP_LOGE(TAG, "[CALIBRATION][%s] %s calibration failed; rollback readback verification failed.", cs,
|
||||
LOG_STR_ARG(name));
|
||||
return;
|
||||
}
|
||||
ESP_LOGE(TAG, "[CALIBRATION][%s] %s calibration failed; previous values restored.", cs, LOG_STR_ARG(name));
|
||||
}
|
||||
|
||||
void ATM90E32Component::run_offset_calibrations() {
|
||||
@@ -803,11 +835,16 @@ void ATM90E32Component::run_offset_calibrations() {
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_voltage | offset_current |", cs);
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] ------------------------------------------------------------------", cs);
|
||||
|
||||
OffsetCalibration previous_offsets[3] = {this->offset_phase_[0], this->offset_phase_[1], this->offset_phase_[2]};
|
||||
const bool previous_restored = this->restored_offset_calibration_;
|
||||
const bool previous_using_saved = this->using_saved_calibrations_;
|
||||
|
||||
for (uint8_t phase = 0; phase < 3; phase++) {
|
||||
int16_t voltage_offset = calibrate_offset(phase, true);
|
||||
int16_t current_offset = calibrate_offset(phase, false);
|
||||
|
||||
this->write_offsets_to_registers_(phase, voltage_offset, current_offset);
|
||||
this->write_offsets_to_registers_(phase, voltage_offset, current_offset,
|
||||
OffsetCalibrationType::OFFSET_CALIBRATION_TYPE_VOLTAGE_CURRENT);
|
||||
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase, voltage_offset,
|
||||
current_offset);
|
||||
@@ -815,7 +852,8 @@ void ATM90E32Component::run_offset_calibrations() {
|
||||
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] ==================================================================\n", cs);
|
||||
|
||||
this->save_offset_calibration_to_memory_();
|
||||
this->finish_offset_calibration_(previous_offsets, previous_restored, previous_using_saved,
|
||||
OffsetCalibrationType::OFFSET_CALIBRATION_TYPE_VOLTAGE_CURRENT);
|
||||
}
|
||||
|
||||
void ATM90E32Component::run_power_offset_calibrations() {
|
||||
@@ -834,18 +872,25 @@ void ATM90E32Component::run_power_offset_calibrations() {
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_active_power | offset_reactive_power |", cs);
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
|
||||
|
||||
OffsetCalibration previous_offsets[3] = {this->power_offset_phase_[0], this->power_offset_phase_[1],
|
||||
this->power_offset_phase_[2]};
|
||||
const bool previous_restored = this->restored_power_offset_calibration_;
|
||||
const bool previous_using_saved = this->using_saved_calibrations_;
|
||||
|
||||
for (uint8_t phase = 0; phase < 3; ++phase) {
|
||||
int16_t active_offset = calibrate_power_offset(phase, false);
|
||||
int16_t reactive_offset = calibrate_power_offset(phase, true);
|
||||
|
||||
this->write_power_offsets_to_registers_(phase, active_offset, reactive_offset);
|
||||
this->write_offsets_to_registers_(phase, active_offset, reactive_offset,
|
||||
OffsetCalibrationType::OFFSET_CALIBRATION_TYPE_POWER);
|
||||
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase, active_offset,
|
||||
reactive_offset);
|
||||
}
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] =====================================================================\n", cs);
|
||||
|
||||
this->save_power_offset_calibration_to_memory_();
|
||||
this->finish_offset_calibration_(previous_offsets, previous_restored, previous_using_saved,
|
||||
OffsetCalibrationType::OFFSET_CALIBRATION_TYPE_POWER);
|
||||
}
|
||||
|
||||
void ATM90E32Component::write_gains_to_registers_() {
|
||||
@@ -859,35 +904,26 @@ void ATM90E32Component::write_gains_to_registers_() {
|
||||
this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x0000);
|
||||
}
|
||||
|
||||
void ATM90E32Component::write_offsets_to_registers_(uint8_t phase, int16_t voltage_offset, int16_t current_offset) {
|
||||
// Save to runtime
|
||||
this->offset_phase_[phase].voltage_offset_ = voltage_offset;
|
||||
this->phase_[phase].voltage_offset_ = voltage_offset;
|
||||
void ATM90E32Component::write_offsets_to_registers_(uint8_t phase, int16_t first_offset, int16_t second_offset,
|
||||
OffsetCalibrationType type) {
|
||||
const bool power_offsets = type == OffsetCalibrationType::OFFSET_CALIBRATION_TYPE_POWER;
|
||||
OffsetCalibration &offsets = power_offsets ? this->power_offset_phase_[phase] : this->offset_phase_[phase];
|
||||
offsets.first_offset = first_offset;
|
||||
offsets.second_offset = second_offset;
|
||||
if (power_offsets) {
|
||||
this->phase_[phase].active_power_offset_ = first_offset;
|
||||
this->phase_[phase].reactive_power_offset_ = second_offset;
|
||||
} else {
|
||||
this->phase_[phase].voltage_offset_ = first_offset;
|
||||
this->phase_[phase].current_offset_ = second_offset;
|
||||
}
|
||||
|
||||
// Save to flash-storable struct
|
||||
this->offset_phase_[phase].current_offset_ = current_offset;
|
||||
this->phase_[phase].current_offset_ = current_offset;
|
||||
|
||||
// Write to registers
|
||||
const uint16_t *first_registers = power_offsets ? this->power_offset_registers : this->voltage_offset_registers;
|
||||
const uint16_t *second_registers =
|
||||
power_offsets ? this->reactive_power_offset_registers : this->current_offset_registers;
|
||||
this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x55AA);
|
||||
this->write16_(voltage_offset_registers[phase], static_cast<uint16_t>(voltage_offset));
|
||||
this->write16_(current_offset_registers[phase], static_cast<uint16_t>(current_offset));
|
||||
this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x0000);
|
||||
}
|
||||
|
||||
void ATM90E32Component::write_power_offsets_to_registers_(uint8_t phase, int16_t p_offset, int16_t q_offset) {
|
||||
// Save to runtime
|
||||
this->phase_[phase].active_power_offset_ = p_offset;
|
||||
this->phase_[phase].reactive_power_offset_ = q_offset;
|
||||
|
||||
// Save to flash-storable struct
|
||||
this->power_offset_phase_[phase].active_power_offset = p_offset;
|
||||
this->power_offset_phase_[phase].reactive_power_offset = q_offset;
|
||||
|
||||
// Write to registers
|
||||
this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x55AA);
|
||||
this->write16_(this->power_offset_registers[phase], static_cast<uint16_t>(p_offset));
|
||||
this->write16_(this->reactive_power_offset_registers[phase], static_cast<uint16_t>(q_offset));
|
||||
this->write16_(first_registers[phase], static_cast<uint16_t>(first_offset));
|
||||
this->write16_(second_registers[phase], static_cast<uint16_t>(second_offset));
|
||||
this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x0000);
|
||||
}
|
||||
|
||||
@@ -947,89 +983,78 @@ void ATM90E32Component::restore_gain_calibrations_() {
|
||||
ESP_LOGW(TAG, "[CALIBRATION][%s] No stored gain calibrations found. Using config file values.", cs);
|
||||
}
|
||||
|
||||
void ATM90E32Component::restore_offset_calibrations_() {
|
||||
void ATM90E32Component::restore_offset_calibrations_(OffsetCalibrationType type) {
|
||||
const bool power_offsets = type == OffsetCalibrationType::OFFSET_CALIBRATION_TYPE_POWER;
|
||||
const char *cs = this->get_calibration_id_();
|
||||
const LogString *name = power_offsets ? LOG_STR("power offset") : LOG_STR("offset");
|
||||
OffsetCalibration(*offsets)[3] = power_offsets ? &this->power_offset_phase_ : &this->offset_phase_;
|
||||
OffsetCalibration(*config_offsets)[3] =
|
||||
power_offsets ? &this->config_power_offset_phase_ : &this->config_offset_phase_;
|
||||
ESPPreferenceObject *preference = power_offsets ? &this->power_offset_pref_ : &this->offset_pref_;
|
||||
bool *has_stored =
|
||||
power_offsets ? &this->has_stored_power_offset_calibration_ : &this->has_stored_offset_calibration_;
|
||||
bool *restored = power_offsets ? &this->restored_power_offset_calibration_ : &this->restored_offset_calibration_;
|
||||
bool *mismatches = power_offsets ? this->power_offset_calibration_mismatch_ : this->offset_calibration_mismatch_;
|
||||
const bool *has_first = power_offsets ? this->has_config_active_power_offset_ : this->has_config_voltage_offset_;
|
||||
const bool *has_second = power_offsets ? this->has_config_reactive_power_offset_ : this->has_config_current_offset_;
|
||||
|
||||
for (uint8_t i = 0; i < 3; ++i)
|
||||
this->config_offset_phase_[i] = this->offset_phase_[i];
|
||||
|
||||
bool have_data = this->offset_pref_.load(&this->offset_phase_);
|
||||
(*config_offsets)[i] = (*offsets)[i];
|
||||
|
||||
const bool have_data = preference->load(offsets);
|
||||
bool all_zero = true;
|
||||
if (have_data) {
|
||||
for (auto &phase : this->offset_phase_) {
|
||||
if (phase.voltage_offset_ != 0 || phase.current_offset_ != 0) {
|
||||
for (const auto &phase : *offsets) {
|
||||
if (phase.first_offset != 0 || phase.second_offset != 0) {
|
||||
all_zero = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (have_data && !all_zero) {
|
||||
this->restored_offset_calibration_ = true;
|
||||
for (uint8_t phase = 0; phase < 3; phase++) {
|
||||
auto &offset = this->offset_phase_[phase];
|
||||
bool mismatch = false;
|
||||
if (this->has_config_voltage_offset_[phase] &&
|
||||
offset.voltage_offset_ != this->config_offset_phase_[phase].voltage_offset_)
|
||||
mismatch = true;
|
||||
if (this->has_config_current_offset_[phase] &&
|
||||
offset.current_offset_ != this->config_offset_phase_[phase].current_offset_)
|
||||
mismatch = true;
|
||||
if (mismatch)
|
||||
this->offset_calibration_mismatch_[phase] = true;
|
||||
*has_stored = have_data && !all_zero;
|
||||
*restored = false;
|
||||
for (uint8_t phase = 0; phase < 3; phase++) {
|
||||
mismatches[phase] = false;
|
||||
if (*has_stored) {
|
||||
mismatches[phase] =
|
||||
(has_first[phase] && (*offsets)[phase].first_offset != (*config_offsets)[phase].first_offset) ||
|
||||
(has_second[phase] && (*offsets)[phase].second_offset != (*config_offsets)[phase].second_offset);
|
||||
}
|
||||
} else {
|
||||
}
|
||||
|
||||
if (!*has_stored) {
|
||||
for (uint8_t phase = 0; phase < 3; phase++)
|
||||
this->offset_phase_[phase] = this->config_offset_phase_[phase];
|
||||
ESP_LOGW(TAG, "[CALIBRATION][%s] No stored offset calibrations found. Using default values.", cs);
|
||||
(*offsets)[phase] = (*config_offsets)[phase];
|
||||
ESP_LOGW(TAG, "[CALIBRATION][%s] No stored %s calibrations found. Using default values.", cs, LOG_STR_ARG(name));
|
||||
}
|
||||
|
||||
for (uint8_t phase = 0; phase < 3; phase++) {
|
||||
write_offsets_to_registers_(phase, this->offset_phase_[phase].voltage_offset_,
|
||||
this->offset_phase_[phase].current_offset_);
|
||||
this->write_offsets_to_registers_(phase, (*offsets)[phase].first_offset, (*offsets)[phase].second_offset, type);
|
||||
}
|
||||
}
|
||||
|
||||
void ATM90E32Component::restore_power_offset_calibrations_() {
|
||||
const char *cs = this->get_calibration_id_();
|
||||
for (uint8_t i = 0; i < 3; ++i)
|
||||
this->config_power_offset_phase_[i] = this->power_offset_phase_[i];
|
||||
|
||||
bool have_data = this->power_offset_pref_.load(&this->power_offset_phase_);
|
||||
|
||||
bool all_zero = true;
|
||||
if (have_data) {
|
||||
for (auto &phase : this->power_offset_phase_) {
|
||||
if (phase.active_power_offset != 0 || phase.reactive_power_offset != 0) {
|
||||
all_zero = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const bool initial_values_verified = this->verify_offset_writes_(type);
|
||||
if (initial_values_verified) {
|
||||
const auto state = resolve_offset_restore_state(*has_stored, true, false);
|
||||
*restored = state.restored;
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] %s calibration values verified.", cs, LOG_STR_ARG(name));
|
||||
return;
|
||||
}
|
||||
|
||||
if (have_data && !all_zero) {
|
||||
this->restored_power_offset_calibration_ = true;
|
||||
for (uint8_t phase = 0; phase < 3; ++phase) {
|
||||
auto &offset = this->power_offset_phase_[phase];
|
||||
bool mismatch = false;
|
||||
if (this->has_config_active_power_offset_[phase] &&
|
||||
offset.active_power_offset != this->config_power_offset_phase_[phase].active_power_offset)
|
||||
mismatch = true;
|
||||
if (this->has_config_reactive_power_offset_[phase] &&
|
||||
offset.reactive_power_offset != this->config_power_offset_phase_[phase].reactive_power_offset)
|
||||
mismatch = true;
|
||||
if (mismatch)
|
||||
this->power_offset_calibration_mismatch_[phase] = true;
|
||||
}
|
||||
this->using_saved_calibrations_ = false;
|
||||
for (uint8_t phase = 0; phase < 3; phase++)
|
||||
mismatches[phase] = false;
|
||||
for (uint8_t phase = 0; phase < 3; phase++) {
|
||||
(*offsets)[phase] = (*config_offsets)[phase];
|
||||
this->write_offsets_to_registers_(phase, (*offsets)[phase].first_offset, (*offsets)[phase].second_offset, type);
|
||||
}
|
||||
const auto state = resolve_offset_restore_state(*has_stored, false, this->verify_offset_writes_(type));
|
||||
*restored = state.restored;
|
||||
if (state.values_verified) {
|
||||
ESP_LOGE(TAG, "[CALIBRATION][%s] %s calibration restore failed verification; config values verified.", cs,
|
||||
LOG_STR_ARG(name));
|
||||
} else {
|
||||
for (uint8_t phase = 0; phase < 3; ++phase)
|
||||
this->power_offset_phase_[phase] = this->config_power_offset_phase_[phase];
|
||||
ESP_LOGW(TAG, "[CALIBRATION][%s] No stored power offsets found. Using default values.", cs);
|
||||
}
|
||||
|
||||
for (uint8_t phase = 0; phase < 3; ++phase) {
|
||||
write_power_offsets_to_registers_(phase, this->power_offset_phase_[phase].active_power_offset,
|
||||
this->power_offset_phase_[phase].reactive_power_offset);
|
||||
ESP_LOGE(TAG, "[CALIBRATION][%s] %s calibration restore and config fallback both failed verification.", cs,
|
||||
LOG_STR_ARG(name));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1084,14 +1109,14 @@ void ATM90E32Component::clear_gain_calibrations() {
|
||||
|
||||
void ATM90E32Component::clear_offset_calibrations() {
|
||||
const char *cs = this->get_calibration_id_();
|
||||
if (!this->restored_offset_calibration_) {
|
||||
if (!this->has_stored_offset_calibration_) {
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] No stored offset calibrations to clear. Current values:", cs);
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] --------------------------------------------------------------", cs);
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_voltage | offset_current |", cs);
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] --------------------------------------------------------------", cs);
|
||||
for (uint8_t phase = 0; phase < 3; phase++) {
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase,
|
||||
this->offset_phase_[phase].voltage_offset_, this->offset_phase_[phase].current_offset_);
|
||||
this->offset_phase_[phase].first_offset, this->offset_phase_[phase].second_offset);
|
||||
}
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] ==============================================================\n", cs);
|
||||
return;
|
||||
@@ -1104,10 +1129,11 @@ void ATM90E32Component::clear_offset_calibrations() {
|
||||
|
||||
for (uint8_t phase = 0; phase < 3; phase++) {
|
||||
int16_t voltage_offset =
|
||||
this->has_config_voltage_offset_[phase] ? this->config_offset_phase_[phase].voltage_offset_ : 0;
|
||||
this->has_config_voltage_offset_[phase] ? this->config_offset_phase_[phase].first_offset : 0;
|
||||
int16_t current_offset =
|
||||
this->has_config_current_offset_[phase] ? this->config_offset_phase_[phase].current_offset_ : 0;
|
||||
this->write_offsets_to_registers_(phase, voltage_offset, current_offset);
|
||||
this->has_config_current_offset_[phase] ? this->config_offset_phase_[phase].second_offset : 0;
|
||||
this->write_offsets_to_registers_(phase, voltage_offset, current_offset,
|
||||
OffsetCalibrationType::OFFSET_CALIBRATION_TYPE_VOLTAGE_CURRENT);
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase, voltage_offset,
|
||||
current_offset);
|
||||
}
|
||||
@@ -1117,6 +1143,7 @@ void ATM90E32Component::clear_offset_calibrations() {
|
||||
this->offset_pref_.save(&zero_offsets); // Clear stored values in flash
|
||||
global_preferences->sync();
|
||||
|
||||
this->has_stored_offset_calibration_ = false;
|
||||
this->restored_offset_calibration_ = false;
|
||||
for (bool &phase : this->offset_calibration_mismatch_)
|
||||
phase = false;
|
||||
@@ -1126,15 +1153,14 @@ void ATM90E32Component::clear_offset_calibrations() {
|
||||
|
||||
void ATM90E32Component::clear_power_offset_calibrations() {
|
||||
const char *cs = this->get_calibration_id_();
|
||||
if (!this->restored_power_offset_calibration_) {
|
||||
if (!this->has_stored_power_offset_calibration_) {
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] No stored power offsets to clear. Current values:", cs);
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_active_power | offset_reactive_power |", cs);
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
|
||||
for (uint8_t phase = 0; phase < 3; phase++) {
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase,
|
||||
this->power_offset_phase_[phase].active_power_offset,
|
||||
this->power_offset_phase_[phase].reactive_power_offset);
|
||||
this->power_offset_phase_[phase].first_offset, this->power_offset_phase_[phase].second_offset);
|
||||
}
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] =====================================================================\n", cs);
|
||||
return;
|
||||
@@ -1147,20 +1173,21 @@ void ATM90E32Component::clear_power_offset_calibrations() {
|
||||
|
||||
for (uint8_t phase = 0; phase < 3; phase++) {
|
||||
int16_t active_offset =
|
||||
this->has_config_active_power_offset_[phase] ? this->config_power_offset_phase_[phase].active_power_offset : 0;
|
||||
int16_t reactive_offset = this->has_config_reactive_power_offset_[phase]
|
||||
? this->config_power_offset_phase_[phase].reactive_power_offset
|
||||
: 0;
|
||||
this->write_power_offsets_to_registers_(phase, active_offset, reactive_offset);
|
||||
this->has_config_active_power_offset_[phase] ? this->config_power_offset_phase_[phase].first_offset : 0;
|
||||
int16_t reactive_offset =
|
||||
this->has_config_reactive_power_offset_[phase] ? this->config_power_offset_phase_[phase].second_offset : 0;
|
||||
this->write_offsets_to_registers_(phase, active_offset, reactive_offset,
|
||||
OffsetCalibrationType::OFFSET_CALIBRATION_TYPE_POWER);
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase, active_offset,
|
||||
reactive_offset);
|
||||
}
|
||||
ESP_LOGI(TAG, "[CALIBRATION][%s] =====================================================================\n", cs);
|
||||
|
||||
PowerOffsetCalibration zero_power_offsets[3]{{0, 0}, {0, 0}, {0, 0}};
|
||||
OffsetCalibration zero_power_offsets[3]{{0, 0}, {0, 0}, {0, 0}};
|
||||
this->power_offset_pref_.save(&zero_power_offsets);
|
||||
global_preferences->sync();
|
||||
|
||||
this->has_stored_power_offset_calibration_ = false;
|
||||
this->restored_power_offset_calibration_ = false;
|
||||
for (bool &phase : this->power_offset_calibration_mismatch_)
|
||||
phase = false;
|
||||
@@ -1215,6 +1242,31 @@ bool ATM90E32Component::verify_gain_writes_() {
|
||||
return success; // Return true if all writes were successful, false otherwise
|
||||
}
|
||||
|
||||
bool ATM90E32Component::verify_offset_writes_(OffsetCalibrationType type) {
|
||||
const bool power_offsets = type == OffsetCalibrationType::OFFSET_CALIBRATION_TYPE_POWER;
|
||||
const char *cs = this->get_calibration_id_();
|
||||
const LogString *name = offset_calibration_name(power_offsets);
|
||||
const LogString *first_name = power_offsets ? LOG_STR("active") : LOG_STR("voltage");
|
||||
const LogString *second_name = power_offsets ? LOG_STR("reactive") : LOG_STR("current");
|
||||
const OffsetCalibration *offsets = power_offsets ? this->power_offset_phase_ : this->offset_phase_;
|
||||
const uint16_t *first_registers = power_offsets ? this->power_offset_registers : this->voltage_offset_registers;
|
||||
const uint16_t *second_registers =
|
||||
power_offsets ? this->reactive_power_offset_registers : this->current_offset_registers;
|
||||
bool success = true;
|
||||
for (uint8_t phase = 0; phase < 3; phase++) {
|
||||
const uint16_t first = this->read16_(first_registers[phase]);
|
||||
const uint16_t second = this->read16_(second_registers[phase]);
|
||||
if (!offset_register_value_matches(first, offsets[phase].first_offset) ||
|
||||
!offset_register_value_matches(second, offsets[phase].second_offset)) {
|
||||
ESP_LOGE(TAG, "[CALIBRATION][%s] %s readback failed for Phase %s: %s %d/%d, %s %d/%d.", cs, LOG_STR_ARG(name),
|
||||
phase_labels[phase], LOG_STR_ARG(first_name), static_cast<int16_t>(first), offsets[phase].first_offset,
|
||||
LOG_STR_ARG(second_name), static_cast<int16_t>(second), offsets[phase].second_offset);
|
||||
success = false;
|
||||
}
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
void ATM90E32Component::check_phase_status() {
|
||||
uint16_t state0 = this->read16_(ATM90E32_REGISTER_EMMSTATE0);
|
||||
|
||||
@@ -13,6 +13,40 @@
|
||||
|
||||
namespace esphome::atm90e32 {
|
||||
|
||||
inline bool offset_register_value_matches(uint16_t actual, int16_t expected) {
|
||||
return actual == static_cast<uint16_t>(expected);
|
||||
}
|
||||
|
||||
struct OffsetCalibration {
|
||||
int16_t first_offset{0};
|
||||
int16_t second_offset{0};
|
||||
};
|
||||
|
||||
static_assert(sizeof(OffsetCalibration[3]) == 12, "Offset calibration preference layout must remain compatible");
|
||||
|
||||
enum class OffsetCalibrationType : uint8_t {
|
||||
OFFSET_CALIBRATION_TYPE_VOLTAGE_CURRENT,
|
||||
OFFSET_CALIBRATION_TYPE_POWER,
|
||||
};
|
||||
|
||||
struct OffsetRestoreState {
|
||||
bool restored;
|
||||
bool values_verified;
|
||||
};
|
||||
|
||||
inline OffsetRestoreState resolve_offset_restore_state(bool has_stored_values, bool initial_values_verified,
|
||||
bool fallback_values_verified) {
|
||||
if (initial_values_verified)
|
||||
return {has_stored_values, true};
|
||||
return {false, fallback_values_verified};
|
||||
}
|
||||
|
||||
inline void prepare_offset_rollback(const OffsetCalibration (&previous)[3], bool had_stored_values,
|
||||
OffsetCalibration (&rollback)[3]) {
|
||||
for (uint8_t phase = 0; phase < 3; phase++)
|
||||
rollback[phase] = had_stored_values ? previous[phase] : OffsetCalibration{};
|
||||
}
|
||||
|
||||
class ATM90E32Component final : public PollingComponent,
|
||||
public spi::SPIDevice<spi::BIT_ORDER_MSB_FIRST, spi::CLOCK_POLARITY_HIGH,
|
||||
spi::CLOCK_PHASE_TRAILING, spi::DATA_RATE_1MHZ> {
|
||||
@@ -71,19 +105,19 @@ class ATM90E32Component final : public PollingComponent,
|
||||
this->has_config_current_gain_[phase] = true;
|
||||
}
|
||||
void set_voltage_offset(uint8_t phase, int16_t offset) {
|
||||
this->offset_phase_[phase].voltage_offset_ = offset;
|
||||
this->offset_phase_[phase].first_offset = offset;
|
||||
this->has_config_voltage_offset_[phase] = true;
|
||||
}
|
||||
void set_current_offset(uint8_t phase, int16_t offset) {
|
||||
this->offset_phase_[phase].current_offset_ = offset;
|
||||
this->offset_phase_[phase].second_offset = offset;
|
||||
this->has_config_current_offset_[phase] = true;
|
||||
}
|
||||
void set_active_power_offset(uint8_t phase, int16_t offset) {
|
||||
this->power_offset_phase_[phase].active_power_offset = offset;
|
||||
this->power_offset_phase_[phase].first_offset = offset;
|
||||
this->has_config_active_power_offset_[phase] = true;
|
||||
}
|
||||
void set_reactive_power_offset(uint8_t phase, int16_t offset) {
|
||||
this->power_offset_phase_[phase].reactive_power_offset = offset;
|
||||
this->power_offset_phase_[phase].second_offset = offset;
|
||||
this->has_config_reactive_power_offset_[phase] = true;
|
||||
}
|
||||
void set_freq_sensor(sensor::Sensor *freq_sensor) { freq_sensor_ = freq_sensor; }
|
||||
@@ -171,16 +205,16 @@ class ATM90E32Component final : public PollingComponent,
|
||||
float get_chip_temperature_();
|
||||
bool get_publish_interval_flag_() { return publish_interval_flag_; };
|
||||
void set_publish_interval_flag_(bool flag) { publish_interval_flag_ = flag; };
|
||||
void restore_offset_calibrations_();
|
||||
void restore_power_offset_calibrations_();
|
||||
void restore_offset_calibrations_(OffsetCalibrationType type);
|
||||
void restore_gain_calibrations_();
|
||||
void save_offset_calibration_to_memory_();
|
||||
void save_gain_calibration_to_memory_();
|
||||
void save_power_offset_calibration_to_memory_();
|
||||
void write_offsets_to_registers_(uint8_t phase, int16_t voltage_offset, int16_t current_offset);
|
||||
void write_power_offsets_to_registers_(uint8_t phase, int16_t p_offset, int16_t q_offset);
|
||||
void finish_offset_calibration_(const OffsetCalibration (&previous)[3], bool previous_restored,
|
||||
bool previous_using_saved, OffsetCalibrationType type);
|
||||
void write_offsets_to_registers_(uint8_t phase, int16_t first_offset, int16_t second_offset,
|
||||
OffsetCalibrationType type);
|
||||
void write_gains_to_registers_();
|
||||
bool verify_gain_writes_();
|
||||
bool verify_offset_writes_(OffsetCalibrationType type);
|
||||
bool validate_spi_read_(uint16_t expected, const char *context = nullptr);
|
||||
void log_calibration_status_();
|
||||
const char *get_calibration_id_();
|
||||
@@ -219,19 +253,10 @@ class ATM90E32Component final : public PollingComponent,
|
||||
uint32_t cumulative_reverse_active_energy_{0};
|
||||
} phase_[3];
|
||||
|
||||
struct OffsetCalibration {
|
||||
int16_t voltage_offset_{0};
|
||||
int16_t current_offset_{0};
|
||||
} offset_phase_[3];
|
||||
|
||||
OffsetCalibration offset_phase_[3];
|
||||
OffsetCalibration config_offset_phase_[3];
|
||||
|
||||
struct PowerOffsetCalibration {
|
||||
int16_t active_power_offset{0};
|
||||
int16_t reactive_power_offset{0};
|
||||
} power_offset_phase_[3];
|
||||
|
||||
PowerOffsetCalibration config_power_offset_phase_[3];
|
||||
OffsetCalibration power_offset_phase_[3];
|
||||
OffsetCalibration config_power_offset_phase_[3];
|
||||
|
||||
struct GainCalibration {
|
||||
uint16_t voltage_gain{1};
|
||||
@@ -265,6 +290,8 @@ class ATM90E32Component final : public PollingComponent,
|
||||
bool enable_offset_calibration_{false};
|
||||
bool enable_gain_calibration_{false};
|
||||
const char *instance_id_{nullptr};
|
||||
bool has_stored_offset_calibration_{false};
|
||||
bool has_stored_power_offset_calibration_{false};
|
||||
bool restored_offset_calibration_{false};
|
||||
bool restored_power_offset_calibration_{false};
|
||||
bool restored_gain_calibration_{false};
|
||||
|
||||
@@ -22,6 +22,23 @@ class Automation {
|
||||
static const char *const TAG;
|
||||
};
|
||||
|
||||
// Base for nodes that never read the parent's services.
|
||||
// The parent releases its services only once every node reports Established, so a node that never
|
||||
// reports it keeps that memory allocated for the life of the connection.
|
||||
class BLEClientServicelessNode : public BLEClientNode {
|
||||
public:
|
||||
// Final so that Established is always reported on SEARCH_CMPL, before the derived node sees the event.
|
||||
void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) final {
|
||||
if (event == ESP_GATTC_SEARCH_CMPL_EVT)
|
||||
this->node_state = espbt::ClientState::ESTABLISHED;
|
||||
this->on_gattc_event(event, gattc_if, param);
|
||||
}
|
||||
|
||||
protected:
|
||||
// Derived nodes handle GATT events here rather than by overriding the handler above.
|
||||
virtual void on_gattc_event(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) {}
|
||||
};
|
||||
|
||||
// implement on_connect automation.
|
||||
class BLEClientConnectTrigger final : public Trigger<>, public BLEClientNode {
|
||||
public:
|
||||
@@ -61,7 +78,7 @@ class BLEClientDisconnectTrigger final : public Trigger<>, public BLEClientNode
|
||||
}
|
||||
};
|
||||
|
||||
class BLEClientPasskeyRequestTrigger final : public Trigger<>, public BLEClientNode {
|
||||
class BLEClientPasskeyRequestTrigger final : public Trigger<>, public BLEClientServicelessNode {
|
||||
public:
|
||||
explicit BLEClientPasskeyRequestTrigger(BLEClient *parent) { parent->register_ble_node(this); }
|
||||
void loop() override {}
|
||||
@@ -71,7 +88,7 @@ class BLEClientPasskeyRequestTrigger final : public Trigger<>, public BLEClientN
|
||||
}
|
||||
};
|
||||
|
||||
class BLEClientPasskeyNotificationTrigger final : public Trigger<uint32_t>, public BLEClientNode {
|
||||
class BLEClientPasskeyNotificationTrigger final : public Trigger<uint32_t>, public BLEClientServicelessNode {
|
||||
public:
|
||||
explicit BLEClientPasskeyNotificationTrigger(BLEClient *parent) { parent->register_ble_node(this); }
|
||||
void loop() override {}
|
||||
@@ -82,7 +99,7 @@ class BLEClientPasskeyNotificationTrigger final : public Trigger<uint32_t>, publ
|
||||
}
|
||||
};
|
||||
|
||||
class BLEClientNumericComparisonRequestTrigger final : public Trigger<uint32_t>, public BLEClientNode {
|
||||
class BLEClientNumericComparisonRequestTrigger final : public Trigger<uint32_t>, public BLEClientServicelessNode {
|
||||
public:
|
||||
explicit BLEClientNumericComparisonRequestTrigger(BLEClient *parent) { parent->register_ble_node(this); }
|
||||
void loop() override {}
|
||||
@@ -315,19 +332,17 @@ template<typename... Ts> class BLEClientRemoveBondAction final : public Action<T
|
||||
BLEClient *parent_{nullptr};
|
||||
};
|
||||
|
||||
template<typename... Ts> class BLEClientConnectAction final : public Action<Ts...>, public BLEClientNode {
|
||||
template<typename... Ts> class BLEClientConnectAction final : public Action<Ts...>, public BLEClientServicelessNode {
|
||||
public:
|
||||
BLEClientConnectAction(BLEClient *ble_client) {
|
||||
ble_client->register_ble_node(this);
|
||||
ble_client_ = ble_client;
|
||||
}
|
||||
void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
|
||||
esp_ble_gattc_cb_param_t *param) override {
|
||||
void on_gattc_event(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) override {
|
||||
if (this->num_running_ == 0)
|
||||
return;
|
||||
switch (event) {
|
||||
case ESP_GATTC_SEARCH_CMPL_EVT:
|
||||
this->node_state = espbt::ClientState::ESTABLISHED;
|
||||
this->parent()->run_later([this]() { this->play_next_tuple_(this->var_); });
|
||||
break;
|
||||
// if the connection is closed, terminate the automation chain.
|
||||
@@ -364,14 +379,13 @@ template<typename... Ts> class BLEClientConnectAction final : public Action<Ts..
|
||||
std::tuple<Ts...> var_{};
|
||||
};
|
||||
|
||||
template<typename... Ts> class BLEClientDisconnectAction final : public Action<Ts...>, public BLEClientNode {
|
||||
template<typename... Ts> class BLEClientDisconnectAction final : public Action<Ts...>, public BLEClientServicelessNode {
|
||||
public:
|
||||
BLEClientDisconnectAction(BLEClient *ble_client) {
|
||||
ble_client->register_ble_node(this);
|
||||
ble_client_ = ble_client;
|
||||
}
|
||||
void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
|
||||
esp_ble_gattc_cb_param_t *param) override {
|
||||
void on_gattc_event(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) override {
|
||||
if (this->num_running_ == 0)
|
||||
return;
|
||||
switch (event) {
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace esphome::dallas_temp {
|
||||
static const char *const TAG = "dallas.temp.sensor";
|
||||
|
||||
static const uint8_t DALLAS_MODEL_DS18S20 = 0x10;
|
||||
static const uint8_t DALLAS_MODEL_DS18B20 = 0x28;
|
||||
static const uint8_t DALLAS_COMMAND_START_CONVERSION = 0x44;
|
||||
static const uint8_t DALLAS_COMMAND_READ_SCRATCH_PAD = 0xBE;
|
||||
static const uint8_t DALLAS_COMMAND_WRITE_SCRATCH_PAD = 0x4E;
|
||||
@@ -154,7 +155,14 @@ float DallasTemperatureSensor::get_temp_c_() {
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// undocumented test for powerup measurement of 85
|
||||
// https://github.com/cpetrich/counterfeit_DS18B20#solution-to-the-85-c-problem
|
||||
if ((this->address_ & 0xff) == DALLAS_MODEL_DS18B20) {
|
||||
if ((temp == 85 * 16) && (this->scratch_pad_[6] == 0xc)) {
|
||||
ESP_LOGD(TAG, "dropping reading caused by sensor reset");
|
||||
return NAN;
|
||||
}
|
||||
}
|
||||
return temp / 16.0f;
|
||||
}
|
||||
|
||||
|
||||
@@ -66,11 +66,15 @@ const char *DebugComponent::get_reset_reason_(std::span<char, RESET_REASON_BUFFE
|
||||
|
||||
unsigned reason = esp_reset_reason();
|
||||
if (reason < sizeof(RESET_REASONS) / sizeof(RESET_REASONS[0])) {
|
||||
if (reason == ESP_RST_SW) {
|
||||
if (reason == ESP_RST_SW || reason == ESP_RST_WDT) {
|
||||
// On some ESP32-S3 configurations (e.g. SPIRAM with fetch-instructions/rodata),
|
||||
// esp_restart() intermittently produces RTCWDT_RTC_RST (ESP_RST_WDT) instead of
|
||||
// ESP_RST_SW. Check the stored reboot source for both reset reasons so a software
|
||||
// reboot that ends up as WDT still reports the correct source.
|
||||
auto pref = global_preferences->make_preference(REBOOT_MAX_LEN,
|
||||
fnv1_hash_extend(fnv1_hash(REBOOT_KEY), App.get_name().c_str()));
|
||||
char reboot_source[REBOOT_MAX_LEN]{};
|
||||
if (pref.load(&reboot_source)) {
|
||||
if (pref.load(&reboot_source) && reboot_source[0] != '\0') {
|
||||
reboot_source[REBOOT_MAX_LEN - 1] = '\0';
|
||||
snprintf(buf, size, "Reboot request from %s", reboot_source);
|
||||
} else {
|
||||
|
||||
@@ -41,7 +41,10 @@ const noise::NoiseContext &ESPHomeOTAComponent::noise_context_() const {
|
||||
#endif
|
||||
static constexpr uint16_t OTA_BLOCK_SIZE = 8192;
|
||||
static constexpr uint32_t OTA_SOCKET_TIMEOUT_HANDSHAKE = 20000; // milliseconds for initial handshake
|
||||
static constexpr uint32_t OTA_SOCKET_TIMEOUT_DATA = 90000; // milliseconds for data transfer
|
||||
// Milliseconds for data transfer. Covers the lwIP retransmit run seen in
|
||||
// practice for a lost chunk ack (1.5 + 3 + 6 + 12 + 24 + 48 s); the CLI waits
|
||||
// longer (espota2.DATA_PHASE_TIMEOUT) so the device is free before it retries
|
||||
static constexpr uint32_t OTA_SOCKET_TIMEOUT_DATA = 105000;
|
||||
|
||||
// Single-instance pointer — multi-port configs are rejected in final_validate.
|
||||
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <esp_log.h>
|
||||
|
||||
#include <driver/uart.h>
|
||||
#include <soc/soc_caps.h>
|
||||
|
||||
#ifdef USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG
|
||||
#include <driver/usb_serial_jtag.h>
|
||||
@@ -76,7 +77,11 @@ void init_uart(uart_port_t uart_num, uint32_t baud_rate, int tx_buffer_size) {
|
||||
uart_config.parity = UART_PARITY_DISABLE;
|
||||
uart_config.stop_bits = UART_STOP_BITS_1;
|
||||
uart_config.flow_ctrl = UART_HW_FLOWCTRL_DISABLE;
|
||||
#if SOC_UART_SUPPORT_XTAL_CLK
|
||||
uart_config.source_clk = UART_SCLK_XTAL;
|
||||
#else
|
||||
uart_config.source_clk = UART_SCLK_DEFAULT;
|
||||
#endif
|
||||
uart_param_config(uart_num, &uart_config);
|
||||
// The logger only writes to UART, never reads, so use the minimum RX buffer.
|
||||
// ESP-IDF requires rx_buffer_size > UART_HW_FIFO_LEN (128 bytes).
|
||||
|
||||
@@ -15,6 +15,7 @@ from ..defines import (
|
||||
from ..types import LvCompound, LvType
|
||||
from . import Widget, WidgetType, get_widgets
|
||||
from .buttonmatrix import CONF_BUTTONMATRIX
|
||||
from .label import CONF_LABEL
|
||||
from .textarea import CONF_TEXTAREA, lv_textarea_t
|
||||
|
||||
CONF_KEYBOARD = "keyboard"
|
||||
@@ -49,7 +50,7 @@ class KeyboardType(WidgetType):
|
||||
)
|
||||
|
||||
def get_uses(self):
|
||||
return CONF_KEYBOARD, CONF_TEXTAREA, CONF_BUTTONMATRIX
|
||||
return CONF_KEYBOARD, CONF_TEXTAREA, CONF_BUTTONMATRIX, CONF_LABEL
|
||||
|
||||
async def to_code(self, w: Widget, config: dict):
|
||||
add_lv_use("KEY_LISTENER")
|
||||
|
||||
@@ -10,6 +10,7 @@ from ..types import lv_obj_t
|
||||
from . import Widget, WidgetType
|
||||
from .canvas import CONF_CANVAS
|
||||
from .img import CONF_IMAGE
|
||||
from .label import CONF_LABEL
|
||||
|
||||
CONF_QRCODE = "qrcode"
|
||||
CONF_DARK_COLOR = "dark_color"
|
||||
@@ -41,7 +42,7 @@ class QrCodeType(WidgetType):
|
||||
)
|
||||
|
||||
def get_uses(self):
|
||||
return CONF_CANVAS, CONF_IMAGE
|
||||
return CONF_CANVAS, CONF_IMAGE, CONF_LABEL
|
||||
|
||||
async def to_code(self, w: Widget, config):
|
||||
await w.set_property(
|
||||
|
||||
@@ -28,6 +28,7 @@ from ..types import LV_EVENT, LvType, ObjUpdateAction, lv_obj_t, lv_obj_t_ptr
|
||||
from . import Widget, WidgetType, add_widgets, get_widgets, set_obj_properties
|
||||
from .button import button_spec
|
||||
from .buttonmatrix import CONF_BUTTONMATRIX, buttonmatrix_spec
|
||||
from .label import CONF_LABEL
|
||||
from .obj import obj_spec
|
||||
|
||||
CONF_TABVIEW = "tabview"
|
||||
@@ -74,7 +75,7 @@ class TabviewType(WidgetType):
|
||||
)
|
||||
|
||||
def get_uses(self):
|
||||
return CONF_BUTTONMATRIX, TYPE_FLEX, CONF_BUTTON
|
||||
return CONF_BUTTONMATRIX, TYPE_FLEX, CONF_BUTTON, CONF_LABEL
|
||||
|
||||
async def to_code(self, w: Widget, config: dict):
|
||||
await w.set_property(
|
||||
|
||||
@@ -67,6 +67,9 @@ void MQTTJSONLightComponent::send_discovery(JsonObject root, mqtt::SendDiscovery
|
||||
if (traits.supports_color_mode(ColorMode::RGB_COLD_WARM_WHITE))
|
||||
color_modes.add(ESPHOME_F("rgbww"));
|
||||
|
||||
if (traits.supports_color_capability(ColorCapability::BRIGHTNESS))
|
||||
root[ESPHOME_F("brightness")] = true;
|
||||
|
||||
if (traits.supports_color_mode(ColorMode::COLOR_TEMPERATURE) ||
|
||||
traits.supports_color_mode(ColorMode::COLD_WARM_WHITE)) {
|
||||
root[MQTT_MIN_MIREDS] = traits.get_min_mireds();
|
||||
|
||||
@@ -88,12 +88,12 @@ def encryption_schema(config: ConfigType | None) -> ConfigType:
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
cg.add_define("USE_NOISE")
|
||||
cg.add_library("esphome/noise-c", "0.1.26")
|
||||
cg.add_library("esphome/noise-c", "0.1.24")
|
||||
# noise-c depends on libsodium, but declaring it here too lets the
|
||||
# library manager see the full set up front instead of discovering
|
||||
# libsodium only after noise-c has downloaded, so the two can download
|
||||
# in parallel. The version must match noise-c's library.json.
|
||||
cg.add_library("esphome/libsodium", "1.10021.8")
|
||||
cg.add_library("esphome/libsodium", "1.10021.6")
|
||||
# Enable optimized memzero/memcmp in libsodium instead of volatile byte loops
|
||||
cg.add_build_flag("-DHAVE_WEAK_SYMBOLS=1")
|
||||
cg.add_build_flag("-DHAVE_INLINE_ASM=1")
|
||||
|
||||
@@ -18,6 +18,16 @@ void RFBridgeComponent::ack_() {
|
||||
}
|
||||
|
||||
bool RFBridgeComponent::parse_bridge_byte_(uint8_t byte) {
|
||||
if (this->bucket_frame_candidate_ && byte == RF_CODE_START) {
|
||||
// A queued next frame proves the trailing 0x55 really was the bucket
|
||||
// frame's terminator: Portisch builds pulse entries from alternating
|
||||
// signal edges, so the two level bits inside one pulse byte are always
|
||||
// opposite — 0xAA (two high-level nibbles) cannot occur in pulse data.
|
||||
// Finalize before this byte starts the new frame, so back-to-back
|
||||
// deliveries are split even when loop() never observed a quiet gap
|
||||
// between them.
|
||||
this->finish_bucket_frame_();
|
||||
}
|
||||
size_t at = this->rx_buffer_.size();
|
||||
this->rx_buffer_.push_back(byte);
|
||||
const uint8_t *raw = &this->rx_buffer_[0];
|
||||
@@ -84,26 +94,21 @@ bool RFBridgeComponent::parse_bridge_byte_(uint8_t byte) {
|
||||
break;
|
||||
}
|
||||
case RF_CODE_RFIN_BUCKET: {
|
||||
if (byte != RF_CODE_STOP) {
|
||||
return true;
|
||||
if (at == 2) {
|
||||
// The count byte: Portisch sends at most 7 buckets + sync, so 0 or
|
||||
// >8 cannot be a genuine capture — reject before it can occupy the
|
||||
// buffer for a full frame timeout.
|
||||
return byte != 0 && byte <= B1_MAX_BUCKET_COUNT;
|
||||
}
|
||||
|
||||
uint8_t buckets = raw[2] << 1;
|
||||
std::string str;
|
||||
char next_byte[3]; // 2 hex chars + null
|
||||
|
||||
for (uint32_t i = 0; i <= at; i++) {
|
||||
buf_append_printf(next_byte, sizeof(next_byte), 0, "%02X", raw[i]);
|
||||
str += next_byte;
|
||||
if ((i > 3) && buckets) {
|
||||
buckets--;
|
||||
}
|
||||
if ((i < 3) || (buckets % 2) || (i == at - 1)) {
|
||||
str += " ";
|
||||
}
|
||||
}
|
||||
ESP_LOGI(TAG, "Received RFBridge Bucket: %s", str.c_str());
|
||||
break;
|
||||
// 0x55 is legal DATA inside a B1 frame: bucket durations are sent
|
||||
// with only their HIGH byte masked to 7 bits, so a duration such as
|
||||
// 0x0155 puts a raw 0x55 low byte inside the table — the first 0x55
|
||||
// must therefore not end the capture. The header declares the table
|
||||
// length (raw[2] pairs), so a 0x55 there is always data; one at or
|
||||
// past the first pulse index is a terminator CANDIDATE, confirmed
|
||||
// once the UART goes quiet (finish_bucket_frame_ in loop()).
|
||||
this->bucket_frame_candidate_ = byte == RF_CODE_STOP && at >= 3 + static_cast<size_t>(raw[2]) * 2;
|
||||
return true;
|
||||
}
|
||||
default:
|
||||
ESP_LOGW(TAG, "Unknown action: 0x%02X", action);
|
||||
@@ -119,6 +124,47 @@ bool RFBridgeComponent::parse_bridge_byte_(uint8_t byte) {
|
||||
return false;
|
||||
}
|
||||
|
||||
void RFBridgeComponent::finish_bucket_frame_() {
|
||||
if (this->rx_buffer_.size() < 4) {
|
||||
// The candidate flag requires a header + non-empty bucket table, so
|
||||
// this cannot happen while flag and buffer stay consistent; guard the
|
||||
// raw[2] / size-1 reads against any future divergence anyway.
|
||||
this->rx_buffer_.clear();
|
||||
this->bucket_frame_candidate_ = false;
|
||||
return;
|
||||
}
|
||||
const uint8_t *raw = this->rx_buffer_.data();
|
||||
const size_t at = this->rx_buffer_.size() - 1;
|
||||
|
||||
uint8_t buckets = raw[2] << 1;
|
||||
std::string str;
|
||||
char next_byte[3]; // 2 hex chars + null
|
||||
|
||||
for (uint32_t i = 0; i <= at; i++) {
|
||||
buf_append_printf(next_byte, sizeof(next_byte), 0, "%02X", raw[i]);
|
||||
str += next_byte;
|
||||
if ((i > 3) && buckets) {
|
||||
buckets--;
|
||||
}
|
||||
if ((i < 3) || (buckets % 2) || (i == at - 1)) {
|
||||
str += " ";
|
||||
}
|
||||
}
|
||||
ESP_LOGI(TAG, "Received RFBridge Bucket: %s", str.c_str());
|
||||
|
||||
// Deliberately NOT ACKed: Portisch's B1 command handler leaves its
|
||||
// last_sniffing_command at the previous mode (RF_CODE_RFIN), and its
|
||||
// host-ACK handler re-arms sniffing from that stale value — so ACKing a
|
||||
// bucket delivery silently reverts the radio to standard sniffing and
|
||||
// ends bucket capture. Its delivery path is fire-and-forget and never
|
||||
// waits for a host ACK. Stock Itead firmware never sends B1 frames, so
|
||||
// suppressing this ACK cannot change stock-firmware behavior.
|
||||
// https://github.com/esphome/esphome/issues/17682
|
||||
|
||||
this->rx_buffer_.clear();
|
||||
this->bucket_frame_candidate_ = false;
|
||||
}
|
||||
|
||||
void RFBridgeComponent::write_byte_str_(const std::string &codes) {
|
||||
uint8_t code;
|
||||
int size = codes.length();
|
||||
@@ -130,12 +176,31 @@ void RFBridgeComponent::write_byte_str_(const std::string &codes) {
|
||||
|
||||
void RFBridgeComponent::loop() {
|
||||
const uint32_t now = App.get_loop_component_start_time();
|
||||
if (now - this->last_bridge_byte_ > 50) {
|
||||
size_t avail = this->available();
|
||||
if (avail == 0 && this->bucket_frame_candidate_ && now - this->last_bridge_byte_ > BUCKET_CANDIDATE_QUIET_MS) {
|
||||
// The trailing 0x55 was followed by UART quiet, so it really was the
|
||||
// frame terminator and not an interior data byte.
|
||||
this->finish_bucket_frame_();
|
||||
this->last_bridge_byte_ = now;
|
||||
}
|
||||
const bool receiving_bucket = this->rx_buffer_.size() >= 2 && this->rx_buffer_[1] == RF_CODE_RFIN_BUCKET;
|
||||
if (receiving_bucket) {
|
||||
// Never declare an in-progress bucket frame dead while its continuation
|
||||
// bytes are already queued: a stalled loop() otherwise discards a live
|
||||
// frame that the UART buffer proves is still arriving.
|
||||
if (avail == 0 && now - this->last_bridge_byte_ > BUCKET_FRAME_TIMEOUT_MS) {
|
||||
ESP_LOGD(TAG, "Discarding incomplete RFBridge Bucket frame (%u bytes)",
|
||||
static_cast<unsigned>(this->rx_buffer_.size()));
|
||||
this->rx_buffer_.clear();
|
||||
this->bucket_frame_candidate_ = false;
|
||||
this->last_bridge_byte_ = now;
|
||||
}
|
||||
} else if (now - this->last_bridge_byte_ > 50) {
|
||||
this->rx_buffer_.clear();
|
||||
this->bucket_frame_candidate_ = false;
|
||||
this->last_bridge_byte_ = now;
|
||||
}
|
||||
|
||||
size_t avail = this->available();
|
||||
while (avail > 0) {
|
||||
uint8_t buf[64];
|
||||
size_t to_read = std::min(avail, sizeof(buf));
|
||||
@@ -146,12 +211,14 @@ void RFBridgeComponent::loop() {
|
||||
for (size_t i = 0; i < to_read; i++) {
|
||||
if (this->rx_buffer_.size() > MAX_RX_BUFFER_SIZE) {
|
||||
this->rx_buffer_.clear();
|
||||
this->bucket_frame_candidate_ = false;
|
||||
}
|
||||
if (this->parse_bridge_byte_(buf[i])) {
|
||||
ESP_LOGVV(TAG, "Parsed: 0x%02X", buf[i]);
|
||||
this->last_bridge_byte_ = now;
|
||||
} else {
|
||||
this->rx_buffer_.clear();
|
||||
this->bucket_frame_candidate_ = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,17 @@ static const uint8_t RF_CODE_BEEP = 0xC0;
|
||||
static const uint8_t RF_CODE_STOP = 0x55;
|
||||
static const uint8_t RF_DEBOUNCE = 200;
|
||||
static const size_t MAX_RX_BUFFER_SIZE = 512;
|
||||
// ~10 byte times at 19200 baud: long enough to prove the UART went quiet
|
||||
// after a possible bucket-frame terminator, short enough to finish well
|
||||
// before the next radio capture can be delivered.
|
||||
static const uint32_t BUCKET_CANDIDATE_QUIET_MS = 5;
|
||||
// Portisch drains a B1 frame's header, bucket table, and pulse data as
|
||||
// separate UART writes, so an in-progress bucket frame tolerates a longer
|
||||
// inter-region gap than the generic 50 ms inter-byte timeout.
|
||||
static const uint32_t BUCKET_FRAME_TIMEOUT_MS = 250;
|
||||
// Portisch's uart_put_RF_buckets sends at most 7 buckets plus the sync
|
||||
// bucket, so a B1 count byte above 8 (or 0) is malformed for any protocol.
|
||||
static const uint8_t B1_MAX_BUCKET_COUNT = 8;
|
||||
|
||||
struct RFBridgeData {
|
||||
uint16_t sync;
|
||||
@@ -67,10 +78,12 @@ class RFBridgeComponent final : public uart::UARTDevice, public Component {
|
||||
void ack_();
|
||||
void decode_();
|
||||
bool parse_bridge_byte_(uint8_t byte);
|
||||
void finish_bucket_frame_();
|
||||
void write_byte_str_(const std::string &codes);
|
||||
|
||||
std::vector<uint8_t> rx_buffer_;
|
||||
uint32_t last_bridge_byte_{0};
|
||||
bool bucket_frame_candidate_{false};
|
||||
|
||||
CallbackManager<void(RFBridgeData)> data_callback_;
|
||||
CallbackManager<void(RFBridgeAdvancedData)> advanced_data_callback_;
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
#include "tuya.h"
|
||||
#include "esphome/components/network/util.h"
|
||||
#include "esphome/core/gpio.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/util.h"
|
||||
|
||||
#ifdef USE_NETWORK
|
||||
#include "esphome/components/network/util.h"
|
||||
#endif
|
||||
|
||||
#ifdef USE_WIFI
|
||||
#include "esphome/components/wifi/wifi_component.h"
|
||||
#endif
|
||||
@@ -22,6 +25,14 @@ static const int MAX_RETRIES = 5;
|
||||
// Max bytes to log for datapoint values (larger values are truncated)
|
||||
static constexpr size_t MAX_DATAPOINT_LOG_BYTES = 16;
|
||||
|
||||
static bool network_is_connected() {
|
||||
#ifdef USE_NETWORK
|
||||
return network::is_connected();
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
void Tuya::setup() {
|
||||
this->set_interval("heartbeat", 15000, [this] { this->send_empty_command_(TuyaCommandType::HEARTBEAT); });
|
||||
if (this->status_pin_ != nullptr) {
|
||||
@@ -554,14 +565,14 @@ void Tuya::send_empty_command_(TuyaCommandType command) {
|
||||
}
|
||||
|
||||
void Tuya::set_status_pin_() {
|
||||
bool is_network_ready = network::is_connected() && remote_is_connected();
|
||||
bool is_network_ready = network_is_connected() && remote_is_connected();
|
||||
this->status_pin_->digital_write(is_network_ready);
|
||||
}
|
||||
|
||||
uint8_t Tuya::get_wifi_status_code_() {
|
||||
uint8_t status = 0x02;
|
||||
|
||||
if (network::is_connected()) {
|
||||
if (network_is_connected()) {
|
||||
status = 0x03;
|
||||
|
||||
// Protocol version 3 also supports specifying when connected to "the cloud"
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from collections.abc import Callable
|
||||
from typing import Any, NoReturn
|
||||
from typing import Any
|
||||
|
||||
from esphome import automation
|
||||
from esphome.automation import Trigger
|
||||
@@ -48,17 +47,10 @@ UDP_SCHEMA = cv.Schema(
|
||||
)
|
||||
|
||||
|
||||
def is_relocated(option: str) -> Callable[[Any], NoReturn]:
|
||||
def validator(value: Any) -> NoReturn:
|
||||
raise cv.Invalid(
|
||||
f"The '{option}' option should now be configured in the 'packet_transport' component"
|
||||
)
|
||||
|
||||
return validator
|
||||
|
||||
|
||||
RELOCATED = {
|
||||
cv.Optional(x): is_relocated(x)
|
||||
cv.Optional(x): cv.invalid(
|
||||
f"The '{x}' option should now be configured in the 'packet_transport' component"
|
||||
)
|
||||
for x in (
|
||||
CONF_PROVIDERS,
|
||||
CONF_ENCRYPTION,
|
||||
|
||||
+6
-3
@@ -96,6 +96,10 @@ UPLOAD_BUFFER_SIZE = UPLOAD_BLOCK_SIZE * 8
|
||||
# across the addresses on top of that.
|
||||
EXTRA_UPLOAD_ATTEMPTS = 2
|
||||
UPLOAD_RETRY_DELAY = 5.0
|
||||
# Data phase timeout; must stay longer than the device's OTA_SOCKET_TIMEOUT_DATA
|
||||
# (105 s) so a stalled session is gone before a retry, and long enough for lwIP
|
||||
# to get a lost chunk ack through after the retransmit run seen in practice
|
||||
DATA_PHASE_TIMEOUT = 160.0
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -694,8 +698,7 @@ def perform_ota(
|
||||
|
||||
_LOGGER.info("Handshake complete")
|
||||
|
||||
# Timeout must match device-side OTA_SOCKET_TIMEOUT_DATA to prevent premature failures
|
||||
sock.settimeout(90.0)
|
||||
sock.settimeout(DATA_PHASE_TIMEOUT)
|
||||
|
||||
if extended_proto:
|
||||
send_check(sock, ota_type, "ota type")
|
||||
@@ -854,7 +857,7 @@ def run_ota_impl_(
|
||||
# clean up a half-open connection (its handshake watchdog runs at 20s);
|
||||
# moving on to the next address family stays immediate. Known limitation:
|
||||
# a silent mid-transfer drop with no reset can wedge the device until its
|
||||
# 90s data timeout, which outlasts this budget; the retries target the
|
||||
# 105s data timeout, which outlasts this budget; the retries target the
|
||||
# common failures where the device resets or closes the link promptly.
|
||||
total_attempts = len(res) + EXTRA_UPLOAD_ATTEMPTS
|
||||
last_error = ""
|
||||
|
||||
@@ -616,11 +616,15 @@ def _make_registry_client() -> Any:
|
||||
elsewhere, not by the PlatformIO registry.
|
||||
"""
|
||||
from platformio.package.manager._registry import PackageManagerRegistryMixin
|
||||
from platformio.registry.client import RegistryClient
|
||||
|
||||
class _Registry(PackageManagerRegistryMixin):
|
||||
def __init__(self) -> None:
|
||||
self._registry_client = None
|
||||
self.pkg_type = "library"
|
||||
self._registry_client = RegistryClient()
|
||||
# The probe sleeps ~500 ms per lookup (see runner.patch_registry_private_packages);
|
||||
# instance-level so the ESPHome process never patches PlatformIO's class
|
||||
self._registry_client.allowed_private_packages = lambda: False
|
||||
|
||||
@staticmethod
|
||||
def is_system_compatible(value: Any, custom_system: Any = None) -> bool:
|
||||
|
||||
@@ -951,8 +951,10 @@ def main(argv: list[str]) -> int:
|
||||
"""Subprocess entry point: ``prefetch <build_dir> <env_name>``."""
|
||||
from esphome.core import CORE
|
||||
from esphome.log import setup_log
|
||||
from esphome.platformio.runner import patch_registry_private_packages
|
||||
|
||||
signal.signal(signal.SIGTERM, _sigterm)
|
||||
patch_registry_private_packages()
|
||||
raw_level = os.environ.get("ESPHOME_PREFETCH_LOG_LEVEL")
|
||||
try:
|
||||
level = int(raw_level) if raw_level is not None else logging.INFO
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
Invoked via ``python -m esphome.platformio.runner`` instead of
|
||||
``python -m platformio`` so that the patches (incremental rebuild
|
||||
preservation, download retries) apply inside the subprocess. Running
|
||||
preservation, download retries, skipping the private-package probe) apply
|
||||
inside the subprocess. Running
|
||||
PlatformIO in a subprocess keeps its ``sys.path`` mutations and other
|
||||
global state from leaking into the ESPHome process.
|
||||
"""
|
||||
@@ -105,6 +106,16 @@ def patch_file_downloader() -> None:
|
||||
FileDownloader.__init__ = patched_init
|
||||
|
||||
|
||||
def patch_registry_private_packages() -> None:
|
||||
"""Skip PlatformIO's private-package probe; it sleeps ~500 ms per lookup.
|
||||
|
||||
ESPHome never uses private packages, so the answer is always False.
|
||||
"""
|
||||
from platformio.registry.client import RegistryClient
|
||||
|
||||
RegistryClient.allowed_private_packages = staticmethod(lambda: False) # type: ignore[method-assign]
|
||||
|
||||
|
||||
_IGNORE_LIB_WARNINGS = "(?:Hash|Update)"
|
||||
# Regex patterns matched against each line of PlatformIO output. Lines that
|
||||
# match are dropped by RedirectText before they reach the parent process.
|
||||
@@ -152,6 +163,7 @@ FILTER_PLATFORMIO_LINES = [
|
||||
def main() -> int:
|
||||
patch_structhash()
|
||||
patch_file_downloader()
|
||||
patch_registry_private_packages()
|
||||
|
||||
# Wrap stdout/stderr with RedirectText before PlatformIO runs:
|
||||
#
|
||||
|
||||
+3
-3
@@ -45,7 +45,7 @@ lib_deps_base =
|
||||
lib_deps =
|
||||
${common.lib_deps_base}
|
||||
https://github.com/dudanov/MideaUART.git#eeea6c3e9b4474f067054592b435be1c4e466815 ; midea
|
||||
esphome/noise-c@0.1.26 ; noise (api, ota)
|
||||
esphome/noise-c@0.1.24 ; noise (api, ota)
|
||||
improv/Improv@1.2.7 ; improv_serial / esp32_improv
|
||||
kikuchan98/pngle@1.1.0 ; online_image
|
||||
; Using the repository directly, otherwise ESP-IDF can't use the library
|
||||
@@ -244,7 +244,7 @@ lib_deps =
|
||||
${common:idf-component-libs.lib_deps}
|
||||
ESP32Async/ESPAsyncWebServer@3.9.6 ; web_server_base
|
||||
droscy/esp_wireguard@0.4.5 ; wireguard
|
||||
esphome/noise-c@0.1.26 ; noise (api, ota)
|
||||
esphome/noise-c@0.1.24 ; noise (api, ota)
|
||||
ESP32Async/AsyncTCP@3.4.5 ; async_tcp
|
||||
DNSServer ; captive_portal
|
||||
heman/AsyncMqttClient-esphome@2.0.0 ; mqtt
|
||||
@@ -641,7 +641,7 @@ build_unflags =
|
||||
extends = common
|
||||
platform = platformio/native
|
||||
lib_deps =
|
||||
esphome/noise-c@0.1.26 ; used by noise (api, ota)
|
||||
esphome/noise-c@0.1.24 ; used by noise (api, ota)
|
||||
lvgl/lvgl@9.5.0 ; lvgl
|
||||
build_flags =
|
||||
${common.build_flags}
|
||||
|
||||
@@ -14,7 +14,31 @@ top=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0
|
||||
[ -x "$top/venv/bin/python" ] && exit 0
|
||||
[ -x "$top/script/setup" ] || exit 0
|
||||
|
||||
# Every worktree shares the hooks directory of the checkout it was created
|
||||
# from, and the script/setup run below is the one from whichever branch was just
|
||||
# checked out. Older branches install their own pre-commit hook without checking
|
||||
# for a worktree: that moves the shared hook aside as pre-commit.legacy and
|
||||
# replaces it with one tied to this worktree's virtual environment, so commits
|
||||
# break in every checkout. To rule that out, the hooks directory is copied
|
||||
# before script/setup runs and put back exactly as it was afterwards, including
|
||||
# removing any file script/setup added.
|
||||
hooks=$(git rev-parse --path-format=absolute --git-path hooks 2>/dev/null) || exit 0
|
||||
snap=$(mktemp -d "$hooks/.post-checkout.XXXXXX") || exit 0
|
||||
cp -p "$hooks"/* "$snap"/ 2>/dev/null
|
||||
|
||||
# Clear VIRTUAL_ENV so a checkout made from a shell with an environment already
|
||||
# activated still gets its own, rather than having the active one repointed at
|
||||
# this working tree.
|
||||
exec env -u VIRTUAL_ENV "$top/script/setup"
|
||||
env -u VIRTUAL_ENV "$top/script/setup"
|
||||
status=$?
|
||||
|
||||
for f in "$hooks"/*; do
|
||||
[ -e "$snap/${f##*/}" ] || rm -f "$f"
|
||||
done
|
||||
# Files are moved rather than copied so a hook that is still running, such as
|
||||
# this one, is swapped out atomically instead of being rewritten in place.
|
||||
for f in "$snap"/*; do
|
||||
cmp -s "$f" "$hooks/${f##*/}" 2>/dev/null || mv -f "$f" "$hooks/${f##*/}"
|
||||
done
|
||||
rm -rf "$snap"
|
||||
exit $status
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
esphome:
|
||||
name: test-keyboard-no-label
|
||||
|
||||
esp32:
|
||||
board: esp32dev
|
||||
framework:
|
||||
type: esp-idf
|
||||
|
||||
spi:
|
||||
- id: spi_bus
|
||||
clk_pin: GPIO18
|
||||
mosi_pin: GPIO23
|
||||
|
||||
display:
|
||||
- platform: mipi_spi
|
||||
spi_id: spi_bus
|
||||
model: st7789v
|
||||
id: tft_display
|
||||
dimensions:
|
||||
width: 240
|
||||
height: 320
|
||||
cs_pin: GPIO22
|
||||
dc_pin: GPIO21
|
||||
auto_clear_enabled: false
|
||||
invert_colors: false
|
||||
update_interval: never
|
||||
|
||||
lvgl:
|
||||
displays: tft_display
|
||||
widgets:
|
||||
- keyboard:
|
||||
id: keyboard_widget
|
||||
@@ -0,0 +1,34 @@
|
||||
esphome:
|
||||
name: test-qrcode-no-label
|
||||
|
||||
esp32:
|
||||
board: esp32dev
|
||||
framework:
|
||||
type: esp-idf
|
||||
|
||||
spi:
|
||||
- id: spi_bus
|
||||
clk_pin: GPIO18
|
||||
mosi_pin: GPIO23
|
||||
|
||||
display:
|
||||
- platform: mipi_spi
|
||||
spi_id: spi_bus
|
||||
model: st7789v
|
||||
id: tft_display
|
||||
dimensions:
|
||||
width: 240
|
||||
height: 320
|
||||
cs_pin: GPIO22
|
||||
dc_pin: GPIO21
|
||||
auto_clear_enabled: false
|
||||
invert_colors: false
|
||||
update_interval: never
|
||||
|
||||
lvgl:
|
||||
displays: tft_display
|
||||
widgets:
|
||||
- qrcode:
|
||||
id: qr_widget
|
||||
size: 100
|
||||
text: "esphome.io"
|
||||
@@ -0,0 +1,35 @@
|
||||
esphome:
|
||||
name: test-tabview-no-label
|
||||
|
||||
esp32:
|
||||
board: esp32dev
|
||||
framework:
|
||||
type: esp-idf
|
||||
|
||||
spi:
|
||||
- id: spi_bus
|
||||
clk_pin: GPIO18
|
||||
mosi_pin: GPIO23
|
||||
|
||||
display:
|
||||
- platform: mipi_spi
|
||||
spi_id: spi_bus
|
||||
model: st7789v
|
||||
id: tft_display
|
||||
dimensions:
|
||||
width: 240
|
||||
height: 320
|
||||
cs_pin: GPIO22
|
||||
dc_pin: GPIO21
|
||||
auto_clear_enabled: false
|
||||
invert_colors: false
|
||||
update_interval: never
|
||||
|
||||
lvgl:
|
||||
displays: tft_display
|
||||
widgets:
|
||||
- tabview:
|
||||
id: tabview_widget
|
||||
tabs:
|
||||
- name: "Tab 1"
|
||||
id: tab_1
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Widgets whose LVGL C implementation creates or references labels
|
||||
internally (tab titles, key legends, the QR canvas fallback) must declare
|
||||
the label dependency in ``get_uses()``. Otherwise a config that contains
|
||||
no ``label`` widget of its own compiles LVGL without ``LV_USE_LABEL`` and
|
||||
fails at C compile time with undefined ``lv_label_*`` symbols.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.components.lvgl import defines as df
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"yaml_file",
|
||||
[
|
||||
"qrcode_no_label.yaml",
|
||||
"keyboard_no_label.yaml",
|
||||
"tabview_no_label.yaml",
|
||||
],
|
||||
)
|
||||
def test_label_less_config_enables_lv_use_label(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
component_config_path: Callable[[str], Path],
|
||||
yaml_file: str,
|
||||
) -> None:
|
||||
generate_main(component_config_path(yaml_file))
|
||||
assert "LV_USE_LABEL" in df.get_defines()
|
||||
@@ -0,0 +1,5 @@
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
manifest.dependencies = manifest.dependencies + ["sensor", "spi"]
|
||||
@@ -0,0 +1,62 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "esphome/components/atm90e32/atm90e32.h"
|
||||
|
||||
namespace esphome::atm90e32::testing {
|
||||
|
||||
TEST(ATM90E32OffsetRegisterVerification, AcceptsExactSignedReadback) {
|
||||
EXPECT_TRUE(offset_register_value_matches(0x007B, 123));
|
||||
EXPECT_TRUE(offset_register_value_matches(0xFF85, -123));
|
||||
}
|
||||
|
||||
TEST(ATM90E32OffsetRegisterVerification, RejectsMismatchedReadback) {
|
||||
EXPECT_FALSE(offset_register_value_matches(0x007C, 123));
|
||||
EXPECT_FALSE(offset_register_value_matches(0xFF84, -123));
|
||||
}
|
||||
|
||||
TEST(ATM90E32OffsetRestoreState, ReportsVerifiedStoredValuesAsRestored) {
|
||||
const auto state = resolve_offset_restore_state(true, true, false);
|
||||
|
||||
EXPECT_TRUE(state.restored);
|
||||
EXPECT_TRUE(state.values_verified);
|
||||
}
|
||||
|
||||
TEST(ATM90E32OffsetRestoreState, ReportsVerifiedConfigFallbackAsNotRestored) {
|
||||
const auto state = resolve_offset_restore_state(true, false, true);
|
||||
|
||||
EXPECT_FALSE(state.restored);
|
||||
EXPECT_TRUE(state.values_verified);
|
||||
}
|
||||
|
||||
TEST(ATM90E32OffsetRestoreState, ReportsFailedConfigFallbackAsUnverified) {
|
||||
const auto state = resolve_offset_restore_state(true, false, false);
|
||||
|
||||
EXPECT_FALSE(state.restored);
|
||||
EXPECT_FALSE(state.values_verified);
|
||||
}
|
||||
|
||||
TEST(ATM90E32OffsetRestoreState, ReportsConfigWithoutStoredValuesAsNotRestored) {
|
||||
const auto state = resolve_offset_restore_state(false, true, false);
|
||||
|
||||
EXPECT_FALSE(state.restored);
|
||||
EXPECT_TRUE(state.values_verified);
|
||||
}
|
||||
|
||||
TEST(ATM90E32OffsetPersistence, RollsBackStoredValuesOrZeroSentinel) {
|
||||
const OffsetCalibration previous[3]{{1, -1}, {2, -2}, {3, -3}};
|
||||
OffsetCalibration rollback[3]{};
|
||||
|
||||
prepare_offset_rollback(previous, true, rollback);
|
||||
for (uint8_t phase = 0; phase < 3; phase++) {
|
||||
EXPECT_EQ(rollback[phase].first_offset, previous[phase].first_offset);
|
||||
EXPECT_EQ(rollback[phase].second_offset, previous[phase].second_offset);
|
||||
}
|
||||
|
||||
prepare_offset_rollback(previous, false, rollback);
|
||||
for (const auto &phase : rollback) {
|
||||
EXPECT_EQ(phase.first_offset, 0);
|
||||
EXPECT_EQ(phase.second_offset, 0);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace esphome::atm90e32::testing
|
||||
@@ -0,0 +1,29 @@
|
||||
# Tuya without any network component (no wifi/ethernet/api), as used on
|
||||
# serial-only or BLE-only Tuya MCU boards. Regression test for
|
||||
# https://github.com/esphome/esphome/issues/18942
|
||||
substitutions:
|
||||
status_pin: P6
|
||||
|
||||
packages:
|
||||
uart: !include ../../test_build_components/common/uart/bk72xx-ard.yaml
|
||||
|
||||
tuya:
|
||||
status_pin: ${status_pin}
|
||||
|
||||
binary_sensor:
|
||||
- platform: tuya
|
||||
id: tuya_presence
|
||||
sensor_datapoint: 101
|
||||
|
||||
sensor:
|
||||
- platform: tuya
|
||||
id: tuya_light_intensity
|
||||
sensor_datapoint: 103
|
||||
|
||||
number:
|
||||
- platform: tuya
|
||||
id: tuya_far_detection
|
||||
number_datapoint: 109
|
||||
min_value: 0
|
||||
max_value: 600
|
||||
step: 1
|
||||
@@ -35,8 +35,8 @@ def _load_script():
|
||||
def test_spec_key_collapses_destinations() -> None:
|
||||
"""Two specs delivering one package share a directory and one key."""
|
||||
mod = _load_script()
|
||||
assert mod.spec_key("esphome/noise-c @ 0.1.26") == "noise-c"
|
||||
assert mod.spec_key("esphome/noise-c@0.1.26") == "noise-c"
|
||||
assert mod.spec_key("esphome/noise-c @ 0.1.24") == "noise-c"
|
||||
assert mod.spec_key("esphome/noise-c@0.1.24") == "noise-c"
|
||||
assert mod.spec_key("ESP32Async/AsyncTCP @ ^3.4.10") == mod.spec_key(
|
||||
"esp32async/asynctcp @ 3.5.0"
|
||||
)
|
||||
@@ -54,23 +54,23 @@ def test_parse_specs_and_cli_args(tmp_path: Path) -> None:
|
||||
"[env:a]\n"
|
||||
"platform = fake/platform@1\n"
|
||||
"lib_deps =\n"
|
||||
" esphome/noise-c @ 0.1.26\n"
|
||||
" esphome/noise-c @ 0.1.24\n"
|
||||
" ${common.lib_deps}\n"
|
||||
" internal_lib\n"
|
||||
"[env:b]\n"
|
||||
"lib_deps =\n"
|
||||
" esphome/noise-c @ 0.1.26\n"
|
||||
" esphome/noise-c @ 0.1.24\n"
|
||||
)
|
||||
mod = _load_script()
|
||||
args = Namespace(libraries=True, platforms=True, tools=False)
|
||||
libs, platforms, tools = mod.parse_specs(str(ini), args)
|
||||
# exact-string duplicates collapse; distinct version pins survive
|
||||
assert libs == ["esphome/noise-c @ 0.1.26"]
|
||||
assert libs == ["esphome/noise-c @ 0.1.24"]
|
||||
assert platforms == ["fake/platform@1"]
|
||||
assert tools == []
|
||||
assert mod.build_cli_args(libs, platforms, tools) == [
|
||||
"-l",
|
||||
"esphome/noise-c @ 0.1.26",
|
||||
"esphome/noise-c @ 0.1.24",
|
||||
"-p",
|
||||
"fake/platform@1",
|
||||
]
|
||||
@@ -162,13 +162,13 @@ def test_parallel_install_behavior(tmp_path: Path) -> None:
|
||||
mod.parallel_install(
|
||||
cls,
|
||||
[
|
||||
"esphome/noise-c @ 0.1.26",
|
||||
"esphome/noise-c @ 0.1.26",
|
||||
"esphome/noise-c @ 0.1.24",
|
||||
"esphome/noise-c @ 0.1.24",
|
||||
"esphome/already @ 1.0",
|
||||
"https://x/framework.tar.xz",
|
||||
],
|
||||
)
|
||||
assert cls.calls == ["esphome/noise-c @ 0.1.26"]
|
||||
assert cls.calls == ["esphome/noise-c @ 0.1.24"]
|
||||
assert cls.lock_events == ["lock", "unlock"]
|
||||
|
||||
|
||||
@@ -205,7 +205,7 @@ def test_parallel_install_runs_dependency_waves(tmp_path: Path) -> None:
|
||||
mod = _load_script()
|
||||
cls = _reset_fake(str(tmp_path))
|
||||
cls.deps = {
|
||||
"esphome/noise-c @ 0.1.26": [
|
||||
"esphome/noise-c @ 0.1.24": [
|
||||
{"owner": "esphome", "name": "libsodium", "version": "^1.0"},
|
||||
{"name": "SPI"},
|
||||
],
|
||||
@@ -213,12 +213,12 @@ def test_parallel_install_runs_dependency_waves(tmp_path: Path) -> None:
|
||||
{"owner": "esphome", "name": "libsodium", "version": "^1.0"},
|
||||
],
|
||||
}
|
||||
mod.parallel_install(cls, ["esphome/noise-c @ 0.1.26", "esphome/wg @ 1.0"])
|
||||
mod.parallel_install(cls, ["esphome/noise-c @ 0.1.24", "esphome/wg @ 1.0"])
|
||||
assert len(cls.calls) == 3 # the shared dep installs exactly once
|
||||
assert {mod.spec_key(c) for c in cls.calls} == {"noise-c", "wg", "libsodium"}
|
||||
# Wave-1 strings carry no compatibility; the dependency wave does
|
||||
compats = dict(cls.compat_calls)
|
||||
assert compats["esphome/noise-c @ 0.1.26"] is None
|
||||
assert compats["esphome/noise-c @ 0.1.24"] is None
|
||||
dep_compat = next(v for k, v in cls.compat_calls if "libsodium" in k)
|
||||
assert dep_compat is not None # mirrors pio's install_dependency
|
||||
|
||||
@@ -229,11 +229,11 @@ def test_dependency_wave_excludes_url_specs(tmp_path: Path) -> None:
|
||||
mod = _load_script()
|
||||
cls = _reset_fake(str(tmp_path))
|
||||
cls.deps = {
|
||||
"esphome/noise-c @ 0.1.26": [
|
||||
"esphome/noise-c @ 0.1.24": [
|
||||
{"name": "vendored", "version": "https://github.com/x/y.git"},
|
||||
],
|
||||
}
|
||||
mod.parallel_install(cls, ["esphome/noise-c @ 0.1.26"])
|
||||
mod.parallel_install(cls, ["esphome/noise-c @ 0.1.24"])
|
||||
assert {mod.spec_key(c) for c in cls.calls} == {"noise-c"}
|
||||
|
||||
|
||||
@@ -348,13 +348,13 @@ def test_warm_store_still_walks_dependencies(tmp_path: Path) -> None:
|
||||
"""Already-installed top-level packages still feed the dependency
|
||||
wave; a warm store can be missing a transitive dep."""
|
||||
mod = _load_script()
|
||||
cls = _reset_fake(str(tmp_path), installed={"esphome/noise-c @ 0.1.26"})
|
||||
cls = _reset_fake(str(tmp_path), installed={"esphome/noise-c @ 0.1.24"})
|
||||
cls.deps = {
|
||||
"esphome/noise-c @ 0.1.26": [
|
||||
"esphome/noise-c @ 0.1.24": [
|
||||
{"owner": "esphome", "name": "libsodium", "version": "^1.0"},
|
||||
],
|
||||
}
|
||||
mod.parallel_install(cls, ["esphome/noise-c @ 0.1.26"])
|
||||
mod.parallel_install(cls, ["esphome/noise-c @ 0.1.24"])
|
||||
assert [mod.spec_key(c) for c in cls.calls] == ["libsodium"]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Tests for the udp component configuration schema."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.components import udp
|
||||
from esphome.components.packet_transport import (
|
||||
CONF_BINARY_SENSORS,
|
||||
CONF_ENCRYPTION,
|
||||
CONF_PING_PONG_ENABLE,
|
||||
CONF_PROVIDERS,
|
||||
CONF_ROLLING_CODE_ENABLE,
|
||||
CONF_SENSORS,
|
||||
)
|
||||
import esphome.config_validation as cv
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"option",
|
||||
[
|
||||
CONF_PROVIDERS,
|
||||
CONF_ENCRYPTION,
|
||||
CONF_PING_PONG_ENABLE,
|
||||
CONF_ROLLING_CODE_ENABLE,
|
||||
CONF_SENSORS,
|
||||
CONF_BINARY_SENSORS,
|
||||
],
|
||||
)
|
||||
def test_relocated_option_rejected(option: str) -> None:
|
||||
"""Options that moved to packet_transport raise a pointing error."""
|
||||
with pytest.raises(cv.Invalid) as exc_info:
|
||||
udp.CONFIG_SCHEMA({option: True})
|
||||
assert (
|
||||
f"The '{option}' option should now be configured in the 'packet_transport' component"
|
||||
in str(exc_info.value)
|
||||
)
|
||||
@@ -416,6 +416,9 @@ def test_perform_ota_no_auth(
|
||||
"Update took 14.00 seconds (prepare 2.00, upload 5.00, commit 7.00)"
|
||||
in caplog.text
|
||||
)
|
||||
# The data phase timeout must outlast the device's 105 s data timeout
|
||||
mock_socket.settimeout.assert_any_call(espota2.DATA_PHASE_TIMEOUT)
|
||||
assert espota2.DATA_PHASE_TIMEOUT > 105.0
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_time")
|
||||
|
||||
@@ -7,6 +7,7 @@ exercised in their own test modules)."""
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -228,6 +229,24 @@ def test_resolve_registry_version_raises_without_pkg_file(monkeypatch):
|
||||
_resolve_registry_version("owner", "pkg", set())
|
||||
|
||||
|
||||
def test_make_registry_client_skips_private_package_probe(monkeypatch):
|
||||
"""Our client answers the probe locally without patching PlatformIO's class."""
|
||||
from platformio.account.client import AccountClient
|
||||
from platformio.registry.client import RegistryClient
|
||||
|
||||
pio_probe = RegistryClient.__dict__["allowed_private_packages"]
|
||||
monkeypatch.setattr(
|
||||
AccountClient,
|
||||
"get_account_info",
|
||||
Mock(side_effect=AssertionError("account probe must not run")),
|
||||
)
|
||||
|
||||
client = lib._make_registry_client().get_registry_client_instance()
|
||||
|
||||
assert client.allowed_private_packages() is False
|
||||
assert RegistryClient.__dict__["allowed_private_packages"] is pio_probe
|
||||
|
||||
|
||||
def _patch_registry_resolve(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Stub the registry lookup so tests never touch the network."""
|
||||
monkeypatch.setattr(
|
||||
|
||||
@@ -1225,6 +1225,20 @@ def test_main_runs_prefetch(tmp_path: Path) -> None:
|
||||
mock_prefetch.assert_called_once_with(tmp_path, "testenv")
|
||||
|
||||
|
||||
def test_main_skips_private_package_probe_before_prefetch(tmp_path: Path) -> None:
|
||||
"""The registry probe patch is applied before any package manager runs."""
|
||||
order: list[str] = []
|
||||
with (
|
||||
patch.object(pf, "_prefetch", side_effect=lambda *_: order.append("prefetch")),
|
||||
patch(
|
||||
"esphome.platformio.runner.patch_registry_private_packages",
|
||||
side_effect=lambda: order.append("patch"),
|
||||
),
|
||||
):
|
||||
assert pf.main([str(tmp_path), "testenv"]) == 0
|
||||
assert order == ["patch", "prefetch"]
|
||||
|
||||
|
||||
def test_main_bad_argv_is_a_distinct_exit(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
@@ -1649,7 +1663,7 @@ def test_preinstall_runs_dependency_waves(tmp_path: Path) -> None:
|
||||
{"name": "SPI"},
|
||||
]
|
||||
m.dependency_to_spec.side_effect = lambda dep: _FakeSpec(name=dep["name"])
|
||||
pf._preinstall(m, [("noise-c@0.1.26", _FakeSpec(name="noise-c"))])
|
||||
pf._preinstall(m, [("noise-c@0.1.24", _FakeSpec(name="noise-c"))])
|
||||
assert installed == ["noise-c", "libsodium"] # dep deduped, SPI left out
|
||||
# The dep wave carries its compatibility so _install searches qualified
|
||||
dep_call = m._install.call_args_list[-1]
|
||||
@@ -1669,7 +1683,7 @@ def test_preinstall_dependency_wave_skips_seen_names(tmp_path: Path) -> None:
|
||||
m._install.side_effect = lambda spec, skip_dependencies, compatibility=None: (
|
||||
installed.append(getattr(spec, "name", str(spec)))
|
||||
)
|
||||
pf._preinstall(m, [("noise-c@0.1.26", _FakeSpec(name="noise-c"))])
|
||||
pf._preinstall(m, [("noise-c@0.1.24", _FakeSpec(name="noise-c"))])
|
||||
assert installed == ["noise-c"]
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,9 @@ from collections.abc import Callable
|
||||
import io
|
||||
import sys
|
||||
from types import ModuleType
|
||||
from unittest.mock import Mock
|
||||
|
||||
from platformio.registry.client import RegistryClient
|
||||
import pytest
|
||||
|
||||
from esphome.platformio import runner
|
||||
@@ -30,6 +32,7 @@ def _prepare_main(
|
||||
monkeypatch.setattr(sys, "stderr", stream)
|
||||
monkeypatch.setattr(runner, "patch_structhash", lambda: None)
|
||||
monkeypatch.setattr(runner, "patch_file_downloader", lambda: None)
|
||||
monkeypatch.setattr(runner, "patch_registry_private_packages", lambda: None)
|
||||
|
||||
platformio = ModuleType("platformio")
|
||||
platformio_main = ModuleType("platformio.__main__")
|
||||
@@ -91,3 +94,40 @@ def test_main_still_filters_a_drained_partial_line(
|
||||
|
||||
assert runner.main() == 0
|
||||
assert buf.getvalue() == b""
|
||||
|
||||
|
||||
def test_main_applies_registry_private_packages_patch(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""The probe is patched before PlatformIO runs."""
|
||||
order: list[str] = []
|
||||
_prepare_main(monkeypatch, lambda: order.append("pio") or 0)
|
||||
monkeypatch.setattr(
|
||||
runner, "patch_registry_private_packages", lambda: order.append("patch")
|
||||
)
|
||||
|
||||
assert runner.main() == 0
|
||||
assert order == ["patch", "pio"]
|
||||
|
||||
|
||||
# Snapshot PlatformIO's own probe at import, before any test can patch it
|
||||
_PIO_PROBE = RegistryClient.__dict__["allowed_private_packages"]
|
||||
|
||||
|
||||
def test_patch_registry_private_packages_skips_account_probe(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Answers False without touching the account client."""
|
||||
from platformio.account.client import AccountClient
|
||||
|
||||
monkeypatch.setattr(RegistryClient, "allowed_private_packages", _PIO_PROBE)
|
||||
monkeypatch.setattr(
|
||||
AccountClient,
|
||||
"get_account_info",
|
||||
Mock(side_effect=AssertionError("account probe must not run")),
|
||||
)
|
||||
|
||||
runner.patch_registry_private_packages()
|
||||
|
||||
assert RegistryClient.allowed_private_packages() is False
|
||||
assert RegistryClient().allowed_private_packages() is False
|
||||
|
||||
Reference in New Issue
Block a user