1
0
mirror of https://github.com/esphome/esphome.git synced 2025-11-01 15:41:52 +00:00

Compare commits

...

89 Commits

Author SHA1 Message Date
Jesse Hills
d2df232706 Merge pull request #10763 from esphome/bump-2025.9.0
2025.9.0
2025-09-17 18:51:21 +12:00
Jesse Hills
404e679e66 Bump version to 2025.9.0 2025-09-17 11:02:12 +12:00
Jesse Hills
8d401ad05a Merge pull request #10761 from esphome/bump-2025.9.0b4
2025.9.0b4
2025-09-17 10:50:15 +12:00
Jesse Hills
e542816f7d Bump version to 2025.9.0b4 2025-09-17 09:22:54 +12:00
J. Nick Koston
12cadf0a04 [core] Fix clean build files to properly clear PlatformIO cache (#10754) 2025-09-17 09:22:54 +12:00
J. Nick Koston
adc3d3127d [wizard] Fix KeyError when running wizard with empty OTA password (#10753) 2025-09-17 09:22:54 +12:00
J. Nick Koston
61ab682099 Add additional coverage for util and writer (#10683) 2025-09-17 09:22:54 +12:00
Jesse Hills
c05b7cca5e Merge pull request #10752 from esphome/bump-2025.9.0b3
2025.9.0b3
2025-09-17 00:15:06 +12:00
Jesse Hills
6ac395da6d Bump version to 2025.9.0b3 2025-09-16 20:35:23 +12:00
jokujossai
54616ae1b4 [ade7880] fix channel a voltage registry (#10750) 2025-09-16 20:35:23 +12:00
jokujossai
e33dcda907 [mqtt] fix publish payload length when payload contains null characters (#10744) 2025-09-16 20:35:23 +12:00
J. Nick Koston
04c1b90e57 [ethernet] Conditionally compile PHY-specific code to reduce flash usage (#10747) 2025-09-16 20:35:23 +12:00
J. Nick Koston
ddb8fedef7 [dashboard] Fix archive handler to properly delete build folders using correct path (#10724) 2025-09-16 20:35:23 +12:00
J. Nick Koston
04f4f79cb4 [select] Use const references to avoid unnecessary vector copies (#10741) 2025-09-16 20:35:23 +12:00
J. Nick Koston
8890071360 Add additional test coverage ahead of Path conversion (#10700) 2025-09-16 20:35:23 +12:00
J. Nick Koston
4b3a997a8e Improve coverage for various core modules (#10663) 2025-09-16 20:35:23 +12:00
Jesse Hills
2a4ab6a811 Merge pull request #10725 from esphome/bump-2025.9.0b2
2025.9.0b2
2025-09-15 18:28:51 +12:00
Jesse Hills
971de64494 Bump version to 2025.9.0b2 2025-09-15 12:34:56 +12:00
J. Nick Koston
926fdcbecd [esp32_ble] Optimize BLE hex formatting to eliminate sprintf dependency (#10714)
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
2025-09-15 12:34:56 +12:00
J. Nick Koston
6b147312cd [wifi] Optimize WiFi MAC formatting to eliminate sprintf dependency (#10715)
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
2025-09-15 12:34:56 +12:00
J. Nick Koston
2d9152d9b9 [md5] Optimize MD5::get_hex() to eliminate sprintf dependency (#10710) 2025-09-15 12:34:56 +12:00
dependabot[bot]
24f9550ce5 Bump aioesphomeapi from 40.2.0 to 40.2.1 (#10721)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-09-15 12:34:56 +12:00
Big Mike
3427aaab8c ina2xx should be total increasing for energy sensor (#10711) 2025-09-15 12:34:56 +12:00
J. Nick Koston
4e17d14acc [scheduler] Fix timing accumulation in scheduler causing incorrect execution measurements (#10719) 2025-09-15 12:34:56 +12:00
J. Nick Koston
1750f02ef3 [api] Optimize HelloResponse server_info to reduce memory usage (#10701) 2025-09-15 12:34:56 +12:00
J. Nick Koston
ae158179bd [api] Revert unneeded GetTime bidirectional support added in #9790 (#10702) 2025-09-15 12:34:55 +12:00
J. Nick Koston
c601494779 [core] Optimize MAC address formatting to eliminate sprintf dependency (#10713) 2025-09-15 12:34:55 +12:00
J. Nick Koston
646f4e66be [ethernet] Fix permanent component failure from undocumented ESP_FAIL in IPv6 setup (#10708) 2025-09-15 12:34:55 +12:00
dependabot[bot]
5b5e5c213c Bump aioesphomeapi from 40.1.0 to 40.2.0 (#10703)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-09-15 12:34:55 +12:00
Markus
46235684b1 [core] fix upload to device via MQTT IP lookup (e.g. when mDNS is disable) (#10632)
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick+github@koston.org>
2025-09-15 12:34:55 +12:00
J. Nick Koston
5b702a1efa Add additional dashboard and main tests (#10688)
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-09-15 12:34:55 +12:00
J. Nick Koston
56e9fd2e38 [tests] Add upload_program and show_logs test coverage to prevent regressions (#10684) 2025-09-15 12:34:55 +12:00
J. Nick Koston
65f15a706f Add some more coverage for dashboard web_server (#10682) 2025-09-15 12:34:55 +12:00
J. Nick Koston
eee64cc3a6 Add comprehensive tests for choose_upload_log_host to prevent regressions (#10679)
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2025-09-15 12:34:55 +12:00
J. Nick Koston
f43fb3c3a3 [core] Add millisecond precision to logging timestamps (#10677) 2025-09-15 12:34:55 +12:00
rwrozelle
79b0025fe6 Openthread Fix Factory Reset (#9281)
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
2025-09-15 12:34:55 +12:00
Jesse Hills
c6a039a72f [adc] Fix FILTER_SOURCE_FILES location (#10673) 2025-09-15 12:34:54 +12:00
esphomebot
6f1fa094c2 Update webserver local assets to 20250910-110003 (#10668) 2025-09-15 12:34:54 +12:00
Jesse Hills
7a869a33f0 Merge pull request #10665 from esphome/bump-2025.9.0b1
2025.9.0b1
2025-09-11 07:24:33 +12:00
Keith Burzinski
56e85b3ef9 [thermostat] Rename timer enums to mitigate naming conflict (#10666) 2025-09-10 22:58:35 +12:00
Jesse Hills
2401f81be3 Bump version to 2025.9.0b1 2025-09-10 19:48:01 +12:00
Josip Šimun Kuči
52a7e26c6d [inkplate] Rename component and fix grayscale (#10200)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-09-10 18:46:58 +12:00
Jesse Hills
d729dc20a8 Merge branch 'release' into dev 2025-09-10 17:04:21 +12:00
Jesse Hills
d3b7a9687b Merge pull request #10664 from esphome/bump-2025.8.4
2025.8.4
2025-09-10 17:03:37 +12:00
Jesse Hills
9d7fc11108 Bump version to 2025.8.4 2025-09-10 13:56:50 +12:00
tomaszduda23
7969627d3e [light] add missing header (#10590) 2025-09-10 13:56:50 +12:00
Clyde Stubbs
82d2e367d4 [kmeteriso] Fix i2c call (#10618) 2025-09-10 13:56:50 +12:00
Keith Burzinski
972aa691e4 [sen5x] Fix initialization (#10603) 2025-09-10 13:56:50 +12:00
Daniel M
ac61b8f893 [bl0940] extend configuration options of bl0940 device (#8158)
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2025-09-10 13:50:49 +12:00
Keith Burzinski
d9f625e5c8 [thermostat] General clean-up, optimization, properly support "auto" mode (#10561)
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
2025-09-10 13:24:50 +12:00
Jonathan Swoboda
e218f16f0f Allow both files and directories to be passed to update-all (#10575)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2025-09-09 18:06:59 -05:00
J. Nick Koston
422d209786 [api] Add timezone support to GetTimeResponse for automatic timezone synchronization (#10661) 2025-09-09 15:54:50 -05:00
dependabot[bot]
e972e1f8c2 Bump aioesphomeapi from 40.0.2 to 40.1.0 (#10662)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-09-09 20:33:36 +00:00
dependabot[bot]
cfb90b7b18 Bump pytest-cov from 6.3.0 to 7.0.0 (#10660)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-09-09 15:15:53 -05:00
mrtoy-me
8976ea2436 [ms5611] remove delay in setup (#10658) 2025-09-10 07:31:06 +12:00
tomaszduda23
01ff09064d [nrf52] add more tests (#10591) 2025-09-10 07:29:49 +12:00
tomaszduda23
39212f0d7f allow to implement show_logs as external component (#10523) 2025-09-09 11:45:42 -05:00
Mischa Siekmann
8993f4e6b4 RingBuffer: Make partial writing optional (#10302) 2025-09-09 08:39:47 -05:00
J. Nick Koston
7adad0ee49 [core] Refactor insertion sort functions to eliminate code duplication (#10653) 2025-09-09 02:03:35 -05:00
J. Nick Koston
dd8815ec9d [core] Reduce flash usage by refactoring looping component partitioning (#10652) 2025-09-09 01:17:30 -05:00
Jesse Hills
59e62a1f44 Sort codeowners using case-insensitive (#10651)
Co-authored-by: J. Nick Koston <nick@koston.org>
2025-09-08 21:26:22 -05:00
Edward Firmo
f5f84fe825 [nextion] Increase delay before reboot to prevent TFT upload interruption (#10402) 2025-09-09 12:57:24 +12:00
Edward Firmo
90c2fdd565 [adc] Fix autorange negative coefficient bug causing incorrect voltage readings (#10549) 2025-09-09 12:56:18 +12:00
tomaszduda23
f6d69231e8 [light] add missing header (#10590) 2025-09-09 11:10:29 +12:00
J. Nick Koston
5cc0e21bc7 [core] Reduce unnecessary nesting in scheduler loop (#10644) 2025-09-09 09:04:07 +12:00
Thomas Rupprecht
703b592793 Add I2S Audio Port for ESP32-C5/C6/H2 (#10414) 2025-09-08 14:03:41 -04:00
J. Nick Koston
75c9430d91 [core] Fix serial upload regression from DNS resolution PR #10595 (#10648) 2025-09-08 10:41:03 -05:00
J. Nick Koston
e5bba00deb [esp32] Reduce GPIO memory usage by 50% through bit-packing (#10556) 2025-09-08 08:46:30 -05:00
J. Nick Koston
8d90f13e97 [core] Store component source strings in flash on ESP8266 (breaking change) (#10621) 2025-09-07 20:10:00 -05:00
J. Nick Koston
666e33e70b [api] Store plaintext error message in PROGMEM on ESP8266 (#10634) 2025-09-07 20:09:47 -05:00
Clyde Stubbs
7eaaa4e426 [mipi_rgb] Unified driver for MIPI RGB displays (#9892)
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
2025-09-08 12:56:34 +12:00
J. Nick Koston
166ad942ef [scheduler] Reduce SchedulerItem memory usage by 7.4% on 32-bit platforms (#10553)
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-09-07 18:51:07 -05:00
J. Nick Koston
0ff08bbc09 [mcp23016] Migrate to CachedGpioExpander to reduce I2C bus usage (#10581)
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-09-07 18:26:49 -05:00
J. Nick Koston
6e2bcabbc9 [sx1509] Migrate to CachedGpioExpander to reduce I2C bus usage (#10588)
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
2025-09-07 18:26:33 -05:00
J. Nick Koston
afa191ae41 [pcf8574] Migrate to CachedGpioExpander to reduce I2C bus usage (#10573)
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
2025-09-07 18:26:22 -05:00
J. Nick Koston
93da52c4d2 [pca9554] Migrate to CachedGpioExpander to reduce I2C bus usage (#10571)
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
2025-09-07 18:26:11 -05:00
J. Nick Koston
0cc0979674 [pca6416a] Migrate to CachedGpioExpander to reduce I2C bus usage (#10587) 2025-09-08 10:59:23 +12:00
Jesse Hills
629f1e94f1 [ota] Fix duplicate include and sort (#10643) 2025-09-07 22:58:41 +00:00
J. Nick Koston
8c28f346c7 [gpio_expander] Add intelligent pin type selection to CachedGpioExpander template (#10577) 2025-09-08 10:57:02 +12:00
dependabot[bot]
3cf36e2f94 Bump aioesphomeapi from 40.0.1 to 40.0.2 (#10641)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-09-07 17:32:21 -05:00
J. Nick Koston
1ac07c96b1 [esphome] Store OTA component log strings in flash on ESP8266 (#10570) 2025-09-08 10:30:39 +12:00
J. Nick Koston
91228c82e6 [esp8266][logger] Store LOG_LEVELS strings in PROGMEM to reduce RAM usage (#10569) 2025-09-08 10:29:45 +12:00
J. Nick Koston
28d16728d3 [core] Add memory pool to scheduler to reduce heap fragmentation (#10536) 2025-09-08 10:27:58 +12:00
dependabot[bot]
f24a182ba2 Bump pytest-cov from 6.2.1 to 6.3.0 (#10640)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-09-07 17:26:31 -05:00
dependabot[bot]
0065fe1516 Bump zeroconf from 0.147.0 to 0.147.2 (#10642)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-09-07 17:26:06 -05:00
J. Nick Koston
148fa698cc Fix DNS resolution inconsistency between logs and OTA operations (#10595)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2025-09-08 10:25:22 +12:00
J. Nick Koston
b25506b045 [core] Skip redundant process_to_add() call when no scheduler items added (#10630)
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-09-08 09:10:55 +12:00
J. Nick Koston
0c737fc4df [core] Convert LOG_UPDATE_INTERVAL macro to function to reduce flash usage (#10636) 2025-09-08 09:09:15 +12:00
davidmonro
a8b8507ffc Atm90e32/26 device class fixes (#10629) 2025-09-08 08:06:10 +12:00
189 changed files with 10980 additions and 1791 deletions

View File

@@ -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

View File

@@ -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.0
# 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

View File

@@ -15,9 +15,11 @@ import argcomplete
from esphome import const, writer, yaml_util
import esphome.codegen as cg
from esphome.components.mqtt import CONF_DISCOVER_IP
from esphome.config import iter_component_configs, read_config, strip_default_ids
from esphome.const import (
ALLOWED_NAME_CHARS,
CONF_API,
CONF_BAUD_RATE,
CONF_BROKER,
CONF_DEASSERT_RTS_DTR,
@@ -43,6 +45,7 @@ from esphome.const import (
SECRETS_FILES,
)
from esphome.core import CORE, EsphomeError, coroutine
from esphome.enum import StrEnum
from esphome.helpers import get_bool_env, indent, is_ip_address
from esphome.log import AnsiFore, color, setup_log
from esphome.types import ConfigType
@@ -106,13 +109,15 @@ def choose_prompt(options, purpose: str = None):
return options[opt - 1][1]
class Purpose(StrEnum):
UPLOADING = "uploading"
LOGGING = "logging"
def choose_upload_log_host(
default: list[str] | str | None,
check_default: str | None,
show_ota: bool,
show_mqtt: bool,
show_api: bool,
purpose: str | None = None,
purpose: Purpose,
) -> list[str]:
# Convert to list for uniform handling
defaults = [default] if isinstance(default, str) else default or []
@@ -132,13 +137,30 @@ def choose_upload_log_host(
]
resolved.append(choose_prompt(options, purpose=purpose))
elif device == "OTA":
if CORE.address and (
(show_ota and "ota" in CORE.config)
or (show_api and "api" in CORE.config)
# ensure IP adresses are used first
if is_ip_address(CORE.address) and (
(purpose == Purpose.LOGGING and has_api())
or (purpose == Purpose.UPLOADING and has_ota())
):
resolved.append(CORE.address)
elif show_mqtt and has_mqtt_logging():
resolved.append("MQTT")
if purpose == Purpose.LOGGING:
if has_api() and has_mqtt_ip_lookup():
resolved.append("MQTTIP")
if has_mqtt_logging():
resolved.append("MQTT")
if has_api() and has_non_ip_address():
resolved.append(CORE.address)
elif purpose == Purpose.UPLOADING:
if has_ota() and has_mqtt_ip_lookup():
resolved.append("MQTTIP")
if has_ota() and has_non_ip_address():
resolved.append(CORE.address)
else:
resolved.append(device)
if not resolved:
@@ -149,39 +171,111 @@ def choose_upload_log_host(
options = [
(f"{port.path} ({port.description})", port.path) for port in get_serial_ports()
]
if (show_ota and "ota" in CORE.config) or (show_api and "api" in CORE.config):
options.append((f"Over The Air ({CORE.address})", CORE.address))
if show_mqtt and has_mqtt_logging():
mqtt_config = CORE.config[CONF_MQTT]
options.append((f"MQTT ({mqtt_config[CONF_BROKER]})", "MQTT"))
if purpose == Purpose.LOGGING:
if has_mqtt_logging():
mqtt_config = CORE.config[CONF_MQTT]
options.append((f"MQTT ({mqtt_config[CONF_BROKER]})", "MQTT"))
if has_api():
if has_resolvable_address():
options.append((f"Over The Air ({CORE.address})", CORE.address))
if has_mqtt_ip_lookup():
options.append(("Over The Air (MQTT IP lookup)", "MQTTIP"))
elif purpose == Purpose.UPLOADING and has_ota():
if has_resolvable_address():
options.append((f"Over The Air ({CORE.address})", CORE.address))
if has_mqtt_ip_lookup():
options.append(("Over The Air (MQTT IP lookup)", "MQTTIP"))
if check_default is not None and check_default in [opt[1] for opt in options]:
return [check_default]
return [choose_prompt(options, purpose=purpose)]
def mqtt_logging_enabled(mqtt_config):
def has_mqtt_logging() -> bool:
"""Check if MQTT logging is available."""
if CONF_MQTT not in CORE.config:
return False
mqtt_config = CORE.config[CONF_MQTT]
# enabled by default
if CONF_LOG_TOPIC not in mqtt_config:
return True
log_topic = mqtt_config[CONF_LOG_TOPIC]
if log_topic is None:
return False
if CONF_TOPIC not in log_topic:
return False
return log_topic.get(CONF_LEVEL, None) != "NONE"
return log_topic[CONF_LEVEL] != "NONE"
def has_mqtt_logging() -> bool:
"""Check if MQTT logging is available."""
return (mqtt_config := CORE.config.get(CONF_MQTT)) and mqtt_logging_enabled(
mqtt_config
)
def has_mqtt() -> bool:
"""Check if MQTT is available."""
return CONF_MQTT in CORE.config
def has_api() -> bool:
"""Check if API is available."""
return CONF_API in CORE.config
def has_ota() -> bool:
"""Check if OTA is available."""
return CONF_OTA in CORE.config
def has_mqtt_ip_lookup() -> bool:
"""Check if MQTT is available and IP lookup is supported."""
if CONF_MQTT not in CORE.config:
return False
# Default Enabled
if CONF_DISCOVER_IP not in CORE.config[CONF_MQTT]:
return True
return CORE.config[CONF_MQTT][CONF_DISCOVER_IP]
def has_mdns() -> bool:
"""Check if MDNS is available."""
return CONF_MDNS not in CORE.config or not CORE.config[CONF_MDNS][CONF_DISABLED]
def has_non_ip_address() -> bool:
"""Check if CORE.address is set and is not an IP address."""
return CORE.address is not None and not is_ip_address(CORE.address)
def has_ip_address() -> bool:
"""Check if CORE.address is a valid IP address."""
return CORE.address is not None and is_ip_address(CORE.address)
def has_resolvable_address() -> bool:
"""Check if CORE.address is resolvable (via mDNS or is an IP address)."""
return has_mdns() or has_ip_address()
def mqtt_get_ip(config: ConfigType, username: str, password: str, client_id: str):
from esphome import mqtt
return mqtt.get_esphome_device_ip(config, username, password, client_id)
_PORT_TO_PORT_TYPE = {
"MQTT": "MQTT",
"MQTTIP": "MQTTIP",
}
def get_port_type(port: str) -> str:
if port.startswith("/") or port.startswith("COM"):
return "SERIAL"
if port == "MQTT":
return "MQTT"
return "NETWORK"
return _PORT_TO_PORT_TYPE.get(port, "NETWORK")
def run_miniterm(config: ConfigType, port: str, args) -> int:
@@ -226,7 +320,9 @@ def run_miniterm(config: ConfigType, port: str, args) -> int:
.replace(b"\n", b"")
.decode("utf8", "backslashreplace")
)
time_str = datetime.now().time().strftime("[%H:%M:%S]")
time_ = datetime.now()
nanoseconds = time_.microsecond // 1000
time_str = f"[{time_.hour:02}:{time_.minute:02}:{time_.second:02}.{nanoseconds:03}]"
safe_print(parser.parse_line(line, time_str))
backtrace_state = platformio_api.process_stacktrace(
@@ -396,27 +492,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,31 +531,23 @@ 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"))
and (
((config[CONF_MDNS][CONF_DISABLED]) and not is_ip_address(CORE.address))
or get_port_type(host) == "MQTT"
)
):
from esphome import mqtt
# MQTT address resolution
if get_port_type(host) in ("MQTT", "MQTTIP"):
devices = mqtt_get_ip(config, args.username, args.password, args.client_id)
host = 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!")
@@ -466,20 +556,28 @@ def show_logs(config: ConfigType, args: ArgsProtocol, devices: list[str]) -> int
if get_port_type(port) == "SERIAL":
check_permissions(port)
return run_miniterm(config, port, args)
if get_port_type(port) == "NETWORK" and "api" in config:
addresses_to_use = devices
if config[CONF_MDNS][CONF_DISABLED] and CONF_MQTT in config:
from esphome import mqtt
mqtt_address = mqtt.get_esphome_device_ip(
port_type = get_port_type(port)
# Check if we should use API for logging
if has_api():
addresses_to_use: list[str] | None = None
if port_type == "NETWORK" and (has_mdns() or is_ip_address(port)):
addresses_to_use = devices
elif port_type in ("NETWORK", "MQTT", "MQTTIP") and has_mqtt_ip_lookup():
# Only use MQTT IP lookup if the first condition didn't match
# (for MQTT/MQTTIP types, or for NETWORK when mdns/ip check fails)
addresses_to_use = mqtt_get_ip(
config, args.username, args.password, args.client_id
)[0]
addresses_to_use = [mqtt_address]
)
from esphome.components.api.client import run_logs
if addresses_to_use is not None:
from esphome.components.api.client import run_logs
return run_logs(config, addresses_to_use)
if get_port_type(port) in ("NETWORK", "MQTT") and "mqtt" in config:
return run_logs(config, addresses_to_use)
if port_type in ("NETWORK", "MQTT") and has_mqtt_logging():
from esphome import mqtt
return mqtt.show_logs(
@@ -545,23 +643,14 @@ def command_upload(args: ArgsProtocol, config: ConfigType) -> int | None:
devices = choose_upload_log_host(
default=args.device,
check_default=None,
show_ota=True,
show_mqtt=False,
show_api=False,
purpose="uploading",
purpose=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
@@ -579,10 +668,7 @@ def command_logs(args: ArgsProtocol, config: ConfigType) -> int | None:
devices = choose_upload_log_host(
default=args.device,
check_default=None,
show_ota=False,
show_mqtt=True,
show_api=True,
purpose="logging",
purpose=Purpose.LOGGING,
)
return show_logs(config, args, devices)
@@ -608,25 +694,14 @@ def command_run(args: ArgsProtocol, config: ConfigType) -> int | None:
devices = choose_upload_log_host(
default=args.device,
check_default=None,
show_ota=True,
show_mqtt=False,
show_api=True,
purpose="uploading",
purpose=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:
@@ -636,10 +711,7 @@ def command_run(args: ArgsProtocol, config: ConfigType) -> int | None:
devices = choose_upload_log_host(
default=successful_device,
check_default=successful_device,
show_ota=False,
show_mqtt=True,
show_api=True,
purpose="logging",
purpose=Purpose.LOGGING,
)
return show_logs(config, args, devices)

View File

@@ -11,15 +11,8 @@ from esphome.components.esp32.const import (
VARIANT_ESP32S2,
VARIANT_ESP32S3,
)
from esphome.config_helpers import filter_source_files_from_platform
import esphome.config_validation as cv
from esphome.const import (
CONF_ANALOG,
CONF_INPUT,
CONF_NUMBER,
PLATFORM_ESP8266,
PlatformFramework,
)
from esphome.const import CONF_ANALOG, CONF_INPUT, CONF_NUMBER, PLATFORM_ESP8266
from esphome.core import CORE
CODEOWNERS = ["@esphome/core"]
@@ -273,21 +266,3 @@ def validate_adc_pin(value):
)(value)
raise NotImplementedError
FILTER_SOURCE_FILES = filter_source_files_from_platform(
{
"adc_sensor_esp32.cpp": {
PlatformFramework.ESP32_ARDUINO,
PlatformFramework.ESP32_IDF,
},
"adc_sensor_esp8266.cpp": {PlatformFramework.ESP8266_ARDUINO},
"adc_sensor_rp2040.cpp": {PlatformFramework.RP2040_ARDUINO},
"adc_sensor_libretiny.cpp": {
PlatformFramework.BK72XX_ARDUINO,
PlatformFramework.RTL87XX_ARDUINO,
PlatformFramework.LN882X_ARDUINO,
},
"adc_sensor_zephyr.cpp": {PlatformFramework.NRF52_ZEPHYR},
}
)

View File

@@ -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

View File

@@ -9,6 +9,7 @@ from esphome.components.zephyr import (
zephyr_add_prj_conf,
zephyr_add_user,
)
from esphome.config_helpers import filter_source_files_from_platform
import esphome.config_validation as cv
from esphome.const import (
CONF_ATTENUATION,
@@ -20,6 +21,7 @@ from esphome.const import (
PLATFORM_NRF52,
STATE_CLASS_MEASUREMENT,
UNIT_VOLT,
PlatformFramework,
)
from esphome.core import CORE
@@ -174,3 +176,21 @@ async def to_code(config):
}};
"""
)
FILTER_SOURCE_FILES = filter_source_files_from_platform(
{
"adc_sensor_esp32.cpp": {
PlatformFramework.ESP32_ARDUINO,
PlatformFramework.ESP32_IDF,
},
"adc_sensor_esp8266.cpp": {PlatformFramework.ESP8266_ARDUINO},
"adc_sensor_rp2040.cpp": {PlatformFramework.RP2040_ARDUINO},
"adc_sensor_libretiny.cpp": {
PlatformFramework.BK72XX_ARDUINO,
PlatformFramework.RTL87XX_ARDUINO,
PlatformFramework.LN882X_ARDUINO,
},
"adc_sensor_zephyr.cpp": {PlatformFramework.NRF52_ZEPHYR},
}
)

View File

@@ -113,7 +113,7 @@ void ADE7880::update() {
if (this->channel_a_ != nullptr) {
auto *chan = this->channel_a_;
this->update_sensor_from_s24zp_register16_(chan->current, AIRMS, [](float val) { return val / 100000.0f; });
this->update_sensor_from_s24zp_register16_(chan->voltage, BVRMS, [](float val) { return val / 10000.0f; });
this->update_sensor_from_s24zp_register16_(chan->voltage, AVRMS, [](float val) { return val / 10000.0f; });
this->update_sensor_from_s24zp_register16_(chan->active_power, AWATT, [](float val) { return val / 100.0f; });
this->update_sensor_from_s24zp_register16_(chan->apparent_power, AVA, [](float val) { return val / 100.0f; });
this->update_sensor_from_s16_register16_(chan->power_factor, APF,

View File

@@ -27,9 +27,6 @@ service APIConnection {
rpc subscribe_logs (SubscribeLogsRequest) returns (void) {}
rpc subscribe_homeassistant_services (SubscribeHomeassistantServicesRequest) returns (void) {}
rpc subscribe_home_assistant_states (SubscribeHomeAssistantStatesRequest) returns (void) {}
rpc get_time (GetTimeRequest) returns (GetTimeResponse) {
option (needs_authentication) = false;
}
rpc execute_service (ExecuteServiceRequest) returns (void) {}
rpc noise_encryption_set_key (NoiseEncryptionSetKeyRequest) returns (NoiseEncryptionSetKeyResponse) {}
@@ -809,15 +806,16 @@ message HomeAssistantStateResponse {
// ==================== IMPORT TIME ====================
message GetTimeRequest {
option (id) = 36;
option (source) = SOURCE_BOTH;
option (source) = SOURCE_SERVER;
}
message GetTimeResponse {
option (id) = 37;
option (source) = SOURCE_BOTH;
option (source) = SOURCE_CLIENT;
option (no_delay) = true;
fixed32 epoch_seconds = 1;
string timezone = 2;
}
// ==================== USER-DEFINES SERVICES ====================

View File

@@ -42,6 +42,8 @@ static constexpr uint8_t MAX_PING_RETRIES = 60;
static constexpr uint16_t PING_RETRY_INTERVAL = 1000;
static constexpr uint32_t KEEPALIVE_DISCONNECT_TIMEOUT = (KEEPALIVE_TIMEOUT_MS * 5) / 2;
static constexpr auto ESPHOME_VERSION_REF = StringRef::from_lit(ESPHOME_VERSION);
static const char *const TAG = "api.connection";
#ifdef USE_CAMERA
static const int CAMERA_STOP_STREAM = 5000;
@@ -1070,17 +1072,17 @@ 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
bool APIConnection::send_get_time_response(const GetTimeRequest &msg) {
GetTimeResponse resp;
resp.epoch_seconds = ::time(nullptr);
return this->send_message(resp, GetTimeResponse::MESSAGE_TYPE);
}
#ifdef USE_BLUETOOTH_PROXY
void APIConnection::subscribe_bluetooth_le_advertisements(const SubscribeBluetoothLEAdvertisementsRequest &msg) {
bluetooth_proxy::global_bluetooth_proxy->subscribe_api_connection(this, msg.flags);
@@ -1370,9 +1372,8 @@ bool APIConnection::send_hello_response(const HelloRequest &msg) {
HelloResponse resp;
resp.api_version_major = 1;
resp.api_version_minor = 12;
// Temporary string for concatenation - will be valid during send_message call
std::string server_info = App.get_name() + " (esphome v" ESPHOME_VERSION ")";
resp.set_server_info(StringRef(server_info));
// Send only the version string - the client only logs this for debugging and doesn't use it otherwise
resp.set_server_info(ESPHOME_VERSION_REF);
resp.set_name(StringRef(App.get_name()));
#ifdef USE_API_PASSWORD
@@ -1419,8 +1420,6 @@ bool APIConnection::send_device_info_response(const DeviceInfoRequest &msg) {
std::string mac_address = get_mac_address_pretty();
resp.set_mac_address(StringRef(mac_address));
// Compile-time StringRef constants
static constexpr auto ESPHOME_VERSION_REF = StringRef::from_lit(ESPHOME_VERSION);
resp.set_esphome_version(ESPHOME_VERSION_REF);
resp.set_compilation_time(App.get_compilation_time_ref());

View File

@@ -219,7 +219,6 @@ class APIConnection final : public APIServerConnection {
#ifdef USE_API_HOMEASSISTANT_STATES
void subscribe_home_assistant_states(const SubscribeHomeAssistantStatesRequest &msg) override;
#endif
bool send_get_time_response(const GetTimeRequest &msg) override;
#ifdef USE_API_SERVICES
void execute_service(const ExecuteServiceRequest &msg) override;
#endif

View File

@@ -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;
}

View File

@@ -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,6 @@ 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); }
#ifdef USE_API_SERVICES
void ListEntitiesServicesArgument::encode(ProtoWriteBuffer buffer) const {
buffer.encode_string(1, this->name_ref_);

View File

@@ -1174,19 +1174,19 @@ 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};
void encode(ProtoWriteBuffer buffer) const override;
void calculate_size(ProtoSize &size) const override;
std::string timezone{};
#ifdef HAS_PROTO_MESSAGE_DUMP
void dump_to(std::string &out) const override;
#endif
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 {

View File

@@ -1110,7 +1110,11 @@ 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);
dump_field(out, "timezone", this->timezone);
}
#ifdef USE_API_SERVICES
void ListEntitiesServicesArgument::dump_to(std::string &out) const {
MessageDumpHelper helper(out, "ListEntitiesServicesArgument");

View File

@@ -160,15 +160,6 @@ void APIServerConnectionBase::read_message(uint32_t msg_size, uint32_t msg_type,
break;
}
#endif
case GetTimeRequest::MESSAGE_TYPE: {
GetTimeRequest msg;
// Empty message: no decode needed
#ifdef HAS_PROTO_MESSAGE_DUMP
ESP_LOGVV(TAG, "on_get_time_request: %s", msg.dump().c_str());
#endif
this->on_get_time_request(msg);
break;
}
case GetTimeResponse::MESSAGE_TYPE: {
GetTimeResponse msg;
msg.decode(msg_data, msg_size);
@@ -656,11 +647,6 @@ void APIServerConnection::on_subscribe_home_assistant_states_request(const Subsc
}
}
#endif
void APIServerConnection::on_get_time_request(const GetTimeRequest &msg) {
if (this->check_connection_setup_() && !this->send_get_time_response(msg)) {
this->on_fatal_error();
}
}
#ifdef USE_API_SERVICES
void APIServerConnection::on_execute_service_request(const ExecuteServiceRequest &msg) {
if (this->check_authenticated_()) {

View File

@@ -71,7 +71,7 @@ class APIServerConnectionBase : public ProtoService {
#ifdef USE_API_HOMEASSISTANT_STATES
virtual void on_home_assistant_state_response(const HomeAssistantStateResponse &value){};
#endif
virtual void on_get_time_request(const GetTimeRequest &value){};
virtual void on_get_time_response(const GetTimeResponse &value){};
#ifdef USE_API_SERVICES
@@ -226,7 +226,6 @@ class APIServerConnection : public APIServerConnectionBase {
#ifdef USE_API_HOMEASSISTANT_STATES
virtual void subscribe_home_assistant_states(const SubscribeHomeAssistantStatesRequest &msg) = 0;
#endif
virtual bool send_get_time_response(const GetTimeRequest &msg) = 0;
#ifdef USE_API_SERVICES
virtual void execute_service(const ExecuteServiceRequest &msg) = 0;
#endif
@@ -348,7 +347,6 @@ class APIServerConnection : public APIServerConnectionBase {
#ifdef USE_API_HOMEASSISTANT_STATES
void on_subscribe_home_assistant_states_request(const SubscribeHomeAssistantStatesRequest &msg) override;
#endif
void on_get_time_request(const GetTimeRequest &msg) override;
#ifdef USE_API_SERVICES
void on_execute_service_request(const ExecuteServiceRequest &msg) override;
#endif

View File

@@ -62,9 +62,11 @@ async def async_run_logs(config: dict[str, Any], addresses: list[str]) -> None:
time_ = datetime.now()
message: bytes = msg.message
text = message.decode("utf8", "backslashreplace")
for parsed_msg in parse_log_message(
text, f"[{time_.hour:02}:{time_.minute:02}:{time_.second:02}]"
):
nanoseconds = time_.microsecond // 1000
timestamp = (
f"[{time_.hour:02}:{time_.minute:02}:{time_.second:02}.{nanoseconds:03}]"
)
for parsed_msg in parse_log_message(text, timestamp):
print(parsed_msg.replace("\033", "\\033") if dashboard else parsed_msg)
stop = await async_run(cli, on_log, name=name)

View File

@@ -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(

View File

@@ -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(

View File

@@ -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());

View File

@@ -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")

View File

@@ -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

View File

@@ -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

View 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])

View File

@@ -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

View 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

View 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))

View 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

View 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

View File

@@ -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)))

View File

@@ -130,7 +130,9 @@ class BluetoothProxy final : public esp32_ble_tracker::ESPBTDeviceListener, publ
std::string get_bluetooth_mac_address_pretty() {
const uint8_t *mac = esp_bt_dev_get_address();
return str_snprintf("%02X:%02X:%02X:%02X:%02X:%02X", 17, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
char buf[18];
format_mac_addr_upper(mac, buf);
return std::string(buf);
}
protected:

View File

@@ -7,103 +7,83 @@ namespace esphome {
namespace captive_portal {
const uint8_t INDEX_GZ[] PROGMEM = {
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xdd, 0x58, 0x6d, 0x6f, 0xdb, 0x38, 0x12, 0xfe, 0xde,
0x5f, 0x31, 0xa7, 0x36, 0x6b, 0x6b, 0x1b, 0x51, 0x22, 0xe5, 0xb7, 0xd8, 0x92, 0x16, 0x69, 0xae, 0x8b, 0x5d, 0xa0,
0xdd, 0x2d, 0x90, 0x6c, 0xef, 0x43, 0x51, 0x20, 0xb4, 0x34, 0xb2, 0xd8, 0x48, 0xa4, 0x4e, 0xa4, 0x5f, 0x52, 0xc3,
0xf7, 0xdb, 0x0f, 0x94, 0x6c, 0xc7, 0xe9, 0x35, 0x87, 0xeb, 0xe2, 0x0e, 0x87, 0xdd, 0x18, 0x21, 0x86, 0xe4, 0xcc,
0x70, 0xe6, 0xf1, 0x0c, 0x67, 0xcc, 0xe8, 0x2f, 0x99, 0x4a, 0xcd, 0x7d, 0x8d, 0x50, 0x98, 0xaa, 0x4c, 0x22, 0x3b,
0x42, 0xc9, 0xe5, 0x22, 0x46, 0x99, 0x44, 0x05, 0xf2, 0x2c, 0x89, 0x2a, 0x34, 0x1c, 0xd2, 0x82, 0x37, 0x1a, 0x4d,
0xfc, 0xdb, 0xcd, 0x8f, 0x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, 0x22,
0xa7, 0x18, 0x06, 0x7a, 0xcd, 0x05, 0x8c, 0x61, 0x8c, 0x82, 0x25, 0x3a, 0x79, 0x75, 0xb2, 0xf6, 0xc4, 0xaf, 0x68,
0xfc, 0xda, 0xd1, 0xf8, 0xe9, 0xa3, 0xe1, 0xa6, 0xfb, 0x1f, 0x53, 0x58, 0x46, 0xb2, 0xf9, 0x0a, 0x00, 0x00};
} // namespace captive_portal
} // namespace esphome

View File

@@ -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_)

View File

@@ -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);

View File

@@ -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

View File

@@ -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;
};

View File

@@ -7,6 +7,7 @@
#include <cstdio>
#include <cinttypes>
#include "esphome/core/log.h"
#include "esphome/core/helpers.h"
namespace esphome::esp32_ble {
@@ -169,22 +170,42 @@ bool ESPBTUUID::operator==(const ESPBTUUID &uuid) const {
}
esp_bt_uuid_t ESPBTUUID::get_uuid() const { return this->uuid_; }
std::string ESPBTUUID::to_string() const {
char buf[40]; // Enough for 128-bit UUID with dashes
char *pos = buf;
switch (this->uuid_.len) {
case ESP_UUID_LEN_16:
return str_snprintf("0x%02X%02X", 6, this->uuid_.uuid.uuid16 >> 8, this->uuid_.uuid.uuid16 & 0xff);
*pos++ = '0';
*pos++ = 'x';
*pos++ = format_hex_pretty_char(this->uuid_.uuid.uuid16 >> 12);
*pos++ = format_hex_pretty_char((this->uuid_.uuid.uuid16 >> 8) & 0x0F);
*pos++ = format_hex_pretty_char((this->uuid_.uuid.uuid16 >> 4) & 0x0F);
*pos++ = format_hex_pretty_char(this->uuid_.uuid.uuid16 & 0x0F);
*pos = '\0';
return std::string(buf);
case ESP_UUID_LEN_32:
return str_snprintf("0x%02" PRIX32 "%02" PRIX32 "%02" PRIX32 "%02" PRIX32, 10, (this->uuid_.uuid.uuid32 >> 24),
(this->uuid_.uuid.uuid32 >> 16 & 0xff), (this->uuid_.uuid.uuid32 >> 8 & 0xff),
this->uuid_.uuid.uuid32 & 0xff);
*pos++ = '0';
*pos++ = 'x';
for (int shift = 28; shift >= 0; shift -= 4) {
*pos++ = format_hex_pretty_char((this->uuid_.uuid.uuid32 >> shift) & 0x0F);
}
*pos = '\0';
return std::string(buf);
default:
case ESP_UUID_LEN_128:
std::string buf;
// Format: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
for (int8_t i = 15; i >= 0; i--) {
buf += str_snprintf("%02X", 2, this->uuid_.uuid.uuid128[i]);
if (i == 6 || i == 8 || i == 10 || i == 12)
buf += "-";
uint8_t byte = this->uuid_.uuid.uuid128[i];
*pos++ = format_hex_pretty_char(byte >> 4);
*pos++ = format_hex_pretty_char(byte & 0x0F);
if (i == 12 || i == 10 || i == 8 || i == 6) {
*pos++ = '-';
}
}
return buf;
*pos = '\0';
return std::string(buf);
}
return "";
}

View File

@@ -31,12 +31,13 @@ void ESP32BLEBeacon::dump_config() {
char uuid[37];
char *bpos = uuid;
for (int8_t ii = 0; ii < 16; ++ii) {
bpos += sprintf(bpos, "%02X", this->uuid_[ii]);
*bpos++ = format_hex_pretty_char(this->uuid_[ii] >> 4);
*bpos++ = format_hex_pretty_char(this->uuid_[ii] & 0x0F);
if (ii == 3 || ii == 5 || ii == 7 || ii == 9) {
bpos += sprintf(bpos, "-");
*bpos++ = '-';
}
}
uuid[36] = '\0';
*bpos = '\0';
ESP_LOGCONFIG(TAG,
" UUID: %s, Major: %u, Minor: %u, Min Interval: %ums, Max Interval: %ums, Measured Power: %d"
", TX Power: %ddBm",

View File

@@ -60,11 +60,14 @@ class BLEClientBase : public espbt::ESPBTClient, public Component {
if (address == 0) {
this->address_str_ = "";
} else {
this->address_str_ =
str_snprintf("%02X:%02X:%02X:%02X:%02X:%02X", 17, (uint8_t) (this->address_ >> 40) & 0xff,
(uint8_t) (this->address_ >> 32) & 0xff, (uint8_t) (this->address_ >> 24) & 0xff,
(uint8_t) (this->address_ >> 16) & 0xff, (uint8_t) (this->address_ >> 8) & 0xff,
(uint8_t) (this->address_ >> 0) & 0xff);
char buf[18];
uint8_t mac[6] = {
(uint8_t) ((this->address_ >> 40) & 0xff), (uint8_t) ((this->address_ >> 32) & 0xff),
(uint8_t) ((this->address_ >> 24) & 0xff), (uint8_t) ((this->address_ >> 16) & 0xff),
(uint8_t) ((this->address_ >> 8) & 0xff), (uint8_t) ((this->address_ >> 0) & 0xff),
};
format_mac_addr_upper(mac, buf);
this->address_str_ = buf;
}
}
const std::string &address_str() const { return this->address_str_; }

View File

@@ -607,9 +607,8 @@ void ESPBTDevice::parse_adv_(const uint8_t *payload, uint8_t len) {
}
std::string ESPBTDevice::address_str() const {
char mac[24];
snprintf(mac, sizeof(mac), "%02X:%02X:%02X:%02X:%02X:%02X", this->address_[0], this->address_[1], this->address_[2],
this->address_[3], this->address_[4], this->address_[5]);
char mac[18];
format_mac_addr_upper(this->address_, mac);
return mac;
}

View File

@@ -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 {

View File

@@ -77,6 +77,13 @@ ETHERNET_TYPES = {
"DM9051": EthernetType.ETHERNET_TYPE_DM9051,
}
# PHY types that need compile-time defines for conditional compilation
_PHY_TYPE_TO_DEFINE = {
"KSZ8081": "USE_ETHERNET_KSZ8081",
"KSZ8081RNA": "USE_ETHERNET_KSZ8081",
# Add other PHY types here only if they need conditional compilation
}
SPI_ETHERNET_TYPES = ["W5500", "DM9051"]
SPI_ETHERNET_DEFAULT_POLLING_INTERVAL = TimePeriodMilliseconds(milliseconds=10)
@@ -345,6 +352,10 @@ async def to_code(config):
if CONF_MANUAL_IP in config:
cg.add(var.set_manual_ip(manual_ip(config[CONF_MANUAL_IP])))
# Add compile-time define for PHY types with specific code
if phy_define := _PHY_TYPE_TO_DEFINE.get(config[CONF_TYPE]):
cg.add_define(phy_define)
cg.add_define("USE_ETHERNET")
# Disable WiFi when using Ethernet to save memory

View File

@@ -229,10 +229,12 @@ void EthernetComponent::setup() {
ESPHL_ERROR_CHECK(err, "ETH driver install error");
#ifndef USE_ETHERNET_SPI
#ifdef USE_ETHERNET_KSZ8081
if (this->type_ == ETHERNET_TYPE_KSZ8081RNA && this->clk_mode_ == EMAC_CLK_OUT) {
// KSZ8081RNA default is incorrect. It expects a 25MHz clock instead of the 50MHz we provide.
this->ksz8081_set_clock_reference_(mac);
}
#endif // USE_ETHERNET_KSZ8081
for (const auto &phy_register : this->phy_registers_) {
this->write_phy_register_(mac, phy_register);
@@ -300,6 +302,7 @@ void EthernetComponent::loop() {
this->state_ = EthernetComponentState::CONNECTING;
this->start_connect_();
} else {
this->finish_connect_();
// When connected and stable, disable the loop to save CPU cycles
this->disable_loop();
}
@@ -486,10 +489,35 @@ void EthernetComponent::got_ip6_event_handler(void *arg, esp_event_base_t event_
}
#endif /* USE_NETWORK_IPV6 */
void EthernetComponent::finish_connect_() {
#if USE_NETWORK_IPV6
// Retry IPv6 link-local setup if it failed during initial connect
// This handles the case where min_ipv6_addr_count is NOT set (or is 0),
// allowing us to reach CONNECTED state with just IPv4.
// If IPv6 setup failed in start_connect_() because the interface wasn't ready:
// - Bootup timing issues (#10281)
// - Cable unplugged/network interruption (#10705)
// We can now retry since we're in CONNECTED state and the interface is definitely up.
if (!this->ipv6_setup_done_) {
esp_err_t err = esp_netif_create_ip6_linklocal(this->eth_netif_);
if (err == ESP_OK) {
ESP_LOGD(TAG, "IPv6 link-local address created (retry succeeded)");
}
// Always set the flag to prevent continuous retries
// If IPv6 setup fails here with the interface up and stable, it's
// likely a persistent issue (IPv6 disabled at router, hardware
// limitation, etc.) that won't be resolved by further retries.
// The device continues to work with IPv4.
this->ipv6_setup_done_ = true;
}
#endif /* USE_NETWORK_IPV6 */
}
void EthernetComponent::start_connect_() {
global_eth_component->got_ipv4_address_ = false;
#if USE_NETWORK_IPV6
global_eth_component->ipv6_count_ = 0;
this->ipv6_setup_done_ = false;
#endif /* USE_NETWORK_IPV6 */
this->connect_begin_ = millis();
this->status_set_warning(LOG_STR("waiting for IP configuration"));
@@ -545,9 +573,27 @@ void EthernetComponent::start_connect_() {
}
}
#if USE_NETWORK_IPV6
// Attempt to create IPv6 link-local address
// We MUST attempt this here, not just in finish_connect_(), because with
// min_ipv6_addr_count set, the component won't reach CONNECTED state without IPv6.
// However, this may fail with ESP_FAIL if the interface is not up yet:
// - At bootup when link isn't ready (#10281)
// - After disconnection/cable unplugged (#10705)
// We'll retry in finish_connect_() if it fails here.
err = esp_netif_create_ip6_linklocal(this->eth_netif_);
if (err != ESP_OK) {
ESPHL_ERROR_CHECK(err, "Enable IPv6 link local failed");
if (err == ESP_ERR_ESP_NETIF_INVALID_PARAMS) {
// This is a programming error, not a transient failure
ESPHL_ERROR_CHECK(err, "esp_netif_create_ip6_linklocal invalid parameters");
} else {
// ESP_FAIL means the interface isn't up yet
// This is expected and non-fatal, happens in multiple scenarios:
// - During reconnection after network interruptions (#10705)
// - At bootup when the link isn't ready yet (#10281)
// We'll retry once we reach CONNECTED state and the interface is up
ESP_LOGW(TAG, "esp_netif_create_ip6_linklocal failed: %s", esp_err_to_name(err));
// Don't mark component as failed - this is a transient error
}
}
#endif /* USE_NETWORK_IPV6 */
@@ -638,7 +684,9 @@ void EthernetComponent::get_eth_mac_address_raw(uint8_t *mac) {
std::string EthernetComponent::get_eth_mac_address_pretty() {
uint8_t mac[6];
get_eth_mac_address_raw(mac);
return str_snprintf("%02X:%02X:%02X:%02X:%02X:%02X", 17, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
char buf[18];
format_mac_addr_upper(mac, buf);
return std::string(buf);
}
eth_duplex_t EthernetComponent::get_duplex_mode() {
@@ -675,6 +723,7 @@ bool EthernetComponent::powerdown() {
#ifndef USE_ETHERNET_SPI
#ifdef USE_ETHERNET_KSZ8081
constexpr uint8_t KSZ80XX_PC2R_REG_ADDR = 0x1F;
void EthernetComponent::ksz8081_set_clock_reference_(esp_eth_mac_t *mac) {
@@ -703,6 +752,7 @@ void EthernetComponent::ksz8081_set_clock_reference_(esp_eth_mac_t *mac) {
ESP_LOGVV(TAG, "KSZ8081 PHY Control 2: %s", format_hex_pretty((u_int8_t *) &phy_control_2, 2).c_str());
}
}
#endif // USE_ETHERNET_KSZ8081
void EthernetComponent::write_phy_register_(esp_eth_mac_t *mac, PHYRegister register_data) {
esp_err_t err;

View File

@@ -102,9 +102,12 @@ class EthernetComponent : public Component {
#endif /* LWIP_IPV6 */
void start_connect_();
void finish_connect_();
void dump_connect_params_();
#ifdef USE_ETHERNET_KSZ8081
/// @brief Set `RMII Reference Clock Select` bit for KSZ8081.
void ksz8081_set_clock_reference_(esp_eth_mac_t *mac);
#endif
/// @brief Set arbitratry PHY registers from config.
void write_phy_register_(esp_eth_mac_t *mac, PHYRegister register_data);
@@ -144,6 +147,7 @@ class EthernetComponent : public Component {
bool got_ipv4_address_{false};
#if LWIP_IPV6
uint8_t ipv6_count_{0};
bool ipv6_setup_done_{false};
#endif /* LWIP_IPV6 */
// Pointers at the end (naturally aligned)

View File

@@ -1,7 +1,13 @@
#include "factory_reset_button.h"
#include "esphome/core/defines.h"
#ifdef USE_OPENTHREAD
#include "esphome/components/openthread/openthread.h"
#endif
#include "esphome/core/application.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
#include "esphome/core/application.h"
namespace esphome {
namespace factory_reset {
@@ -13,9 +19,20 @@ void FactoryResetButton::press_action() {
ESP_LOGI(TAG, "Resetting");
// Let MQTT settle a bit
delay(100); // NOLINT
#ifdef USE_OPENTHREAD
openthread::global_openthread_component->on_factory_reset(FactoryResetButton::factory_reset_callback);
#else
global_preferences->reset();
App.safe_reboot();
#endif
}
#ifdef USE_OPENTHREAD
void FactoryResetButton::factory_reset_callback() {
global_preferences->reset();
App.safe_reboot();
}
#endif
} // namespace factory_reset
} // namespace esphome

View File

@@ -1,7 +1,9 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#include "esphome/components/button/button.h"
#include "esphome/core/component.h"
namespace esphome {
namespace factory_reset {
@@ -9,6 +11,9 @@ namespace factory_reset {
class FactoryResetButton : public button::Button, public Component {
public:
void dump_config() override;
#ifdef USE_OPENTHREAD
static void factory_reset_callback();
#endif
protected:
void press_action() override;

View File

@@ -1,7 +1,13 @@
#include "factory_reset_switch.h"
#include "esphome/core/defines.h"
#ifdef USE_OPENTHREAD
#include "esphome/components/openthread/openthread.h"
#endif
#include "esphome/core/application.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
#include "esphome/core/application.h"
namespace esphome {
namespace factory_reset {
@@ -17,10 +23,21 @@ void FactoryResetSwitch::write_state(bool state) {
ESP_LOGI(TAG, "Resetting");
// Let MQTT settle a bit
delay(100); // NOLINT
#ifdef USE_OPENTHREAD
openthread::global_openthread_component->on_factory_reset(FactoryResetSwitch::factory_reset_callback);
#else
global_preferences->reset();
App.safe_reboot();
#endif
}
}
#ifdef USE_OPENTHREAD
void FactoryResetSwitch::factory_reset_callback() {
global_preferences->reset();
App.safe_reboot();
}
#endif
} // namespace factory_reset
} // namespace esphome

View File

@@ -1,7 +1,8 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/switch/switch.h"
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
namespace esphome {
namespace factory_reset {
@@ -9,6 +10,9 @@ namespace factory_reset {
class FactoryResetSwitch : public switch_::Switch, public Component {
public:
void dump_config() override;
#ifdef USE_OPENTHREAD
static void factory_reset_callback();
#endif
protected:
void write_state(bool state) override;

View File

@@ -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);

View File

@@ -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_);

View File

@@ -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_);

View File

@@ -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,
}

View File

@@ -18,6 +18,7 @@ from esphome.const import (
DEVICE_CLASS_TEMPERATURE,
DEVICE_CLASS_VOLTAGE,
STATE_CLASS_MEASUREMENT,
STATE_CLASS_TOTAL_INCREASING,
UNIT_AMPERE,
UNIT_CELSIUS,
UNIT_VOLT,
@@ -162,7 +163,7 @@ INA2XX_SCHEMA = cv.Schema(
unit_of_measurement=UNIT_WATT_HOURS,
accuracy_decimals=8,
device_class=DEVICE_CLASS_ENERGY,
state_class=STATE_CLASS_MEASUREMENT,
state_class=STATE_CLASS_TOTAL_INCREASING,
),
key=CONF_NAME,
),
@@ -170,7 +171,8 @@ INA2XX_SCHEMA = cv.Schema(
sensor.sensor_schema(
unit_of_measurement=UNIT_JOULE,
accuracy_decimals=8,
state_class=STATE_CLASS_MEASUREMENT,
device_class=DEVICE_CLASS_ENERGY,
state_class=STATE_CLASS_TOTAL_INCREASING,
),
key=CONF_NAME,
),

View File

@@ -0,0 +1 @@
CODEOWNERS = ["@jesserockz", "@JosipKuci"]

View 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, 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 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),
),
)

View 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))

View File

@@ -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

View File

@@ -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, 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PLATE_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

View File

@@ -1 +0,0 @@
CODEOWNERS = ["@jesserockz"]

View File

@@ -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))

View File

@@ -12,6 +12,7 @@
#include "light_transformer.h"
#include <vector>
#include <strings.h>
namespace esphome {
namespace light {

View File

@@ -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);

View File

@@ -11,6 +11,7 @@ from esphome.const import (
CONF_OUTPUT,
)
AUTO_LOAD = ["gpio_expander"]
DEPENDENCIES = ["i2c"]
MULTI_CONF = True

View File

@@ -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);
}

View File

@@ -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 {

View File

@@ -1,4 +1,3 @@
#include <cstdio>
#include <cstring>
#include "md5.h"
#ifdef USE_MD5
@@ -44,7 +43,9 @@ void MD5Digest::get_bytes(uint8_t *output) { memcpy(output, this->digest_, 16);
void MD5Digest::get_hex(char *output) {
for (size_t i = 0; i < 16; i++) {
sprintf(output + i * 2, "%02x", this->digest_[i]);
uint8_t byte = this->digest_[i];
output[i * 2] = format_hex_char(byte >> 4);
output[i * 2 + 1] = format_hex_char(byte & 0x0F);
}
}

View File

@@ -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:

View File

@@ -0,0 +1,2 @@
CODEOWNERS = ["@clydebarrow"]
DOMAIN = "mipi_rgb"

View 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_))

View 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

View 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

View 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),),
)

View File

@@ -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),
)
)

View 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=(),
)

View 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)
)
)

View 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],
},
)

View File

@@ -491,7 +491,7 @@ bool MQTTClientComponent::publish(const std::string &topic, const std::string &p
bool MQTTClientComponent::publish(const std::string &topic, const char *payload, size_t payload_length, uint8_t qos,
bool retain) {
return publish({.topic = topic, .payload = payload, .qos = qos, .retain = retain});
return publish({.topic = topic, .payload = std::string(payload, payload_length), .qos = qos, .retain = retain});
}
bool MQTTClientComponent::publish(const MQTTMessage &message) {

View File

@@ -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:");

View File

@@ -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");

View File

@@ -11,8 +11,6 @@
#include <openthread/instance.h>
#include <openthread/logging.h>
#include <openthread/netdata.h>
#include <openthread/srp_client.h>
#include <openthread/srp_client_buffers.h>
#include <openthread/tasklet.h>
#include <cstring>
@@ -77,8 +75,14 @@ std::optional<otIp6Address> OpenThreadComponent::get_omr_address_(InstanceLock &
return {};
}
void srp_callback(otError err, const otSrpClientHostInfo *host_info, const otSrpClientService *services,
const otSrpClientService *removed_services, void *context) {
void OpenThreadComponent::defer_factory_reset_external_callback() {
ESP_LOGD(TAG, "Defer factory_reset_external_callback_");
this->defer([this]() { this->factory_reset_external_callback_(); });
}
void OpenThreadSrpComponent::srp_callback(otError err, const otSrpClientHostInfo *host_info,
const otSrpClientService *services,
const otSrpClientService *removed_services, void *context) {
if (err != 0) {
ESP_LOGW(TAG, "SRP client reported an error: %s", otThreadErrorToString(err));
for (const otSrpClientHostInfo *host = host_info; host; host = nullptr) {
@@ -90,16 +94,30 @@ void srp_callback(otError err, const otSrpClientHostInfo *host_info, const otSrp
}
}
void srp_start_callback(const otSockAddr *server_socket_address, void *context) {
void OpenThreadSrpComponent::srp_start_callback(const otSockAddr *server_socket_address, void *context) {
ESP_LOGI(TAG, "SRP client has started");
}
void OpenThreadSrpComponent::srp_factory_reset_callback(otError err, const otSrpClientHostInfo *host_info,
const otSrpClientService *services,
const otSrpClientService *removed_services, void *context) {
OpenThreadComponent *obj = (OpenThreadComponent *) context;
if (err == OT_ERROR_NONE && removed_services != NULL && host_info != NULL &&
host_info->mState == OT_SRP_CLIENT_ITEM_STATE_REMOVED) {
ESP_LOGD(TAG, "Successful Removal SRP Host and Services");
} else if (err != OT_ERROR_NONE) {
// Handle other SRP client events or errors
ESP_LOGW(TAG, "SRP client event/error: %s", otThreadErrorToString(err));
}
obj->defer_factory_reset_external_callback();
}
void OpenThreadSrpComponent::setup() {
otError error;
InstanceLock lock = InstanceLock::acquire();
otInstance *instance = lock.get_instance();
otSrpClientSetCallback(instance, srp_callback, nullptr);
otSrpClientSetCallback(instance, OpenThreadSrpComponent::srp_callback, nullptr);
// set the host name
uint16_t size;
@@ -179,7 +197,8 @@ void OpenThreadSrpComponent::setup() {
ESP_LOGD(TAG, "Added service: %s", full_service.c_str());
}
otSrpClientEnableAutoStartMode(instance, srp_start_callback, nullptr);
otSrpClientEnableAutoStartMode(instance, OpenThreadSrpComponent::srp_start_callback, nullptr);
ESP_LOGD(TAG, "Finished SRP setup");
}
void *OpenThreadSrpComponent::pool_alloc_(size_t size) {
@@ -217,6 +236,21 @@ bool OpenThreadComponent::teardown() {
return this->teardown_complete_;
}
void OpenThreadComponent::on_factory_reset(std::function<void()> callback) {
factory_reset_external_callback_ = callback;
ESP_LOGD(TAG, "Start Removal SRP Host and Services");
otError error;
InstanceLock lock = InstanceLock::acquire();
otInstance *instance = lock.get_instance();
otSrpClientSetCallback(instance, OpenThreadSrpComponent::srp_factory_reset_callback, this);
error = otSrpClientRemoveHostAndServices(instance, true, true);
if (error != OT_ERROR_NONE) {
ESP_LOGW(TAG, "Failed to Remove SRP Host and Services");
return;
}
ESP_LOGD(TAG, "Waiting on Confirmation Removal SRP Host and Services");
}
} // namespace openthread
} // namespace esphome

View File

@@ -6,6 +6,8 @@
#include "esphome/components/network/ip_address.h"
#include "esphome/core/component.h"
#include <openthread/srp_client.h>
#include <openthread/srp_client_buffers.h>
#include <openthread/thread.h>
#include <optional>
@@ -28,11 +30,14 @@ class OpenThreadComponent : public Component {
network::IPAddresses get_ip_addresses();
std::optional<otIp6Address> get_omr_address();
void ot_main();
void on_factory_reset(std::function<void()> callback);
void defer_factory_reset_external_callback();
protected:
std::optional<otIp6Address> get_omr_address_(InstanceLock &lock);
bool teardown_started_{false};
bool teardown_complete_{false};
std::function<void()> factory_reset_external_callback_;
};
extern OpenThreadComponent *global_openthread_component; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
@@ -43,6 +48,12 @@ class OpenThreadSrpComponent : public Component {
// This has to run after the mdns component or else no services are available to advertise
float get_setup_priority() const override { return this->mdns_->get_setup_priority() - 1.0; }
void setup() override;
static void srp_callback(otError err, const otSrpClientHostInfo *host_info, const otSrpClientService *services,
const otSrpClientService *removed_services, void *context);
static void srp_start_callback(const otSockAddr *server_socket_address, void *context);
static void srp_factory_reset_callback(otError err, const otSrpClientHostInfo *host_info,
const otSrpClientService *services, const otSrpClientService *removed_services,
void *context);
protected:
esphome::mdns::MDNSComponent *mdns_{nullptr};

View File

@@ -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")

View File

@@ -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);
}

View File

@@ -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

View File

@@ -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"

View File

@@ -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_); }

View File

@@ -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_;
};

View File

@@ -11,6 +11,7 @@ from esphome.const import (
CONF_OUTPUT,
)
AUTO_LOAD = ["gpio_expander"]
DEPENDENCIES = ["i2c"]
MULTI_CONF = True

View File

@@ -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_; }

View File

@@ -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

View File

@@ -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() {

View File

@@ -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());
}
}

View File

@@ -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_;
};

View File

@@ -28,12 +28,12 @@ bool Select::has_option(const std::string &option) const { return this->index_of
bool Select::has_index(size_t index) const { return index < this->size(); }
size_t Select::size() const {
auto options = traits.get_options();
const auto &options = traits.get_options();
return options.size();
}
optional<size_t> Select::index_of(const std::string &option) const {
auto options = traits.get_options();
const auto &options = traits.get_options();
auto it = std::find(options.begin(), options.end(), option);
if (it == options.end()) {
return {};
@@ -51,7 +51,7 @@ optional<size_t> Select::active_index() const {
optional<std::string> Select::at(size_t index) const {
if (this->has_index(index)) {
auto options = traits.get_options();
const auto &options = traits.get_options();
return options.at(index);
} else {
return {};

View File

@@ -45,7 +45,7 @@ void SelectCall::perform() {
auto *parent = this->parent_;
const auto *name = parent->get_name().c_str();
const auto &traits = parent->traits;
auto options = traits.get_options();
const auto &options = traits.get_options();
if (this->operation_ == SELECT_OP_NONE) {
ESP_LOGW(TAG, "'%s' - SelectCall performed without selecting an operation", name);

View File

@@ -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

View File

@@ -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;

View File

@@ -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;

View File

@@ -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]

View File

@@ -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;

Some files were not shown because too many files have changed in this diff Show More