mirror of
https://github.com/esphome/esphome.git
synced 2025-11-09 11:31:50 +00:00
Compare commits
51 Commits
base64_cha
...
2025.9.0b1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7a869a33f0 | ||
|
|
56e85b3ef9 | ||
|
|
2401f81be3 | ||
|
|
52a7e26c6d | ||
|
|
d729dc20a8 | ||
|
|
d3b7a9687b | ||
|
|
9d7fc11108 | ||
|
|
7969627d3e | ||
|
|
82d2e367d4 | ||
|
|
972aa691e4 | ||
|
|
ac61b8f893 | ||
|
|
d9f625e5c8 | ||
|
|
e218f16f0f | ||
|
|
422d209786 | ||
|
|
e972e1f8c2 | ||
|
|
cfb90b7b18 | ||
|
|
8976ea2436 | ||
|
|
01ff09064d | ||
|
|
39212f0d7f | ||
|
|
8993f4e6b4 | ||
|
|
7adad0ee49 | ||
|
|
dd8815ec9d | ||
|
|
59e62a1f44 | ||
|
|
f5f84fe825 | ||
|
|
90c2fdd565 | ||
|
|
f6d69231e8 | ||
|
|
5cc0e21bc7 | ||
|
|
703b592793 | ||
|
|
75c9430d91 | ||
|
|
e5bba00deb | ||
|
|
8d90f13e97 | ||
|
|
666e33e70b | ||
|
|
7eaaa4e426 | ||
|
|
166ad942ef | ||
|
|
0ff08bbc09 | ||
|
|
6e2bcabbc9 | ||
|
|
afa191ae41 | ||
|
|
93da52c4d2 | ||
|
|
0cc0979674 | ||
|
|
629f1e94f1 | ||
|
|
8c28f346c7 | ||
|
|
3cf36e2f94 | ||
|
|
1ac07c96b1 | ||
|
|
91228c82e6 | ||
|
|
28d16728d3 | ||
|
|
f24a182ba2 | ||
|
|
0065fe1516 | ||
|
|
148fa698cc | ||
|
|
b25506b045 | ||
|
|
0c737fc4df | ||
|
|
a8b8507ffc |
33
CODEOWNERS
33
CODEOWNERS
@@ -66,7 +66,7 @@ esphome/components/binary_sensor/* @esphome/core
|
||||
esphome/components/bk72xx/* @kuba2k2
|
||||
esphome/components/bl0906/* @athom-tech @jesserockz @tarontop
|
||||
esphome/components/bl0939/* @ziceva
|
||||
esphome/components/bl0940/* @tobias-
|
||||
esphome/components/bl0940/* @dan-s-github @tobias-
|
||||
esphome/components/bl0942/* @dbuezas @dwmw2
|
||||
esphome/components/ble_client/* @buxtronix @clydebarrow
|
||||
esphome/components/bluetooth_proxy/* @bdraco @jesserockz
|
||||
@@ -88,7 +88,7 @@ esphome/components/bp1658cj/* @Cossid
|
||||
esphome/components/bp5758d/* @Cossid
|
||||
esphome/components/button/* @esphome/core
|
||||
esphome/components/bytebuffer/* @clydebarrow
|
||||
esphome/components/camera/* @DT-art1 @bdraco
|
||||
esphome/components/camera/* @bdraco @DT-art1
|
||||
esphome/components/camera_encoder/* @DT-art1
|
||||
esphome/components/canbus/* @danielschramm @mvturnho
|
||||
esphome/components/cap1188/* @mreditor97
|
||||
@@ -145,9 +145,9 @@ esphome/components/es8156/* @kbx81
|
||||
esphome/components/es8311/* @kahrendt @kroimon
|
||||
esphome/components/es8388/* @P4uLT
|
||||
esphome/components/esp32/* @esphome/core
|
||||
esphome/components/esp32_ble/* @Rapsssito @bdraco @jesserockz
|
||||
esphome/components/esp32_ble/* @bdraco @jesserockz @Rapsssito
|
||||
esphome/components/esp32_ble_client/* @bdraco @jesserockz
|
||||
esphome/components/esp32_ble_server/* @Rapsssito @clydebarrow @jesserockz
|
||||
esphome/components/esp32_ble_server/* @clydebarrow @jesserockz @Rapsssito
|
||||
esphome/components/esp32_ble_tracker/* @bdraco
|
||||
esphome/components/esp32_camera_web_server/* @ayufan
|
||||
esphome/components/esp32_can/* @Sympatron
|
||||
@@ -167,7 +167,7 @@ esphome/components/ezo_pmp/* @carlos-sarmiento
|
||||
esphome/components/factory_reset/* @anatoly-savchenkov
|
||||
esphome/components/fastled_base/* @OttoWinter
|
||||
esphome/components/feedback/* @ianchi
|
||||
esphome/components/fingerprint_grow/* @OnFreund @alexborro @loongyh
|
||||
esphome/components/fingerprint_grow/* @alexborro @loongyh @OnFreund
|
||||
esphome/components/font/* @clydebarrow @esphome/core
|
||||
esphome/components/fs3000/* @kahrendt
|
||||
esphome/components/ft5x06/* @clydebarrow
|
||||
@@ -203,7 +203,7 @@ esphome/components/heatpumpir/* @rob-deutsch
|
||||
esphome/components/hitachi_ac424/* @sourabhjaiswal
|
||||
esphome/components/hm3301/* @freekode
|
||||
esphome/components/hmac_md5/* @dwmw2
|
||||
esphome/components/homeassistant/* @OttoWinter @esphome/core
|
||||
esphome/components/homeassistant/* @esphome/core @OttoWinter
|
||||
esphome/components/homeassistant/number/* @landonr
|
||||
esphome/components/homeassistant/switch/* @Links2004
|
||||
esphome/components/honeywell_hih_i2c/* @Benichou34
|
||||
@@ -228,13 +228,13 @@ esphome/components/iaqcore/* @yozik04
|
||||
esphome/components/ili9xxx/* @clydebarrow @nielsnl68
|
||||
esphome/components/improv_base/* @esphome/core
|
||||
esphome/components/improv_serial/* @esphome/core
|
||||
esphome/components/ina226/* @Sergio303 @latonita
|
||||
esphome/components/ina226/* @latonita @Sergio303
|
||||
esphome/components/ina260/* @mreditor97
|
||||
esphome/components/ina2xx_base/* @latonita
|
||||
esphome/components/ina2xx_i2c/* @latonita
|
||||
esphome/components/ina2xx_spi/* @latonita
|
||||
esphome/components/inkbird_ibsth1_mini/* @fkirill
|
||||
esphome/components/inkplate6/* @jesserockz
|
||||
esphome/components/inkplate/* @jesserockz @JosipKuci
|
||||
esphome/components/integration/* @OttoWinter
|
||||
esphome/components/internal_temperature/* @Mat931
|
||||
esphome/components/interval/* @esphome/core
|
||||
@@ -277,8 +277,8 @@ esphome/components/max7219digit/* @rspaargaren
|
||||
esphome/components/max9611/* @mckaymatthew
|
||||
esphome/components/mcp23008/* @jesserockz
|
||||
esphome/components/mcp23017/* @jesserockz
|
||||
esphome/components/mcp23s08/* @SenexCrenshaw @jesserockz
|
||||
esphome/components/mcp23s17/* @SenexCrenshaw @jesserockz
|
||||
esphome/components/mcp23s08/* @jesserockz @SenexCrenshaw
|
||||
esphome/components/mcp23s17/* @jesserockz @SenexCrenshaw
|
||||
esphome/components/mcp23x08_base/* @jesserockz
|
||||
esphome/components/mcp23x17_base/* @jesserockz
|
||||
esphome/components/mcp23xxx_base/* @jesserockz
|
||||
@@ -299,6 +299,7 @@ esphome/components/mics_4514/* @jesserockz
|
||||
esphome/components/midea/* @dudanov
|
||||
esphome/components/midea_ir/* @dudanov
|
||||
esphome/components/mipi_dsi/* @clydebarrow
|
||||
esphome/components/mipi_rgb/* @clydebarrow
|
||||
esphome/components/mipi_spi/* @clydebarrow
|
||||
esphome/components/mitsubishi/* @RubyBailey
|
||||
esphome/components/mixer/speaker/* @kahrendt
|
||||
@@ -342,7 +343,7 @@ esphome/components/ota/* @esphome/core
|
||||
esphome/components/output/* @esphome/core
|
||||
esphome/components/packet_transport/* @clydebarrow
|
||||
esphome/components/pca6416a/* @Mat931
|
||||
esphome/components/pca9554/* @clydebarrow @hwstar
|
||||
esphome/components/pca9554/* @bdraco @clydebarrow @hwstar
|
||||
esphome/components/pcf85063/* @brogon
|
||||
esphome/components/pcf8563/* @KoenBreeman
|
||||
esphome/components/pi4ioe5v6408/* @jesserockz
|
||||
@@ -353,9 +354,9 @@ esphome/components/pm2005/* @andrewjswan
|
||||
esphome/components/pmsa003i/* @sjtrny
|
||||
esphome/components/pmsx003/* @ximex
|
||||
esphome/components/pmwcs3/* @SeByDocKy
|
||||
esphome/components/pn532/* @OttoWinter @jesserockz
|
||||
esphome/components/pn532_i2c/* @OttoWinter @jesserockz
|
||||
esphome/components/pn532_spi/* @OttoWinter @jesserockz
|
||||
esphome/components/pn532/* @jesserockz @OttoWinter
|
||||
esphome/components/pn532_i2c/* @jesserockz @OttoWinter
|
||||
esphome/components/pn532_spi/* @jesserockz @OttoWinter
|
||||
esphome/components/pn7150/* @jesserockz @kbx81
|
||||
esphome/components/pn7150_i2c/* @jesserockz @kbx81
|
||||
esphome/components/pn7160/* @jesserockz @kbx81
|
||||
@@ -364,7 +365,7 @@ esphome/components/pn7160_spi/* @jesserockz @kbx81
|
||||
esphome/components/power_supply/* @esphome/core
|
||||
esphome/components/preferences/* @esphome/core
|
||||
esphome/components/psram/* @esphome/core
|
||||
esphome/components/pulse_meter/* @TrentHouliston @cstaahl @stevebaxter
|
||||
esphome/components/pulse_meter/* @cstaahl @stevebaxter @TrentHouliston
|
||||
esphome/components/pvvx_mithermometer/* @pasiz
|
||||
esphome/components/pylontech/* @functionpointer
|
||||
esphome/components/qmp6988/* @andrewpc
|
||||
@@ -405,7 +406,7 @@ esphome/components/sensirion_common/* @martgras
|
||||
esphome/components/sensor/* @esphome/core
|
||||
esphome/components/sfa30/* @ghsensdev
|
||||
esphome/components/sgp40/* @SenexCrenshaw
|
||||
esphome/components/sgp4x/* @SenexCrenshaw @martgras
|
||||
esphome/components/sgp4x/* @martgras @SenexCrenshaw
|
||||
esphome/components/shelly_dimmer/* @edge90 @rnauber
|
||||
esphome/components/sht3xd/* @mrtoy-me
|
||||
esphome/components/sht4x/* @sjtrny
|
||||
|
||||
2
Doxyfile
2
Doxyfile
@@ -48,7 +48,7 @@ PROJECT_NAME = ESPHome
|
||||
# could be handy for archiving the generated documentation or if some version
|
||||
# control system is used.
|
||||
|
||||
PROJECT_NUMBER = 2025.9.0-dev
|
||||
PROJECT_NUMBER = 2025.9.0b1
|
||||
|
||||
# Using the PROJECT_BRIEF tag one can provide an optional one line description
|
||||
# for a project that appears at the top of each page and should give viewer a
|
||||
|
||||
@@ -396,27 +396,29 @@ def check_permissions(port: str):
|
||||
)
|
||||
|
||||
|
||||
def upload_program(config: ConfigType, args: ArgsProtocol, host: str) -> int | str:
|
||||
def upload_program(
|
||||
config: ConfigType, args: ArgsProtocol, devices: list[str]
|
||||
) -> tuple[int, str | None]:
|
||||
host = devices[0]
|
||||
try:
|
||||
module = importlib.import_module("esphome.components." + CORE.target_platform)
|
||||
if getattr(module, "upload_program")(config, args, host):
|
||||
return 0
|
||||
return 0, host
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
if get_port_type(host) == "SERIAL":
|
||||
check_permissions(host)
|
||||
|
||||
exit_code = 1
|
||||
if CORE.target_platform in (PLATFORM_ESP32, PLATFORM_ESP8266):
|
||||
file = getattr(args, "file", None)
|
||||
return upload_using_esptool(config, host, file, args.upload_speed)
|
||||
exit_code = upload_using_esptool(config, host, file, args.upload_speed)
|
||||
elif CORE.target_platform == PLATFORM_RP2040 or CORE.is_libretiny:
|
||||
exit_code = upload_using_platformio(config, host)
|
||||
# else: Unknown target platform, exit_code remains 1
|
||||
|
||||
if CORE.target_platform in (PLATFORM_RP2040):
|
||||
return upload_using_platformio(config, host)
|
||||
|
||||
if CORE.is_libretiny:
|
||||
return upload_using_platformio(config, host)
|
||||
|
||||
return 1 # Unknown target platform
|
||||
return exit_code, host if exit_code == 0 else None
|
||||
|
||||
ota_conf = {}
|
||||
for ota_item in config.get(CONF_OTA, []):
|
||||
@@ -433,10 +435,10 @@ def upload_program(config: ConfigType, args: ArgsProtocol, host: str) -> int | s
|
||||
|
||||
remote_port = int(ota_conf[CONF_PORT])
|
||||
password = ota_conf.get(CONF_PASSWORD, "")
|
||||
binary = args.file if getattr(args, "file", None) is not None else CORE.firmware_bin
|
||||
|
||||
# Check if we should use MQTT for address resolution
|
||||
# This happens when no device was specified, or the current host is "MQTT"/"OTA"
|
||||
devices: list[str] = args.device or []
|
||||
if (
|
||||
CONF_MQTT in config # pylint: disable=too-many-boolean-expressions
|
||||
and (not devices or host in ("MQTT", "OTA"))
|
||||
@@ -447,17 +449,23 @@ def upload_program(config: ConfigType, args: ArgsProtocol, host: str) -> int | s
|
||||
):
|
||||
from esphome import mqtt
|
||||
|
||||
host = mqtt.get_esphome_device_ip(
|
||||
config, args.username, args.password, args.client_id
|
||||
)
|
||||
devices = [
|
||||
mqtt.get_esphome_device_ip(
|
||||
config, args.username, args.password, args.client_id
|
||||
)
|
||||
]
|
||||
|
||||
if getattr(args, "file", None) is not None:
|
||||
return espota2.run_ota(host, remote_port, password, args.file)
|
||||
|
||||
return espota2.run_ota(host, remote_port, password, CORE.firmware_bin)
|
||||
return espota2.run_ota(devices, remote_port, password, binary)
|
||||
|
||||
|
||||
def show_logs(config: ConfigType, args: ArgsProtocol, devices: list[str]) -> int | None:
|
||||
try:
|
||||
module = importlib.import_module("esphome.components." + CORE.target_platform)
|
||||
if getattr(module, "show_logs")(config, args, devices):
|
||||
return 0
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
if "logger" not in config:
|
||||
raise EsphomeError("Logger is not configured!")
|
||||
|
||||
@@ -551,17 +559,11 @@ def command_upload(args: ArgsProtocol, config: ConfigType) -> int | None:
|
||||
purpose="uploading",
|
||||
)
|
||||
|
||||
# Try each device until one succeeds
|
||||
exit_code = 1
|
||||
for device in devices:
|
||||
_LOGGER.info("Uploading to %s", device)
|
||||
exit_code = upload_program(config, args, device)
|
||||
if exit_code == 0:
|
||||
_LOGGER.info("Successfully uploaded program.")
|
||||
return 0
|
||||
if len(devices) > 1:
|
||||
_LOGGER.warning("Failed to upload to %s", device)
|
||||
|
||||
exit_code, _ = upload_program(config, args, devices)
|
||||
if exit_code == 0:
|
||||
_LOGGER.info("Successfully uploaded program.")
|
||||
else:
|
||||
_LOGGER.warning("Failed to upload to %s", devices)
|
||||
return exit_code
|
||||
|
||||
|
||||
@@ -614,19 +616,11 @@ def command_run(args: ArgsProtocol, config: ConfigType) -> int | None:
|
||||
purpose="uploading",
|
||||
)
|
||||
|
||||
# Try each device for upload until one succeeds
|
||||
successful_device: str | None = None
|
||||
for device in devices:
|
||||
_LOGGER.info("Uploading to %s", device)
|
||||
exit_code = upload_program(config, args, device)
|
||||
if exit_code == 0:
|
||||
_LOGGER.info("Successfully uploaded program.")
|
||||
successful_device = device
|
||||
break
|
||||
if len(devices) > 1:
|
||||
_LOGGER.warning("Failed to upload to %s", device)
|
||||
|
||||
if successful_device is None:
|
||||
exit_code, successful_device = upload_program(config, args, devices)
|
||||
if exit_code == 0:
|
||||
_LOGGER.info("Successfully uploaded program.")
|
||||
else:
|
||||
_LOGGER.warning("Failed to upload to %s", devices)
|
||||
return exit_code
|
||||
|
||||
if args.no_logs:
|
||||
|
||||
@@ -241,6 +241,8 @@ float ADCSensor::sample_autorange_() {
|
||||
cali_config.bitwidth = ADC_BITWIDTH_DEFAULT;
|
||||
|
||||
err = adc_cali_create_scheme_curve_fitting(&cali_config, &handle);
|
||||
ESP_LOGVV(TAG, "Autorange atten=%d: Calibration handle creation %s (err=%d)", atten,
|
||||
(err == ESP_OK) ? "SUCCESS" : "FAILED", err);
|
||||
#else
|
||||
adc_cali_line_fitting_config_t cali_config = {
|
||||
.unit_id = this->adc_unit_,
|
||||
@@ -251,10 +253,14 @@ float ADCSensor::sample_autorange_() {
|
||||
#endif
|
||||
};
|
||||
err = adc_cali_create_scheme_line_fitting(&cali_config, &handle);
|
||||
ESP_LOGVV(TAG, "Autorange atten=%d: Calibration handle creation %s (err=%d)", atten,
|
||||
(err == ESP_OK) ? "SUCCESS" : "FAILED", err);
|
||||
#endif
|
||||
|
||||
int raw;
|
||||
err = adc_oneshot_read(this->adc_handle_, this->channel_, &raw);
|
||||
ESP_LOGVV(TAG, "Autorange atten=%d: Raw ADC read %s, value=%d (err=%d)", atten,
|
||||
(err == ESP_OK) ? "SUCCESS" : "FAILED", raw, err);
|
||||
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGW(TAG, "ADC read failed in autorange with error %d", err);
|
||||
@@ -275,8 +281,10 @@ float ADCSensor::sample_autorange_() {
|
||||
err = adc_cali_raw_to_voltage(handle, raw, &voltage_mv);
|
||||
if (err == ESP_OK) {
|
||||
voltage = voltage_mv / 1000.0f;
|
||||
ESP_LOGVV(TAG, "Autorange atten=%d: CALIBRATED - raw=%d -> %dmV -> %.6fV", atten, raw, voltage_mv, voltage);
|
||||
} else {
|
||||
voltage = raw * 3.3f / 4095.0f;
|
||||
ESP_LOGVV(TAG, "Autorange atten=%d: UNCALIBRATED FALLBACK - raw=%d -> %.6fV (3.3V ref)", atten, raw, voltage);
|
||||
}
|
||||
// Clean up calibration handle
|
||||
#if USE_ESP32_VARIANT_ESP32C3 || USE_ESP32_VARIANT_ESP32C5 || USE_ESP32_VARIANT_ESP32C6 || \
|
||||
@@ -287,6 +295,7 @@ float ADCSensor::sample_autorange_() {
|
||||
#endif
|
||||
} else {
|
||||
voltage = raw * 3.3f / 4095.0f;
|
||||
ESP_LOGVV(TAG, "Autorange atten=%d: NO CALIBRATION - raw=%d -> %.6fV (3.3V ref)", atten, raw, voltage);
|
||||
}
|
||||
|
||||
return {raw, voltage};
|
||||
@@ -324,18 +333,32 @@ float ADCSensor::sample_autorange_() {
|
||||
}
|
||||
|
||||
const int adc_half = 2048;
|
||||
uint32_t c12 = std::min(raw12, adc_half);
|
||||
uint32_t c6 = adc_half - std::abs(raw6 - adc_half);
|
||||
uint32_t c2 = adc_half - std::abs(raw2 - adc_half);
|
||||
uint32_t c0 = std::min(4095 - raw0, adc_half);
|
||||
uint32_t csum = c12 + c6 + c2 + c0;
|
||||
const uint32_t c12 = std::min(raw12, adc_half);
|
||||
|
||||
const int32_t c6_signed = adc_half - std::abs(raw6 - adc_half);
|
||||
const uint32_t c6 = (c6_signed > 0) ? c6_signed : 0; // Clamp to prevent underflow
|
||||
|
||||
const int32_t c2_signed = adc_half - std::abs(raw2 - adc_half);
|
||||
const uint32_t c2 = (c2_signed > 0) ? c2_signed : 0; // Clamp to prevent underflow
|
||||
|
||||
const uint32_t c0 = std::min(4095 - raw0, adc_half);
|
||||
const uint32_t csum = c12 + c6 + c2 + c0;
|
||||
|
||||
ESP_LOGVV(TAG, "Autorange summary:");
|
||||
ESP_LOGVV(TAG, " Raw readings: 12db=%d, 6db=%d, 2.5db=%d, 0db=%d", raw12, raw6, raw2, raw0);
|
||||
ESP_LOGVV(TAG, " Voltages: 12db=%.6f, 6db=%.6f, 2.5db=%.6f, 0db=%.6f", mv12, mv6, mv2, mv0);
|
||||
ESP_LOGVV(TAG, " Coefficients: c12=%u, c6=%u, c2=%u, c0=%u, sum=%u", c12, c6, c2, c0, csum);
|
||||
|
||||
if (csum == 0) {
|
||||
ESP_LOGE(TAG, "Invalid weight sum in autorange calculation");
|
||||
return NAN;
|
||||
}
|
||||
|
||||
return (mv12 * c12 + mv6 * c6 + mv2 * c2 + mv0 * c0) / csum;
|
||||
const float final_result = (mv12 * c12 + mv6 * c6 + mv2 * c2 + mv0 * c0) / csum;
|
||||
ESP_LOGV(TAG, "Autorange final: (%.6f*%u + %.6f*%u + %.6f*%u + %.6f*%u)/%u = %.6fV", mv12, c12, mv6, c6, mv2, c2, mv0,
|
||||
c0, csum, final_result);
|
||||
|
||||
return final_result;
|
||||
}
|
||||
|
||||
} // namespace adc
|
||||
|
||||
@@ -818,6 +818,7 @@ message GetTimeResponse {
|
||||
option (no_delay) = true;
|
||||
|
||||
fixed32 epoch_seconds = 1;
|
||||
string timezone = 2;
|
||||
}
|
||||
|
||||
// ==================== USER-DEFINES SERVICES ====================
|
||||
|
||||
@@ -1070,8 +1070,14 @@ void APIConnection::camera_image(const CameraImageRequest &msg) {
|
||||
|
||||
#ifdef USE_HOMEASSISTANT_TIME
|
||||
void APIConnection::on_get_time_response(const GetTimeResponse &value) {
|
||||
if (homeassistant::global_homeassistant_time != nullptr)
|
||||
if (homeassistant::global_homeassistant_time != nullptr) {
|
||||
homeassistant::global_homeassistant_time->set_epoch_time(value.epoch_seconds);
|
||||
#ifdef USE_TIME_TIMEZONE
|
||||
if (!value.timezone.empty() && value.timezone != homeassistant::global_homeassistant_time->get_timezone()) {
|
||||
homeassistant::global_homeassistant_time->set_timezone(value.timezone);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -10,6 +10,10 @@
|
||||
#include <cstring>
|
||||
#include <cinttypes>
|
||||
|
||||
#ifdef USE_ESP8266
|
||||
#include <pgmspace.h>
|
||||
#endif
|
||||
|
||||
namespace esphome::api {
|
||||
|
||||
static const char *const TAG = "api.plaintext";
|
||||
@@ -197,11 +201,20 @@ APIError APIPlaintextFrameHelper::read_packet(ReadPacketBuffer *buffer) {
|
||||
// We must send at least 3 bytes to be read, so we add
|
||||
// a message after the indicator byte to ensures its long
|
||||
// enough and can aid in debugging.
|
||||
const char msg[] = "\x00"
|
||||
"Bad indicator byte";
|
||||
static constexpr uint8_t INDICATOR_MSG_SIZE = 19;
|
||||
#ifdef USE_ESP8266
|
||||
static const char MSG_PROGMEM[] PROGMEM = "\x00"
|
||||
"Bad indicator byte";
|
||||
char msg[INDICATOR_MSG_SIZE];
|
||||
memcpy_P(msg, MSG_PROGMEM, INDICATOR_MSG_SIZE);
|
||||
iov[0].iov_base = (void *) msg;
|
||||
iov[0].iov_len = 19;
|
||||
this->write_raw_(iov, 1, 19);
|
||||
#else
|
||||
static const char MSG[] = "\x00"
|
||||
"Bad indicator byte";
|
||||
iov[0].iov_base = (void *) MSG;
|
||||
#endif
|
||||
iov[0].iov_len = INDICATOR_MSG_SIZE;
|
||||
this->write_raw_(iov, 1, INDICATOR_MSG_SIZE);
|
||||
}
|
||||
return aerr;
|
||||
}
|
||||
|
||||
@@ -901,6 +901,16 @@ bool HomeAssistantStateResponse::decode_length(uint32_t field_id, ProtoLengthDel
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
bool GetTimeResponse::decode_length(uint32_t field_id, ProtoLengthDelimited value) {
|
||||
switch (field_id) {
|
||||
case 2:
|
||||
this->timezone = value.as_string();
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool GetTimeResponse::decode_32bit(uint32_t field_id, Proto32Bit value) {
|
||||
switch (field_id) {
|
||||
case 1:
|
||||
@@ -911,8 +921,14 @@ bool GetTimeResponse::decode_32bit(uint32_t field_id, Proto32Bit value) {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
void GetTimeResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_fixed32(1, this->epoch_seconds); }
|
||||
void GetTimeResponse::calculate_size(ProtoSize &size) const { size.add_fixed32(1, this->epoch_seconds); }
|
||||
void GetTimeResponse::encode(ProtoWriteBuffer buffer) const {
|
||||
buffer.encode_fixed32(1, this->epoch_seconds);
|
||||
buffer.encode_string(2, this->timezone_ref_);
|
||||
}
|
||||
void GetTimeResponse::calculate_size(ProtoSize &size) const {
|
||||
size.add_fixed32(1, this->epoch_seconds);
|
||||
size.add_length(1, this->timezone_ref_.size());
|
||||
}
|
||||
#ifdef USE_API_SERVICES
|
||||
void ListEntitiesServicesArgument::encode(ProtoWriteBuffer buffer) const {
|
||||
buffer.encode_string(1, this->name_ref_);
|
||||
|
||||
@@ -1174,11 +1174,14 @@ class GetTimeRequest final : public ProtoMessage {
|
||||
class GetTimeResponse final : public ProtoDecodableMessage {
|
||||
public:
|
||||
static constexpr uint8_t MESSAGE_TYPE = 37;
|
||||
static constexpr uint8_t ESTIMATED_SIZE = 5;
|
||||
static constexpr uint8_t ESTIMATED_SIZE = 14;
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
const char *message_name() const override { return "get_time_response"; }
|
||||
#endif
|
||||
uint32_t epoch_seconds{0};
|
||||
std::string timezone{};
|
||||
StringRef timezone_ref_{};
|
||||
void set_timezone(const StringRef &ref) { this->timezone_ref_ = ref; }
|
||||
void encode(ProtoWriteBuffer buffer) const override;
|
||||
void calculate_size(ProtoSize &size) const override;
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
@@ -1187,6 +1190,7 @@ class GetTimeResponse final : public ProtoDecodableMessage {
|
||||
|
||||
protected:
|
||||
bool decode_32bit(uint32_t field_id, Proto32Bit value) override;
|
||||
bool decode_length(uint32_t field_id, ProtoLengthDelimited value) override;
|
||||
};
|
||||
#ifdef USE_API_SERVICES
|
||||
class ListEntitiesServicesArgument final : public ProtoMessage {
|
||||
|
||||
@@ -1110,7 +1110,17 @@ void HomeAssistantStateResponse::dump_to(std::string &out) const {
|
||||
}
|
||||
#endif
|
||||
void GetTimeRequest::dump_to(std::string &out) const { out.append("GetTimeRequest {}"); }
|
||||
void GetTimeResponse::dump_to(std::string &out) const { dump_field(out, "epoch_seconds", this->epoch_seconds); }
|
||||
void GetTimeResponse::dump_to(std::string &out) const {
|
||||
MessageDumpHelper helper(out, "GetTimeResponse");
|
||||
dump_field(out, "epoch_seconds", this->epoch_seconds);
|
||||
out.append(" timezone: ");
|
||||
if (!this->timezone_ref_.empty()) {
|
||||
out.append("'").append(this->timezone_ref_.c_str()).append("'");
|
||||
} else {
|
||||
out.append("'").append(this->timezone).append("'");
|
||||
}
|
||||
out.append("\n");
|
||||
}
|
||||
#ifdef USE_API_SERVICES
|
||||
void ListEntitiesServicesArgument::dump_to(std::string &out) const {
|
||||
MessageDumpHelper helper(out, "ListEntitiesServicesArgument");
|
||||
|
||||
@@ -16,6 +16,7 @@ from esphome.const import (
|
||||
DEVICE_CLASS_ENERGY,
|
||||
DEVICE_CLASS_POWER,
|
||||
DEVICE_CLASS_POWER_FACTOR,
|
||||
DEVICE_CLASS_REACTIVE_POWER,
|
||||
DEVICE_CLASS_VOLTAGE,
|
||||
ICON_CURRENT_AC,
|
||||
ICON_LIGHTBULB,
|
||||
@@ -78,6 +79,7 @@ CONFIG_SCHEMA = (
|
||||
unit_of_measurement=UNIT_VOLT_AMPS_REACTIVE,
|
||||
icon=ICON_LIGHTBULB,
|
||||
accuracy_decimals=2,
|
||||
device_class=DEVICE_CLASS_REACTIVE_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional(CONF_POWER_FACTOR): sensor.sensor_schema(
|
||||
|
||||
@@ -17,10 +17,12 @@ from esphome.const import (
|
||||
CONF_REACTIVE_POWER,
|
||||
CONF_REVERSE_ACTIVE_ENERGY,
|
||||
CONF_VOLTAGE,
|
||||
DEVICE_CLASS_APPARENT_POWER,
|
||||
DEVICE_CLASS_CURRENT,
|
||||
DEVICE_CLASS_ENERGY,
|
||||
DEVICE_CLASS_POWER,
|
||||
DEVICE_CLASS_POWER_FACTOR,
|
||||
DEVICE_CLASS_REACTIVE_POWER,
|
||||
DEVICE_CLASS_TEMPERATURE,
|
||||
DEVICE_CLASS_VOLTAGE,
|
||||
ENTITY_CATEGORY_DIAGNOSTIC,
|
||||
@@ -100,13 +102,13 @@ ATM90E32_PHASE_SCHEMA = cv.Schema(
|
||||
unit_of_measurement=UNIT_VOLT_AMPS_REACTIVE,
|
||||
icon=ICON_LIGHTBULB,
|
||||
accuracy_decimals=2,
|
||||
device_class=DEVICE_CLASS_POWER,
|
||||
device_class=DEVICE_CLASS_REACTIVE_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional(CONF_APPARENT_POWER): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_VOLT_AMPS,
|
||||
accuracy_decimals=2,
|
||||
device_class=DEVICE_CLASS_POWER,
|
||||
device_class=DEVICE_CLASS_APPARENT_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional(CONF_POWER_FACTOR): sensor.sensor_schema(
|
||||
|
||||
@@ -493,7 +493,7 @@ void BedJetHub::dump_config() {
|
||||
" ble_client.app_id: %d\n"
|
||||
" ble_client.conn_id: %d",
|
||||
this->get_name().c_str(), this->parent()->app_id, this->parent()->get_conn_id());
|
||||
LOG_UPDATE_INTERVAL(this)
|
||||
LOG_UPDATE_INTERVAL(this);
|
||||
ESP_LOGCONFIG(TAG, " Child components (%d):", this->children_.size());
|
||||
for (auto *child : this->children_) {
|
||||
ESP_LOGCONFIG(TAG, " - %s", child->describe().c_str());
|
||||
|
||||
@@ -1 +1,6 @@
|
||||
CODEOWNERS = ["@tobias-"]
|
||||
import esphome.codegen as cg
|
||||
|
||||
CODEOWNERS = ["@tobias-", "@dan-s-github"]
|
||||
|
||||
CONF_BL0940_ID = "bl0940_id"
|
||||
bl0940_ns = cg.esphome_ns.namespace("bl0940")
|
||||
|
||||
@@ -7,28 +7,26 @@ namespace bl0940 {
|
||||
|
||||
static const char *const TAG = "bl0940";
|
||||
|
||||
static const uint8_t BL0940_READ_COMMAND = 0x50; // 0x58 according to documentation
|
||||
static const uint8_t BL0940_FULL_PACKET = 0xAA;
|
||||
static const uint8_t BL0940_PACKET_HEADER = 0x55; // 0x58 according to documentation
|
||||
static const uint8_t BL0940_PACKET_HEADER = 0x55; // 0x58 according to en doc but 0x55 in cn doc
|
||||
|
||||
static const uint8_t BL0940_WRITE_COMMAND = 0xA0; // 0xA8 according to documentation
|
||||
static const uint8_t BL0940_REG_I_FAST_RMS_CTRL = 0x10;
|
||||
static const uint8_t BL0940_REG_MODE = 0x18;
|
||||
static const uint8_t BL0940_REG_SOFT_RESET = 0x19;
|
||||
static const uint8_t BL0940_REG_USR_WRPROT = 0x1A;
|
||||
static const uint8_t BL0940_REG_TPS_CTRL = 0x1B;
|
||||
|
||||
const uint8_t BL0940_INIT[5][6] = {
|
||||
static const uint8_t BL0940_INIT[5][5] = {
|
||||
// Reset to default
|
||||
{BL0940_WRITE_COMMAND, BL0940_REG_SOFT_RESET, 0x5A, 0x5A, 0x5A, 0x38},
|
||||
{BL0940_REG_SOFT_RESET, 0x5A, 0x5A, 0x5A, 0x38},
|
||||
// Enable User Operation Write
|
||||
{BL0940_WRITE_COMMAND, BL0940_REG_USR_WRPROT, 0x55, 0x00, 0x00, 0xF0},
|
||||
{BL0940_REG_USR_WRPROT, 0x55, 0x00, 0x00, 0xF0},
|
||||
// 0x0100 = CF_UNABLE energy pulse, AC_FREQ_SEL 50Hz, RMS_UPDATE_SEL 800mS
|
||||
{BL0940_WRITE_COMMAND, BL0940_REG_MODE, 0x00, 0x10, 0x00, 0x37},
|
||||
{BL0940_REG_MODE, 0x00, 0x10, 0x00, 0x37},
|
||||
// 0x47FF = Over-current and leakage alarm on, Automatic temperature measurement, Interval 100mS
|
||||
{BL0940_WRITE_COMMAND, BL0940_REG_TPS_CTRL, 0xFF, 0x47, 0x00, 0xFE},
|
||||
{BL0940_REG_TPS_CTRL, 0xFF, 0x47, 0x00, 0xFE},
|
||||
// 0x181C = Half cycle, Fast RMS threshold 6172
|
||||
{BL0940_WRITE_COMMAND, BL0940_REG_I_FAST_RMS_CTRL, 0x1C, 0x18, 0x00, 0x1B}};
|
||||
{BL0940_REG_I_FAST_RMS_CTRL, 0x1C, 0x18, 0x00, 0x1B}};
|
||||
|
||||
void BL0940::loop() {
|
||||
DataPacket buffer;
|
||||
@@ -36,8 +34,8 @@ void BL0940::loop() {
|
||||
return;
|
||||
}
|
||||
if (read_array((uint8_t *) &buffer, sizeof(buffer))) {
|
||||
if (validate_checksum(&buffer)) {
|
||||
received_package_(&buffer);
|
||||
if (this->validate_checksum_(&buffer)) {
|
||||
this->received_package_(&buffer);
|
||||
}
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Junk on wire. Throwing away partial message");
|
||||
@@ -46,35 +44,151 @@ void BL0940::loop() {
|
||||
}
|
||||
}
|
||||
|
||||
bool BL0940::validate_checksum(const DataPacket *data) {
|
||||
uint8_t checksum = BL0940_READ_COMMAND;
|
||||
bool BL0940::validate_checksum_(DataPacket *data) {
|
||||
uint8_t checksum = this->read_command_;
|
||||
// Whole package but checksum
|
||||
for (uint32_t i = 0; i < sizeof(data->raw) - 1; i++) {
|
||||
checksum += data->raw[i];
|
||||
uint8_t *raw = (uint8_t *) data;
|
||||
for (uint32_t i = 0; i < sizeof(*data) - 1; i++) {
|
||||
checksum += raw[i];
|
||||
}
|
||||
checksum ^= 0xFF;
|
||||
if (checksum != data->checksum) {
|
||||
ESP_LOGW(TAG, "BL0940 invalid checksum! 0x%02X != 0x%02X", checksum, data->checksum);
|
||||
ESP_LOGW(TAG, "Invalid checksum! 0x%02X != 0x%02X", checksum, data->checksum);
|
||||
}
|
||||
return checksum == data->checksum;
|
||||
}
|
||||
|
||||
void BL0940::update() {
|
||||
this->flush();
|
||||
this->write_byte(BL0940_READ_COMMAND);
|
||||
this->write_byte(this->read_command_);
|
||||
this->write_byte(BL0940_FULL_PACKET);
|
||||
}
|
||||
|
||||
void BL0940::setup() {
|
||||
#ifdef USE_NUMBER
|
||||
// add calibration callbacks
|
||||
if (this->voltage_calibration_number_ != nullptr) {
|
||||
this->voltage_calibration_number_->add_on_state_callback(
|
||||
[this](float state) { this->voltage_calibration_callback_(state); });
|
||||
if (this->voltage_calibration_number_->has_state()) {
|
||||
this->voltage_calibration_callback_(this->voltage_calibration_number_->state);
|
||||
}
|
||||
}
|
||||
|
||||
if (this->current_calibration_number_ != nullptr) {
|
||||
this->current_calibration_number_->add_on_state_callback(
|
||||
[this](float state) { this->current_calibration_callback_(state); });
|
||||
if (this->current_calibration_number_->has_state()) {
|
||||
this->current_calibration_callback_(this->current_calibration_number_->state);
|
||||
}
|
||||
}
|
||||
|
||||
if (this->power_calibration_number_ != nullptr) {
|
||||
this->power_calibration_number_->add_on_state_callback(
|
||||
[this](float state) { this->power_calibration_callback_(state); });
|
||||
if (this->power_calibration_number_->has_state()) {
|
||||
this->power_calibration_callback_(this->power_calibration_number_->state);
|
||||
}
|
||||
}
|
||||
|
||||
if (this->energy_calibration_number_ != nullptr) {
|
||||
this->energy_calibration_number_->add_on_state_callback(
|
||||
[this](float state) { this->energy_calibration_callback_(state); });
|
||||
if (this->energy_calibration_number_->has_state()) {
|
||||
this->energy_calibration_callback_(this->energy_calibration_number_->state);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// calculate calibrated reference values
|
||||
this->voltage_reference_cal_ = this->voltage_reference_ / this->voltage_cal_;
|
||||
this->current_reference_cal_ = this->current_reference_ / this->current_cal_;
|
||||
this->power_reference_cal_ = this->power_reference_ / this->power_cal_;
|
||||
this->energy_reference_cal_ = this->energy_reference_ / this->energy_cal_;
|
||||
|
||||
for (auto *i : BL0940_INIT) {
|
||||
this->write_array(i, 6);
|
||||
this->write_byte(this->write_command_), this->write_array(i, 5);
|
||||
delay(1);
|
||||
}
|
||||
this->flush();
|
||||
}
|
||||
|
||||
float BL0940::update_temp_(sensor::Sensor *sensor, ube16_t temperature) const {
|
||||
auto tb = (float) (temperature.h << 8 | temperature.l);
|
||||
float BL0940::calculate_power_reference_() {
|
||||
// calculate power reference based on voltage and current reference
|
||||
return this->voltage_reference_cal_ * this->current_reference_cal_ * 4046 / 324004 / 79931;
|
||||
}
|
||||
|
||||
float BL0940::calculate_energy_reference_() {
|
||||
// formula: 3600000 * 4046 * RL * R1 * 1000 / (1638.4 * 256) / Vref² / (R1 + R2)
|
||||
// or: power_reference_ * 3600000 / (1638.4 * 256)
|
||||
return this->power_reference_cal_ * 3600000 / (1638.4 * 256);
|
||||
}
|
||||
|
||||
float BL0940::calculate_calibration_value_(float state) { return (100 + state) / 100; }
|
||||
|
||||
void BL0940::reset_calibration() {
|
||||
#ifdef USE_NUMBER
|
||||
if (this->current_calibration_number_ != nullptr && this->current_cal_ != 1) {
|
||||
this->current_calibration_number_->make_call().set_value(0).perform();
|
||||
}
|
||||
if (this->voltage_calibration_number_ != nullptr && this->voltage_cal_ != 1) {
|
||||
this->voltage_calibration_number_->make_call().set_value(0).perform();
|
||||
}
|
||||
if (this->power_calibration_number_ != nullptr && this->power_cal_ != 1) {
|
||||
this->power_calibration_number_->make_call().set_value(0).perform();
|
||||
}
|
||||
if (this->energy_calibration_number_ != nullptr && this->energy_cal_ != 1) {
|
||||
this->energy_calibration_number_->make_call().set_value(0).perform();
|
||||
}
|
||||
#endif
|
||||
ESP_LOGD(TAG, "external calibration values restored to initial state");
|
||||
}
|
||||
|
||||
void BL0940::current_calibration_callback_(float state) {
|
||||
this->current_cal_ = this->calculate_calibration_value_(state);
|
||||
ESP_LOGV(TAG, "update current calibration state: %f", this->current_cal_);
|
||||
this->recalibrate_();
|
||||
}
|
||||
void BL0940::voltage_calibration_callback_(float state) {
|
||||
this->voltage_cal_ = this->calculate_calibration_value_(state);
|
||||
ESP_LOGV(TAG, "update voltage calibration state: %f", this->voltage_cal_);
|
||||
this->recalibrate_();
|
||||
}
|
||||
void BL0940::power_calibration_callback_(float state) {
|
||||
this->power_cal_ = this->calculate_calibration_value_(state);
|
||||
ESP_LOGV(TAG, "update power calibration state: %f", this->power_cal_);
|
||||
this->recalibrate_();
|
||||
}
|
||||
void BL0940::energy_calibration_callback_(float state) {
|
||||
this->energy_cal_ = this->calculate_calibration_value_(state);
|
||||
ESP_LOGV(TAG, "update energy calibration state: %f", this->energy_cal_);
|
||||
this->recalibrate_();
|
||||
}
|
||||
|
||||
void BL0940::recalibrate_() {
|
||||
ESP_LOGV(TAG, "Recalibrating reference values");
|
||||
this->voltage_reference_cal_ = this->voltage_reference_ / this->voltage_cal_;
|
||||
this->current_reference_cal_ = this->current_reference_ / this->current_cal_;
|
||||
|
||||
if (this->voltage_cal_ != 1 || this->current_cal_ != 1) {
|
||||
this->power_reference_ = this->calculate_power_reference_();
|
||||
}
|
||||
this->power_reference_cal_ = this->power_reference_ / this->power_cal_;
|
||||
|
||||
if (this->voltage_cal_ != 1 || this->current_cal_ != 1 || this->power_cal_ != 1) {
|
||||
this->energy_reference_ = this->calculate_energy_reference_();
|
||||
}
|
||||
this->energy_reference_cal_ = this->energy_reference_ / this->energy_cal_;
|
||||
|
||||
ESP_LOGD(TAG,
|
||||
"Recalibrated reference values:\n"
|
||||
"Voltage: %f\n, Current: %f\n, Power: %f\n, Energy: %f\n",
|
||||
this->voltage_reference_cal_, this->current_reference_cal_, this->power_reference_cal_,
|
||||
this->energy_reference_cal_);
|
||||
}
|
||||
|
||||
float BL0940::update_temp_(sensor::Sensor *sensor, uint16_le_t temperature) const {
|
||||
auto tb = (float) temperature;
|
||||
float converted_temp = ((float) 170 / 448) * (tb / 2 - 32) - 45;
|
||||
if (sensor != nullptr) {
|
||||
if (sensor->has_state() && std::abs(converted_temp - sensor->get_state()) > max_temperature_diff_) {
|
||||
@@ -87,33 +201,40 @@ float BL0940::update_temp_(sensor::Sensor *sensor, ube16_t temperature) const {
|
||||
return converted_temp;
|
||||
}
|
||||
|
||||
void BL0940::received_package_(const DataPacket *data) const {
|
||||
void BL0940::received_package_(DataPacket *data) {
|
||||
// Bad header
|
||||
if (data->frame_header != BL0940_PACKET_HEADER) {
|
||||
ESP_LOGI(TAG, "Invalid data. Header mismatch: %d", data->frame_header);
|
||||
return;
|
||||
}
|
||||
|
||||
float v_rms = (float) to_uint32_t(data->v_rms) / voltage_reference_;
|
||||
float i_rms = (float) to_uint32_t(data->i_rms) / current_reference_;
|
||||
float watt = (float) to_int32_t(data->watt) / power_reference_;
|
||||
uint32_t cf_cnt = to_uint32_t(data->cf_cnt);
|
||||
float total_energy_consumption = (float) cf_cnt / energy_reference_;
|
||||
// cf_cnt is only 24 bits, so track overflows
|
||||
uint32_t cf_cnt = (uint24_t) data->cf_cnt;
|
||||
cf_cnt |= this->prev_cf_cnt_ & 0xff000000;
|
||||
if (cf_cnt < this->prev_cf_cnt_) {
|
||||
cf_cnt += 0x1000000;
|
||||
}
|
||||
this->prev_cf_cnt_ = cf_cnt;
|
||||
|
||||
float tps1 = update_temp_(internal_temperature_sensor_, data->tps1);
|
||||
float tps2 = update_temp_(external_temperature_sensor_, data->tps2);
|
||||
float v_rms = (uint24_t) data->v_rms / this->voltage_reference_cal_;
|
||||
float i_rms = (uint24_t) data->i_rms / this->current_reference_cal_;
|
||||
float watt = (int24_t) data->watt / this->power_reference_cal_;
|
||||
float total_energy_consumption = cf_cnt / this->energy_reference_cal_;
|
||||
|
||||
if (voltage_sensor_ != nullptr) {
|
||||
voltage_sensor_->publish_state(v_rms);
|
||||
float tps1 = update_temp_(this->internal_temperature_sensor_, data->tps1);
|
||||
float tps2 = update_temp_(this->external_temperature_sensor_, data->tps2);
|
||||
|
||||
if (this->voltage_sensor_ != nullptr) {
|
||||
this->voltage_sensor_->publish_state(v_rms);
|
||||
}
|
||||
if (current_sensor_ != nullptr) {
|
||||
current_sensor_->publish_state(i_rms);
|
||||
if (this->current_sensor_ != nullptr) {
|
||||
this->current_sensor_->publish_state(i_rms);
|
||||
}
|
||||
if (power_sensor_ != nullptr) {
|
||||
power_sensor_->publish_state(watt);
|
||||
if (this->power_sensor_ != nullptr) {
|
||||
this->power_sensor_->publish_state(watt);
|
||||
}
|
||||
if (energy_sensor_ != nullptr) {
|
||||
energy_sensor_->publish_state(total_energy_consumption);
|
||||
if (this->energy_sensor_ != nullptr) {
|
||||
this->energy_sensor_->publish_state(total_energy_consumption);
|
||||
}
|
||||
|
||||
ESP_LOGV(TAG, "BL0940: U %fV, I %fA, P %fW, Cnt %" PRId32 ", ∫P %fkWh, T1 %f°C, T2 %f°C", v_rms, i_rms, watt, cf_cnt,
|
||||
@@ -121,7 +242,27 @@ void BL0940::received_package_(const DataPacket *data) const {
|
||||
}
|
||||
|
||||
void BL0940::dump_config() { // NOLINT(readability-function-cognitive-complexity)
|
||||
ESP_LOGCONFIG(TAG, "BL0940:");
|
||||
ESP_LOGCONFIG(TAG,
|
||||
"BL0940:\n"
|
||||
" LEGACY MODE: %s\n"
|
||||
" READ CMD: 0x%02X\n"
|
||||
" WRITE CMD: 0x%02X\n"
|
||||
" ------------------\n"
|
||||
" Current reference: %f\n"
|
||||
" Energy reference: %f\n"
|
||||
" Power reference: %f\n"
|
||||
" Voltage reference: %f\n",
|
||||
TRUEFALSE(this->legacy_mode_enabled_), this->read_command_, this->write_command_,
|
||||
this->current_reference_, this->energy_reference_, this->power_reference_, this->voltage_reference_);
|
||||
#ifdef USE_NUMBER
|
||||
ESP_LOGCONFIG(TAG,
|
||||
"BL0940:\n"
|
||||
" Current calibration: %f\n"
|
||||
" Energy calibration: %f\n"
|
||||
" Power calibration: %f\n"
|
||||
" Voltage calibration: %f\n",
|
||||
this->current_cal_, this->energy_cal_, this->power_cal_, this->voltage_cal_);
|
||||
#endif
|
||||
LOG_SENSOR("", "Voltage", this->voltage_sensor_);
|
||||
LOG_SENSOR("", "Current", this->current_sensor_);
|
||||
LOG_SENSOR("", "Power", this->power_sensor_);
|
||||
@@ -130,9 +271,5 @@ void BL0940::dump_config() { // NOLINT(readability-function-cognitive-complexit
|
||||
LOG_SENSOR("", "External temperature", this->external_temperature_sensor_);
|
||||
}
|
||||
|
||||
uint32_t BL0940::to_uint32_t(ube24_t input) { return input.h << 16 | input.m << 8 | input.l; }
|
||||
|
||||
int32_t BL0940::to_int32_t(sbe24_t input) { return input.h << 16 | input.m << 8 | input.l; }
|
||||
|
||||
} // namespace bl0940
|
||||
} // namespace esphome
|
||||
|
||||
@@ -1,66 +1,48 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/components/uart/uart.h"
|
||||
#include "esphome/core/datatypes.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#ifdef USE_BUTTON
|
||||
#include "esphome/components/button/button.h"
|
||||
#endif
|
||||
#ifdef USE_NUMBER
|
||||
#include "esphome/components/number/number.h"
|
||||
#endif
|
||||
#include "esphome/components/sensor/sensor.h"
|
||||
#include "esphome/components/uart/uart.h"
|
||||
|
||||
namespace esphome {
|
||||
namespace bl0940 {
|
||||
|
||||
static const float BL0940_PREF = 1430;
|
||||
static const float BL0940_UREF = 33000;
|
||||
static const float BL0940_IREF = 275000; // 2750 from tasmota. Seems to generate values 100 times too high
|
||||
|
||||
// Measured to 297J per click according to power consumption of 5 minutes
|
||||
// Converted to kWh (3.6MJ per kwH). Used to be 256 * 1638.4
|
||||
static const float BL0940_EREF = 3.6e6 / 297;
|
||||
|
||||
struct ube24_t { // NOLINT(readability-identifier-naming,altera-struct-pack-align)
|
||||
uint8_t l;
|
||||
uint8_t m;
|
||||
uint8_t h;
|
||||
} __attribute__((packed));
|
||||
|
||||
struct ube16_t { // NOLINT(readability-identifier-naming,altera-struct-pack-align)
|
||||
uint8_t l;
|
||||
uint8_t h;
|
||||
} __attribute__((packed));
|
||||
|
||||
struct sbe24_t { // NOLINT(readability-identifier-naming,altera-struct-pack-align)
|
||||
uint8_t l;
|
||||
uint8_t m;
|
||||
int8_t h;
|
||||
} __attribute__((packed));
|
||||
|
||||
// Caveat: All these values are big endian (low - middle - high)
|
||||
|
||||
union DataPacket { // NOLINT(altera-struct-pack-align)
|
||||
uint8_t raw[35];
|
||||
struct {
|
||||
uint8_t frame_header; // value of 0x58 according to docs. 0x55 according to Tasmota real world tests. Reality wins.
|
||||
ube24_t i_fast_rms; // 0x00
|
||||
ube24_t i_rms; // 0x04
|
||||
ube24_t RESERVED0; // reserved
|
||||
ube24_t v_rms; // 0x06
|
||||
ube24_t RESERVED1; // reserved
|
||||
sbe24_t watt; // 0x08
|
||||
ube24_t RESERVED2; // reserved
|
||||
ube24_t cf_cnt; // 0x0A
|
||||
ube24_t RESERVED3; // reserved
|
||||
ube16_t tps1; // 0x0c
|
||||
uint8_t RESERVED4; // value of 0x00
|
||||
ube16_t tps2; // 0x0c
|
||||
uint8_t RESERVED5; // value of 0x00
|
||||
uint8_t checksum; // checksum
|
||||
};
|
||||
struct DataPacket {
|
||||
uint8_t frame_header; // Packet header (0x58 in EN docs, 0x55 in CN docs and Tasmota tests)
|
||||
uint24_le_t i_fast_rms; // Fast RMS current
|
||||
uint24_le_t i_rms; // RMS current
|
||||
uint24_t RESERVED0; // Reserved
|
||||
uint24_le_t v_rms; // RMS voltage
|
||||
uint24_t RESERVED1; // Reserved
|
||||
int24_le_t watt; // Active power (can be negative for bidirectional measurement)
|
||||
uint24_t RESERVED2; // Reserved
|
||||
uint24_le_t cf_cnt; // Energy pulse count
|
||||
uint24_t RESERVED3; // Reserved
|
||||
uint16_le_t tps1; // Internal temperature sensor 1
|
||||
uint8_t RESERVED4; // Reserved (should be 0x00)
|
||||
uint16_le_t tps2; // Internal temperature sensor 2
|
||||
uint8_t RESERVED5; // Reserved (should be 0x00)
|
||||
uint8_t checksum; // Packet checksum
|
||||
} __attribute__((packed));
|
||||
|
||||
class BL0940 : public PollingComponent, public uart::UARTDevice {
|
||||
public:
|
||||
// Sensor setters
|
||||
void set_voltage_sensor(sensor::Sensor *voltage_sensor) { voltage_sensor_ = voltage_sensor; }
|
||||
void set_current_sensor(sensor::Sensor *current_sensor) { current_sensor_ = current_sensor; }
|
||||
void set_power_sensor(sensor::Sensor *power_sensor) { power_sensor_ = power_sensor; }
|
||||
void set_energy_sensor(sensor::Sensor *energy_sensor) { energy_sensor_ = energy_sensor; }
|
||||
|
||||
// Temperature sensor setters
|
||||
void set_internal_temperature_sensor(sensor::Sensor *internal_temperature_sensor) {
|
||||
internal_temperature_sensor_ = internal_temperature_sensor;
|
||||
}
|
||||
@@ -68,42 +50,105 @@ class BL0940 : public PollingComponent, public uart::UARTDevice {
|
||||
external_temperature_sensor_ = external_temperature_sensor;
|
||||
}
|
||||
|
||||
void loop() override;
|
||||
// Configuration setters
|
||||
void set_legacy_mode(bool enable) { this->legacy_mode_enabled_ = enable; }
|
||||
void set_read_command(uint8_t read_command) { this->read_command_ = read_command; }
|
||||
void set_write_command(uint8_t write_command) { this->write_command_ = write_command; }
|
||||
|
||||
// Reference value setters (used for calibration and conversion)
|
||||
void set_current_reference(float current_ref) { this->current_reference_ = current_ref; }
|
||||
void set_energy_reference(float energy_ref) { this->energy_reference_ = energy_ref; }
|
||||
void set_power_reference(float power_ref) { this->power_reference_ = power_ref; }
|
||||
void set_voltage_reference(float voltage_ref) { this->voltage_reference_ = voltage_ref; }
|
||||
|
||||
#ifdef USE_NUMBER
|
||||
// Calibration number setters (for Home Assistant number entities)
|
||||
void set_current_calibration_number(number::Number *num) { this->current_calibration_number_ = num; }
|
||||
void set_voltage_calibration_number(number::Number *num) { this->voltage_calibration_number_ = num; }
|
||||
void set_power_calibration_number(number::Number *num) { this->power_calibration_number_ = num; }
|
||||
void set_energy_calibration_number(number::Number *num) { this->energy_calibration_number_ = num; }
|
||||
#endif
|
||||
|
||||
#ifdef USE_BUTTON
|
||||
// Resets all calibration values to defaults (can be triggered by a button)
|
||||
void reset_calibration();
|
||||
#endif
|
||||
|
||||
// Core component methods
|
||||
void loop() override;
|
||||
void update() override;
|
||||
void setup() override;
|
||||
void dump_config() override;
|
||||
|
||||
protected:
|
||||
sensor::Sensor *voltage_sensor_{nullptr};
|
||||
sensor::Sensor *current_sensor_{nullptr};
|
||||
// NB This may be negative as the circuits is seemingly able to measure
|
||||
// power in both directions
|
||||
sensor::Sensor *power_sensor_{nullptr};
|
||||
sensor::Sensor *energy_sensor_{nullptr};
|
||||
sensor::Sensor *internal_temperature_sensor_{nullptr};
|
||||
sensor::Sensor *external_temperature_sensor_{nullptr};
|
||||
// --- Sensor pointers ---
|
||||
sensor::Sensor *voltage_sensor_{nullptr}; // Voltage sensor
|
||||
sensor::Sensor *current_sensor_{nullptr}; // Current sensor
|
||||
sensor::Sensor *power_sensor_{nullptr}; // Power sensor (can be negative for bidirectional)
|
||||
sensor::Sensor *energy_sensor_{nullptr}; // Energy sensor
|
||||
sensor::Sensor *internal_temperature_sensor_{nullptr}; // Internal temperature sensor
|
||||
sensor::Sensor *external_temperature_sensor_{nullptr}; // External temperature sensor
|
||||
|
||||
// Max difference between two measurements of the temperature. Used to avoid noise.
|
||||
float max_temperature_diff_{0};
|
||||
// Divide by this to turn into Watt
|
||||
float power_reference_ = BL0940_PREF;
|
||||
// Divide by this to turn into Volt
|
||||
float voltage_reference_ = BL0940_UREF;
|
||||
// Divide by this to turn into Ampere
|
||||
float current_reference_ = BL0940_IREF;
|
||||
// Divide by this to turn into kWh
|
||||
float energy_reference_ = BL0940_EREF;
|
||||
#ifdef USE_NUMBER
|
||||
// --- Calibration number entities (for dynamic calibration via HA UI) ---
|
||||
number::Number *voltage_calibration_number_{nullptr};
|
||||
number::Number *current_calibration_number_{nullptr};
|
||||
number::Number *power_calibration_number_{nullptr};
|
||||
number::Number *energy_calibration_number_{nullptr};
|
||||
#endif
|
||||
|
||||
float update_temp_(sensor::Sensor *sensor, ube16_t packed_temperature) const;
|
||||
// --- Internal state ---
|
||||
uint32_t prev_cf_cnt_ = 0; // Previous energy pulse count (for energy calculation)
|
||||
float max_temperature_diff_{0}; // Max allowed temperature difference between two measurements (noise filter)
|
||||
|
||||
static uint32_t to_uint32_t(ube24_t input);
|
||||
// --- Reference values for conversion ---
|
||||
float power_reference_; // Divider for raw power to get Watts
|
||||
float power_reference_cal_; // Calibrated power reference
|
||||
float voltage_reference_; // Divider for raw voltage to get Volts
|
||||
float voltage_reference_cal_; // Calibrated voltage reference
|
||||
float current_reference_; // Divider for raw current to get Amperes
|
||||
float current_reference_cal_; // Calibrated current reference
|
||||
float energy_reference_; // Divider for raw energy to get kWh
|
||||
float energy_reference_cal_; // Calibrated energy reference
|
||||
|
||||
static int32_t to_int32_t(sbe24_t input);
|
||||
// --- Home Assistant calibration values (multipliers, default 1) ---
|
||||
float current_cal_{1};
|
||||
float voltage_cal_{1};
|
||||
float power_cal_{1};
|
||||
float energy_cal_{1};
|
||||
|
||||
static bool validate_checksum(const DataPacket *data);
|
||||
// --- Protocol commands ---
|
||||
uint8_t read_command_;
|
||||
uint8_t write_command_;
|
||||
|
||||
void received_package_(const DataPacket *data) const;
|
||||
// --- Mode flags ---
|
||||
bool legacy_mode_enabled_ = true;
|
||||
|
||||
// --- Methods ---
|
||||
// Converts packed temperature value to float and updates the sensor
|
||||
float update_temp_(sensor::Sensor *sensor, uint16_le_t packed_temperature) const;
|
||||
|
||||
// Validates the checksum of a received data packet
|
||||
bool validate_checksum_(DataPacket *data);
|
||||
|
||||
// Handles a received data packet
|
||||
void received_package_(DataPacket *data);
|
||||
|
||||
// Calculates reference values for calibration and conversion
|
||||
float calculate_energy_reference_();
|
||||
float calculate_power_reference_();
|
||||
float calculate_calibration_value_(float state);
|
||||
|
||||
// Calibration update callbacks (used with number entities)
|
||||
void current_calibration_callback_(float state);
|
||||
void voltage_calibration_callback_(float state);
|
||||
void power_calibration_callback_(float state);
|
||||
void energy_calibration_callback_(float state);
|
||||
void reset_calibration_callback_();
|
||||
|
||||
// Recalculates all reference values after calibration changes
|
||||
void recalibrate_();
|
||||
};
|
||||
|
||||
} // namespace bl0940
|
||||
} // namespace esphome
|
||||
|
||||
27
esphome/components/bl0940/button/__init__.py
Normal file
27
esphome/components/bl0940/button/__init__.py
Normal file
@@ -0,0 +1,27 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import button
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import ENTITY_CATEGORY_CONFIG, ICON_RESTART
|
||||
|
||||
from .. import CONF_BL0940_ID, bl0940_ns
|
||||
from ..sensor import BL0940
|
||||
|
||||
CalibrationResetButton = bl0940_ns.class_(
|
||||
"CalibrationResetButton", button.Button, cg.Component
|
||||
)
|
||||
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
button.button_schema(
|
||||
CalibrationResetButton,
|
||||
entity_category=ENTITY_CATEGORY_CONFIG,
|
||||
icon=ICON_RESTART,
|
||||
)
|
||||
.extend({cv.GenerateID(CONF_BL0940_ID): cv.use_id(BL0940)})
|
||||
.extend(cv.COMPONENT_SCHEMA)
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
var = await button.new_button(config)
|
||||
await cg.register_component(var, config)
|
||||
await cg.register_parented(var, config[CONF_BL0940_ID])
|
||||
@@ -0,0 +1,20 @@
|
||||
#include "calibration_reset_button.h"
|
||||
#include "../bl0940.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/application.h"
|
||||
|
||||
namespace esphome {
|
||||
namespace bl0940 {
|
||||
|
||||
static const char *const TAG = "bl0940.button.calibration_reset";
|
||||
|
||||
void CalibrationResetButton::dump_config() { LOG_BUTTON("", "Calibration Reset Button", this); }
|
||||
|
||||
void CalibrationResetButton::press_action() {
|
||||
ESP_LOGI(TAG, "Resetting calibration defaults...");
|
||||
this->parent_->reset_calibration();
|
||||
}
|
||||
|
||||
} // namespace bl0940
|
||||
} // namespace esphome
|
||||
19
esphome/components/bl0940/button/calibration_reset_button.h
Normal file
19
esphome/components/bl0940/button/calibration_reset_button.h
Normal file
@@ -0,0 +1,19 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/components/button/button.h"
|
||||
|
||||
namespace esphome {
|
||||
namespace bl0940 {
|
||||
|
||||
class BL0940; // Forward declaration of BL0940 class
|
||||
|
||||
class CalibrationResetButton : public button::Button, public Component, public Parented<BL0940> {
|
||||
public:
|
||||
void dump_config() override;
|
||||
|
||||
void press_action() override;
|
||||
};
|
||||
|
||||
} // namespace bl0940
|
||||
} // namespace esphome
|
||||
94
esphome/components/bl0940/number/__init__.py
Normal file
94
esphome/components/bl0940/number/__init__.py
Normal file
@@ -0,0 +1,94 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import number
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
CONF_MAX_VALUE,
|
||||
CONF_MIN_VALUE,
|
||||
CONF_MODE,
|
||||
CONF_RESTORE_VALUE,
|
||||
CONF_STEP,
|
||||
ENTITY_CATEGORY_CONFIG,
|
||||
UNIT_PERCENT,
|
||||
)
|
||||
|
||||
from .. import CONF_BL0940_ID, bl0940_ns
|
||||
from ..sensor import BL0940
|
||||
|
||||
# Define calibration types
|
||||
CONF_CURRENT_CALIBRATION = "current_calibration"
|
||||
CONF_VOLTAGE_CALIBRATION = "voltage_calibration"
|
||||
CONF_POWER_CALIBRATION = "power_calibration"
|
||||
CONF_ENERGY_CALIBRATION = "energy_calibration"
|
||||
|
||||
BL0940Number = bl0940_ns.class_("BL0940Number")
|
||||
|
||||
CalibrationNumber = bl0940_ns.class_(
|
||||
"CalibrationNumber", number.Number, cg.PollingComponent
|
||||
)
|
||||
|
||||
|
||||
def validate_min_max(config):
|
||||
if config[CONF_MAX_VALUE] <= config[CONF_MIN_VALUE]:
|
||||
raise cv.Invalid("max_value must be greater than min_value")
|
||||
return config
|
||||
|
||||
|
||||
CALIBRATION_SCHEMA = cv.All(
|
||||
number.number_schema(
|
||||
CalibrationNumber,
|
||||
entity_category=ENTITY_CATEGORY_CONFIG,
|
||||
unit_of_measurement=UNIT_PERCENT,
|
||||
)
|
||||
.extend(
|
||||
{
|
||||
cv.Optional(CONF_MODE, default="BOX"): cv.enum(number.NUMBER_MODES),
|
||||
cv.Optional(CONF_MAX_VALUE, default=10): cv.All(
|
||||
cv.float_, cv.Range(max=50)
|
||||
),
|
||||
cv.Optional(CONF_MIN_VALUE, default=-10): cv.All(
|
||||
cv.float_, cv.Range(min=-50)
|
||||
),
|
||||
cv.Optional(CONF_STEP, default=0.1): cv.positive_float,
|
||||
cv.Optional(CONF_RESTORE_VALUE): cv.boolean,
|
||||
}
|
||||
)
|
||||
.extend(cv.COMPONENT_SCHEMA),
|
||||
validate_min_max,
|
||||
)
|
||||
|
||||
# Configuration schema for BL0940 numbers
|
||||
CONFIG_SCHEMA = cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(BL0940Number),
|
||||
cv.GenerateID(CONF_BL0940_ID): cv.use_id(BL0940),
|
||||
cv.Optional(CONF_CURRENT_CALIBRATION): CALIBRATION_SCHEMA,
|
||||
cv.Optional(CONF_VOLTAGE_CALIBRATION): CALIBRATION_SCHEMA,
|
||||
cv.Optional(CONF_POWER_CALIBRATION): CALIBRATION_SCHEMA,
|
||||
cv.Optional(CONF_ENERGY_CALIBRATION): CALIBRATION_SCHEMA,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
# Get the BL0940 component instance
|
||||
bl0940 = await cg.get_variable(config[CONF_BL0940_ID])
|
||||
|
||||
# Process all calibration types
|
||||
for cal_type, setter_method in [
|
||||
(CONF_CURRENT_CALIBRATION, "set_current_calibration_number"),
|
||||
(CONF_VOLTAGE_CALIBRATION, "set_voltage_calibration_number"),
|
||||
(CONF_POWER_CALIBRATION, "set_power_calibration_number"),
|
||||
(CONF_ENERGY_CALIBRATION, "set_energy_calibration_number"),
|
||||
]:
|
||||
if conf := config.get(cal_type):
|
||||
var = await number.new_number(
|
||||
conf,
|
||||
min_value=conf.get(CONF_MIN_VALUE),
|
||||
max_value=conf.get(CONF_MAX_VALUE),
|
||||
step=conf.get(CONF_STEP),
|
||||
)
|
||||
await cg.register_component(var, conf)
|
||||
|
||||
if restore_value := config.get(CONF_RESTORE_VALUE):
|
||||
cg.add(var.set_restore_value(restore_value))
|
||||
cg.add(getattr(bl0940, setter_method)(var))
|
||||
29
esphome/components/bl0940/number/calibration_number.cpp
Normal file
29
esphome/components/bl0940/number/calibration_number.cpp
Normal file
@@ -0,0 +1,29 @@
|
||||
#include "calibration_number.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
namespace bl0940 {
|
||||
|
||||
static const char *const TAG = "bl0940.number";
|
||||
|
||||
void CalibrationNumber::setup() {
|
||||
float value = 0.0f;
|
||||
if (this->restore_value_) {
|
||||
this->pref_ = global_preferences->make_preference<float>(this->get_object_id_hash());
|
||||
if (!this->pref_.load(&value)) {
|
||||
value = 0.0f;
|
||||
}
|
||||
}
|
||||
this->publish_state(value);
|
||||
}
|
||||
|
||||
void CalibrationNumber::control(float value) {
|
||||
this->publish_state(value);
|
||||
if (this->restore_value_)
|
||||
this->pref_.save(&value);
|
||||
}
|
||||
|
||||
void CalibrationNumber::dump_config() { LOG_NUMBER("", "Calibration Number", this); }
|
||||
|
||||
} // namespace bl0940
|
||||
} // namespace esphome
|
||||
26
esphome/components/bl0940/number/calibration_number.h
Normal file
26
esphome/components/bl0940/number/calibration_number.h
Normal file
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/components/number/number.h"
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/preferences.h"
|
||||
|
||||
namespace esphome {
|
||||
namespace bl0940 {
|
||||
|
||||
class CalibrationNumber : public number::Number, public Component {
|
||||
public:
|
||||
void setup() override;
|
||||
void dump_config() override;
|
||||
float get_setup_priority() const override { return setup_priority::HARDWARE; }
|
||||
|
||||
void set_restore_value(bool restore_value) { this->restore_value_ = restore_value; }
|
||||
|
||||
protected:
|
||||
void control(float value) override;
|
||||
bool restore_value_{true};
|
||||
|
||||
ESPPreferenceObject pref_;
|
||||
};
|
||||
|
||||
} // namespace bl0940
|
||||
} // namespace esphome
|
||||
@@ -8,6 +8,7 @@ from esphome.const import (
|
||||
CONF_ID,
|
||||
CONF_INTERNAL_TEMPERATURE,
|
||||
CONF_POWER,
|
||||
CONF_REFERENCE_VOLTAGE,
|
||||
CONF_VOLTAGE,
|
||||
DEVICE_CLASS_CURRENT,
|
||||
DEVICE_CLASS_ENERGY,
|
||||
@@ -23,12 +24,133 @@ from esphome.const import (
|
||||
UNIT_WATT,
|
||||
)
|
||||
|
||||
from . import bl0940_ns
|
||||
|
||||
DEPENDENCIES = ["uart"]
|
||||
|
||||
|
||||
bl0940_ns = cg.esphome_ns.namespace("bl0940")
|
||||
BL0940 = bl0940_ns.class_("BL0940", cg.PollingComponent, uart.UARTDevice)
|
||||
|
||||
CONF_LEGACY_MODE = "legacy_mode"
|
||||
|
||||
CONF_READ_COMMAND = "read_command"
|
||||
CONF_WRITE_COMMAND = "write_command"
|
||||
|
||||
CONF_RESISTOR_SHUNT = "resistor_shunt"
|
||||
CONF_RESISTOR_ONE = "resistor_one"
|
||||
CONF_RESISTOR_TWO = "resistor_two"
|
||||
|
||||
CONF_CURRENT_REFERENCE = "current_reference"
|
||||
CONF_ENERGY_REFERENCE = "energy_reference"
|
||||
CONF_POWER_REFERENCE = "power_reference"
|
||||
CONF_VOLTAGE_REFERENCE = "voltage_reference"
|
||||
|
||||
DEFAULT_BL0940_READ_COMMAND = 0x58
|
||||
DEFAULT_BL0940_WRITE_COMMAND = 0xA1
|
||||
|
||||
# Values according to BL0940 application note:
|
||||
# https://www.belling.com.cn/media/file_object/bel_product/BL0940/guide/BL0940_APPNote_TSSOP14_V1.04_EN.pdf
|
||||
DEFAULT_BL0940_VREF = 1.218 # Vref = 1.218
|
||||
DEFAULT_BL0940_RL = 1 # RL = 1 mΩ
|
||||
DEFAULT_BL0940_R1 = 0.51 # R1 = 0.51 kΩ
|
||||
DEFAULT_BL0940_R2 = 1950 # R2 = 5 x 390 kΩ -> 1950 kΩ
|
||||
|
||||
# ----------------------------------------------------
|
||||
# values from initial implementation
|
||||
DEFAULT_BL0940_LEGACY_READ_COMMAND = 0x50
|
||||
DEFAULT_BL0940_LEGACY_WRITE_COMMAND = 0xA0
|
||||
|
||||
DEFAULT_BL0940_LEGACY_UREF = 33000
|
||||
DEFAULT_BL0940_LEGACY_IREF = 275000
|
||||
DEFAULT_BL0940_LEGACY_PREF = 1430
|
||||
# Measured to 297J per click according to power consumption of 5 minutes
|
||||
# Converted to kWh (3.6MJ per kwH). Used to be 256 * 1638.4
|
||||
DEFAULT_BL0940_LEGACY_EREF = 3.6e6 / 297
|
||||
# ----------------------------------------------------
|
||||
|
||||
|
||||
# methods to calculate voltage and current reference values
|
||||
def calculate_voltage_reference(vref, r_one, r_two):
|
||||
# formula: 79931 / Vref * (R1 * 1000) / (R1 + R2)
|
||||
return 79931 / vref * (r_one * 1000) / (r_one + r_two)
|
||||
|
||||
|
||||
def calculate_current_reference(vref, r_shunt):
|
||||
# formula: 324004 * RL / Vref
|
||||
return 324004 * r_shunt / vref
|
||||
|
||||
|
||||
def calculate_power_reference(voltage_reference, current_reference):
|
||||
# calculate power reference based on voltage and current reference
|
||||
return voltage_reference * current_reference * 4046 / 324004 / 79931
|
||||
|
||||
|
||||
def calculate_energy_reference(power_reference):
|
||||
# formula: power_reference * 3600000 / (1638.4 * 256)
|
||||
return power_reference * 3600000 / (1638.4 * 256)
|
||||
|
||||
|
||||
def validate_legacy_mode(config):
|
||||
# Only allow schematic calibration options if legacy_mode is False
|
||||
if config.get(CONF_LEGACY_MODE, True):
|
||||
forbidden = [
|
||||
CONF_REFERENCE_VOLTAGE,
|
||||
CONF_RESISTOR_SHUNT,
|
||||
CONF_RESISTOR_ONE,
|
||||
CONF_RESISTOR_TWO,
|
||||
]
|
||||
for key in forbidden:
|
||||
if key in config:
|
||||
raise cv.Invalid(
|
||||
f"Option '{key}' is only allowed when legacy_mode: false"
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
def set_command_defaults(config):
|
||||
# Set defaults for read_command and write_command based on legacy_mode
|
||||
legacy = config.get(CONF_LEGACY_MODE, True)
|
||||
if legacy:
|
||||
config.setdefault(CONF_READ_COMMAND, DEFAULT_BL0940_LEGACY_READ_COMMAND)
|
||||
config.setdefault(CONF_WRITE_COMMAND, DEFAULT_BL0940_LEGACY_WRITE_COMMAND)
|
||||
else:
|
||||
config.setdefault(CONF_READ_COMMAND, DEFAULT_BL0940_READ_COMMAND)
|
||||
config.setdefault(CONF_WRITE_COMMAND, DEFAULT_BL0940_WRITE_COMMAND)
|
||||
return config
|
||||
|
||||
|
||||
def set_reference_values(config):
|
||||
# Set default reference values based on legacy_mode
|
||||
if config.get(CONF_LEGACY_MODE, True):
|
||||
config.setdefault(CONF_VOLTAGE_REFERENCE, DEFAULT_BL0940_LEGACY_UREF)
|
||||
config.setdefault(CONF_CURRENT_REFERENCE, DEFAULT_BL0940_LEGACY_IREF)
|
||||
config.setdefault(CONF_POWER_REFERENCE, DEFAULT_BL0940_LEGACY_PREF)
|
||||
config.setdefault(CONF_ENERGY_REFERENCE, DEFAULT_BL0940_LEGACY_PREF)
|
||||
else:
|
||||
vref = config.get(CONF_VOLTAGE_REFERENCE, DEFAULT_BL0940_VREF)
|
||||
r_one = config.get(CONF_RESISTOR_ONE, DEFAULT_BL0940_R1)
|
||||
r_two = config.get(CONF_RESISTOR_TWO, DEFAULT_BL0940_R2)
|
||||
r_shunt = config.get(CONF_RESISTOR_SHUNT, DEFAULT_BL0940_RL)
|
||||
|
||||
config.setdefault(
|
||||
CONF_VOLTAGE_REFERENCE, calculate_voltage_reference(vref, r_one, r_two)
|
||||
)
|
||||
config.setdefault(
|
||||
CONF_CURRENT_REFERENCE, calculate_current_reference(vref, r_shunt)
|
||||
)
|
||||
config.setdefault(
|
||||
CONF_POWER_REFERENCE,
|
||||
calculate_power_reference(
|
||||
config.get(CONF_VOLTAGE_REFERENCE), config.get(CONF_CURRENT_REFERENCE)
|
||||
),
|
||||
)
|
||||
config.setdefault(
|
||||
CONF_ENERGY_REFERENCE,
|
||||
calculate_energy_reference(config.get(CONF_POWER_REFERENCE)),
|
||||
)
|
||||
|
||||
return config
|
||||
|
||||
|
||||
CONFIG_SCHEMA = (
|
||||
cv.Schema(
|
||||
{
|
||||
@@ -69,10 +191,24 @@ CONFIG_SCHEMA = (
|
||||
device_class=DEVICE_CLASS_TEMPERATURE,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional(CONF_LEGACY_MODE, default=True): cv.boolean,
|
||||
cv.Optional(CONF_READ_COMMAND): cv.hex_uint8_t,
|
||||
cv.Optional(CONF_WRITE_COMMAND): cv.hex_uint8_t,
|
||||
cv.Optional(CONF_REFERENCE_VOLTAGE): cv.float_,
|
||||
cv.Optional(CONF_RESISTOR_SHUNT): cv.float_,
|
||||
cv.Optional(CONF_RESISTOR_ONE): cv.float_,
|
||||
cv.Optional(CONF_RESISTOR_TWO): cv.float_,
|
||||
cv.Optional(CONF_CURRENT_REFERENCE): cv.float_,
|
||||
cv.Optional(CONF_ENERGY_REFERENCE): cv.float_,
|
||||
cv.Optional(CONF_POWER_REFERENCE): cv.float_,
|
||||
cv.Optional(CONF_VOLTAGE_REFERENCE): cv.float_,
|
||||
}
|
||||
)
|
||||
.extend(cv.polling_component_schema("60s"))
|
||||
.extend(uart.UART_DEVICE_SCHEMA)
|
||||
.add_extra(validate_legacy_mode)
|
||||
.add_extra(set_command_defaults)
|
||||
.add_extra(set_reference_values)
|
||||
)
|
||||
|
||||
|
||||
@@ -99,3 +235,16 @@ async def to_code(config):
|
||||
if external_temperature_config := config.get(CONF_EXTERNAL_TEMPERATURE):
|
||||
sens = await sensor.new_sensor(external_temperature_config)
|
||||
cg.add(var.set_external_temperature_sensor(sens))
|
||||
|
||||
# enable legacy mode
|
||||
cg.add(var.set_legacy_mode(config.get(CONF_LEGACY_MODE)))
|
||||
|
||||
# Set bl0940 commands after validator has determined which defaults to use if not set
|
||||
cg.add(var.set_read_command(config.get(CONF_READ_COMMAND)))
|
||||
cg.add(var.set_write_command(config.get(CONF_WRITE_COMMAND)))
|
||||
|
||||
# Set reference values after validator has set the values either from defaults or calculated
|
||||
cg.add(var.set_current_reference(config.get(CONF_CURRENT_REFERENCE)))
|
||||
cg.add(var.set_voltage_reference(config.get(CONF_VOLTAGE_REFERENCE)))
|
||||
cg.add(var.set_power_reference(config.get(CONF_POWER_REFERENCE)))
|
||||
cg.add(var.set_energy_reference(config.get(CONF_ENERGY_REFERENCE)))
|
||||
|
||||
@@ -152,7 +152,7 @@ void CCS811Component::send_env_data_() {
|
||||
void CCS811Component::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "CCS811");
|
||||
LOG_I2C_DEVICE(this)
|
||||
LOG_UPDATE_INTERVAL(this)
|
||||
LOG_UPDATE_INTERVAL(this);
|
||||
LOG_SENSOR(" ", "CO2 Sensor", this->co2_);
|
||||
LOG_SENSOR(" ", "TVOC Sensor", this->tvoc_);
|
||||
LOG_TEXT_SENSOR(" ", "Firmware Version Sensor", this->version_)
|
||||
|
||||
@@ -52,7 +52,7 @@ void DebugComponent::on_shutdown() {
|
||||
char buffer[REBOOT_MAX_LEN]{};
|
||||
auto pref = global_preferences->make_preference(REBOOT_MAX_LEN, fnv1_hash(REBOOT_KEY + App.get_name()));
|
||||
if (component != nullptr) {
|
||||
strncpy(buffer, component->get_component_source(), REBOOT_MAX_LEN - 1);
|
||||
strncpy(buffer, LOG_STR_ARG(component->get_component_log_str()), REBOOT_MAX_LEN - 1);
|
||||
buffer[REBOOT_MAX_LEN - 1] = '\0';
|
||||
}
|
||||
ESP_LOGD(TAG, "Storing reboot source: %s", buffer);
|
||||
|
||||
@@ -54,13 +54,13 @@ struct ISRPinArg {
|
||||
|
||||
ISRInternalGPIOPin ESP32InternalGPIOPin::to_isr() const {
|
||||
auto *arg = new ISRPinArg{}; // NOLINT(cppcoreguidelines-owning-memory)
|
||||
arg->pin = this->pin_;
|
||||
arg->pin = this->get_pin_num();
|
||||
arg->flags = gpio::FLAG_NONE;
|
||||
arg->inverted = inverted_;
|
||||
arg->inverted = this->pin_flags_.inverted;
|
||||
#if defined(USE_ESP32_VARIANT_ESP32)
|
||||
arg->use_rtc = rtc_gpio_is_valid_gpio(this->pin_);
|
||||
arg->use_rtc = rtc_gpio_is_valid_gpio(this->get_pin_num());
|
||||
if (arg->use_rtc)
|
||||
arg->rtc_pin = rtc_io_number_get(this->pin_);
|
||||
arg->rtc_pin = rtc_io_number_get(this->get_pin_num());
|
||||
#endif
|
||||
return ISRInternalGPIOPin((void *) arg);
|
||||
}
|
||||
@@ -69,23 +69,23 @@ void ESP32InternalGPIOPin::attach_interrupt(void (*func)(void *), void *arg, gpi
|
||||
gpio_int_type_t idf_type = GPIO_INTR_ANYEDGE;
|
||||
switch (type) {
|
||||
case gpio::INTERRUPT_RISING_EDGE:
|
||||
idf_type = inverted_ ? GPIO_INTR_NEGEDGE : GPIO_INTR_POSEDGE;
|
||||
idf_type = this->pin_flags_.inverted ? GPIO_INTR_NEGEDGE : GPIO_INTR_POSEDGE;
|
||||
break;
|
||||
case gpio::INTERRUPT_FALLING_EDGE:
|
||||
idf_type = inverted_ ? GPIO_INTR_POSEDGE : GPIO_INTR_NEGEDGE;
|
||||
idf_type = this->pin_flags_.inverted ? GPIO_INTR_POSEDGE : GPIO_INTR_NEGEDGE;
|
||||
break;
|
||||
case gpio::INTERRUPT_ANY_EDGE:
|
||||
idf_type = GPIO_INTR_ANYEDGE;
|
||||
break;
|
||||
case gpio::INTERRUPT_LOW_LEVEL:
|
||||
idf_type = inverted_ ? GPIO_INTR_HIGH_LEVEL : GPIO_INTR_LOW_LEVEL;
|
||||
idf_type = this->pin_flags_.inverted ? GPIO_INTR_HIGH_LEVEL : GPIO_INTR_LOW_LEVEL;
|
||||
break;
|
||||
case gpio::INTERRUPT_HIGH_LEVEL:
|
||||
idf_type = inverted_ ? GPIO_INTR_LOW_LEVEL : GPIO_INTR_HIGH_LEVEL;
|
||||
idf_type = this->pin_flags_.inverted ? GPIO_INTR_LOW_LEVEL : GPIO_INTR_HIGH_LEVEL;
|
||||
break;
|
||||
}
|
||||
gpio_set_intr_type(pin_, idf_type);
|
||||
gpio_intr_enable(pin_);
|
||||
gpio_set_intr_type(this->get_pin_num(), idf_type);
|
||||
gpio_intr_enable(this->get_pin_num());
|
||||
if (!isr_service_installed) {
|
||||
auto res = gpio_install_isr_service(ESP_INTR_FLAG_LEVEL3);
|
||||
if (res != ESP_OK) {
|
||||
@@ -94,31 +94,31 @@ void ESP32InternalGPIOPin::attach_interrupt(void (*func)(void *), void *arg, gpi
|
||||
}
|
||||
isr_service_installed = true;
|
||||
}
|
||||
gpio_isr_handler_add(pin_, func, arg);
|
||||
gpio_isr_handler_add(this->get_pin_num(), func, arg);
|
||||
}
|
||||
|
||||
std::string ESP32InternalGPIOPin::dump_summary() const {
|
||||
char buffer[32];
|
||||
snprintf(buffer, sizeof(buffer), "GPIO%" PRIu32, static_cast<uint32_t>(pin_));
|
||||
snprintf(buffer, sizeof(buffer), "GPIO%" PRIu32, static_cast<uint32_t>(this->pin_));
|
||||
return buffer;
|
||||
}
|
||||
|
||||
void ESP32InternalGPIOPin::setup() {
|
||||
gpio_config_t conf{};
|
||||
conf.pin_bit_mask = 1ULL << static_cast<uint32_t>(pin_);
|
||||
conf.mode = flags_to_mode(flags_);
|
||||
conf.pull_up_en = flags_ & gpio::FLAG_PULLUP ? GPIO_PULLUP_ENABLE : GPIO_PULLUP_DISABLE;
|
||||
conf.pull_down_en = flags_ & gpio::FLAG_PULLDOWN ? GPIO_PULLDOWN_ENABLE : GPIO_PULLDOWN_DISABLE;
|
||||
conf.pin_bit_mask = 1ULL << static_cast<uint32_t>(this->pin_);
|
||||
conf.mode = flags_to_mode(this->flags_);
|
||||
conf.pull_up_en = this->flags_ & gpio::FLAG_PULLUP ? GPIO_PULLUP_ENABLE : GPIO_PULLUP_DISABLE;
|
||||
conf.pull_down_en = this->flags_ & gpio::FLAG_PULLDOWN ? GPIO_PULLDOWN_ENABLE : GPIO_PULLDOWN_DISABLE;
|
||||
conf.intr_type = GPIO_INTR_DISABLE;
|
||||
gpio_config(&conf);
|
||||
if (flags_ & gpio::FLAG_OUTPUT) {
|
||||
gpio_set_drive_capability(pin_, drive_strength_);
|
||||
if (this->flags_ & gpio::FLAG_OUTPUT) {
|
||||
gpio_set_drive_capability(this->get_pin_num(), this->get_drive_strength());
|
||||
}
|
||||
}
|
||||
|
||||
void ESP32InternalGPIOPin::pin_mode(gpio::Flags flags) {
|
||||
// can't call gpio_config here because that logs in esp-idf which may cause issues
|
||||
gpio_set_direction(pin_, flags_to_mode(flags));
|
||||
gpio_set_direction(this->get_pin_num(), flags_to_mode(flags));
|
||||
gpio_pull_mode_t pull_mode = GPIO_FLOATING;
|
||||
if ((flags & gpio::FLAG_PULLUP) && (flags & gpio::FLAG_PULLDOWN)) {
|
||||
pull_mode = GPIO_PULLUP_PULLDOWN;
|
||||
@@ -127,12 +127,16 @@ void ESP32InternalGPIOPin::pin_mode(gpio::Flags flags) {
|
||||
} else if (flags & gpio::FLAG_PULLDOWN) {
|
||||
pull_mode = GPIO_PULLDOWN_ONLY;
|
||||
}
|
||||
gpio_set_pull_mode(pin_, pull_mode);
|
||||
gpio_set_pull_mode(this->get_pin_num(), pull_mode);
|
||||
}
|
||||
|
||||
bool ESP32InternalGPIOPin::digital_read() { return bool(gpio_get_level(pin_)) != inverted_; }
|
||||
void ESP32InternalGPIOPin::digital_write(bool value) { gpio_set_level(pin_, value != inverted_ ? 1 : 0); }
|
||||
void ESP32InternalGPIOPin::detach_interrupt() const { gpio_intr_disable(pin_); }
|
||||
bool ESP32InternalGPIOPin::digital_read() {
|
||||
return bool(gpio_get_level(this->get_pin_num())) != this->pin_flags_.inverted;
|
||||
}
|
||||
void ESP32InternalGPIOPin::digital_write(bool value) {
|
||||
gpio_set_level(this->get_pin_num(), value != this->pin_flags_.inverted ? 1 : 0);
|
||||
}
|
||||
void ESP32InternalGPIOPin::detach_interrupt() const { gpio_intr_disable(this->get_pin_num()); }
|
||||
|
||||
} // namespace esp32
|
||||
|
||||
|
||||
@@ -7,12 +7,18 @@
|
||||
namespace esphome {
|
||||
namespace esp32 {
|
||||
|
||||
// Static assertions to ensure our bit-packed fields can hold the enum values
|
||||
static_assert(GPIO_NUM_MAX <= 256, "gpio_num_t has too many values for uint8_t");
|
||||
static_assert(GPIO_DRIVE_CAP_MAX <= 4, "gpio_drive_cap_t has too many values for 2-bit field");
|
||||
|
||||
class ESP32InternalGPIOPin : public InternalGPIOPin {
|
||||
public:
|
||||
void set_pin(gpio_num_t pin) { pin_ = pin; }
|
||||
void set_inverted(bool inverted) { inverted_ = inverted; }
|
||||
void set_drive_strength(gpio_drive_cap_t drive_strength) { drive_strength_ = drive_strength; }
|
||||
void set_flags(gpio::Flags flags) { flags_ = flags; }
|
||||
void set_pin(gpio_num_t pin) { this->pin_ = static_cast<uint8_t>(pin); }
|
||||
void set_inverted(bool inverted) { this->pin_flags_.inverted = inverted; }
|
||||
void set_drive_strength(gpio_drive_cap_t drive_strength) {
|
||||
this->pin_flags_.drive_strength = static_cast<uint8_t>(drive_strength);
|
||||
}
|
||||
void set_flags(gpio::Flags flags) { this->flags_ = flags; }
|
||||
|
||||
void setup() override;
|
||||
void pin_mode(gpio::Flags flags) override;
|
||||
@@ -21,17 +27,26 @@ class ESP32InternalGPIOPin : public InternalGPIOPin {
|
||||
std::string dump_summary() const override;
|
||||
void detach_interrupt() const override;
|
||||
ISRInternalGPIOPin to_isr() const override;
|
||||
uint8_t get_pin() const override { return (uint8_t) pin_; }
|
||||
gpio::Flags get_flags() const override { return flags_; }
|
||||
bool is_inverted() const override { return inverted_; }
|
||||
uint8_t get_pin() const override { return this->pin_; }
|
||||
gpio::Flags get_flags() const override { return this->flags_; }
|
||||
bool is_inverted() const override { return this->pin_flags_.inverted; }
|
||||
gpio_num_t get_pin_num() const { return static_cast<gpio_num_t>(this->pin_); }
|
||||
gpio_drive_cap_t get_drive_strength() const { return static_cast<gpio_drive_cap_t>(this->pin_flags_.drive_strength); }
|
||||
|
||||
protected:
|
||||
void attach_interrupt(void (*func)(void *), void *arg, gpio::InterruptType type) const override;
|
||||
|
||||
gpio_num_t pin_;
|
||||
gpio_drive_cap_t drive_strength_;
|
||||
gpio::Flags flags_;
|
||||
bool inverted_;
|
||||
// Memory layout: 8 bytes total on 32-bit systems
|
||||
// - 3 bytes for members below
|
||||
// - 1 byte padding for alignment
|
||||
// - 4 bytes for vtable pointer
|
||||
uint8_t pin_; // GPIO pin number (0-255, actual max ~54 on ESP32)
|
||||
gpio::Flags flags_; // GPIO flags (1 byte)
|
||||
struct PinFlags {
|
||||
uint8_t inverted : 1; // Invert pin logic (1 bit)
|
||||
uint8_t drive_strength : 2; // Drive strength 0-3 (2 bits)
|
||||
uint8_t reserved : 5; // Reserved for future use (5 bits)
|
||||
} pin_flags_; // Total: 1 byte
|
||||
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
|
||||
static bool isr_service_installed;
|
||||
};
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
#include "esphome/core/defines.h"
|
||||
#ifdef USE_OTA
|
||||
#include "esphome/components/ota/ota_backend.h"
|
||||
#include "esphome/components/socket/socket.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/preferences.h"
|
||||
#include "esphome/components/ota/ota_backend.h"
|
||||
#include "esphome/components/socket/socket.h"
|
||||
|
||||
namespace esphome {
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <type_traits>
|
||||
#include "esphome/core/hal.h"
|
||||
|
||||
namespace esphome::gpio_expander {
|
||||
@@ -11,18 +12,27 @@ namespace esphome::gpio_expander {
|
||||
/// @brief A class to cache the read state of a GPIO expander.
|
||||
/// This class caches reads between GPIO Pins which are on the same bank.
|
||||
/// This means that for reading whole Port (ex. 8 pins) component needs only one
|
||||
/// I2C/SPI read per main loop call. It assumes, that one bit in byte identifies one GPIO pin
|
||||
/// I2C/SPI read per main loop call. It assumes that one bit in byte identifies one GPIO pin.
|
||||
///
|
||||
/// Template parameters:
|
||||
/// T - Type which represents internal register. Could be uint8_t or uint16_t. Adjust to
|
||||
/// match size of your internal GPIO bank register.
|
||||
/// N - Number of pins
|
||||
template<typename T, T N> class CachedGpioExpander {
|
||||
/// T - Type which represents internal bank register. Could be uint8_t or uint16_t.
|
||||
/// Choose based on how your I/O expander reads pins:
|
||||
/// * uint8_t: For chips that read banks separately (8 pins at a time)
|
||||
/// Examples: MCP23017 (2x8-bit banks), TCA9555 (2x8-bit banks)
|
||||
/// * uint16_t: For chips that read all pins at once (up to 16 pins)
|
||||
/// Examples: PCF8574/8575 (8/16 pins), PCA9554/9555 (8/16 pins)
|
||||
/// N - Total number of pins (maximum 65535)
|
||||
/// P - Type for pin number parameters (automatically selected based on N:
|
||||
/// uint8_t for N<=256, uint16_t for N>256). Can be explicitly specified
|
||||
/// if needed (e.g., for components like SN74HC165 with >256 pins)
|
||||
template<typename T, uint16_t N, typename P = typename std::conditional<(N > 256), uint16_t, uint8_t>::type>
|
||||
class CachedGpioExpander {
|
||||
public:
|
||||
/// @brief Read the state of the given pin. This will invalidate the cache for the given pin number.
|
||||
/// @param pin Pin number to read
|
||||
/// @return Pin state
|
||||
bool digital_read(T pin) {
|
||||
const uint8_t bank = pin / BANK_SIZE;
|
||||
bool digital_read(P pin) {
|
||||
const P bank = pin / BANK_SIZE;
|
||||
const T pin_mask = (1 << (pin % BANK_SIZE));
|
||||
// Check if specific pin cache is valid
|
||||
if (this->read_cache_valid_[bank] & pin_mask) {
|
||||
@@ -38,21 +48,31 @@ template<typename T, T N> class CachedGpioExpander {
|
||||
return this->digital_read_cache(pin);
|
||||
}
|
||||
|
||||
void digital_write(T pin, bool value) { this->digital_write_hw(pin, value); }
|
||||
void digital_write(P pin, bool value) { this->digital_write_hw(pin, value); }
|
||||
|
||||
protected:
|
||||
/// @brief Call component low level function to read GPIO state from device
|
||||
virtual bool digital_read_hw(T pin) = 0;
|
||||
/// @brief Call component read function from internal cache.
|
||||
virtual bool digital_read_cache(T pin) = 0;
|
||||
/// @brief Call component low level function to write GPIO state to device
|
||||
virtual void digital_write_hw(T pin, bool value) = 0;
|
||||
/// @brief Read GPIO bank from hardware into internal state
|
||||
/// @param pin Pin number (used to determine which bank to read)
|
||||
/// @return true if read succeeded, false on communication error
|
||||
/// @note This does NOT return the pin state. It returns whether the read operation succeeded.
|
||||
/// The actual pin state should be returned by digital_read_cache().
|
||||
virtual bool digital_read_hw(P pin) = 0;
|
||||
|
||||
/// @brief Get cached pin value from internal state
|
||||
/// @param pin Pin number to read
|
||||
/// @return Pin state (true = HIGH, false = LOW)
|
||||
virtual bool digital_read_cache(P pin) = 0;
|
||||
|
||||
/// @brief Write GPIO state to hardware
|
||||
/// @param pin Pin number to write
|
||||
/// @param value Pin state to write (true = HIGH, false = LOW)
|
||||
virtual void digital_write_hw(P pin, bool value) = 0;
|
||||
|
||||
/// @brief Invalidate cache. This function should be called in component loop().
|
||||
void reset_pin_cache_() { memset(this->read_cache_valid_, 0x00, CACHE_SIZE_BYTES); }
|
||||
|
||||
static constexpr uint8_t BITS_PER_BYTE = 8;
|
||||
static constexpr uint8_t BANK_SIZE = sizeof(T) * BITS_PER_BYTE;
|
||||
static constexpr uint16_t BITS_PER_BYTE = 8;
|
||||
static constexpr uint16_t BANK_SIZE = sizeof(T) * BITS_PER_BYTE;
|
||||
static constexpr size_t BANKS = N / BANK_SIZE;
|
||||
static constexpr size_t CACHE_SIZE_BYTES = BANKS * sizeof(T);
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ void GroveGasMultichannelV2Component::update() {
|
||||
void GroveGasMultichannelV2Component::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "Grove Multichannel Gas Sensor V2");
|
||||
LOG_I2C_DEVICE(this)
|
||||
LOG_UPDATE_INTERVAL(this)
|
||||
LOG_UPDATE_INTERVAL(this);
|
||||
LOG_SENSOR(" ", "Nitrogen Dioxide", this->nitrogen_dioxide_sensor_);
|
||||
LOG_SENSOR(" ", "Ethanol", this->ethanol_sensor_);
|
||||
LOG_SENSOR(" ", "Carbon Monoxide", this->carbon_monoxide_sensor_);
|
||||
|
||||
@@ -42,7 +42,7 @@ void HLW8012Component::dump_config() {
|
||||
" Current resistor: %.1f mΩ\n"
|
||||
" Voltage Divider: %.1f",
|
||||
this->change_mode_every_, this->current_resistor_ * 1000.0f, this->voltage_divider_);
|
||||
LOG_UPDATE_INTERVAL(this)
|
||||
LOG_UPDATE_INTERVAL(this);
|
||||
LOG_SENSOR(" ", "Voltage", this->voltage_sensor_);
|
||||
LOG_SENSOR(" ", "Current", this->current_sensor_);
|
||||
LOG_SENSOR(" ", "Power", this->power_sensor_);
|
||||
|
||||
@@ -4,6 +4,9 @@ from esphome.components.esp32 import add_idf_sdkconfig_option, get_esp32_variant
|
||||
from esphome.components.esp32.const import (
|
||||
VARIANT_ESP32,
|
||||
VARIANT_ESP32C3,
|
||||
VARIANT_ESP32C5,
|
||||
VARIANT_ESP32C6,
|
||||
VARIANT_ESP32H2,
|
||||
VARIANT_ESP32P4,
|
||||
VARIANT_ESP32S2,
|
||||
VARIANT_ESP32S3,
|
||||
@@ -62,12 +65,15 @@ I2S_ROLE_OPTIONS = {
|
||||
CONF_SECONDARY: i2s_role_t.I2S_ROLE_SLAVE, # NOLINT
|
||||
}
|
||||
|
||||
# https://github.com/espressif/esp-idf/blob/master/components/soc/{variant}/include/soc/soc_caps.h
|
||||
# https://github.com/espressif/esp-idf/blob/master/components/soc/{variant}/include/soc/soc_caps.h (SOC_I2S_NUM)
|
||||
I2S_PORTS = {
|
||||
VARIANT_ESP32: 2,
|
||||
VARIANT_ESP32S2: 1,
|
||||
VARIANT_ESP32S3: 2,
|
||||
VARIANT_ESP32C3: 1,
|
||||
VARIANT_ESP32C5: 1,
|
||||
VARIANT_ESP32C6: 1,
|
||||
VARIANT_ESP32H2: 1,
|
||||
VARIANT_ESP32P4: 3,
|
||||
}
|
||||
|
||||
|
||||
1
esphome/components/inkplate/__init__.py
Normal file
1
esphome/components/inkplate/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
CODEOWNERS = ["@jesserockz", "@JosipKuci"]
|
||||
105
esphome/components/inkplate/const.py
Normal file
105
esphome/components/inkplate/const.py
Normal file
@@ -0,0 +1,105 @@
|
||||
WAVEFORMS = {
|
||||
"inkplate_6": (
|
||||
(0, 1, 1, 0, 0, 1, 1, 0, 0),
|
||||
(0, 1, 2, 1, 1, 2, 1, 0, 0),
|
||||
(1, 1, 1, 2, 2, 1, 0, 0, 0),
|
||||
(0, 0, 0, 1, 1, 1, 2, 0, 0),
|
||||
(2, 1, 1, 1, 2, 1, 2, 0, 0),
|
||||
(2, 2, 1, 1, 2, 1, 2, 0, 0),
|
||||
(1, 1, 1, 2, 1, 2, 2, 0, 0),
|
||||
(0, 0, 0, 0, 0, 0, 2, 0, 0),
|
||||
),
|
||||
"inkplate_10": (
|
||||
(0, 0, 0, 0, 0, 0, 0, 1, 0),
|
||||
(0, 0, 0, 2, 2, 2, 1, 1, 0),
|
||||
(0, 0, 2, 1, 1, 2, 2, 1, 0),
|
||||
(0, 1, 2, 2, 1, 2, 2, 1, 0),
|
||||
(0, 0, 2, 1, 2, 2, 2, 1, 0),
|
||||
(0, 2, 2, 2, 2, 2, 2, 1, 0),
|
||||
(0, 0, 0, 0, 0, 2, 1, 2, 0),
|
||||
(0, 0, 0, 2, 2, 2, 2, 2, 0),
|
||||
),
|
||||
"inkplate_6_plus": (
|
||||
(0, 0, 0, 0, 0, 2, 1, 1, 0),
|
||||
(0, 0, 2, 1, 1, 1, 2, 1, 0),
|
||||
(0, 2, 2, 2, 1, 1, 2, 1, 0),
|
||||
(0, 0, 2, 2, 2, 1, 2, 1, 0),
|
||||
(0, 0, 0, 0, 2, 2, 2, 1, 0),
|
||||
(0, 0, 2, 1, 2, 1, 1, 2, 0),
|
||||
(0, 0, 2, 2, 2, 1, 1, 2, 0),
|
||||
(0, 0, 0, 0, 2, 2, 2, 2, 0),
|
||||
),
|
||||
"inkplate_6_v2": (
|
||||
(1, 0, 1, 0, 1, 1, 1, 0, 0),
|
||||
(0, 0, 0, 1, 1, 1, 1, 0, 0),
|
||||
(1, 1, 1, 1, 0, 2, 1, 0, 0),
|
||||
(1, 1, 1, 2, 2, 1, 1, 0, 0),
|
||||
(1, 1, 1, 1, 2, 2, 1, 0, 0),
|
||||
(0, 1, 1, 1, 2, 2, 1, 0, 0),
|
||||
(0, 0, 0, 0, 1, 1, 2, 0, 0),
|
||||
(0, 0, 0, 0, 0, 1, 2, 0, 0),
|
||||
),
|
||||
"inkplate_5": (
|
||||
(0, 0, 1, 1, 0, 1, 1, 1, 0),
|
||||
(0, 1, 1, 1, 1, 2, 0, 1, 0),
|
||||
(1, 2, 2, 0, 2, 1, 1, 1, 0),
|
||||
(1, 1, 1, 2, 0, 1, 1, 2, 0),
|
||||
(0, 1, 1, 1, 2, 0, 1, 2, 0),
|
||||
(0, 0, 0, 1, 1, 2, 1, 2, 0),
|
||||
(1, 1, 1, 2, 0, 2, 1, 2, 0),
|
||||
(0, 0, 0, 0, 0, 0, 0, 0, 0),
|
||||
),
|
||||
"inkplate_5_v2": (
|
||||
(0, 0, 1, 1, 2, 1, 1, 1, 0),
|
||||
(1, 1, 2, 2, 1, 2, 1, 1, 0),
|
||||
(0, 1, 2, 2, 1, 1, 2, 1, 0),
|
||||
(0, 0, 1, 1, 1, 1, 1, 2, 0),
|
||||
(1, 2, 1, 2, 1, 1, 1, 2, 0),
|
||||
(0, 1, 1, 1, 2, 0, 1, 2, 0),
|
||||
(1, 1, 1, 2, 2, 2, 1, 2, 0),
|
||||
(0, 0, 0, 0, 0, 0, 0, 0, 0),
|
||||
),
|
||||
}
|
||||
|
||||
INKPLATE_10_CUSTOM_WAVEFORMS = (
|
||||
(
|
||||
(0, 0, 0, 0, 0, 0, 0, 0, 0),
|
||||
(0, 0, 0, 2, 1, 2, 1, 1, 0),
|
||||
(0, 0, 0, 2, 2, 1, 2, 1, 0),
|
||||
(0, 0, 2, 2, 1, 2, 2, 1, 0),
|
||||
(0, 0, 0, 2, 1, 1, 1, 2, 0),
|
||||
(0, 0, 2, 2, 2, 1, 1, 2, 0),
|
||||
(0, 0, 0, 0, 0, 1, 2, 2, 0),
|
||||
(0, 0, 0, 0, 2, 2, 2, 2, 0),
|
||||
),
|
||||
(
|
||||
(0, 3, 3, 3, 3, 3, 3, 3, 0),
|
||||
(0, 1, 2, 1, 1, 2, 2, 1, 0),
|
||||
(0, 2, 2, 2, 1, 2, 2, 1, 0),
|
||||
(0, 0, 2, 2, 2, 2, 2, 1, 0),
|
||||
(0, 3, 3, 2, 1, 1, 1, 2, 0),
|
||||
(0, 3, 3, 2, 2, 1, 1, 2, 0),
|
||||
(0, 2, 1, 2, 1, 2, 1, 2, 0),
|
||||
(0, 3, 3, 3, 2, 2, 2, 2, 0),
|
||||
),
|
||||
(
|
||||
(0, 0, 0, 0, 0, 0, 0, 1, 0),
|
||||
(0, 0, 0, 2, 2, 2, 1, 1, 0),
|
||||
(0, 0, 2, 1, 1, 2, 2, 1, 0),
|
||||
(1, 1, 2, 2, 1, 2, 2, 1, 0),
|
||||
(0, 0, 2, 1, 2, 2, 2, 1, 0),
|
||||
(0, 1, 2, 2, 2, 2, 2, 1, 0),
|
||||
(0, 0, 0, 2, 2, 2, 1, 2, 0),
|
||||
(0, 0, 0, 2, 2, 2, 2, 2, 0),
|
||||
),
|
||||
(
|
||||
(0, 0, 0, 0, 0, 0, 0, 1, 0),
|
||||
(0, 0, 0, 2, 2, 2, 1, 1, 0),
|
||||
(2, 2, 2, 1, 0, 2, 1, 0, 0),
|
||||
(2, 1, 1, 2, 1, 1, 1, 2, 0),
|
||||
(2, 2, 2, 1, 1, 1, 0, 2, 0),
|
||||
(2, 2, 2, 1, 1, 2, 1, 2, 0),
|
||||
(0, 0, 0, 0, 2, 1, 2, 2, 0),
|
||||
(0, 0, 0, 0, 2, 2, 2, 2, 0),
|
||||
),
|
||||
)
|
||||
238
esphome/components/inkplate/display.py
Normal file
238
esphome/components/inkplate/display.py
Normal file
@@ -0,0 +1,238 @@
|
||||
from esphome import pins
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import display, i2c
|
||||
from esphome.components.esp32 import CONF_CPU_FREQUENCY
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
CONF_FULL_UPDATE_EVERY,
|
||||
CONF_ID,
|
||||
CONF_LAMBDA,
|
||||
CONF_MIRROR_X,
|
||||
CONF_MIRROR_Y,
|
||||
CONF_MODEL,
|
||||
CONF_OE_PIN,
|
||||
CONF_PAGES,
|
||||
CONF_TRANSFORM,
|
||||
CONF_WAKEUP_PIN,
|
||||
PLATFORM_ESP32,
|
||||
)
|
||||
import esphome.final_validate as fv
|
||||
|
||||
from .const import INKPLATE_10_CUSTOM_WAVEFORMS, WAVEFORMS
|
||||
|
||||
DEPENDENCIES = ["i2c", "esp32"]
|
||||
AUTO_LOAD = ["psram"]
|
||||
|
||||
CONF_DISPLAY_DATA_0_PIN = "display_data_0_pin"
|
||||
CONF_DISPLAY_DATA_1_PIN = "display_data_1_pin"
|
||||
CONF_DISPLAY_DATA_2_PIN = "display_data_2_pin"
|
||||
CONF_DISPLAY_DATA_3_PIN = "display_data_3_pin"
|
||||
CONF_DISPLAY_DATA_4_PIN = "display_data_4_pin"
|
||||
CONF_DISPLAY_DATA_5_PIN = "display_data_5_pin"
|
||||
CONF_DISPLAY_DATA_6_PIN = "display_data_6_pin"
|
||||
CONF_DISPLAY_DATA_7_PIN = "display_data_7_pin"
|
||||
|
||||
CONF_CL_PIN = "cl_pin"
|
||||
CONF_CKV_PIN = "ckv_pin"
|
||||
CONF_GREYSCALE = "greyscale"
|
||||
CONF_GMOD_PIN = "gmod_pin"
|
||||
CONF_GPIO0_ENABLE_PIN = "gpio0_enable_pin"
|
||||
CONF_LE_PIN = "le_pin"
|
||||
CONF_PARTIAL_UPDATING = "partial_updating"
|
||||
CONF_POWERUP_PIN = "powerup_pin"
|
||||
CONF_SPH_PIN = "sph_pin"
|
||||
CONF_SPV_PIN = "spv_pin"
|
||||
CONF_VCOM_PIN = "vcom_pin"
|
||||
|
||||
inkplate_ns = cg.esphome_ns.namespace("inkplate")
|
||||
Inkplate = inkplate_ns.class_(
|
||||
"Inkplate",
|
||||
cg.PollingComponent,
|
||||
i2c.I2CDevice,
|
||||
display.Display,
|
||||
display.DisplayBuffer,
|
||||
)
|
||||
|
||||
InkplateModel = inkplate_ns.enum("InkplateModel")
|
||||
|
||||
MODELS = {
|
||||
"inkplate_6": InkplateModel.INKPLATE_6,
|
||||
"inkplate_10": InkplateModel.INKPLATE_10,
|
||||
"inkplate_6_plus": InkplateModel.INKPLATE_6_PLUS,
|
||||
"inkplate_6_v2": InkplateModel.INKPLATE_6_V2,
|
||||
"inkplate_5": InkplateModel.INKPLATE_5,
|
||||
"inkplate_5_v2": InkplateModel.INKPLATE_5_V2,
|
||||
}
|
||||
|
||||
CONF_CUSTOM_WAVEFORM = "custom_waveform"
|
||||
|
||||
|
||||
def _validate_custom_waveform(config):
|
||||
if CONF_CUSTOM_WAVEFORM in config and config[CONF_MODEL] != "inkplate_10":
|
||||
raise cv.Invalid("Custom waveforms are only supported on the Inkplate 10")
|
||||
return config
|
||||
|
||||
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
display.FULL_DISPLAY_SCHEMA.extend(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(Inkplate),
|
||||
cv.Optional(CONF_GREYSCALE, default=False): cv.boolean,
|
||||
cv.Optional(CONF_CUSTOM_WAVEFORM): cv.All(
|
||||
cv.uint8_t, cv.Range(min=1, max=len(INKPLATE_10_CUSTOM_WAVEFORMS))
|
||||
),
|
||||
cv.Optional(CONF_TRANSFORM): cv.Schema(
|
||||
{
|
||||
cv.Optional(CONF_MIRROR_X, default=False): cv.boolean,
|
||||
cv.Optional(CONF_MIRROR_Y, default=False): cv.boolean,
|
||||
}
|
||||
),
|
||||
cv.Optional(CONF_PARTIAL_UPDATING, default=True): cv.boolean,
|
||||
cv.Optional(CONF_FULL_UPDATE_EVERY, default=10): cv.uint32_t,
|
||||
cv.Optional(CONF_MODEL, default="inkplate_6"): cv.enum(
|
||||
MODELS, lower=True, space="_"
|
||||
),
|
||||
# Control pins
|
||||
cv.Required(CONF_CKV_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Required(CONF_GMOD_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Required(CONF_GPIO0_ENABLE_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Required(CONF_OE_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Required(CONF_POWERUP_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Required(CONF_SPH_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Required(CONF_SPV_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Required(CONF_VCOM_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Required(CONF_WAKEUP_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Optional(CONF_CL_PIN, default=0): pins.internal_gpio_output_pin_schema,
|
||||
cv.Optional(CONF_LE_PIN, default=2): pins.internal_gpio_output_pin_schema,
|
||||
# Data pins
|
||||
cv.Optional(
|
||||
CONF_DISPLAY_DATA_0_PIN, default=4
|
||||
): pins.internal_gpio_output_pin_schema,
|
||||
cv.Optional(
|
||||
CONF_DISPLAY_DATA_1_PIN, default=5
|
||||
): pins.internal_gpio_output_pin_schema,
|
||||
cv.Optional(
|
||||
CONF_DISPLAY_DATA_2_PIN, default=18
|
||||
): pins.internal_gpio_output_pin_schema,
|
||||
cv.Optional(
|
||||
CONF_DISPLAY_DATA_3_PIN, default=19
|
||||
): pins.internal_gpio_output_pin_schema,
|
||||
cv.Optional(
|
||||
CONF_DISPLAY_DATA_4_PIN, default=23
|
||||
): pins.internal_gpio_output_pin_schema,
|
||||
cv.Optional(
|
||||
CONF_DISPLAY_DATA_5_PIN, default=25
|
||||
): pins.internal_gpio_output_pin_schema,
|
||||
cv.Optional(
|
||||
CONF_DISPLAY_DATA_6_PIN, default=26
|
||||
): pins.internal_gpio_output_pin_schema,
|
||||
cv.Optional(
|
||||
CONF_DISPLAY_DATA_7_PIN, default=27
|
||||
): pins.internal_gpio_output_pin_schema,
|
||||
}
|
||||
)
|
||||
.extend(cv.polling_component_schema("5s"))
|
||||
.extend(i2c.i2c_device_schema(0x48)),
|
||||
cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA),
|
||||
_validate_custom_waveform,
|
||||
)
|
||||
|
||||
|
||||
def _validate_cpu_frequency(config):
|
||||
esp32_config = fv.full_config.get()[PLATFORM_ESP32]
|
||||
if esp32_config[CONF_CPU_FREQUENCY] != "240MHZ":
|
||||
raise cv.Invalid(
|
||||
"Inkplate requires 240MHz CPU frequency (set in esp32 component)"
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
FINAL_VALIDATE_SCHEMA = _validate_cpu_frequency
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
|
||||
await display.register_display(var, config)
|
||||
await i2c.register_i2c_device(var, config)
|
||||
|
||||
if CONF_LAMBDA in config:
|
||||
lambda_ = await cg.process_lambda(
|
||||
config[CONF_LAMBDA], [(display.DisplayRef, "it")], return_type=cg.void
|
||||
)
|
||||
cg.add(var.set_writer(lambda_))
|
||||
|
||||
cg.add(var.set_greyscale(config[CONF_GREYSCALE]))
|
||||
if transform := config.get(CONF_TRANSFORM):
|
||||
cg.add(var.set_mirror_x(transform[CONF_MIRROR_X]))
|
||||
cg.add(var.set_mirror_y(transform[CONF_MIRROR_Y]))
|
||||
cg.add(var.set_partial_updating(config[CONF_PARTIAL_UPDATING]))
|
||||
cg.add(var.set_full_update_every(config[CONF_FULL_UPDATE_EVERY]))
|
||||
|
||||
cg.add(var.set_model(config[CONF_MODEL]))
|
||||
|
||||
if custom_waveform := config.get(CONF_CUSTOM_WAVEFORM):
|
||||
waveform = INKPLATE_10_CUSTOM_WAVEFORMS[custom_waveform - 1]
|
||||
waveform = [element for tupl in waveform for element in tupl]
|
||||
cg.add(var.set_waveform(waveform, True))
|
||||
else:
|
||||
waveform = WAVEFORMS[config[CONF_MODEL]]
|
||||
waveform = [element for tupl in waveform for element in tupl]
|
||||
cg.add(var.set_waveform(waveform, False))
|
||||
|
||||
ckv = await cg.gpio_pin_expression(config[CONF_CKV_PIN])
|
||||
cg.add(var.set_ckv_pin(ckv))
|
||||
|
||||
gmod = await cg.gpio_pin_expression(config[CONF_GMOD_PIN])
|
||||
cg.add(var.set_gmod_pin(gmod))
|
||||
|
||||
gpio0_enable = await cg.gpio_pin_expression(config[CONF_GPIO0_ENABLE_PIN])
|
||||
cg.add(var.set_gpio0_enable_pin(gpio0_enable))
|
||||
|
||||
oe = await cg.gpio_pin_expression(config[CONF_OE_PIN])
|
||||
cg.add(var.set_oe_pin(oe))
|
||||
|
||||
powerup = await cg.gpio_pin_expression(config[CONF_POWERUP_PIN])
|
||||
cg.add(var.set_powerup_pin(powerup))
|
||||
|
||||
sph = await cg.gpio_pin_expression(config[CONF_SPH_PIN])
|
||||
cg.add(var.set_sph_pin(sph))
|
||||
|
||||
spv = await cg.gpio_pin_expression(config[CONF_SPV_PIN])
|
||||
cg.add(var.set_spv_pin(spv))
|
||||
|
||||
vcom = await cg.gpio_pin_expression(config[CONF_VCOM_PIN])
|
||||
cg.add(var.set_vcom_pin(vcom))
|
||||
|
||||
wakeup = await cg.gpio_pin_expression(config[CONF_WAKEUP_PIN])
|
||||
cg.add(var.set_wakeup_pin(wakeup))
|
||||
|
||||
cl = await cg.gpio_pin_expression(config[CONF_CL_PIN])
|
||||
cg.add(var.set_cl_pin(cl))
|
||||
|
||||
le = await cg.gpio_pin_expression(config[CONF_LE_PIN])
|
||||
cg.add(var.set_le_pin(le))
|
||||
|
||||
display_data_0 = await cg.gpio_pin_expression(config[CONF_DISPLAY_DATA_0_PIN])
|
||||
cg.add(var.set_display_data_0_pin(display_data_0))
|
||||
|
||||
display_data_1 = await cg.gpio_pin_expression(config[CONF_DISPLAY_DATA_1_PIN])
|
||||
cg.add(var.set_display_data_1_pin(display_data_1))
|
||||
|
||||
display_data_2 = await cg.gpio_pin_expression(config[CONF_DISPLAY_DATA_2_PIN])
|
||||
cg.add(var.set_display_data_2_pin(display_data_2))
|
||||
|
||||
display_data_3 = await cg.gpio_pin_expression(config[CONF_DISPLAY_DATA_3_PIN])
|
||||
cg.add(var.set_display_data_3_pin(display_data_3))
|
||||
|
||||
display_data_4 = await cg.gpio_pin_expression(config[CONF_DISPLAY_DATA_4_PIN])
|
||||
cg.add(var.set_display_data_4_pin(display_data_4))
|
||||
|
||||
display_data_5 = await cg.gpio_pin_expression(config[CONF_DISPLAY_DATA_5_PIN])
|
||||
cg.add(var.set_display_data_5_pin(display_data_5))
|
||||
|
||||
display_data_6 = await cg.gpio_pin_expression(config[CONF_DISPLAY_DATA_6_PIN])
|
||||
cg.add(var.set_display_data_6_pin(display_data_6))
|
||||
|
||||
display_data_7 = await cg.gpio_pin_expression(config[CONF_DISPLAY_DATA_7_PIN])
|
||||
cg.add(var.set_display_data_7_pin(display_data_7))
|
||||
@@ -6,11 +6,11 @@
|
||||
#include <hal/gpio_hal.h>
|
||||
|
||||
namespace esphome {
|
||||
namespace inkplate6 {
|
||||
namespace inkplate {
|
||||
|
||||
static const char *const TAG = "inkplate";
|
||||
|
||||
void Inkplate6::setup() {
|
||||
void Inkplate::setup() {
|
||||
for (uint32_t i = 0; i < 256; i++) {
|
||||
this->pin_lut_[i] = ((i & 0b00000011) << 4) | (((i & 0b00001100) >> 2) << 18) | (((i & 0b00010000) >> 4) << 23) |
|
||||
(((i & 0b11100000) >> 5) << 25);
|
||||
@@ -56,7 +56,7 @@ void Inkplate6::setup() {
|
||||
/**
|
||||
* Allocate buffers. May be called after setup to re-initialise if e.g. greyscale is changed.
|
||||
*/
|
||||
void Inkplate6::initialize_() {
|
||||
void Inkplate::initialize_() {
|
||||
RAMAllocator<uint8_t> allocator;
|
||||
RAMAllocator<uint32_t> allocator32;
|
||||
uint32_t buffer_size = this->get_buffer_length_();
|
||||
@@ -81,29 +81,25 @@ void Inkplate6::initialize_() {
|
||||
return;
|
||||
}
|
||||
if (this->greyscale_) {
|
||||
uint8_t glut_size = 9;
|
||||
|
||||
this->glut_ = allocator32.allocate(256 * glut_size);
|
||||
this->glut_ = allocator32.allocate(256 * GLUT_SIZE);
|
||||
if (this->glut_ == nullptr) {
|
||||
ESP_LOGE(TAG, "Could not allocate glut!");
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
this->glut2_ = allocator32.allocate(256 * glut_size);
|
||||
this->glut2_ = allocator32.allocate(256 * GLUT_SIZE);
|
||||
if (this->glut2_ == nullptr) {
|
||||
ESP_LOGE(TAG, "Could not allocate glut2!");
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
|
||||
const auto *const waveform3_bit = waveform3BitAll[this->model_];
|
||||
|
||||
for (int i = 0; i < glut_size; i++) {
|
||||
for (uint8_t i = 0; i < GLUT_SIZE; i++) {
|
||||
for (uint32_t j = 0; j < 256; j++) {
|
||||
uint8_t z = (waveform3_bit[j & 0x07][i] << 2) | (waveform3_bit[(j >> 4) & 0x07][i]);
|
||||
uint8_t z = (this->waveform_[j & 0x07][i] << 2) | (this->waveform_[(j >> 4) & 0x07][i]);
|
||||
this->glut_[i * 256 + j] = ((z & 0b00000011) << 4) | (((z & 0b00001100) >> 2) << 18) |
|
||||
(((z & 0b00010000) >> 4) << 23) | (((z & 0b11100000) >> 5) << 25);
|
||||
z = ((waveform3_bit[j & 0x07][i] << 2) | (waveform3_bit[(j >> 4) & 0x07][i])) << 4;
|
||||
z = ((this->waveform_[j & 0x07][i] << 2) | (this->waveform_[(j >> 4) & 0x07][i])) << 4;
|
||||
this->glut2_[i * 256 + j] = ((z & 0b00000011) << 4) | (((z & 0b00001100) >> 2) << 18) |
|
||||
(((z & 0b00010000) >> 4) << 23) | (((z & 0b11100000) >> 5) << 25);
|
||||
}
|
||||
@@ -130,9 +126,9 @@ void Inkplate6::initialize_() {
|
||||
memset(this->buffer_, 0, buffer_size);
|
||||
}
|
||||
|
||||
float Inkplate6::get_setup_priority() const { return setup_priority::PROCESSOR; }
|
||||
float Inkplate::get_setup_priority() const { return setup_priority::PROCESSOR; }
|
||||
|
||||
size_t Inkplate6::get_buffer_length_() {
|
||||
size_t Inkplate::get_buffer_length_() {
|
||||
if (this->greyscale_) {
|
||||
return size_t(this->get_width_internal()) * size_t(this->get_height_internal()) / 2u;
|
||||
} else {
|
||||
@@ -140,7 +136,7 @@ size_t Inkplate6::get_buffer_length_() {
|
||||
}
|
||||
}
|
||||
|
||||
void Inkplate6::update() {
|
||||
void Inkplate::update() {
|
||||
this->do_update_();
|
||||
|
||||
if (this->full_update_every_ > 0 && this->partial_updates_ >= this->full_update_every_) {
|
||||
@@ -150,7 +146,7 @@ void Inkplate6::update() {
|
||||
this->display();
|
||||
}
|
||||
|
||||
void HOT Inkplate6::draw_absolute_pixel_internal(int x, int y, Color color) {
|
||||
void HOT Inkplate::draw_absolute_pixel_internal(int x, int y, Color color) {
|
||||
if (x >= this->get_width_internal() || y >= this->get_height_internal() || x < 0 || y < 0)
|
||||
return;
|
||||
|
||||
@@ -171,18 +167,18 @@ void HOT Inkplate6::draw_absolute_pixel_internal(int x, int y, Color color) {
|
||||
// uint8_t gs = (uint8_t)(px*7);
|
||||
|
||||
uint8_t gs = ((color.red * 2126 / 10000) + (color.green * 7152 / 10000) + (color.blue * 722 / 10000)) >> 5;
|
||||
this->buffer_[pos] = (pixelMaskGLUT[x_sub] & current) | (x_sub ? gs : gs << 4);
|
||||
this->buffer_[pos] = (PIXEL_MASK_GLUT[x_sub] & current) | (x_sub ? gs : gs << 4);
|
||||
|
||||
} else {
|
||||
int x1 = x / 8;
|
||||
int x_sub = x % 8;
|
||||
uint32_t pos = (x1 + y * (this->get_width_internal() / 8));
|
||||
uint8_t current = this->partial_buffer_[pos];
|
||||
this->partial_buffer_[pos] = (~pixelMaskLUT[x_sub] & current) | (color.is_on() ? 0 : pixelMaskLUT[x_sub]);
|
||||
this->partial_buffer_[pos] = (~PIXEL_MASK_LUT[x_sub] & current) | (color.is_on() ? 0 : PIXEL_MASK_LUT[x_sub]);
|
||||
}
|
||||
}
|
||||
|
||||
void Inkplate6::dump_config() {
|
||||
void Inkplate::dump_config() {
|
||||
LOG_DISPLAY("", "Inkplate", this);
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Greyscale: %s\n"
|
||||
@@ -214,7 +210,7 @@ void Inkplate6::dump_config() {
|
||||
LOG_UPDATE_INTERVAL(this);
|
||||
}
|
||||
|
||||
void Inkplate6::eink_off_() {
|
||||
void Inkplate::eink_off_() {
|
||||
ESP_LOGV(TAG, "Eink off called");
|
||||
if (!panel_on_)
|
||||
return;
|
||||
@@ -242,7 +238,7 @@ void Inkplate6::eink_off_() {
|
||||
pins_z_state_();
|
||||
}
|
||||
|
||||
void Inkplate6::eink_on_() {
|
||||
void Inkplate::eink_on_() {
|
||||
ESP_LOGV(TAG, "Eink on called");
|
||||
if (panel_on_)
|
||||
return;
|
||||
@@ -284,7 +280,7 @@ void Inkplate6::eink_on_() {
|
||||
this->oe_pin_->digital_write(true);
|
||||
}
|
||||
|
||||
bool Inkplate6::read_power_status_() {
|
||||
bool Inkplate::read_power_status_() {
|
||||
uint8_t data;
|
||||
auto err = this->read_register(0x0F, &data, 1);
|
||||
if (err == i2c::ERROR_OK) {
|
||||
@@ -293,7 +289,7 @@ bool Inkplate6::read_power_status_() {
|
||||
return false;
|
||||
}
|
||||
|
||||
void Inkplate6::fill(Color color) {
|
||||
void Inkplate::fill(Color color) {
|
||||
ESP_LOGV(TAG, "Fill called");
|
||||
uint32_t start_time = millis();
|
||||
|
||||
@@ -308,7 +304,7 @@ void Inkplate6::fill(Color color) {
|
||||
ESP_LOGV(TAG, "Fill finished (%ums)", millis() - start_time);
|
||||
}
|
||||
|
||||
void Inkplate6::display() {
|
||||
void Inkplate::display() {
|
||||
ESP_LOGV(TAG, "Display called");
|
||||
uint32_t start_time = millis();
|
||||
|
||||
@@ -324,7 +320,7 @@ void Inkplate6::display() {
|
||||
ESP_LOGV(TAG, "Display finished (full) (%ums)", millis() - start_time);
|
||||
}
|
||||
|
||||
void Inkplate6::display1b_() {
|
||||
void Inkplate::display1b_() {
|
||||
ESP_LOGV(TAG, "Display1b called");
|
||||
uint32_t start_time = millis();
|
||||
|
||||
@@ -334,32 +330,71 @@ void Inkplate6::display1b_() {
|
||||
uint8_t buffer_value;
|
||||
const uint8_t *buffer_ptr;
|
||||
eink_on_();
|
||||
if (this->model_ == INKPLATE_6_PLUS) {
|
||||
clean_fast_(0, 1);
|
||||
clean_fast_(1, 15);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 5);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(1, 15);
|
||||
} else {
|
||||
clean_fast_(0, 1);
|
||||
clean_fast_(1, 21);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 12);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(1, 21);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 12);
|
||||
clean_fast_(2, 1);
|
||||
uint8_t rep = 4;
|
||||
switch (this->model_) {
|
||||
case INKPLATE_10:
|
||||
clean_fast_(0, 1);
|
||||
clean_fast_(1, 10);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 10);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(1, 10);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 10);
|
||||
rep = 5;
|
||||
break;
|
||||
case INKPLATE_6_PLUS:
|
||||
clean_fast_(0, 1);
|
||||
clean_fast_(1, 15);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 5);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(1, 15);
|
||||
break;
|
||||
case INKPLATE_6:
|
||||
case INKPLATE_6_V2:
|
||||
clean_fast_(0, 1);
|
||||
clean_fast_(1, 18);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 18);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(1, 18);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 18);
|
||||
clean_fast_(2, 1);
|
||||
if (this->model_ == INKPLATE_6_V2)
|
||||
rep = 5;
|
||||
break;
|
||||
case INKPLATE_5:
|
||||
clean_fast_(0, 1);
|
||||
clean_fast_(1, 14);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 14);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(1, 14);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 14);
|
||||
clean_fast_(2, 1);
|
||||
rep = 5;
|
||||
break;
|
||||
case INKPLATE_5_V2:
|
||||
clean_fast_(0, 1);
|
||||
clean_fast_(1, 11);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 11);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(1, 11);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 11);
|
||||
rep = 3;
|
||||
break;
|
||||
}
|
||||
|
||||
uint32_t clock = (1 << this->cl_pin_->get_pin());
|
||||
uint32_t data_mask = this->get_data_pin_mask_();
|
||||
ESP_LOGV(TAG, "Display1b start loops (%ums)", millis() - start_time);
|
||||
|
||||
int rep = (this->model_ == INKPLATE_6_V2) ? 5 : 4;
|
||||
|
||||
for (int k = 0; k < rep; k++) {
|
||||
for (uint8_t k = 0; k < rep; k++) {
|
||||
buffer_ptr = &this->buffer_[this->get_buffer_length_() - 1];
|
||||
vscan_start_();
|
||||
for (int i = 0, im = this->get_height_internal(); i < im; i++) {
|
||||
@@ -452,28 +487,75 @@ void Inkplate6::display1b_() {
|
||||
ESP_LOGV(TAG, "Display1b finished (%ums)", millis() - start_time);
|
||||
}
|
||||
|
||||
void Inkplate6::display3b_() {
|
||||
void Inkplate::display3b_() {
|
||||
ESP_LOGV(TAG, "Display3b called");
|
||||
uint32_t start_time = millis();
|
||||
|
||||
eink_on_();
|
||||
if (this->model_ == INKPLATE_6_PLUS) {
|
||||
clean_fast_(0, 1);
|
||||
clean_fast_(1, 15);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 5);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(1, 15);
|
||||
} else {
|
||||
clean_fast_(0, 1);
|
||||
clean_fast_(1, 21);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 12);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(1, 21);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 12);
|
||||
clean_fast_(2, 1);
|
||||
|
||||
switch (this->model_) {
|
||||
case INKPLATE_10:
|
||||
if (this->custom_waveform_) {
|
||||
clean_fast_(1, 1);
|
||||
clean_fast_(0, 7);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(1, 12);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 7);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(1, 12);
|
||||
} else {
|
||||
clean_fast_(1, 1);
|
||||
clean_fast_(0, 10);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(1, 10);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 10);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(1, 10);
|
||||
}
|
||||
break;
|
||||
case INKPLATE_6_PLUS:
|
||||
clean_fast_(0, 1);
|
||||
clean_fast_(1, 15);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 5);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(1, 15);
|
||||
break;
|
||||
case INKPLATE_6:
|
||||
case INKPLATE_6_V2:
|
||||
clean_fast_(0, 1);
|
||||
clean_fast_(1, 18);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 18);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(1, 18);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 18);
|
||||
clean_fast_(2, 1);
|
||||
break;
|
||||
case INKPLATE_5:
|
||||
clean_fast_(0, 1);
|
||||
clean_fast_(1, 14);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 14);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(1, 14);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 14);
|
||||
clean_fast_(2, 1);
|
||||
break;
|
||||
case INKPLATE_5_V2:
|
||||
clean_fast_(0, 1);
|
||||
clean_fast_(1, 11);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 11);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(1, 11);
|
||||
clean_fast_(2, 1);
|
||||
clean_fast_(0, 11);
|
||||
break;
|
||||
}
|
||||
|
||||
uint32_t clock = (1 << this->cl_pin_->get_pin());
|
||||
@@ -518,7 +600,7 @@ void Inkplate6::display3b_() {
|
||||
ESP_LOGV(TAG, "Display3b finished (%ums)", millis() - start_time);
|
||||
}
|
||||
|
||||
bool Inkplate6::partial_update_() {
|
||||
bool Inkplate::partial_update_() {
|
||||
ESP_LOGV(TAG, "Partial update called");
|
||||
uint32_t start_time = millis();
|
||||
if (this->greyscale_)
|
||||
@@ -560,7 +642,7 @@ bool Inkplate6::partial_update_() {
|
||||
GPIO.out_w1ts = this->pin_lut_[data] | clock;
|
||||
GPIO.out_w1tc = data_mask | clock;
|
||||
}
|
||||
// New Inkplate6 panel doesn't need last clock
|
||||
// New Inkplate panel doesn't need last clock
|
||||
if (this->model_ != INKPLATE_6_V2) {
|
||||
GPIO.out_w1ts = clock;
|
||||
GPIO.out_w1tc = data_mask | clock;
|
||||
@@ -580,7 +662,7 @@ bool Inkplate6::partial_update_() {
|
||||
return true;
|
||||
}
|
||||
|
||||
void Inkplate6::vscan_start_() {
|
||||
void Inkplate::vscan_start_() {
|
||||
this->ckv_pin_->digital_write(true);
|
||||
delayMicroseconds(7);
|
||||
this->spv_pin_->digital_write(false);
|
||||
@@ -604,7 +686,7 @@ void Inkplate6::vscan_start_() {
|
||||
this->ckv_pin_->digital_write(true);
|
||||
}
|
||||
|
||||
void Inkplate6::hscan_start_(uint32_t d) {
|
||||
void Inkplate::hscan_start_(uint32_t d) {
|
||||
uint8_t clock = (1 << this->cl_pin_->get_pin());
|
||||
this->sph_pin_->digital_write(false);
|
||||
GPIO.out_w1ts = d | clock;
|
||||
@@ -613,14 +695,14 @@ void Inkplate6::hscan_start_(uint32_t d) {
|
||||
this->ckv_pin_->digital_write(true);
|
||||
}
|
||||
|
||||
void Inkplate6::vscan_end_() {
|
||||
void Inkplate::vscan_end_() {
|
||||
this->ckv_pin_->digital_write(false);
|
||||
this->le_pin_->digital_write(true);
|
||||
this->le_pin_->digital_write(false);
|
||||
delayMicroseconds(0);
|
||||
}
|
||||
|
||||
void Inkplate6::clean() {
|
||||
void Inkplate::clean() {
|
||||
ESP_LOGV(TAG, "Clean called");
|
||||
uint32_t start_time = millis();
|
||||
|
||||
@@ -634,7 +716,7 @@ void Inkplate6::clean() {
|
||||
ESP_LOGV(TAG, "Clean finished (%ums)", millis() - start_time);
|
||||
}
|
||||
|
||||
void Inkplate6::clean_fast_(uint8_t c, uint8_t rep) {
|
||||
void Inkplate::clean_fast_(uint8_t c, uint8_t rep) {
|
||||
ESP_LOGV(TAG, "Clean fast called with: (%d, %d)", c, rep);
|
||||
uint32_t start_time = millis();
|
||||
|
||||
@@ -666,7 +748,7 @@ void Inkplate6::clean_fast_(uint8_t c, uint8_t rep) {
|
||||
GPIO.out_w1ts = clock;
|
||||
GPIO.out_w1tc = clock;
|
||||
}
|
||||
// New Inkplate6 panel doesn't need last clock
|
||||
// New Inkplate panel doesn't need last clock
|
||||
if (this->model_ != INKPLATE_6_V2) {
|
||||
GPIO.out_w1ts = send | clock;
|
||||
GPIO.out_w1tc = clock;
|
||||
@@ -679,7 +761,7 @@ void Inkplate6::clean_fast_(uint8_t c, uint8_t rep) {
|
||||
ESP_LOGV(TAG, "Clean fast finished (%ums)", millis() - start_time);
|
||||
}
|
||||
|
||||
void Inkplate6::pins_z_state_() {
|
||||
void Inkplate::pins_z_state_() {
|
||||
this->cl_pin_->pin_mode(gpio::FLAG_INPUT);
|
||||
this->le_pin_->pin_mode(gpio::FLAG_INPUT);
|
||||
this->ckv_pin_->pin_mode(gpio::FLAG_INPUT);
|
||||
@@ -699,7 +781,7 @@ void Inkplate6::pins_z_state_() {
|
||||
this->display_data_7_pin_->pin_mode(gpio::FLAG_INPUT);
|
||||
}
|
||||
|
||||
void Inkplate6::pins_as_outputs_() {
|
||||
void Inkplate::pins_as_outputs_() {
|
||||
this->cl_pin_->pin_mode(gpio::FLAG_OUTPUT);
|
||||
this->le_pin_->pin_mode(gpio::FLAG_OUTPUT);
|
||||
this->ckv_pin_->pin_mode(gpio::FLAG_OUTPUT);
|
||||
@@ -719,5 +801,5 @@ void Inkplate6::pins_as_outputs_() {
|
||||
this->display_data_7_pin_->pin_mode(gpio::FLAG_OUTPUT);
|
||||
}
|
||||
|
||||
} // namespace inkplate6
|
||||
} // namespace inkplate
|
||||
} // namespace esphome
|
||||
@@ -5,8 +5,10 @@
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/hal.h"
|
||||
|
||||
#include <array>
|
||||
|
||||
namespace esphome {
|
||||
namespace inkplate6 {
|
||||
namespace inkplate {
|
||||
|
||||
enum InkplateModel : uint8_t {
|
||||
INKPLATE_6 = 0,
|
||||
@@ -17,79 +19,35 @@ enum InkplateModel : uint8_t {
|
||||
INKPLATE_5_V2 = 5,
|
||||
};
|
||||
|
||||
class Inkplate6 : public display::DisplayBuffer, public i2c::I2CDevice {
|
||||
static constexpr uint8_t GLUT_SIZE = 9;
|
||||
static constexpr uint8_t GLUT_COUNT = 8;
|
||||
|
||||
static constexpr uint8_t LUT2[16] = {0xAA, 0xA9, 0xA6, 0xA5, 0x9A, 0x99, 0x96, 0x95,
|
||||
0x6A, 0x69, 0x66, 0x65, 0x5A, 0x59, 0x56, 0x55};
|
||||
static constexpr uint8_t LUTW[16] = {0xFF, 0xFE, 0xFB, 0xFA, 0xEF, 0xEE, 0xEB, 0xEA,
|
||||
0xBF, 0xBE, 0xBB, 0xBA, 0xAF, 0xAE, 0xAB, 0xAA};
|
||||
static constexpr uint8_t LUTB[16] = {0xFF, 0xFD, 0xF7, 0xF5, 0xDF, 0xDD, 0xD7, 0xD5,
|
||||
0x7F, 0x7D, 0x77, 0x75, 0x5F, 0x5D, 0x57, 0x55};
|
||||
|
||||
static constexpr uint8_t PIXEL_MASK_LUT[8] = {0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80};
|
||||
static constexpr uint8_t PIXEL_MASK_GLUT[2] = {0x0F, 0xF0};
|
||||
|
||||
class Inkplate : public display::DisplayBuffer, public i2c::I2CDevice {
|
||||
public:
|
||||
const uint8_t LUT2[16] = {0xAA, 0xA9, 0xA6, 0xA5, 0x9A, 0x99, 0x96, 0x95,
|
||||
0x6A, 0x69, 0x66, 0x65, 0x5A, 0x59, 0x56, 0x55};
|
||||
const uint8_t LUTW[16] = {0xFF, 0xFE, 0xFB, 0xFA, 0xEF, 0xEE, 0xEB, 0xEA,
|
||||
0xBF, 0xBE, 0xBB, 0xBA, 0xAF, 0xAE, 0xAB, 0xAA};
|
||||
const uint8_t LUTB[16] = {0xFF, 0xFD, 0xF7, 0xF5, 0xDF, 0xDD, 0xD7, 0xD5,
|
||||
0x7F, 0x7D, 0x77, 0x75, 0x5F, 0x5D, 0x57, 0x55};
|
||||
|
||||
const uint8_t pixelMaskLUT[8] = {0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80};
|
||||
const uint8_t pixelMaskGLUT[2] = {0x0F, 0xF0};
|
||||
|
||||
const uint8_t waveform3BitAll[6][8][9] = {// INKPLATE_6
|
||||
{{0, 1, 1, 0, 0, 1, 1, 0, 0},
|
||||
{0, 1, 2, 1, 1, 2, 1, 0, 0},
|
||||
{1, 1, 1, 2, 2, 1, 0, 0, 0},
|
||||
{0, 0, 0, 1, 1, 1, 2, 0, 0},
|
||||
{2, 1, 1, 1, 2, 1, 2, 0, 0},
|
||||
{2, 2, 1, 1, 2, 1, 2, 0, 0},
|
||||
{1, 1, 1, 2, 1, 2, 2, 0, 0},
|
||||
{0, 0, 0, 0, 0, 0, 2, 0, 0}},
|
||||
// INKPLATE_10
|
||||
{{0, 0, 0, 0, 0, 0, 0, 1, 0},
|
||||
{0, 0, 0, 2, 2, 2, 1, 1, 0},
|
||||
{0, 0, 2, 1, 1, 2, 2, 1, 0},
|
||||
{0, 1, 2, 2, 1, 2, 2, 1, 0},
|
||||
{0, 0, 2, 1, 2, 2, 2, 1, 0},
|
||||
{0, 2, 2, 2, 2, 2, 2, 1, 0},
|
||||
{0, 0, 0, 0, 0, 2, 1, 2, 0},
|
||||
{0, 0, 0, 2, 2, 2, 2, 2, 0}},
|
||||
// INKPLATE_6_PLUS
|
||||
{{0, 0, 0, 0, 0, 2, 1, 1, 0},
|
||||
{0, 0, 2, 1, 1, 1, 2, 1, 0},
|
||||
{0, 2, 2, 2, 1, 1, 2, 1, 0},
|
||||
{0, 0, 2, 2, 2, 1, 2, 1, 0},
|
||||
{0, 0, 0, 0, 2, 2, 2, 1, 0},
|
||||
{0, 0, 2, 1, 2, 1, 1, 2, 0},
|
||||
{0, 0, 2, 2, 2, 1, 1, 2, 0},
|
||||
{0, 0, 0, 0, 2, 2, 2, 2, 0}},
|
||||
// INKPLATE_6_V2
|
||||
{{1, 0, 1, 0, 1, 1, 1, 0, 0},
|
||||
{0, 0, 0, 1, 1, 1, 1, 0, 0},
|
||||
{1, 1, 1, 1, 0, 2, 1, 0, 0},
|
||||
{1, 1, 1, 2, 2, 1, 1, 0, 0},
|
||||
{1, 1, 1, 1, 2, 2, 1, 0, 0},
|
||||
{0, 1, 1, 1, 2, 2, 1, 0, 0},
|
||||
{0, 0, 0, 0, 1, 1, 2, 0, 0},
|
||||
{0, 0, 0, 0, 0, 1, 2, 0, 0}},
|
||||
// INKPLATE_5
|
||||
{{0, 0, 1, 1, 0, 1, 1, 1, 0},
|
||||
{0, 1, 1, 1, 1, 2, 0, 1, 0},
|
||||
{1, 2, 2, 0, 2, 1, 1, 1, 0},
|
||||
{1, 1, 1, 2, 0, 1, 1, 2, 0},
|
||||
{0, 1, 1, 1, 2, 0, 1, 2, 0},
|
||||
{0, 0, 0, 1, 1, 2, 1, 2, 0},
|
||||
{1, 1, 1, 2, 0, 2, 1, 2, 0},
|
||||
{0, 0, 0, 0, 0, 0, 0, 0, 0}},
|
||||
// INKPLATE_5_V2
|
||||
{{0, 0, 1, 1, 2, 1, 1, 1, 0},
|
||||
{1, 1, 2, 2, 1, 2, 1, 1, 0},
|
||||
{0, 1, 2, 2, 1, 1, 2, 1, 0},
|
||||
{0, 0, 1, 1, 1, 1, 1, 2, 0},
|
||||
{1, 2, 1, 2, 1, 1, 1, 2, 0},
|
||||
{0, 1, 1, 1, 2, 0, 1, 2, 0},
|
||||
{1, 1, 1, 2, 2, 2, 1, 2, 0},
|
||||
{0, 0, 0, 0, 0, 0, 0, 0, 0}}};
|
||||
|
||||
void set_greyscale(bool greyscale) {
|
||||
this->greyscale_ = greyscale;
|
||||
this->block_partial_ = true;
|
||||
if (this->is_ready())
|
||||
this->initialize_();
|
||||
}
|
||||
|
||||
void set_waveform(const std::array<uint8_t, GLUT_COUNT * GLUT_SIZE> &waveform, bool is_custom) {
|
||||
static_assert(sizeof(this->waveform_) == sizeof(uint8_t) * GLUT_COUNT * GLUT_SIZE,
|
||||
"waveform_ buffer size must match input waveform array size");
|
||||
memmove(this->waveform_, waveform.data(), sizeof(this->waveform_));
|
||||
this->custom_waveform_ = is_custom;
|
||||
}
|
||||
|
||||
void set_mirror_y(bool mirror_y) { this->mirror_y_ = mirror_y; }
|
||||
void set_mirror_x(bool mirror_x) { this->mirror_x_ = mirror_x; }
|
||||
|
||||
@@ -225,6 +183,8 @@ class Inkplate6 : public display::DisplayBuffer, public i2c::I2CDevice {
|
||||
bool mirror_y_{false};
|
||||
bool mirror_x_{false};
|
||||
bool partial_updating_;
|
||||
bool custom_waveform_{false};
|
||||
uint8_t waveform_[GLUT_COUNT][GLUT_SIZE];
|
||||
|
||||
InkplateModel model_;
|
||||
|
||||
@@ -250,5 +210,5 @@ class Inkplate6 : public display::DisplayBuffer, public i2c::I2CDevice {
|
||||
GPIOPin *wakeup_pin_;
|
||||
};
|
||||
|
||||
} // namespace inkplate6
|
||||
} // namespace inkplate
|
||||
} // namespace esphome
|
||||
@@ -1 +0,0 @@
|
||||
CODEOWNERS = ["@jesserockz"]
|
||||
|
||||
@@ -1,214 +1,5 @@
|
||||
from esphome import pins
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import display, i2c
|
||||
from esphome.components.esp32 import CONF_CPU_FREQUENCY
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
CONF_FULL_UPDATE_EVERY,
|
||||
CONF_ID,
|
||||
CONF_LAMBDA,
|
||||
CONF_MIRROR_X,
|
||||
CONF_MIRROR_Y,
|
||||
CONF_MODEL,
|
||||
CONF_OE_PIN,
|
||||
CONF_PAGES,
|
||||
CONF_TRANSFORM,
|
||||
CONF_WAKEUP_PIN,
|
||||
PLATFORM_ESP32,
|
||||
|
||||
CONFIG_SCHEMA = cv.invalid(
|
||||
"The inkplate6 display component has been renamed to inkplate."
|
||||
)
|
||||
import esphome.final_validate as fv
|
||||
|
||||
DEPENDENCIES = ["i2c", "esp32"]
|
||||
AUTO_LOAD = ["psram"]
|
||||
|
||||
CONF_DISPLAY_DATA_0_PIN = "display_data_0_pin"
|
||||
CONF_DISPLAY_DATA_1_PIN = "display_data_1_pin"
|
||||
CONF_DISPLAY_DATA_2_PIN = "display_data_2_pin"
|
||||
CONF_DISPLAY_DATA_3_PIN = "display_data_3_pin"
|
||||
CONF_DISPLAY_DATA_4_PIN = "display_data_4_pin"
|
||||
CONF_DISPLAY_DATA_5_PIN = "display_data_5_pin"
|
||||
CONF_DISPLAY_DATA_6_PIN = "display_data_6_pin"
|
||||
CONF_DISPLAY_DATA_7_PIN = "display_data_7_pin"
|
||||
|
||||
CONF_CL_PIN = "cl_pin"
|
||||
CONF_CKV_PIN = "ckv_pin"
|
||||
CONF_GREYSCALE = "greyscale"
|
||||
CONF_GMOD_PIN = "gmod_pin"
|
||||
CONF_GPIO0_ENABLE_PIN = "gpio0_enable_pin"
|
||||
CONF_LE_PIN = "le_pin"
|
||||
CONF_PARTIAL_UPDATING = "partial_updating"
|
||||
CONF_POWERUP_PIN = "powerup_pin"
|
||||
CONF_SPH_PIN = "sph_pin"
|
||||
CONF_SPV_PIN = "spv_pin"
|
||||
CONF_VCOM_PIN = "vcom_pin"
|
||||
|
||||
inkplate6_ns = cg.esphome_ns.namespace("inkplate6")
|
||||
Inkplate6 = inkplate6_ns.class_(
|
||||
"Inkplate6",
|
||||
cg.PollingComponent,
|
||||
i2c.I2CDevice,
|
||||
display.Display,
|
||||
display.DisplayBuffer,
|
||||
)
|
||||
|
||||
InkplateModel = inkplate6_ns.enum("InkplateModel")
|
||||
|
||||
MODELS = {
|
||||
"inkplate_6": InkplateModel.INKPLATE_6,
|
||||
"inkplate_10": InkplateModel.INKPLATE_10,
|
||||
"inkplate_6_plus": InkplateModel.INKPLATE_6_PLUS,
|
||||
"inkplate_6_v2": InkplateModel.INKPLATE_6_V2,
|
||||
"inkplate_5": InkplateModel.INKPLATE_5,
|
||||
"inkplate_5_v2": InkplateModel.INKPLATE_5_V2,
|
||||
}
|
||||
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
display.FULL_DISPLAY_SCHEMA.extend(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(Inkplate6),
|
||||
cv.Optional(CONF_GREYSCALE, default=False): cv.boolean,
|
||||
cv.Optional(CONF_TRANSFORM): cv.Schema(
|
||||
{
|
||||
cv.Optional(CONF_MIRROR_X, default=False): cv.boolean,
|
||||
cv.Optional(CONF_MIRROR_Y, default=False): cv.boolean,
|
||||
}
|
||||
),
|
||||
cv.Optional(CONF_PARTIAL_UPDATING, default=True): cv.boolean,
|
||||
cv.Optional(CONF_FULL_UPDATE_EVERY, default=10): cv.uint32_t,
|
||||
cv.Optional(CONF_MODEL, default="inkplate_6"): cv.enum(
|
||||
MODELS, lower=True, space="_"
|
||||
),
|
||||
# Control pins
|
||||
cv.Required(CONF_CKV_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Required(CONF_GMOD_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Required(CONF_GPIO0_ENABLE_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Required(CONF_OE_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Required(CONF_POWERUP_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Required(CONF_SPH_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Required(CONF_SPV_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Required(CONF_VCOM_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Required(CONF_WAKEUP_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Optional(CONF_CL_PIN, default=0): pins.internal_gpio_output_pin_schema,
|
||||
cv.Optional(CONF_LE_PIN, default=2): pins.internal_gpio_output_pin_schema,
|
||||
# Data pins
|
||||
cv.Optional(
|
||||
CONF_DISPLAY_DATA_0_PIN, default=4
|
||||
): pins.internal_gpio_output_pin_schema,
|
||||
cv.Optional(
|
||||
CONF_DISPLAY_DATA_1_PIN, default=5
|
||||
): pins.internal_gpio_output_pin_schema,
|
||||
cv.Optional(
|
||||
CONF_DISPLAY_DATA_2_PIN, default=18
|
||||
): pins.internal_gpio_output_pin_schema,
|
||||
cv.Optional(
|
||||
CONF_DISPLAY_DATA_3_PIN, default=19
|
||||
): pins.internal_gpio_output_pin_schema,
|
||||
cv.Optional(
|
||||
CONF_DISPLAY_DATA_4_PIN, default=23
|
||||
): pins.internal_gpio_output_pin_schema,
|
||||
cv.Optional(
|
||||
CONF_DISPLAY_DATA_5_PIN, default=25
|
||||
): pins.internal_gpio_output_pin_schema,
|
||||
cv.Optional(
|
||||
CONF_DISPLAY_DATA_6_PIN, default=26
|
||||
): pins.internal_gpio_output_pin_schema,
|
||||
cv.Optional(
|
||||
CONF_DISPLAY_DATA_7_PIN, default=27
|
||||
): pins.internal_gpio_output_pin_schema,
|
||||
}
|
||||
)
|
||||
.extend(cv.polling_component_schema("5s"))
|
||||
.extend(i2c.i2c_device_schema(0x48)),
|
||||
cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA),
|
||||
)
|
||||
|
||||
|
||||
def _validate_cpu_frequency(config):
|
||||
esp32_config = fv.full_config.get()[PLATFORM_ESP32]
|
||||
if esp32_config[CONF_CPU_FREQUENCY] != "240MHZ":
|
||||
raise cv.Invalid(
|
||||
"Inkplate requires 240MHz CPU frequency (set in esp32 component)"
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
FINAL_VALIDATE_SCHEMA = _validate_cpu_frequency
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
|
||||
await display.register_display(var, config)
|
||||
await i2c.register_i2c_device(var, config)
|
||||
|
||||
if CONF_LAMBDA in config:
|
||||
lambda_ = await cg.process_lambda(
|
||||
config[CONF_LAMBDA], [(display.DisplayRef, "it")], return_type=cg.void
|
||||
)
|
||||
cg.add(var.set_writer(lambda_))
|
||||
|
||||
cg.add(var.set_greyscale(config[CONF_GREYSCALE]))
|
||||
if transform := config.get(CONF_TRANSFORM):
|
||||
cg.add(var.set_mirror_x(transform[CONF_MIRROR_X]))
|
||||
cg.add(var.set_mirror_y(transform[CONF_MIRROR_Y]))
|
||||
cg.add(var.set_partial_updating(config[CONF_PARTIAL_UPDATING]))
|
||||
cg.add(var.set_full_update_every(config[CONF_FULL_UPDATE_EVERY]))
|
||||
|
||||
cg.add(var.set_model(config[CONF_MODEL]))
|
||||
|
||||
ckv = await cg.gpio_pin_expression(config[CONF_CKV_PIN])
|
||||
cg.add(var.set_ckv_pin(ckv))
|
||||
|
||||
gmod = await cg.gpio_pin_expression(config[CONF_GMOD_PIN])
|
||||
cg.add(var.set_gmod_pin(gmod))
|
||||
|
||||
gpio0_enable = await cg.gpio_pin_expression(config[CONF_GPIO0_ENABLE_PIN])
|
||||
cg.add(var.set_gpio0_enable_pin(gpio0_enable))
|
||||
|
||||
oe = await cg.gpio_pin_expression(config[CONF_OE_PIN])
|
||||
cg.add(var.set_oe_pin(oe))
|
||||
|
||||
powerup = await cg.gpio_pin_expression(config[CONF_POWERUP_PIN])
|
||||
cg.add(var.set_powerup_pin(powerup))
|
||||
|
||||
sph = await cg.gpio_pin_expression(config[CONF_SPH_PIN])
|
||||
cg.add(var.set_sph_pin(sph))
|
||||
|
||||
spv = await cg.gpio_pin_expression(config[CONF_SPV_PIN])
|
||||
cg.add(var.set_spv_pin(spv))
|
||||
|
||||
vcom = await cg.gpio_pin_expression(config[CONF_VCOM_PIN])
|
||||
cg.add(var.set_vcom_pin(vcom))
|
||||
|
||||
wakeup = await cg.gpio_pin_expression(config[CONF_WAKEUP_PIN])
|
||||
cg.add(var.set_wakeup_pin(wakeup))
|
||||
|
||||
cl = await cg.gpio_pin_expression(config[CONF_CL_PIN])
|
||||
cg.add(var.set_cl_pin(cl))
|
||||
|
||||
le = await cg.gpio_pin_expression(config[CONF_LE_PIN])
|
||||
cg.add(var.set_le_pin(le))
|
||||
|
||||
display_data_0 = await cg.gpio_pin_expression(config[CONF_DISPLAY_DATA_0_PIN])
|
||||
cg.add(var.set_display_data_0_pin(display_data_0))
|
||||
|
||||
display_data_1 = await cg.gpio_pin_expression(config[CONF_DISPLAY_DATA_1_PIN])
|
||||
cg.add(var.set_display_data_1_pin(display_data_1))
|
||||
|
||||
display_data_2 = await cg.gpio_pin_expression(config[CONF_DISPLAY_DATA_2_PIN])
|
||||
cg.add(var.set_display_data_2_pin(display_data_2))
|
||||
|
||||
display_data_3 = await cg.gpio_pin_expression(config[CONF_DISPLAY_DATA_3_PIN])
|
||||
cg.add(var.set_display_data_3_pin(display_data_3))
|
||||
|
||||
display_data_4 = await cg.gpio_pin_expression(config[CONF_DISPLAY_DATA_4_PIN])
|
||||
cg.add(var.set_display_data_4_pin(display_data_4))
|
||||
|
||||
display_data_5 = await cg.gpio_pin_expression(config[CONF_DISPLAY_DATA_5_PIN])
|
||||
cg.add(var.set_display_data_5_pin(display_data_5))
|
||||
|
||||
display_data_6 = await cg.gpio_pin_expression(config[CONF_DISPLAY_DATA_6_PIN])
|
||||
cg.add(var.set_display_data_6_pin(display_data_6))
|
||||
|
||||
display_data_7 = await cg.gpio_pin_expression(config[CONF_DISPLAY_DATA_7_PIN])
|
||||
cg.add(var.set_display_data_7_pin(display_data_7))
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include "light_transformer.h"
|
||||
|
||||
#include <vector>
|
||||
#include <strings.h>
|
||||
|
||||
namespace esphome {
|
||||
namespace light {
|
||||
|
||||
@@ -246,14 +246,35 @@ void Logger::add_on_log_callback(std::function<void(uint8_t, const char *, const
|
||||
this->log_callback_.add(std::move(callback));
|
||||
}
|
||||
float Logger::get_setup_priority() const { return setup_priority::BUS + 500.0f; }
|
||||
|
||||
#ifdef USE_STORE_LOG_STR_IN_FLASH
|
||||
// ESP8266: PSTR() cannot be used in array initializers, so we need to declare
|
||||
// each string separately as a global constant first
|
||||
static const char LOG_LEVEL_NONE[] PROGMEM = "NONE";
|
||||
static const char LOG_LEVEL_ERROR[] PROGMEM = "ERROR";
|
||||
static const char LOG_LEVEL_WARN[] PROGMEM = "WARN";
|
||||
static const char LOG_LEVEL_INFO[] PROGMEM = "INFO";
|
||||
static const char LOG_LEVEL_CONFIG[] PROGMEM = "CONFIG";
|
||||
static const char LOG_LEVEL_DEBUG[] PROGMEM = "DEBUG";
|
||||
static const char LOG_LEVEL_VERBOSE[] PROGMEM = "VERBOSE";
|
||||
static const char LOG_LEVEL_VERY_VERBOSE[] PROGMEM = "VERY_VERBOSE";
|
||||
|
||||
static const LogString *const LOG_LEVELS[] = {
|
||||
reinterpret_cast<const LogString *>(LOG_LEVEL_NONE), reinterpret_cast<const LogString *>(LOG_LEVEL_ERROR),
|
||||
reinterpret_cast<const LogString *>(LOG_LEVEL_WARN), reinterpret_cast<const LogString *>(LOG_LEVEL_INFO),
|
||||
reinterpret_cast<const LogString *>(LOG_LEVEL_CONFIG), reinterpret_cast<const LogString *>(LOG_LEVEL_DEBUG),
|
||||
reinterpret_cast<const LogString *>(LOG_LEVEL_VERBOSE), reinterpret_cast<const LogString *>(LOG_LEVEL_VERY_VERBOSE),
|
||||
};
|
||||
#else
|
||||
static const char *const LOG_LEVELS[] = {"NONE", "ERROR", "WARN", "INFO", "CONFIG", "DEBUG", "VERBOSE", "VERY_VERBOSE"};
|
||||
#endif
|
||||
|
||||
void Logger::dump_config() {
|
||||
ESP_LOGCONFIG(TAG,
|
||||
"Logger:\n"
|
||||
" Max Level: %s\n"
|
||||
" Initial Level: %s",
|
||||
LOG_LEVELS[ESPHOME_LOG_LEVEL], LOG_LEVELS[this->current_level_]);
|
||||
LOG_STR_ARG(LOG_LEVELS[ESPHOME_LOG_LEVEL]), LOG_STR_ARG(LOG_LEVELS[this->current_level_]));
|
||||
#ifndef USE_HOST
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Log Baud Rate: %" PRIu32 "\n"
|
||||
@@ -267,14 +288,14 @@ void Logger::dump_config() {
|
||||
#endif
|
||||
|
||||
for (auto &it : this->log_levels_) {
|
||||
ESP_LOGCONFIG(TAG, " Level for '%s': %s", it.first.c_str(), LOG_LEVELS[it.second]);
|
||||
ESP_LOGCONFIG(TAG, " Level for '%s': %s", it.first.c_str(), LOG_STR_ARG(LOG_LEVELS[it.second]));
|
||||
}
|
||||
}
|
||||
|
||||
void Logger::set_log_level(uint8_t level) {
|
||||
if (level > ESPHOME_LOG_LEVEL) {
|
||||
level = ESPHOME_LOG_LEVEL;
|
||||
ESP_LOGW(TAG, "Cannot set log level higher than pre-compiled %s", LOG_LEVELS[ESPHOME_LOG_LEVEL]);
|
||||
ESP_LOGW(TAG, "Cannot set log level higher than pre-compiled %s", LOG_STR_ARG(LOG_LEVELS[ESPHOME_LOG_LEVEL]));
|
||||
}
|
||||
this->current_level_ = level;
|
||||
this->level_callback_.call(level);
|
||||
|
||||
@@ -11,6 +11,7 @@ from esphome.const import (
|
||||
CONF_OUTPUT,
|
||||
)
|
||||
|
||||
AUTO_LOAD = ["gpio_expander"]
|
||||
DEPENDENCIES = ["i2c"]
|
||||
MULTI_CONF = True
|
||||
|
||||
|
||||
@@ -22,14 +22,29 @@ void MCP23016::setup() {
|
||||
this->write_reg_(MCP23016_IODIR0, 0xFF);
|
||||
this->write_reg_(MCP23016_IODIR1, 0xFF);
|
||||
}
|
||||
bool MCP23016::digital_read(uint8_t pin) {
|
||||
uint8_t bit = pin % 8;
|
||||
|
||||
void MCP23016::loop() {
|
||||
// Invalidate cache at the start of each loop
|
||||
this->reset_pin_cache_();
|
||||
}
|
||||
bool MCP23016::digital_read_hw(uint8_t pin) {
|
||||
uint8_t reg_addr = pin < 8 ? MCP23016_GP0 : MCP23016_GP1;
|
||||
uint8_t value = 0;
|
||||
this->read_reg_(reg_addr, &value);
|
||||
return value & (1 << bit);
|
||||
if (!this->read_reg_(reg_addr, &value)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Update the appropriate part of input_mask_
|
||||
if (pin < 8) {
|
||||
this->input_mask_ = (this->input_mask_ & 0xFF00) | value;
|
||||
} else {
|
||||
this->input_mask_ = (this->input_mask_ & 0x00FF) | (uint16_t(value) << 8);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
void MCP23016::digital_write(uint8_t pin, bool value) {
|
||||
|
||||
bool MCP23016::digital_read_cache(uint8_t pin) { return this->input_mask_ & (1 << pin); }
|
||||
void MCP23016::digital_write_hw(uint8_t pin, bool value) {
|
||||
uint8_t reg_addr = pin < 8 ? MCP23016_OLAT0 : MCP23016_OLAT1;
|
||||
this->update_reg_(pin, value, reg_addr);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/components/i2c/i2c.h"
|
||||
#include "esphome/components/gpio_expander/cached_gpio.h"
|
||||
|
||||
namespace esphome {
|
||||
namespace mcp23016 {
|
||||
@@ -24,19 +25,22 @@ enum MCP23016GPIORegisters {
|
||||
MCP23016_IOCON1 = 0x0B,
|
||||
};
|
||||
|
||||
class MCP23016 : public Component, public i2c::I2CDevice {
|
||||
class MCP23016 : public Component, public i2c::I2CDevice, public gpio_expander::CachedGpioExpander<uint8_t, 16> {
|
||||
public:
|
||||
MCP23016() = default;
|
||||
|
||||
void setup() override;
|
||||
|
||||
bool digital_read(uint8_t pin);
|
||||
void digital_write(uint8_t pin, bool value);
|
||||
void loop() override;
|
||||
void pin_mode(uint8_t pin, gpio::Flags flags);
|
||||
|
||||
float get_setup_priority() const override;
|
||||
|
||||
protected:
|
||||
// Virtual methods from CachedGpioExpander
|
||||
bool digital_read_hw(uint8_t pin) override;
|
||||
bool digital_read_cache(uint8_t pin) override;
|
||||
void digital_write_hw(uint8_t pin, bool value) override;
|
||||
|
||||
// read a given register
|
||||
bool read_reg_(uint8_t reg, uint8_t *value);
|
||||
// write a value to a given register
|
||||
@@ -46,6 +50,8 @@ class MCP23016 : public Component, public i2c::I2CDevice {
|
||||
|
||||
uint8_t olat_0_{0x00};
|
||||
uint8_t olat_1_{0x00};
|
||||
// Cache for input values (16-bit combined for both banks)
|
||||
uint16_t input_mask_{0x00};
|
||||
};
|
||||
|
||||
class MCP23016GPIOPin : public GPIOPin {
|
||||
|
||||
@@ -222,6 +222,12 @@ def delay(ms):
|
||||
|
||||
|
||||
class DriverChip:
|
||||
"""
|
||||
A class representing a MIPI DBI driver chip model.
|
||||
The parameters supplied as defaults will be used to provide default values for the display configuration.
|
||||
Setting swap_xy to cv.UNDEFINED will indicate that the model does not support swapping X and Y axes.
|
||||
"""
|
||||
|
||||
models: dict[str, Self] = {}
|
||||
|
||||
def __init__(
|
||||
@@ -232,7 +238,7 @@ class DriverChip:
|
||||
):
|
||||
name = name.upper()
|
||||
self.name = name
|
||||
self.initsequence = initsequence or defaults.get("init_sequence")
|
||||
self.initsequence = initsequence
|
||||
self.defaults = defaults
|
||||
DriverChip.models[name] = self
|
||||
|
||||
@@ -246,6 +252,17 @@ class DriverChip:
|
||||
return models
|
||||
|
||||
def extend(self, name, **kwargs) -> "DriverChip":
|
||||
"""
|
||||
Extend the current model with additional parameters or a modified init sequence.
|
||||
Parameters supplied here will override the defaults of the current model.
|
||||
if the initsequence is not provided, the current model's initsequence will be used.
|
||||
If add_init_sequence is provided, it will be appended to the current initsequence.
|
||||
:param name:
|
||||
:param kwargs:
|
||||
:return:
|
||||
"""
|
||||
initsequence = list(kwargs.pop("initsequence", self.initsequence))
|
||||
initsequence.extend(kwargs.pop("add_init_sequence", ()))
|
||||
defaults = self.defaults.copy()
|
||||
if (
|
||||
CONF_WIDTH in defaults
|
||||
@@ -260,23 +277,39 @@ class DriverChip:
|
||||
):
|
||||
defaults[CONF_NATIVE_HEIGHT] = defaults[CONF_HEIGHT]
|
||||
defaults.update(kwargs)
|
||||
return DriverChip(name, initsequence=self.initsequence, **defaults)
|
||||
return self.__class__(name, initsequence=tuple(initsequence), **defaults)
|
||||
|
||||
def get_default(self, key, fallback: Any = False) -> Any:
|
||||
return self.defaults.get(key, fallback)
|
||||
|
||||
@property
|
||||
def transforms(self) -> set[str]:
|
||||
"""
|
||||
Return the available transforms for this model.
|
||||
"""
|
||||
if self.get_default("no_transform", False):
|
||||
return set()
|
||||
if self.get_default(CONF_SWAP_XY) != cv.UNDEFINED:
|
||||
return {CONF_MIRROR_X, CONF_MIRROR_Y, CONF_SWAP_XY}
|
||||
return {CONF_MIRROR_X, CONF_MIRROR_Y}
|
||||
|
||||
def option(self, name, fallback=False) -> cv.Optional:
|
||||
return cv.Optional(name, default=self.get_default(name, fallback))
|
||||
|
||||
def rotation_as_transform(self, config) -> bool:
|
||||
"""
|
||||
Check if a rotation can be implemented in hardware using the MADCTL register.
|
||||
A rotation of 180 is always possible, 90 and 270 are possible if the model supports swapping X and Y.
|
||||
A rotation of 180 is always possible if x and y mirroring are supported, 90 and 270 are possible if the model supports swapping X and Y.
|
||||
"""
|
||||
transforms = self.transforms
|
||||
rotation = config.get(CONF_ROTATION, 0)
|
||||
return rotation and (
|
||||
self.get_default(CONF_SWAP_XY) != cv.UNDEFINED or rotation == 180
|
||||
)
|
||||
if rotation == 0 or not transforms:
|
||||
return False
|
||||
if rotation == 180:
|
||||
return CONF_MIRROR_X in transforms and CONF_MIRROR_Y in transforms
|
||||
if rotation == 90:
|
||||
return CONF_SWAP_XY in transforms and CONF_MIRROR_X in transforms
|
||||
return CONF_SWAP_XY in transforms and CONF_MIRROR_Y in transforms
|
||||
|
||||
def get_dimensions(self, config) -> tuple[int, int, int, int]:
|
||||
if CONF_DIMENSIONS in config:
|
||||
@@ -301,10 +334,10 @@ class DriverChip:
|
||||
|
||||
# if mirroring axes and there are offsets, also mirror the offsets to cater for situations where
|
||||
# the offset is asymmetric
|
||||
if transform[CONF_MIRROR_X]:
|
||||
if transform.get(CONF_MIRROR_X):
|
||||
native_width = self.get_default(CONF_NATIVE_WIDTH, width + offset_width * 2)
|
||||
offset_width = native_width - width - offset_width
|
||||
if transform[CONF_MIRROR_Y]:
|
||||
if transform.get(CONF_MIRROR_Y):
|
||||
native_height = self.get_default(
|
||||
CONF_NATIVE_HEIGHT, height + offset_height * 2
|
||||
)
|
||||
@@ -314,7 +347,7 @@ class DriverChip:
|
||||
90,
|
||||
270,
|
||||
)
|
||||
if transform[CONF_SWAP_XY] is True or rotated:
|
||||
if transform.get(CONF_SWAP_XY) is True or rotated:
|
||||
width, height = height, width
|
||||
offset_height, offset_width = offset_width, offset_height
|
||||
return width, height, offset_width, offset_height
|
||||
@@ -324,27 +357,50 @@ class DriverChip:
|
||||
transform = config.get(
|
||||
CONF_TRANSFORM,
|
||||
{
|
||||
CONF_MIRROR_X: self.get_default(CONF_MIRROR_X, False),
|
||||
CONF_MIRROR_Y: self.get_default(CONF_MIRROR_Y, False),
|
||||
CONF_SWAP_XY: self.get_default(CONF_SWAP_XY, False),
|
||||
CONF_MIRROR_X: self.get_default(CONF_MIRROR_X),
|
||||
CONF_MIRROR_Y: self.get_default(CONF_MIRROR_Y),
|
||||
CONF_SWAP_XY: self.get_default(CONF_SWAP_XY),
|
||||
},
|
||||
)
|
||||
# fill in defaults if not provided
|
||||
mirror_x = transform.get(CONF_MIRROR_X, self.get_default(CONF_MIRROR_X))
|
||||
mirror_y = transform.get(CONF_MIRROR_Y, self.get_default(CONF_MIRROR_Y))
|
||||
swap_xy = transform.get(CONF_SWAP_XY, self.get_default(CONF_SWAP_XY))
|
||||
transform[CONF_MIRROR_X] = mirror_x
|
||||
transform[CONF_MIRROR_Y] = mirror_y
|
||||
transform[CONF_SWAP_XY] = swap_xy
|
||||
|
||||
# Can we use the MADCTL register to set the rotation?
|
||||
if can_transform and CONF_TRANSFORM not in config:
|
||||
rotation = config[CONF_ROTATION]
|
||||
if rotation == 180:
|
||||
transform[CONF_MIRROR_X] = not transform[CONF_MIRROR_X]
|
||||
transform[CONF_MIRROR_Y] = not transform[CONF_MIRROR_Y]
|
||||
transform[CONF_MIRROR_X] = not mirror_x
|
||||
transform[CONF_MIRROR_Y] = not mirror_y
|
||||
elif rotation == 90:
|
||||
transform[CONF_SWAP_XY] = not transform[CONF_SWAP_XY]
|
||||
transform[CONF_MIRROR_X] = not transform[CONF_MIRROR_X]
|
||||
transform[CONF_SWAP_XY] = not swap_xy
|
||||
transform[CONF_MIRROR_X] = not mirror_x
|
||||
else:
|
||||
transform[CONF_SWAP_XY] = not transform[CONF_SWAP_XY]
|
||||
transform[CONF_MIRROR_Y] = not transform[CONF_MIRROR_Y]
|
||||
transform[CONF_SWAP_XY] = not swap_xy
|
||||
transform[CONF_MIRROR_Y] = not mirror_y
|
||||
transform[CONF_TRANSFORM] = True
|
||||
return transform
|
||||
|
||||
def add_madctl(self, sequence: list, config: dict):
|
||||
# Add the MADCTL command to the sequence based on the configuration.
|
||||
use_flip = config.get(CONF_USE_AXIS_FLIPS)
|
||||
madctl = 0
|
||||
transform = self.get_transform(config)
|
||||
if transform[CONF_MIRROR_X]:
|
||||
madctl |= MADCTL_XFLIP if use_flip else MADCTL_MX
|
||||
if transform[CONF_MIRROR_Y]:
|
||||
madctl |= MADCTL_YFLIP if use_flip else MADCTL_MY
|
||||
if transform.get(CONF_SWAP_XY) is True: # Exclude Undefined
|
||||
madctl |= MADCTL_MV
|
||||
if config[CONF_COLOR_ORDER] == MODE_BGR:
|
||||
madctl |= MADCTL_BGR
|
||||
sequence.append((MADCTL, madctl))
|
||||
return madctl
|
||||
|
||||
def get_sequence(self, config) -> tuple[tuple[int, ...], int]:
|
||||
"""
|
||||
Create the init sequence for the display.
|
||||
@@ -367,21 +423,9 @@ class DriverChip:
|
||||
pixel_mode = PIXEL_MODES[pixel_mode]
|
||||
sequence.append((PIXFMT, pixel_mode))
|
||||
|
||||
# Does the chip use the flipping bits for mirroring rather than the reverse order bits?
|
||||
use_flip = config.get(CONF_USE_AXIS_FLIPS)
|
||||
madctl = 0
|
||||
transform = self.get_transform(config)
|
||||
if self.rotation_as_transform(config):
|
||||
LOGGER.info("Using hardware transform to implement rotation")
|
||||
if transform.get(CONF_MIRROR_X):
|
||||
madctl |= MADCTL_XFLIP if use_flip else MADCTL_MX
|
||||
if transform.get(CONF_MIRROR_Y):
|
||||
madctl |= MADCTL_YFLIP if use_flip else MADCTL_MY
|
||||
if transform.get(CONF_SWAP_XY) is True: # Exclude Undefined
|
||||
madctl |= MADCTL_MV
|
||||
if config[CONF_COLOR_ORDER] == MODE_BGR:
|
||||
madctl |= MADCTL_BGR
|
||||
sequence.append((MADCTL, madctl))
|
||||
madctl = self.add_madctl(sequence, config)
|
||||
if config[CONF_INVERT_COLORS]:
|
||||
sequence.append((INVON,))
|
||||
else:
|
||||
|
||||
2
esphome/components/mipi_rgb/__init__.py
Normal file
2
esphome/components/mipi_rgb/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
||||
CODEOWNERS = ["@clydebarrow"]
|
||||
DOMAIN = "mipi_rgb"
|
||||
321
esphome/components/mipi_rgb/display.py
Normal file
321
esphome/components/mipi_rgb/display.py
Normal file
@@ -0,0 +1,321 @@
|
||||
import importlib
|
||||
import pkgutil
|
||||
|
||||
from esphome import pins
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import display, spi
|
||||
from esphome.components.const import (
|
||||
BYTE_ORDER_BIG,
|
||||
BYTE_ORDER_LITTLE,
|
||||
CONF_BYTE_ORDER,
|
||||
CONF_DRAW_ROUNDING,
|
||||
)
|
||||
from esphome.components.display import CONF_SHOW_TEST_CARD
|
||||
from esphome.components.esp32 import const, only_on_variant
|
||||
from esphome.components.mipi import (
|
||||
COLOR_ORDERS,
|
||||
CONF_DE_PIN,
|
||||
CONF_HSYNC_BACK_PORCH,
|
||||
CONF_HSYNC_FRONT_PORCH,
|
||||
CONF_HSYNC_PULSE_WIDTH,
|
||||
CONF_PCLK_PIN,
|
||||
CONF_PIXEL_MODE,
|
||||
CONF_USE_AXIS_FLIPS,
|
||||
CONF_VSYNC_BACK_PORCH,
|
||||
CONF_VSYNC_FRONT_PORCH,
|
||||
CONF_VSYNC_PULSE_WIDTH,
|
||||
MODE_BGR,
|
||||
PIXEL_MODE_16BIT,
|
||||
PIXEL_MODE_18BIT,
|
||||
DriverChip,
|
||||
dimension_schema,
|
||||
map_sequence,
|
||||
power_of_two,
|
||||
requires_buffer,
|
||||
)
|
||||
from esphome.components.rpi_dpi_rgb.display import (
|
||||
CONF_PCLK_FREQUENCY,
|
||||
CONF_PCLK_INVERTED,
|
||||
)
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
CONF_BLUE,
|
||||
CONF_COLOR_ORDER,
|
||||
CONF_CS_PIN,
|
||||
CONF_DATA_PINS,
|
||||
CONF_DATA_RATE,
|
||||
CONF_DC_PIN,
|
||||
CONF_DIMENSIONS,
|
||||
CONF_ENABLE_PIN,
|
||||
CONF_GREEN,
|
||||
CONF_HSYNC_PIN,
|
||||
CONF_ID,
|
||||
CONF_IGNORE_STRAPPING_WARNING,
|
||||
CONF_INIT_SEQUENCE,
|
||||
CONF_INVERT_COLORS,
|
||||
CONF_LAMBDA,
|
||||
CONF_MIRROR_X,
|
||||
CONF_MIRROR_Y,
|
||||
CONF_MODEL,
|
||||
CONF_NUMBER,
|
||||
CONF_RED,
|
||||
CONF_RESET_PIN,
|
||||
CONF_ROTATION,
|
||||
CONF_SPI_ID,
|
||||
CONF_SWAP_XY,
|
||||
CONF_TRANSFORM,
|
||||
CONF_VSYNC_PIN,
|
||||
CONF_WIDTH,
|
||||
)
|
||||
from esphome.final_validate import full_config
|
||||
|
||||
from ..spi import CONF_SPI_MODE, SPI_DATA_RATE_SCHEMA, SPI_MODE_OPTIONS, SPIComponent
|
||||
from . import models
|
||||
|
||||
DEPENDENCIES = ["esp32", "psram"]
|
||||
|
||||
mipi_rgb_ns = cg.esphome_ns.namespace("mipi_rgb")
|
||||
mipi_rgb = mipi_rgb_ns.class_("MipiRgb", display.Display, cg.Component)
|
||||
mipi_rgb_spi = mipi_rgb_ns.class_(
|
||||
"MipiRgbSpi", mipi_rgb, display.Display, cg.Component, spi.SPIDevice
|
||||
)
|
||||
ColorOrder = display.display_ns.enum("ColorMode")
|
||||
|
||||
DATA_PIN_SCHEMA = pins.internal_gpio_output_pin_schema
|
||||
|
||||
DriverChip("CUSTOM")
|
||||
|
||||
# Import all models dynamically from the models package
|
||||
|
||||
for module_info in pkgutil.iter_modules(models.__path__):
|
||||
importlib.import_module(f".models.{module_info.name}", package=__package__)
|
||||
|
||||
MODELS = DriverChip.get_models()
|
||||
|
||||
|
||||
def data_pin_validate(value):
|
||||
"""
|
||||
It is safe to use strapping pins as RGB output data bits, as they are outputs only,
|
||||
and not initialised until after boot.
|
||||
"""
|
||||
if not isinstance(value, dict):
|
||||
try:
|
||||
return DATA_PIN_SCHEMA(
|
||||
{CONF_NUMBER: value, CONF_IGNORE_STRAPPING_WARNING: True}
|
||||
)
|
||||
except cv.Invalid:
|
||||
pass
|
||||
return DATA_PIN_SCHEMA(value)
|
||||
|
||||
|
||||
def data_pin_set(length):
|
||||
return cv.All(
|
||||
[data_pin_validate],
|
||||
cv.Length(min=length, max=length, msg=f"Exactly {length} data pins required"),
|
||||
)
|
||||
|
||||
|
||||
def model_schema(config):
|
||||
model = MODELS[config[CONF_MODEL].upper()]
|
||||
if transforms := model.transforms:
|
||||
transform = cv.Schema({cv.Required(x): cv.boolean for x in transforms})
|
||||
for x in (CONF_SWAP_XY, CONF_MIRROR_X, CONF_MIRROR_Y):
|
||||
if x not in transforms:
|
||||
transform = transform.extend(
|
||||
{cv.Optional(x): cv.invalid(f"{x} not supported by this model")}
|
||||
)
|
||||
else:
|
||||
transform = cv.invalid("This model does not support transforms")
|
||||
|
||||
# RPI model does not use an init sequence, indicates with empty list
|
||||
if model.initsequence is None:
|
||||
# Custom model requires an init sequence
|
||||
iseqconf = cv.Required(CONF_INIT_SEQUENCE)
|
||||
uses_spi = True
|
||||
else:
|
||||
iseqconf = cv.Optional(CONF_INIT_SEQUENCE)
|
||||
uses_spi = CONF_INIT_SEQUENCE in config or len(model.initsequence) != 0
|
||||
swap_xy = config.get(CONF_TRANSFORM, {}).get(CONF_SWAP_XY, False)
|
||||
|
||||
# Dimensions are optional if the model has a default width and the swap_xy transform is not overridden
|
||||
cv_dimensions = (
|
||||
cv.Optional if model.get_default(CONF_WIDTH) and not swap_xy else cv.Required
|
||||
)
|
||||
pixel_modes = (PIXEL_MODE_16BIT, PIXEL_MODE_18BIT, "16", "18")
|
||||
schema = display.FULL_DISPLAY_SCHEMA.extend(
|
||||
{
|
||||
model.option(CONF_RESET_PIN, cv.UNDEFINED): pins.gpio_output_pin_schema,
|
||||
cv.GenerateID(): cv.declare_id(mipi_rgb_spi if uses_spi else mipi_rgb),
|
||||
cv_dimensions(CONF_DIMENSIONS): dimension_schema(
|
||||
model.get_default(CONF_DRAW_ROUNDING, 1)
|
||||
),
|
||||
model.option(CONF_ENABLE_PIN, cv.UNDEFINED): cv.ensure_list(
|
||||
pins.gpio_output_pin_schema
|
||||
),
|
||||
model.option(CONF_COLOR_ORDER, MODE_BGR): cv.enum(COLOR_ORDERS, upper=True),
|
||||
model.option(CONF_DRAW_ROUNDING, 2): power_of_two,
|
||||
model.option(CONF_PIXEL_MODE, PIXEL_MODE_16BIT): cv.one_of(
|
||||
*pixel_modes, lower=True
|
||||
),
|
||||
model.option(CONF_TRANSFORM, cv.UNDEFINED): transform,
|
||||
cv.Required(CONF_MODEL): cv.one_of(model.name, upper=True),
|
||||
model.option(CONF_INVERT_COLORS, False): cv.boolean,
|
||||
model.option(CONF_USE_AXIS_FLIPS, True): cv.boolean,
|
||||
model.option(CONF_PCLK_FREQUENCY, "40MHz"): cv.All(
|
||||
cv.frequency, cv.Range(min=4e6, max=100e6)
|
||||
),
|
||||
model.option(CONF_PCLK_INVERTED, True): cv.boolean,
|
||||
iseqconf: cv.ensure_list(map_sequence),
|
||||
model.option(CONF_BYTE_ORDER, BYTE_ORDER_BIG): cv.one_of(
|
||||
BYTE_ORDER_LITTLE, BYTE_ORDER_BIG, lower=True
|
||||
),
|
||||
model.option(CONF_HSYNC_PULSE_WIDTH): cv.int_,
|
||||
model.option(CONF_HSYNC_BACK_PORCH): cv.int_,
|
||||
model.option(CONF_HSYNC_FRONT_PORCH): cv.int_,
|
||||
model.option(CONF_VSYNC_PULSE_WIDTH): cv.int_,
|
||||
model.option(CONF_VSYNC_BACK_PORCH): cv.int_,
|
||||
model.option(CONF_VSYNC_FRONT_PORCH): cv.int_,
|
||||
model.option(CONF_DATA_PINS): cv.Any(
|
||||
data_pin_set(16),
|
||||
cv.Schema(
|
||||
{
|
||||
cv.Required(CONF_RED): data_pin_set(5),
|
||||
cv.Required(CONF_GREEN): data_pin_set(6),
|
||||
cv.Required(CONF_BLUE): data_pin_set(5),
|
||||
}
|
||||
),
|
||||
),
|
||||
model.option(
|
||||
CONF_DE_PIN, cv.UNDEFINED
|
||||
): pins.internal_gpio_output_pin_schema,
|
||||
model.option(CONF_PCLK_PIN): pins.internal_gpio_output_pin_schema,
|
||||
model.option(CONF_HSYNC_PIN): pins.internal_gpio_output_pin_schema,
|
||||
model.option(CONF_VSYNC_PIN): pins.internal_gpio_output_pin_schema,
|
||||
model.option(CONF_RESET_PIN, cv.UNDEFINED): pins.gpio_output_pin_schema,
|
||||
}
|
||||
)
|
||||
if uses_spi:
|
||||
schema = schema.extend(
|
||||
{
|
||||
cv.GenerateID(CONF_SPI_ID): cv.use_id(SPIComponent),
|
||||
model.option(CONF_DC_PIN, cv.UNDEFINED): pins.gpio_output_pin_schema,
|
||||
model.option(CONF_DATA_RATE, "1MHz"): SPI_DATA_RATE_SCHEMA,
|
||||
model.option(CONF_SPI_MODE, "MODE0"): cv.enum(
|
||||
SPI_MODE_OPTIONS, upper=True
|
||||
),
|
||||
model.option(CONF_CS_PIN, cv.UNDEFINED): pins.gpio_output_pin_schema,
|
||||
}
|
||||
)
|
||||
return schema
|
||||
|
||||
|
||||
def _config_schema(config):
|
||||
config = cv.Schema(
|
||||
{
|
||||
cv.Required(CONF_MODEL): cv.one_of(*MODELS, upper=True),
|
||||
},
|
||||
extra=cv.ALLOW_EXTRA,
|
||||
)(config)
|
||||
schema = model_schema(config)
|
||||
return cv.All(
|
||||
schema,
|
||||
only_on_variant(supported=[const.VARIANT_ESP32S3]),
|
||||
cv.only_with_esp_idf,
|
||||
)(config)
|
||||
|
||||
|
||||
CONFIG_SCHEMA = _config_schema
|
||||
|
||||
|
||||
def _final_validate(config):
|
||||
global_config = full_config.get()
|
||||
|
||||
from esphome.components.lvgl import DOMAIN as LVGL_DOMAIN
|
||||
|
||||
if not requires_buffer(config) and LVGL_DOMAIN not in global_config:
|
||||
# If no drawing methods are configured, and LVGL is not enabled, show a test card
|
||||
config[CONF_SHOW_TEST_CARD] = True
|
||||
if CONF_SPI_ID in config:
|
||||
config = spi.final_validate_device_schema(
|
||||
"mipi_rgb", require_miso=False, require_mosi=True
|
||||
)(config)
|
||||
return config
|
||||
|
||||
|
||||
FINAL_VALIDATE_SCHEMA = _final_validate
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
model = MODELS[config[CONF_MODEL].upper()]
|
||||
width, height, _offset_width, _offset_height = model.get_dimensions(config)
|
||||
var = cg.new_Pvariable(config[CONF_ID], width, height)
|
||||
cg.add(var.set_model(model.name))
|
||||
if enable_pin := config.get(CONF_ENABLE_PIN):
|
||||
enable = [await cg.gpio_pin_expression(pin) for pin in enable_pin]
|
||||
cg.add(var.set_enable_pins(enable))
|
||||
|
||||
if CONF_SPI_ID in config:
|
||||
await spi.register_spi_device(var, config)
|
||||
sequence, madctl = model.get_sequence(config)
|
||||
cg.add(var.set_init_sequence(sequence))
|
||||
cg.add(var.set_madctl(madctl))
|
||||
|
||||
cg.add(var.set_color_mode(COLOR_ORDERS[config[CONF_COLOR_ORDER]]))
|
||||
cg.add(var.set_invert_colors(config[CONF_INVERT_COLORS]))
|
||||
cg.add(var.set_hsync_pulse_width(config[CONF_HSYNC_PULSE_WIDTH]))
|
||||
cg.add(var.set_hsync_back_porch(config[CONF_HSYNC_BACK_PORCH]))
|
||||
cg.add(var.set_hsync_front_porch(config[CONF_HSYNC_FRONT_PORCH]))
|
||||
cg.add(var.set_vsync_pulse_width(config[CONF_VSYNC_PULSE_WIDTH]))
|
||||
cg.add(var.set_vsync_back_porch(config[CONF_VSYNC_BACK_PORCH]))
|
||||
cg.add(var.set_vsync_front_porch(config[CONF_VSYNC_FRONT_PORCH]))
|
||||
cg.add(var.set_pclk_inverted(config[CONF_PCLK_INVERTED]))
|
||||
cg.add(var.set_pclk_frequency(config[CONF_PCLK_FREQUENCY]))
|
||||
index = 0
|
||||
dpins = []
|
||||
if CONF_RED in config[CONF_DATA_PINS]:
|
||||
red_pins = config[CONF_DATA_PINS][CONF_RED]
|
||||
green_pins = config[CONF_DATA_PINS][CONF_GREEN]
|
||||
blue_pins = config[CONF_DATA_PINS][CONF_BLUE]
|
||||
if config[CONF_COLOR_ORDER] == "BGR":
|
||||
dpins.extend(red_pins)
|
||||
dpins.extend(green_pins)
|
||||
dpins.extend(blue_pins)
|
||||
else:
|
||||
dpins.extend(blue_pins)
|
||||
dpins.extend(green_pins)
|
||||
dpins.extend(red_pins)
|
||||
# swap bytes to match big-endian format
|
||||
dpins = dpins[8:16] + dpins[0:8]
|
||||
else:
|
||||
dpins = config[CONF_DATA_PINS]
|
||||
for index, pin in enumerate(dpins):
|
||||
data_pin = await cg.gpio_pin_expression(pin)
|
||||
cg.add(var.add_data_pin(data_pin, index))
|
||||
|
||||
if dc_pin := config.get(CONF_DC_PIN):
|
||||
dc = await cg.gpio_pin_expression(dc_pin)
|
||||
cg.add(var.set_dc_pin(dc))
|
||||
|
||||
if reset_pin := config.get(CONF_RESET_PIN):
|
||||
reset = await cg.gpio_pin_expression(reset_pin)
|
||||
cg.add(var.set_reset_pin(reset))
|
||||
|
||||
if model.rotation_as_transform(config):
|
||||
config[CONF_ROTATION] = 0
|
||||
|
||||
if de_pin := config.get(CONF_DE_PIN):
|
||||
pin = await cg.gpio_pin_expression(de_pin)
|
||||
cg.add(var.set_de_pin(pin))
|
||||
pin = await cg.gpio_pin_expression(config[CONF_PCLK_PIN])
|
||||
cg.add(var.set_pclk_pin(pin))
|
||||
pin = await cg.gpio_pin_expression(config[CONF_HSYNC_PIN])
|
||||
cg.add(var.set_hsync_pin(pin))
|
||||
pin = await cg.gpio_pin_expression(config[CONF_VSYNC_PIN])
|
||||
cg.add(var.set_vsync_pin(pin))
|
||||
|
||||
await display.register_display(var, config)
|
||||
if lamb := config.get(CONF_LAMBDA):
|
||||
lambda_ = await cg.process_lambda(
|
||||
lamb, [(display.DisplayRef, "it")], return_type=cg.void
|
||||
)
|
||||
cg.add(var.set_writer(lambda_))
|
||||
388
esphome/components/mipi_rgb/mipi_rgb.cpp
Normal file
388
esphome/components/mipi_rgb/mipi_rgb.cpp
Normal file
@@ -0,0 +1,388 @@
|
||||
#ifdef USE_ESP32_VARIANT_ESP32S3
|
||||
#include "mipi_rgb.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esp_lcd_panel_rgb.h"
|
||||
|
||||
namespace esphome {
|
||||
namespace mipi_rgb {
|
||||
|
||||
static const uint8_t DELAY_FLAG = 0xFF;
|
||||
static constexpr uint8_t MADCTL_MY = 0x80; // Bit 7 Bottom to top
|
||||
static constexpr uint8_t MADCTL_MX = 0x40; // Bit 6 Right to left
|
||||
static constexpr uint8_t MADCTL_MV = 0x20; // Bit 5 Swap axes
|
||||
static constexpr uint8_t MADCTL_ML = 0x10; // Bit 4 Refresh bottom to top
|
||||
static constexpr uint8_t MADCTL_BGR = 0x08; // Bit 3 Blue-Green-Red pixel order
|
||||
static constexpr uint8_t MADCTL_XFLIP = 0x02; // Mirror the display horizontally
|
||||
static constexpr uint8_t MADCTL_YFLIP = 0x01; // Mirror the display vertically
|
||||
|
||||
void MipiRgb::setup_enables_() {
|
||||
if (!this->enable_pins_.empty()) {
|
||||
for (auto *pin : this->enable_pins_) {
|
||||
pin->setup();
|
||||
pin->digital_write(true);
|
||||
}
|
||||
delay(10);
|
||||
}
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(5);
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(5);
|
||||
this->reset_pin_->digital_write(true);
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef USE_SPI
|
||||
void MipiRgbSpi::setup() {
|
||||
this->setup_enables_();
|
||||
this->spi_setup();
|
||||
this->write_init_sequence_();
|
||||
this->common_setup_();
|
||||
}
|
||||
void MipiRgbSpi::write_command_(uint8_t value) {
|
||||
this->enable();
|
||||
if (this->dc_pin_ == nullptr) {
|
||||
this->write(value, 9);
|
||||
} else {
|
||||
this->dc_pin_->digital_write(false);
|
||||
this->write_byte(value);
|
||||
this->dc_pin_->digital_write(true);
|
||||
}
|
||||
this->disable();
|
||||
}
|
||||
|
||||
void MipiRgbSpi::write_data_(uint8_t value) {
|
||||
this->enable();
|
||||
if (this->dc_pin_ == nullptr) {
|
||||
this->write(value | 0x100, 9);
|
||||
} else {
|
||||
this->dc_pin_->digital_write(true);
|
||||
this->write_byte(value);
|
||||
}
|
||||
this->disable();
|
||||
}
|
||||
|
||||
/**
|
||||
* this relies upon the init sequence being well-formed, which is guaranteed by the Python init code.
|
||||
*/
|
||||
|
||||
void MipiRgbSpi::write_init_sequence_() {
|
||||
size_t index = 0;
|
||||
auto &vec = this->init_sequence_;
|
||||
while (index != vec.size()) {
|
||||
if (vec.size() - index < 2) {
|
||||
this->mark_failed("Malformed init sequence");
|
||||
return;
|
||||
}
|
||||
uint8_t cmd = vec[index++];
|
||||
uint8_t x = vec[index++];
|
||||
if (x == DELAY_FLAG) {
|
||||
ESP_LOGD(TAG, "Delay %dms", cmd);
|
||||
delay(cmd);
|
||||
} else {
|
||||
uint8_t num_args = x & 0x7F;
|
||||
if (vec.size() - index < num_args) {
|
||||
this->mark_failed("Malformed init sequence");
|
||||
return;
|
||||
}
|
||||
if (cmd == SLEEP_OUT) {
|
||||
delay(120); // NOLINT
|
||||
}
|
||||
const auto *ptr = vec.data() + index;
|
||||
ESP_LOGD(TAG, "Write command %02X, length %d, byte(s) %s", cmd, num_args,
|
||||
format_hex_pretty(ptr, num_args, '.', false).c_str());
|
||||
index += num_args;
|
||||
this->write_command_(cmd);
|
||||
while (num_args-- != 0)
|
||||
this->write_data_(*ptr++);
|
||||
if (cmd == SLEEP_OUT)
|
||||
delay(10);
|
||||
}
|
||||
}
|
||||
// this->spi_teardown(); // SPI not needed after this
|
||||
this->init_sequence_.clear();
|
||||
delay(10);
|
||||
}
|
||||
|
||||
void MipiRgbSpi::dump_config() {
|
||||
MipiRgb::dump_config();
|
||||
LOG_PIN(" CS Pin: ", this->cs_);
|
||||
LOG_PIN(" DC Pin: ", this->dc_pin_);
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" SPI Data rate: %uMHz"
|
||||
"\n Mirror X: %s"
|
||||
"\n Mirror Y: %s"
|
||||
"\n Swap X/Y: %s"
|
||||
"\n Color Order: %s",
|
||||
(unsigned) (this->data_rate_ / 1000000), YESNO(this->madctl_ & (MADCTL_XFLIP | MADCTL_MX)),
|
||||
YESNO(this->madctl_ & (MADCTL_YFLIP | MADCTL_MY | MADCTL_ML)), YESNO(this->madctl_ & MADCTL_MV),
|
||||
this->madctl_ & MADCTL_BGR ? "BGR" : "RGB");
|
||||
}
|
||||
|
||||
#endif // USE_SPI
|
||||
|
||||
void MipiRgb::setup() {
|
||||
this->setup_enables_();
|
||||
this->common_setup_();
|
||||
}
|
||||
|
||||
void MipiRgb::common_setup_() {
|
||||
esp_lcd_rgb_panel_config_t config{};
|
||||
config.flags.fb_in_psram = 1;
|
||||
config.bounce_buffer_size_px = this->width_ * 10;
|
||||
config.num_fbs = 1;
|
||||
config.timings.h_res = this->width_;
|
||||
config.timings.v_res = this->height_;
|
||||
config.timings.hsync_pulse_width = this->hsync_pulse_width_;
|
||||
config.timings.hsync_back_porch = this->hsync_back_porch_;
|
||||
config.timings.hsync_front_porch = this->hsync_front_porch_;
|
||||
config.timings.vsync_pulse_width = this->vsync_pulse_width_;
|
||||
config.timings.vsync_back_porch = this->vsync_back_porch_;
|
||||
config.timings.vsync_front_porch = this->vsync_front_porch_;
|
||||
config.timings.flags.pclk_active_neg = this->pclk_inverted_;
|
||||
config.timings.pclk_hz = this->pclk_frequency_;
|
||||
config.clk_src = LCD_CLK_SRC_PLL160M;
|
||||
size_t data_pin_count = sizeof(this->data_pins_) / sizeof(this->data_pins_[0]);
|
||||
for (size_t i = 0; i != data_pin_count; i++) {
|
||||
config.data_gpio_nums[i] = this->data_pins_[i]->get_pin();
|
||||
}
|
||||
config.data_width = data_pin_count;
|
||||
config.disp_gpio_num = -1;
|
||||
config.hsync_gpio_num = this->hsync_pin_->get_pin();
|
||||
config.vsync_gpio_num = this->vsync_pin_->get_pin();
|
||||
if (this->de_pin_) {
|
||||
config.de_gpio_num = this->de_pin_->get_pin();
|
||||
} else {
|
||||
config.de_gpio_num = -1;
|
||||
}
|
||||
config.pclk_gpio_num = this->pclk_pin_->get_pin();
|
||||
esp_err_t err = esp_lcd_new_rgb_panel(&config, &this->handle_);
|
||||
if (err == ESP_OK)
|
||||
err = esp_lcd_panel_reset(this->handle_);
|
||||
if (err == ESP_OK)
|
||||
err = esp_lcd_panel_init(this->handle_);
|
||||
if (err != ESP_OK) {
|
||||
auto msg = str_sprintf("lcd setup failed: %s", esp_err_to_name(err));
|
||||
this->mark_failed(msg.c_str());
|
||||
}
|
||||
ESP_LOGCONFIG(TAG, "MipiRgb setup complete");
|
||||
}
|
||||
|
||||
void MipiRgb::loop() {
|
||||
if (this->handle_ != nullptr)
|
||||
esp_lcd_rgb_panel_restart(this->handle_);
|
||||
}
|
||||
|
||||
void MipiRgb::update() {
|
||||
if (this->is_failed())
|
||||
return;
|
||||
if (this->auto_clear_enabled_) {
|
||||
this->clear();
|
||||
}
|
||||
if (this->show_test_card_) {
|
||||
this->test_card();
|
||||
} else if (this->page_ != nullptr) {
|
||||
this->page_->get_writer()(*this);
|
||||
} else if (this->writer_.has_value()) {
|
||||
(*this->writer_)(*this);
|
||||
} else {
|
||||
this->stop_poller();
|
||||
}
|
||||
if (this->buffer_ == nullptr || this->x_low_ > this->x_high_ || this->y_low_ > this->y_high_)
|
||||
return;
|
||||
ESP_LOGV(TAG, "x_low %d, y_low %d, x_high %d, y_high %d", this->x_low_, this->y_low_, this->x_high_, this->y_high_);
|
||||
int w = this->x_high_ - this->x_low_ + 1;
|
||||
int h = this->y_high_ - this->y_low_ + 1;
|
||||
this->write_to_display_(this->x_low_, this->y_low_, w, h, reinterpret_cast<const uint8_t *>(this->buffer_),
|
||||
this->x_low_, this->y_low_, this->width_ - w - this->x_low_);
|
||||
// invalidate watermarks
|
||||
this->x_low_ = this->width_;
|
||||
this->y_low_ = this->height_;
|
||||
this->x_high_ = 0;
|
||||
this->y_high_ = 0;
|
||||
}
|
||||
|
||||
void MipiRgb::draw_pixels_at(int x_start, int y_start, int w, int h, const uint8_t *ptr, display::ColorOrder order,
|
||||
display::ColorBitness bitness, bool big_endian, int x_offset, int y_offset, int x_pad) {
|
||||
if (w <= 0 || h <= 0 || this->is_failed())
|
||||
return;
|
||||
// if color mapping is required, pass the buck.
|
||||
// note that endianness is not considered here - it is assumed to match!
|
||||
if (bitness != display::COLOR_BITNESS_565) {
|
||||
Display::draw_pixels_at(x_start, y_start, w, h, ptr, order, bitness, big_endian, x_offset, y_offset, x_pad);
|
||||
this->write_to_display_(x_start, y_start, w, h, reinterpret_cast<const uint8_t *>(this->buffer_), x_start, y_start,
|
||||
this->width_ - w - x_start);
|
||||
} else {
|
||||
this->write_to_display_(x_start, y_start, w, h, ptr, x_offset, y_offset, x_pad);
|
||||
}
|
||||
}
|
||||
|
||||
void MipiRgb::write_to_display_(int x_start, int y_start, int w, int h, const uint8_t *ptr, int x_offset, int y_offset,
|
||||
int x_pad) {
|
||||
esp_err_t err = ESP_OK;
|
||||
auto stride = (x_offset + w + x_pad) * 2;
|
||||
ptr += y_offset * stride + x_offset * 2; // skip to the first pixel
|
||||
// x_ and y_offset are offsets into the source buffer, unrelated to our own offsets into the display.
|
||||
if (x_offset == 0 && x_pad == 0) {
|
||||
err = esp_lcd_panel_draw_bitmap(this->handle_, x_start, y_start, x_start + w, y_start + h, ptr);
|
||||
} else {
|
||||
// draw line by line
|
||||
for (int y = 0; y != h; y++) {
|
||||
err = esp_lcd_panel_draw_bitmap(this->handle_, x_start, y + y_start, x_start + w, y + y_start + 1, ptr);
|
||||
if (err != ESP_OK)
|
||||
break;
|
||||
ptr += stride; // next line
|
||||
}
|
||||
}
|
||||
if (err != ESP_OK)
|
||||
ESP_LOGE(TAG, "lcd_lcd_panel_draw_bitmap failed: %s", esp_err_to_name(err));
|
||||
}
|
||||
|
||||
bool MipiRgb::check_buffer_() {
|
||||
if (this->is_failed())
|
||||
return false;
|
||||
if (this->buffer_ != nullptr)
|
||||
return true;
|
||||
// this is dependent on the enum values.
|
||||
RAMAllocator<uint16_t> allocator;
|
||||
this->buffer_ = allocator.allocate(this->height_ * this->width_);
|
||||
if (this->buffer_ == nullptr) {
|
||||
this->mark_failed("Could not allocate buffer for display!");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void MipiRgb::draw_pixel_at(int x, int y, Color color) {
|
||||
if (!this->get_clipping().inside(x, y) || this->is_failed())
|
||||
return;
|
||||
|
||||
switch (this->rotation_) {
|
||||
case display::DISPLAY_ROTATION_0_DEGREES:
|
||||
break;
|
||||
case display::DISPLAY_ROTATION_90_DEGREES:
|
||||
std::swap(x, y);
|
||||
x = this->width_ - x - 1;
|
||||
break;
|
||||
case display::DISPLAY_ROTATION_180_DEGREES:
|
||||
x = this->width_ - x - 1;
|
||||
y = this->height_ - y - 1;
|
||||
break;
|
||||
case display::DISPLAY_ROTATION_270_DEGREES:
|
||||
std::swap(x, y);
|
||||
y = this->height_ - y - 1;
|
||||
break;
|
||||
}
|
||||
if (x >= this->get_width_internal() || x < 0 || y >= this->get_height_internal() || y < 0) {
|
||||
return;
|
||||
}
|
||||
if (!this->check_buffer_())
|
||||
return;
|
||||
size_t pos = (y * this->width_) + x;
|
||||
uint8_t hi_byte = static_cast<uint8_t>(color.r & 0xF8) | (color.g >> 5);
|
||||
uint8_t lo_byte = static_cast<uint8_t>((color.g & 0x1C) << 3) | (color.b >> 3);
|
||||
uint16_t new_color = hi_byte | (lo_byte << 8); // big endian
|
||||
if (this->buffer_[pos] == new_color)
|
||||
return;
|
||||
this->buffer_[pos] = new_color;
|
||||
// low and high watermark may speed up drawing from buffer
|
||||
if (x < this->x_low_)
|
||||
this->x_low_ = x;
|
||||
if (y < this->y_low_)
|
||||
this->y_low_ = y;
|
||||
if (x > this->x_high_)
|
||||
this->x_high_ = x;
|
||||
if (y > this->y_high_)
|
||||
this->y_high_ = y;
|
||||
}
|
||||
void MipiRgb::fill(Color color) {
|
||||
if (!this->check_buffer_())
|
||||
return;
|
||||
auto *ptr_16 = reinterpret_cast<uint16_t *>(this->buffer_);
|
||||
uint8_t hi_byte = static_cast<uint8_t>(color.r & 0xF8) | (color.g >> 5);
|
||||
uint8_t lo_byte = static_cast<uint8_t>((color.g & 0x1C) << 3) | (color.b >> 3);
|
||||
uint16_t new_color = lo_byte | (hi_byte << 8); // little endian
|
||||
std::fill_n(ptr_16, this->width_ * this->height_, new_color);
|
||||
}
|
||||
|
||||
int MipiRgb::get_width() {
|
||||
switch (this->rotation_) {
|
||||
case display::DISPLAY_ROTATION_90_DEGREES:
|
||||
case display::DISPLAY_ROTATION_270_DEGREES:
|
||||
return this->get_height_internal();
|
||||
case display::DISPLAY_ROTATION_0_DEGREES:
|
||||
case display::DISPLAY_ROTATION_180_DEGREES:
|
||||
default:
|
||||
return this->get_width_internal();
|
||||
}
|
||||
}
|
||||
|
||||
int MipiRgb::get_height() {
|
||||
switch (this->rotation_) {
|
||||
case display::DISPLAY_ROTATION_0_DEGREES:
|
||||
case display::DISPLAY_ROTATION_180_DEGREES:
|
||||
return this->get_height_internal();
|
||||
case display::DISPLAY_ROTATION_90_DEGREES:
|
||||
case display::DISPLAY_ROTATION_270_DEGREES:
|
||||
default:
|
||||
return this->get_width_internal();
|
||||
}
|
||||
}
|
||||
|
||||
static std::string get_pin_name(GPIOPin *pin) {
|
||||
if (pin == nullptr)
|
||||
return "None";
|
||||
return pin->dump_summary();
|
||||
}
|
||||
|
||||
void MipiRgb::dump_pins_(uint8_t start, uint8_t end, const char *name, uint8_t offset) {
|
||||
for (uint8_t i = start; i != end; i++) {
|
||||
ESP_LOGCONFIG(TAG, " %s pin %d: %s", name, offset++, this->data_pins_[i]->dump_summary().c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void MipiRgb::dump_config() {
|
||||
ESP_LOGCONFIG(TAG,
|
||||
"MIPI_RGB LCD"
|
||||
"\n Model: %s"
|
||||
"\n Width: %u"
|
||||
"\n Height: %u"
|
||||
"\n Rotation: %d degrees"
|
||||
"\n HSync Pulse Width: %u"
|
||||
"\n HSync Back Porch: %u"
|
||||
"\n HSync Front Porch: %u"
|
||||
"\n VSync Pulse Width: %u"
|
||||
"\n VSync Back Porch: %u"
|
||||
"\n VSync Front Porch: %u"
|
||||
"\n Invert Colors: %s"
|
||||
"\n Pixel Clock: %dMHz"
|
||||
"\n Reset Pin: %s"
|
||||
"\n DE Pin: %s"
|
||||
"\n PCLK Pin: %s"
|
||||
"\n HSYNC Pin: %s"
|
||||
"\n VSYNC Pin: %s",
|
||||
this->model_, this->width_, this->height_, this->rotation_, this->hsync_pulse_width_,
|
||||
this->hsync_back_porch_, this->hsync_front_porch_, this->vsync_pulse_width_, this->vsync_back_porch_,
|
||||
this->vsync_front_porch_, YESNO(this->invert_colors_), this->pclk_frequency_ / 1000000,
|
||||
get_pin_name(this->reset_pin_).c_str(), get_pin_name(this->de_pin_).c_str(),
|
||||
get_pin_name(this->pclk_pin_).c_str(), get_pin_name(this->hsync_pin_).c_str(),
|
||||
get_pin_name(this->vsync_pin_).c_str());
|
||||
|
||||
if (this->madctl_ & MADCTL_BGR) {
|
||||
this->dump_pins_(8, 13, "Blue", 0);
|
||||
this->dump_pins_(13, 16, "Green", 0);
|
||||
this->dump_pins_(0, 3, "Green", 3);
|
||||
this->dump_pins_(3, 8, "Red", 0);
|
||||
} else {
|
||||
this->dump_pins_(8, 13, "Red", 0);
|
||||
this->dump_pins_(13, 16, "Green", 0);
|
||||
this->dump_pins_(0, 3, "Green", 3);
|
||||
this->dump_pins_(3, 8, "Blue", 0);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace mipi_rgb
|
||||
} // namespace esphome
|
||||
#endif // USE_ESP32_VARIANT_ESP32S3
|
||||
127
esphome/components/mipi_rgb/mipi_rgb.h
Normal file
127
esphome/components/mipi_rgb/mipi_rgb.h
Normal file
@@ -0,0 +1,127 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef USE_ESP32_VARIANT_ESP32S3
|
||||
#include "esphome/core/gpio.h"
|
||||
#include "esphome/components/display/display.h"
|
||||
#include "esp_lcd_panel_ops.h"
|
||||
#ifdef USE_SPI
|
||||
#include "esphome/components/spi/spi.h"
|
||||
#endif
|
||||
|
||||
namespace esphome {
|
||||
namespace mipi_rgb {
|
||||
|
||||
constexpr static const char *const TAG = "display.mipi_rgb";
|
||||
const uint8_t SW_RESET_CMD = 0x01;
|
||||
const uint8_t SLEEP_OUT = 0x11;
|
||||
const uint8_t SDIR_CMD = 0xC7;
|
||||
const uint8_t MADCTL_CMD = 0x36;
|
||||
const uint8_t INVERT_OFF = 0x20;
|
||||
const uint8_t INVERT_ON = 0x21;
|
||||
const uint8_t DISPLAY_ON = 0x29;
|
||||
const uint8_t CMD2_BKSEL = 0xFF;
|
||||
const uint8_t CMD2_BK0[5] = {0x77, 0x01, 0x00, 0x00, 0x10};
|
||||
|
||||
class MipiRgb : public display::Display {
|
||||
public:
|
||||
MipiRgb(int width, int height) : width_(width), height_(height) {}
|
||||
void setup() override;
|
||||
void loop() override;
|
||||
void update() override;
|
||||
void fill(Color color);
|
||||
void draw_pixels_at(int x_start, int y_start, int w, int h, const uint8_t *ptr, display::ColorOrder order,
|
||||
display::ColorBitness bitness, bool big_endian, int x_offset, int y_offset, int x_pad) override;
|
||||
void write_to_display_(int x_start, int y_start, int w, int h, const uint8_t *ptr, int x_offset, int y_offset,
|
||||
int x_pad);
|
||||
bool check_buffer_();
|
||||
|
||||
display::ColorOrder get_color_mode() { return this->color_mode_; }
|
||||
void set_color_mode(display::ColorOrder color_mode) { this->color_mode_ = color_mode; }
|
||||
void set_invert_colors(bool invert_colors) { this->invert_colors_ = invert_colors; }
|
||||
void set_madctl(uint8_t madctl) { this->madctl_ = madctl; }
|
||||
|
||||
void add_data_pin(InternalGPIOPin *data_pin, size_t index) { this->data_pins_[index] = data_pin; };
|
||||
void set_de_pin(InternalGPIOPin *de_pin) { this->de_pin_ = de_pin; }
|
||||
void set_pclk_pin(InternalGPIOPin *pclk_pin) { this->pclk_pin_ = pclk_pin; }
|
||||
void set_vsync_pin(InternalGPIOPin *vsync_pin) { this->vsync_pin_ = vsync_pin; }
|
||||
void set_hsync_pin(InternalGPIOPin *hsync_pin) { this->hsync_pin_ = hsync_pin; }
|
||||
void set_reset_pin(GPIOPin *reset_pin) { this->reset_pin_ = reset_pin; }
|
||||
void set_width(uint16_t width) { this->width_ = width; }
|
||||
void set_pclk_frequency(uint32_t pclk_frequency) { this->pclk_frequency_ = pclk_frequency; }
|
||||
void set_pclk_inverted(bool inverted) { this->pclk_inverted_ = inverted; }
|
||||
void set_model(const char *model) { this->model_ = model; }
|
||||
int get_width() override;
|
||||
int get_height() override;
|
||||
void set_hsync_back_porch(uint16_t hsync_back_porch) { this->hsync_back_porch_ = hsync_back_porch; }
|
||||
void set_hsync_front_porch(uint16_t hsync_front_porch) { this->hsync_front_porch_ = hsync_front_porch; }
|
||||
void set_hsync_pulse_width(uint16_t hsync_pulse_width) { this->hsync_pulse_width_ = hsync_pulse_width; }
|
||||
void set_vsync_pulse_width(uint16_t vsync_pulse_width) { this->vsync_pulse_width_ = vsync_pulse_width; }
|
||||
void set_vsync_back_porch(uint16_t vsync_back_porch) { this->vsync_back_porch_ = vsync_back_porch; }
|
||||
void set_vsync_front_porch(uint16_t vsync_front_porch) { this->vsync_front_porch_ = vsync_front_porch; }
|
||||
void set_enable_pins(std::vector<GPIOPin *> enable_pins) { this->enable_pins_ = std::move(enable_pins); }
|
||||
display::DisplayType get_display_type() override { return display::DisplayType::DISPLAY_TYPE_COLOR; }
|
||||
int get_width_internal() override { return this->width_; }
|
||||
int get_height_internal() override { return this->height_; }
|
||||
void dump_pins_(uint8_t start, uint8_t end, const char *name, uint8_t offset);
|
||||
void dump_config() override;
|
||||
void draw_pixel_at(int x, int y, Color color) override;
|
||||
|
||||
// this will be horribly slow.
|
||||
protected:
|
||||
void setup_enables_();
|
||||
void common_setup_();
|
||||
InternalGPIOPin *de_pin_{nullptr};
|
||||
InternalGPIOPin *pclk_pin_{nullptr};
|
||||
InternalGPIOPin *hsync_pin_{nullptr};
|
||||
InternalGPIOPin *vsync_pin_{nullptr};
|
||||
GPIOPin *reset_pin_{nullptr};
|
||||
InternalGPIOPin *data_pins_[16] = {};
|
||||
uint16_t hsync_pulse_width_ = 10;
|
||||
uint16_t hsync_back_porch_ = 10;
|
||||
uint16_t hsync_front_porch_ = 20;
|
||||
uint16_t vsync_pulse_width_ = 10;
|
||||
uint16_t vsync_back_porch_ = 10;
|
||||
uint16_t vsync_front_porch_ = 10;
|
||||
uint32_t pclk_frequency_ = 16 * 1000 * 1000;
|
||||
bool pclk_inverted_{true};
|
||||
uint8_t madctl_{};
|
||||
const char *model_{"Unknown"};
|
||||
bool invert_colors_{};
|
||||
display::ColorOrder color_mode_{display::COLOR_ORDER_BGR};
|
||||
size_t width_;
|
||||
size_t height_;
|
||||
uint16_t *buffer_{nullptr};
|
||||
std::vector<GPIOPin *> enable_pins_{};
|
||||
uint16_t x_low_{1};
|
||||
uint16_t y_low_{1};
|
||||
uint16_t x_high_{0};
|
||||
uint16_t y_high_{0};
|
||||
|
||||
esp_lcd_panel_handle_t handle_{};
|
||||
};
|
||||
|
||||
#ifdef USE_SPI
|
||||
class MipiRgbSpi : public MipiRgb,
|
||||
public spi::SPIDevice<spi::BIT_ORDER_MSB_FIRST, spi::CLOCK_POLARITY_LOW, spi::CLOCK_PHASE_LEADING,
|
||||
spi::DATA_RATE_1MHZ> {
|
||||
public:
|
||||
MipiRgbSpi(int width, int height) : MipiRgb(width, height) {}
|
||||
|
||||
void set_init_sequence(const std::vector<uint8_t> &init_sequence) { this->init_sequence_ = init_sequence; }
|
||||
void set_dc_pin(GPIOPin *dc_pin) { this->dc_pin_ = dc_pin; }
|
||||
void setup() override;
|
||||
|
||||
protected:
|
||||
void write_command_(uint8_t value);
|
||||
void write_data_(uint8_t value);
|
||||
void write_init_sequence_();
|
||||
void dump_config();
|
||||
|
||||
GPIOPin *dc_pin_{nullptr};
|
||||
std::vector<uint8_t> init_sequence_;
|
||||
};
|
||||
#endif
|
||||
|
||||
} // namespace mipi_rgb
|
||||
} // namespace esphome
|
||||
#endif
|
||||
24
esphome/components/mipi_rgb/models/guition.py
Normal file
24
esphome/components/mipi_rgb/models/guition.py
Normal file
@@ -0,0 +1,24 @@
|
||||
from .st7701s import st7701s
|
||||
|
||||
st7701s.extend(
|
||||
"GUITION-4848S040",
|
||||
width=480,
|
||||
height=480,
|
||||
data_rate="2MHz",
|
||||
cs_pin=39,
|
||||
de_pin=18,
|
||||
hsync_pin=16,
|
||||
vsync_pin=17,
|
||||
pclk_pin=21,
|
||||
pclk_frequency="12MHz",
|
||||
pixel_mode="18bit",
|
||||
mirror_x=True,
|
||||
mirror_y=True,
|
||||
data_pins={
|
||||
"red": [11, 12, 13, 14, 0],
|
||||
"green": [8, 20, 3, 46, 9, 10],
|
||||
"blue": [4, 5, 6, 7, 15],
|
||||
},
|
||||
# Additional configuration for Guition 4848S040, 16 bit bus config
|
||||
add_init_sequence=((0xCD, 0x00),),
|
||||
)
|
||||
@@ -0,0 +1,228 @@
|
||||
from esphome.config_validation import UNDEFINED
|
||||
|
||||
from .st7701s import ST7701S
|
||||
|
||||
# fmt: off
|
||||
ST7701S(
|
||||
"T-PANEL-S3",
|
||||
width=480,
|
||||
height=480,
|
||||
color_order="BGR",
|
||||
invert_colors=False,
|
||||
swap_xy=UNDEFINED,
|
||||
spi_mode="MODE3",
|
||||
cs_pin={"xl9535": None, "number": 17},
|
||||
reset_pin={"xl9535": None, "number": 5},
|
||||
hsync_pin=39,
|
||||
vsync_pin=40,
|
||||
pclk_pin=41,
|
||||
data_pins={
|
||||
"red": [12, 13, 42, 46, 45],
|
||||
"green": [6, 7, 8, 9, 10, 11],
|
||||
"blue": [1, 2, 3, 4, 5],
|
||||
},
|
||||
hsync_front_porch=20,
|
||||
hsync_back_porch=0,
|
||||
hsync_pulse_width=2,
|
||||
vsync_front_porch=30,
|
||||
vsync_back_porch=1,
|
||||
vsync_pulse_width=8,
|
||||
pclk_frequency="6MHz",
|
||||
pclk_inverted=False,
|
||||
initsequence=(
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x13), (0xEF, 0x08), (0xFF, 0x77, 0x01, 0x00, 0x00, 0x10),
|
||||
(0xC0, 0x3B, 0x00), (0xC1, 0x0B, 0x02), (0xC2, 0x30, 0x02, 0x37), (0xCC, 0x10),
|
||||
(0xB0, 0x00, 0x0F, 0x16, 0x0E, 0x11, 0x07, 0x09, 0x09, 0x08, 0x23, 0x05, 0x11, 0x0F, 0x28, 0x2D, 0x18),
|
||||
(0xB1, 0x00, 0x0F, 0x16, 0x0E, 0x11, 0x07, 0x09, 0x08, 0x09, 0x23, 0x05, 0x11, 0x0F, 0x28, 0x2D, 0x18),
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x11),
|
||||
(0xB0, 0x4D), (0xB1, 0x33), (0xB2, 0x87), (0xB5, 0x4B), (0xB7, 0x8C), (0xB8, 0x20), (0xC1, 0x78),
|
||||
(0xC2, 0x78), (0xD0, 0x88), (0xE0, 0x00, 0x00, 0x02),
|
||||
(0xE1, 0x02, 0xF0, 0x00, 0x00, 0x03, 0xF0, 0x00, 0x00, 0x00, 0x44, 0x44),
|
||||
(0xE2, 0x10, 0x10, 0x40, 0x40, 0xF2, 0xF0, 0x00, 0x00, 0xF2, 0xF0, 0x00, 0x00),
|
||||
(0xE3, 0x00, 0x00, 0x11, 0x11), (0xE4, 0x44, 0x44),
|
||||
(0xE5, 0x07, 0xEF, 0xF0, 0xF0, 0x09, 0xF1, 0xF0, 0xF0, 0x03, 0xF3, 0xF0, 0xF0, 0x05, 0xED, 0xF0, 0xF0),
|
||||
(0xE6, 0x00, 0x00, 0x11, 0x11), (0xE7, 0x44, 0x44),
|
||||
(0xE8, 0x08, 0xF0, 0xF0, 0xF0, 0x0A, 0xF2, 0xF0, 0xF0, 0x04, 0xF4, 0xF0, 0xF0, 0x06, 0xEE, 0xF0, 0xF0),
|
||||
(0xEB, 0x00, 0x00, 0xE4, 0xE4, 0x44, 0x88, 0x40),
|
||||
(0xEC, 0x78, 0x00),
|
||||
(0xED, 0x20, 0xF9, 0x87, 0x76, 0x65, 0x54, 0x4F, 0xFF, 0xFF, 0xF4, 0x45, 0x56, 0x67, 0x78, 0x9F, 0x02),
|
||||
(0xEF, 0x10, 0x0D, 0x04, 0x08, 0x3F, 0x1F),
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x10),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
t_rgb = ST7701S(
|
||||
"T-RGB-2.1",
|
||||
width=480,
|
||||
height=480,
|
||||
color_order="BGR",
|
||||
pixel_mode="18bit",
|
||||
invert_colors=False,
|
||||
swap_xy=UNDEFINED,
|
||||
spi_mode="MODE3",
|
||||
cs_pin={"xl9535": None, "number": 3},
|
||||
de_pin=45,
|
||||
hsync_pin=47,
|
||||
vsync_pin=41,
|
||||
pclk_pin=42,
|
||||
data_pins={
|
||||
"red": [7, 6, 5, 3, 2],
|
||||
"green": [14, 13, 12, 11, 10, 9],
|
||||
"blue": [21, 18, 17, 16, 15],
|
||||
},
|
||||
hsync_front_porch=50,
|
||||
hsync_pulse_width=1,
|
||||
hsync_back_porch=30,
|
||||
vsync_front_porch=20,
|
||||
vsync_pulse_width=1,
|
||||
vsync_back_porch=30,
|
||||
pclk_frequency="12MHz",
|
||||
pclk_inverted=False,
|
||||
initsequence=(
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x10),
|
||||
|
||||
(0xC0, 0x3B, 0x00),
|
||||
(0xC1, 0x0B, 0x02),
|
||||
(0xC2, 0x07, 0x02),
|
||||
(0xCC, 0x10),
|
||||
(0xCD, 0x08),
|
||||
|
||||
(0xB0,
|
||||
0x00, 0x11, 0x16, 0x0e,
|
||||
0x11, 0x06, 0x05, 0x09,
|
||||
0x08, 0x21, 0x06, 0x13,
|
||||
0x10, 0x29, 0x31, 0x18),
|
||||
|
||||
(0xB1,
|
||||
0x00, 0x11, 0x16, 0x0e,
|
||||
0x11, 0x07, 0x05, 0x09,
|
||||
0x09, 0x21, 0x05, 0x13,
|
||||
0x11, 0x2a, 0x31, 0x18),
|
||||
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x11),
|
||||
|
||||
(0xB0, 0x6D),
|
||||
(0xB1, 0x37),
|
||||
(0xB2, 0x81),
|
||||
(0xB3, 0x80),
|
||||
(0xB5, 0x43),
|
||||
(0xB7, 0x85),
|
||||
(0xB8, 0x20),
|
||||
|
||||
(0xC1, 0x78),
|
||||
(0xC2, 0x78),
|
||||
(0xC3, 0x8C),
|
||||
|
||||
(0xD0, 0x88),
|
||||
|
||||
(0xE0, 0x00, 0x00, 0x02),
|
||||
(0xE1,
|
||||
0x03, 0xA0, 0x00, 0x00,
|
||||
0x04, 0xA0, 0x00, 0x00,
|
||||
0x00, 0x20, 0x20),
|
||||
|
||||
(0xE2,
|
||||
0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00,
|
||||
0x00),
|
||||
|
||||
(0xE3, 0x00, 0x00, 0x11, 0x00),
|
||||
(0xE4, 0x22, 0x00),
|
||||
|
||||
(0xE5,
|
||||
0x05, 0xEC, 0xA0, 0xA0,
|
||||
0x07, 0xEE, 0xA0, 0xA0,
|
||||
0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00),
|
||||
|
||||
(0xE6, 0x00, 0x00, 0x11, 0x00),
|
||||
(0xE7, 0x22, 0x00),
|
||||
|
||||
(0xE8,
|
||||
0x06, 0xED, 0xA0, 0xA0,
|
||||
0x08, 0xEF, 0xA0, 0xA0,
|
||||
0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00),
|
||||
|
||||
(0xEB, 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x10),
|
||||
|
||||
(0xED,
|
||||
0xFF, 0xFF, 0xFF, 0xBA,
|
||||
0x0A, 0xBF, 0x45, 0xFF,
|
||||
0xFF, 0x54, 0xFB, 0xA0,
|
||||
0xAB, 0xFF, 0xFF, 0xFF),
|
||||
|
||||
(0xEF, 0x10, 0x0D, 0x04, 0x08, 0x3F, 0x1F),
|
||||
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x13),
|
||||
(0xEF, 0x08),
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x10)
|
||||
)
|
||||
|
||||
)
|
||||
t_rgb.extend(
|
||||
"T-RGB-2.8",
|
||||
initsequence=(
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x13),
|
||||
(0xEF, 0x08),
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x10),
|
||||
(0xC0, 0x3B, 0x00),
|
||||
(0xC1, 0x10, 0x0C),
|
||||
(0xC2, 0x07, 0x0A),
|
||||
(0xC7, 0x00),
|
||||
(0xC7, 0x10),
|
||||
(0xCD, 0x08),
|
||||
(0xB0,
|
||||
0x05, 0x12, 0x98, 0x0e, 0x0F,
|
||||
0x07, 0x07, 0x09, 0x09, 0x23,
|
||||
0x05, 0x52, 0x0F, 0x67, 0x2C, 0x11),
|
||||
(0xB1,
|
||||
0x0B, 0x11, 0x97, 0x0C, 0x12,
|
||||
0x06, 0x06, 0x08, 0x08, 0x22,
|
||||
0x03, 0x51, 0x11, 0x66, 0x2B, 0x0F),
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x11),
|
||||
(0xB0, 0x5D),
|
||||
(0xB1, 0x2D),
|
||||
(0xB2, 0x81),
|
||||
(0xB3, 0x80),
|
||||
(0xB5, 0x4E),
|
||||
(0xB7, 0x85),
|
||||
(0xB8, 0x20),
|
||||
(0xC1, 0x78),
|
||||
(0xC2, 0x78),
|
||||
(0xD0, 0x88),
|
||||
(0xE0, 0x00, 0x00, 0x02),
|
||||
(0xE1,
|
||||
0x06, 0x30, 0x08, 0x30, 0x05,
|
||||
0x30, 0x07, 0x30, 0x00, 0x33,
|
||||
0x33),
|
||||
(0xE2,
|
||||
0x11, 0x11, 0x33, 0x33, 0xf4,
|
||||
0x00, 0x00, 0x00, 0xf4, 0x00,
|
||||
0x00, 0x00),
|
||||
(0xE3, 0x00, 0x00, 0x11, 0x11),
|
||||
(0xE4, 0x44, 0x44),
|
||||
(0xE5,
|
||||
0x0d, 0xf5, 0x30, 0xf0, 0x0f,
|
||||
0xf7, 0x30, 0xf0, 0x09, 0xf1,
|
||||
0x30, 0xf0, 0x0b, 0xf3, 0x30, 0xf0),
|
||||
(0xE6, 0x00, 0x00, 0x11, 0x11),
|
||||
(0xE7, 0x44, 0x44),
|
||||
(0xE8,
|
||||
0x0c, 0xf4, 0x30, 0xf0,
|
||||
0x0e, 0xf6, 0x30, 0xf0,
|
||||
0x08, 0xf0, 0x30, 0xf0,
|
||||
0x0a, 0xf2, 0x30, 0xf0),
|
||||
(0xe9, 0x36),
|
||||
(0xEB, 0x00, 0x01, 0xe4, 0xe4, 0x44, 0x88, 0x40),
|
||||
(0xED,
|
||||
0xff, 0x10, 0xaf, 0x76,
|
||||
0x54, 0x2b, 0xcf, 0xff,
|
||||
0xff, 0xfc, 0xb2, 0x45,
|
||||
0x67, 0xfa, 0x01, 0xff),
|
||||
(0xEF, 0x08, 0x08, 0x08, 0x45, 0x3f, 0x54),
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x10),
|
||||
)
|
||||
)
|
||||
|
||||
9
esphome/components/mipi_rgb/models/rpi.py
Normal file
9
esphome/components/mipi_rgb/models/rpi.py
Normal file
@@ -0,0 +1,9 @@
|
||||
from esphome.components.mipi import DriverChip
|
||||
from esphome.config_validation import UNDEFINED
|
||||
|
||||
# A driver chip for Raspberry Pi MIPI RGB displays. These require no init sequence
|
||||
DriverChip(
|
||||
"RPI",
|
||||
swap_xy=UNDEFINED,
|
||||
initsequence=(),
|
||||
)
|
||||
214
esphome/components/mipi_rgb/models/st7701s.py
Normal file
214
esphome/components/mipi_rgb/models/st7701s.py
Normal file
@@ -0,0 +1,214 @@
|
||||
from esphome.components.mipi import (
|
||||
MADCTL,
|
||||
MADCTL_ML,
|
||||
MADCTL_XFLIP,
|
||||
MODE_BGR,
|
||||
DriverChip,
|
||||
)
|
||||
from esphome.config_validation import UNDEFINED
|
||||
from esphome.const import CONF_COLOR_ORDER, CONF_HEIGHT, CONF_MIRROR_X, CONF_MIRROR_Y
|
||||
|
||||
SDIR_CMD = 0xC7
|
||||
|
||||
|
||||
class ST7701S(DriverChip):
|
||||
# The ST7701s does not use the standard MADCTL bits for x/y mirroring
|
||||
def add_madctl(self, sequence: list, config: dict):
|
||||
transform = self.get_transform(config)
|
||||
madctl = 0x00
|
||||
if config[CONF_COLOR_ORDER] == MODE_BGR:
|
||||
madctl |= 0x08
|
||||
if transform.get(CONF_MIRROR_Y):
|
||||
madctl |= MADCTL_ML
|
||||
sequence.append((MADCTL, madctl))
|
||||
sdir = 0
|
||||
if transform.get(CONF_MIRROR_X):
|
||||
sdir |= 0x04
|
||||
madctl |= MADCTL_XFLIP
|
||||
sequence.append((SDIR_CMD, sdir))
|
||||
return madctl
|
||||
|
||||
@property
|
||||
def transforms(self) -> set[str]:
|
||||
"""
|
||||
The ST7701 never supports axis swapping, and mirroring the y-axis only works for full height.
|
||||
"""
|
||||
if self.get_default(CONF_HEIGHT) != 864:
|
||||
return {CONF_MIRROR_X}
|
||||
return {CONF_MIRROR_X, CONF_MIRROR_Y}
|
||||
|
||||
|
||||
# fmt: off
|
||||
st7701s = ST7701S(
|
||||
"ST7701S",
|
||||
width=480,
|
||||
height=864,
|
||||
swap_xy=UNDEFINED,
|
||||
hsync_front_porch=20,
|
||||
hsync_back_porch=10,
|
||||
hsync_pulse_width=10,
|
||||
vsync_front_porch=10,
|
||||
vsync_back_porch=10,
|
||||
vsync_pulse_width=10,
|
||||
pclk_frequency="16MHz",
|
||||
pclk_inverted=True,
|
||||
initsequence=(
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x10), # Page 0
|
||||
(0xC0, 0x3B, 0x00), (0xC1, 0x0D, 0x02), (0xC2, 0x31, 0x05),
|
||||
(0xB0, 0x00, 0x11, 0x18, 0x0E, 0x11, 0x06, 0x07, 0x08, 0x07, 0x22, 0x04, 0x12, 0x0F, 0xAA, 0x31, 0x18,),
|
||||
(0xB1, 0x00, 0x11, 0x19, 0x0E, 0x12, 0x07, 0x08, 0x08, 0x08, 0x22, 0x04, 0x11, 0x11, 0xA9, 0x32, 0x18,),
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x11), # page 1
|
||||
(0xB0, 0x60), (0xB1, 0x32), (0xB2, 0x07), (0xB3, 0x80), (0xB5, 0x49), (0xB7, 0x85), (0xB8, 0x21), (0xC1, 0x78),
|
||||
(0xC2, 0x78), (0xE0, 0x00, 0x1B, 0x02),
|
||||
(0xE1, 0x08, 0xA0, 0x00, 0x00, 0x07, 0xA0, 0x00, 0x00, 0x00, 0x44, 0x44),
|
||||
(0xE2, 0x11, 0x11, 0x44, 0x44, 0xED, 0xA0, 0x00, 0x00, 0xEC, 0xA0, 0x00, 0x00),
|
||||
(0xE3, 0x00, 0x00, 0x11, 0x11),
|
||||
(0xE4, 0x44, 0x44),
|
||||
(0xE5, 0x0A, 0xE9, 0xD8, 0xA0, 0x0C, 0xEB, 0xD8, 0xA0, 0x0E, 0xED, 0xD8, 0xA0, 0x10, 0xEF, 0xD8, 0xA0,),
|
||||
(0xE6, 0x00, 0x00, 0x11, 0x11), (0xE7, 0x44, 0x44),
|
||||
(0xE8, 0x09, 0xE8, 0xD8, 0xA0, 0x0B, 0xEA, 0xD8, 0xA0, 0x0D, 0xEC, 0xD8, 0xA0, 0x0F, 0xEE, 0xD8, 0xA0,),
|
||||
(0xEB, 0x02, 0x00, 0xE4, 0xE4, 0x88, 0x00, 0x40), (0xEC, 0x3C, 0x00),
|
||||
(0xED, 0xAB, 0x89, 0x76, 0x54, 0x02, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x20, 0x45, 0x67, 0x98, 0xBA,),
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x13), # Page 3
|
||||
(0xE5, 0xE4),
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x10), # Page 0
|
||||
(0xCD, 0x08),
|
||||
)
|
||||
)
|
||||
|
||||
st7701s.extend(
|
||||
"MAKERFABS-4",
|
||||
width=480,
|
||||
height=480,
|
||||
color_order="RGB",
|
||||
invert_colors=True,
|
||||
pixel_mode="18bit",
|
||||
cs_pin=1,
|
||||
de_pin={
|
||||
"number": 45,
|
||||
"ignore_strapping_warning": True
|
||||
},
|
||||
hsync_pin=5,
|
||||
vsync_pin=4,
|
||||
pclk_pin=21,
|
||||
data_pins={
|
||||
"red": [39, 40, 41, 42, 2],
|
||||
"green": [0, 9, 14, 47, 48, 3],
|
||||
"blue": [6, 7, 15, 16, 8]
|
||||
}
|
||||
)
|
||||
|
||||
st7701s.extend(
|
||||
"SEEED-INDICATOR-D1",
|
||||
width=480,
|
||||
height=480,
|
||||
mirror_x=True,
|
||||
mirror_y=True,
|
||||
invert_colors=True,
|
||||
pixel_mode="18bit",
|
||||
spi_mode="MODE3",
|
||||
data_rate="2MHz",
|
||||
hsync_front_porch=10,
|
||||
hsync_pulse_width=8,
|
||||
hsync_back_porch=50,
|
||||
vsync_front_porch=10,
|
||||
vsync_pulse_width=8,
|
||||
vsync_back_porch=20,
|
||||
cs_pin={"pca9554": None, "number": 4},
|
||||
de_pin=18,
|
||||
hsync_pin=16,
|
||||
vsync_pin=17,
|
||||
pclk_pin=21,
|
||||
pclk_inverted=False,
|
||||
data_pins={
|
||||
"red": [4, 3, 2, 1, 0],
|
||||
"green": [10, 9, 8, 7, 6, 5],
|
||||
"blue": [15, 14, 13, 12, 11]
|
||||
},
|
||||
)
|
||||
|
||||
st7701s.extend(
|
||||
"UEDX48480021-MD80ET",
|
||||
width=480,
|
||||
height=480,
|
||||
pixel_mode="18bit",
|
||||
cs_pin=18,
|
||||
reset_pin=8,
|
||||
de_pin=17,
|
||||
vsync_pin={"number": 3, "ignore_strapping_warning": True},
|
||||
hsync_pin={"number": 46, "ignore_strapping_warning": True},
|
||||
pclk_pin=9,
|
||||
data_pins={
|
||||
"red": [40, 41, 42, 2, 1],
|
||||
"green": [21, 47, 48, 45, 38, 39],
|
||||
"blue": [10, 11, {"number": 12, "allow_other_uses": True}, {"number": 13, "allow_other_uses": True}, 14]
|
||||
},
|
||||
initsequence=(
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x13), (0xEF, 0x08), (0xFF, 0x77, 0x01, 0x00, 0x00, 0x10),
|
||||
(0xC0, 0x3B, 0x00), (0xC1, 0x0B, 0x02), (0xC2, 0x07, 0x02), (0xC7, 0x00), (0xCC, 0x10), (0xCD, 0x08),
|
||||
(0xB0, 0x00, 0x11, 0x16, 0x0E, 0x11, 0x06, 0x05, 0x09, 0x08, 0x21, 0x06, 0x13, 0x10, 0x29, 0x31, 0x18),
|
||||
(0xB1, 0x00, 0x11, 0x16, 0x0E, 0x11, 0x07, 0x05, 0x09, 0x09, 0x21, 0x05, 0x13, 0x11, 0x2A, 0x31, 0x18),
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x11),
|
||||
(0xB0, 0x6D), (0xB1, 0x37), (0xB2, 0x8B), (0xB3, 0x80), (0xB5, 0x43), (0xB7, 0x85),
|
||||
(0xB8, 0x20), (0xC0, 0x09), (0xC1, 0x78), (0xC2, 0x78), (0xD0, 0x88),
|
||||
(0xE0, 0x00, 0x00, 0x02),
|
||||
(0xE1, 0x03, 0xA0, 0x00, 0x00, 0x04, 0xA0, 0x00, 0x00, 0x00, 0x20, 0x20),
|
||||
(0xE2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00),
|
||||
(0xE3, 0x00, 0x00, 0x11, 0x00),
|
||||
(0xE4, 0x22, 0x00),
|
||||
(0xE5, 0x05, 0xEC, 0xF6, 0xCA, 0x07, 0xEE, 0xF6, 0xCA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00),
|
||||
(0xE6, 0x00, 0x00, 0x11, 0x00),
|
||||
(0xE7, 0x22, 0x00),
|
||||
(0xE8, 0x06, 0xED, 0xF6, 0xCA, 0x08, 0xEF, 0xF6, 0xCA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00),
|
||||
(0xE9, 0x36, 0x00),
|
||||
(0xEB, 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x00),
|
||||
(0xED, 0xFF, 0xFF, 0xFF, 0xBA, 0x0A, 0xFF, 0x45, 0xFF, 0xFF, 0x54, 0xFF, 0xA0, 0xAB, 0xFF, 0xFF, 0xFF),
|
||||
(0xEF, 0x08, 0x08, 0x08, 0x45, 0x3F, 0x54),
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x13), (0xE8, 0x00, 0x0E), (0xFF, 0x77, 0x01, 0x00, 0x00, 0x00),
|
||||
(0x11, 0x00), (0xFF, 0x77, 0x01, 0x00, 0x00, 0x13), (0xE8, 0x00, 0x0C),
|
||||
(0xE8, 0x00, 0x00), (0xFF, 0x77, 0x01, 0x00, 0x00, 0x00)
|
||||
)
|
||||
)
|
||||
|
||||
st7701s.extend(
|
||||
"ZX2D10GE01R-V4848",
|
||||
width=480,
|
||||
height=480,
|
||||
pixel_mode="18bit",
|
||||
cs_pin=21,
|
||||
de_pin=39,
|
||||
vsync_pin=48,
|
||||
hsync_pin=40,
|
||||
pclk_pin={"number": 45, "ignore_strapping_warning": True},
|
||||
pclk_frequency="15MHz",
|
||||
pclk_inverted=True,
|
||||
hsync_pulse_width=10,
|
||||
hsync_back_porch=10,
|
||||
hsync_front_porch=10,
|
||||
vsync_pulse_width=2,
|
||||
vsync_back_porch=12,
|
||||
vsync_front_porch=14,
|
||||
data_pins={
|
||||
"red": [10, 16, 9, 15, 46],
|
||||
"green": [8, 13, 18, 12, 11, 17],
|
||||
"blue": [{"number": 47, "allow_other_uses": True}, {"number": 41, "allow_other_uses": True}, 0, 42, 14]
|
||||
},
|
||||
initsequence=(
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x13), (0xEF, 0x08), (0xFF, 0x77, 0x01, 0x00, 0x00, 0x10), (0xC0, 0x3B, 0x00),
|
||||
(0xC1, 0x0B, 0x02), (0xC2, 0x07, 0x02), (0xCC, 0x10), (0xCD, 0x08),
|
||||
(0xB0, 0x00, 0x11, 0x16, 0x0e, 0x11, 0x06, 0x05, 0x09, 0x08, 0x21, 0x06, 0x13, 0x10, 0x29, 0x31, 0x18),
|
||||
(0xB1, 0x00, 0x11, 0x16, 0x0e, 0x11, 0x07, 0x05, 0x09, 0x09, 0x21, 0x05, 0x13, 0x11, 0x2a, 0x31, 0x18),
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x11), (0xB0, 0x6d), (0xB1, 0x37), (0xB2, 0x81), (0xB3, 0x80), (0xB5, 0x43),
|
||||
(0xB7, 0x85), (0xB8, 0x20), (0xC1, 0x78), (0xC2, 0x78), (0xD0, 0x88), (0xE0, 0x00, 0x00, 0x02),
|
||||
(0xE1, 0x03, 0xA0, 0x00, 0x00, 0x04, 0xA0, 0x00, 0x00, 0x00, 0x20, 0x20),
|
||||
(0xE2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00),
|
||||
(0xE3, 0x00, 0x00, 0x11, 0x00), (0xE4, 0x22, 0x00),
|
||||
(0xE5, 0x05, 0xEC, 0xA0, 0xA0, 0x07, 0xEE, 0xA0, 0xA0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00),
|
||||
(0xE6, 0x00, 0x00, 0x11, 0x00), (0xE7, 0x22, 0x00),
|
||||
(0xE8, 0x06, 0xED, 0xA0, 0xA0, 0x08, 0xEF, 0xA0, 0xA0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00),
|
||||
(0xEB, 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x00),
|
||||
(0xED, 0xFF, 0xFF, 0xFF, 0xBA, 0x0A, 0xBF, 0x45, 0xFF, 0xFF, 0x54, 0xFB, 0xA0, 0xAB, 0xFF, 0xFF, 0xFF),
|
||||
(0xEF, 0x10, 0x0D, 0x04, 0x08, 0x3F, 0x1F),
|
||||
(0xFF, 0x77, 0x01, 0x00, 0x00, 0x13), (0xEF, 0x08), (0xFF, 0x77, 0x01, 0x00, 0x00, 0x00)
|
||||
)
|
||||
)
|
||||
64
esphome/components/mipi_rgb/models/waveshare.py
Normal file
64
esphome/components/mipi_rgb/models/waveshare.py
Normal file
@@ -0,0 +1,64 @@
|
||||
from esphome.components.mipi import DriverChip
|
||||
from esphome.config_validation import UNDEFINED
|
||||
|
||||
from .st7701s import st7701s
|
||||
|
||||
wave_4_3 = DriverChip(
|
||||
"ESP32-S3-TOUCH-LCD-4.3",
|
||||
swap_xy=UNDEFINED,
|
||||
initsequence=(),
|
||||
width=800,
|
||||
height=480,
|
||||
pclk_frequency="16MHz",
|
||||
reset_pin={"ch422g": None, "number": 3},
|
||||
enable_pin={"ch422g": None, "number": 2},
|
||||
de_pin=5,
|
||||
hsync_pin={"number": 46, "ignore_strapping_warning": True},
|
||||
vsync_pin={"number": 3, "ignore_strapping_warning": True},
|
||||
pclk_pin=7,
|
||||
pclk_inverted=True,
|
||||
hsync_front_porch=210,
|
||||
hsync_pulse_width=30,
|
||||
hsync_back_porch=30,
|
||||
vsync_front_porch=4,
|
||||
vsync_pulse_width=4,
|
||||
vsync_back_porch=4,
|
||||
data_pins={
|
||||
"red": [1, 2, 42, 41, 40],
|
||||
"green": [39, 0, 45, 48, 47, 21],
|
||||
"blue": [14, 38, 18, 17, 10],
|
||||
},
|
||||
)
|
||||
wave_4_3.extend(
|
||||
"ESP32-S3-TOUCH-LCD-7-800X480",
|
||||
enable_pin=[{"ch422g": None, "number": 2}, {"ch422g": None, "number": 6}],
|
||||
hsync_back_porch=8,
|
||||
hsync_front_porch=8,
|
||||
hsync_pulse_width=4,
|
||||
vsync_back_porch=16,
|
||||
vsync_front_porch=16,
|
||||
vsync_pulse_width=4,
|
||||
)
|
||||
|
||||
st7701s.extend(
|
||||
"WAVESHARE-4-480x480",
|
||||
data_rate="2MHz",
|
||||
spi_mode="MODE3",
|
||||
color_order="BGR",
|
||||
pixel_mode="18bit",
|
||||
width=480,
|
||||
height=480,
|
||||
invert_colors=True,
|
||||
cs_pin=42,
|
||||
de_pin=40,
|
||||
hsync_pin=38,
|
||||
vsync_pin=39,
|
||||
pclk_pin=41,
|
||||
pclk_frequency="12MHz",
|
||||
pclk_inverted=False,
|
||||
data_pins={
|
||||
"red": [46, 3, 8, 18, 17],
|
||||
"green": [14, 13, 12, 11, 10, 9],
|
||||
"blue": [5, 45, 48, 47, 21],
|
||||
},
|
||||
)
|
||||
@@ -19,13 +19,14 @@ void MS5611Component::setup() {
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
delay(100); // NOLINT
|
||||
for (uint8_t offset = 0; offset < 6; offset++) {
|
||||
if (!this->read_byte_16(MS5611_CMD_READ_PROM + (offset * 2), &this->prom_[offset])) {
|
||||
this->mark_failed();
|
||||
return;
|
||||
this->set_timeout(100, [this]() {
|
||||
for (uint8_t offset = 0; offset < 6; offset++) {
|
||||
if (!this->read_byte_16(MS5611_CMD_READ_PROM + (offset * 2), &this->prom_[offset])) {
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
void MS5611Component::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "MS5611:");
|
||||
|
||||
@@ -11,7 +11,10 @@ static const char *const TAG = "nextion.upload";
|
||||
bool Nextion::upload_end_(bool successful) {
|
||||
if (successful) {
|
||||
ESP_LOGD(TAG, "Upload successful");
|
||||
delay(1500); // NOLINT
|
||||
for (uint8_t i = 0; i <= 5; i++) {
|
||||
delay(1000); // NOLINT
|
||||
App.feed_wdt(); // Feed the watchdog timer.
|
||||
}
|
||||
App.safe_reboot();
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Upload failed");
|
||||
|
||||
@@ -14,6 +14,7 @@ from esphome.const import (
|
||||
|
||||
CODEOWNERS = ["@Mat931"]
|
||||
DEPENDENCIES = ["i2c"]
|
||||
AUTO_LOAD = ["gpio_expander"]
|
||||
MULTI_CONF = True
|
||||
pca6416a_ns = cg.esphome_ns.namespace("pca6416a")
|
||||
|
||||
|
||||
@@ -51,6 +51,11 @@ void PCA6416AComponent::setup() {
|
||||
this->status_has_error());
|
||||
}
|
||||
|
||||
void PCA6416AComponent::loop() {
|
||||
// Invalidate cache at the start of each loop
|
||||
this->reset_pin_cache_();
|
||||
}
|
||||
|
||||
void PCA6416AComponent::dump_config() {
|
||||
if (this->has_pullup_) {
|
||||
ESP_LOGCONFIG(TAG, "PCAL6416A:");
|
||||
@@ -63,15 +68,25 @@ void PCA6416AComponent::dump_config() {
|
||||
}
|
||||
}
|
||||
|
||||
bool PCA6416AComponent::digital_read(uint8_t pin) {
|
||||
uint8_t bit = pin % 8;
|
||||
bool PCA6416AComponent::digital_read_hw(uint8_t pin) {
|
||||
uint8_t reg_addr = pin < 8 ? PCA6416A_INPUT0 : PCA6416A_INPUT1;
|
||||
uint8_t value = 0;
|
||||
this->read_register_(reg_addr, &value);
|
||||
return value & (1 << bit);
|
||||
if (!this->read_register_(reg_addr, &value)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Update the appropriate part of input_mask_
|
||||
if (pin < 8) {
|
||||
this->input_mask_ = (this->input_mask_ & 0xFF00) | value;
|
||||
} else {
|
||||
this->input_mask_ = (this->input_mask_ & 0x00FF) | (uint16_t(value) << 8);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void PCA6416AComponent::digital_write(uint8_t pin, bool value) {
|
||||
bool PCA6416AComponent::digital_read_cache(uint8_t pin) { return this->input_mask_ & (1 << pin); }
|
||||
|
||||
void PCA6416AComponent::digital_write_hw(uint8_t pin, bool value) {
|
||||
uint8_t reg_addr = pin < 8 ? PCA6416A_OUTPUT0 : PCA6416A_OUTPUT1;
|
||||
this->update_register_(pin, value, reg_addr);
|
||||
}
|
||||
|
||||
@@ -3,20 +3,20 @@
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/components/i2c/i2c.h"
|
||||
#include "esphome/components/gpio_expander/cached_gpio.h"
|
||||
|
||||
namespace esphome {
|
||||
namespace pca6416a {
|
||||
|
||||
class PCA6416AComponent : public Component, public i2c::I2CDevice {
|
||||
class PCA6416AComponent : public Component,
|
||||
public i2c::I2CDevice,
|
||||
public gpio_expander::CachedGpioExpander<uint8_t, 16> {
|
||||
public:
|
||||
PCA6416AComponent() = default;
|
||||
|
||||
/// Check i2c availability and setup masks
|
||||
void setup() override;
|
||||
/// Helper function to read the value of a pin.
|
||||
bool digital_read(uint8_t pin);
|
||||
/// Helper function to write the value of a pin.
|
||||
void digital_write(uint8_t pin, bool value);
|
||||
void loop() override;
|
||||
/// Helper function to set the pin mode of a pin.
|
||||
void pin_mode(uint8_t pin, gpio::Flags flags);
|
||||
|
||||
@@ -25,6 +25,11 @@ class PCA6416AComponent : public Component, public i2c::I2CDevice {
|
||||
void dump_config() override;
|
||||
|
||||
protected:
|
||||
// Virtual methods from CachedGpioExpander
|
||||
bool digital_read_hw(uint8_t pin) override;
|
||||
bool digital_read_cache(uint8_t pin) override;
|
||||
void digital_write_hw(uint8_t pin, bool value) override;
|
||||
|
||||
bool read_register_(uint8_t reg, uint8_t *value);
|
||||
bool write_register_(uint8_t reg, uint8_t value);
|
||||
void update_register_(uint8_t pin, bool pin_value, uint8_t reg_addr);
|
||||
@@ -32,6 +37,8 @@ class PCA6416AComponent : public Component, public i2c::I2CDevice {
|
||||
/// The mask to write as output state - 1 means HIGH, 0 means LOW
|
||||
uint8_t output_0_{0x00};
|
||||
uint8_t output_1_{0x00};
|
||||
/// Cache for input values (16-bit combined for both banks)
|
||||
uint16_t input_mask_{0x00};
|
||||
/// Storage for last I2C error seen
|
||||
esphome::i2c::ErrorCode last_error_;
|
||||
/// Only the PCAL6416A has pull-up resistors
|
||||
|
||||
@@ -11,7 +11,8 @@ from esphome.const import (
|
||||
CONF_OUTPUT,
|
||||
)
|
||||
|
||||
CODEOWNERS = ["@hwstar", "@clydebarrow"]
|
||||
CODEOWNERS = ["@hwstar", "@clydebarrow", "@bdraco"]
|
||||
AUTO_LOAD = ["gpio_expander"]
|
||||
DEPENDENCIES = ["i2c"]
|
||||
MULTI_CONF = True
|
||||
CONF_PIN_COUNT = "pin_count"
|
||||
|
||||
@@ -37,10 +37,9 @@ void PCA9554Component::setup() {
|
||||
}
|
||||
|
||||
void PCA9554Component::loop() {
|
||||
// The read_inputs_() method will cache the input values from the chip.
|
||||
this->read_inputs_();
|
||||
// Clear all the previously read flags.
|
||||
this->was_previously_read_ = 0x00;
|
||||
// Invalidate the cache at the start of each loop.
|
||||
// The actual read will happen on demand when digital_read() is called
|
||||
this->reset_pin_cache_();
|
||||
}
|
||||
|
||||
void PCA9554Component::dump_config() {
|
||||
@@ -54,21 +53,17 @@ void PCA9554Component::dump_config() {
|
||||
}
|
||||
}
|
||||
|
||||
bool PCA9554Component::digital_read(uint8_t pin) {
|
||||
// Note: We want to try and avoid doing any I2C bus read transactions here
|
||||
// to conserve I2C bus bandwidth. So what we do is check to see if we
|
||||
// have seen a read during the time esphome is running this loop. If we have,
|
||||
// we do an I2C bus transaction to get the latest value. If we haven't
|
||||
// we return a cached value which was read at the time loop() was called.
|
||||
if (this->was_previously_read_ & (1 << pin))
|
||||
this->read_inputs_(); // Force a read of a new value
|
||||
// Indicate we saw a read request for this pin in case a
|
||||
// read happens later in the same loop.
|
||||
this->was_previously_read_ |= (1 << pin);
|
||||
bool PCA9554Component::digital_read_hw(uint8_t pin) {
|
||||
// Read all pins from hardware into input_mask_
|
||||
return this->read_inputs_(); // Return true if I2C read succeeded, false on error
|
||||
}
|
||||
|
||||
bool PCA9554Component::digital_read_cache(uint8_t pin) {
|
||||
// Return the cached pin state from input_mask_
|
||||
return this->input_mask_ & (1 << pin);
|
||||
}
|
||||
|
||||
void PCA9554Component::digital_write(uint8_t pin, bool value) {
|
||||
void PCA9554Component::digital_write_hw(uint8_t pin, bool value) {
|
||||
if (value) {
|
||||
this->output_mask_ |= (1 << pin);
|
||||
} else {
|
||||
@@ -127,8 +122,7 @@ bool PCA9554Component::write_register_(uint8_t reg, uint16_t value) {
|
||||
|
||||
float PCA9554Component::get_setup_priority() const { return setup_priority::IO; }
|
||||
|
||||
// Run our loop() method very early in the loop, so that we cache read values before
|
||||
// before other components call our digital_read() method.
|
||||
// Run our loop() method early to invalidate cache before any other components access the pins
|
||||
float PCA9554Component::get_loop_priority() const { return 9.0f; } // Just after WIFI
|
||||
|
||||
void PCA9554GPIOPin::setup() { pin_mode(flags_); }
|
||||
|
||||
@@ -3,22 +3,21 @@
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/components/i2c/i2c.h"
|
||||
#include "esphome/components/gpio_expander/cached_gpio.h"
|
||||
|
||||
namespace esphome {
|
||||
namespace pca9554 {
|
||||
|
||||
class PCA9554Component : public Component, public i2c::I2CDevice {
|
||||
class PCA9554Component : public Component,
|
||||
public i2c::I2CDevice,
|
||||
public gpio_expander::CachedGpioExpander<uint16_t, 16> {
|
||||
public:
|
||||
PCA9554Component() = default;
|
||||
|
||||
/// Check i2c availability and setup masks
|
||||
void setup() override;
|
||||
/// Poll for input changes periodically
|
||||
/// Invalidate cache at start of each loop
|
||||
void loop() override;
|
||||
/// Helper function to read the value of a pin.
|
||||
bool digital_read(uint8_t pin);
|
||||
/// Helper function to write the value of a pin.
|
||||
void digital_write(uint8_t pin, bool value);
|
||||
/// Helper function to set the pin mode of a pin.
|
||||
void pin_mode(uint8_t pin, gpio::Flags flags);
|
||||
|
||||
@@ -32,9 +31,13 @@ class PCA9554Component : public Component, public i2c::I2CDevice {
|
||||
|
||||
protected:
|
||||
bool read_inputs_();
|
||||
|
||||
bool write_register_(uint8_t reg, uint16_t value);
|
||||
|
||||
// Virtual methods from CachedGpioExpander
|
||||
bool digital_read_hw(uint8_t pin) override;
|
||||
bool digital_read_cache(uint8_t pin) override;
|
||||
void digital_write_hw(uint8_t pin, bool value) override;
|
||||
|
||||
/// number of bits the expander has
|
||||
size_t pin_count_{8};
|
||||
/// width of registers
|
||||
@@ -45,8 +48,6 @@ class PCA9554Component : public Component, public i2c::I2CDevice {
|
||||
uint16_t output_mask_{0x00};
|
||||
/// The state of the actual input pin states - 1 means HIGH, 0 means LOW
|
||||
uint16_t input_mask_{0x00};
|
||||
/// Flags to check if read previously during this loop
|
||||
uint16_t was_previously_read_ = {0x00};
|
||||
/// Storage for last I2C error seen
|
||||
esphome::i2c::ErrorCode last_error_;
|
||||
};
|
||||
|
||||
@@ -11,6 +11,7 @@ from esphome.const import (
|
||||
CONF_OUTPUT,
|
||||
)
|
||||
|
||||
AUTO_LOAD = ["gpio_expander"]
|
||||
DEPENDENCIES = ["i2c"]
|
||||
MULTI_CONF = True
|
||||
|
||||
|
||||
@@ -16,6 +16,10 @@ void PCF8574Component::setup() {
|
||||
this->write_gpio_();
|
||||
this->read_gpio_();
|
||||
}
|
||||
void PCF8574Component::loop() {
|
||||
// Invalidate the cache at the start of each loop
|
||||
this->reset_pin_cache_();
|
||||
}
|
||||
void PCF8574Component::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "PCF8574:");
|
||||
LOG_I2C_DEVICE(this)
|
||||
@@ -24,17 +28,19 @@ void PCF8574Component::dump_config() {
|
||||
ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
|
||||
}
|
||||
}
|
||||
bool PCF8574Component::digital_read(uint8_t pin) {
|
||||
this->read_gpio_();
|
||||
return this->input_mask_ & (1 << pin);
|
||||
bool PCF8574Component::digital_read_hw(uint8_t pin) {
|
||||
// Read all pins from hardware into input_mask_
|
||||
return this->read_gpio_(); // Return true if I2C read succeeded, false on error
|
||||
}
|
||||
void PCF8574Component::digital_write(uint8_t pin, bool value) {
|
||||
|
||||
bool PCF8574Component::digital_read_cache(uint8_t pin) { return this->input_mask_ & (1 << pin); }
|
||||
|
||||
void PCF8574Component::digital_write_hw(uint8_t pin, bool value) {
|
||||
if (value) {
|
||||
this->output_mask_ |= (1 << pin);
|
||||
} else {
|
||||
this->output_mask_ &= ~(1 << pin);
|
||||
}
|
||||
|
||||
this->write_gpio_();
|
||||
}
|
||||
void PCF8574Component::pin_mode(uint8_t pin, gpio::Flags flags) {
|
||||
@@ -91,6 +97,9 @@ bool PCF8574Component::write_gpio_() {
|
||||
}
|
||||
float PCF8574Component::get_setup_priority() const { return setup_priority::IO; }
|
||||
|
||||
// Run our loop() method early to invalidate cache before any other components access the pins
|
||||
float PCF8574Component::get_loop_priority() const { return 9.0f; } // Just after WIFI
|
||||
|
||||
void PCF8574GPIOPin::setup() { pin_mode(flags_); }
|
||||
void PCF8574GPIOPin::pin_mode(gpio::Flags flags) { this->parent_->pin_mode(this->pin_, flags); }
|
||||
bool PCF8574GPIOPin::digital_read() { return this->parent_->digital_read(this->pin_) != this->inverted_; }
|
||||
|
||||
@@ -3,11 +3,16 @@
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/components/i2c/i2c.h"
|
||||
#include "esphome/components/gpio_expander/cached_gpio.h"
|
||||
|
||||
namespace esphome {
|
||||
namespace pcf8574 {
|
||||
|
||||
class PCF8574Component : public Component, public i2c::I2CDevice {
|
||||
// PCF8574(8 pins)/PCF8575(16 pins) always read/write all pins in a single I2C transaction
|
||||
// so we use uint16_t as bank type to ensure all pins are in one bank and cached together
|
||||
class PCF8574Component : public Component,
|
||||
public i2c::I2CDevice,
|
||||
public gpio_expander::CachedGpioExpander<uint16_t, 16> {
|
||||
public:
|
||||
PCF8574Component() = default;
|
||||
|
||||
@@ -15,20 +20,22 @@ class PCF8574Component : public Component, public i2c::I2CDevice {
|
||||
|
||||
/// Check i2c availability and setup masks
|
||||
void setup() override;
|
||||
/// Helper function to read the value of a pin.
|
||||
bool digital_read(uint8_t pin);
|
||||
/// Helper function to write the value of a pin.
|
||||
void digital_write(uint8_t pin, bool value);
|
||||
/// Invalidate cache at start of each loop
|
||||
void loop() override;
|
||||
/// Helper function to set the pin mode of a pin.
|
||||
void pin_mode(uint8_t pin, gpio::Flags flags);
|
||||
|
||||
float get_setup_priority() const override;
|
||||
float get_loop_priority() const override;
|
||||
|
||||
void dump_config() override;
|
||||
|
||||
protected:
|
||||
bool read_gpio_();
|
||||
bool digital_read_hw(uint8_t pin) override;
|
||||
bool digital_read_cache(uint8_t pin) override;
|
||||
void digital_write_hw(uint8_t pin, bool value) override;
|
||||
|
||||
bool read_gpio_();
|
||||
bool write_gpio_();
|
||||
|
||||
/// Mask for the pin mode - 1 means output, 0 means input
|
||||
|
||||
@@ -18,7 +18,7 @@ void IRAM_ATTR PulseWidthSensorStore::gpio_intr(PulseWidthSensorStore *arg) {
|
||||
|
||||
void PulseWidthSensor::dump_config() {
|
||||
LOG_SENSOR("", "Pulse Width", this);
|
||||
LOG_UPDATE_INTERVAL(this)
|
||||
LOG_UPDATE_INTERVAL(this);
|
||||
LOG_PIN(" Pin: ", this->pin_);
|
||||
}
|
||||
void PulseWidthSensor::update() {
|
||||
|
||||
@@ -17,16 +17,8 @@ void RuntimeStatsCollector::record_component_time(Component *component, uint32_t
|
||||
if (component == nullptr)
|
||||
return;
|
||||
|
||||
// Check if we have cached the name for this component
|
||||
auto name_it = this->component_names_cache_.find(component);
|
||||
if (name_it == this->component_names_cache_.end()) {
|
||||
// First time seeing this component, cache its name
|
||||
const char *source = component->get_component_source();
|
||||
this->component_names_cache_[component] = source;
|
||||
this->component_stats_[source].record_time(duration_ms);
|
||||
} else {
|
||||
this->component_stats_[name_it->second].record_time(duration_ms);
|
||||
}
|
||||
// Record stats using component pointer as key
|
||||
this->component_stats_[component].record_time(duration_ms);
|
||||
|
||||
if (this->next_log_time_ == 0) {
|
||||
this->next_log_time_ = current_time + this->log_interval_;
|
||||
@@ -42,9 +34,10 @@ void RuntimeStatsCollector::log_stats_() {
|
||||
std::vector<ComponentStatPair> stats_to_display;
|
||||
|
||||
for (const auto &it : this->component_stats_) {
|
||||
Component *component = it.first;
|
||||
const ComponentRuntimeStats &stats = it.second;
|
||||
if (stats.get_period_count() > 0) {
|
||||
ComponentStatPair pair = {it.first, &stats};
|
||||
ComponentStatPair pair = {component, &stats};
|
||||
stats_to_display.push_back(pair);
|
||||
}
|
||||
}
|
||||
@@ -54,12 +47,9 @@ void RuntimeStatsCollector::log_stats_() {
|
||||
|
||||
// Log top components by period runtime
|
||||
for (const auto &it : stats_to_display) {
|
||||
const char *source = it.name;
|
||||
const ComponentRuntimeStats *stats = it.stats;
|
||||
|
||||
ESP_LOGI(TAG, " %s: count=%" PRIu32 ", avg=%.2fms, max=%" PRIu32 "ms, total=%" PRIu32 "ms", source,
|
||||
stats->get_period_count(), stats->get_period_avg_time_ms(), stats->get_period_max_time_ms(),
|
||||
stats->get_period_time_ms());
|
||||
ESP_LOGI(TAG, " %s: count=%" PRIu32 ", avg=%.2fms, max=%" PRIu32 "ms, total=%" PRIu32 "ms",
|
||||
LOG_STR_ARG(it.component->get_component_log_str()), it.stats->get_period_count(),
|
||||
it.stats->get_period_avg_time_ms(), it.stats->get_period_max_time_ms(), it.stats->get_period_time_ms());
|
||||
}
|
||||
|
||||
// Log total stats since boot
|
||||
@@ -72,12 +62,9 @@ void RuntimeStatsCollector::log_stats_() {
|
||||
});
|
||||
|
||||
for (const auto &it : stats_to_display) {
|
||||
const char *source = it.name;
|
||||
const ComponentRuntimeStats *stats = it.stats;
|
||||
|
||||
ESP_LOGI(TAG, " %s: count=%" PRIu32 ", avg=%.2fms, max=%" PRIu32 "ms, total=%" PRIu32 "ms", source,
|
||||
stats->get_total_count(), stats->get_total_avg_time_ms(), stats->get_total_max_time_ms(),
|
||||
stats->get_total_time_ms());
|
||||
ESP_LOGI(TAG, " %s: count=%" PRIu32 ", avg=%.2fms, max=%" PRIu32 "ms, total=%" PRIu32 "ms",
|
||||
LOG_STR_ARG(it.component->get_component_log_str()), it.stats->get_total_count(),
|
||||
it.stats->get_total_avg_time_ms(), it.stats->get_total_max_time_ms(), it.stats->get_total_time_ms());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -79,7 +79,7 @@ class ComponentRuntimeStats {
|
||||
|
||||
// For sorting components by run time
|
||||
struct ComponentStatPair {
|
||||
const char *name;
|
||||
Component *component;
|
||||
const ComponentRuntimeStats *stats;
|
||||
|
||||
bool operator>(const ComponentStatPair &other) const {
|
||||
@@ -109,15 +109,9 @@ class RuntimeStatsCollector {
|
||||
}
|
||||
}
|
||||
|
||||
// Use const char* keys for efficiency
|
||||
// Custom comparator for const char* keys in map
|
||||
// Without this, std::map would compare pointer addresses instead of string contents,
|
||||
// causing identical component names at different addresses to be treated as different keys
|
||||
struct CStrCompare {
|
||||
bool operator()(const char *a, const char *b) const { return std::strcmp(a, b) < 0; }
|
||||
};
|
||||
std::map<const char *, ComponentRuntimeStats, CStrCompare> component_stats_;
|
||||
std::map<Component *, const char *> component_names_cache_;
|
||||
// Map from component to its stats
|
||||
// We use Component* as the key since each component is unique
|
||||
std::map<Component *, ComponentRuntimeStats> component_stats_;
|
||||
uint32_t log_interval_;
|
||||
uint32_t next_log_time_;
|
||||
};
|
||||
|
||||
@@ -25,7 +25,7 @@ CONF_SCAN_TIME = "scan_time"
|
||||
CONF_DEBOUNCE_TIME = "debounce_time"
|
||||
CONF_SX1509_ID = "sx1509_id"
|
||||
|
||||
AUTO_LOAD = ["key_provider"]
|
||||
AUTO_LOAD = ["key_provider", "gpio_expander"]
|
||||
DEPENDENCIES = ["i2c"]
|
||||
MULTI_CONF = True
|
||||
|
||||
|
||||
@@ -39,6 +39,9 @@ void SX1509Component::dump_config() {
|
||||
}
|
||||
|
||||
void SX1509Component::loop() {
|
||||
// Reset cache at the start of each loop
|
||||
this->reset_pin_cache_();
|
||||
|
||||
if (this->has_keypad_) {
|
||||
if (millis() - this->last_loop_timestamp_ < min_loop_period_)
|
||||
return;
|
||||
@@ -73,18 +76,20 @@ void SX1509Component::loop() {
|
||||
}
|
||||
}
|
||||
|
||||
bool SX1509Component::digital_read(uint8_t pin) {
|
||||
bool SX1509Component::digital_read_hw(uint8_t pin) {
|
||||
// Always read all pins when any input pin is accessed
|
||||
return this->read_byte_16(REG_DATA_B, &this->input_mask_);
|
||||
}
|
||||
|
||||
bool SX1509Component::digital_read_cache(uint8_t pin) {
|
||||
// Return cached value for input pins, false for output pins
|
||||
if (this->ddr_mask_ & (1 << pin)) {
|
||||
uint16_t temp_reg_data;
|
||||
if (!this->read_byte_16(REG_DATA_B, &temp_reg_data))
|
||||
return false;
|
||||
if (temp_reg_data & (1 << pin))
|
||||
return true;
|
||||
return (this->input_mask_ & (1 << pin)) != 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void SX1509Component::digital_write(uint8_t pin, bool bit_value) {
|
||||
void SX1509Component::digital_write_hw(uint8_t pin, bool bit_value) {
|
||||
if ((~this->ddr_mask_) & (1 << pin)) {
|
||||
// If the pin is an output, write high/low
|
||||
uint16_t temp_reg_data = 0;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include "esphome/components/i2c/i2c.h"
|
||||
#include "esphome/components/key_provider/key_provider.h"
|
||||
#include "esphome/components/gpio_expander/cached_gpio.h"
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "sx1509_gpio_pin.h"
|
||||
@@ -30,7 +31,10 @@ class SX1509Processor {
|
||||
|
||||
class SX1509KeyTrigger : public Trigger<uint8_t> {};
|
||||
|
||||
class SX1509Component : public Component, public i2c::I2CDevice, public key_provider::KeyProvider {
|
||||
class SX1509Component : public Component,
|
||||
public i2c::I2CDevice,
|
||||
public gpio_expander::CachedGpioExpander<uint16_t, 16>,
|
||||
public key_provider::KeyProvider {
|
||||
public:
|
||||
SX1509Component() = default;
|
||||
|
||||
@@ -39,11 +43,9 @@ class SX1509Component : public Component, public i2c::I2CDevice, public key_prov
|
||||
float get_setup_priority() const override { return setup_priority::HARDWARE; }
|
||||
void loop() override;
|
||||
|
||||
bool digital_read(uint8_t pin);
|
||||
uint16_t read_key_data();
|
||||
void set_pin_value(uint8_t pin, uint8_t i_on) { this->write_byte(REG_I_ON[pin], i_on); };
|
||||
void pin_mode(uint8_t pin, gpio::Flags flags);
|
||||
void digital_write(uint8_t pin, bool bit_value);
|
||||
uint32_t get_clock() { return this->clk_x_; };
|
||||
void set_rows_cols(uint8_t rows, uint8_t cols) {
|
||||
this->rows_ = rows;
|
||||
@@ -61,10 +63,15 @@ class SX1509Component : public Component, public i2c::I2CDevice, public key_prov
|
||||
void setup_led_driver(uint8_t pin);
|
||||
|
||||
protected:
|
||||
// Virtual methods from CachedGpioExpander
|
||||
bool digital_read_hw(uint8_t pin) override;
|
||||
bool digital_read_cache(uint8_t pin) override;
|
||||
void digital_write_hw(uint8_t pin, bool value) override;
|
||||
|
||||
uint32_t clk_x_ = 2000000;
|
||||
uint8_t frequency_ = 0;
|
||||
uint16_t ddr_mask_ = 0x00;
|
||||
uint16_t input_mask_ = 0x00;
|
||||
uint16_t input_mask_ = 0x00; // Cache for input values (16-bit for all pins)
|
||||
uint16_t port_mask_ = 0x00;
|
||||
uint16_t output_state_ = 0x00;
|
||||
bool has_keypad_ = false;
|
||||
|
||||
@@ -32,6 +32,7 @@ from esphome.const import (
|
||||
CONF_FAN_WITH_COOLING,
|
||||
CONF_FAN_WITH_HEATING,
|
||||
CONF_HEAT_ACTION,
|
||||
CONF_HEAT_COOL_MODE,
|
||||
CONF_HEAT_DEADBAND,
|
||||
CONF_HEAT_MODE,
|
||||
CONF_HEAT_OVERRUN,
|
||||
@@ -150,7 +151,7 @@ def generate_comparable_preset(config, name):
|
||||
def validate_thermostat(config):
|
||||
# verify corresponding action(s) exist(s) for any defined climate mode or action
|
||||
requirements = {
|
||||
CONF_AUTO_MODE: [
|
||||
CONF_HEAT_COOL_MODE: [
|
||||
CONF_COOL_ACTION,
|
||||
CONF_HEAT_ACTION,
|
||||
CONF_MIN_COOLING_OFF_TIME,
|
||||
@@ -540,6 +541,9 @@ CONFIG_SCHEMA = cv.All(
|
||||
cv.Optional(CONF_FAN_ONLY_MODE): automation.validate_automation(
|
||||
single=True
|
||||
),
|
||||
cv.Optional(CONF_HEAT_COOL_MODE): automation.validate_automation(
|
||||
single=True
|
||||
),
|
||||
cv.Optional(CONF_HEAT_MODE): automation.validate_automation(single=True),
|
||||
cv.Optional(CONF_OFF_MODE): automation.validate_automation(single=True),
|
||||
cv.Optional(CONF_FAN_MODE_ON_ACTION): automation.validate_automation(
|
||||
@@ -644,7 +648,6 @@ async def to_code(config):
|
||||
var = await climate.new_climate(config)
|
||||
await cg.register_component(var, config)
|
||||
|
||||
heat_cool_mode_available = CONF_HEAT_ACTION in config and CONF_COOL_ACTION in config
|
||||
two_points_available = CONF_HEAT_ACTION in config and (
|
||||
CONF_COOL_ACTION in config
|
||||
or (config[CONF_FAN_ONLY_COOLING] and CONF_FAN_ONLY_ACTION in config)
|
||||
@@ -739,11 +742,6 @@ async def to_code(config):
|
||||
var.get_idle_action_trigger(), [], config[CONF_IDLE_ACTION]
|
||||
)
|
||||
|
||||
if heat_cool_mode_available is True:
|
||||
cg.add(var.set_supports_heat_cool(True))
|
||||
else:
|
||||
cg.add(var.set_supports_heat_cool(False))
|
||||
|
||||
if CONF_COOL_ACTION in config:
|
||||
await automation.build_automation(
|
||||
var.get_cool_action_trigger(), [], config[CONF_COOL_ACTION]
|
||||
@@ -780,6 +778,7 @@ async def to_code(config):
|
||||
await automation.build_automation(
|
||||
var.get_auto_mode_trigger(), [], config[CONF_AUTO_MODE]
|
||||
)
|
||||
cg.add(var.set_supports_auto(True))
|
||||
if CONF_COOL_MODE in config:
|
||||
await automation.build_automation(
|
||||
var.get_cool_mode_trigger(), [], config[CONF_COOL_MODE]
|
||||
@@ -800,6 +799,11 @@ async def to_code(config):
|
||||
var.get_heat_mode_trigger(), [], config[CONF_HEAT_MODE]
|
||||
)
|
||||
cg.add(var.set_supports_heat(True))
|
||||
if CONF_HEAT_COOL_MODE in config:
|
||||
await automation.build_automation(
|
||||
var.get_heat_cool_mode_trigger(), [], config[CONF_HEAT_COOL_MODE]
|
||||
)
|
||||
cg.add(var.set_supports_heat_cool(True))
|
||||
if CONF_OFF_MODE in config:
|
||||
await automation.build_automation(
|
||||
var.get_off_mode_trigger(), [], config[CONF_OFF_MODE]
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#include "thermostat_climate.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -9,11 +11,11 @@ static const char *const TAG = "thermostat.climate";
|
||||
void ThermostatClimate::setup() {
|
||||
if (this->use_startup_delay_) {
|
||||
// start timers so that no actions are called for a moment
|
||||
this->start_timer_(thermostat::TIMER_COOLING_OFF);
|
||||
this->start_timer_(thermostat::TIMER_FANNING_OFF);
|
||||
this->start_timer_(thermostat::TIMER_HEATING_OFF);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_COOLING_OFF);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_FANNING_OFF);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_HEATING_OFF);
|
||||
if (this->supports_fan_only_action_uses_fan_mode_timer_)
|
||||
this->start_timer_(thermostat::TIMER_FAN_MODE);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_FAN_MODE);
|
||||
}
|
||||
// add a callback so that whenever the sensor state changes we can take action
|
||||
this->sensor_->add_on_state_callback([this](float state) {
|
||||
@@ -64,7 +66,7 @@ void ThermostatClimate::setup() {
|
||||
|
||||
void ThermostatClimate::loop() {
|
||||
for (auto &timer : this->timer_) {
|
||||
if (timer.active && (timer.started + timer.time < millis())) {
|
||||
if (timer.active && (timer.started + timer.time < App.get_loop_component_start_time())) {
|
||||
timer.active = false;
|
||||
timer.func();
|
||||
}
|
||||
@@ -127,26 +129,35 @@ bool ThermostatClimate::hysteresis_valid() {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ThermostatClimate::limit_setpoints_for_heat_cool() {
|
||||
return this->mode == climate::CLIMATE_MODE_HEAT_COOL ||
|
||||
(this->mode == climate::CLIMATE_MODE_AUTO && this->supports_heat_cool_);
|
||||
}
|
||||
|
||||
void ThermostatClimate::validate_target_temperature() {
|
||||
if (std::isnan(this->target_temperature)) {
|
||||
// default to the midpoint between visual min and max
|
||||
this->target_temperature =
|
||||
((this->get_traits().get_visual_max_temperature() - this->get_traits().get_visual_min_temperature()) / 2) +
|
||||
this->get_traits().get_visual_min_temperature();
|
||||
} else {
|
||||
// target_temperature must be between the visual minimum and the visual maximum
|
||||
if (this->target_temperature < this->get_traits().get_visual_min_temperature())
|
||||
this->target_temperature = this->get_traits().get_visual_min_temperature();
|
||||
if (this->target_temperature > this->get_traits().get_visual_max_temperature())
|
||||
this->target_temperature = this->get_traits().get_visual_max_temperature();
|
||||
this->target_temperature = clamp(this->target_temperature, this->get_traits().get_visual_min_temperature(),
|
||||
this->get_traits().get_visual_max_temperature());
|
||||
}
|
||||
}
|
||||
|
||||
void ThermostatClimate::validate_target_temperatures() {
|
||||
if (this->supports_two_points_) {
|
||||
void ThermostatClimate::validate_target_temperatures(const bool pin_target_temperature_high) {
|
||||
if (!this->supports_two_points_) {
|
||||
this->validate_target_temperature();
|
||||
} else if (pin_target_temperature_high) {
|
||||
// if target_temperature_high is set less than target_temperature_low, move down target_temperature_low
|
||||
this->validate_target_temperature_low();
|
||||
this->validate_target_temperature_high();
|
||||
} else {
|
||||
this->validate_target_temperature();
|
||||
// if target_temperature_low is set greater than target_temperature_high, move up target_temperature_high
|
||||
this->validate_target_temperature_high();
|
||||
this->validate_target_temperature_low();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,18 +165,13 @@ void ThermostatClimate::validate_target_temperature_low() {
|
||||
if (std::isnan(this->target_temperature_low)) {
|
||||
this->target_temperature_low = this->get_traits().get_visual_min_temperature();
|
||||
} else {
|
||||
// target_temperature_low must not be lower than the visual minimum
|
||||
if (this->target_temperature_low < this->get_traits().get_visual_min_temperature())
|
||||
this->target_temperature_low = this->get_traits().get_visual_min_temperature();
|
||||
// target_temperature_low must not be greater than the visual maximum minus set_point_minimum_differential_
|
||||
if (this->target_temperature_low >
|
||||
this->get_traits().get_visual_max_temperature() - this->set_point_minimum_differential_) {
|
||||
this->target_temperature_low =
|
||||
this->get_traits().get_visual_max_temperature() - this->set_point_minimum_differential_;
|
||||
}
|
||||
// if target_temperature_low is set greater than target_temperature_high, move up target_temperature_high
|
||||
if (this->target_temperature_low > this->target_temperature_high - this->set_point_minimum_differential_)
|
||||
this->target_temperature_high = this->target_temperature_low + this->set_point_minimum_differential_;
|
||||
float target_temperature_low_upper_limit =
|
||||
this->limit_setpoints_for_heat_cool()
|
||||
? clamp(this->target_temperature_high - this->set_point_minimum_differential_,
|
||||
this->get_traits().get_visual_min_temperature(), this->get_traits().get_visual_max_temperature())
|
||||
: this->get_traits().get_visual_max_temperature();
|
||||
this->target_temperature_low = clamp(this->target_temperature_low, this->get_traits().get_visual_min_temperature(),
|
||||
target_temperature_low_upper_limit);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,62 +179,64 @@ void ThermostatClimate::validate_target_temperature_high() {
|
||||
if (std::isnan(this->target_temperature_high)) {
|
||||
this->target_temperature_high = this->get_traits().get_visual_max_temperature();
|
||||
} else {
|
||||
// target_temperature_high must not be lower than the visual maximum
|
||||
if (this->target_temperature_high > this->get_traits().get_visual_max_temperature())
|
||||
this->target_temperature_high = this->get_traits().get_visual_max_temperature();
|
||||
// target_temperature_high must not be lower than the visual minimum plus set_point_minimum_differential_
|
||||
if (this->target_temperature_high <
|
||||
this->get_traits().get_visual_min_temperature() + this->set_point_minimum_differential_) {
|
||||
this->target_temperature_high =
|
||||
this->get_traits().get_visual_min_temperature() + this->set_point_minimum_differential_;
|
||||
}
|
||||
// if target_temperature_high is set less than target_temperature_low, move down target_temperature_low
|
||||
if (this->target_temperature_high < this->target_temperature_low + this->set_point_minimum_differential_)
|
||||
this->target_temperature_low = this->target_temperature_high - this->set_point_minimum_differential_;
|
||||
float target_temperature_high_lower_limit =
|
||||
this->limit_setpoints_for_heat_cool()
|
||||
? clamp(this->target_temperature_low + this->set_point_minimum_differential_,
|
||||
this->get_traits().get_visual_min_temperature(), this->get_traits().get_visual_max_temperature())
|
||||
: this->get_traits().get_visual_min_temperature();
|
||||
this->target_temperature_high = clamp(this->target_temperature_high, target_temperature_high_lower_limit,
|
||||
this->get_traits().get_visual_max_temperature());
|
||||
}
|
||||
}
|
||||
|
||||
void ThermostatClimate::control(const climate::ClimateCall &call) {
|
||||
bool target_temperature_high_changed = false;
|
||||
|
||||
if (call.get_preset().has_value()) {
|
||||
// setup_complete_ blocks modifying/resetting the temps immediately after boot
|
||||
if (this->setup_complete_) {
|
||||
this->change_preset_(*call.get_preset());
|
||||
this->change_preset_(call.get_preset().value());
|
||||
} else {
|
||||
this->preset = *call.get_preset();
|
||||
this->preset = call.get_preset().value();
|
||||
}
|
||||
}
|
||||
if (call.get_custom_preset().has_value()) {
|
||||
// setup_complete_ blocks modifying/resetting the temps immediately after boot
|
||||
if (this->setup_complete_) {
|
||||
this->change_custom_preset_(*call.get_custom_preset());
|
||||
this->change_custom_preset_(call.get_custom_preset().value());
|
||||
} else {
|
||||
this->custom_preset = *call.get_custom_preset();
|
||||
this->custom_preset = call.get_custom_preset().value();
|
||||
}
|
||||
}
|
||||
|
||||
if (call.get_mode().has_value())
|
||||
this->mode = *call.get_mode();
|
||||
if (call.get_fan_mode().has_value())
|
||||
this->fan_mode = *call.get_fan_mode();
|
||||
if (call.get_swing_mode().has_value())
|
||||
this->swing_mode = *call.get_swing_mode();
|
||||
if (call.get_mode().has_value()) {
|
||||
this->mode = call.get_mode().value();
|
||||
}
|
||||
if (call.get_fan_mode().has_value()) {
|
||||
this->fan_mode = call.get_fan_mode().value();
|
||||
}
|
||||
if (call.get_swing_mode().has_value()) {
|
||||
this->swing_mode = call.get_swing_mode().value();
|
||||
}
|
||||
if (this->supports_two_points_) {
|
||||
if (call.get_target_temperature_low().has_value()) {
|
||||
this->target_temperature_low = *call.get_target_temperature_low();
|
||||
validate_target_temperature_low();
|
||||
this->target_temperature_low = call.get_target_temperature_low().value();
|
||||
}
|
||||
if (call.get_target_temperature_high().has_value()) {
|
||||
this->target_temperature_high = *call.get_target_temperature_high();
|
||||
validate_target_temperature_high();
|
||||
target_temperature_high_changed = this->target_temperature_high != call.get_target_temperature_high().value();
|
||||
this->target_temperature_high = call.get_target_temperature_high().value();
|
||||
}
|
||||
// ensure the two set points are valid and adjust one of them if necessary
|
||||
this->validate_target_temperatures(target_temperature_high_changed ||
|
||||
(this->prev_mode_ == climate::CLIMATE_MODE_COOL));
|
||||
} else {
|
||||
if (call.get_target_temperature().has_value()) {
|
||||
this->target_temperature = *call.get_target_temperature();
|
||||
validate_target_temperature();
|
||||
this->target_temperature = call.get_target_temperature().value();
|
||||
this->validate_target_temperature();
|
||||
}
|
||||
}
|
||||
// make any changes happen
|
||||
refresh();
|
||||
this->refresh();
|
||||
}
|
||||
|
||||
climate::ClimateTraits ThermostatClimate::traits() {
|
||||
@@ -237,47 +245,47 @@ climate::ClimateTraits ThermostatClimate::traits() {
|
||||
if (this->humidity_sensor_ != nullptr)
|
||||
traits.set_supports_current_humidity(true);
|
||||
|
||||
if (supports_auto_)
|
||||
if (this->supports_auto_)
|
||||
traits.add_supported_mode(climate::CLIMATE_MODE_AUTO);
|
||||
if (supports_heat_cool_)
|
||||
if (this->supports_heat_cool_)
|
||||
traits.add_supported_mode(climate::CLIMATE_MODE_HEAT_COOL);
|
||||
if (supports_cool_)
|
||||
if (this->supports_cool_)
|
||||
traits.add_supported_mode(climate::CLIMATE_MODE_COOL);
|
||||
if (supports_dry_)
|
||||
if (this->supports_dry_)
|
||||
traits.add_supported_mode(climate::CLIMATE_MODE_DRY);
|
||||
if (supports_fan_only_)
|
||||
if (this->supports_fan_only_)
|
||||
traits.add_supported_mode(climate::CLIMATE_MODE_FAN_ONLY);
|
||||
if (supports_heat_)
|
||||
if (this->supports_heat_)
|
||||
traits.add_supported_mode(climate::CLIMATE_MODE_HEAT);
|
||||
|
||||
if (supports_fan_mode_on_)
|
||||
if (this->supports_fan_mode_on_)
|
||||
traits.add_supported_fan_mode(climate::CLIMATE_FAN_ON);
|
||||
if (supports_fan_mode_off_)
|
||||
if (this->supports_fan_mode_off_)
|
||||
traits.add_supported_fan_mode(climate::CLIMATE_FAN_OFF);
|
||||
if (supports_fan_mode_auto_)
|
||||
if (this->supports_fan_mode_auto_)
|
||||
traits.add_supported_fan_mode(climate::CLIMATE_FAN_AUTO);
|
||||
if (supports_fan_mode_low_)
|
||||
if (this->supports_fan_mode_low_)
|
||||
traits.add_supported_fan_mode(climate::CLIMATE_FAN_LOW);
|
||||
if (supports_fan_mode_medium_)
|
||||
if (this->supports_fan_mode_medium_)
|
||||
traits.add_supported_fan_mode(climate::CLIMATE_FAN_MEDIUM);
|
||||
if (supports_fan_mode_high_)
|
||||
if (this->supports_fan_mode_high_)
|
||||
traits.add_supported_fan_mode(climate::CLIMATE_FAN_HIGH);
|
||||
if (supports_fan_mode_middle_)
|
||||
if (this->supports_fan_mode_middle_)
|
||||
traits.add_supported_fan_mode(climate::CLIMATE_FAN_MIDDLE);
|
||||
if (supports_fan_mode_focus_)
|
||||
if (this->supports_fan_mode_focus_)
|
||||
traits.add_supported_fan_mode(climate::CLIMATE_FAN_FOCUS);
|
||||
if (supports_fan_mode_diffuse_)
|
||||
if (this->supports_fan_mode_diffuse_)
|
||||
traits.add_supported_fan_mode(climate::CLIMATE_FAN_DIFFUSE);
|
||||
if (supports_fan_mode_quiet_)
|
||||
if (this->supports_fan_mode_quiet_)
|
||||
traits.add_supported_fan_mode(climate::CLIMATE_FAN_QUIET);
|
||||
|
||||
if (supports_swing_mode_both_)
|
||||
if (this->supports_swing_mode_both_)
|
||||
traits.add_supported_swing_mode(climate::CLIMATE_SWING_BOTH);
|
||||
if (supports_swing_mode_horizontal_)
|
||||
if (this->supports_swing_mode_horizontal_)
|
||||
traits.add_supported_swing_mode(climate::CLIMATE_SWING_HORIZONTAL);
|
||||
if (supports_swing_mode_off_)
|
||||
if (this->supports_swing_mode_off_)
|
||||
traits.add_supported_swing_mode(climate::CLIMATE_SWING_OFF);
|
||||
if (supports_swing_mode_vertical_)
|
||||
if (this->supports_swing_mode_vertical_)
|
||||
traits.add_supported_swing_mode(climate::CLIMATE_SWING_VERTICAL);
|
||||
|
||||
for (auto &it : this->preset_config_) {
|
||||
@@ -299,14 +307,15 @@ climate::ClimateAction ThermostatClimate::compute_action_(const bool ignore_time
|
||||
return climate::CLIMATE_ACTION_OFF;
|
||||
}
|
||||
// do not change the action if an "ON" timer is running
|
||||
if ((!ignore_timers) &&
|
||||
(timer_active_(thermostat::TIMER_IDLE_ON) || timer_active_(thermostat::TIMER_COOLING_ON) ||
|
||||
timer_active_(thermostat::TIMER_FANNING_ON) || timer_active_(thermostat::TIMER_HEATING_ON))) {
|
||||
if ((!ignore_timers) && (this->timer_active_(thermostat::THERMOSTAT_TIMER_IDLE_ON) ||
|
||||
this->timer_active_(thermostat::THERMOSTAT_TIMER_COOLING_ON) ||
|
||||
this->timer_active_(thermostat::THERMOSTAT_TIMER_FANNING_ON) ||
|
||||
this->timer_active_(thermostat::THERMOSTAT_TIMER_HEATING_ON))) {
|
||||
return this->action;
|
||||
}
|
||||
|
||||
// ensure set point(s) is/are valid before computing the action
|
||||
this->validate_target_temperatures();
|
||||
this->validate_target_temperatures(this->prev_mode_ == climate::CLIMATE_MODE_COOL);
|
||||
// everything has been validated so we can now safely compute the action
|
||||
switch (this->mode) {
|
||||
// if the climate mode is OFF then the climate action must be OFF
|
||||
@@ -340,6 +349,22 @@ climate::ClimateAction ThermostatClimate::compute_action_(const bool ignore_time
|
||||
target_action = climate::CLIMATE_ACTION_HEATING;
|
||||
}
|
||||
break;
|
||||
case climate::CLIMATE_MODE_AUTO:
|
||||
if (this->supports_two_points_) {
|
||||
if (this->cooling_required_() && this->heating_required_()) {
|
||||
// this is bad and should never happen, so just stop.
|
||||
// target_action = climate::CLIMATE_ACTION_IDLE;
|
||||
} else if (this->cooling_required_()) {
|
||||
target_action = climate::CLIMATE_ACTION_COOLING;
|
||||
} else if (this->heating_required_()) {
|
||||
target_action = climate::CLIMATE_ACTION_HEATING;
|
||||
}
|
||||
} else if (this->supports_cool_ && this->cooling_required_()) {
|
||||
target_action = climate::CLIMATE_ACTION_COOLING;
|
||||
} else if (this->supports_heat_ && this->heating_required_()) {
|
||||
target_action = climate::CLIMATE_ACTION_HEATING;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
@@ -362,7 +387,7 @@ climate::ClimateAction ThermostatClimate::compute_supplemental_action_() {
|
||||
}
|
||||
|
||||
// ensure set point(s) is/are valid before computing the action
|
||||
this->validate_target_temperatures();
|
||||
this->validate_target_temperatures(this->prev_mode_ == climate::CLIMATE_MODE_COOL);
|
||||
// everything has been validated so we can now safely compute the action
|
||||
switch (this->mode) {
|
||||
// if the climate mode is OFF then the climate action must be OFF
|
||||
@@ -420,18 +445,18 @@ void ThermostatClimate::switch_to_action_(climate::ClimateAction action, bool pu
|
||||
case climate::CLIMATE_ACTION_OFF:
|
||||
case climate::CLIMATE_ACTION_IDLE:
|
||||
if (this->idle_action_ready_()) {
|
||||
this->start_timer_(thermostat::TIMER_IDLE_ON);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_IDLE_ON);
|
||||
if (this->action == climate::CLIMATE_ACTION_COOLING)
|
||||
this->start_timer_(thermostat::TIMER_COOLING_OFF);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_COOLING_OFF);
|
||||
if (this->action == climate::CLIMATE_ACTION_FAN) {
|
||||
if (this->supports_fan_only_action_uses_fan_mode_timer_) {
|
||||
this->start_timer_(thermostat::TIMER_FAN_MODE);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_FAN_MODE);
|
||||
} else {
|
||||
this->start_timer_(thermostat::TIMER_FANNING_OFF);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_FANNING_OFF);
|
||||
}
|
||||
}
|
||||
if (this->action == climate::CLIMATE_ACTION_HEATING)
|
||||
this->start_timer_(thermostat::TIMER_HEATING_OFF);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_HEATING_OFF);
|
||||
// trig = this->idle_action_trigger_;
|
||||
ESP_LOGVV(TAG, "Switching to IDLE/OFF action");
|
||||
this->cooling_max_runtime_exceeded_ = false;
|
||||
@@ -441,10 +466,10 @@ void ThermostatClimate::switch_to_action_(climate::ClimateAction action, bool pu
|
||||
break;
|
||||
case climate::CLIMATE_ACTION_COOLING:
|
||||
if (this->cooling_action_ready_()) {
|
||||
this->start_timer_(thermostat::TIMER_COOLING_ON);
|
||||
this->start_timer_(thermostat::TIMER_COOLING_MAX_RUN_TIME);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_COOLING_ON);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_COOLING_MAX_RUN_TIME);
|
||||
if (this->supports_fan_with_cooling_) {
|
||||
this->start_timer_(thermostat::TIMER_FANNING_ON);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_FANNING_ON);
|
||||
trig_fan = this->fan_only_action_trigger_;
|
||||
}
|
||||
this->cooling_max_runtime_exceeded_ = false;
|
||||
@@ -455,10 +480,10 @@ void ThermostatClimate::switch_to_action_(climate::ClimateAction action, bool pu
|
||||
break;
|
||||
case climate::CLIMATE_ACTION_HEATING:
|
||||
if (this->heating_action_ready_()) {
|
||||
this->start_timer_(thermostat::TIMER_HEATING_ON);
|
||||
this->start_timer_(thermostat::TIMER_HEATING_MAX_RUN_TIME);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_HEATING_ON);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_HEATING_MAX_RUN_TIME);
|
||||
if (this->supports_fan_with_heating_) {
|
||||
this->start_timer_(thermostat::TIMER_FANNING_ON);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_FANNING_ON);
|
||||
trig_fan = this->fan_only_action_trigger_;
|
||||
}
|
||||
this->heating_max_runtime_exceeded_ = false;
|
||||
@@ -470,9 +495,9 @@ void ThermostatClimate::switch_to_action_(climate::ClimateAction action, bool pu
|
||||
case climate::CLIMATE_ACTION_FAN:
|
||||
if (this->fanning_action_ready_()) {
|
||||
if (this->supports_fan_only_action_uses_fan_mode_timer_) {
|
||||
this->start_timer_(thermostat::TIMER_FAN_MODE);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_FAN_MODE);
|
||||
} else {
|
||||
this->start_timer_(thermostat::TIMER_FANNING_ON);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_FANNING_ON);
|
||||
}
|
||||
trig = this->fan_only_action_trigger_;
|
||||
ESP_LOGVV(TAG, "Switching to FAN_ONLY action");
|
||||
@@ -481,8 +506,8 @@ void ThermostatClimate::switch_to_action_(climate::ClimateAction action, bool pu
|
||||
break;
|
||||
case climate::CLIMATE_ACTION_DRYING:
|
||||
if (this->drying_action_ready_()) {
|
||||
this->start_timer_(thermostat::TIMER_COOLING_ON);
|
||||
this->start_timer_(thermostat::TIMER_FANNING_ON);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_COOLING_ON);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_FANNING_ON);
|
||||
trig = this->dry_action_trigger_;
|
||||
ESP_LOGVV(TAG, "Switching to DRYING action");
|
||||
action_ready = true;
|
||||
@@ -525,14 +550,14 @@ void ThermostatClimate::switch_to_supplemental_action_(climate::ClimateAction ac
|
||||
switch (action) {
|
||||
case climate::CLIMATE_ACTION_OFF:
|
||||
case climate::CLIMATE_ACTION_IDLE:
|
||||
this->cancel_timer_(thermostat::TIMER_COOLING_MAX_RUN_TIME);
|
||||
this->cancel_timer_(thermostat::TIMER_HEATING_MAX_RUN_TIME);
|
||||
this->cancel_timer_(thermostat::THERMOSTAT_TIMER_COOLING_MAX_RUN_TIME);
|
||||
this->cancel_timer_(thermostat::THERMOSTAT_TIMER_HEATING_MAX_RUN_TIME);
|
||||
break;
|
||||
case climate::CLIMATE_ACTION_COOLING:
|
||||
this->cancel_timer_(thermostat::TIMER_COOLING_MAX_RUN_TIME);
|
||||
this->cancel_timer_(thermostat::THERMOSTAT_TIMER_COOLING_MAX_RUN_TIME);
|
||||
break;
|
||||
case climate::CLIMATE_ACTION_HEATING:
|
||||
this->cancel_timer_(thermostat::TIMER_HEATING_MAX_RUN_TIME);
|
||||
this->cancel_timer_(thermostat::THERMOSTAT_TIMER_HEATING_MAX_RUN_TIME);
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
@@ -547,15 +572,15 @@ void ThermostatClimate::trigger_supplemental_action_() {
|
||||
|
||||
switch (this->supplemental_action_) {
|
||||
case climate::CLIMATE_ACTION_COOLING:
|
||||
if (!this->timer_active_(thermostat::TIMER_COOLING_MAX_RUN_TIME)) {
|
||||
this->start_timer_(thermostat::TIMER_COOLING_MAX_RUN_TIME);
|
||||
if (!this->timer_active_(thermostat::THERMOSTAT_TIMER_COOLING_MAX_RUN_TIME)) {
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_COOLING_MAX_RUN_TIME);
|
||||
}
|
||||
trig = this->supplemental_cool_action_trigger_;
|
||||
ESP_LOGVV(TAG, "Calling supplemental COOLING action");
|
||||
break;
|
||||
case climate::CLIMATE_ACTION_HEATING:
|
||||
if (!this->timer_active_(thermostat::TIMER_HEATING_MAX_RUN_TIME)) {
|
||||
this->start_timer_(thermostat::TIMER_HEATING_MAX_RUN_TIME);
|
||||
if (!this->timer_active_(thermostat::THERMOSTAT_TIMER_HEATING_MAX_RUN_TIME)) {
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_HEATING_MAX_RUN_TIME);
|
||||
}
|
||||
trig = this->supplemental_heat_action_trigger_;
|
||||
ESP_LOGVV(TAG, "Calling supplemental HEATING action");
|
||||
@@ -633,7 +658,7 @@ void ThermostatClimate::switch_to_fan_mode_(climate::ClimateFanMode fan_mode, bo
|
||||
this->prev_fan_mode_trigger_->stop_action();
|
||||
this->prev_fan_mode_trigger_ = nullptr;
|
||||
}
|
||||
this->start_timer_(thermostat::TIMER_FAN_MODE);
|
||||
this->start_timer_(thermostat::THERMOSTAT_TIMER_FAN_MODE);
|
||||
if (trig != nullptr) {
|
||||
trig->trigger();
|
||||
}
|
||||
@@ -653,13 +678,13 @@ void ThermostatClimate::switch_to_mode_(climate::ClimateMode mode, bool publish_
|
||||
this->prev_mode_trigger_->stop_action();
|
||||
this->prev_mode_trigger_ = nullptr;
|
||||
}
|
||||
Trigger<> *trig = this->auto_mode_trigger_;
|
||||
Trigger<> *trig = this->off_mode_trigger_;
|
||||
switch (mode) {
|
||||
case climate::CLIMATE_MODE_OFF:
|
||||
trig = this->off_mode_trigger_;
|
||||
case climate::CLIMATE_MODE_AUTO:
|
||||
trig = this->auto_mode_trigger_;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_HEAT_COOL:
|
||||
// trig = this->auto_mode_trigger_;
|
||||
trig = this->heat_cool_mode_trigger_;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_COOL:
|
||||
trig = this->cool_mode_trigger_;
|
||||
@@ -673,11 +698,12 @@ void ThermostatClimate::switch_to_mode_(climate::ClimateMode mode, bool publish_
|
||||
case climate::CLIMATE_MODE_DRY:
|
||||
trig = this->dry_mode_trigger_;
|
||||
break;
|
||||
case climate::CLIMATE_MODE_OFF:
|
||||
default:
|
||||
// we cannot report an invalid mode back to HA (even if it asked for one)
|
||||
// and must assume some valid value
|
||||
mode = climate::CLIMATE_MODE_HEAT_COOL;
|
||||
// trig = this->auto_mode_trigger_;
|
||||
mode = climate::CLIMATE_MODE_OFF;
|
||||
// trig = this->off_mode_trigger_;
|
||||
}
|
||||
if (trig != nullptr) {
|
||||
trig->trigger();
|
||||
@@ -685,8 +711,9 @@ void ThermostatClimate::switch_to_mode_(climate::ClimateMode mode, bool publish_
|
||||
this->mode = mode;
|
||||
this->prev_mode_ = mode;
|
||||
this->prev_mode_trigger_ = trig;
|
||||
if (publish_state)
|
||||
if (publish_state) {
|
||||
this->publish_state();
|
||||
}
|
||||
}
|
||||
|
||||
void ThermostatClimate::switch_to_swing_mode_(climate::ClimateSwingMode swing_mode, bool publish_state) {
|
||||
@@ -732,35 +759,44 @@ void ThermostatClimate::switch_to_swing_mode_(climate::ClimateSwingMode swing_mo
|
||||
|
||||
bool ThermostatClimate::idle_action_ready_() {
|
||||
if (this->supports_fan_only_action_uses_fan_mode_timer_) {
|
||||
return !(this->timer_active_(thermostat::TIMER_COOLING_ON) || this->timer_active_(thermostat::TIMER_FAN_MODE) ||
|
||||
this->timer_active_(thermostat::TIMER_HEATING_ON));
|
||||
return !(this->timer_active_(thermostat::THERMOSTAT_TIMER_COOLING_ON) ||
|
||||
this->timer_active_(thermostat::THERMOSTAT_TIMER_FAN_MODE) ||
|
||||
this->timer_active_(thermostat::THERMOSTAT_TIMER_HEATING_ON));
|
||||
}
|
||||
return !(this->timer_active_(thermostat::TIMER_COOLING_ON) || this->timer_active_(thermostat::TIMER_FANNING_ON) ||
|
||||
this->timer_active_(thermostat::TIMER_HEATING_ON));
|
||||
return !(this->timer_active_(thermostat::THERMOSTAT_TIMER_COOLING_ON) ||
|
||||
this->timer_active_(thermostat::THERMOSTAT_TIMER_FANNING_ON) ||
|
||||
this->timer_active_(thermostat::THERMOSTAT_TIMER_HEATING_ON));
|
||||
}
|
||||
|
||||
bool ThermostatClimate::cooling_action_ready_() {
|
||||
return !(this->timer_active_(thermostat::TIMER_IDLE_ON) || this->timer_active_(thermostat::TIMER_FANNING_OFF) ||
|
||||
this->timer_active_(thermostat::TIMER_COOLING_OFF) || this->timer_active_(thermostat::TIMER_HEATING_ON));
|
||||
return !(this->timer_active_(thermostat::THERMOSTAT_TIMER_IDLE_ON) ||
|
||||
this->timer_active_(thermostat::THERMOSTAT_TIMER_FANNING_OFF) ||
|
||||
this->timer_active_(thermostat::THERMOSTAT_TIMER_COOLING_OFF) ||
|
||||
this->timer_active_(thermostat::THERMOSTAT_TIMER_HEATING_ON));
|
||||
}
|
||||
|
||||
bool ThermostatClimate::drying_action_ready_() {
|
||||
return !(this->timer_active_(thermostat::TIMER_IDLE_ON) || this->timer_active_(thermostat::TIMER_FANNING_OFF) ||
|
||||
this->timer_active_(thermostat::TIMER_COOLING_OFF) || this->timer_active_(thermostat::TIMER_HEATING_ON));
|
||||
return !(this->timer_active_(thermostat::THERMOSTAT_TIMER_IDLE_ON) ||
|
||||
this->timer_active_(thermostat::THERMOSTAT_TIMER_FANNING_OFF) ||
|
||||
this->timer_active_(thermostat::THERMOSTAT_TIMER_COOLING_OFF) ||
|
||||
this->timer_active_(thermostat::THERMOSTAT_TIMER_HEATING_ON));
|
||||
}
|
||||
|
||||
bool ThermostatClimate::fan_mode_ready_() { return !(this->timer_active_(thermostat::TIMER_FAN_MODE)); }
|
||||
bool ThermostatClimate::fan_mode_ready_() { return !(this->timer_active_(thermostat::THERMOSTAT_TIMER_FAN_MODE)); }
|
||||
|
||||
bool ThermostatClimate::fanning_action_ready_() {
|
||||
if (this->supports_fan_only_action_uses_fan_mode_timer_) {
|
||||
return !(this->timer_active_(thermostat::TIMER_FAN_MODE));
|
||||
return !(this->timer_active_(thermostat::THERMOSTAT_TIMER_FAN_MODE));
|
||||
}
|
||||
return !(this->timer_active_(thermostat::TIMER_IDLE_ON) || this->timer_active_(thermostat::TIMER_FANNING_OFF));
|
||||
return !(this->timer_active_(thermostat::THERMOSTAT_TIMER_IDLE_ON) ||
|
||||
this->timer_active_(thermostat::THERMOSTAT_TIMER_FANNING_OFF));
|
||||
}
|
||||
|
||||
bool ThermostatClimate::heating_action_ready_() {
|
||||
return !(this->timer_active_(thermostat::TIMER_IDLE_ON) || this->timer_active_(thermostat::TIMER_COOLING_ON) ||
|
||||
this->timer_active_(thermostat::TIMER_FANNING_OFF) || this->timer_active_(thermostat::TIMER_HEATING_OFF));
|
||||
return !(this->timer_active_(thermostat::THERMOSTAT_TIMER_IDLE_ON) ||
|
||||
this->timer_active_(thermostat::THERMOSTAT_TIMER_COOLING_ON) ||
|
||||
this->timer_active_(thermostat::THERMOSTAT_TIMER_FANNING_OFF) ||
|
||||
this->timer_active_(thermostat::THERMOSTAT_TIMER_HEATING_OFF));
|
||||
}
|
||||
|
||||
void ThermostatClimate::start_timer_(const ThermostatClimateTimerIndex timer_index) {
|
||||
@@ -958,37 +994,25 @@ bool ThermostatClimate::supplemental_heating_required_() {
|
||||
(this->supplemental_action_ == climate::CLIMATE_ACTION_HEATING));
|
||||
}
|
||||
|
||||
void ThermostatClimate::dump_preset_config_(const char *preset_name, const ThermostatClimateTargetTempConfig &config,
|
||||
bool is_default_preset) {
|
||||
ESP_LOGCONFIG(TAG, " %s Is Default: %s", preset_name, YESNO(is_default_preset));
|
||||
|
||||
void ThermostatClimate::dump_preset_config_(const char *preset_name, const ThermostatClimateTargetTempConfig &config) {
|
||||
if (this->supports_heat_) {
|
||||
if (this->supports_two_points_) {
|
||||
ESP_LOGCONFIG(TAG, " %s Default Target Temperature Low: %.1f°C", preset_name,
|
||||
config.default_temperature_low);
|
||||
} else {
|
||||
ESP_LOGCONFIG(TAG, " %s Default Target Temperature Low: %.1f°C", preset_name, config.default_temperature);
|
||||
}
|
||||
ESP_LOGCONFIG(TAG, " Default Target Temperature Low: %.1f°C",
|
||||
this->supports_two_points_ ? config.default_temperature_low : config.default_temperature);
|
||||
}
|
||||
if ((this->supports_cool_) || (this->supports_fan_only_)) {
|
||||
if (this->supports_two_points_) {
|
||||
ESP_LOGCONFIG(TAG, " %s Default Target Temperature High: %.1f°C", preset_name,
|
||||
config.default_temperature_high);
|
||||
} else {
|
||||
ESP_LOGCONFIG(TAG, " %s Default Target Temperature High: %.1f°C", preset_name, config.default_temperature);
|
||||
}
|
||||
ESP_LOGCONFIG(TAG, " Default Target Temperature High: %.1f°C",
|
||||
this->supports_two_points_ ? config.default_temperature_high : config.default_temperature);
|
||||
}
|
||||
|
||||
if (config.mode_.has_value()) {
|
||||
ESP_LOGCONFIG(TAG, " %s Default Mode: %s", preset_name,
|
||||
LOG_STR_ARG(climate::climate_mode_to_string(*config.mode_)));
|
||||
ESP_LOGCONFIG(TAG, " Default Mode: %s", LOG_STR_ARG(climate::climate_mode_to_string(*config.mode_)));
|
||||
}
|
||||
if (config.fan_mode_.has_value()) {
|
||||
ESP_LOGCONFIG(TAG, " %s Default Fan Mode: %s", preset_name,
|
||||
ESP_LOGCONFIG(TAG, " Default Fan Mode: %s",
|
||||
LOG_STR_ARG(climate::climate_fan_mode_to_string(*config.fan_mode_)));
|
||||
}
|
||||
if (config.swing_mode_.has_value()) {
|
||||
ESP_LOGCONFIG(TAG, " %s Default Swing Mode: %s", preset_name,
|
||||
ESP_LOGCONFIG(TAG, " Default Swing Mode: %s",
|
||||
LOG_STR_ARG(climate::climate_swing_mode_to_string(*config.swing_mode_)));
|
||||
}
|
||||
}
|
||||
@@ -1106,6 +1130,7 @@ ThermostatClimate::ThermostatClimate()
|
||||
heat_action_trigger_(new Trigger<>()),
|
||||
supplemental_heat_action_trigger_(new Trigger<>()),
|
||||
heat_mode_trigger_(new Trigger<>()),
|
||||
heat_cool_mode_trigger_(new Trigger<>()),
|
||||
auto_mode_trigger_(new Trigger<>()),
|
||||
idle_action_trigger_(new Trigger<>()),
|
||||
off_mode_trigger_(new Trigger<>()),
|
||||
@@ -1147,43 +1172,43 @@ void ThermostatClimate::set_heat_overrun(float overrun) { this->heating_overrun_
|
||||
void ThermostatClimate::set_supplemental_cool_delta(float delta) { this->supplemental_cool_delta_ = delta; }
|
||||
void ThermostatClimate::set_supplemental_heat_delta(float delta) { this->supplemental_heat_delta_ = delta; }
|
||||
void ThermostatClimate::set_cooling_maximum_run_time_in_sec(uint32_t time) {
|
||||
this->timer_[thermostat::TIMER_COOLING_MAX_RUN_TIME].time =
|
||||
this->timer_[thermostat::THERMOSTAT_TIMER_COOLING_MAX_RUN_TIME].time =
|
||||
1000 * (time < this->min_timer_duration_ ? this->min_timer_duration_ : time);
|
||||
}
|
||||
void ThermostatClimate::set_cooling_minimum_off_time_in_sec(uint32_t time) {
|
||||
this->timer_[thermostat::TIMER_COOLING_OFF].time =
|
||||
this->timer_[thermostat::THERMOSTAT_TIMER_COOLING_OFF].time =
|
||||
1000 * (time < this->min_timer_duration_ ? this->min_timer_duration_ : time);
|
||||
}
|
||||
void ThermostatClimate::set_cooling_minimum_run_time_in_sec(uint32_t time) {
|
||||
this->timer_[thermostat::TIMER_COOLING_ON].time =
|
||||
this->timer_[thermostat::THERMOSTAT_TIMER_COOLING_ON].time =
|
||||
1000 * (time < this->min_timer_duration_ ? this->min_timer_duration_ : time);
|
||||
}
|
||||
void ThermostatClimate::set_fan_mode_minimum_switching_time_in_sec(uint32_t time) {
|
||||
this->timer_[thermostat::TIMER_FAN_MODE].time =
|
||||
this->timer_[thermostat::THERMOSTAT_TIMER_FAN_MODE].time =
|
||||
1000 * (time < this->min_timer_duration_ ? this->min_timer_duration_ : time);
|
||||
}
|
||||
void ThermostatClimate::set_fanning_minimum_off_time_in_sec(uint32_t time) {
|
||||
this->timer_[thermostat::TIMER_FANNING_OFF].time =
|
||||
this->timer_[thermostat::THERMOSTAT_TIMER_FANNING_OFF].time =
|
||||
1000 * (time < this->min_timer_duration_ ? this->min_timer_duration_ : time);
|
||||
}
|
||||
void ThermostatClimate::set_fanning_minimum_run_time_in_sec(uint32_t time) {
|
||||
this->timer_[thermostat::TIMER_FANNING_ON].time =
|
||||
this->timer_[thermostat::THERMOSTAT_TIMER_FANNING_ON].time =
|
||||
1000 * (time < this->min_timer_duration_ ? this->min_timer_duration_ : time);
|
||||
}
|
||||
void ThermostatClimate::set_heating_maximum_run_time_in_sec(uint32_t time) {
|
||||
this->timer_[thermostat::TIMER_HEATING_MAX_RUN_TIME].time =
|
||||
this->timer_[thermostat::THERMOSTAT_TIMER_HEATING_MAX_RUN_TIME].time =
|
||||
1000 * (time < this->min_timer_duration_ ? this->min_timer_duration_ : time);
|
||||
}
|
||||
void ThermostatClimate::set_heating_minimum_off_time_in_sec(uint32_t time) {
|
||||
this->timer_[thermostat::TIMER_HEATING_OFF].time =
|
||||
this->timer_[thermostat::THERMOSTAT_TIMER_HEATING_OFF].time =
|
||||
1000 * (time < this->min_timer_duration_ ? this->min_timer_duration_ : time);
|
||||
}
|
||||
void ThermostatClimate::set_heating_minimum_run_time_in_sec(uint32_t time) {
|
||||
this->timer_[thermostat::TIMER_HEATING_ON].time =
|
||||
this->timer_[thermostat::THERMOSTAT_TIMER_HEATING_ON].time =
|
||||
1000 * (time < this->min_timer_duration_ ? this->min_timer_duration_ : time);
|
||||
}
|
||||
void ThermostatClimate::set_idle_minimum_time_in_sec(uint32_t time) {
|
||||
this->timer_[thermostat::TIMER_IDLE_ON].time =
|
||||
this->timer_[thermostat::THERMOSTAT_TIMER_IDLE_ON].time =
|
||||
1000 * (time < this->min_timer_duration_ ? this->min_timer_duration_ : time);
|
||||
}
|
||||
void ThermostatClimate::set_sensor(sensor::Sensor *sensor) { this->sensor_ = sensor; }
|
||||
@@ -1274,6 +1299,7 @@ Trigger<> *ThermostatClimate::get_cool_mode_trigger() const { return this->cool_
|
||||
Trigger<> *ThermostatClimate::get_dry_mode_trigger() const { return this->dry_mode_trigger_; }
|
||||
Trigger<> *ThermostatClimate::get_fan_only_mode_trigger() const { return this->fan_only_mode_trigger_; }
|
||||
Trigger<> *ThermostatClimate::get_heat_mode_trigger() const { return this->heat_mode_trigger_; }
|
||||
Trigger<> *ThermostatClimate::get_heat_cool_mode_trigger() const { return this->heat_cool_mode_trigger_; }
|
||||
Trigger<> *ThermostatClimate::get_off_mode_trigger() const { return this->off_mode_trigger_; }
|
||||
Trigger<> *ThermostatClimate::get_fan_mode_on_trigger() const { return this->fan_mode_on_trigger_; }
|
||||
Trigger<> *ThermostatClimate::get_fan_mode_off_trigger() const { return this->fan_mode_off_trigger_; }
|
||||
@@ -1295,64 +1321,69 @@ Trigger<> *ThermostatClimate::get_preset_change_trigger() const { return this->p
|
||||
void ThermostatClimate::dump_config() {
|
||||
LOG_CLIMATE("", "Thermostat", this);
|
||||
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" On boot, restore from: %s\n"
|
||||
" Use Start-up Delay: %s",
|
||||
this->on_boot_restore_from_ == thermostat::DEFAULT_PRESET ? "DEFAULT_PRESET" : "MEMORY",
|
||||
YESNO(this->use_startup_delay_));
|
||||
if (this->supports_two_points_) {
|
||||
ESP_LOGCONFIG(TAG, " Minimum Set Point Differential: %.1f°C", this->set_point_minimum_differential_);
|
||||
}
|
||||
ESP_LOGCONFIG(TAG, " Use Start-up Delay: %s", YESNO(this->use_startup_delay_));
|
||||
if (this->supports_cool_) {
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Cooling Parameters:\n"
|
||||
" Deadband: %.1f°C\n"
|
||||
" Overrun: %.1f°C",
|
||||
this->cooling_deadband_, this->cooling_overrun_);
|
||||
if ((this->supplemental_cool_delta_ > 0) || (this->timer_duration_(thermostat::TIMER_COOLING_MAX_RUN_TIME) > 0)) {
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Supplemental Delta: %.1f°C\n"
|
||||
" Maximum Run Time: %" PRIu32 "s",
|
||||
this->supplemental_cool_delta_,
|
||||
this->timer_duration_(thermostat::TIMER_COOLING_MAX_RUN_TIME) / 1000);
|
||||
}
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Overrun: %.1f°C\n"
|
||||
" Minimum Off Time: %" PRIu32 "s\n"
|
||||
" Minimum Run Time: %" PRIu32 "s",
|
||||
this->timer_duration_(thermostat::TIMER_COOLING_OFF) / 1000,
|
||||
this->timer_duration_(thermostat::TIMER_COOLING_ON) / 1000);
|
||||
this->cooling_deadband_, this->cooling_overrun_,
|
||||
this->timer_duration_(thermostat::THERMOSTAT_TIMER_COOLING_OFF) / 1000,
|
||||
this->timer_duration_(thermostat::THERMOSTAT_TIMER_COOLING_ON) / 1000);
|
||||
if ((this->supplemental_cool_delta_ > 0) ||
|
||||
(this->timer_duration_(thermostat::THERMOSTAT_TIMER_COOLING_MAX_RUN_TIME) > 0)) {
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Maximum Run Time: %" PRIu32 "s\n"
|
||||
" Supplemental Delta: %.1f°C",
|
||||
this->timer_duration_(thermostat::THERMOSTAT_TIMER_COOLING_MAX_RUN_TIME) / 1000,
|
||||
this->supplemental_cool_delta_);
|
||||
}
|
||||
}
|
||||
if (this->supports_heat_) {
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Heating Parameters:\n"
|
||||
" Deadband: %.1f°C\n"
|
||||
" Overrun: %.1f°C",
|
||||
this->heating_deadband_, this->heating_overrun_);
|
||||
if ((this->supplemental_heat_delta_ > 0) || (this->timer_duration_(thermostat::TIMER_HEATING_MAX_RUN_TIME) > 0)) {
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Supplemental Delta: %.1f°C\n"
|
||||
" Maximum Run Time: %" PRIu32 "s",
|
||||
this->supplemental_heat_delta_,
|
||||
this->timer_duration_(thermostat::TIMER_HEATING_MAX_RUN_TIME) / 1000);
|
||||
}
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Overrun: %.1f°C\n"
|
||||
" Minimum Off Time: %" PRIu32 "s\n"
|
||||
" Minimum Run Time: %" PRIu32 "s",
|
||||
this->timer_duration_(thermostat::TIMER_HEATING_OFF) / 1000,
|
||||
this->timer_duration_(thermostat::TIMER_HEATING_ON) / 1000);
|
||||
this->heating_deadband_, this->heating_overrun_,
|
||||
this->timer_duration_(thermostat::THERMOSTAT_TIMER_HEATING_OFF) / 1000,
|
||||
this->timer_duration_(thermostat::THERMOSTAT_TIMER_HEATING_ON) / 1000);
|
||||
if ((this->supplemental_heat_delta_ > 0) ||
|
||||
(this->timer_duration_(thermostat::THERMOSTAT_TIMER_HEATING_MAX_RUN_TIME) > 0)) {
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Maximum Run Time: %" PRIu32 "s\n"
|
||||
" Supplemental Delta: %.1f°C",
|
||||
this->timer_duration_(thermostat::THERMOSTAT_TIMER_HEATING_MAX_RUN_TIME) / 1000,
|
||||
this->supplemental_heat_delta_);
|
||||
}
|
||||
}
|
||||
if (this->supports_fan_only_) {
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Fanning Minimum Off Time: %" PRIu32 "s\n"
|
||||
" Fanning Minimum Run Time: %" PRIu32 "s",
|
||||
this->timer_duration_(thermostat::TIMER_FANNING_OFF) / 1000,
|
||||
this->timer_duration_(thermostat::TIMER_FANNING_ON) / 1000);
|
||||
" Fan Parameters:\n"
|
||||
" Minimum Off Time: %" PRIu32 "s\n"
|
||||
" Minimum Run Time: %" PRIu32 "s",
|
||||
this->timer_duration_(thermostat::THERMOSTAT_TIMER_FANNING_OFF) / 1000,
|
||||
this->timer_duration_(thermostat::THERMOSTAT_TIMER_FANNING_ON) / 1000);
|
||||
}
|
||||
if (this->supports_fan_mode_on_ || this->supports_fan_mode_off_ || this->supports_fan_mode_auto_ ||
|
||||
this->supports_fan_mode_low_ || this->supports_fan_mode_medium_ || this->supports_fan_mode_high_ ||
|
||||
this->supports_fan_mode_middle_ || this->supports_fan_mode_focus_ || this->supports_fan_mode_diffuse_ ||
|
||||
this->supports_fan_mode_quiet_) {
|
||||
ESP_LOGCONFIG(TAG, " Minimum Fan Mode Switching Time: %" PRIu32 "s",
|
||||
this->timer_duration_(thermostat::TIMER_FAN_MODE) / 1000);
|
||||
this->timer_duration_(thermostat::THERMOSTAT_TIMER_FAN_MODE) / 1000);
|
||||
}
|
||||
ESP_LOGCONFIG(TAG, " Minimum Idle Time: %" PRIu32 "s", this->timer_[thermostat::TIMER_IDLE_ON].time / 1000);
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Minimum Idle Time: %" PRIu32 "s\n"
|
||||
" Supported MODES:\n"
|
||||
" AUTO: %s\n"
|
||||
" HEAT/COOL: %s\n"
|
||||
@@ -1362,8 +1393,9 @@ void ThermostatClimate::dump_config() {
|
||||
" FAN_ONLY: %s\n"
|
||||
" FAN_ONLY_ACTION_USES_FAN_MODE_TIMER: %s\n"
|
||||
" FAN_ONLY_COOLING: %s",
|
||||
YESNO(this->supports_auto_), YESNO(this->supports_heat_cool_), YESNO(this->supports_heat_),
|
||||
YESNO(this->supports_cool_), YESNO(this->supports_dry_), YESNO(this->supports_fan_only_),
|
||||
this->timer_[thermostat::THERMOSTAT_TIMER_IDLE_ON].time / 1000, YESNO(this->supports_auto_),
|
||||
YESNO(this->supports_heat_cool_), YESNO(this->supports_heat_), YESNO(this->supports_cool_),
|
||||
YESNO(this->supports_dry_), YESNO(this->supports_fan_only_),
|
||||
YESNO(this->supports_fan_only_action_uses_fan_mode_timer_), YESNO(this->supports_fan_only_cooling_));
|
||||
if (this->supports_cool_) {
|
||||
ESP_LOGCONFIG(TAG, " FAN_WITH_COOLING: %s", YESNO(this->supports_fan_with_cooling_));
|
||||
@@ -1382,40 +1414,39 @@ void ThermostatClimate::dump_config() {
|
||||
" MIDDLE: %s\n"
|
||||
" FOCUS: %s\n"
|
||||
" DIFFUSE: %s\n"
|
||||
" QUIET: %s",
|
||||
YESNO(this->supports_fan_mode_on_), YESNO(this->supports_fan_mode_off_),
|
||||
YESNO(this->supports_fan_mode_auto_), YESNO(this->supports_fan_mode_low_),
|
||||
YESNO(this->supports_fan_mode_medium_), YESNO(this->supports_fan_mode_high_),
|
||||
YESNO(this->supports_fan_mode_middle_), YESNO(this->supports_fan_mode_focus_),
|
||||
YESNO(this->supports_fan_mode_diffuse_), YESNO(this->supports_fan_mode_quiet_));
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" QUIET: %s\n"
|
||||
" Supported SWING MODES:\n"
|
||||
" BOTH: %s\n"
|
||||
" OFF: %s\n"
|
||||
" HORIZONTAL: %s\n"
|
||||
" VERTICAL: %s\n"
|
||||
" Supports TWO SET POINTS: %s",
|
||||
YESNO(this->supports_fan_mode_on_), YESNO(this->supports_fan_mode_off_),
|
||||
YESNO(this->supports_fan_mode_auto_), YESNO(this->supports_fan_mode_low_),
|
||||
YESNO(this->supports_fan_mode_medium_), YESNO(this->supports_fan_mode_high_),
|
||||
YESNO(this->supports_fan_mode_middle_), YESNO(this->supports_fan_mode_focus_),
|
||||
YESNO(this->supports_fan_mode_diffuse_), YESNO(this->supports_fan_mode_quiet_),
|
||||
YESNO(this->supports_swing_mode_both_), YESNO(this->supports_swing_mode_off_),
|
||||
YESNO(this->supports_swing_mode_horizontal_), YESNO(this->supports_swing_mode_vertical_),
|
||||
YESNO(this->supports_two_points_));
|
||||
|
||||
ESP_LOGCONFIG(TAG, " Supported PRESETS: ");
|
||||
for (auto &it : this->preset_config_) {
|
||||
const auto *preset_name = LOG_STR_ARG(climate::climate_preset_to_string(it.first));
|
||||
|
||||
ESP_LOGCONFIG(TAG, " Supports %s: %s", preset_name, YESNO(true));
|
||||
this->dump_preset_config_(preset_name, it.second, it.first == this->default_preset_);
|
||||
if (!this->preset_config_.empty()) {
|
||||
ESP_LOGCONFIG(TAG, " Supported PRESETS:");
|
||||
for (auto &it : this->preset_config_) {
|
||||
const auto *preset_name = LOG_STR_ARG(climate::climate_preset_to_string(it.first));
|
||||
ESP_LOGCONFIG(TAG, " %s:%s", preset_name, it.first == this->default_preset_ ? " (default)" : "");
|
||||
this->dump_preset_config_(preset_name, it.second);
|
||||
}
|
||||
}
|
||||
|
||||
ESP_LOGCONFIG(TAG, " Supported CUSTOM PRESETS: ");
|
||||
for (auto &it : this->custom_preset_config_) {
|
||||
const auto *preset_name = it.first.c_str();
|
||||
|
||||
ESP_LOGCONFIG(TAG, " Supports %s: %s", preset_name, YESNO(true));
|
||||
this->dump_preset_config_(preset_name, it.second, it.first == this->default_custom_preset_);
|
||||
if (!this->custom_preset_config_.empty()) {
|
||||
ESP_LOGCONFIG(TAG, " Supported CUSTOM PRESETS:");
|
||||
for (auto &it : this->custom_preset_config_) {
|
||||
const auto *preset_name = it.first.c_str();
|
||||
ESP_LOGCONFIG(TAG, " %s:%s", preset_name, it.first == this->default_custom_preset_ ? " (default)" : "");
|
||||
this->dump_preset_config_(preset_name, it.second);
|
||||
}
|
||||
}
|
||||
ESP_LOGCONFIG(TAG, " On boot, restore from: %s",
|
||||
this->on_boot_restore_from_ == thermostat::DEFAULT_PRESET ? "DEFAULT_PRESET" : "MEMORY");
|
||||
}
|
||||
|
||||
ThermostatClimateTargetTempConfig::ThermostatClimateTargetTempConfig() = default;
|
||||
|
||||
@@ -6,24 +6,25 @@
|
||||
#include "esphome/components/climate/climate.h"
|
||||
#include "esphome/components/sensor/sensor.h"
|
||||
|
||||
#include <array>
|
||||
#include <cinttypes>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
namespace esphome {
|
||||
namespace thermostat {
|
||||
|
||||
enum ThermostatClimateTimerIndex : uint8_t {
|
||||
TIMER_COOLING_MAX_RUN_TIME = 0,
|
||||
TIMER_COOLING_OFF = 1,
|
||||
TIMER_COOLING_ON = 2,
|
||||
TIMER_FAN_MODE = 3,
|
||||
TIMER_FANNING_OFF = 4,
|
||||
TIMER_FANNING_ON = 5,
|
||||
TIMER_HEATING_MAX_RUN_TIME = 6,
|
||||
TIMER_HEATING_OFF = 7,
|
||||
TIMER_HEATING_ON = 8,
|
||||
TIMER_IDLE_ON = 9,
|
||||
THERMOSTAT_TIMER_COOLING_MAX_RUN_TIME = 0,
|
||||
THERMOSTAT_TIMER_COOLING_OFF = 1,
|
||||
THERMOSTAT_TIMER_COOLING_ON = 2,
|
||||
THERMOSTAT_TIMER_FAN_MODE = 3,
|
||||
THERMOSTAT_TIMER_FANNING_OFF = 4,
|
||||
THERMOSTAT_TIMER_FANNING_ON = 5,
|
||||
THERMOSTAT_TIMER_HEATING_MAX_RUN_TIME = 6,
|
||||
THERMOSTAT_TIMER_HEATING_OFF = 7,
|
||||
THERMOSTAT_TIMER_HEATING_ON = 8,
|
||||
THERMOSTAT_TIMER_IDLE_ON = 9,
|
||||
THERMOSTAT_TIMER_COUNT = 10,
|
||||
};
|
||||
|
||||
enum OnBootRestoreFrom : uint8_t {
|
||||
@@ -131,6 +132,7 @@ class ThermostatClimate : public climate::Climate, public Component {
|
||||
Trigger<> *get_dry_mode_trigger() const;
|
||||
Trigger<> *get_fan_only_mode_trigger() const;
|
||||
Trigger<> *get_heat_mode_trigger() const;
|
||||
Trigger<> *get_heat_cool_mode_trigger() const;
|
||||
Trigger<> *get_off_mode_trigger() const;
|
||||
Trigger<> *get_fan_mode_on_trigger() const;
|
||||
Trigger<> *get_fan_mode_off_trigger() const;
|
||||
@@ -163,9 +165,10 @@ class ThermostatClimate : public climate::Climate, public Component {
|
||||
/// Returns the fan mode that is locked in (check fan_mode_change_delayed(), first!)
|
||||
climate::ClimateFanMode locked_fan_mode();
|
||||
/// Set point and hysteresis validation
|
||||
bool hysteresis_valid(); // returns true if valid
|
||||
bool hysteresis_valid(); // returns true if valid
|
||||
bool limit_setpoints_for_heat_cool(); // returns true if set points should be further limited within visual range
|
||||
void validate_target_temperature();
|
||||
void validate_target_temperatures();
|
||||
void validate_target_temperatures(bool pin_target_temperature_high);
|
||||
void validate_target_temperature_low();
|
||||
void validate_target_temperature_high();
|
||||
|
||||
@@ -241,12 +244,28 @@ class ThermostatClimate : public climate::Climate, public Component {
|
||||
bool supplemental_cooling_required_();
|
||||
bool supplemental_heating_required_();
|
||||
|
||||
void dump_preset_config_(const char *preset_name, const ThermostatClimateTargetTempConfig &config,
|
||||
bool is_default_preset);
|
||||
void dump_preset_config_(const char *preset_name, const ThermostatClimateTargetTempConfig &config);
|
||||
|
||||
/// Minimum allowable duration in seconds for action timers
|
||||
const uint8_t min_timer_duration_{1};
|
||||
|
||||
/// Store previously-known states
|
||||
///
|
||||
/// These are used to determine when a trigger/action needs to be called
|
||||
climate::ClimateFanMode prev_fan_mode_{climate::CLIMATE_FAN_ON};
|
||||
climate::ClimateMode prev_mode_{climate::CLIMATE_MODE_OFF};
|
||||
climate::ClimateSwingMode prev_swing_mode_{climate::CLIMATE_SWING_OFF};
|
||||
|
||||
/// The current supplemental action
|
||||
climate::ClimateAction supplemental_action_{climate::CLIMATE_ACTION_OFF};
|
||||
|
||||
/// Default standard preset to use on start up
|
||||
climate::ClimatePreset default_preset_{};
|
||||
|
||||
/// If set to DEFAULT_PRESET then the default preset is always used. When MEMORY prior
|
||||
/// state will attempt to be restored if possible
|
||||
OnBootRestoreFrom on_boot_restore_from_{OnBootRestoreFrom::MEMORY};
|
||||
|
||||
/// Whether the controller supports auto/cooling/drying/fanning/heating.
|
||||
///
|
||||
/// A false value for any given attribute means that the controller has no such action
|
||||
@@ -362,9 +381,15 @@ class ThermostatClimate : public climate::Climate, public Component {
|
||||
Trigger<> *supplemental_heat_action_trigger_{nullptr};
|
||||
Trigger<> *heat_mode_trigger_{nullptr};
|
||||
|
||||
/// The trigger to call when the controller should switch to heat/cool mode.
|
||||
///
|
||||
/// In heat/cool mode, the controller will enable heating/cooling as necessary and switch
|
||||
/// to idle when the temperature is within the thresholds/set points.
|
||||
Trigger<> *heat_cool_mode_trigger_{nullptr};
|
||||
|
||||
/// The trigger to call when the controller should switch to auto mode.
|
||||
///
|
||||
/// In auto mode, the controller will enable heating/cooling as necessary and switch
|
||||
/// In auto mode, the controller will enable heating/cooling as supported/necessary and switch
|
||||
/// to idle when the temperature is within the thresholds/set points.
|
||||
Trigger<> *auto_mode_trigger_{nullptr};
|
||||
|
||||
@@ -438,35 +463,21 @@ class ThermostatClimate : public climate::Climate, public Component {
|
||||
Trigger<> *prev_mode_trigger_{nullptr};
|
||||
Trigger<> *prev_swing_mode_trigger_{nullptr};
|
||||
|
||||
/// If set to DEFAULT_PRESET then the default preset is always used. When MEMORY prior
|
||||
/// state will attempt to be restored if possible
|
||||
OnBootRestoreFrom on_boot_restore_from_{OnBootRestoreFrom::MEMORY};
|
||||
|
||||
/// Store previously-known states
|
||||
///
|
||||
/// These are used to determine when a trigger/action needs to be called
|
||||
climate::ClimateAction supplemental_action_{climate::CLIMATE_ACTION_OFF};
|
||||
climate::ClimateFanMode prev_fan_mode_{climate::CLIMATE_FAN_ON};
|
||||
climate::ClimateMode prev_mode_{climate::CLIMATE_MODE_OFF};
|
||||
climate::ClimateSwingMode prev_swing_mode_{climate::CLIMATE_SWING_OFF};
|
||||
|
||||
/// Default standard preset to use on start up
|
||||
climate::ClimatePreset default_preset_{};
|
||||
/// Default custom preset to use on start up
|
||||
std::string default_custom_preset_{};
|
||||
|
||||
/// Climate action timers
|
||||
std::vector<ThermostatClimateTimer> timer_{
|
||||
{false, 0, 0, std::bind(&ThermostatClimate::cooling_max_run_time_timer_callback_, this)},
|
||||
{false, 0, 0, std::bind(&ThermostatClimate::cooling_off_timer_callback_, this)},
|
||||
{false, 0, 0, std::bind(&ThermostatClimate::cooling_on_timer_callback_, this)},
|
||||
{false, 0, 0, std::bind(&ThermostatClimate::fan_mode_timer_callback_, this)},
|
||||
{false, 0, 0, std::bind(&ThermostatClimate::fanning_off_timer_callback_, this)},
|
||||
{false, 0, 0, std::bind(&ThermostatClimate::fanning_on_timer_callback_, this)},
|
||||
{false, 0, 0, std::bind(&ThermostatClimate::heating_max_run_time_timer_callback_, this)},
|
||||
{false, 0, 0, std::bind(&ThermostatClimate::heating_off_timer_callback_, this)},
|
||||
{false, 0, 0, std::bind(&ThermostatClimate::heating_on_timer_callback_, this)},
|
||||
{false, 0, 0, std::bind(&ThermostatClimate::idle_on_timer_callback_, this)},
|
||||
std::array<ThermostatClimateTimer, THERMOSTAT_TIMER_COUNT> timer_{
|
||||
ThermostatClimateTimer(false, 0, 0, std::bind(&ThermostatClimate::cooling_max_run_time_timer_callback_, this)),
|
||||
ThermostatClimateTimer(false, 0, 0, std::bind(&ThermostatClimate::cooling_off_timer_callback_, this)),
|
||||
ThermostatClimateTimer(false, 0, 0, std::bind(&ThermostatClimate::cooling_on_timer_callback_, this)),
|
||||
ThermostatClimateTimer(false, 0, 0, std::bind(&ThermostatClimate::fan_mode_timer_callback_, this)),
|
||||
ThermostatClimateTimer(false, 0, 0, std::bind(&ThermostatClimate::fanning_off_timer_callback_, this)),
|
||||
ThermostatClimateTimer(false, 0, 0, std::bind(&ThermostatClimate::fanning_on_timer_callback_, this)),
|
||||
ThermostatClimateTimer(false, 0, 0, std::bind(&ThermostatClimate::heating_max_run_time_timer_callback_, this)),
|
||||
ThermostatClimateTimer(false, 0, 0, std::bind(&ThermostatClimate::heating_off_timer_callback_, this)),
|
||||
ThermostatClimateTimer(false, 0, 0, std::bind(&ThermostatClimate::heating_on_timer_callback_, this)),
|
||||
ThermostatClimateTimer(false, 0, 0, std::bind(&ThermostatClimate::idle_on_timer_callback_, this)),
|
||||
};
|
||||
|
||||
/// The set of standard preset configurations this thermostat supports (Eg. AWAY, ECO, etc)
|
||||
|
||||
@@ -104,7 +104,7 @@ void UFireECComponent::write_data_(uint8_t reg, float data) {
|
||||
void UFireECComponent::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "uFire-EC");
|
||||
LOG_I2C_DEVICE(this)
|
||||
LOG_UPDATE_INTERVAL(this)
|
||||
LOG_UPDATE_INTERVAL(this);
|
||||
LOG_SENSOR(" ", "EC Sensor", this->ec_sensor_);
|
||||
LOG_SENSOR(" ", "Temperature Sensor", this->temperature_sensor_);
|
||||
LOG_SENSOR(" ", "Temperature Sensor external", this->temperature_sensor_external_);
|
||||
|
||||
@@ -141,7 +141,7 @@ void UFireISEComponent::write_data_(uint8_t reg, float data) {
|
||||
void UFireISEComponent::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "uFire-ISE");
|
||||
LOG_I2C_DEVICE(this)
|
||||
LOG_UPDATE_INTERVAL(this)
|
||||
LOG_UPDATE_INTERVAL(this);
|
||||
LOG_SENSOR(" ", "PH Sensor", this->ph_sensor_);
|
||||
LOG_SENSOR(" ", "Temperature Sensor", this->temperature_sensor_);
|
||||
LOG_SENSOR(" ", "Temperature Sensor external", this->temperature_sensor_external_);
|
||||
|
||||
@@ -181,7 +181,7 @@ void WaveshareEPaper2P13InV3::dump_config() {
|
||||
LOG_PIN(" Reset Pin: ", this->reset_pin_)
|
||||
LOG_PIN(" DC Pin: ", this->dc_pin_)
|
||||
LOG_PIN(" Busy Pin: ", this->busy_pin_)
|
||||
LOG_UPDATE_INTERVAL(this)
|
||||
LOG_UPDATE_INTERVAL(this);
|
||||
}
|
||||
|
||||
void WaveshareEPaper2P13InV3::set_full_update_every(uint32_t full_update_every) {
|
||||
|
||||
@@ -4,7 +4,7 @@ from enum import Enum
|
||||
|
||||
from esphome.enum import StrEnum
|
||||
|
||||
__version__ = "2025.9.0-dev"
|
||||
__version__ = "2025.9.0b1"
|
||||
|
||||
ALLOWED_NAME_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789-_"
|
||||
VALID_SUBSTITUTIONS_CHARACTERS = (
|
||||
@@ -424,6 +424,7 @@ CONF_HEAD = "head"
|
||||
CONF_HEADING = "heading"
|
||||
CONF_HEARTBEAT = "heartbeat"
|
||||
CONF_HEAT_ACTION = "heat_action"
|
||||
CONF_HEAT_COOL_MODE = "heat_cool_mode"
|
||||
CONF_HEAT_DEADBAND = "heat_deadband"
|
||||
CONF_HEAT_MODE = "heat_mode"
|
||||
CONF_HEAT_OVERRUN = "heat_overrun"
|
||||
|
||||
@@ -34,37 +34,20 @@ namespace esphome {
|
||||
|
||||
static const char *const TAG = "app";
|
||||
|
||||
// Helper function for insertion sort of components by setup priority
|
||||
// Helper function for insertion sort of components by priority
|
||||
// Using insertion sort instead of std::stable_sort saves ~1.3KB of flash
|
||||
// by avoiding template instantiations (std::rotate, std::stable_sort, lambdas)
|
||||
// IMPORTANT: This sort is stable (preserves relative order of equal elements),
|
||||
// which is necessary to maintain user-defined component order for same priority
|
||||
template<typename Iterator> static void insertion_sort_by_setup_priority(Iterator first, Iterator last) {
|
||||
template<typename Iterator, float (Component::*GetPriority)() const>
|
||||
static void insertion_sort_by_priority(Iterator first, Iterator last) {
|
||||
for (auto it = first + 1; it != last; ++it) {
|
||||
auto key = *it;
|
||||
float key_priority = key->get_actual_setup_priority();
|
||||
float key_priority = (key->*GetPriority)();
|
||||
auto j = it - 1;
|
||||
|
||||
// Using '<' (not '<=') ensures stability - equal priority components keep their order
|
||||
while (j >= first && (*j)->get_actual_setup_priority() < key_priority) {
|
||||
*(j + 1) = *j;
|
||||
j--;
|
||||
}
|
||||
*(j + 1) = key;
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function for insertion sort of components by loop priority
|
||||
// IMPORTANT: This sort is stable (preserves relative order of equal elements),
|
||||
// which is required when components are re-sorted during setup() if they block
|
||||
template<typename Iterator> static void insertion_sort_by_loop_priority(Iterator first, Iterator last) {
|
||||
for (auto it = first + 1; it != last; ++it) {
|
||||
auto key = *it;
|
||||
float key_priority = key->get_loop_priority();
|
||||
auto j = it - 1;
|
||||
|
||||
// Using '<' (not '<=') ensures stability - equal priority components keep their order
|
||||
while (j >= first && (*j)->get_loop_priority() < key_priority) {
|
||||
while (j >= first && ((*j)->*GetPriority)() < key_priority) {
|
||||
*(j + 1) = *j;
|
||||
j--;
|
||||
}
|
||||
@@ -80,7 +63,7 @@ void Application::register_component_(Component *comp) {
|
||||
|
||||
for (auto *c : this->components_) {
|
||||
if (comp == c) {
|
||||
ESP_LOGW(TAG, "Component %s already registered! (%p)", c->get_component_source(), c);
|
||||
ESP_LOGW(TAG, "Component %s already registered! (%p)", LOG_STR_ARG(c->get_component_log_str()), c);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -91,7 +74,8 @@ void Application::setup() {
|
||||
ESP_LOGV(TAG, "Sorting components by setup priority");
|
||||
|
||||
// Sort by setup priority using our helper function
|
||||
insertion_sort_by_setup_priority(this->components_.begin(), this->components_.end());
|
||||
insertion_sort_by_priority<decltype(this->components_.begin()), &Component::get_actual_setup_priority>(
|
||||
this->components_.begin(), this->components_.end());
|
||||
|
||||
// Initialize looping_components_ early so enable_pending_loops_() works during setup
|
||||
this->calculate_looping_components_();
|
||||
@@ -108,7 +92,8 @@ void Application::setup() {
|
||||
continue;
|
||||
|
||||
// Sort components 0 through i by loop priority
|
||||
insertion_sort_by_loop_priority(this->components_.begin(), this->components_.begin() + i + 1);
|
||||
insertion_sort_by_priority<decltype(this->components_.begin()), &Component::get_loop_priority>(
|
||||
this->components_.begin(), this->components_.begin() + i + 1);
|
||||
|
||||
do {
|
||||
uint8_t new_app_state = STATUS_LED_WARNING;
|
||||
@@ -340,8 +325,8 @@ void Application::teardown_components(uint32_t timeout_ms) {
|
||||
// Note: At this point, connections are either disconnected or in a bad state,
|
||||
// so this warning will only appear via serial rather than being transmitted to clients
|
||||
for (size_t i = 0; i < pending_count; ++i) {
|
||||
ESP_LOGW(TAG, "%s did not complete teardown within %" PRIu32 " ms", pending_components[i]->get_component_source(),
|
||||
timeout_ms);
|
||||
ESP_LOGW(TAG, "%s did not complete teardown within %" PRIu32 " ms",
|
||||
LOG_STR_ARG(pending_components[i]->get_component_log_str()), timeout_ms);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -361,20 +346,19 @@ void Application::calculate_looping_components_() {
|
||||
// Add all components with loop override that aren't already LOOP_DONE
|
||||
// Some components (like logger) may call disable_loop() during initialization
|
||||
// before setup runs, so we need to respect their LOOP_DONE state
|
||||
for (auto *obj : this->components_) {
|
||||
if (obj->has_overridden_loop() &&
|
||||
(obj->get_component_state() & COMPONENT_STATE_MASK) != COMPONENT_STATE_LOOP_DONE) {
|
||||
this->looping_components_.push_back(obj);
|
||||
}
|
||||
}
|
||||
this->add_looping_components_by_state_(false);
|
||||
|
||||
this->looping_components_active_end_ = this->looping_components_.size();
|
||||
|
||||
// Then add any components that are already LOOP_DONE to the inactive section
|
||||
// This handles components that called disable_loop() during initialization
|
||||
this->add_looping_components_by_state_(true);
|
||||
}
|
||||
|
||||
void Application::add_looping_components_by_state_(bool match_loop_done) {
|
||||
for (auto *obj : this->components_) {
|
||||
if (obj->has_overridden_loop() &&
|
||||
(obj->get_component_state() & COMPONENT_STATE_MASK) == COMPONENT_STATE_LOOP_DONE) {
|
||||
((obj->get_component_state() & COMPONENT_STATE_MASK) == COMPONENT_STATE_LOOP_DONE) == match_loop_done) {
|
||||
this->looping_components_.push_back(obj);
|
||||
}
|
||||
}
|
||||
@@ -473,7 +457,7 @@ void Application::enable_pending_loops_() {
|
||||
|
||||
// Clear the pending flag and enable the loop
|
||||
component->pending_enable_loop_ = false;
|
||||
ESP_LOGVV(TAG, "%s loop enabled from ISR", component->get_component_source());
|
||||
ESP_LOGVV(TAG, "%s loop enabled from ISR", LOG_STR_ARG(component->get_component_log_str()));
|
||||
component->component_state_ &= ~COMPONENT_STATE_MASK;
|
||||
component->component_state_ |= COMPONENT_STATE_LOOP;
|
||||
|
||||
|
||||
@@ -431,6 +431,7 @@ class Application {
|
||||
void register_component_(Component *comp);
|
||||
|
||||
void calculate_looping_components_();
|
||||
void add_looping_components_by_state_(bool match_loop_done);
|
||||
|
||||
// These methods are called by Component::disable_loop() and Component::enable_loop()
|
||||
// Components should not call these directly - use this->disable_loop() or this->enable_loop()
|
||||
|
||||
@@ -141,7 +141,7 @@ void Component::call_dump_config() {
|
||||
}
|
||||
}
|
||||
}
|
||||
ESP_LOGE(TAG, " %s is marked FAILED: %s", this->get_component_source(),
|
||||
ESP_LOGE(TAG, " %s is marked FAILED: %s", LOG_STR_ARG(this->get_component_log_str()),
|
||||
error_msg ? error_msg : LOG_STR_LITERAL("unspecified"));
|
||||
}
|
||||
}
|
||||
@@ -153,14 +153,14 @@ void Component::call() {
|
||||
case COMPONENT_STATE_CONSTRUCTION: {
|
||||
// State Construction: Call setup and set state to setup
|
||||
this->set_component_state_(COMPONENT_STATE_SETUP);
|
||||
ESP_LOGV(TAG, "Setup %s", this->get_component_source());
|
||||
ESP_LOGV(TAG, "Setup %s", LOG_STR_ARG(this->get_component_log_str()));
|
||||
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
|
||||
uint32_t start_time = millis();
|
||||
#endif
|
||||
this->call_setup();
|
||||
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
|
||||
uint32_t setup_time = millis() - start_time;
|
||||
ESP_LOGCONFIG(TAG, "Setup %s took %ums", this->get_component_source(), (unsigned) setup_time);
|
||||
ESP_LOGCONFIG(TAG, "Setup %s took %ums", LOG_STR_ARG(this->get_component_log_str()), (unsigned) setup_time);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
@@ -181,10 +181,8 @@ void Component::call() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
const char *Component::get_component_source() const {
|
||||
if (this->component_source_ == nullptr)
|
||||
return "<unknown>";
|
||||
return this->component_source_;
|
||||
const LogString *Component::get_component_log_str() const {
|
||||
return this->component_source_ == nullptr ? LOG_STR("<unknown>") : this->component_source_;
|
||||
}
|
||||
bool Component::should_warn_of_blocking(uint32_t blocking_time) {
|
||||
if (blocking_time > this->warn_if_blocking_over_) {
|
||||
@@ -200,7 +198,7 @@ bool Component::should_warn_of_blocking(uint32_t blocking_time) {
|
||||
return false;
|
||||
}
|
||||
void Component::mark_failed() {
|
||||
ESP_LOGE(TAG, "%s was marked as failed", this->get_component_source());
|
||||
ESP_LOGE(TAG, "%s was marked as failed", LOG_STR_ARG(this->get_component_log_str()));
|
||||
this->set_component_state_(COMPONENT_STATE_FAILED);
|
||||
this->status_set_error();
|
||||
// Also remove from loop since failed components shouldn't loop
|
||||
@@ -212,14 +210,14 @@ void Component::set_component_state_(uint8_t state) {
|
||||
}
|
||||
void Component::disable_loop() {
|
||||
if ((this->component_state_ & COMPONENT_STATE_MASK) != COMPONENT_STATE_LOOP_DONE) {
|
||||
ESP_LOGVV(TAG, "%s loop disabled", this->get_component_source());
|
||||
ESP_LOGVV(TAG, "%s loop disabled", LOG_STR_ARG(this->get_component_log_str()));
|
||||
this->set_component_state_(COMPONENT_STATE_LOOP_DONE);
|
||||
App.disable_component_loop_(this);
|
||||
}
|
||||
}
|
||||
void Component::enable_loop() {
|
||||
if ((this->component_state_ & COMPONENT_STATE_MASK) == COMPONENT_STATE_LOOP_DONE) {
|
||||
ESP_LOGVV(TAG, "%s loop enabled", this->get_component_source());
|
||||
ESP_LOGVV(TAG, "%s loop enabled", LOG_STR_ARG(this->get_component_log_str()));
|
||||
this->set_component_state_(COMPONENT_STATE_LOOP);
|
||||
App.enable_component_loop_(this);
|
||||
}
|
||||
@@ -239,7 +237,7 @@ void IRAM_ATTR HOT Component::enable_loop_soon_any_context() {
|
||||
}
|
||||
void Component::reset_to_construction_state() {
|
||||
if ((this->component_state_ & COMPONENT_STATE_MASK) == COMPONENT_STATE_FAILED) {
|
||||
ESP_LOGI(TAG, "%s is being reset to construction state", this->get_component_source());
|
||||
ESP_LOGI(TAG, "%s is being reset to construction state", LOG_STR_ARG(this->get_component_log_str()));
|
||||
this->set_component_state_(COMPONENT_STATE_CONSTRUCTION);
|
||||
// Clear error status when resetting
|
||||
this->status_clear_error();
|
||||
@@ -286,7 +284,7 @@ void Component::status_set_warning(const char *message) {
|
||||
return;
|
||||
this->component_state_ |= STATUS_LED_WARNING;
|
||||
App.app_state_ |= STATUS_LED_WARNING;
|
||||
ESP_LOGW(TAG, "%s set Warning flag: %s", this->get_component_source(),
|
||||
ESP_LOGW(TAG, "%s set Warning flag: %s", LOG_STR_ARG(this->get_component_log_str()),
|
||||
message ? message : LOG_STR_LITERAL("unspecified"));
|
||||
}
|
||||
void Component::status_set_warning(const LogString *message) {
|
||||
@@ -295,7 +293,7 @@ void Component::status_set_warning(const LogString *message) {
|
||||
return;
|
||||
this->component_state_ |= STATUS_LED_WARNING;
|
||||
App.app_state_ |= STATUS_LED_WARNING;
|
||||
ESP_LOGW(TAG, "%s set Warning flag: %s", this->get_component_source(),
|
||||
ESP_LOGW(TAG, "%s set Warning flag: %s", LOG_STR_ARG(this->get_component_log_str()),
|
||||
message ? LOG_STR_ARG(message) : LOG_STR_LITERAL("unspecified"));
|
||||
}
|
||||
void Component::status_set_error(const char *message) {
|
||||
@@ -303,7 +301,7 @@ void Component::status_set_error(const char *message) {
|
||||
return;
|
||||
this->component_state_ |= STATUS_LED_ERROR;
|
||||
App.app_state_ |= STATUS_LED_ERROR;
|
||||
ESP_LOGE(TAG, "%s set Error flag: %s", this->get_component_source(),
|
||||
ESP_LOGE(TAG, "%s set Error flag: %s", LOG_STR_ARG(this->get_component_log_str()),
|
||||
message ? message : LOG_STR_LITERAL("unspecified"));
|
||||
if (message != nullptr) {
|
||||
// Lazy allocate the error messages vector if needed
|
||||
@@ -325,13 +323,13 @@ void Component::status_clear_warning() {
|
||||
if ((this->component_state_ & STATUS_LED_WARNING) == 0)
|
||||
return;
|
||||
this->component_state_ &= ~STATUS_LED_WARNING;
|
||||
ESP_LOGW(TAG, "%s cleared Warning flag", this->get_component_source());
|
||||
ESP_LOGW(TAG, "%s cleared Warning flag", LOG_STR_ARG(this->get_component_log_str()));
|
||||
}
|
||||
void Component::status_clear_error() {
|
||||
if ((this->component_state_ & STATUS_LED_ERROR) == 0)
|
||||
return;
|
||||
this->component_state_ &= ~STATUS_LED_ERROR;
|
||||
ESP_LOGE(TAG, "%s cleared Error flag", this->get_component_source());
|
||||
ESP_LOGE(TAG, "%s cleared Error flag", LOG_STR_ARG(this->get_component_log_str()));
|
||||
}
|
||||
void Component::status_momentary_warning(const std::string &name, uint32_t length) {
|
||||
this->status_set_warning();
|
||||
@@ -342,6 +340,18 @@ void Component::status_momentary_error(const std::string &name, uint32_t length)
|
||||
this->set_timeout(name, length, [this]() { this->status_clear_error(); });
|
||||
}
|
||||
void Component::dump_config() {}
|
||||
|
||||
// Function implementation of LOG_UPDATE_INTERVAL macro to reduce code size
|
||||
void log_update_interval(const char *tag, PollingComponent *component) {
|
||||
uint32_t update_interval = component->get_update_interval();
|
||||
if (update_interval == SCHEDULER_DONT_RUN) {
|
||||
ESP_LOGCONFIG(tag, " Update Interval: never");
|
||||
} else if (update_interval < 100) {
|
||||
ESP_LOGCONFIG(tag, " Update Interval: %.3fs", update_interval / 1000.0f);
|
||||
} else {
|
||||
ESP_LOGCONFIG(tag, " Update Interval: %.1fs", update_interval / 1000.0f);
|
||||
}
|
||||
}
|
||||
float Component::get_actual_setup_priority() const {
|
||||
// Check if there's an override in the global vector
|
||||
if (setup_priority_overrides) {
|
||||
@@ -430,8 +440,9 @@ uint32_t WarnIfComponentBlockingGuard::finish() {
|
||||
should_warn = blocking_time > WARN_IF_BLOCKING_OVER_MS;
|
||||
}
|
||||
if (should_warn) {
|
||||
const char *src = component_ == nullptr ? "<null>" : component_->get_component_source();
|
||||
ESP_LOGW(TAG, "%s took a long time for an operation (%" PRIu32 " ms)", src, blocking_time);
|
||||
ESP_LOGW(TAG, "%s took a long time for an operation (%" PRIu32 " ms)",
|
||||
component_ == nullptr ? LOG_STR_LITERAL("<null>") : LOG_STR_ARG(component_->get_component_log_str()),
|
||||
blocking_time);
|
||||
ESP_LOGW(TAG, "Components should block for at most 30 ms");
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <functional>
|
||||
#include <string>
|
||||
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/optional.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -47,14 +48,13 @@ extern const float LATE;
|
||||
|
||||
static const uint32_t SCHEDULER_DONT_RUN = 4294967295UL;
|
||||
|
||||
#define LOG_UPDATE_INTERVAL(this) \
|
||||
if (this->get_update_interval() == SCHEDULER_DONT_RUN) { \
|
||||
ESP_LOGCONFIG(TAG, " Update Interval: never"); \
|
||||
} else if (this->get_update_interval() < 100) { \
|
||||
ESP_LOGCONFIG(TAG, " Update Interval: %.3fs", this->get_update_interval() / 1000.0f); \
|
||||
} else { \
|
||||
ESP_LOGCONFIG(TAG, " Update Interval: %.1fs", this->get_update_interval() / 1000.0f); \
|
||||
}
|
||||
// Forward declaration
|
||||
class PollingComponent;
|
||||
|
||||
// Function declaration for LOG_UPDATE_INTERVAL
|
||||
void log_update_interval(const char *tag, PollingComponent *component);
|
||||
|
||||
#define LOG_UPDATE_INTERVAL(this) log_update_interval(TAG, this)
|
||||
|
||||
extern const uint8_t COMPONENT_STATE_MASK;
|
||||
extern const uint8_t COMPONENT_STATE_CONSTRUCTION;
|
||||
@@ -224,12 +224,12 @@ class Component {
|
||||
*
|
||||
* This is set by the ESPHome core, and should not be called manually.
|
||||
*/
|
||||
void set_component_source(const char *source) { component_source_ = source; }
|
||||
/** Get the integration where this component was declared as a string.
|
||||
void set_component_source(const LogString *source) { component_source_ = source; }
|
||||
/** Get the integration where this component was declared as a LogString for logging.
|
||||
*
|
||||
* Returns "<unknown>" if source not set
|
||||
* Returns LOG_STR("<unknown>") if source not set
|
||||
*/
|
||||
const char *get_component_source() const;
|
||||
const LogString *get_component_log_str() const;
|
||||
|
||||
bool should_warn_of_blocking(uint32_t blocking_time);
|
||||
|
||||
@@ -409,7 +409,7 @@ class Component {
|
||||
bool cancel_defer(const std::string &name); // NOLINT
|
||||
|
||||
// Ordered for optimal packing on 32-bit systems
|
||||
const char *component_source_{nullptr};
|
||||
const LogString *component_source_{nullptr};
|
||||
uint16_t warn_if_blocking_over_{WARN_IF_BLOCKING_OVER_MS}; ///< Warn if blocked for this many ms (max 65.5s)
|
||||
/// State of this component - each bit has a purpose:
|
||||
/// Bits 0-2: Component state (0x00=CONSTRUCTION, 0x01=SETUP, 0x02=LOOP, 0x03=FAILED, 0x04=LOOP_DONE)
|
||||
|
||||
@@ -373,8 +373,10 @@ int8_t step_to_accuracy_decimals(float step) {
|
||||
return str.length() - dot_pos - 1;
|
||||
}
|
||||
|
||||
// Store BASE64 characters as array - automatically placed in flash/ROM on embedded platforms
|
||||
static const char BASE64_CHARS[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
// Use C-style string constant to store in ROM instead of RAM (saves 24 bytes)
|
||||
static constexpr const char *BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
"abcdefghijklmnopqrstuvwxyz"
|
||||
"0123456789+/";
|
||||
|
||||
// Helper function to find the index of a base64 character in the lookup table.
|
||||
// Returns the character's position (0-63) if found, or 0 if not found.
|
||||
@@ -384,8 +386,8 @@ static const char BASE64_CHARS[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqr
|
||||
// stops processing at the first invalid character due to the is_base64() check in its
|
||||
// while loop condition, making this edge case harmless in practice.
|
||||
static inline uint8_t base64_find_char(char c) {
|
||||
const void *ptr = memchr(BASE64_CHARS, c, sizeof(BASE64_CHARS));
|
||||
return ptr ? (static_cast<const char *>(ptr) - BASE64_CHARS) : 0;
|
||||
const char *pos = strchr(BASE64_CHARS, c);
|
||||
return pos ? (pos - BASE64_CHARS) : 0;
|
||||
}
|
||||
|
||||
static inline bool is_base64(char c) { return (isalnum(c) || (c == '+') || (c == '/')); }
|
||||
|
||||
@@ -78,9 +78,13 @@ size_t RingBuffer::write(const void *data, size_t len) {
|
||||
return this->write_without_replacement(data, len, 0);
|
||||
}
|
||||
|
||||
size_t RingBuffer::write_without_replacement(const void *data, size_t len, TickType_t ticks_to_wait) {
|
||||
size_t RingBuffer::write_without_replacement(const void *data, size_t len, TickType_t ticks_to_wait,
|
||||
bool write_partial) {
|
||||
if (!xRingbufferSend(this->handle_, data, len, ticks_to_wait)) {
|
||||
// Couldn't fit all the data, so only write what will fit
|
||||
if (!write_partial) {
|
||||
return 0; // Not enough space available and not allowed to write partial data
|
||||
}
|
||||
// Couldn't fit all the data, write what will fit
|
||||
size_t free = std::min(this->free(), len);
|
||||
if (xRingbufferSend(this->handle_, data, free, 0)) {
|
||||
return free;
|
||||
|
||||
@@ -50,7 +50,8 @@ class RingBuffer {
|
||||
* @param ticks_to_wait Maximum number of FreeRTOS ticks to wait (default: 0)
|
||||
* @return Number of bytes written
|
||||
*/
|
||||
size_t write_without_replacement(const void *data, size_t len, TickType_t ticks_to_wait = 0);
|
||||
size_t write_without_replacement(const void *data, size_t len, TickType_t ticks_to_wait = 0,
|
||||
bool write_partial = true);
|
||||
|
||||
/**
|
||||
* @brief Returns the number of available bytes in the ring buffer.
|
||||
|
||||
@@ -14,7 +14,19 @@ namespace esphome {
|
||||
|
||||
static const char *const TAG = "scheduler";
|
||||
|
||||
static const uint32_t MAX_LOGICALLY_DELETED_ITEMS = 10;
|
||||
// Memory pool configuration constants
|
||||
// Pool size of 5 matches typical usage patterns (2-4 active timers)
|
||||
// - Minimal memory overhead (~250 bytes on ESP32)
|
||||
// - Sufficient for most configs with a couple sensors/components
|
||||
// - Still prevents heap fragmentation and allocation stalls
|
||||
// - Complex setups with many timers will just allocate beyond the pool
|
||||
// See https://github.com/esphome/backlog/issues/52
|
||||
static constexpr size_t MAX_POOL_SIZE = 5;
|
||||
|
||||
// Maximum number of logically deleted (cancelled) items before forcing cleanup.
|
||||
// Set to 5 to match the pool size - when we have as many cancelled items as our
|
||||
// pool can hold, it's time to clean up and recycle them.
|
||||
static constexpr uint32_t MAX_LOGICALLY_DELETED_ITEMS = 5;
|
||||
// Half the 32-bit range - used to detect rollovers vs normal time progression
|
||||
static constexpr uint32_t HALF_MAX_UINT32 = std::numeric_limits<uint32_t>::max() / 2;
|
||||
// max delay to start an interval sequence
|
||||
@@ -79,8 +91,28 @@ void HOT Scheduler::set_timer_common_(Component *component, SchedulerItem::Type
|
||||
return;
|
||||
}
|
||||
|
||||
// Get fresh timestamp BEFORE taking lock - millis_64_ may need to acquire lock itself
|
||||
const uint64_t now = this->millis_64_(millis());
|
||||
|
||||
// Take lock early to protect scheduler_item_pool_ access
|
||||
LockGuard guard{this->lock_};
|
||||
|
||||
// Create and populate the scheduler item
|
||||
auto item = make_unique<SchedulerItem>();
|
||||
std::unique_ptr<SchedulerItem> item;
|
||||
if (!this->scheduler_item_pool_.empty()) {
|
||||
// Reuse from pool
|
||||
item = std::move(this->scheduler_item_pool_.back());
|
||||
this->scheduler_item_pool_.pop_back();
|
||||
#ifdef ESPHOME_DEBUG_SCHEDULER
|
||||
ESP_LOGD(TAG, "Reused item from pool (pool size now: %zu)", this->scheduler_item_pool_.size());
|
||||
#endif
|
||||
} else {
|
||||
// Allocate new if pool is empty
|
||||
item = make_unique<SchedulerItem>();
|
||||
#ifdef ESPHOME_DEBUG_SCHEDULER
|
||||
ESP_LOGD(TAG, "Allocated new item (pool empty)");
|
||||
#endif
|
||||
}
|
||||
item->component = component;
|
||||
item->set_name(name_cstr, !is_static_string);
|
||||
item->type = type;
|
||||
@@ -99,7 +131,6 @@ void HOT Scheduler::set_timer_common_(Component *component, SchedulerItem::Type
|
||||
// Single-core platforms don't need thread-safe defer handling
|
||||
if (delay == 0 && type == SchedulerItem::TIMEOUT) {
|
||||
// Put in defer queue for guaranteed FIFO execution
|
||||
LockGuard guard{this->lock_};
|
||||
if (!skip_cancel) {
|
||||
this->cancel_item_locked_(component, name_cstr, type);
|
||||
}
|
||||
@@ -108,21 +139,18 @@ void HOT Scheduler::set_timer_common_(Component *component, SchedulerItem::Type
|
||||
}
|
||||
#endif /* not ESPHOME_THREAD_SINGLE */
|
||||
|
||||
// Get fresh timestamp for new timer/interval - ensures accurate scheduling
|
||||
const auto now = this->millis_64_(millis()); // Fresh millis() call
|
||||
|
||||
// Type-specific setup
|
||||
if (type == SchedulerItem::INTERVAL) {
|
||||
item->interval = delay;
|
||||
// first execution happens immediately after a random smallish offset
|
||||
// Calculate random offset (0 to min(interval/2, 5s))
|
||||
uint32_t offset = (uint32_t) (std::min(delay / 2, MAX_INTERVAL_DELAY) * random_float());
|
||||
item->next_execution_ = now + offset;
|
||||
item->set_next_execution(now + offset);
|
||||
ESP_LOGV(TAG, "Scheduler interval for %s is %" PRIu32 "ms, offset %" PRIu32 "ms", name_cstr ? name_cstr : "", delay,
|
||||
offset);
|
||||
} else {
|
||||
item->interval = 0;
|
||||
item->next_execution_ = now + delay;
|
||||
item->set_next_execution(now + delay);
|
||||
}
|
||||
|
||||
#ifdef ESPHOME_DEBUG_SCHEDULER
|
||||
@@ -134,16 +162,15 @@ void HOT Scheduler::set_timer_common_(Component *component, SchedulerItem::Type
|
||||
// Debug logging
|
||||
const char *type_str = (type == SchedulerItem::TIMEOUT) ? "timeout" : "interval";
|
||||
if (type == SchedulerItem::TIMEOUT) {
|
||||
ESP_LOGD(TAG, "set_%s(name='%s/%s', %s=%" PRIu32 ")", type_str, item->get_source(),
|
||||
ESP_LOGD(TAG, "set_%s(name='%s/%s', %s=%" PRIu32 ")", type_str, LOG_STR_ARG(item->get_source()),
|
||||
name_cstr ? name_cstr : "(null)", type_str, delay);
|
||||
} else {
|
||||
ESP_LOGD(TAG, "set_%s(name='%s/%s', %s=%" PRIu32 ", offset=%" PRIu32 ")", type_str, item->get_source(),
|
||||
name_cstr ? name_cstr : "(null)", type_str, delay, static_cast<uint32_t>(item->next_execution_ - now));
|
||||
ESP_LOGD(TAG, "set_%s(name='%s/%s', %s=%" PRIu32 ", offset=%" PRIu32 ")", type_str, LOG_STR_ARG(item->get_source()),
|
||||
name_cstr ? name_cstr : "(null)", type_str, delay,
|
||||
static_cast<uint32_t>(item->get_next_execution() - now));
|
||||
}
|
||||
#endif /* ESPHOME_DEBUG_SCHEDULER */
|
||||
|
||||
LockGuard guard{this->lock_};
|
||||
|
||||
// For retries, check if there's a cancelled timeout first
|
||||
if (is_retry && name_cstr != nullptr && type == SchedulerItem::TIMEOUT &&
|
||||
(has_cancelled_timeout_in_container_(this->items_, component, name_cstr, /* match_retry= */ true) ||
|
||||
@@ -285,9 +312,10 @@ optional<uint32_t> HOT Scheduler::next_schedule_in(uint32_t now) {
|
||||
auto &item = this->items_[0];
|
||||
// Convert the fresh timestamp from caller (usually Application::loop()) to 64-bit
|
||||
const auto now_64 = this->millis_64_(now); // 'now' from parameter - fresh from caller
|
||||
if (item->next_execution_ < now_64)
|
||||
const uint64_t next_exec = item->get_next_execution();
|
||||
if (next_exec < now_64)
|
||||
return 0;
|
||||
return item->next_execution_ - now_64;
|
||||
return next_exec - now_64;
|
||||
}
|
||||
void HOT Scheduler::call(uint32_t now) {
|
||||
#ifndef ESPHOME_THREAD_SINGLE
|
||||
@@ -319,6 +347,8 @@ void HOT Scheduler::call(uint32_t now) {
|
||||
if (!this->should_skip_item_(item.get())) {
|
||||
this->execute_item_(item.get(), now);
|
||||
}
|
||||
// Recycle the defer item after execution
|
||||
this->recycle_item_(std::move(item));
|
||||
}
|
||||
#endif /* not ESPHOME_THREAD_SINGLE */
|
||||
|
||||
@@ -326,6 +356,9 @@ void HOT Scheduler::call(uint32_t now) {
|
||||
const auto now_64 = this->millis_64_(now); // 'now' from parameter - fresh from Application::loop()
|
||||
this->process_to_add();
|
||||
|
||||
// Track if any items were added to to_add_ during this call (intervals or from callbacks)
|
||||
bool has_added_items = false;
|
||||
|
||||
#ifdef ESPHOME_DEBUG_SCHEDULER
|
||||
static uint64_t last_print = 0;
|
||||
|
||||
@@ -335,11 +368,11 @@ void HOT Scheduler::call(uint32_t now) {
|
||||
#ifdef ESPHOME_THREAD_MULTI_ATOMICS
|
||||
const auto last_dbg = this->last_millis_.load(std::memory_order_relaxed);
|
||||
const auto major_dbg = this->millis_major_.load(std::memory_order_relaxed);
|
||||
ESP_LOGD(TAG, "Items: count=%zu, now=%" PRIu64 " (%" PRIu16 ", %" PRIu32 ")", this->items_.size(), now_64,
|
||||
major_dbg, last_dbg);
|
||||
ESP_LOGD(TAG, "Items: count=%zu, pool=%zu, now=%" PRIu64 " (%" PRIu16 ", %" PRIu32 ")", this->items_.size(),
|
||||
this->scheduler_item_pool_.size(), now_64, major_dbg, last_dbg);
|
||||
#else /* not ESPHOME_THREAD_MULTI_ATOMICS */
|
||||
ESP_LOGD(TAG, "Items: count=%zu, now=%" PRIu64 " (%" PRIu16 ", %" PRIu32 ")", this->items_.size(), now_64,
|
||||
this->millis_major_, this->last_millis_);
|
||||
ESP_LOGD(TAG, "Items: count=%zu, pool=%zu, now=%" PRIu64 " (%" PRIu16 ", %" PRIu32 ")", this->items_.size(),
|
||||
this->scheduler_item_pool_.size(), now_64, this->millis_major_, this->last_millis_);
|
||||
#endif /* else ESPHOME_THREAD_MULTI_ATOMICS */
|
||||
// Cleanup before debug output
|
||||
this->cleanup_();
|
||||
@@ -352,9 +385,10 @@ void HOT Scheduler::call(uint32_t now) {
|
||||
}
|
||||
|
||||
const char *name = item->get_name();
|
||||
ESP_LOGD(TAG, " %s '%s/%s' interval=%" PRIu32 " next_execution in %" PRIu64 "ms at %" PRIu64,
|
||||
item->get_type_str(), item->get_source(), name ? name : "(null)", item->interval,
|
||||
item->next_execution_ - now_64, item->next_execution_);
|
||||
bool is_cancelled = is_item_removed_(item.get());
|
||||
ESP_LOGD(TAG, " %s '%s/%s' interval=%" PRIu32 " next_execution in %" PRIu64 "ms at %" PRIu64 "%s",
|
||||
item->get_type_str(), LOG_STR_ARG(item->get_source()), name ? name : "(null)", item->interval,
|
||||
item->get_next_execution() - now_64, item->get_next_execution(), is_cancelled ? " [CANCELLED]" : "");
|
||||
|
||||
old_items.push_back(std::move(item));
|
||||
}
|
||||
@@ -369,8 +403,13 @@ void HOT Scheduler::call(uint32_t now) {
|
||||
}
|
||||
#endif /* ESPHOME_DEBUG_SCHEDULER */
|
||||
|
||||
// If we have too many items to remove
|
||||
if (this->to_remove_ > MAX_LOGICALLY_DELETED_ITEMS) {
|
||||
// Cleanup removed items before processing
|
||||
// First try to clean items from the top of the heap (fast path)
|
||||
this->cleanup_();
|
||||
|
||||
// If we still have too many cancelled items, do a full cleanup
|
||||
// This only happens if cancelled items are stuck in the middle/bottom of the heap
|
||||
if (this->to_remove_ >= MAX_LOGICALLY_DELETED_ITEMS) {
|
||||
// We hold the lock for the entire cleanup operation because:
|
||||
// 1. We're rebuilding the entire items_ list, so we need exclusive access throughout
|
||||
// 2. Other threads must see either the old state or the new state, not intermediate states
|
||||
@@ -380,10 +419,13 @@ void HOT Scheduler::call(uint32_t now) {
|
||||
|
||||
std::vector<std::unique_ptr<SchedulerItem>> valid_items;
|
||||
|
||||
// Move all non-removed items to valid_items
|
||||
// Move all non-removed items to valid_items, recycle removed ones
|
||||
for (auto &item : this->items_) {
|
||||
if (!item->remove) {
|
||||
if (!is_item_removed_(item.get())) {
|
||||
valid_items.push_back(std::move(item));
|
||||
} else {
|
||||
// Recycle removed items
|
||||
this->recycle_item_(std::move(item));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -393,92 +435,92 @@ void HOT Scheduler::call(uint32_t now) {
|
||||
std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
|
||||
this->to_remove_ = 0;
|
||||
}
|
||||
|
||||
// Cleanup removed items before processing
|
||||
this->cleanup_();
|
||||
while (!this->items_.empty()) {
|
||||
// use scoping to indicate visibility of `item` variable
|
||||
{
|
||||
// Don't copy-by value yet
|
||||
auto &item = this->items_[0];
|
||||
if (item->next_execution_ > now_64) {
|
||||
// Not reached timeout yet, done for this call
|
||||
break;
|
||||
}
|
||||
// Don't run on failed components
|
||||
if (item->component != nullptr && item->component->is_failed()) {
|
||||
LockGuard guard{this->lock_};
|
||||
this->pop_raw_();
|
||||
continue;
|
||||
}
|
||||
// Don't copy-by value yet
|
||||
auto &item = this->items_[0];
|
||||
if (item->get_next_execution() > now_64) {
|
||||
// Not reached timeout yet, done for this call
|
||||
break;
|
||||
}
|
||||
// Don't run on failed components
|
||||
if (item->component != nullptr && item->component->is_failed()) {
|
||||
LockGuard guard{this->lock_};
|
||||
this->pop_raw_();
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if item is marked for removal
|
||||
// This handles two cases:
|
||||
// 1. Item was marked for removal after cleanup_() but before we got here
|
||||
// 2. Item is marked for removal but wasn't at the front of the heap during cleanup_()
|
||||
// Check if item is marked for removal
|
||||
// This handles two cases:
|
||||
// 1. Item was marked for removal after cleanup_() but before we got here
|
||||
// 2. Item is marked for removal but wasn't at the front of the heap during cleanup_()
|
||||
#ifdef ESPHOME_THREAD_MULTI_NO_ATOMICS
|
||||
// Multi-threaded platforms without atomics: must take lock to safely read remove flag
|
||||
{
|
||||
LockGuard guard{this->lock_};
|
||||
if (is_item_removed_(item.get())) {
|
||||
this->pop_raw_();
|
||||
this->to_remove_--;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
#else
|
||||
// Single-threaded or multi-threaded with atomics: can check without lock
|
||||
// Multi-threaded platforms without atomics: must take lock to safely read remove flag
|
||||
{
|
||||
LockGuard guard{this->lock_};
|
||||
if (is_item_removed_(item.get())) {
|
||||
LockGuard guard{this->lock_};
|
||||
this->pop_raw_();
|
||||
this->to_remove_--;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
#else
|
||||
// Single-threaded or multi-threaded with atomics: can check without lock
|
||||
if (is_item_removed_(item.get())) {
|
||||
LockGuard guard{this->lock_};
|
||||
this->pop_raw_();
|
||||
this->to_remove_--;
|
||||
continue;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef ESPHOME_DEBUG_SCHEDULER
|
||||
const char *item_name = item->get_name();
|
||||
ESP_LOGV(TAG, "Running %s '%s/%s' with interval=%" PRIu32 " next_execution=%" PRIu64 " (now=%" PRIu64 ")",
|
||||
item->get_type_str(), item->get_source(), item_name ? item_name : "(null)", item->interval,
|
||||
item->next_execution_, now_64);
|
||||
const char *item_name = item->get_name();
|
||||
ESP_LOGV(TAG, "Running %s '%s/%s' with interval=%" PRIu32 " next_execution=%" PRIu64 " (now=%" PRIu64 ")",
|
||||
item->get_type_str(), LOG_STR_ARG(item->get_source()), item_name ? item_name : "(null)", item->interval,
|
||||
item->get_next_execution(), now_64);
|
||||
#endif /* ESPHOME_DEBUG_SCHEDULER */
|
||||
|
||||
// Warning: During callback(), a lot of stuff can happen, including:
|
||||
// - timeouts/intervals get added, potentially invalidating vector pointers
|
||||
// - timeouts/intervals get cancelled
|
||||
this->execute_item_(item.get(), now);
|
||||
// Warning: During callback(), a lot of stuff can happen, including:
|
||||
// - timeouts/intervals get added, potentially invalidating vector pointers
|
||||
// - timeouts/intervals get cancelled
|
||||
this->execute_item_(item.get(), now);
|
||||
|
||||
LockGuard guard{this->lock_};
|
||||
|
||||
auto executed_item = std::move(this->items_[0]);
|
||||
// Only pop after function call, this ensures we were reachable
|
||||
// during the function call and know if we were cancelled.
|
||||
this->pop_raw_();
|
||||
|
||||
if (executed_item->remove) {
|
||||
// We were removed/cancelled in the function call, stop
|
||||
this->to_remove_--;
|
||||
continue;
|
||||
}
|
||||
|
||||
{
|
||||
LockGuard guard{this->lock_};
|
||||
|
||||
// new scope, item from before might have been moved in the vector
|
||||
auto item = std::move(this->items_[0]);
|
||||
// Only pop after function call, this ensures we were reachable
|
||||
// during the function call and know if we were cancelled.
|
||||
this->pop_raw_();
|
||||
|
||||
if (item->remove) {
|
||||
// We were removed/cancelled in the function call, stop
|
||||
this->to_remove_--;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (item->type == SchedulerItem::INTERVAL) {
|
||||
item->next_execution_ = now_64 + item->interval;
|
||||
// Add new item directly to to_add_
|
||||
// since we have the lock held
|
||||
this->to_add_.push_back(std::move(item));
|
||||
}
|
||||
if (executed_item->type == SchedulerItem::INTERVAL) {
|
||||
executed_item->set_next_execution(now_64 + executed_item->interval);
|
||||
// Add new item directly to to_add_
|
||||
// since we have the lock held
|
||||
this->to_add_.push_back(std::move(executed_item));
|
||||
} else {
|
||||
// Timeout completed - recycle it
|
||||
this->recycle_item_(std::move(executed_item));
|
||||
}
|
||||
|
||||
has_added_items |= !this->to_add_.empty();
|
||||
}
|
||||
|
||||
this->process_to_add();
|
||||
if (has_added_items) {
|
||||
this->process_to_add();
|
||||
}
|
||||
}
|
||||
void HOT Scheduler::process_to_add() {
|
||||
LockGuard guard{this->lock_};
|
||||
for (auto &it : this->to_add_) {
|
||||
if (it->remove) {
|
||||
if (is_item_removed_(it.get())) {
|
||||
// Recycle cancelled items
|
||||
this->recycle_item_(std::move(it));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -518,6 +560,10 @@ size_t HOT Scheduler::cleanup_() {
|
||||
}
|
||||
void HOT Scheduler::pop_raw_() {
|
||||
std::pop_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
|
||||
|
||||
// Instead of destroying, recycle the item
|
||||
this->recycle_item_(std::move(this->items_.back()));
|
||||
|
||||
this->items_.pop_back();
|
||||
}
|
||||
|
||||
@@ -552,7 +598,7 @@ bool HOT Scheduler::cancel_item_locked_(Component *component, const char *name_c
|
||||
|
||||
// Check all containers for matching items
|
||||
#ifndef ESPHOME_THREAD_SINGLE
|
||||
// Only check defer queue for timeouts (intervals never go there)
|
||||
// Mark items in defer queue as cancelled (they'll be skipped when processed)
|
||||
if (type == SchedulerItem::TIMEOUT) {
|
||||
for (auto &item : this->defer_queue_) {
|
||||
if (this->matches_item_(item, component, name_cstr, type, match_retry)) {
|
||||
@@ -564,11 +610,22 @@ bool HOT Scheduler::cancel_item_locked_(Component *component, const char *name_c
|
||||
#endif /* not ESPHOME_THREAD_SINGLE */
|
||||
|
||||
// Cancel items in the main heap
|
||||
for (auto &item : this->items_) {
|
||||
if (this->matches_item_(item, component, name_cstr, type, match_retry)) {
|
||||
this->mark_item_removed_(item.get());
|
||||
// Special case: if the last item in the heap matches, we can remove it immediately
|
||||
// (removing the last element doesn't break heap structure)
|
||||
if (!this->items_.empty()) {
|
||||
auto &last_item = this->items_.back();
|
||||
if (this->matches_item_(last_item, component, name_cstr, type, match_retry)) {
|
||||
this->recycle_item_(std::move(this->items_.back()));
|
||||
this->items_.pop_back();
|
||||
total_cancelled++;
|
||||
this->to_remove_++; // Track removals for heap items
|
||||
}
|
||||
// For other items in heap, we can only mark for removal (can't remove from middle of heap)
|
||||
for (auto &item : this->items_) {
|
||||
if (this->matches_item_(item, component, name_cstr, type, match_retry)) {
|
||||
this->mark_item_removed_(item.get());
|
||||
total_cancelled++;
|
||||
this->to_remove_++; // Track removals for heap items
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -744,7 +801,31 @@ uint64_t Scheduler::millis_64_(uint32_t now) {
|
||||
|
||||
bool HOT Scheduler::SchedulerItem::cmp(const std::unique_ptr<SchedulerItem> &a,
|
||||
const std::unique_ptr<SchedulerItem> &b) {
|
||||
return a->next_execution_ > b->next_execution_;
|
||||
// High bits are almost always equal (change only on 32-bit rollover ~49 days)
|
||||
// Optimize for common case: check low bits first when high bits are equal
|
||||
return (a->next_execution_high_ == b->next_execution_high_) ? (a->next_execution_low_ > b->next_execution_low_)
|
||||
: (a->next_execution_high_ > b->next_execution_high_);
|
||||
}
|
||||
|
||||
void Scheduler::recycle_item_(std::unique_ptr<SchedulerItem> item) {
|
||||
if (!item)
|
||||
return;
|
||||
|
||||
if (this->scheduler_item_pool_.size() < MAX_POOL_SIZE) {
|
||||
// Clear callback to release captured resources
|
||||
item->callback = nullptr;
|
||||
// Clear dynamic name if any
|
||||
item->clear_dynamic_name();
|
||||
this->scheduler_item_pool_.push_back(std::move(item));
|
||||
#ifdef ESPHOME_DEBUG_SCHEDULER
|
||||
ESP_LOGD(TAG, "Recycled item to pool (pool size now: %zu)", this->scheduler_item_pool_.size());
|
||||
#endif
|
||||
} else {
|
||||
#ifdef ESPHOME_DEBUG_SCHEDULER
|
||||
ESP_LOGD(TAG, "Pool full (size: %zu), deleting item", this->scheduler_item_pool_.size());
|
||||
#endif
|
||||
}
|
||||
// else: unique_ptr will delete the item when it goes out of scope
|
||||
}
|
||||
|
||||
} // namespace esphome
|
||||
|
||||
@@ -88,19 +88,22 @@ class Scheduler {
|
||||
struct SchedulerItem {
|
||||
// Ordered by size to minimize padding
|
||||
Component *component;
|
||||
uint32_t interval;
|
||||
// 64-bit time to handle millis() rollover. The scheduler combines the 32-bit millis()
|
||||
// with a 16-bit rollover counter to create a 64-bit time that won't roll over for
|
||||
// billions of years. This ensures correct scheduling even when devices run for months.
|
||||
uint64_t next_execution_;
|
||||
|
||||
// Optimized name storage using tagged union
|
||||
union {
|
||||
const char *static_name; // For string literals (no allocation)
|
||||
char *dynamic_name; // For allocated strings
|
||||
} name_;
|
||||
|
||||
uint32_t interval;
|
||||
// Split time to handle millis() rollover. The scheduler combines the 32-bit millis()
|
||||
// with a 16-bit rollover counter to create a 48-bit time space (using 32+16 bits).
|
||||
// This is intentionally limited to 48 bits, not stored as a full 64-bit value.
|
||||
// With 49.7 days per 32-bit rollover, the 16-bit counter supports
|
||||
// 49.7 days × 65536 = ~8900 years. This ensures correct scheduling
|
||||
// even when devices run for months. Split into two fields for better memory
|
||||
// alignment on 32-bit systems.
|
||||
uint32_t next_execution_low_; // Lower 32 bits of execution time (millis value)
|
||||
std::function<void()> callback;
|
||||
uint16_t next_execution_high_; // Upper 16 bits (millis_major counter)
|
||||
|
||||
#ifdef ESPHOME_THREAD_MULTI_ATOMICS
|
||||
// Multi-threaded with atomics: use atomic for lock-free access
|
||||
@@ -126,7 +129,8 @@ class Scheduler {
|
||||
SchedulerItem()
|
||||
: component(nullptr),
|
||||
interval(0),
|
||||
next_execution_(0),
|
||||
next_execution_low_(0),
|
||||
next_execution_high_(0),
|
||||
#ifdef ESPHOME_THREAD_MULTI_ATOMICS
|
||||
// remove is initialized in the member declaration as std::atomic<bool>{false}
|
||||
type(TIMEOUT),
|
||||
@@ -142,11 +146,7 @@ class Scheduler {
|
||||
}
|
||||
|
||||
// Destructor to clean up dynamic names
|
||||
~SchedulerItem() {
|
||||
if (name_is_dynamic) {
|
||||
delete[] name_.dynamic_name;
|
||||
}
|
||||
}
|
||||
~SchedulerItem() { clear_dynamic_name(); }
|
||||
|
||||
// Delete copy operations to prevent accidental copies
|
||||
SchedulerItem(const SchedulerItem &) = delete;
|
||||
@@ -159,13 +159,19 @@ class Scheduler {
|
||||
// Helper to get the name regardless of storage type
|
||||
const char *get_name() const { return name_is_dynamic ? name_.dynamic_name : name_.static_name; }
|
||||
|
||||
// Helper to clear dynamic name if allocated
|
||||
void clear_dynamic_name() {
|
||||
if (name_is_dynamic && name_.dynamic_name) {
|
||||
delete[] name_.dynamic_name;
|
||||
name_.dynamic_name = nullptr;
|
||||
name_is_dynamic = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to set name with proper ownership
|
||||
void set_name(const char *name, bool make_copy = false) {
|
||||
// Clean up old dynamic name if any
|
||||
if (name_is_dynamic && name_.dynamic_name) {
|
||||
delete[] name_.dynamic_name;
|
||||
name_is_dynamic = false;
|
||||
}
|
||||
clear_dynamic_name();
|
||||
|
||||
if (!name) {
|
||||
// nullptr case - no name provided
|
||||
@@ -183,8 +189,22 @@ class Scheduler {
|
||||
}
|
||||
|
||||
static bool cmp(const std::unique_ptr<SchedulerItem> &a, const std::unique_ptr<SchedulerItem> &b);
|
||||
const char *get_type_str() const { return (type == TIMEOUT) ? "timeout" : "interval"; }
|
||||
const char *get_source() const { return component ? component->get_component_source() : "unknown"; }
|
||||
|
||||
// Note: We use 48 bits total (32 + 16), stored in a 64-bit value for API compatibility.
|
||||
// The upper 16 bits of the 64-bit value are always zero, which is fine since
|
||||
// millis_major_ is also 16 bits and they must match.
|
||||
constexpr uint64_t get_next_execution() const {
|
||||
return (static_cast<uint64_t>(next_execution_high_) << 32) | next_execution_low_;
|
||||
}
|
||||
|
||||
constexpr void set_next_execution(uint64_t value) {
|
||||
next_execution_low_ = static_cast<uint32_t>(value);
|
||||
// Cast to uint16_t intentionally truncates to lower 16 bits of the upper 32 bits.
|
||||
// This is correct because millis_major_ that creates these values is also 16 bits.
|
||||
next_execution_high_ = static_cast<uint16_t>(value >> 32);
|
||||
}
|
||||
constexpr const char *get_type_str() const { return (type == TIMEOUT) ? "timeout" : "interval"; }
|
||||
const LogString *get_source() const { return component ? component->get_component_log_str() : LOG_STR("unknown"); }
|
||||
};
|
||||
|
||||
// Common implementation for both timeout and interval
|
||||
@@ -214,6 +234,15 @@ class Scheduler {
|
||||
// Common implementation for cancel operations
|
||||
bool cancel_item_(Component *component, bool is_static_string, const void *name_ptr, SchedulerItem::Type type);
|
||||
|
||||
// Helper to check if two scheduler item names match
|
||||
inline bool HOT names_match_(const char *name1, const char *name2) const {
|
||||
// Check pointer equality first (common for static strings), then string contents
|
||||
// The core ESPHome codebase uses static strings (const char*) for component names,
|
||||
// making pointer comparison effective. The std::string overloads exist only for
|
||||
// compatibility with external components but are rarely used in practice.
|
||||
return (name1 != nullptr && name2 != nullptr) && ((name1 == name2) || (strcmp(name1, name2) == 0));
|
||||
}
|
||||
|
||||
// Helper function to check if item matches criteria for cancellation
|
||||
inline bool HOT matches_item_(const std::unique_ptr<SchedulerItem> &item, Component *component, const char *name_cstr,
|
||||
SchedulerItem::Type type, bool match_retry, bool skip_removed = true) const {
|
||||
@@ -221,29 +250,20 @@ class Scheduler {
|
||||
(match_retry && !item->is_retry)) {
|
||||
return false;
|
||||
}
|
||||
const char *item_name = item->get_name();
|
||||
if (item_name == nullptr) {
|
||||
return false;
|
||||
}
|
||||
// Fast path: if pointers are equal
|
||||
// This is effective because the core ESPHome codebase uses static strings (const char*)
|
||||
// for component names. The std::string overloads exist only for compatibility with
|
||||
// external components, but are rarely used in practice.
|
||||
if (item_name == name_cstr) {
|
||||
return true;
|
||||
}
|
||||
// Slow path: compare string contents
|
||||
return strcmp(name_cstr, item_name) == 0;
|
||||
return this->names_match_(item->get_name(), name_cstr);
|
||||
}
|
||||
|
||||
// Helper to execute a scheduler item
|
||||
void execute_item_(SchedulerItem *item, uint32_t now);
|
||||
|
||||
// Helper to check if item should be skipped
|
||||
bool should_skip_item_(const SchedulerItem *item) const {
|
||||
return item->remove || (item->component != nullptr && item->component->is_failed());
|
||||
bool should_skip_item_(SchedulerItem *item) const {
|
||||
return is_item_removed_(item) || (item->component != nullptr && item->component->is_failed());
|
||||
}
|
||||
|
||||
// Helper to recycle a SchedulerItem
|
||||
void recycle_item_(std::unique_ptr<SchedulerItem> item);
|
||||
|
||||
// Helper to check if item is marked for removal (platform-specific)
|
||||
// Returns true if item should be skipped, handles platform-specific synchronization
|
||||
// For ESPHOME_THREAD_MULTI_NO_ATOMICS platforms, the caller must hold the scheduler lock before calling this
|
||||
@@ -280,8 +300,9 @@ class Scheduler {
|
||||
bool has_cancelled_timeout_in_container_(const Container &container, Component *component, const char *name_cstr,
|
||||
bool match_retry) const {
|
||||
for (const auto &item : container) {
|
||||
if (item->remove && this->matches_item_(item, component, name_cstr, SchedulerItem::TIMEOUT, match_retry,
|
||||
/* skip_removed= */ false)) {
|
||||
if (is_item_removed_(item.get()) &&
|
||||
this->matches_item_(item, component, name_cstr, SchedulerItem::TIMEOUT, match_retry,
|
||||
/* skip_removed= */ false)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -297,6 +318,16 @@ class Scheduler {
|
||||
#endif /* ESPHOME_THREAD_SINGLE */
|
||||
uint32_t to_remove_{0};
|
||||
|
||||
// Memory pool for recycling SchedulerItem objects to reduce heap churn.
|
||||
// Design decisions:
|
||||
// - std::vector is used instead of a fixed array because many systems only need 1-2 scheduler items
|
||||
// - The vector grows dynamically up to MAX_POOL_SIZE (5) only when needed, saving memory on simple setups
|
||||
// - Pool size of 5 matches typical usage (2-4 timers) while keeping memory overhead low (~250 bytes on ESP32)
|
||||
// - The pool significantly reduces heap fragmentation which is critical because heap allocation/deallocation
|
||||
// can stall the entire system, causing timing issues and dropped events for any components that need
|
||||
// to synchronize between tasks (see https://github.com/esphome/backlog/issues/52)
|
||||
std::vector<std::unique_ptr<SchedulerItem>> scheduler_item_pool_;
|
||||
|
||||
#ifdef ESPHOME_THREAD_MULTI_ATOMICS
|
||||
/*
|
||||
* Multi-threaded platforms with atomic support: last_millis_ needs atomic for lock-free updates
|
||||
|
||||
@@ -253,6 +253,19 @@ class StringLiteral(Literal):
|
||||
return cpp_string_escape(self.string)
|
||||
|
||||
|
||||
class LogStringLiteral(Literal):
|
||||
"""A string literal that uses LOG_STR() macro for flash storage on ESP8266."""
|
||||
|
||||
__slots__ = ("string",)
|
||||
|
||||
def __init__(self, string: str) -> None:
|
||||
super().__init__()
|
||||
self.string = string
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"LOG_STR({cpp_string_escape(self.string)})"
|
||||
|
||||
|
||||
class IntLiteral(Literal):
|
||||
__slots__ = ("i",)
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ from esphome.const import (
|
||||
)
|
||||
from esphome.core import CORE, ID, coroutine
|
||||
from esphome.coroutine import FakeAwaitable
|
||||
from esphome.cpp_generator import add, get_variable
|
||||
from esphome.cpp_generator import LogStringLiteral, add, get_variable
|
||||
from esphome.cpp_types import App
|
||||
from esphome.types import ConfigFragmentType, ConfigType
|
||||
from esphome.util import Registry, RegistryEntry
|
||||
@@ -76,7 +76,7 @@ async def register_component(var, config):
|
||||
"Error while finding name of component, please report this", exc_info=e
|
||||
)
|
||||
if name is not None:
|
||||
add(var.set_component_source(name))
|
||||
add(var.set_component_source(LogStringLiteral(name)))
|
||||
|
||||
add(App.register_component(var))
|
||||
return var
|
||||
|
||||
@@ -308,8 +308,12 @@ def perform_ota(
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def run_ota_impl_(remote_host, remote_port, password, filename):
|
||||
def run_ota_impl_(
|
||||
remote_host: str | list[str], remote_port: int, password: str, filename: str
|
||||
) -> tuple[int, str | None]:
|
||||
# Handle both single host and list of hosts
|
||||
try:
|
||||
# Resolve all hosts at once for parallel DNS resolution
|
||||
res = resolve_ip_address(remote_host, remote_port)
|
||||
except EsphomeError as err:
|
||||
_LOGGER.error(
|
||||
@@ -340,19 +344,22 @@ def run_ota_impl_(remote_host, remote_port, password, filename):
|
||||
perform_ota(sock, password, file_handle, filename)
|
||||
except OTAError as err:
|
||||
_LOGGER.error(str(err))
|
||||
return 1
|
||||
return 1, None
|
||||
finally:
|
||||
sock.close()
|
||||
|
||||
return 0
|
||||
# Successfully uploaded to sa[0]
|
||||
return 0, sa[0]
|
||||
|
||||
_LOGGER.error("Connection failed.")
|
||||
return 1
|
||||
return 1, None
|
||||
|
||||
|
||||
def run_ota(remote_host, remote_port, password, filename):
|
||||
def run_ota(
|
||||
remote_host: str | list[str], remote_port: int, password: str, filename: str
|
||||
) -> tuple[int, str | None]:
|
||||
try:
|
||||
return run_ota_impl_(remote_host, remote_port, password, filename)
|
||||
except OTAError as err:
|
||||
_LOGGER.error(err)
|
||||
return 1
|
||||
return 1, None
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import codecs
|
||||
from contextlib import suppress
|
||||
import ipaddress
|
||||
@@ -11,6 +13,18 @@ from urllib.parse import urlparse
|
||||
|
||||
from esphome.const import __version__ as ESPHOME_VERSION
|
||||
|
||||
# Type aliases for socket address information
|
||||
AddrInfo = tuple[
|
||||
int, # family (AF_INET, AF_INET6, etc.)
|
||||
int, # type (SOCK_STREAM, SOCK_DGRAM, etc.)
|
||||
int, # proto (IPPROTO_TCP, etc.)
|
||||
str, # canonname
|
||||
tuple[str, int] | tuple[str, int, int, int], # sockaddr (IPv4 or IPv6)
|
||||
]
|
||||
IPv4SockAddr = tuple[str, int] # (host, port)
|
||||
IPv6SockAddr = tuple[str, int, int, int] # (host, port, flowinfo, scope_id)
|
||||
SockAddr = IPv4SockAddr | IPv6SockAddr
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
IS_MACOS = platform.system() == "Darwin"
|
||||
@@ -147,32 +161,7 @@ def is_ip_address(host):
|
||||
return False
|
||||
|
||||
|
||||
def _resolve_with_zeroconf(host):
|
||||
from esphome.core import EsphomeError
|
||||
from esphome.zeroconf import EsphomeZeroconf
|
||||
|
||||
try:
|
||||
zc = EsphomeZeroconf()
|
||||
except Exception as err:
|
||||
raise EsphomeError(
|
||||
"Cannot start mDNS sockets, is this a docker container without "
|
||||
"host network mode?"
|
||||
) from err
|
||||
try:
|
||||
info = zc.resolve_host(f"{host}.")
|
||||
except Exception as err:
|
||||
raise EsphomeError(f"Error resolving mDNS hostname: {err}") from err
|
||||
finally:
|
||||
zc.close()
|
||||
if info is None:
|
||||
raise EsphomeError(
|
||||
"Error resolving address with mDNS: Did not respond. "
|
||||
"Maybe the device is offline."
|
||||
)
|
||||
return info
|
||||
|
||||
|
||||
def addr_preference_(res):
|
||||
def addr_preference_(res: AddrInfo) -> int:
|
||||
# Trivial alternative to RFC6724 sorting. Put sane IPv6 first, then
|
||||
# Legacy IP, then IPv6 link-local addresses without an actual link.
|
||||
sa = res[4]
|
||||
@@ -184,66 +173,70 @@ def addr_preference_(res):
|
||||
return 1
|
||||
|
||||
|
||||
def resolve_ip_address(host, port):
|
||||
def resolve_ip_address(host: str | list[str], port: int) -> list[AddrInfo]:
|
||||
import socket
|
||||
|
||||
from esphome.core import EsphomeError
|
||||
|
||||
# There are five cases here. The host argument could be one of:
|
||||
# • a *list* of IP addresses discovered by MQTT,
|
||||
# • a single IP address specified by the user,
|
||||
# • a .local hostname to be resolved by mDNS,
|
||||
# • a normal hostname to be resolved in DNS, or
|
||||
# • A URL from which we should extract the hostname.
|
||||
#
|
||||
# In each of the first three cases, we end up with IP addresses in
|
||||
# string form which need to be converted to a 5-tuple to be used
|
||||
# for the socket connection attempt. The easiest way to construct
|
||||
# those is to pass the IP address string to getaddrinfo(). Which,
|
||||
# coincidentally, is how we do hostname lookups in the other cases
|
||||
# too. So first build a list which contains either IP addresses or
|
||||
# a single hostname, then call getaddrinfo() on each element of
|
||||
# that list.
|
||||
|
||||
errs = []
|
||||
hosts: list[str]
|
||||
if isinstance(host, list):
|
||||
addr_list = host
|
||||
elif is_ip_address(host):
|
||||
addr_list = [host]
|
||||
hosts = host
|
||||
else:
|
||||
url = urlparse(host)
|
||||
if url.scheme != "":
|
||||
host = url.hostname
|
||||
if not is_ip_address(host):
|
||||
url = urlparse(host)
|
||||
if url.scheme != "":
|
||||
host = url.hostname
|
||||
hosts = [host]
|
||||
|
||||
addr_list = []
|
||||
if host.endswith(".local"):
|
||||
res: list[AddrInfo] = []
|
||||
if all(is_ip_address(h) for h in hosts):
|
||||
# Fast path: all are IP addresses, use socket.getaddrinfo with AI_NUMERICHOST
|
||||
for addr in hosts:
|
||||
try:
|
||||
_LOGGER.info("Resolving IP address of %s in mDNS", host)
|
||||
addr_list = _resolve_with_zeroconf(host)
|
||||
except EsphomeError as err:
|
||||
errs.append(str(err))
|
||||
res += socket.getaddrinfo(
|
||||
addr, port, proto=socket.IPPROTO_TCP, flags=socket.AI_NUMERICHOST
|
||||
)
|
||||
except OSError:
|
||||
_LOGGER.debug("Failed to parse IP address '%s'", addr)
|
||||
# Sort by preference
|
||||
res.sort(key=addr_preference_)
|
||||
return res
|
||||
|
||||
# If not mDNS, or if mDNS failed, use normal DNS
|
||||
if not addr_list:
|
||||
addr_list = [host]
|
||||
from esphome.resolver import AsyncResolver
|
||||
|
||||
# Now we have a list containing either IP addresses or a hostname
|
||||
res = []
|
||||
for addr in addr_list:
|
||||
if not is_ip_address(addr):
|
||||
_LOGGER.info("Resolving IP address of %s", host)
|
||||
try:
|
||||
r = socket.getaddrinfo(addr, port, proto=socket.IPPROTO_TCP)
|
||||
except OSError as err:
|
||||
errs.append(str(err))
|
||||
raise EsphomeError(
|
||||
f"Error resolving IP address: {', '.join(errs)}"
|
||||
) from err
|
||||
resolver = AsyncResolver(hosts, port)
|
||||
addr_infos = resolver.resolve()
|
||||
# Convert aioesphomeapi AddrInfo to our format
|
||||
for addr_info in addr_infos:
|
||||
sockaddr = addr_info.sockaddr
|
||||
if addr_info.family == socket.AF_INET6:
|
||||
# IPv6
|
||||
sockaddr_tuple = (
|
||||
sockaddr.address,
|
||||
sockaddr.port,
|
||||
sockaddr.flowinfo,
|
||||
sockaddr.scope_id,
|
||||
)
|
||||
else:
|
||||
# IPv4
|
||||
sockaddr_tuple = (sockaddr.address, sockaddr.port)
|
||||
|
||||
res = res + r
|
||||
res.append(
|
||||
(
|
||||
addr_info.family,
|
||||
addr_info.type,
|
||||
addr_info.proto,
|
||||
"", # canonname
|
||||
sockaddr_tuple,
|
||||
)
|
||||
)
|
||||
|
||||
# Zeroconf tends to give us link-local IPv6 addresses without specifying
|
||||
# the link. Put those last in the list to be attempted.
|
||||
# Sort by preference
|
||||
res.sort(key=addr_preference_)
|
||||
return res
|
||||
|
||||
@@ -262,15 +255,7 @@ def sort_ip_addresses(address_list: list[str]) -> list[str]:
|
||||
|
||||
# First "resolve" all the IP addresses to getaddrinfo() tuples of the form
|
||||
# (family, type, proto, canonname, sockaddr)
|
||||
res: list[
|
||||
tuple[
|
||||
int,
|
||||
int,
|
||||
int,
|
||||
str | None,
|
||||
tuple[str, int] | tuple[str, int, int, int],
|
||||
]
|
||||
] = []
|
||||
res: list[AddrInfo] = []
|
||||
for addr in address_list:
|
||||
# This should always work as these are supposed to be IP addresses
|
||||
try:
|
||||
|
||||
67
esphome/resolver.py
Normal file
67
esphome/resolver.py
Normal file
@@ -0,0 +1,67 @@
|
||||
"""DNS resolver for ESPHome using aioesphomeapi."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
|
||||
from aioesphomeapi.core import ResolveAPIError, ResolveTimeoutAPIError
|
||||
import aioesphomeapi.host_resolver as hr
|
||||
|
||||
from esphome.core import EsphomeError
|
||||
|
||||
RESOLVE_TIMEOUT = 10.0 # seconds
|
||||
|
||||
|
||||
class AsyncResolver(threading.Thread):
|
||||
"""Resolver using aioesphomeapi that runs in a thread for faster results.
|
||||
|
||||
This resolver uses aioesphomeapi's async_resolve_host to handle DNS resolution,
|
||||
including proper .local domain fallback. Running in a thread allows us to get
|
||||
the result immediately without waiting for asyncio.run() to complete its
|
||||
cleanup cycle, which can take significant time.
|
||||
"""
|
||||
|
||||
def __init__(self, hosts: list[str], port: int) -> None:
|
||||
"""Initialize the resolver."""
|
||||
super().__init__(daemon=True)
|
||||
self.hosts = hosts
|
||||
self.port = port
|
||||
self.result: list[hr.AddrInfo] | None = None
|
||||
self.exception: Exception | None = None
|
||||
self.event = threading.Event()
|
||||
|
||||
async def _resolve(self) -> None:
|
||||
"""Resolve hostnames to IP addresses."""
|
||||
try:
|
||||
self.result = await hr.async_resolve_host(
|
||||
self.hosts, self.port, timeout=RESOLVE_TIMEOUT
|
||||
)
|
||||
except Exception as e: # pylint: disable=broad-except
|
||||
# We need to catch all exceptions to ensure the event is set
|
||||
# Otherwise the thread could hang forever
|
||||
self.exception = e
|
||||
finally:
|
||||
self.event.set()
|
||||
|
||||
def run(self) -> None:
|
||||
"""Run the DNS resolution."""
|
||||
asyncio.run(self._resolve())
|
||||
|
||||
def resolve(self) -> list[hr.AddrInfo]:
|
||||
"""Start the thread and wait for the result."""
|
||||
self.start()
|
||||
|
||||
if not self.event.wait(
|
||||
timeout=RESOLVE_TIMEOUT + 1.0
|
||||
): # Give it 1 second more than the resolver timeout
|
||||
raise EsphomeError("Timeout resolving IP address")
|
||||
|
||||
if exc := self.exception:
|
||||
if isinstance(exc, ResolveTimeoutAPIError):
|
||||
raise EsphomeError(f"Timeout resolving IP address: {exc}") from exc
|
||||
if isinstance(exc, ResolveAPIError):
|
||||
raise EsphomeError(f"Error resolving IP address: {exc}") from exc
|
||||
raise exc
|
||||
|
||||
return self.result
|
||||
@@ -272,12 +272,15 @@ class OrderedDict(collections.OrderedDict):
|
||||
return dict(self).__repr__()
|
||||
|
||||
|
||||
def list_yaml_files(folders: list[str]) -> list[str]:
|
||||
files = filter_yaml_files(
|
||||
[os.path.join(folder, p) for folder in folders for p in os.listdir(folder)]
|
||||
)
|
||||
files.sort()
|
||||
return files
|
||||
def list_yaml_files(configs: list[str]) -> list[str]:
|
||||
files: list[str] = []
|
||||
for config in configs:
|
||||
if os.path.isfile(config):
|
||||
files.append(config)
|
||||
else:
|
||||
files.extend(os.path.join(config, p) for p in os.listdir(config))
|
||||
files = filter_yaml_files(files)
|
||||
return sorted(files)
|
||||
|
||||
|
||||
def filter_yaml_files(files: list[str]) -> list[str]:
|
||||
|
||||
@@ -12,8 +12,8 @@ platformio==6.1.18 # When updating platformio, also update /docker/Dockerfile
|
||||
esptool==5.0.2
|
||||
click==8.1.7
|
||||
esphome-dashboard==20250904.0
|
||||
aioesphomeapi==40.0.1
|
||||
zeroconf==0.147.0
|
||||
aioesphomeapi==40.1.0
|
||||
zeroconf==0.147.2
|
||||
puremagic==1.30
|
||||
ruamel.yaml==0.18.15 # dashboard_import
|
||||
esphome-glyphsets==0.2.0
|
||||
|
||||
@@ -6,7 +6,7 @@ pre-commit
|
||||
|
||||
# Unit tests
|
||||
pytest==8.4.2
|
||||
pytest-cov==6.2.1
|
||||
pytest-cov==7.0.0
|
||||
pytest-mock==3.15.0
|
||||
pytest-asyncio==1.1.0
|
||||
pytest-xdist==3.8.0
|
||||
|
||||
@@ -82,7 +82,7 @@ for path in components_dir.iterdir():
|
||||
|
||||
|
||||
for path, owners in sorted(codeowners.items()):
|
||||
owners = sorted(set(owners))
|
||||
owners = sorted(set(owners), key=str.casefold)
|
||||
if not owners:
|
||||
continue
|
||||
for owner in owners:
|
||||
|
||||
1
tests/components/binary_sensor/test.nrf52-adafruit.yaml
Normal file
1
tests/components/binary_sensor/test.nrf52-adafruit.yaml
Normal file
@@ -0,0 +1 @@
|
||||
<<: !include common.yaml
|
||||
1
tests/components/binary_sensor/test.nrf52-mcumgr.yaml
Normal file
1
tests/components/binary_sensor/test.nrf52-mcumgr.yaml
Normal file
@@ -0,0 +1 @@
|
||||
<<: !include common.yaml
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user