mirror of
				https://github.com/esphome/esphome.git
				synced 2025-10-31 07:03:55 +00:00 
			
		
		
		
	Merge branch 'dev' into optolink
This commit is contained in:
		| @@ -63,15 +63,16 @@ Checks: >- | |||||||
|   -misc-non-private-member-variables-in-classes, |   -misc-non-private-member-variables-in-classes, | ||||||
|   -misc-no-recursion, |   -misc-no-recursion, | ||||||
|   -misc-unused-parameters, |   -misc-unused-parameters, | ||||||
|   -modernize-avoid-c-arrays, |  | ||||||
|   -modernize-avoid-bind, |   -modernize-avoid-bind, | ||||||
|  |   -modernize-avoid-c-arrays, | ||||||
|   -modernize-concat-nested-namespaces, |   -modernize-concat-nested-namespaces, | ||||||
|   -modernize-return-braced-init-list, |   -modernize-return-braced-init-list, | ||||||
|   -modernize-use-auto, |   -modernize-use-auto, | ||||||
|   -modernize-use-default-member-init, |   -modernize-use-default-member-init, | ||||||
|   -modernize-use-equals-default, |   -modernize-use-equals-default, | ||||||
|   -modernize-use-trailing-return-type, |  | ||||||
|   -modernize-use-nodiscard, |   -modernize-use-nodiscard, | ||||||
|  |   -modernize-use-nullptr, | ||||||
|  |   -modernize-use-trailing-return-type, | ||||||
|   -mpi-*, |   -mpi-*, | ||||||
|   -objc-*, |   -objc-*, | ||||||
|   -readability-container-data-pointer, |   -readability-container-data-pointer, | ||||||
| @@ -82,6 +83,7 @@ Checks: >- | |||||||
|   -readability-isolate-declaration, |   -readability-isolate-declaration, | ||||||
|   -readability-magic-numbers, |   -readability-magic-numbers, | ||||||
|   -readability-make-member-function-const, |   -readability-make-member-function-const, | ||||||
|  |   -readability-named-parameter, | ||||||
|   -readability-redundant-string-init, |   -readability-redundant-string-init, | ||||||
|   -readability-uppercase-literal-suffix, |   -readability-uppercase-literal-suffix, | ||||||
|   -readability-use-anyofallof, |   -readability-use-anyofallof, | ||||||
|   | |||||||
| @@ -75,6 +75,9 @@ target/ | |||||||
| # pyenv | # pyenv | ||||||
| .python-version | .python-version | ||||||
|  |  | ||||||
|  | # asdf | ||||||
|  | .tool-versions | ||||||
|  |  | ||||||
| # celery beat schedule file | # celery beat schedule file | ||||||
| celerybeat-schedule | celerybeat-schedule | ||||||
|  |  | ||||||
|   | |||||||
							
								
								
									
										4
									
								
								.github/actions/build-image/action.yaml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										4
									
								
								.github/actions/build-image/action.yaml
									
									
									
									
										vendored
									
									
								
							| @@ -46,7 +46,7 @@ runs: | |||||||
|  |  | ||||||
|     - name: Build and push to ghcr by digest |     - name: Build and push to ghcr by digest | ||||||
|       id: build-ghcr |       id: build-ghcr | ||||||
|       uses: docker/build-push-action@v6.9.0 |       uses: docker/build-push-action@v6.10.0 | ||||||
|       env: |       env: | ||||||
|         DOCKER_BUILD_SUMMARY: false |         DOCKER_BUILD_SUMMARY: false | ||||||
|         DOCKER_BUILD_RECORD_UPLOAD: false |         DOCKER_BUILD_RECORD_UPLOAD: false | ||||||
| @@ -72,7 +72,7 @@ runs: | |||||||
|  |  | ||||||
|     - name: Build and push to dockerhub by digest |     - name: Build and push to dockerhub by digest | ||||||
|       id: build-dockerhub |       id: build-dockerhub | ||||||
|       uses: docker/build-push-action@v6.9.0 |       uses: docker/build-push-action@v6.10.0 | ||||||
|       env: |       env: | ||||||
|         DOCKER_BUILD_SUMMARY: false |         DOCKER_BUILD_SUMMARY: false | ||||||
|         DOCKER_BUILD_RECORD_UPLOAD: false |         DOCKER_BUILD_RECORD_UPLOAD: false | ||||||
|   | |||||||
							
								
								
									
										2
									
								
								.github/workflows/ci.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										2
									
								
								.github/workflows/ci.yml
									
									
									
									
										vendored
									
									
								
							| @@ -219,7 +219,7 @@ jobs: | |||||||
|           . venv/bin/activate |           . venv/bin/activate | ||||||
|           pytest -vv --cov-report=xml --tb=native tests |           pytest -vv --cov-report=xml --tb=native tests | ||||||
|       - name: Upload coverage to Codecov |       - name: Upload coverage to Codecov | ||||||
|         uses: codecov/codecov-action@v4 |         uses: codecov/codecov-action@v5 | ||||||
|         with: |         with: | ||||||
|           token: ${{ secrets.CODECOV_TOKEN }} |           token: ${{ secrets.CODECOV_TOKEN }} | ||||||
|  |  | ||||||
|   | |||||||
							
								
								
									
										2
									
								
								.github/workflows/release.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										2
									
								
								.github/workflows/release.yml
									
									
									
									
										vendored
									
									
								
							| @@ -65,7 +65,7 @@ jobs: | |||||||
|           pip3 install build |           pip3 install build | ||||||
|           python3 -m build |           python3 -m build | ||||||
|       - name: Publish |       - name: Publish | ||||||
|         uses: pypa/gh-action-pypi-publish@v1.10.3 |         uses: pypa/gh-action-pypi-publish@v1.12.2 | ||||||
|  |  | ||||||
|   deploy-docker: |   deploy-docker: | ||||||
|     name: Build ESPHome ${{ matrix.platform }} |     name: Build ESPHome ${{ matrix.platform }} | ||||||
|   | |||||||
							
								
								
									
										3
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										3
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							| @@ -75,6 +75,9 @@ cov.xml | |||||||
| # pyenv | # pyenv | ||||||
| .python-version | .python-version | ||||||
|  |  | ||||||
|  | # asdf | ||||||
|  | .tool-versions | ||||||
|  |  | ||||||
| # Environments | # Environments | ||||||
| .env | .env | ||||||
| .venv | .venv | ||||||
|   | |||||||
| @@ -85,6 +85,7 @@ esphome/components/bmp581/* @kahrendt | |||||||
| esphome/components/bp1658cj/* @Cossid | esphome/components/bp1658cj/* @Cossid | ||||||
| esphome/components/bp5758d/* @Cossid | esphome/components/bp5758d/* @Cossid | ||||||
| esphome/components/button/* @esphome/core | esphome/components/button/* @esphome/core | ||||||
|  | esphome/components/bytebuffer/* @clydebarrow | ||||||
| esphome/components/canbus/* @danielschramm @mvturnho | esphome/components/canbus/* @danielschramm @mvturnho | ||||||
| esphome/components/cap1188/* @mreditor97 | esphome/components/cap1188/* @mreditor97 | ||||||
| esphome/components/captive_portal/* @OttoWinter | esphome/components/captive_portal/* @OttoWinter | ||||||
| @@ -130,6 +131,7 @@ esphome/components/ens160_base/* @latonita @vincentscode | |||||||
| esphome/components/ens160_i2c/* @latonita | esphome/components/ens160_i2c/* @latonita | ||||||
| esphome/components/ens160_spi/* @latonita | esphome/components/ens160_spi/* @latonita | ||||||
| esphome/components/ens210/* @itn3rd77 | esphome/components/ens210/* @itn3rd77 | ||||||
|  | esphome/components/es8311/* @kahrendt @kroimon | ||||||
| esphome/components/esp32/* @esphome/core | esphome/components/esp32/* @esphome/core | ||||||
| esphome/components/esp32_ble/* @Rapsssito @jesserockz | esphome/components/esp32_ble/* @Rapsssito @jesserockz | ||||||
| esphome/components/esp32_ble_client/* @jesserockz | esphome/components/esp32_ble_client/* @jesserockz | ||||||
| @@ -360,6 +362,7 @@ esphome/components/sdl/* @clydebarrow | |||||||
| esphome/components/sdm_meter/* @jesserockz @polyfaces | esphome/components/sdm_meter/* @jesserockz @polyfaces | ||||||
| esphome/components/sdp3x/* @Azimath | esphome/components/sdp3x/* @Azimath | ||||||
| esphome/components/seeed_mr24hpc1/* @limengdu | esphome/components/seeed_mr24hpc1/* @limengdu | ||||||
|  | esphome/components/seeed_mr60fda2/* @limengdu | ||||||
| esphome/components/selec_meter/* @sourabhjaiswal | esphome/components/selec_meter/* @sourabhjaiswal | ||||||
| esphome/components/select/* @esphome/core | esphome/components/select/* @esphome/core | ||||||
| esphome/components/sen0321/* @notjj | esphome/components/sen0321/* @notjj | ||||||
| @@ -414,6 +417,7 @@ esphome/components/substitutions/* @esphome/core | |||||||
| esphome/components/sun/* @OttoWinter | esphome/components/sun/* @OttoWinter | ||||||
| esphome/components/sun_gtil2/* @Mat931 | esphome/components/sun_gtil2/* @Mat931 | ||||||
| esphome/components/switch/* @esphome/core | esphome/components/switch/* @esphome/core | ||||||
|  | esphome/components/switch/binary_sensor/* @ssieb | ||||||
| esphome/components/t6615/* @tylermenezes | esphome/components/t6615/* @tylermenezes | ||||||
| esphome/components/tc74/* @sethgirvan | esphome/components/tc74/* @sethgirvan | ||||||
| esphome/components/tca9548a/* @andreashergert1984 | esphome/components/tca9548a/* @andreashergert1984 | ||||||
|   | |||||||
| @@ -32,33 +32,14 @@ RUN \ | |||||||
|         python3-setuptools=66.1.1-1 \ |         python3-setuptools=66.1.1-1 \ | ||||||
|         python3-venv=3.11.2-1+b1 \ |         python3-venv=3.11.2-1+b1 \ | ||||||
|         python3-wheel=0.38.4-2 \ |         python3-wheel=0.38.4-2 \ | ||||||
|         iputils-ping=3:20221126-1 \ |         iputils-ping=3:20221126-1+deb12u1 \ | ||||||
|         git=1:2.39.5-0+deb12u1 \ |         git=1:2.39.5-0+deb12u1 \ | ||||||
|         curl=7.88.1-10+deb12u7 \ |         curl=7.88.1-10+deb12u8 \ | ||||||
|         openssh-client=1:9.2p1-2+deb12u3 \ |         openssh-client=1:9.2p1-2+deb12u3 \ | ||||||
|         python3-cffi=1.15.1-5 \ |         python3-cffi=1.15.1-5 \ | ||||||
|         libcairo2=1.16.0-7 \ |         libcairo2=1.16.0-7 \ | ||||||
|         libmagic1=1:5.44-3 \ |         libmagic1=1:5.44-3 \ | ||||||
|         patch=2.7.6-7 \ |         patch=2.7.6-7 \ | ||||||
|     && ( \ |  | ||||||
|         ( \ |  | ||||||
|             [ "$TARGETARCH$TARGETVARIANT" = "armv7" ] && \ |  | ||||||
|                 apt-get install -y --no-install-recommends \ |  | ||||||
|                 build-essential=12.9 \ |  | ||||||
|                 python3-dev=3.11.2-1+b1 \ |  | ||||||
|                 zlib1g-dev=1:1.2.13.dfsg-1 \ |  | ||||||
|                 libjpeg-dev=1:2.1.5-2 \ |  | ||||||
|                 libfreetype-dev=2.12.1+dfsg-5+deb12u3 \ |  | ||||||
|                 libssl-dev=3.0.14-1~deb12u2 \ |  | ||||||
|                 libffi-dev=3.4.4-1 \ |  | ||||||
|                 libopenjp2-7=2.5.0-2 \ |  | ||||||
|                 libtiff6=4.5.0-6+deb12u1 \ |  | ||||||
|                 cargo=0.66.0+ds1-1 \ |  | ||||||
|                 pkg-config=1.8.1-1 \ |  | ||||||
|                 gcc-arm-linux-gnueabihf=4:12.2.0-3 \ |  | ||||||
|         ) \ |  | ||||||
|         || [ "$TARGETARCH$TARGETVARIANT" != "armv7" ] \ |  | ||||||
|     ) \ |  | ||||||
|     && rm -rf \ |     && rm -rf \ | ||||||
|         /tmp/* \ |         /tmp/* \ | ||||||
|         /var/{cache,log}/* \ |         /var/{cache,log}/* \ | ||||||
| @@ -97,15 +78,50 @@ RUN \ | |||||||
| # tmpfs is for https://github.com/rust-lang/cargo/issues/8719 | # tmpfs is for https://github.com/rust-lang/cargo/issues/8719 | ||||||
|  |  | ||||||
| COPY requirements.txt requirements_optional.txt / | COPY requirements.txt requirements_optional.txt / | ||||||
| RUN --mount=type=tmpfs,target=/root/.cargo if [ "$TARGETARCH$TARGETVARIANT" = "armv7" ]; then \ | RUN --mount=type=tmpfs,target=/root/.cargo <<END-OF-RUN | ||||||
|         curl -L https://www.piwheels.org/cp311/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl -o /tmp/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl \ | # Fail on any non-zero status | ||||||
|         && pip3 install --break-system-packages --no-cache-dir /tmp/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl \ | set -e | ||||||
|         && rm /tmp/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl \ |  | ||||||
|         && export PIP_EXTRA_INDEX_URL="https://www.piwheels.org/simple"; \ | if [ "$TARGETARCH$TARGETVARIANT" = "armv7" ] | ||||||
|     fi; \ | then | ||||||
|     CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse CARGO_HOME=/root/.cargo \ |     curl -L https://www.piwheels.org/cp311/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl -o /tmp/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl | ||||||
|     pip3 install \ |     pip3 install --break-system-packages --no-cache-dir /tmp/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl | ||||||
|     --break-system-packages --no-cache-dir -r /requirements.txt -r /requirements_optional.txt |     rm /tmp/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl | ||||||
|  |     export PIP_EXTRA_INDEX_URL="https://www.piwheels.org/simple"; | ||||||
|  | fi | ||||||
|  |  | ||||||
|  | # install build tools in case wheels are not available | ||||||
|  | BUILD_DEPS=" | ||||||
|  |     build-essential=12.9 | ||||||
|  |     python3-dev=3.11.2-1+b1 | ||||||
|  |     zlib1g-dev=1:1.2.13.dfsg-1 | ||||||
|  |     libjpeg-dev=1:2.1.5-2 | ||||||
|  |     libfreetype-dev=2.12.1+dfsg-5+deb12u3 | ||||||
|  |     libssl-dev=3.0.15-1~deb12u1 | ||||||
|  |     libffi-dev=3.4.4-1 | ||||||
|  |     cargo=0.66.0+ds1-1 | ||||||
|  |     pkg-config=1.8.1-1 | ||||||
|  | " | ||||||
|  | LIB_DEPS=" | ||||||
|  |     libtiff6=4.5.0-6+deb12u1 | ||||||
|  |     libopenjp2-7=2.5.0-2 | ||||||
|  | " | ||||||
|  | if [ "$TARGETARCH$TARGETVARIANT" = "arm64" ] || [ "$TARGETARCH$TARGETVARIANT" = "armv7" ] | ||||||
|  | then | ||||||
|  |     apt-get update | ||||||
|  |     apt-get install -y --no-install-recommends $BUILD_DEPS $LIB_DEPS | ||||||
|  | fi | ||||||
|  |  | ||||||
|  | CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse CARGO_HOME=/root/.cargo | ||||||
|  | pip3 install --break-system-packages --no-cache-dir -r /requirements.txt -r /requirements_optional.txt | ||||||
|  |  | ||||||
|  | if [ "$TARGETARCH$TARGETVARIANT" = "arm64" ] || [ "$TARGETARCH$TARGETVARIANT" = "armv7" ] | ||||||
|  | then | ||||||
|  |     apt-get remove -y --purge --auto-remove $BUILD_DEPS | ||||||
|  |     rm -rf /tmp/* /var/{cache,log}/* /var/lib/apt/lists/* | ||||||
|  | fi | ||||||
|  | END-OF-RUN | ||||||
|  |  | ||||||
|  |  | ||||||
| COPY script/platformio_install_deps.py platformio.ini / | COPY script/platformio_install_deps.py platformio.ini / | ||||||
| RUN /platformio_install_deps.py /platformio.ini --libraries | RUN /platformio_install_deps.py /platformio.ini --libraries | ||||||
|   | |||||||
| @@ -20,6 +20,8 @@ from esphome.const import ( | |||||||
|     CONF_DEASSERT_RTS_DTR, |     CONF_DEASSERT_RTS_DTR, | ||||||
|     CONF_DISABLED, |     CONF_DISABLED, | ||||||
|     CONF_ESPHOME, |     CONF_ESPHOME, | ||||||
|  |     CONF_LEVEL, | ||||||
|  |     CONF_LOG_TOPIC, | ||||||
|     CONF_LOGGER, |     CONF_LOGGER, | ||||||
|     CONF_MDNS, |     CONF_MDNS, | ||||||
|     CONF_MQTT, |     CONF_MQTT, | ||||||
| @@ -30,6 +32,7 @@ from esphome.const import ( | |||||||
|     CONF_PLATFORMIO_OPTIONS, |     CONF_PLATFORMIO_OPTIONS, | ||||||
|     CONF_PORT, |     CONF_PORT, | ||||||
|     CONF_SUBSTITUTIONS, |     CONF_SUBSTITUTIONS, | ||||||
|  |     CONF_TOPIC, | ||||||
|     PLATFORM_BK72XX, |     PLATFORM_BK72XX, | ||||||
|     PLATFORM_ESP32, |     PLATFORM_ESP32, | ||||||
|     PLATFORM_ESP8266, |     PLATFORM_ESP8266, | ||||||
| @@ -38,7 +41,7 @@ from esphome.const import ( | |||||||
|     SECRETS_FILES, |     SECRETS_FILES, | ||||||
| ) | ) | ||||||
| from esphome.core import CORE, EsphomeError, coroutine | from esphome.core import CORE, EsphomeError, coroutine | ||||||
| from esphome.helpers import indent, is_ip_address, get_bool_env | from esphome.helpers import get_bool_env, indent, is_ip_address | ||||||
| from esphome.log import Fore, color, setup_log | from esphome.log import Fore, color, setup_log | ||||||
| from esphome.util import ( | from esphome.util import ( | ||||||
|     get_serial_ports, |     get_serial_ports, | ||||||
| @@ -95,8 +98,12 @@ def choose_upload_log_host( | |||||||
|         options.append((f"Over The Air ({CORE.address})", CORE.address)) |         options.append((f"Over The Air ({CORE.address})", CORE.address)) | ||||||
|         if default == "OTA": |         if default == "OTA": | ||||||
|             return CORE.address |             return CORE.address | ||||||
|     if show_mqtt and CONF_MQTT in CORE.config: |     if ( | ||||||
|         options.append((f"MQTT ({CORE.config['mqtt'][CONF_BROKER]})", "MQTT")) |         show_mqtt | ||||||
|  |         and (mqtt_config := CORE.config.get(CONF_MQTT)) | ||||||
|  |         and mqtt_logging_enabled(mqtt_config) | ||||||
|  |     ): | ||||||
|  |         options.append((f"MQTT ({mqtt_config[CONF_BROKER]})", "MQTT")) | ||||||
|         if default == "OTA": |         if default == "OTA": | ||||||
|             return "MQTT" |             return "MQTT" | ||||||
|     if default is not None: |     if default is not None: | ||||||
| @@ -106,6 +113,17 @@ def choose_upload_log_host( | |||||||
|     return choose_prompt(options, purpose=purpose) |     return choose_prompt(options, purpose=purpose) | ||||||
|  |  | ||||||
|  |  | ||||||
|  | def mqtt_logging_enabled(mqtt_config): | ||||||
|  |     log_topic = mqtt_config[CONF_LOG_TOPIC] | ||||||
|  |     if log_topic is None: | ||||||
|  |         return False | ||||||
|  |     if CONF_TOPIC not in log_topic: | ||||||
|  |         return False | ||||||
|  |     if log_topic.get(CONF_LEVEL, None) == "NONE": | ||||||
|  |         return False | ||||||
|  |     return True | ||||||
|  |  | ||||||
|  |  | ||||||
| def get_port_type(port): | def get_port_type(port): | ||||||
|     if port.startswith("/") or port.startswith("COM"): |     if port.startswith("/") or port.startswith("COM"): | ||||||
|         return "SERIAL" |         return "SERIAL" | ||||||
| @@ -378,7 +396,7 @@ def show_logs(config, args, port): | |||||||
|  |  | ||||||
|             port = mqtt.get_esphome_device_ip( |             port = mqtt.get_esphome_device_ip( | ||||||
|                 config, args.username, args.password, args.client_id |                 config, args.username, args.password, args.client_id | ||||||
|             ) |             )[0] | ||||||
|  |  | ||||||
|         from esphome.components.api.client import run_logs |         from esphome.components.api.client import run_logs | ||||||
|  |  | ||||||
|   | |||||||
| @@ -72,10 +72,9 @@ void AlarmControlPanelCall::validate_() { | |||||||
|       this->state_.reset(); |       this->state_.reset(); | ||||||
|       return; |       return; | ||||||
|     } |     } | ||||||
|     if (state == ACP_STATE_DISARMED && |     if (state == ACP_STATE_DISARMED && !this->parent_->is_state_armed(this->parent_->get_state()) && | ||||||
|         !(this->parent_->is_state_armed(this->parent_->get_state()) || |         this->parent_->get_state() != ACP_STATE_PENDING && this->parent_->get_state() != ACP_STATE_ARMING && | ||||||
|           this->parent_->get_state() == ACP_STATE_PENDING || this->parent_->get_state() == ACP_STATE_ARMING || |         this->parent_->get_state() != ACP_STATE_TRIGGERED) { | ||||||
|           this->parent_->get_state() == ACP_STATE_TRIGGERED)) { |  | ||||||
|       ESP_LOGW(TAG, "Cannot disarm when not armed"); |       ESP_LOGW(TAG, "Cannot disarm when not armed"); | ||||||
|       this->state_.reset(); |       this->state_.reset(); | ||||||
|       return; |       return; | ||||||
|   | |||||||
| @@ -122,7 +122,8 @@ void APDS9306::update() { | |||||||
|  |  | ||||||
|   this->status_clear_warning(); |   this->status_clear_warning(); | ||||||
|  |  | ||||||
|   if (!(status &= 0b00001000)) {  // No new data |   status &= 0b00001000; | ||||||
|  |   if (!status) {  // No new data | ||||||
|     return; |     return; | ||||||
|   } |   } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -1,7 +1,7 @@ | |||||||
| #pragma once | #pragma once | ||||||
|  |  | ||||||
|  | #include <cstddef> | ||||||
| #include <cstdint> | #include <cstdint> | ||||||
| #include <stddef.h> |  | ||||||
|  |  | ||||||
| namespace esphome { | namespace esphome { | ||||||
| namespace audio { | namespace audio { | ||||||
|   | |||||||
| @@ -58,7 +58,7 @@ class BinarySensor : public EntityBase, public EntityBase_DeviceClass { | |||||||
|   void publish_initial_state(bool state); |   void publish_initial_state(bool state); | ||||||
|  |  | ||||||
|   /// The current reported state of the binary sensor. |   /// The current reported state of the binary sensor. | ||||||
|   bool state; |   bool state{false}; | ||||||
|  |  | ||||||
|   void add_filter(Filter *filter); |   void add_filter(Filter *filter); | ||||||
|   void add_filters(const std::vector<Filter *> &filters); |   void add_filters(const std::vector<Filter *> &filters); | ||||||
|   | |||||||
| @@ -15,7 +15,7 @@ from esphome.components.libretiny.const import ( | |||||||
| ) | ) | ||||||
| from esphome.core import CORE | from esphome.core import CORE | ||||||
|  |  | ||||||
| from .boards import BK72XX_BOARDS, BK72XX_BOARD_PINS | from .boards import BK72XX_BOARD_PINS, BK72XX_BOARDS | ||||||
|  |  | ||||||
| CODEOWNERS = ["@kuba2k2"] | CODEOWNERS = ["@kuba2k2"] | ||||||
| AUTO_LOAD = ["libretiny"] | AUTO_LOAD = ["libretiny"] | ||||||
|   | |||||||
| @@ -204,11 +204,11 @@ void BME68xBSEC2Component::update_subscription_() { | |||||||
| } | } | ||||||
|  |  | ||||||
| void BME68xBSEC2Component::run_() { | void BME68xBSEC2Component::run_() { | ||||||
|  |   this->op_mode_ = this->bsec_settings_.op_mode; | ||||||
|   int64_t curr_time_ns = this->get_time_ns_(); |   int64_t curr_time_ns = this->get_time_ns_(); | ||||||
|   if (curr_time_ns < this->next_call_ns_) { |   if (curr_time_ns < this->bsec_settings_.next_call) { | ||||||
|     return; |     return; | ||||||
|   } |   } | ||||||
|   this->op_mode_ = this->bsec_settings_.op_mode; |  | ||||||
|   uint8_t status; |   uint8_t status; | ||||||
|  |  | ||||||
|   ESP_LOGV(TAG, "Performing sensor run"); |   ESP_LOGV(TAG, "Performing sensor run"); | ||||||
| @@ -219,57 +219,60 @@ void BME68xBSEC2Component::run_() { | |||||||
|     ESP_LOGW(TAG, "Failed to fetch sensor control settings (BSEC2 error code %d)", this->bsec_status_); |     ESP_LOGW(TAG, "Failed to fetch sensor control settings (BSEC2 error code %d)", this->bsec_status_); | ||||||
|     return; |     return; | ||||||
|   } |   } | ||||||
|   this->next_call_ns_ = this->bsec_settings_.next_call; |  | ||||||
|  |  | ||||||
|   if (this->bsec_settings_.trigger_measurement) { |   switch (this->bsec_settings_.op_mode) { | ||||||
|     bme68x_get_conf(&bme68x_conf, &this->bme68x_); |     case BME68X_FORCED_MODE: | ||||||
|  |       bme68x_get_conf(&bme68x_conf, &this->bme68x_); | ||||||
|  |  | ||||||
|     bme68x_conf.os_hum = this->bsec_settings_.humidity_oversampling; |       bme68x_conf.os_hum = this->bsec_settings_.humidity_oversampling; | ||||||
|     bme68x_conf.os_temp = this->bsec_settings_.temperature_oversampling; |       bme68x_conf.os_temp = this->bsec_settings_.temperature_oversampling; | ||||||
|     bme68x_conf.os_pres = this->bsec_settings_.pressure_oversampling; |       bme68x_conf.os_pres = this->bsec_settings_.pressure_oversampling; | ||||||
|     bme68x_set_conf(&bme68x_conf, &this->bme68x_); |       bme68x_set_conf(&bme68x_conf, &this->bme68x_); | ||||||
|  |       this->bme68x_heatr_conf_.enable = BME68X_ENABLE; | ||||||
|  |       this->bme68x_heatr_conf_.heatr_temp = this->bsec_settings_.heater_temperature; | ||||||
|  |       this->bme68x_heatr_conf_.heatr_dur = this->bsec_settings_.heater_duration; | ||||||
|  |  | ||||||
|  |       // status = bme68x_set_op_mode(this->bsec_settings_.op_mode, &this->bme68x_); | ||||||
|  |       status = bme68x_set_heatr_conf(BME68X_FORCED_MODE, &this->bme68x_heatr_conf_, &this->bme68x_); | ||||||
|  |       status = bme68x_set_op_mode(BME68X_FORCED_MODE, &this->bme68x_); | ||||||
|  |       this->op_mode_ = BME68X_FORCED_MODE; | ||||||
|  |       ESP_LOGV(TAG, "Using forced mode"); | ||||||
|  |  | ||||||
|  |       break; | ||||||
|  |     case BME68X_PARALLEL_MODE: | ||||||
|  |       if (this->op_mode_ != this->bsec_settings_.op_mode) { | ||||||
|  |         bme68x_get_conf(&bme68x_conf, &this->bme68x_); | ||||||
|  |  | ||||||
|  |         bme68x_conf.os_hum = this->bsec_settings_.humidity_oversampling; | ||||||
|  |         bme68x_conf.os_temp = this->bsec_settings_.temperature_oversampling; | ||||||
|  |         bme68x_conf.os_pres = this->bsec_settings_.pressure_oversampling; | ||||||
|  |         bme68x_set_conf(&bme68x_conf, &this->bme68x_); | ||||||
|  |  | ||||||
|     switch (this->bsec_settings_.op_mode) { |  | ||||||
|       case BME68X_FORCED_MODE: |  | ||||||
|         this->bme68x_heatr_conf_.enable = BME68X_ENABLE; |         this->bme68x_heatr_conf_.enable = BME68X_ENABLE; | ||||||
|         this->bme68x_heatr_conf_.heatr_temp = this->bsec_settings_.heater_temperature; |         this->bme68x_heatr_conf_.heatr_temp_prof = this->bsec_settings_.heater_temperature_profile; | ||||||
|         this->bme68x_heatr_conf_.heatr_dur = this->bsec_settings_.heater_duration; |         this->bme68x_heatr_conf_.heatr_dur_prof = this->bsec_settings_.heater_duration_profile; | ||||||
|  |         this->bme68x_heatr_conf_.profile_len = this->bsec_settings_.heater_profile_len; | ||||||
|  |         this->bme68x_heatr_conf_.shared_heatr_dur = | ||||||
|  |             BSEC_TOTAL_HEAT_DUR - | ||||||
|  |             (bme68x_get_meas_dur(BME68X_PARALLEL_MODE, &bme68x_conf, &this->bme68x_) / INT64_C(1000)); | ||||||
|  |  | ||||||
|         status = bme68x_set_op_mode(this->bsec_settings_.op_mode, &this->bme68x_); |         status = bme68x_set_heatr_conf(BME68X_PARALLEL_MODE, &this->bme68x_heatr_conf_, &this->bme68x_); | ||||||
|         status = bme68x_set_heatr_conf(BME68X_FORCED_MODE, &this->bme68x_heatr_conf_, &this->bme68x_); |  | ||||||
|         status = bme68x_set_op_mode(BME68X_FORCED_MODE, &this->bme68x_); |  | ||||||
|         this->op_mode_ = BME68X_FORCED_MODE; |  | ||||||
|         this->sleep_mode_ = false; |  | ||||||
|         ESP_LOGV(TAG, "Using forced mode"); |  | ||||||
|  |  | ||||||
|         break; |         status = bme68x_set_op_mode(BME68X_PARALLEL_MODE, &this->bme68x_); | ||||||
|       case BME68X_PARALLEL_MODE: |         this->op_mode_ = BME68X_PARALLEL_MODE; | ||||||
|         if (this->op_mode_ != this->bsec_settings_.op_mode) { |         ESP_LOGV(TAG, "Using parallel mode"); | ||||||
|           this->bme68x_heatr_conf_.enable = BME68X_ENABLE; |       } | ||||||
|           this->bme68x_heatr_conf_.heatr_temp_prof = this->bsec_settings_.heater_temperature_profile; |       break; | ||||||
|           this->bme68x_heatr_conf_.heatr_dur_prof = this->bsec_settings_.heater_duration_profile; |     case BME68X_SLEEP_MODE: | ||||||
|           this->bme68x_heatr_conf_.profile_len = this->bsec_settings_.heater_profile_len; |       if (this->op_mode_ != this->bsec_settings_.op_mode) { | ||||||
|           this->bme68x_heatr_conf_.shared_heatr_dur = |         bme68x_set_op_mode(BME68X_SLEEP_MODE, &this->bme68x_); | ||||||
|               BSEC_TOTAL_HEAT_DUR - |         this->op_mode_ = BME68X_SLEEP_MODE; | ||||||
|               (bme68x_get_meas_dur(BME68X_PARALLEL_MODE, &bme68x_conf, &this->bme68x_) / INT64_C(1000)); |         ESP_LOGV(TAG, "Using sleep mode"); | ||||||
|  |       } | ||||||
|           status = bme68x_set_heatr_conf(BME68X_PARALLEL_MODE, &this->bme68x_heatr_conf_, &this->bme68x_); |       break; | ||||||
|  |   } | ||||||
|           status = bme68x_set_op_mode(BME68X_PARALLEL_MODE, &this->bme68x_); |  | ||||||
|           this->op_mode_ = BME68X_PARALLEL_MODE; |  | ||||||
|           this->sleep_mode_ = false; |  | ||||||
|           ESP_LOGV(TAG, "Using parallel mode"); |  | ||||||
|         } |  | ||||||
|         break; |  | ||||||
|       case BME68X_SLEEP_MODE: |  | ||||||
|         if (!this->sleep_mode_) { |  | ||||||
|           bme68x_set_op_mode(BME68X_SLEEP_MODE, &this->bme68x_); |  | ||||||
|           this->sleep_mode_ = true; |  | ||||||
|           ESP_LOGV(TAG, "Using sleep mode"); |  | ||||||
|         } |  | ||||||
|         break; |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|  |   if (this->bsec_settings_.trigger_measurement && this->bsec_settings_.op_mode != BME68X_SLEEP_MODE) { | ||||||
|     uint32_t meas_dur = 0; |     uint32_t meas_dur = 0; | ||||||
|     meas_dur = bme68x_get_meas_dur(this->op_mode_, &bme68x_conf, &this->bme68x_); |     meas_dur = bme68x_get_meas_dur(this->op_mode_, &bme68x_conf, &this->bme68x_); | ||||||
|     ESP_LOGV(TAG, "Queueing read in %uus", meas_dur); |     ESP_LOGV(TAG, "Queueing read in %uus", meas_dur); | ||||||
|   | |||||||
| @@ -113,13 +113,11 @@ class BME68xBSEC2Component : public Component { | |||||||
|  |  | ||||||
|   struct bme68x_heatr_conf bme68x_heatr_conf_; |   struct bme68x_heatr_conf bme68x_heatr_conf_; | ||||||
|   uint8_t op_mode_;  // operating mode of sensor |   uint8_t op_mode_;  // operating mode of sensor | ||||||
|   bool sleep_mode_; |  | ||||||
|   bsec_library_return_t bsec_status_{BSEC_OK}; |   bsec_library_return_t bsec_status_{BSEC_OK}; | ||||||
|   int8_t bme68x_status_{BME68X_OK}; |   int8_t bme68x_status_{BME68X_OK}; | ||||||
|  |  | ||||||
|   int64_t last_time_ms_{0}; |   int64_t last_time_ms_{0}; | ||||||
|   uint32_t millis_overflow_counter_{0}; |   uint32_t millis_overflow_counter_{0}; | ||||||
|   int64_t next_call_ns_{0}; |  | ||||||
|  |  | ||||||
|   std::queue<std::function<void()>> queue_; |   std::queue<std::function<void()>> queue_; | ||||||
|  |  | ||||||
|   | |||||||
							
								
								
									
										5
									
								
								esphome/components/bytebuffer/__init__.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										5
									
								
								esphome/components/bytebuffer/__init__.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,5 @@ | |||||||
|  | CODEOWNERS = ["@clydebarrow"] | ||||||
|  |  | ||||||
|  | # Allows bytebuffer to be configured in yaml, to allow use of the C++ api. | ||||||
|  |  | ||||||
|  | CONFIG_SCHEMA = {} | ||||||
							
								
								
									
										421
									
								
								esphome/components/bytebuffer/bytebuffer.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										421
									
								
								esphome/components/bytebuffer/bytebuffer.h
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,421 @@ | |||||||
|  | #pragma once | ||||||
|  |  | ||||||
|  | #include <utility> | ||||||
|  | #include <vector> | ||||||
|  | #include <cinttypes> | ||||||
|  | #include <cstddef> | ||||||
|  | #include "esphome/core/helpers.h" | ||||||
|  |  | ||||||
|  | namespace esphome { | ||||||
|  | namespace bytebuffer { | ||||||
|  |  | ||||||
|  | enum Endian { LITTLE, BIG }; | ||||||
|  |  | ||||||
|  | /** | ||||||
|  |  * A class modelled on the Java ByteBuffer class. It wraps a vector of bytes and permits putting and getting | ||||||
|  |  * items of various sizes, with an automatically incremented position. | ||||||
|  |  * | ||||||
|  |  * There are three variables maintained pointing into the buffer: | ||||||
|  |  * | ||||||
|  |  * capacity: the maximum amount of data that can be stored - set on construction and cannot be changed | ||||||
|  |  * limit: the limit of the data currently available to get or put | ||||||
|  |  * position: the current insert or extract position | ||||||
|  |  * | ||||||
|  |  * 0 <= position <= limit <= capacity | ||||||
|  |  * | ||||||
|  |  * In addition a mark can be set to the current position with mark(). A subsequent call to reset() will restore | ||||||
|  |  * the position to the mark. | ||||||
|  |  * | ||||||
|  |  * The buffer can be marked to be little-endian (default) or big-endian. All subsequent operations will use that order. | ||||||
|  |  * | ||||||
|  |  * The flip() operation will reset the position to 0 and limit to the current position. This is useful for reading | ||||||
|  |  * data from a buffer after it has been written. | ||||||
|  |  * | ||||||
|  |  * The code is defined here in the header file rather than in a .cpp file, so that it does not get compiled if not used. | ||||||
|  |  * The templated functions ensure that only those typed functions actually used are compiled. The functions | ||||||
|  |  * are implicitly inline-able which will aid performance. | ||||||
|  |  */ | ||||||
|  | class ByteBuffer { | ||||||
|  |  public: | ||||||
|  |   // Default constructor (compatibility with TEMPLATABLE_VALUE) | ||||||
|  |   // Creates a zero-length ByteBuffer which is little use to anybody. | ||||||
|  |   ByteBuffer() : ByteBuffer(std::vector<uint8_t>()) {} | ||||||
|  |  | ||||||
|  |   /** | ||||||
|  |    * Create a new Bytebuffer with the given capacity | ||||||
|  |    */ | ||||||
|  |   ByteBuffer(size_t capacity, Endian endianness = LITTLE) | ||||||
|  |       : data_(std::vector<uint8_t>(capacity)), endianness_(endianness), limit_(capacity){}; | ||||||
|  |  | ||||||
|  |   // templated functions to implement putting and getting data of various types. There are two flavours of all | ||||||
|  |   // functions - one that uses the position as the offset, and updates the position accordingly, and one that | ||||||
|  |   // takes an explicit offset and does not update the position. | ||||||
|  |   // Separate temnplates are provided for types that fit into 32 bits and those that are bigger. These delegate | ||||||
|  |   // the actual put/get to common code based around those sizes. | ||||||
|  |   // This reduces the code size and execution time for smaller types. A similar structure for e.g. 16 bits is unlikely | ||||||
|  |   // to provide any further benefit given that all target platforms are native 32 bit. | ||||||
|  |  | ||||||
|  |   template<typename T> | ||||||
|  |   T get(typename std::enable_if<std::is_integral<T>::value, T>::type * = 0, | ||||||
|  |         typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) { | ||||||
|  |     // integral types that fit into 32 bit | ||||||
|  |     return static_cast<T>(this->get_uint32_(sizeof(T))); | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   template<typename T> | ||||||
|  |   T get(size_t offset, typename std::enable_if<std::is_integral<T>::value, T>::type * = 0, | ||||||
|  |         typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) { | ||||||
|  |     return static_cast<T>(this->get_uint32_(offset, sizeof(T))); | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   template<typename T> | ||||||
|  |   void put(const T &value, typename std::enable_if<std::is_integral<T>::value, T>::type * = 0, | ||||||
|  |            typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) { | ||||||
|  |     this->put_uint32_(static_cast<uint32_t>(value), sizeof(T)); | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   template<typename T> | ||||||
|  |   void put(const T &value, size_t offset, typename std::enable_if<std::is_integral<T>::value, T>::type * = 0, | ||||||
|  |            typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) { | ||||||
|  |     this->put_uint32_(static_cast<uint32_t>(value), offset, sizeof(T)); | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   // integral types that do not fit into 32 bit (basically only 64 bit types) | ||||||
|  |   template<typename T> | ||||||
|  |   T get(typename std::enable_if<std::is_integral<T>::value, T>::type * = 0, | ||||||
|  |         typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) { | ||||||
|  |     return static_cast<T>(this->get_uint64_(sizeof(T))); | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   template<typename T> | ||||||
|  |   T get(size_t offset, typename std::enable_if<std::is_integral<T>::value, T>::type * = 0, | ||||||
|  |         typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) { | ||||||
|  |     return static_cast<T>(this->get_uint64_(offset, sizeof(T))); | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   template<typename T> | ||||||
|  |   void put(const T &value, typename std::enable_if<std::is_integral<T>::value, T>::type * = 0, | ||||||
|  |            typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) { | ||||||
|  |     this->put_uint64_(value, sizeof(T)); | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   template<typename T> | ||||||
|  |   void put(const T &value, size_t offset, typename std::enable_if<std::is_integral<T>::value, T>::type * = 0, | ||||||
|  |            typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) { | ||||||
|  |     this->put_uint64_(static_cast<uint64_t>(value), offset, sizeof(T)); | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   // floating point types. Caters for 32 and 64 bit floating point. | ||||||
|  |   template<typename T> | ||||||
|  |   T get(typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0, | ||||||
|  |         typename std::enable_if<(sizeof(T) == sizeof(uint32_t)), T>::type * = 0) { | ||||||
|  |     return bit_cast<T>(this->get_uint32_(sizeof(T))); | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   template<typename T> | ||||||
|  |   T get(typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0, | ||||||
|  |         typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) { | ||||||
|  |     return bit_cast<T>(this->get_uint64_(sizeof(T))); | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   template<typename T> | ||||||
|  |   T get(size_t offset, typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0, | ||||||
|  |         typename std::enable_if<(sizeof(T) == sizeof(uint32_t)), T>::type * = 0) { | ||||||
|  |     return bit_cast<T>(this->get_uint32_(offset, sizeof(T))); | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   template<typename T> | ||||||
|  |   T get(size_t offset, typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0, | ||||||
|  |         typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) { | ||||||
|  |     return bit_cast<T>(this->get_uint64_(offset, sizeof(T))); | ||||||
|  |   } | ||||||
|  |   template<typename T> | ||||||
|  |   void put(const T &value, typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0, | ||||||
|  |            typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) { | ||||||
|  |     this->put_uint32_(bit_cast<uint32_t>(value), sizeof(T)); | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   template<typename T> | ||||||
|  |   void put(const T &value, typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0, | ||||||
|  |            typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) { | ||||||
|  |     this->put_uint64_(bit_cast<uint64_t>(value), sizeof(T)); | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   template<typename T> | ||||||
|  |   void put(const T &value, size_t offset, typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0, | ||||||
|  |            typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) { | ||||||
|  |     this->put_uint32_(bit_cast<uint32_t>(value), offset, sizeof(T)); | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   template<typename T> | ||||||
|  |   void put(const T &value, size_t offset, typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0, | ||||||
|  |            typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) { | ||||||
|  |     this->put_uint64_(bit_cast<uint64_t>(value), offset, sizeof(T)); | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   template<typename T> static ByteBuffer wrap(T value, Endian endianness = LITTLE) { | ||||||
|  |     ByteBuffer buffer = ByteBuffer(sizeof(T), endianness); | ||||||
|  |     buffer.put(value); | ||||||
|  |     buffer.flip(); | ||||||
|  |     return buffer; | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   static ByteBuffer wrap(std::vector<uint8_t> const &data, Endian endianness = LITTLE) { | ||||||
|  |     ByteBuffer buffer = {data}; | ||||||
|  |     buffer.endianness_ = endianness; | ||||||
|  |     return buffer; | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   static ByteBuffer wrap(const uint8_t *ptr, size_t len, Endian endianness = LITTLE) { | ||||||
|  |     return wrap(std::vector<uint8_t>(ptr, ptr + len), endianness); | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   // convenience functions with explicit types named.. | ||||||
|  |   void put_float(float value) { this->put(value); } | ||||||
|  |   void put_double(double value) { this->put(value); } | ||||||
|  |  | ||||||
|  |   uint8_t get_uint8() { return this->data_[this->position_++]; } | ||||||
|  |   // Get a 16 bit unsigned value, increment by 2 | ||||||
|  |   uint16_t get_uint16() { return this->get<uint16_t>(); } | ||||||
|  |   // Get a 24 bit unsigned value, increment by 3 | ||||||
|  |   uint32_t get_uint24() { return this->get_uint32_(3); }; | ||||||
|  |   // Get a 32 bit unsigned value, increment by 4 | ||||||
|  |   uint32_t get_uint32() { return this->get<uint32_t>(); }; | ||||||
|  |   // Get a 64 bit unsigned value, increment by 8 | ||||||
|  |   uint64_t get_uint64() { return this->get<uint64_t>(); }; | ||||||
|  |   // Signed versions of the get functions | ||||||
|  |   uint8_t get_int8() { return static_cast<int8_t>(this->get_uint8()); }; | ||||||
|  |   int16_t get_int16() { return this->get<uint16_t>(); } | ||||||
|  |   int32_t get_int32() { return this->get<int32_t>(); } | ||||||
|  |   int64_t get_int64() { return this->get<int64_t>(); } | ||||||
|  |   // Get a float value, increment by 4 | ||||||
|  |   float get_float() { return this->get<float>(); } | ||||||
|  |   // Get a double value, increment by 8 | ||||||
|  |   double get_double() { return this->get<double>(); } | ||||||
|  |  | ||||||
|  |   // Get a bool value, increment by 1 | ||||||
|  |   bool get_bool() { return static_cast<bool>(this->get_uint8()); } | ||||||
|  |  | ||||||
|  |   uint32_t get_int24(size_t offset) { | ||||||
|  |     auto value = this->get_uint24(offset); | ||||||
|  |     uint32_t mask = (~static_cast<uint32_t>(0)) << 23; | ||||||
|  |     if ((value & mask) != 0) | ||||||
|  |       value |= mask; | ||||||
|  |     return value; | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   uint32_t get_int24() { | ||||||
|  |     auto value = this->get_uint24(); | ||||||
|  |     uint32_t mask = (~static_cast<uint32_t>(0)) << 23; | ||||||
|  |     if ((value & mask) != 0) | ||||||
|  |       value |= mask; | ||||||
|  |     return value; | ||||||
|  |   } | ||||||
|  |   std::vector<uint8_t> get_vector(size_t length, size_t offset) { | ||||||
|  |     auto start = this->data_.begin() + offset; | ||||||
|  |     return {start, start + length}; | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   std::vector<uint8_t> get_vector(size_t length) { | ||||||
|  |     auto result = this->get_vector(length, this->position_); | ||||||
|  |     this->position_ += length; | ||||||
|  |     return result; | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   // Convenience named functions | ||||||
|  |   void put_uint8(uint8_t value) { this->data_[this->position_++] = value; } | ||||||
|  |   void put_uint16(uint16_t value) { this->put(value); } | ||||||
|  |   void put_uint24(uint32_t value) { this->put_uint32_(value, 3); } | ||||||
|  |   void put_uint32(uint32_t value) { this->put(value); } | ||||||
|  |   void put_uint64(uint64_t value) { this->put(value); } | ||||||
|  |   // Signed versions of the put functions | ||||||
|  |   void put_int8(int8_t value) { this->put_uint8(static_cast<uint8_t>(value)); } | ||||||
|  |   void put_int16(int16_t value) { this->put(value); } | ||||||
|  |   void put_int24(int32_t value) { this->put_uint32_(value, 3); } | ||||||
|  |   void put_int32(int32_t value) { this->put(value); } | ||||||
|  |   void put_int64(int64_t value) { this->put(value); } | ||||||
|  |   // Extra put functions | ||||||
|  |   void put_bool(bool value) { this->put_uint8(value); } | ||||||
|  |  | ||||||
|  |   // versions of the above with an offset, these do not update the position | ||||||
|  |  | ||||||
|  |   uint64_t get_uint64(size_t offset) { return this->get<uint64_t>(offset); } | ||||||
|  |   uint32_t get_uint24(size_t offset) { return this->get_uint32_(offset, 3); }; | ||||||
|  |   double get_double(size_t offset) { return get<double>(offset); } | ||||||
|  |  | ||||||
|  |   // Get one byte from the buffer, increment position by 1 | ||||||
|  |   uint8_t get_uint8(size_t offset) { return this->data_[offset]; } | ||||||
|  |   // Get a 16 bit unsigned value, increment by 2 | ||||||
|  |   uint16_t get_uint16(size_t offset) { return get<uint16_t>(offset); } | ||||||
|  |   // Get a 24 bit unsigned value, increment by 3 | ||||||
|  |   uint32_t get_uint32(size_t offset) { return this->get<uint32_t>(offset); }; | ||||||
|  |   // Get a 64 bit unsigned value, increment by 8 | ||||||
|  |   uint8_t get_int8(size_t offset) { return get<int8_t>(offset); } | ||||||
|  |   int16_t get_int16(size_t offset) { return get<int16_t>(offset); } | ||||||
|  |   int32_t get_int32(size_t offset) { return get<int32_t>(offset); } | ||||||
|  |   int64_t get_int64(size_t offset) { return get<int64_t>(offset); } | ||||||
|  |   // Get a float value, increment by 4 | ||||||
|  |   float get_float(size_t offset) { return get<float>(offset); } | ||||||
|  |   // Get a double value, increment by 8 | ||||||
|  |  | ||||||
|  |   // Get a bool value, increment by 1 | ||||||
|  |   bool get_bool(size_t offset) { return this->get_uint8(offset); } | ||||||
|  |  | ||||||
|  |   void put_uint8(uint8_t value, size_t offset) { this->data_[offset] = value; } | ||||||
|  |   void put_uint16(uint16_t value, size_t offset) { this->put(value, offset); } | ||||||
|  |   void put_uint24(uint32_t value, size_t offset) { this->put(value, offset); } | ||||||
|  |   void put_uint32(uint32_t value, size_t offset) { this->put(value, offset); } | ||||||
|  |   void put_uint64(uint64_t value, size_t offset) { this->put(value, offset); } | ||||||
|  |   // Signed versions of the put functions | ||||||
|  |   void put_int8(int8_t value, size_t offset) { this->put_uint8(static_cast<uint8_t>(value), offset); } | ||||||
|  |   void put_int16(int16_t value, size_t offset) { this->put(value, offset); } | ||||||
|  |   void put_int24(int32_t value, size_t offset) { this->put_uint32_(value, offset, 3); } | ||||||
|  |   void put_int32(int32_t value, size_t offset) { this->put(value, offset); } | ||||||
|  |   void put_int64(int64_t value, size_t offset) { this->put(value, offset); } | ||||||
|  |   // Extra put functions | ||||||
|  |   void put_float(float value, size_t offset) { this->put(value, offset); } | ||||||
|  |   void put_double(double value, size_t offset) { this->put(value, offset); } | ||||||
|  |   void put_bool(bool value, size_t offset) { this->put_uint8(value, offset); } | ||||||
|  |   void put(const std::vector<uint8_t> &value, size_t offset) { | ||||||
|  |     std::copy(value.begin(), value.end(), this->data_.begin() + offset); | ||||||
|  |   } | ||||||
|  |   void put_vector(const std::vector<uint8_t> &value, size_t offset) { this->put(value, offset); } | ||||||
|  |   void put(const std::vector<uint8_t> &value) { | ||||||
|  |     this->put_vector(value, this->position_); | ||||||
|  |     this->position_ += value.size(); | ||||||
|  |   } | ||||||
|  |   void put_vector(const std::vector<uint8_t> &value) { this->put(value); } | ||||||
|  |  | ||||||
|  |   // Getters | ||||||
|  |  | ||||||
|  |   inline size_t get_capacity() const { return this->data_.size(); } | ||||||
|  |   inline size_t get_position() const { return this->position_; } | ||||||
|  |   inline size_t get_limit() const { return this->limit_; } | ||||||
|  |   inline size_t get_remaining() const { return this->get_limit() - this->get_position(); } | ||||||
|  |   inline Endian get_endianness() const { return this->endianness_; } | ||||||
|  |   inline void mark() { this->mark_ = this->position_; } | ||||||
|  |   inline void big_endian() { this->endianness_ = BIG; } | ||||||
|  |   inline void little_endian() { this->endianness_ = LITTLE; } | ||||||
|  |   // retrieve a pointer to the underlying data. | ||||||
|  |   std::vector<uint8_t> get_data() { return this->data_; }; | ||||||
|  |  | ||||||
|  |   void get_bytes(void *dest, size_t length) { | ||||||
|  |     std::copy(this->data_.begin() + this->position_, this->data_.begin() + this->position_ + length, (uint8_t *) dest); | ||||||
|  |     this->position_ += length; | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   void get_bytes(void *dest, size_t length, size_t offset) { | ||||||
|  |     std::copy(this->data_.begin() + offset, this->data_.begin() + offset + length, (uint8_t *) dest); | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   void rewind() { this->position_ = 0; } | ||||||
|  |   void reset() { this->position_ = this->mark_; } | ||||||
|  |  | ||||||
|  |   void set_limit(size_t limit) { this->limit_ = limit; } | ||||||
|  |   void set_position(size_t position) { this->position_ = position; } | ||||||
|  |   void clear() { | ||||||
|  |     this->limit_ = this->get_capacity(); | ||||||
|  |     this->position_ = 0; | ||||||
|  |   } | ||||||
|  |   void flip() { | ||||||
|  |     this->limit_ = this->position_; | ||||||
|  |     this->position_ = 0; | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |  protected: | ||||||
|  |   uint64_t get_uint64_(size_t offset, size_t length) const { | ||||||
|  |     uint64_t value = 0; | ||||||
|  |     if (this->endianness_ == LITTLE) { | ||||||
|  |       offset += length; | ||||||
|  |       while (length-- != 0) { | ||||||
|  |         value <<= 8; | ||||||
|  |         value |= this->data_[--offset]; | ||||||
|  |       } | ||||||
|  |     } else { | ||||||
|  |       while (length-- != 0) { | ||||||
|  |         value <<= 8; | ||||||
|  |         value |= this->data_[offset++]; | ||||||
|  |       } | ||||||
|  |     } | ||||||
|  |     return value; | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   uint64_t get_uint64_(size_t length) { | ||||||
|  |     auto result = this->get_uint64_(this->position_, length); | ||||||
|  |     this->position_ += length; | ||||||
|  |     return result; | ||||||
|  |   } | ||||||
|  |   uint32_t get_uint32_(size_t offset, size_t length) const { | ||||||
|  |     uint32_t value = 0; | ||||||
|  |     if (this->endianness_ == LITTLE) { | ||||||
|  |       offset += length; | ||||||
|  |       while (length-- != 0) { | ||||||
|  |         value <<= 8; | ||||||
|  |         value |= this->data_[--offset]; | ||||||
|  |       } | ||||||
|  |     } else { | ||||||
|  |       while (length-- != 0) { | ||||||
|  |         value <<= 8; | ||||||
|  |         value |= this->data_[offset++]; | ||||||
|  |       } | ||||||
|  |     } | ||||||
|  |     return value; | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   uint32_t get_uint32_(size_t length) { | ||||||
|  |     auto result = this->get_uint32_(this->position_, length); | ||||||
|  |     this->position_ += length; | ||||||
|  |     return result; | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   /// Putters | ||||||
|  |  | ||||||
|  |   void put_uint64_(uint64_t value, size_t length) { | ||||||
|  |     this->put_uint64_(value, this->position_, length); | ||||||
|  |     this->position_ += length; | ||||||
|  |   } | ||||||
|  |   void put_uint32_(uint32_t value, size_t length) { | ||||||
|  |     this->put_uint32_(value, this->position_, length); | ||||||
|  |     this->position_ += length; | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   void put_uint64_(uint64_t value, size_t offset, size_t length) { | ||||||
|  |     if (this->endianness_ == LITTLE) { | ||||||
|  |       while (length-- != 0) { | ||||||
|  |         this->data_[offset++] = static_cast<uint8_t>(value); | ||||||
|  |         value >>= 8; | ||||||
|  |       } | ||||||
|  |     } else { | ||||||
|  |       offset += length; | ||||||
|  |       while (length-- != 0) { | ||||||
|  |         this->data_[--offset] = static_cast<uint8_t>(value); | ||||||
|  |         value >>= 8; | ||||||
|  |       } | ||||||
|  |     } | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   void put_uint32_(uint32_t value, size_t offset, size_t length) { | ||||||
|  |     if (this->endianness_ == LITTLE) { | ||||||
|  |       while (length-- != 0) { | ||||||
|  |         this->data_[offset++] = static_cast<uint8_t>(value); | ||||||
|  |         value >>= 8; | ||||||
|  |       } | ||||||
|  |     } else { | ||||||
|  |       offset += length; | ||||||
|  |       while (length-- != 0) { | ||||||
|  |         this->data_[--offset] = static_cast<uint8_t>(value); | ||||||
|  |         value >>= 8; | ||||||
|  |       } | ||||||
|  |     } | ||||||
|  |   } | ||||||
|  |   ByteBuffer(std::vector<uint8_t> const &data) : data_(data), limit_(data.size()) {} | ||||||
|  |  | ||||||
|  |   std::vector<uint8_t> data_; | ||||||
|  |   Endian endianness_{LITTLE}; | ||||||
|  |   size_t position_{0}; | ||||||
|  |   size_t mark_{0}; | ||||||
|  |   size_t limit_{0}; | ||||||
|  | }; | ||||||
|  |  | ||||||
|  | }  // namespace bytebuffer | ||||||
|  | }  // namespace esphome | ||||||
| @@ -119,10 +119,21 @@ visual_temperature = cv.float_with_unit( | |||||||
| ) | ) | ||||||
|  |  | ||||||
|  |  | ||||||
| def single_visual_temperature(value): | VISUAL_TEMPERATURE_STEP_SCHEMA = cv.Schema( | ||||||
|     if isinstance(value, dict): |     { | ||||||
|         return value |         cv.Required(CONF_TARGET_TEMPERATURE): visual_temperature, | ||||||
|  |         cv.Required(CONF_CURRENT_TEMPERATURE): visual_temperature, | ||||||
|  |     } | ||||||
|  | ) | ||||||
|  |  | ||||||
|  |  | ||||||
|  | def visual_temperature_step(value): | ||||||
|  |  | ||||||
|  |     # Allow defining target/current temperature steps separately | ||||||
|  |     if isinstance(value, dict): | ||||||
|  |         return VISUAL_TEMPERATURE_STEP_SCHEMA(value) | ||||||
|  |  | ||||||
|  |     # Otherwise, use the single value for both properties | ||||||
|     value = visual_temperature(value) |     value = visual_temperature(value) | ||||||
|     return VISUAL_TEMPERATURE_STEP_SCHEMA( |     return VISUAL_TEMPERATURE_STEP_SCHEMA( | ||||||
|         { |         { | ||||||
| @@ -141,16 +152,6 @@ ControlTrigger = climate_ns.class_( | |||||||
|     "ControlTrigger", automation.Trigger.template(ClimateCall.operator("ref")) |     "ControlTrigger", automation.Trigger.template(ClimateCall.operator("ref")) | ||||||
| ) | ) | ||||||
|  |  | ||||||
| VISUAL_TEMPERATURE_STEP_SCHEMA = cv.Any( |  | ||||||
|     single_visual_temperature, |  | ||||||
|     cv.Schema( |  | ||||||
|         { |  | ||||||
|             cv.Required(CONF_TARGET_TEMPERATURE): visual_temperature, |  | ||||||
|             cv.Required(CONF_CURRENT_TEMPERATURE): visual_temperature, |  | ||||||
|         } |  | ||||||
|     ), |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| CLIMATE_SCHEMA = ( | CLIMATE_SCHEMA = ( | ||||||
|     cv.ENTITY_BASE_SCHEMA.extend(web_server.WEBSERVER_SORTING_SCHEMA) |     cv.ENTITY_BASE_SCHEMA.extend(web_server.WEBSERVER_SORTING_SCHEMA) | ||||||
|     .extend(cv.MQTT_COMMAND_COMPONENT_SCHEMA) |     .extend(cv.MQTT_COMMAND_COMPONENT_SCHEMA) | ||||||
| @@ -162,7 +163,7 @@ CLIMATE_SCHEMA = ( | |||||||
|                 { |                 { | ||||||
|                     cv.Optional(CONF_MIN_TEMPERATURE): cv.temperature, |                     cv.Optional(CONF_MIN_TEMPERATURE): cv.temperature, | ||||||
|                     cv.Optional(CONF_MAX_TEMPERATURE): cv.temperature, |                     cv.Optional(CONF_MAX_TEMPERATURE): cv.temperature, | ||||||
|                     cv.Optional(CONF_TEMPERATURE_STEP): VISUAL_TEMPERATURE_STEP_SCHEMA, |                     cv.Optional(CONF_TEMPERATURE_STEP): visual_temperature_step, | ||||||
|                     cv.Optional(CONF_MIN_HUMIDITY): cv.percentage_int, |                     cv.Optional(CONF_MIN_HUMIDITY): cv.percentage_int, | ||||||
|                     cv.Optional(CONF_MAX_HUMIDITY): cv.percentage_int, |                     cv.Optional(CONF_MAX_HUMIDITY): cv.percentage_int, | ||||||
|                 } |                 } | ||||||
|   | |||||||
| @@ -43,7 +43,7 @@ bool CSE7766Component::check_byte_() { | |||||||
|   uint8_t index = this->raw_data_index_; |   uint8_t index = this->raw_data_index_; | ||||||
|   uint8_t byte = this->raw_data_[index]; |   uint8_t byte = this->raw_data_[index]; | ||||||
|   if (index == 0) { |   if (index == 0) { | ||||||
|     return !((byte != 0x55) && ((byte & 0xF0) != 0xF0) && (byte != 0xAA)); |     return (byte == 0x55) || ((byte & 0xF0) == 0xF0) || (byte == 0xAA); | ||||||
|   } |   } | ||||||
|  |  | ||||||
|   if (index == 1) { |   if (index == 1) { | ||||||
|   | |||||||
| @@ -70,8 +70,6 @@ def _validate_time_present(config): | |||||||
|  |  | ||||||
|  |  | ||||||
| _DATETIME_SCHEMA = cv.ENTITY_BASE_SCHEMA.extend( | _DATETIME_SCHEMA = cv.ENTITY_BASE_SCHEMA.extend( | ||||||
|     web_server.WEBSERVER_SORTING_SCHEMA, |  | ||||||
|     cv.MQTT_COMMAND_COMPONENT_SCHEMA, |  | ||||||
|     cv.Schema( |     cv.Schema( | ||||||
|         { |         { | ||||||
|             cv.Optional(CONF_ON_VALUE): automation.validate_automation( |             cv.Optional(CONF_ON_VALUE): automation.validate_automation( | ||||||
| @@ -81,7 +79,9 @@ _DATETIME_SCHEMA = cv.ENTITY_BASE_SCHEMA.extend( | |||||||
|             ), |             ), | ||||||
|             cv.Optional(CONF_TIME_ID): cv.use_id(time.RealTimeClock), |             cv.Optional(CONF_TIME_ID): cv.use_id(time.RealTimeClock), | ||||||
|         } |         } | ||||||
|     ), |     ) | ||||||
|  |     .extend(web_server.WEBSERVER_SORTING_SCHEMA) | ||||||
|  |     .extend(cv.MQTT_COMMAND_COMPONENT_SCHEMA) | ||||||
| ).add_extra(_validate_time_present) | ).add_extra(_validate_time_present) | ||||||
|  |  | ||||||
|  |  | ||||||
|   | |||||||
| @@ -60,9 +60,7 @@ ESPTime DateTimeEntity::state_as_esptime() const { | |||||||
|   obj.hour = this->hour_; |   obj.hour = this->hour_; | ||||||
|   obj.minute = this->minute_; |   obj.minute = this->minute_; | ||||||
|   obj.second = this->second_; |   obj.second = this->second_; | ||||||
|   obj.day_of_week = 1;  // Required to be valid for recalc_timestamp_local but not used. |   obj.recalc_timestamp_local(); | ||||||
|   obj.day_of_year = 1;  // Required to be valid for recalc_timestamp_local but not used. |  | ||||||
|   obj.recalc_timestamp_local(false); |  | ||||||
|   return obj; |   return obj; | ||||||
| } | } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -52,11 +52,11 @@ void DeepSleepComponent::dump_config_platform_() { | |||||||
|  |  | ||||||
| bool DeepSleepComponent::prepare_to_sleep_() { | bool DeepSleepComponent::prepare_to_sleep_() { | ||||||
|   if (this->wakeup_pin_mode_ == WAKEUP_PIN_MODE_KEEP_AWAKE && this->wakeup_pin_ != nullptr && |   if (this->wakeup_pin_mode_ == WAKEUP_PIN_MODE_KEEP_AWAKE && this->wakeup_pin_ != nullptr && | ||||||
|       !this->sleep_duration_.has_value() && this->wakeup_pin_->digital_read()) { |       this->wakeup_pin_->digital_read()) { | ||||||
|     // Defer deep sleep until inactive |     // Defer deep sleep until inactive | ||||||
|     if (!this->next_enter_deep_sleep_) { |     if (!this->next_enter_deep_sleep_) { | ||||||
|       this->status_set_warning(); |       this->status_set_warning(); | ||||||
|       ESP_LOGW(TAG, "Waiting for pin_ to switch state to enter deep sleep..."); |       ESP_LOGW(TAG, "Waiting wakeup pin state change to enter deep sleep..."); | ||||||
|     } |     } | ||||||
|     this->next_enter_deep_sleep_ = true; |     this->next_enter_deep_sleep_ = true; | ||||||
|     return false; |     return false; | ||||||
|   | |||||||
| @@ -6,7 +6,104 @@ namespace dfplayer { | |||||||
|  |  | ||||||
| static const char *const TAG = "dfplayer"; | static const char *const TAG = "dfplayer"; | ||||||
|  |  | ||||||
|  | void DFPlayer::next() { | ||||||
|  |   this->ack_set_is_playing_ = true; | ||||||
|  |   ESP_LOGD(TAG, "Playing next track"); | ||||||
|  |   this->send_cmd_(0x01); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | void DFPlayer::previous() { | ||||||
|  |   this->ack_set_is_playing_ = true; | ||||||
|  |   ESP_LOGD(TAG, "Playing previous track"); | ||||||
|  |   this->send_cmd_(0x02); | ||||||
|  | } | ||||||
|  | void DFPlayer::play_mp3(uint16_t file) { | ||||||
|  |   this->ack_set_is_playing_ = true; | ||||||
|  |   ESP_LOGD(TAG, "Playing file %d in mp3 folder", file); | ||||||
|  |   this->send_cmd_(0x12, file); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | void DFPlayer::play_file(uint16_t file) { | ||||||
|  |   this->ack_set_is_playing_ = true; | ||||||
|  |   ESP_LOGD(TAG, "Playing file %d", file); | ||||||
|  |   this->send_cmd_(0x03, file); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | void DFPlayer::play_file_loop(uint16_t file) { | ||||||
|  |   this->ack_set_is_playing_ = true; | ||||||
|  |   ESP_LOGD(TAG, "Playing file %d in loop", file); | ||||||
|  |   this->send_cmd_(0x08, file); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | void DFPlayer::play_folder_loop(uint16_t folder) { | ||||||
|  |   this->ack_set_is_playing_ = true; | ||||||
|  |   ESP_LOGD(TAG, "Playing folder %d in loop", folder); | ||||||
|  |   this->send_cmd_(0x17, folder); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | void DFPlayer::volume_up() { | ||||||
|  |   ESP_LOGD(TAG, "Increasing volume"); | ||||||
|  |   this->send_cmd_(0x04); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | void DFPlayer::volume_down() { | ||||||
|  |   ESP_LOGD(TAG, "Decreasing volume"); | ||||||
|  |   this->send_cmd_(0x05); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | void DFPlayer::set_device(Device device) { | ||||||
|  |   ESP_LOGD(TAG, "Setting device to %d", device); | ||||||
|  |   this->send_cmd_(0x09, device); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | void DFPlayer::set_volume(uint8_t volume) { | ||||||
|  |   ESP_LOGD(TAG, "Setting volume to %d", volume); | ||||||
|  |   this->send_cmd_(0x06, volume); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | void DFPlayer::set_eq(EqPreset preset) { | ||||||
|  |   ESP_LOGD(TAG, "Setting EQ to %d", preset); | ||||||
|  |   this->send_cmd_(0x07, preset); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | void DFPlayer::sleep() { | ||||||
|  |   this->ack_reset_is_playing_ = true; | ||||||
|  |   ESP_LOGD(TAG, "Putting DFPlayer to sleep"); | ||||||
|  |   this->send_cmd_(0x0A); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | void DFPlayer::reset() { | ||||||
|  |   this->ack_reset_is_playing_ = true; | ||||||
|  |   ESP_LOGD(TAG, "Resetting DFPlayer"); | ||||||
|  |   this->send_cmd_(0x0C); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | void DFPlayer::start() { | ||||||
|  |   this->ack_set_is_playing_ = true; | ||||||
|  |   ESP_LOGD(TAG, "Starting playback"); | ||||||
|  |   this->send_cmd_(0x0D); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | void DFPlayer::pause() { | ||||||
|  |   this->ack_reset_is_playing_ = true; | ||||||
|  |   ESP_LOGD(TAG, "Pausing playback"); | ||||||
|  |   this->send_cmd_(0x0E); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | void DFPlayer::stop() { | ||||||
|  |   this->ack_reset_is_playing_ = true; | ||||||
|  |   ESP_LOGD(TAG, "Stopping playback"); | ||||||
|  |   this->send_cmd_(0x16); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | void DFPlayer::random() { | ||||||
|  |   this->ack_set_is_playing_ = true; | ||||||
|  |   ESP_LOGD(TAG, "Playing random file"); | ||||||
|  |   this->send_cmd_(0x18); | ||||||
|  | } | ||||||
|  |  | ||||||
| void DFPlayer::play_folder(uint16_t folder, uint16_t file) { | void DFPlayer::play_folder(uint16_t folder, uint16_t file) { | ||||||
|  |   ESP_LOGD(TAG, "Playing file %d in folder %d", file, folder); | ||||||
|   if (folder < 100 && file < 256) { |   if (folder < 100 && file < 256) { | ||||||
|     this->ack_set_is_playing_ = true; |     this->ack_set_is_playing_ = true; | ||||||
|     this->send_cmd_(0x0F, (uint8_t) folder, (uint8_t) file); |     this->send_cmd_(0x0F, (uint8_t) folder, (uint8_t) file); | ||||||
| @@ -29,7 +126,7 @@ void DFPlayer::send_cmd_(uint8_t cmd, uint16_t argument) { | |||||||
|  |  | ||||||
|   this->sent_cmd_ = cmd; |   this->sent_cmd_ = cmd; | ||||||
|  |  | ||||||
|   ESP_LOGD(TAG, "Send Command %#02x arg %#04x", cmd, argument); |   ESP_LOGV(TAG, "Send Command %#02x arg %#04x", cmd, argument); | ||||||
|   this->write_array(buffer, 10); |   this->write_array(buffer, 10); | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -101,9 +198,37 @@ void DFPlayer::loop() { | |||||||
|             ESP_LOGV(TAG, "Nack"); |             ESP_LOGV(TAG, "Nack"); | ||||||
|             this->ack_set_is_playing_ = false; |             this->ack_set_is_playing_ = false; | ||||||
|             this->ack_reset_is_playing_ = false; |             this->ack_reset_is_playing_ = false; | ||||||
|             if (argument == 6) { |             switch (argument) { | ||||||
|               ESP_LOGV(TAG, "File not found"); |               case 0x01: | ||||||
|               this->is_playing_ = false; |                 ESP_LOGE(TAG, "Module is busy or uninitialized"); | ||||||
|  |                 break; | ||||||
|  |               case 0x02: | ||||||
|  |                 ESP_LOGE(TAG, "Module is in sleep mode"); | ||||||
|  |                 break; | ||||||
|  |               case 0x03: | ||||||
|  |                 ESP_LOGE(TAG, "Serial receive error"); | ||||||
|  |                 break; | ||||||
|  |               case 0x04: | ||||||
|  |                 ESP_LOGE(TAG, "Checksum incorrect"); | ||||||
|  |                 break; | ||||||
|  |               case 0x05: | ||||||
|  |                 ESP_LOGE(TAG, "Specified track is out of current track scope"); | ||||||
|  |                 this->is_playing_ = false; | ||||||
|  |                 break; | ||||||
|  |               case 0x06: | ||||||
|  |                 ESP_LOGE(TAG, "Specified track is not found"); | ||||||
|  |                 this->is_playing_ = false; | ||||||
|  |                 break; | ||||||
|  |               case 0x07: | ||||||
|  |                 ESP_LOGE(TAG, "Insertion error (an inserting operation only can be done when a track is being played)"); | ||||||
|  |                 break; | ||||||
|  |               case 0x08: | ||||||
|  |                 ESP_LOGE(TAG, "SD card reading failed (SD card pulled out or damaged)"); | ||||||
|  |                 break; | ||||||
|  |               case 0x09: | ||||||
|  |                 ESP_LOGE(TAG, "Entered into sleep mode"); | ||||||
|  |                 this->is_playing_ = false; | ||||||
|  |                 break; | ||||||
|             } |             } | ||||||
|             break; |             break; | ||||||
|           case 0x41: |           case 0x41: | ||||||
| @@ -113,12 +238,13 @@ void DFPlayer::loop() { | |||||||
|             this->ack_set_is_playing_ = false; |             this->ack_set_is_playing_ = false; | ||||||
|             this->ack_reset_is_playing_ = false; |             this->ack_reset_is_playing_ = false; | ||||||
|             break; |             break; | ||||||
|           case 0x3D:  // Playback finished |           case 0x3D: | ||||||
|  |             ESP_LOGV(TAG, "Playback finished"); | ||||||
|             this->is_playing_ = false; |             this->is_playing_ = false; | ||||||
|             this->on_finished_playback_callback_.call(); |             this->on_finished_playback_callback_.call(); | ||||||
|             break; |             break; | ||||||
|           default: |           default: | ||||||
|             ESP_LOGD(TAG, "Command %#02x arg %#04x", cmd, argument); |             ESP_LOGV(TAG, "Received unknown cmd %#02x arg %#04x", cmd, argument); | ||||||
|         } |         } | ||||||
|         this->sent_cmd_ = 0; |         this->sent_cmd_ = 0; | ||||||
|         this->read_pos_ = 0; |         this->read_pos_ = 0; | ||||||
|   | |||||||
| @@ -23,64 +23,30 @@ enum Device { | |||||||
|   TF_CARD = 2, |   TF_CARD = 2, | ||||||
| }; | }; | ||||||
|  |  | ||||||
|  | // See the datasheet here: | ||||||
|  | // https://github.com/DFRobot/DFRobotDFPlayerMini/blob/master/doc/FN-M16P%2BEmbedded%2BMP3%2BAudio%2BModule%2BDatasheet.pdf | ||||||
| class DFPlayer : public uart::UARTDevice, public Component { | class DFPlayer : public uart::UARTDevice, public Component { | ||||||
|  public: |  public: | ||||||
|   void loop() override; |   void loop() override; | ||||||
|  |  | ||||||
|   void next() { |   void next(); | ||||||
|     this->ack_set_is_playing_ = true; |   void previous(); | ||||||
|     this->send_cmd_(0x01); |   void play_mp3(uint16_t file); | ||||||
|   } |   void play_file(uint16_t file); | ||||||
|   void previous() { |   void play_file_loop(uint16_t file); | ||||||
|     this->ack_set_is_playing_ = true; |  | ||||||
|     this->send_cmd_(0x02); |  | ||||||
|   } |  | ||||||
|   void play_mp3(uint16_t file) { |  | ||||||
|     this->ack_set_is_playing_ = true; |  | ||||||
|     this->send_cmd_(0x12, file); |  | ||||||
|   } |  | ||||||
|   void play_file(uint16_t file) { |  | ||||||
|     this->ack_set_is_playing_ = true; |  | ||||||
|     this->send_cmd_(0x03, file); |  | ||||||
|   } |  | ||||||
|   void play_file_loop(uint16_t file) { |  | ||||||
|     this->ack_set_is_playing_ = true; |  | ||||||
|     this->send_cmd_(0x08, file); |  | ||||||
|   } |  | ||||||
|   void play_folder(uint16_t folder, uint16_t file); |   void play_folder(uint16_t folder, uint16_t file); | ||||||
|   void play_folder_loop(uint16_t folder) { |   void play_folder_loop(uint16_t folder); | ||||||
|     this->ack_set_is_playing_ = true; |   void volume_up(); | ||||||
|     this->send_cmd_(0x17, folder); |   void volume_down(); | ||||||
|   } |   void set_device(Device device); | ||||||
|   void volume_up() { this->send_cmd_(0x04); } |   void set_volume(uint8_t volume); | ||||||
|   void volume_down() { this->send_cmd_(0x05); } |   void set_eq(EqPreset preset); | ||||||
|   void set_device(Device device) { this->send_cmd_(0x09, device); } |   void sleep(); | ||||||
|   void set_volume(uint8_t volume) { this->send_cmd_(0x06, volume); } |   void reset(); | ||||||
|   void set_eq(EqPreset preset) { this->send_cmd_(0x07, preset); } |   void start(); | ||||||
|   void sleep() { |   void pause(); | ||||||
|     this->ack_reset_is_playing_ = true; |   void stop(); | ||||||
|     this->send_cmd_(0x0A); |   void random(); | ||||||
|   } |  | ||||||
|   void reset() { |  | ||||||
|     this->ack_reset_is_playing_ = true; |  | ||||||
|     this->send_cmd_(0x0C); |  | ||||||
|   } |  | ||||||
|   void start() { |  | ||||||
|     this->ack_set_is_playing_ = true; |  | ||||||
|     this->send_cmd_(0x0D); |  | ||||||
|   } |  | ||||||
|   void pause() { |  | ||||||
|     this->ack_reset_is_playing_ = true; |  | ||||||
|     this->send_cmd_(0x0E); |  | ||||||
|   } |  | ||||||
|   void stop() { |  | ||||||
|     this->ack_reset_is_playing_ = true; |  | ||||||
|     this->send_cmd_(0x16); |  | ||||||
|   } |  | ||||||
|   void random() { |  | ||||||
|     this->ack_set_is_playing_ = true; |  | ||||||
|     this->send_cmd_(0x18); |  | ||||||
|   } |  | ||||||
|  |  | ||||||
|   bool is_playing() { return is_playing_; } |   bool is_playing() { return is_playing_; } | ||||||
|   void dump_config() override; |   void dump_config() override; | ||||||
|   | |||||||
| @@ -135,7 +135,8 @@ bool HOT IRAM_ATTR DHT::read_sensor_(float *temperature, float *humidity, bool r | |||||||
|  |  | ||||||
|       // Wait for falling edge |       // Wait for falling edge | ||||||
|       while (this->pin_->digital_read()) { |       while (this->pin_->digital_read()) { | ||||||
|         if ((end_time = micros()) - start_time > 90) { |         end_time = micros(); | ||||||
|  |         if (end_time - start_time > 90) { | ||||||
|           if (i < 0) { |           if (i < 0) { | ||||||
|             error_code = 3; |             error_code = 3; | ||||||
|           } else { |           } else { | ||||||
|   | |||||||
| @@ -68,8 +68,6 @@ IsActiveCondition = display_menu_base_ns.class_( | |||||||
|     "IsActiveCondition", automation.Condition |     "IsActiveCondition", automation.Condition | ||||||
| ) | ) | ||||||
|  |  | ||||||
| MULTI_CONF = True |  | ||||||
|  |  | ||||||
| MenuItemType = display_menu_base_ns.enum("MenuItemType") | MenuItemType = display_menu_base_ns.enum("MenuItemType") | ||||||
|  |  | ||||||
| MENU_ITEM_TYPES = { | MENU_ITEM_TYPES = { | ||||||
|   | |||||||
| @@ -280,7 +280,7 @@ bool DisplayMenuComponent::cursor_down_() { | |||||||
| bool DisplayMenuComponent::enter_menu_() { | bool DisplayMenuComponent::enter_menu_() { | ||||||
|   this->displayed_item_->on_leave(); |   this->displayed_item_->on_leave(); | ||||||
|   this->displayed_item_ = static_cast<MenuItemMenu *>(this->get_selected_item_()); |   this->displayed_item_ = static_cast<MenuItemMenu *>(this->get_selected_item_()); | ||||||
|   this->selection_stack_.push_front({this->top_index_, this->cursor_index_}); |   this->selection_stack_.emplace_front(this->top_index_, this->cursor_index_); | ||||||
|   this->cursor_index_ = this->top_index_ = 0; |   this->cursor_index_ = this->top_index_ = 0; | ||||||
|   this->displayed_item_->on_enter(); |   this->displayed_item_->on_enter(); | ||||||
|  |  | ||||||
|   | |||||||
| @@ -296,7 +296,7 @@ void Dsmr::dump_config() { | |||||||
| } | } | ||||||
|  |  | ||||||
| void Dsmr::set_decryption_key(const std::string &decryption_key) { | void Dsmr::set_decryption_key(const std::string &decryption_key) { | ||||||
|   if (decryption_key.length() == 0) { |   if (decryption_key.empty()) { | ||||||
|     ESP_LOGI(TAG, "Disabling decryption"); |     ESP_LOGI(TAG, "Disabling decryption"); | ||||||
|     this->decryption_key_.clear(); |     this->decryption_key_.clear(); | ||||||
|     if (this->crypt_telegram_ != nullptr) { |     if (this->crypt_telegram_ != nullptr) { | ||||||
|   | |||||||
							
								
								
									
										0
									
								
								esphome/components/es8311/__init__.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										0
									
								
								esphome/components/es8311/__init__.py
									
									
									
									
									
										Normal file
									
								
							
							
								
								
									
										70
									
								
								esphome/components/es8311/audio_dac.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										70
									
								
								esphome/components/es8311/audio_dac.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,70 @@ | |||||||
|  | import esphome.codegen as cg | ||||||
|  | from esphome.components import i2c | ||||||
|  | from esphome.components.audio_dac import AudioDac | ||||||
|  | import esphome.config_validation as cv | ||||||
|  | from esphome.const import CONF_BITS_PER_SAMPLE, CONF_ID, CONF_SAMPLE_RATE | ||||||
|  |  | ||||||
|  | CODEOWNERS = ["@kroimon", "@kahrendt"] | ||||||
|  | DEPENDENCIES = ["i2c"] | ||||||
|  |  | ||||||
|  | es8311_ns = cg.esphome_ns.namespace("es8311") | ||||||
|  | ES8311 = es8311_ns.class_("ES8311", AudioDac, cg.Component, i2c.I2CDevice) | ||||||
|  |  | ||||||
|  | CONF_MIC_GAIN = "mic_gain" | ||||||
|  | CONF_USE_MCLK = "use_mclk" | ||||||
|  | CONF_USE_MICROPHONE = "use_microphone" | ||||||
|  |  | ||||||
|  | es8311_resolution = es8311_ns.enum("ES8311Resolution") | ||||||
|  | ES8311_BITS_PER_SAMPLE_ENUM = { | ||||||
|  |     16: es8311_resolution.ES8311_RESOLUTION_16, | ||||||
|  |     24: es8311_resolution.ES8311_RESOLUTION_24, | ||||||
|  |     32: es8311_resolution.ES8311_RESOLUTION_32, | ||||||
|  | } | ||||||
|  |  | ||||||
|  | es8311_mic_gain = es8311_ns.enum("ES8311MicGain") | ||||||
|  | ES8311_MIC_GAIN_ENUM = { | ||||||
|  |     "MIN": es8311_mic_gain.ES8311_MIC_GAIN_MIN, | ||||||
|  |     "0DB": es8311_mic_gain.ES8311_MIC_GAIN_0DB, | ||||||
|  |     "6DB": es8311_mic_gain.ES8311_MIC_GAIN_6DB, | ||||||
|  |     "12DB": es8311_mic_gain.ES8311_MIC_GAIN_12DB, | ||||||
|  |     "18DB": es8311_mic_gain.ES8311_MIC_GAIN_18DB, | ||||||
|  |     "24DB": es8311_mic_gain.ES8311_MIC_GAIN_24DB, | ||||||
|  |     "30DB": es8311_mic_gain.ES8311_MIC_GAIN_30DB, | ||||||
|  |     "36DB": es8311_mic_gain.ES8311_MIC_GAIN_36DB, | ||||||
|  |     "42DB": es8311_mic_gain.ES8311_MIC_GAIN_42DB, | ||||||
|  |     "MAX": es8311_mic_gain.ES8311_MIC_GAIN_MAX, | ||||||
|  | } | ||||||
|  |  | ||||||
|  |  | ||||||
|  | _validate_bits = cv.float_with_unit("bits", "bit") | ||||||
|  |  | ||||||
|  | CONFIG_SCHEMA = ( | ||||||
|  |     cv.Schema( | ||||||
|  |         { | ||||||
|  |             cv.GenerateID(): cv.declare_id(ES8311), | ||||||
|  |             cv.Optional(CONF_BITS_PER_SAMPLE, default="16bit"): cv.All( | ||||||
|  |                 _validate_bits, cv.enum(ES8311_BITS_PER_SAMPLE_ENUM) | ||||||
|  |             ), | ||||||
|  |             cv.Optional(CONF_MIC_GAIN, default="42DB"): cv.enum( | ||||||
|  |                 ES8311_MIC_GAIN_ENUM, upper=True | ||||||
|  |             ), | ||||||
|  |             cv.Optional(CONF_SAMPLE_RATE, default=16000): cv.int_range(min=1), | ||||||
|  |             cv.Optional(CONF_USE_MCLK, default=True): cv.boolean, | ||||||
|  |             cv.Optional(CONF_USE_MICROPHONE, default=False): cv.boolean, | ||||||
|  |         } | ||||||
|  |     ) | ||||||
|  |     .extend(cv.COMPONENT_SCHEMA) | ||||||
|  |     .extend(i2c.i2c_device_schema(0x18)) | ||||||
|  | ) | ||||||
|  |  | ||||||
|  |  | ||||||
|  | async def to_code(config): | ||||||
|  |     var = cg.new_Pvariable(config[CONF_ID]) | ||||||
|  |     await cg.register_component(var, config) | ||||||
|  |     await i2c.register_i2c_device(var, config) | ||||||
|  |  | ||||||
|  |     cg.add(var.set_bits_per_sample(config[CONF_BITS_PER_SAMPLE])) | ||||||
|  |     cg.add(var.set_mic_gain(config[CONF_MIC_GAIN])) | ||||||
|  |     cg.add(var.set_sample_frequency(config[CONF_SAMPLE_RATE])) | ||||||
|  |     cg.add(var.set_use_mclk(config[CONF_USE_MCLK])) | ||||||
|  |     cg.add(var.set_use_mic(config[CONF_USE_MICROPHONE])) | ||||||
							
								
								
									
										227
									
								
								esphome/components/es8311/es8311.cpp
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										227
									
								
								esphome/components/es8311/es8311.cpp
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,227 @@ | |||||||
|  | #include "es8311.h" | ||||||
|  | #include "es8311_const.h" | ||||||
|  | #include "esphome/core/hal.h" | ||||||
|  | #include "esphome/core/log.h" | ||||||
|  | #include <cinttypes> | ||||||
|  |  | ||||||
|  | namespace esphome { | ||||||
|  | namespace es8311 { | ||||||
|  |  | ||||||
|  | static const char *const TAG = "es8311"; | ||||||
|  |  | ||||||
|  | // Mark the component as failed; use only in setup | ||||||
|  | #define ES8311_ERROR_FAILED(func) \ | ||||||
|  |   if (!(func)) { \ | ||||||
|  |     this->mark_failed(); \ | ||||||
|  |     return; \ | ||||||
|  |   } | ||||||
|  | // Return false; use outside of setup | ||||||
|  | #define ES8311_ERROR_CHECK(func) \ | ||||||
|  |   if (!(func)) { \ | ||||||
|  |     return false; \ | ||||||
|  |   } | ||||||
|  |  | ||||||
|  | void ES8311::setup() { | ||||||
|  |   ESP_LOGCONFIG(TAG, "Setting up ES8311..."); | ||||||
|  |  | ||||||
|  |   // Reset | ||||||
|  |   ES8311_ERROR_FAILED(this->write_byte(ES8311_REG00_RESET, 0x1F)); | ||||||
|  |   ES8311_ERROR_FAILED(this->write_byte(ES8311_REG00_RESET, 0x00)); | ||||||
|  |  | ||||||
|  |   ES8311_ERROR_FAILED(this->configure_clock_()); | ||||||
|  |   ES8311_ERROR_FAILED(this->configure_format_()); | ||||||
|  |   ES8311_ERROR_FAILED(this->configure_mic_()); | ||||||
|  |  | ||||||
|  |   // Set initial volume | ||||||
|  |   this->set_volume(0.75);  // 0.75 = 0xBF = 0dB | ||||||
|  |  | ||||||
|  |   // Power up analog circuitry | ||||||
|  |   ES8311_ERROR_FAILED(this->write_byte(ES8311_REG0D_SYSTEM, 0x01)); | ||||||
|  |   // Enable analog PGA, enable ADC modulator | ||||||
|  |   ES8311_ERROR_FAILED(this->write_byte(ES8311_REG0E_SYSTEM, 0x02)); | ||||||
|  |   // Power up DAC | ||||||
|  |   ES8311_ERROR_FAILED(this->write_byte(ES8311_REG12_SYSTEM, 0x00)); | ||||||
|  |   // Enable output to HP drive | ||||||
|  |   ES8311_ERROR_FAILED(this->write_byte(ES8311_REG13_SYSTEM, 0x10)); | ||||||
|  |   // ADC Equalizer bypass, cancel DC offset in digital domain | ||||||
|  |   ES8311_ERROR_FAILED(this->write_byte(ES8311_REG1C_ADC, 0x6A)); | ||||||
|  |   // Bypass DAC equalizer | ||||||
|  |   ES8311_ERROR_FAILED(this->write_byte(ES8311_REG37_DAC, 0x08)); | ||||||
|  |   // Power On | ||||||
|  |   ES8311_ERROR_FAILED(this->write_byte(ES8311_REG00_RESET, 0x80)); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | void ES8311::dump_config() { | ||||||
|  |   ESP_LOGCONFIG(TAG, "ES8311 Audio Codec:"); | ||||||
|  |   ESP_LOGCONFIG(TAG, "  Use MCLK: %s", YESNO(this->use_mclk_)); | ||||||
|  |   ESP_LOGCONFIG(TAG, "  Use Microphone: %s", YESNO(this->use_mic_)); | ||||||
|  |   ESP_LOGCONFIG(TAG, "  DAC Bits per Sample: %" PRIu8, this->resolution_out_); | ||||||
|  |   ESP_LOGCONFIG(TAG, "  Sample Rate: %" PRIu32, this->sample_frequency_); | ||||||
|  |  | ||||||
|  |   if (this->is_failed()) { | ||||||
|  |     ESP_LOGCONFIG(TAG, "  Failed to initialize!"); | ||||||
|  |     return; | ||||||
|  |   } | ||||||
|  | } | ||||||
|  |  | ||||||
|  | bool ES8311::set_volume(float volume) { | ||||||
|  |   volume = clamp(volume, 0.0f, 1.0f); | ||||||
|  |   uint8_t reg32 = remap<uint8_t, float>(volume, 0.0f, 1.0f, 0, 255); | ||||||
|  |   return this->write_byte(ES8311_REG32_DAC, reg32); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | float ES8311::volume() { | ||||||
|  |   uint8_t reg32; | ||||||
|  |   this->read_byte(ES8311_REG32_DAC, ®32); | ||||||
|  |   return remap<float, uint8_t>(reg32, 0, 255, 0.0f, 1.0f); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | uint8_t ES8311::calculate_resolution_value(ES8311Resolution resolution) { | ||||||
|  |   switch (resolution) { | ||||||
|  |     case ES8311_RESOLUTION_16: | ||||||
|  |       return (3 << 2); | ||||||
|  |     case ES8311_RESOLUTION_18: | ||||||
|  |       return (2 << 2); | ||||||
|  |     case ES8311_RESOLUTION_20: | ||||||
|  |       return (1 << 2); | ||||||
|  |     case ES8311_RESOLUTION_24: | ||||||
|  |       return (0 << 2); | ||||||
|  |     case ES8311_RESOLUTION_32: | ||||||
|  |       return (4 << 2); | ||||||
|  |     default: | ||||||
|  |       return 0; | ||||||
|  |   } | ||||||
|  | } | ||||||
|  |  | ||||||
|  | const ES8311Coefficient *ES8311::get_coefficient(uint32_t mclk, uint32_t rate) { | ||||||
|  |   for (const auto &coefficient : ES8311_COEFFICIENTS) { | ||||||
|  |     if (coefficient.mclk == mclk && coefficient.rate == rate) | ||||||
|  |       return &coefficient; | ||||||
|  |   } | ||||||
|  |   return nullptr; | ||||||
|  | } | ||||||
|  |  | ||||||
|  | bool ES8311::configure_clock_() { | ||||||
|  |   // Register 0x01: select clock source for internal MCLK and determine its frequency | ||||||
|  |   uint8_t reg01 = 0x3F;  // Enable all clocks | ||||||
|  |  | ||||||
|  |   uint32_t mclk_frequency = this->sample_frequency_ * this->mclk_multiple_; | ||||||
|  |   if (!this->use_mclk_) { | ||||||
|  |     reg01 |= BIT(7);  // Use SCLK | ||||||
|  |     mclk_frequency = this->sample_frequency_ * (int) this->resolution_out_ * 2; | ||||||
|  |   } | ||||||
|  |   if (this->mclk_inverted_) { | ||||||
|  |     reg01 |= BIT(6);  // Invert MCLK pin | ||||||
|  |   } | ||||||
|  |   ES8311_ERROR_CHECK(this->write_byte(ES8311_REG01_CLK_MANAGER, reg01)); | ||||||
|  |  | ||||||
|  |   // Get clock coefficients from coefficient table | ||||||
|  |   auto *coefficient = get_coefficient(mclk_frequency, this->sample_frequency_); | ||||||
|  |   if (coefficient == nullptr) { | ||||||
|  |     ESP_LOGE(TAG, "Unable to configure sample rate %" PRIu32 "Hz with %" PRIu32 "Hz MCLK", this->sample_frequency_, | ||||||
|  |              mclk_frequency); | ||||||
|  |     return false; | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   // Register 0x02 | ||||||
|  |   uint8_t reg02; | ||||||
|  |   ES8311_ERROR_CHECK(this->read_byte(ES8311_REG02_CLK_MANAGER, ®02)); | ||||||
|  |   reg02 &= 0x07; | ||||||
|  |   reg02 |= (coefficient->pre_div - 1) << 5; | ||||||
|  |   reg02 |= coefficient->pre_mult << 3; | ||||||
|  |   ES8311_ERROR_CHECK(this->write_byte(ES8311_REG02_CLK_MANAGER, reg02)); | ||||||
|  |  | ||||||
|  |   // Register 0x03 | ||||||
|  |   const uint8_t reg03 = (coefficient->fs_mode << 6) | coefficient->adc_osr; | ||||||
|  |   ES8311_ERROR_CHECK(this->write_byte(ES8311_REG03_CLK_MANAGER, reg03)); | ||||||
|  |  | ||||||
|  |   // Register 0x04 | ||||||
|  |   ES8311_ERROR_CHECK(this->write_byte(ES8311_REG04_CLK_MANAGER, coefficient->dac_osr)); | ||||||
|  |  | ||||||
|  |   // Register 0x05 | ||||||
|  |   const uint8_t reg05 = ((coefficient->adc_div - 1) << 4) | (coefficient->dac_div - 1); | ||||||
|  |   ES8311_ERROR_CHECK(this->write_byte(ES8311_REG05_CLK_MANAGER, reg05)); | ||||||
|  |  | ||||||
|  |   // Register 0x06 | ||||||
|  |   uint8_t reg06; | ||||||
|  |   ES8311_ERROR_CHECK(this->read_byte(ES8311_REG06_CLK_MANAGER, ®06)); | ||||||
|  |   if (this->sclk_inverted_) { | ||||||
|  |     reg06 |= BIT(5); | ||||||
|  |   } else { | ||||||
|  |     reg06 &= ~BIT(5); | ||||||
|  |   } | ||||||
|  |   reg06 &= 0xE0; | ||||||
|  |   if (coefficient->bclk_div < 19) { | ||||||
|  |     reg06 |= (coefficient->bclk_div - 1) << 0; | ||||||
|  |   } else { | ||||||
|  |     reg06 |= (coefficient->bclk_div) << 0; | ||||||
|  |   } | ||||||
|  |   ES8311_ERROR_CHECK(this->write_byte(ES8311_REG06_CLK_MANAGER, reg06)); | ||||||
|  |  | ||||||
|  |   // Register 0x07 | ||||||
|  |   uint8_t reg07; | ||||||
|  |   ES8311_ERROR_CHECK(this->read_byte(ES8311_REG07_CLK_MANAGER, ®07)); | ||||||
|  |   reg07 &= 0xC0; | ||||||
|  |   reg07 |= coefficient->lrck_h << 0; | ||||||
|  |   ES8311_ERROR_CHECK(this->write_byte(ES8311_REG07_CLK_MANAGER, reg07)); | ||||||
|  |  | ||||||
|  |   // Register 0x08 | ||||||
|  |   ES8311_ERROR_CHECK(this->write_byte(ES8311_REG08_CLK_MANAGER, coefficient->lrck_l)); | ||||||
|  |  | ||||||
|  |   // Successfully configured the clock | ||||||
|  |   return true; | ||||||
|  | } | ||||||
|  |  | ||||||
|  | bool ES8311::configure_format_() { | ||||||
|  |   // Configure I2S mode and format | ||||||
|  |   uint8_t reg00; | ||||||
|  |   ES8311_ERROR_CHECK(this->read_byte(ES8311_REG00_RESET, ®00)); | ||||||
|  |   reg00 &= 0xBF; | ||||||
|  |   ES8311_ERROR_CHECK(this->write_byte(ES8311_REG00_RESET, reg00)); | ||||||
|  |  | ||||||
|  |   // Configure SDP in resolution | ||||||
|  |   uint8_t reg09 = calculate_resolution_value(this->resolution_in_); | ||||||
|  |   ES8311_ERROR_CHECK(this->write_byte(ES8311_REG09_SDPIN, reg09)); | ||||||
|  |  | ||||||
|  |   // Configure SDP out resolution | ||||||
|  |   uint8_t reg0a = calculate_resolution_value(this->resolution_out_); | ||||||
|  |   ES8311_ERROR_CHECK(this->write_byte(ES8311_REG0A_SDPOUT, reg0a)); | ||||||
|  |  | ||||||
|  |   // Successfully configured the format | ||||||
|  |   return true; | ||||||
|  | } | ||||||
|  |  | ||||||
|  | bool ES8311::configure_mic_() { | ||||||
|  |   uint8_t reg14 = 0x1A;  // Enable analog MIC and max PGA gain | ||||||
|  |   if (this->use_mic_) { | ||||||
|  |     reg14 |= BIT(6);  // Enable PDM digital microphone | ||||||
|  |   } | ||||||
|  |   ES8311_ERROR_CHECK(this->write_byte(ES8311_REG14_SYSTEM, reg14)); | ||||||
|  |  | ||||||
|  |   ES8311_ERROR_CHECK(this->write_byte(ES8311_REG16_ADC, this->mic_gain_));  // ADC gain scale up | ||||||
|  |   ES8311_ERROR_CHECK(this->write_byte(ES8311_REG17_ADC, 0xC8));             // Set ADC gain | ||||||
|  |  | ||||||
|  |   // Successfully configured the microphones | ||||||
|  |   return true; | ||||||
|  | } | ||||||
|  |  | ||||||
|  | bool ES8311::set_mute_state_(bool mute_state) { | ||||||
|  |   uint8_t reg31; | ||||||
|  |  | ||||||
|  |   this->is_muted_ = mute_state; | ||||||
|  |  | ||||||
|  |   if (!this->read_byte(ES8311_REG31_DAC, ®31)) { | ||||||
|  |     return false; | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   if (mute_state) { | ||||||
|  |     reg31 |= BIT(6) | BIT(5); | ||||||
|  |   } else { | ||||||
|  |     reg31 &= ~(BIT(6) | BIT(5)); | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   return this->write_byte(ES8311_REG31_DAC, reg31); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | }  // namespace es8311 | ||||||
|  | }  // namespace esphome | ||||||
							
								
								
									
										135
									
								
								esphome/components/es8311/es8311.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										135
									
								
								esphome/components/es8311/es8311.h
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,135 @@ | |||||||
|  | #pragma once | ||||||
|  |  | ||||||
|  | #include "esphome/components/audio_dac/audio_dac.h" | ||||||
|  | #include "esphome/components/i2c/i2c.h" | ||||||
|  | #include "esphome/core/component.h" | ||||||
|  |  | ||||||
|  | namespace esphome { | ||||||
|  | namespace es8311 { | ||||||
|  |  | ||||||
|  | enum ES8311MicGain { | ||||||
|  |   ES8311_MIC_GAIN_MIN = -1, | ||||||
|  |   ES8311_MIC_GAIN_0DB, | ||||||
|  |   ES8311_MIC_GAIN_6DB, | ||||||
|  |   ES8311_MIC_GAIN_12DB, | ||||||
|  |   ES8311_MIC_GAIN_18DB, | ||||||
|  |   ES8311_MIC_GAIN_24DB, | ||||||
|  |   ES8311_MIC_GAIN_30DB, | ||||||
|  |   ES8311_MIC_GAIN_36DB, | ||||||
|  |   ES8311_MIC_GAIN_42DB, | ||||||
|  |   ES8311_MIC_GAIN_MAX | ||||||
|  | }; | ||||||
|  |  | ||||||
|  | enum ES8311Resolution : uint8_t { | ||||||
|  |   ES8311_RESOLUTION_16 = 16, | ||||||
|  |   ES8311_RESOLUTION_18 = 18, | ||||||
|  |   ES8311_RESOLUTION_20 = 20, | ||||||
|  |   ES8311_RESOLUTION_24 = 24, | ||||||
|  |   ES8311_RESOLUTION_32 = 32 | ||||||
|  | }; | ||||||
|  |  | ||||||
|  | struct ES8311Coefficient { | ||||||
|  |   uint32_t mclk;     // mclk frequency | ||||||
|  |   uint32_t rate;     // sample rate | ||||||
|  |   uint8_t pre_div;   // the pre divider with range from 1 to 8 | ||||||
|  |   uint8_t pre_mult;  // the pre multiplier with x1, x2, x4 and x8 selection | ||||||
|  |   uint8_t adc_div;   // adcclk divider | ||||||
|  |   uint8_t dac_div;   // dacclk divider | ||||||
|  |   uint8_t fs_mode;   // single speed (0) or double speed (1) | ||||||
|  |   uint8_t lrck_h;    // adc lrck divider and dac lrck divider | ||||||
|  |   uint8_t lrck_l;    // | ||||||
|  |   uint8_t bclk_div;  // sclk divider | ||||||
|  |   uint8_t adc_osr;   // adc osr | ||||||
|  |   uint8_t dac_osr;   // dac osr | ||||||
|  | }; | ||||||
|  |  | ||||||
|  | class ES8311 : public audio_dac::AudioDac, public Component, public i2c::I2CDevice { | ||||||
|  |  public: | ||||||
|  |   ///////////////////////// | ||||||
|  |   // Component overrides // | ||||||
|  |   ///////////////////////// | ||||||
|  |  | ||||||
|  |   void setup() override; | ||||||
|  |   float get_setup_priority() const override { return setup_priority::DATA; } | ||||||
|  |   void dump_config() override; | ||||||
|  |  | ||||||
|  |   //////////////////////// | ||||||
|  |   // AudioDac overrides // | ||||||
|  |   //////////////////////// | ||||||
|  |  | ||||||
|  |   /// @brief Writes the volume out to the DAC | ||||||
|  |   /// @param volume floating point between 0.0 and 1.0 | ||||||
|  |   /// @return True if successful and false otherwise | ||||||
|  |   bool set_volume(float volume) override; | ||||||
|  |  | ||||||
|  |   /// @brief Gets the current volume out from the DAC | ||||||
|  |   /// @return floating point between 0.0 and 1.0 | ||||||
|  |   float volume() override; | ||||||
|  |  | ||||||
|  |   /// @brief Disables mute for audio out | ||||||
|  |   /// @return True if successful and false otherwise | ||||||
|  |   bool set_mute_off() override { return this->set_mute_state_(false); } | ||||||
|  |  | ||||||
|  |   /// @brief Enables mute for audio out | ||||||
|  |   /// @return True if successful and false otherwise | ||||||
|  |   bool set_mute_on() override { return this->set_mute_state_(true); } | ||||||
|  |  | ||||||
|  |   bool is_muted() override { return this->is_muted_; } | ||||||
|  |  | ||||||
|  |   ////////////////////////////////// | ||||||
|  |   // ES8311 configuration setters // | ||||||
|  |   ////////////////////////////////// | ||||||
|  |  | ||||||
|  |   void set_use_mclk(bool use_mclk) { this->use_mclk_ = use_mclk; } | ||||||
|  |   void set_bits_per_sample(ES8311Resolution resolution) { | ||||||
|  |     this->resolution_in_ = resolution; | ||||||
|  |     this->resolution_out_ = resolution; | ||||||
|  |   } | ||||||
|  |   void set_sample_frequency(uint32_t sample_frequency) { this->sample_frequency_ = sample_frequency; } | ||||||
|  |   void set_use_mic(bool use_mic) { this->use_mic_ = use_mic; } | ||||||
|  |   void set_mic_gain(ES8311MicGain mic_gain) { this->mic_gain_ = mic_gain; } | ||||||
|  |  | ||||||
|  |  protected: | ||||||
|  |   /// @brief Computes the register value for the configured resolution (bits per sample) | ||||||
|  |   /// @param resolution bits per sample enum for both audio in and audio out | ||||||
|  |   /// @return register value | ||||||
|  |   static uint8_t calculate_resolution_value(ES8311Resolution resolution); | ||||||
|  |  | ||||||
|  |   /// @brief Retrieves the appropriate registers values for the configured mclk and rate | ||||||
|  |   /// @param mclk mlck frequency in Hz | ||||||
|  |   /// @param rate sample rate frequency in Hz | ||||||
|  |   /// @return ES8311Coeffecient containing appropriate register values to configure the ES8311 or nullptr if impossible | ||||||
|  |   static const ES8311Coefficient *get_coefficient(uint32_t mclk, uint32_t rate); | ||||||
|  |  | ||||||
|  |   /// @brief Configures the ES8311 registers for the chosen sample rate | ||||||
|  |   /// @return True if successful and false otherwise | ||||||
|  |   bool configure_clock_(); | ||||||
|  |  | ||||||
|  |   /// @brief Configures the ES8311 registers for the chosen bits per sample | ||||||
|  |   /// @return True if successful and false otherwise | ||||||
|  |   bool configure_format_(); | ||||||
|  |  | ||||||
|  |   /// @brief Configures the ES8311 microphone registers | ||||||
|  |   /// @return True if successful and false otherwise | ||||||
|  |   bool configure_mic_(); | ||||||
|  |  | ||||||
|  |   /// @brief Mutes or unmute the DAC audio out | ||||||
|  |   /// @param mute_state True to mute, false to unmute | ||||||
|  |   /// @return | ||||||
|  |   bool set_mute_state_(bool mute_state); | ||||||
|  |  | ||||||
|  |   bool use_mic_; | ||||||
|  |   ES8311MicGain mic_gain_; | ||||||
|  |  | ||||||
|  |   bool use_mclk_;                // true = use dedicated MCLK pin, false = use SCLK | ||||||
|  |   bool sclk_inverted_{false};    // SCLK is inverted | ||||||
|  |   bool mclk_inverted_{false};    // MCLK is inverted (ignored if use_mclk_ == false) | ||||||
|  |   uint32_t mclk_multiple_{256};  // MCLK frequency is sample rate * mclk_multiple_ (ignored if use_mclk_ == false) | ||||||
|  |  | ||||||
|  |   uint32_t sample_frequency_;  // in Hz | ||||||
|  |   ES8311Resolution resolution_in_; | ||||||
|  |   ES8311Resolution resolution_out_; | ||||||
|  | }; | ||||||
|  |  | ||||||
|  | }  // namespace es8311 | ||||||
|  | }  // namespace esphome | ||||||
							
								
								
									
										195
									
								
								esphome/components/es8311/es8311_const.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										195
									
								
								esphome/components/es8311/es8311_const.h
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,195 @@ | |||||||
|  | #pragma once | ||||||
|  |  | ||||||
|  | #include "es8311.h" | ||||||
|  |  | ||||||
|  | namespace esphome { | ||||||
|  | namespace es8311 { | ||||||
|  |  | ||||||
|  | // ES8311 register addresses | ||||||
|  | static const uint8_t ES8311_REG00_RESET = 0x00;        // Reset | ||||||
|  | static const uint8_t ES8311_REG01_CLK_MANAGER = 0x01;  // Clock Manager: select clk src for mclk, enable clock for codec | ||||||
|  | static const uint8_t ES8311_REG02_CLK_MANAGER = 0x02;  // Clock Manager: clk divider and clk multiplier | ||||||
|  | static const uint8_t ES8311_REG03_CLK_MANAGER = 0x03;  // Clock Manager: adc fsmode and osr | ||||||
|  | static const uint8_t ES8311_REG04_CLK_MANAGER = 0x04;  // Clock Manager: dac osr | ||||||
|  | static const uint8_t ES8311_REG05_CLK_MANAGER = 0x05;  // Clock Manager: clk divider for adc and dac | ||||||
|  | static const uint8_t ES8311_REG06_CLK_MANAGER = 0x06;  // Clock Manager: bclk inverter BIT(5) and divider | ||||||
|  | static const uint8_t ES8311_REG07_CLK_MANAGER = 0x07;  // Clock Manager: tri-state, lrck divider | ||||||
|  | static const uint8_t ES8311_REG08_CLK_MANAGER = 0x08;  // Clock Manager: lrck divider | ||||||
|  | static const uint8_t ES8311_REG09_SDPIN = 0x09;        // Serial Digital Port: DAC | ||||||
|  | static const uint8_t ES8311_REG0A_SDPOUT = 0x0A;       // Serial Digital Port: ADC | ||||||
|  | static const uint8_t ES8311_REG0B_SYSTEM = 0x0B;       // System | ||||||
|  | static const uint8_t ES8311_REG0C_SYSTEM = 0x0C;       // System | ||||||
|  | static const uint8_t ES8311_REG0D_SYSTEM = 0x0D;       // System: power up/down | ||||||
|  | static const uint8_t ES8311_REG0E_SYSTEM = 0x0E;       // System: power up/down | ||||||
|  | static const uint8_t ES8311_REG0F_SYSTEM = 0x0F;       // System: low power | ||||||
|  | static const uint8_t ES8311_REG10_SYSTEM = 0x10;       // System | ||||||
|  | static const uint8_t ES8311_REG11_SYSTEM = 0x11;       // System | ||||||
|  | static const uint8_t ES8311_REG12_SYSTEM = 0x12;       // System: Enable DAC | ||||||
|  | static const uint8_t ES8311_REG13_SYSTEM = 0x13;       // System | ||||||
|  | static const uint8_t ES8311_REG14_SYSTEM = 0x14;       // System: select DMIC, select analog pga gain | ||||||
|  | static const uint8_t ES8311_REG15_ADC = 0x15;          // ADC: adc ramp rate, dmic sense | ||||||
|  | static const uint8_t ES8311_REG16_ADC = 0x16;          // ADC | ||||||
|  | static const uint8_t ES8311_REG17_ADC = 0x17;          // ADC: volume | ||||||
|  | static const uint8_t ES8311_REG18_ADC = 0x18;          // ADC: alc enable and winsize | ||||||
|  | static const uint8_t ES8311_REG19_ADC = 0x19;          // ADC: alc maxlevel | ||||||
|  | static const uint8_t ES8311_REG1A_ADC = 0x1A;          // ADC: alc automute | ||||||
|  | static const uint8_t ES8311_REG1B_ADC = 0x1B;          // ADC: alc automute, adc hpf s1 | ||||||
|  | static const uint8_t ES8311_REG1C_ADC = 0x1C;          // ADC: equalizer, hpf s2 | ||||||
|  | static const uint8_t ES8311_REG1D_ADCEQ = 0x1D;        // ADCEQ: equalizer B0 | ||||||
|  | static const uint8_t ES8311_REG1E_ADCEQ = 0x1E;        // ADCEQ: equalizer B0 | ||||||
|  | static const uint8_t ES8311_REG1F_ADCEQ = 0x1F;        // ADCEQ: equalizer B0 | ||||||
|  | static const uint8_t ES8311_REG20_ADCEQ = 0x20;        // ADCEQ: equalizer B0 | ||||||
|  | static const uint8_t ES8311_REG21_ADCEQ = 0x21;        // ADCEQ: equalizer A1 | ||||||
|  | static const uint8_t ES8311_REG22_ADCEQ = 0x22;        // ADCEQ: equalizer A1 | ||||||
|  | static const uint8_t ES8311_REG23_ADCEQ = 0x23;        // ADCEQ: equalizer A1 | ||||||
|  | static const uint8_t ES8311_REG24_ADCEQ = 0x24;        // ADCEQ: equalizer A1 | ||||||
|  | static const uint8_t ES8311_REG25_ADCEQ = 0x25;        // ADCEQ: equalizer A2 | ||||||
|  | static const uint8_t ES8311_REG26_ADCEQ = 0x26;        // ADCEQ: equalizer A2 | ||||||
|  | static const uint8_t ES8311_REG27_ADCEQ = 0x27;        // ADCEQ: equalizer A2 | ||||||
|  | static const uint8_t ES8311_REG28_ADCEQ = 0x28;        // ADCEQ: equalizer A2 | ||||||
|  | static const uint8_t ES8311_REG29_ADCEQ = 0x29;        // ADCEQ: equalizer B1 | ||||||
|  | static const uint8_t ES8311_REG2A_ADCEQ = 0x2A;        // ADCEQ: equalizer B1 | ||||||
|  | static const uint8_t ES8311_REG2B_ADCEQ = 0x2B;        // ADCEQ: equalizer B1 | ||||||
|  | static const uint8_t ES8311_REG2C_ADCEQ = 0x2C;        // ADCEQ: equalizer B1 | ||||||
|  | static const uint8_t ES8311_REG2D_ADCEQ = 0x2D;        // ADCEQ: equalizer B2 | ||||||
|  | static const uint8_t ES8311_REG2E_ADCEQ = 0x2E;        // ADCEQ: equalizer B2 | ||||||
|  | static const uint8_t ES8311_REG2F_ADCEQ = 0x2F;        // ADCEQ: equalizer B2 | ||||||
|  | static const uint8_t ES8311_REG30_ADCEQ = 0x30;        // ADCEQ: equalizer B2 | ||||||
|  | static const uint8_t ES8311_REG31_DAC = 0x31;          // DAC: mute | ||||||
|  | static const uint8_t ES8311_REG32_DAC = 0x32;          // DAC: volume | ||||||
|  | static const uint8_t ES8311_REG33_DAC = 0x33;          // DAC: offset | ||||||
|  | static const uint8_t ES8311_REG34_DAC = 0x34;          // DAC: drc enable, drc winsize | ||||||
|  | static const uint8_t ES8311_REG35_DAC = 0x35;          // DAC: drc maxlevel, minilevel | ||||||
|  | static const uint8_t ES8311_REG36_DAC = 0x36;          // DAC | ||||||
|  | static const uint8_t ES8311_REG37_DAC = 0x37;          // DAC: ramprate | ||||||
|  | static const uint8_t ES8311_REG38_DACEQ = 0x38;        // DACEQ: equalizer B0 | ||||||
|  | static const uint8_t ES8311_REG39_DACEQ = 0x39;        // DACEQ: equalizer B0 | ||||||
|  | static const uint8_t ES8311_REG3A_DACEQ = 0x3A;        // DACEQ: equalizer B0 | ||||||
|  | static const uint8_t ES8311_REG3B_DACEQ = 0x3B;        // DACEQ: equalizer B0 | ||||||
|  | static const uint8_t ES8311_REG3C_DACEQ = 0x3C;        // DACEQ: equalizer B1 | ||||||
|  | static const uint8_t ES8311_REG3D_DACEQ = 0x3D;        // DACEQ: equalizer B1 | ||||||
|  | static const uint8_t ES8311_REG3E_DACEQ = 0x3E;        // DACEQ: equalizer B1 | ||||||
|  | static const uint8_t ES8311_REG3F_DACEQ = 0x3F;        // DACEQ: equalizer B1 | ||||||
|  | static const uint8_t ES8311_REG40_DACEQ = 0x40;        // DACEQ: equalizer A1 | ||||||
|  | static const uint8_t ES8311_REG41_DACEQ = 0x41;        // DACEQ: equalizer A1 | ||||||
|  | static const uint8_t ES8311_REG42_DACEQ = 0x42;        // DACEQ: equalizer A1 | ||||||
|  | static const uint8_t ES8311_REG43_DACEQ = 0x43;        // DACEQ: equalizer A1 | ||||||
|  | static const uint8_t ES8311_REG44_GPIO = 0x44;         // GPIO: dac2adc for test | ||||||
|  | static const uint8_t ES8311_REG45_GP = 0x45;           // GPIO: GP control | ||||||
|  | static const uint8_t ES8311_REGFA_I2C = 0xFA;          // I2C: reset registers | ||||||
|  | static const uint8_t ES8311_REGFC_FLAG = 0xFC;         // Flag | ||||||
|  | static const uint8_t ES8311_REGFD_CHD1 = 0xFD;         // Chip: ID1 | ||||||
|  | static const uint8_t ES8311_REGFE_CHD2 = 0xFE;         // Chip: ID2 | ||||||
|  | static const uint8_t ES8311_REGFF_CHVER = 0xFF;        // Chip: Version | ||||||
|  |  | ||||||
|  | // ES8311 clock divider coefficients | ||||||
|  | static const ES8311Coefficient ES8311_COEFFICIENTS[] = { | ||||||
|  |     // clang-format off | ||||||
|  |  | ||||||
|  |   //   mclk,  rate, pre_  pre_  adc_  dac_  fs_   lrck  lrck bclk_  adc_  dac_ | ||||||
|  |   //                 div, mult,  div,  div, mode,   _h,   _l,  div,  osr,  osr | ||||||
|  |  | ||||||
|  |   // 8k | ||||||
|  |   {12288000,  8000, 0x06, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   {18432000,  8000, 0x03, 0x02, 0x03, 0x03, 0x00, 0x05, 0xff, 0x18, 0x10, 0x20}, | ||||||
|  |   {16384000,  8000, 0x08, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 8192000,  8000, 0x04, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 6144000,  8000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 4096000,  8000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 3072000,  8000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 2048000,  8000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 1536000,  8000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 1024000,  8000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |  | ||||||
|  |   // 11.025k | ||||||
|  |   {11289600, 11025, 0x04, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 5644800, 11025, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 2822400, 11025, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 1411200, 11025, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |  | ||||||
|  |   // 12k | ||||||
|  |   {12288000, 12000, 0x04, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 6144000, 12000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 3072000, 12000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 1536000, 12000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |  | ||||||
|  |   // 16k | ||||||
|  |   {12288000, 16000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   {18432000, 16000, 0x03, 0x02, 0x03, 0x03, 0x00, 0x02, 0xff, 0x0c, 0x10, 0x20}, | ||||||
|  |   {16384000, 16000, 0x04, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 8192000, 16000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 6144000, 16000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 4096000, 16000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 3072000, 16000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 2048000, 16000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 1536000, 16000, 0x03, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |   { 1024000, 16000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20}, | ||||||
|  |  | ||||||
|  |   // 22.05k | ||||||
|  |   {11289600, 22050, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 5644800, 22050, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 2822400, 22050, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 1411200, 22050, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |  | ||||||
|  |   // 24k | ||||||
|  |   {12288000, 24000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   {18432000, 24000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 6144000, 24000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 3072000, 24000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 1536000, 24000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |  | ||||||
|  |   // 32k | ||||||
|  |   {12288000, 32000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   {18432000, 32000, 0x03, 0x04, 0x03, 0x03, 0x00, 0x02, 0xff, 0x0c, 0x10, 0x10}, | ||||||
|  |   {16384000, 32000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 8192000, 32000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 6144000, 32000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 4096000, 32000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 3072000, 32000, 0x03, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 2048000, 32000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 1536000, 32000, 0x03, 0x08, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10}, | ||||||
|  |   { 1024000, 32000, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |  | ||||||
|  |   // 44.1k | ||||||
|  |   {11289600, 44100, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 5644800, 44100, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 2822400, 44100, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 1411200, 44100, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |  | ||||||
|  |   // 48k | ||||||
|  |   {12288000, 48000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   {18432000, 48000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 6144000, 48000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 3072000, 48000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 1536000, 48000, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |  | ||||||
|  |   // 64k | ||||||
|  |   {12288000, 64000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   {18432000, 64000, 0x03, 0x04, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10}, | ||||||
|  |   {16384000, 64000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 8192000, 64000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 6144000, 64000, 0x01, 0x04, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10}, | ||||||
|  |   { 4096000, 64000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 3072000, 64000, 0x01, 0x08, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10}, | ||||||
|  |   { 2048000, 64000, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 1536000, 64000, 0x01, 0x08, 0x01, 0x01, 0x01, 0x00, 0xbf, 0x03, 0x18, 0x18}, | ||||||
|  |   { 1024000, 64000, 0x01, 0x08, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10}, | ||||||
|  |  | ||||||
|  |   // 88.2k | ||||||
|  |   {11289600, 88200, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 5644800, 88200, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 2822400, 88200, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 1411200, 88200, 0x01, 0x08, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10}, | ||||||
|  |  | ||||||
|  |   // 96k | ||||||
|  |   {12288000, 96000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   {18432000, 96000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 6144000, 96000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 3072000, 96000, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, | ||||||
|  |   { 1536000, 96000, 0x01, 0x08, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10}, | ||||||
|  |  | ||||||
|  |     // clang-format on | ||||||
|  | }; | ||||||
|  |  | ||||||
|  | }  // namespace es8311 | ||||||
|  | }  // namespace esphome | ||||||
| @@ -67,8 +67,10 @@ def _translate_pin(value): | |||||||
|             "This variable only supports pin numbers, not full pin schemas " |             "This variable only supports pin numbers, not full pin schemas " | ||||||
|             "(with inverted and mode)." |             "(with inverted and mode)." | ||||||
|         ) |         ) | ||||||
|     if isinstance(value, int): |     if isinstance(value, int) and not isinstance(value, bool): | ||||||
|         return value |         return value | ||||||
|  |     if not isinstance(value, str): | ||||||
|  |         raise cv.Invalid(f"Invalid pin number: {value}") | ||||||
|     try: |     try: | ||||||
|         return int(value) |         return int(value) | ||||||
|     except ValueError: |     except ValueError: | ||||||
|   | |||||||
| @@ -34,7 +34,7 @@ ESPBTUUID ESPBTUUID::from_raw(const uint8_t *data) { | |||||||
| ESPBTUUID ESPBTUUID::from_raw_reversed(const uint8_t *data) { | ESPBTUUID ESPBTUUID::from_raw_reversed(const uint8_t *data) { | ||||||
|   ESPBTUUID ret; |   ESPBTUUID ret; | ||||||
|   ret.uuid_.len = ESP_UUID_LEN_128; |   ret.uuid_.len = ESP_UUID_LEN_128; | ||||||
|   for (int i = 0; i < ESP_UUID_LEN_128; i++) |   for (uint8_t i = 0; i < ESP_UUID_LEN_128; i++) | ||||||
|     ret.uuid_.uuid.uuid128[ESP_UUID_LEN_128 - 1 - i] = data[i]; |     ret.uuid_.uuid.uuid128[ESP_UUID_LEN_128 - 1 - i] = data[i]; | ||||||
|   return ret; |   return ret; | ||||||
| } | } | ||||||
| @@ -43,30 +43,30 @@ ESPBTUUID ESPBTUUID::from_raw(const std::string &data) { | |||||||
|   if (data.length() == 4) { |   if (data.length() == 4) { | ||||||
|     ret.uuid_.len = ESP_UUID_LEN_16; |     ret.uuid_.len = ESP_UUID_LEN_16; | ||||||
|     ret.uuid_.uuid.uuid16 = 0; |     ret.uuid_.uuid.uuid16 = 0; | ||||||
|     for (int i = 0; i < data.length();) { |     for (uint i = 0; i < data.length(); i += 2) { | ||||||
|       uint8_t msb = data.c_str()[i]; |       uint8_t msb = data.c_str()[i]; | ||||||
|       uint8_t lsb = data.c_str()[i + 1]; |       uint8_t lsb = data.c_str()[i + 1]; | ||||||
|  |       uint8_t lsb_shift = i <= 2 ? (2 - i) * 4 : 0; | ||||||
|  |  | ||||||
|       if (msb > '9') |       if (msb > '9') | ||||||
|         msb -= 7; |         msb -= 7; | ||||||
|       if (lsb > '9') |       if (lsb > '9') | ||||||
|         lsb -= 7; |         lsb -= 7; | ||||||
|       ret.uuid_.uuid.uuid16 += (((msb & 0x0F) << 4) | (lsb & 0x0F)) << (2 - i) * 4; |       ret.uuid_.uuid.uuid16 += (((msb & 0x0F) << 4) | (lsb & 0x0F)) << lsb_shift; | ||||||
|       i += 2; |  | ||||||
|     } |     } | ||||||
|   } else if (data.length() == 8) { |   } else if (data.length() == 8) { | ||||||
|     ret.uuid_.len = ESP_UUID_LEN_32; |     ret.uuid_.len = ESP_UUID_LEN_32; | ||||||
|     ret.uuid_.uuid.uuid32 = 0; |     ret.uuid_.uuid.uuid32 = 0; | ||||||
|     for (int i = 0; i < data.length();) { |     for (uint i = 0; i < data.length(); i += 2) { | ||||||
|       uint8_t msb = data.c_str()[i]; |       uint8_t msb = data.c_str()[i]; | ||||||
|       uint8_t lsb = data.c_str()[i + 1]; |       uint8_t lsb = data.c_str()[i + 1]; | ||||||
|  |       uint8_t lsb_shift = i <= 6 ? (6 - i) * 4 : 0; | ||||||
|  |  | ||||||
|       if (msb > '9') |       if (msb > '9') | ||||||
|         msb -= 7; |         msb -= 7; | ||||||
|       if (lsb > '9') |       if (lsb > '9') | ||||||
|         lsb -= 7; |         lsb -= 7; | ||||||
|       ret.uuid_.uuid.uuid32 += (((msb & 0x0F) << 4) | (lsb & 0x0F)) << (6 - i) * 4; |       ret.uuid_.uuid.uuid32 += (((msb & 0x0F) << 4) | (lsb & 0x0F)) << lsb_shift; | ||||||
|       i += 2; |  | ||||||
|     } |     } | ||||||
|   } else if (data.length() == 16) {  // how we can have 16 byte length string reprezenting 128 bit uuid??? needs to be |   } else if (data.length() == 16) {  // how we can have 16 byte length string reprezenting 128 bit uuid??? needs to be | ||||||
|                                      // investigated (lack of time) |                                      // investigated (lack of time) | ||||||
| @@ -77,7 +77,7 @@ ESPBTUUID ESPBTUUID::from_raw(const std::string &data) { | |||||||
|     // UUID format. |     // UUID format. | ||||||
|     ret.uuid_.len = ESP_UUID_LEN_128; |     ret.uuid_.len = ESP_UUID_LEN_128; | ||||||
|     int n = 0; |     int n = 0; | ||||||
|     for (int i = 0; i < data.length();) { |     for (uint i = 0; i < data.length(); i += 2) { | ||||||
|       if (data.c_str()[i] == '-') |       if (data.c_str()[i] == '-') | ||||||
|         i++; |         i++; | ||||||
|       uint8_t msb = data.c_str()[i]; |       uint8_t msb = data.c_str()[i]; | ||||||
| @@ -88,7 +88,6 @@ ESPBTUUID ESPBTUUID::from_raw(const std::string &data) { | |||||||
|       if (lsb > '9') |       if (lsb > '9') | ||||||
|         lsb -= 7; |         lsb -= 7; | ||||||
|       ret.uuid_.uuid.uuid128[15 - n++] = ((msb & 0x0F) << 4) | (lsb & 0x0F); |       ret.uuid_.uuid.uuid128[15 - n++] = ((msb & 0x0F) << 4) | (lsb & 0x0F); | ||||||
|       i += 2; |  | ||||||
|     } |     } | ||||||
|   } else { |   } else { | ||||||
|     ESP_LOGE(TAG, "ERROR: UUID value not 2, 4, 16 or 36 bytes - %s", data.c_str()); |     ESP_LOGE(TAG, "ERROR: UUID value not 2, 4, 16 or 36 bytes - %s", data.c_str()); | ||||||
| @@ -155,7 +154,7 @@ bool ESPBTUUID::operator==(const ESPBTUUID &uuid) const { | |||||||
|         } |         } | ||||||
|         break; |         break; | ||||||
|       case ESP_UUID_LEN_128: |       case ESP_UUID_LEN_128: | ||||||
|         for (int i = 0; i < ESP_UUID_LEN_128; i++) { |         for (uint8_t i = 0; i < ESP_UUID_LEN_128; i++) { | ||||||
|           if (uuid.uuid_.uuid.uuid128[i] != this->uuid_.uuid.uuid128[i]) { |           if (uuid.uuid_.uuid.uuid128[i] != this->uuid_.uuid.uuid128[i]) { | ||||||
|             return false; |             return false; | ||||||
|           } |           } | ||||||
|   | |||||||
| @@ -35,7 +35,7 @@ class BLEClientBase : public espbt::ESPBTClient, public Component { | |||||||
|   void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override; |   void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override; | ||||||
|   void connect() override; |   void connect() override; | ||||||
|   esp_err_t pair(); |   esp_err_t pair(); | ||||||
|   void disconnect(); |   void disconnect() override; | ||||||
|   void release_services(); |   void release_services(); | ||||||
|  |  | ||||||
|   bool connected() { return this->state_ == espbt::ClientState::ESTABLISHED; } |   bool connected() { return this->state_ == espbt::ClientState::ESTABLISHED; } | ||||||
|   | |||||||
| @@ -65,6 +65,9 @@ void ESP32BLETracker::setup() { | |||||||
|       [this](ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) { |       [this](ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) { | ||||||
|         if (state == ota::OTA_STARTED) { |         if (state == ota::OTA_STARTED) { | ||||||
|           this->stop_scan(); |           this->stop_scan(); | ||||||
|  |           for (auto *client : this->clients_) { | ||||||
|  |             client->disconnect(); | ||||||
|  |           } | ||||||
|         } |         } | ||||||
|       }); |       }); | ||||||
| #endif | #endif | ||||||
| @@ -429,7 +432,7 @@ void ESPBTDevice::parse_scan_rst(const esp_ble_gap_cb_param_t::ble_scan_result_e | |||||||
|  |  | ||||||
| #ifdef ESPHOME_LOG_HAS_VERY_VERBOSE | #ifdef ESPHOME_LOG_HAS_VERY_VERBOSE | ||||||
|   ESP_LOGVV(TAG, "Parse Result:"); |   ESP_LOGVV(TAG, "Parse Result:"); | ||||||
|   const char *address_type = ""; |   const char *address_type; | ||||||
|   switch (this->address_type_) { |   switch (this->address_type_) { | ||||||
|     case BLE_ADDR_TYPE_PUBLIC: |     case BLE_ADDR_TYPE_PUBLIC: | ||||||
|       address_type = "PUBLIC"; |       address_type = "PUBLIC"; | ||||||
| @@ -443,6 +446,9 @@ void ESPBTDevice::parse_scan_rst(const esp_ble_gap_cb_param_t::ble_scan_result_e | |||||||
|     case BLE_ADDR_TYPE_RPA_RANDOM: |     case BLE_ADDR_TYPE_RPA_RANDOM: | ||||||
|       address_type = "RPA_RANDOM"; |       address_type = "RPA_RANDOM"; | ||||||
|       break; |       break; | ||||||
|  |     default: | ||||||
|  |       address_type = "UNKNOWN"; | ||||||
|  |       break; | ||||||
|   } |   } | ||||||
|   ESP_LOGVV(TAG, "  Address: %02X:%02X:%02X:%02X:%02X:%02X (%s)", this->address_[0], this->address_[1], |   ESP_LOGVV(TAG, "  Address: %02X:%02X:%02X:%02X:%02X:%02X (%s)", this->address_[0], this->address_[1], | ||||||
|             this->address_[2], this->address_[3], this->address_[4], this->address_[5], address_type); |             this->address_[2], this->address_[3], this->address_[4], this->address_[5], address_type); | ||||||
|   | |||||||
| @@ -11,9 +11,9 @@ | |||||||
|  |  | ||||||
| #ifdef USE_ESP32 | #ifdef USE_ESP32 | ||||||
|  |  | ||||||
|  | #include <esp_bt_defs.h> | ||||||
| #include <esp_gap_ble_api.h> | #include <esp_gap_ble_api.h> | ||||||
| #include <esp_gattc_api.h> | #include <esp_gattc_api.h> | ||||||
| #include <esp_bt_defs.h> |  | ||||||
|  |  | ||||||
| #include <freertos/FreeRTOS.h> | #include <freertos/FreeRTOS.h> | ||||||
| #include <freertos/semphr.h> | #include <freertos/semphr.h> | ||||||
| @@ -172,6 +172,7 @@ class ESPBTClient : public ESPBTDeviceListener { | |||||||
|                                    esp_ble_gattc_cb_param_t *param) = 0; |                                    esp_ble_gattc_cb_param_t *param) = 0; | ||||||
|   virtual void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) = 0; |   virtual void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) = 0; | ||||||
|   virtual void connect() = 0; |   virtual void connect() = 0; | ||||||
|  |   virtual void disconnect() = 0; | ||||||
|   virtual void set_state(ClientState st) { this->state_ = st; } |   virtual void set_state(ClientState st) { this->state_ = st; } | ||||||
|   ClientState state() const { return state_; } |   ClientState state() const { return state_; } | ||||||
|   int app_id; |   int app_id; | ||||||
|   | |||||||
| @@ -11,7 +11,7 @@ | |||||||
| #include "esphome/core/helpers.h" | #include "esphome/core/helpers.h" | ||||||
| #include "esphome/core/preferences.h" | #include "esphome/core/preferences.h" | ||||||
|  |  | ||||||
| struct httpd_req; | struct httpd_req;  // NOLINT(readability-identifier-naming) | ||||||
|  |  | ||||||
| namespace esphome { | namespace esphome { | ||||||
| namespace esp32_camera_web_server { | namespace esp32_camera_web_server { | ||||||
|   | |||||||
| @@ -1,10 +1,13 @@ | |||||||
| import logging | import logging | ||||||
| import os | import os | ||||||
|  |  | ||||||
|  | import esphome.codegen as cg | ||||||
|  | import esphome.config_validation as cv | ||||||
| from esphome.const import ( | from esphome.const import ( | ||||||
|     CONF_BOARD, |     CONF_BOARD, | ||||||
|     CONF_BOARD_FLASH_MODE, |     CONF_BOARD_FLASH_MODE, | ||||||
|     CONF_FRAMEWORK, |     CONF_FRAMEWORK, | ||||||
|  |     CONF_PLATFORM_VERSION, | ||||||
|     CONF_SOURCE, |     CONF_SOURCE, | ||||||
|     CONF_VERSION, |     CONF_VERSION, | ||||||
|     KEY_CORE, |     KEY_CORE, | ||||||
| @@ -12,27 +15,22 @@ from esphome.const import ( | |||||||
|     KEY_TARGET_FRAMEWORK, |     KEY_TARGET_FRAMEWORK, | ||||||
|     KEY_TARGET_PLATFORM, |     KEY_TARGET_PLATFORM, | ||||||
|     PLATFORM_ESP8266, |     PLATFORM_ESP8266, | ||||||
|     CONF_PLATFORM_VERSION, |  | ||||||
| ) | ) | ||||||
| from esphome.core import CORE, coroutine_with_priority | from esphome.core import CORE, coroutine_with_priority | ||||||
| import esphome.config_validation as cv |  | ||||||
| import esphome.codegen as cg |  | ||||||
| from esphome.helpers import copy_file_if_changed | from esphome.helpers import copy_file_if_changed | ||||||
|  |  | ||||||
|  | from .boards import BOARDS, ESP8266_LD_SCRIPTS | ||||||
| from .const import ( | from .const import ( | ||||||
|     CONF_RESTORE_FROM_FLASH, |  | ||||||
|     CONF_EARLY_PIN_INIT, |     CONF_EARLY_PIN_INIT, | ||||||
|  |     CONF_RESTORE_FROM_FLASH, | ||||||
|     KEY_BOARD, |     KEY_BOARD, | ||||||
|     KEY_ESP8266, |     KEY_ESP8266, | ||||||
|     KEY_FLASH_SIZE, |     KEY_FLASH_SIZE, | ||||||
|     KEY_PIN_INITIAL_STATES, |     KEY_PIN_INITIAL_STATES, | ||||||
|     esp8266_ns, |     esp8266_ns, | ||||||
| ) | ) | ||||||
| from .boards import BOARDS, ESP8266_LD_SCRIPTS |  | ||||||
|  |  | ||||||
| from .gpio import PinInitialState, add_pin_initial_states_array | from .gpio import PinInitialState, add_pin_initial_states_array | ||||||
|  |  | ||||||
|  |  | ||||||
| CODEOWNERS = ["@esphome/core"] | CODEOWNERS = ["@esphome/core"] | ||||||
| _LOGGER = logging.getLogger(__name__) | _LOGGER = logging.getLogger(__name__) | ||||||
| AUTO_LOAD = ["preferences"] | AUTO_LOAD = ["preferences"] | ||||||
|   | |||||||
| @@ -1,6 +1,9 @@ | |||||||
| import logging |  | ||||||
| from dataclasses import dataclass | from dataclasses import dataclass | ||||||
|  | import logging | ||||||
|  |  | ||||||
|  | from esphome import pins | ||||||
|  | import esphome.codegen as cg | ||||||
|  | import esphome.config_validation as cv | ||||||
| from esphome.const import ( | from esphome.const import ( | ||||||
|     CONF_ANALOG, |     CONF_ANALOG, | ||||||
|     CONF_ID, |     CONF_ID, | ||||||
| @@ -14,10 +17,7 @@ from esphome.const import ( | |||||||
|     CONF_PULLUP, |     CONF_PULLUP, | ||||||
|     PLATFORM_ESP8266, |     PLATFORM_ESP8266, | ||||||
| ) | ) | ||||||
| from esphome import pins |  | ||||||
| from esphome.core import CORE, coroutine_with_priority | from esphome.core import CORE, coroutine_with_priority | ||||||
| import esphome.config_validation as cv |  | ||||||
| import esphome.codegen as cg |  | ||||||
|  |  | ||||||
| from . import boards | from . import boards | ||||||
| from .const import KEY_BOARD, KEY_ESP8266, KEY_PIN_INITIAL_STATES, esp8266_ns | from .const import KEY_BOARD, KEY_ESP8266, KEY_PIN_INITIAL_STATES, esp8266_ns | ||||||
| @@ -48,8 +48,10 @@ def _translate_pin(value): | |||||||
|             "This variable only supports pin numbers, not full pin schemas " |             "This variable only supports pin numbers, not full pin schemas " | ||||||
|             "(with inverted and mode)." |             "(with inverted and mode)." | ||||||
|         ) |         ) | ||||||
|     if isinstance(value, int): |     if isinstance(value, int) and not isinstance(value, bool): | ||||||
|         return value |         return value | ||||||
|  |     if not isinstance(value, str): | ||||||
|  |         raise cv.Invalid(f"Invalid pin number: {value}") | ||||||
|     try: |     try: | ||||||
|         return int(value) |         return int(value) | ||||||
|     except ValueError: |     except ValueError: | ||||||
|   | |||||||
| @@ -1,10 +1,9 @@ | |||||||
| import logging | import logging | ||||||
|  |  | ||||||
| import esphome.codegen as cg | import esphome.codegen as cg | ||||||
| import esphome.config_validation as cv | from esphome.components.ota import BASE_OTA_SCHEMA, OTAComponent, ota_to_code | ||||||
| import esphome.final_validate as fv |  | ||||||
| from esphome.components.ota import BASE_OTA_SCHEMA, ota_to_code, OTAComponent |  | ||||||
| from esphome.config_helpers import merge_config | from esphome.config_helpers import merge_config | ||||||
|  | import esphome.config_validation as cv | ||||||
| from esphome.const import ( | from esphome.const import ( | ||||||
|     CONF_ESPHOME, |     CONF_ESPHOME, | ||||||
|     CONF_ID, |     CONF_ID, | ||||||
| @@ -18,6 +17,7 @@ from esphome.const import ( | |||||||
|     CONF_VERSION, |     CONF_VERSION, | ||||||
| ) | ) | ||||||
| from esphome.core import coroutine_with_priority | from esphome.core import coroutine_with_priority | ||||||
|  | import esphome.final_validate as fv | ||||||
|  |  | ||||||
| _LOGGER = logging.getLogger(__name__) | _LOGGER = logging.getLogger(__name__) | ||||||
|  |  | ||||||
| @@ -124,7 +124,6 @@ FINAL_VALIDATE_SCHEMA = ota_esphome_final_validate | |||||||
| @coroutine_with_priority(52.0) | @coroutine_with_priority(52.0) | ||||||
| async def to_code(config): | async def to_code(config): | ||||||
|     var = cg.new_Pvariable(config[CONF_ID]) |     var = cg.new_Pvariable(config[CONF_ID]) | ||||||
|     await ota_to_code(var, config) |  | ||||||
|     cg.add(var.set_port(config[CONF_PORT])) |     cg.add(var.set_port(config[CONF_PORT])) | ||||||
|     if CONF_PASSWORD in config: |     if CONF_PASSWORD in config: | ||||||
|         cg.add(var.set_auth_password(config[CONF_PASSWORD])) |         cg.add(var.set_auth_password(config[CONF_PASSWORD])) | ||||||
| @@ -132,3 +131,4 @@ async def to_code(config): | |||||||
|     cg.add_define("USE_OTA_VERSION", config[CONF_VERSION]) |     cg.add_define("USE_OTA_VERSION", config[CONF_VERSION]) | ||||||
|  |  | ||||||
|     await cg.register_component(var, config) |     await cg.register_component(var, config) | ||||||
|  |     await ota_to_code(var, config) | ||||||
|   | |||||||
| @@ -1,3 +1,4 @@ | |||||||
|  | import logging | ||||||
| from esphome import pins | from esphome import pins | ||||||
| import esphome.codegen as cg | import esphome.codegen as cg | ||||||
| from esphome.components.esp32 import add_idf_sdkconfig_option, get_esp32_variant | from esphome.components.esp32 import add_idf_sdkconfig_option, get_esp32_variant | ||||||
| @@ -23,6 +24,7 @@ from esphome.const import ( | |||||||
|     CONF_MISO_PIN, |     CONF_MISO_PIN, | ||||||
|     CONF_MOSI_PIN, |     CONF_MOSI_PIN, | ||||||
|     CONF_PAGE_ID, |     CONF_PAGE_ID, | ||||||
|  |     CONF_POLLING_INTERVAL, | ||||||
|     CONF_RESET_PIN, |     CONF_RESET_PIN, | ||||||
|     CONF_SPI, |     CONF_SPI, | ||||||
|     CONF_STATIC_IP, |     CONF_STATIC_IP, | ||||||
| @@ -30,13 +32,16 @@ from esphome.const import ( | |||||||
|     CONF_TYPE, |     CONF_TYPE, | ||||||
|     CONF_USE_ADDRESS, |     CONF_USE_ADDRESS, | ||||||
|     CONF_VALUE, |     CONF_VALUE, | ||||||
|  |     KEY_CORE, | ||||||
|  |     KEY_FRAMEWORK_VERSION, | ||||||
| ) | ) | ||||||
| from esphome.core import CORE, coroutine_with_priority | from esphome.core import CORE, TimePeriodMilliseconds, coroutine_with_priority | ||||||
| import esphome.final_validate as fv | import esphome.final_validate as fv | ||||||
|  |  | ||||||
| CONFLICTS_WITH = ["wifi"] | CONFLICTS_WITH = ["wifi"] | ||||||
| DEPENDENCIES = ["esp32"] | DEPENDENCIES = ["esp32"] | ||||||
| AUTO_LOAD = ["network"] | AUTO_LOAD = ["network"] | ||||||
|  | LOGGER = logging.getLogger(__name__) | ||||||
|  |  | ||||||
| ethernet_ns = cg.esphome_ns.namespace("ethernet") | ethernet_ns = cg.esphome_ns.namespace("ethernet") | ||||||
| PHYRegister = ethernet_ns.struct("PHYRegister") | PHYRegister = ethernet_ns.struct("PHYRegister") | ||||||
| @@ -63,6 +68,7 @@ ETHERNET_TYPES = { | |||||||
| } | } | ||||||
|  |  | ||||||
| SPI_ETHERNET_TYPES = ["W5500"] | SPI_ETHERNET_TYPES = ["W5500"] | ||||||
|  | SPI_ETHERNET_DEFAULT_POLLING_INTERVAL = TimePeriodMilliseconds(milliseconds=10) | ||||||
|  |  | ||||||
| emac_rmii_clock_mode_t = cg.global_ns.enum("emac_rmii_clock_mode_t") | emac_rmii_clock_mode_t = cg.global_ns.enum("emac_rmii_clock_mode_t") | ||||||
| emac_rmii_clock_gpio_t = cg.global_ns.enum("emac_rmii_clock_gpio_t") | emac_rmii_clock_gpio_t = cg.global_ns.enum("emac_rmii_clock_gpio_t") | ||||||
| @@ -100,6 +106,24 @@ EthernetComponent = ethernet_ns.class_("EthernetComponent", cg.Component) | |||||||
| ManualIP = ethernet_ns.struct("ManualIP") | ManualIP = ethernet_ns.struct("ManualIP") | ||||||
|  |  | ||||||
|  |  | ||||||
|  | def _is_framework_spi_polling_mode_supported(): | ||||||
|  |     # SPI Ethernet without IRQ feature is added in | ||||||
|  |     # esp-idf >= (5.3+ ,5.2.1+, 5.1.4) and arduino-esp32 >= 3.0.0 | ||||||
|  |     framework_version = CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION] | ||||||
|  |     if CORE.using_esp_idf: | ||||||
|  |         if framework_version >= cv.Version(5, 3, 0): | ||||||
|  |             return True | ||||||
|  |         if cv.Version(5, 3, 0) > framework_version >= cv.Version(5, 2, 1): | ||||||
|  |             return True | ||||||
|  |         if cv.Version(5, 2, 0) > framework_version >= cv.Version(5, 1, 4): | ||||||
|  |             return True | ||||||
|  |         return False | ||||||
|  |     if CORE.using_arduino: | ||||||
|  |         return framework_version >= cv.Version(3, 0, 0) | ||||||
|  |     # fail safe: Unknown framework | ||||||
|  |     return False | ||||||
|  |  | ||||||
|  |  | ||||||
| def _validate(config): | def _validate(config): | ||||||
|     if CONF_USE_ADDRESS not in config: |     if CONF_USE_ADDRESS not in config: | ||||||
|         if CONF_MANUAL_IP in config: |         if CONF_MANUAL_IP in config: | ||||||
| @@ -107,6 +131,27 @@ def _validate(config): | |||||||
|         else: |         else: | ||||||
|             use_address = CORE.name + config[CONF_DOMAIN] |             use_address = CORE.name + config[CONF_DOMAIN] | ||||||
|         config[CONF_USE_ADDRESS] = use_address |         config[CONF_USE_ADDRESS] = use_address | ||||||
|  |     if config[CONF_TYPE] in SPI_ETHERNET_TYPES: | ||||||
|  |         if _is_framework_spi_polling_mode_supported(): | ||||||
|  |             if CONF_POLLING_INTERVAL in config and CONF_INTERRUPT_PIN in config: | ||||||
|  |                 raise cv.Invalid( | ||||||
|  |                     f"Cannot specify more than one of {CONF_INTERRUPT_PIN}, {CONF_POLLING_INTERVAL}" | ||||||
|  |                 ) | ||||||
|  |             if CONF_POLLING_INTERVAL not in config and CONF_INTERRUPT_PIN not in config: | ||||||
|  |                 config[CONF_POLLING_INTERVAL] = SPI_ETHERNET_DEFAULT_POLLING_INTERVAL | ||||||
|  |         else: | ||||||
|  |             if CONF_POLLING_INTERVAL in config: | ||||||
|  |                 raise cv.Invalid( | ||||||
|  |                     "In this version of the framework " | ||||||
|  |                     f"({CORE.target_framework} {CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION]}), " | ||||||
|  |                     f"'{CONF_POLLING_INTERVAL}' is not supported." | ||||||
|  |                 ) | ||||||
|  |             if CONF_INTERRUPT_PIN not in config: | ||||||
|  |                 raise cv.Invalid( | ||||||
|  |                     "In this version of the framework " | ||||||
|  |                     f"({CORE.target_framework} {CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION]}), " | ||||||
|  |                     f"'{CONF_INTERRUPT_PIN}' is a required option for [ethernet]." | ||||||
|  |                 ) | ||||||
|     return config |     return config | ||||||
|  |  | ||||||
|  |  | ||||||
| @@ -157,6 +202,11 @@ SPI_SCHEMA = BASE_SCHEMA.extend( | |||||||
|             cv.Optional(CONF_CLOCK_SPEED, default="26.67MHz"): cv.All( |             cv.Optional(CONF_CLOCK_SPEED, default="26.67MHz"): cv.All( | ||||||
|                 cv.frequency, cv.int_range(int(8e6), int(80e6)) |                 cv.frequency, cv.int_range(int(8e6), int(80e6)) | ||||||
|             ), |             ), | ||||||
|  |             # Set default value (SPI_ETHERNET_DEFAULT_POLLING_INTERVAL) at _validate() | ||||||
|  |             cv.Optional(CONF_POLLING_INTERVAL): cv.All( | ||||||
|  |                 cv.positive_time_period_milliseconds, | ||||||
|  |                 cv.Range(min=TimePeriodMilliseconds(milliseconds=1)), | ||||||
|  |             ), | ||||||
|         } |         } | ||||||
|     ), |     ), | ||||||
| ) | ) | ||||||
| @@ -234,6 +284,10 @@ async def to_code(config): | |||||||
|         cg.add(var.set_cs_pin(config[CONF_CS_PIN])) |         cg.add(var.set_cs_pin(config[CONF_CS_PIN])) | ||||||
|         if CONF_INTERRUPT_PIN in config: |         if CONF_INTERRUPT_PIN in config: | ||||||
|             cg.add(var.set_interrupt_pin(config[CONF_INTERRUPT_PIN])) |             cg.add(var.set_interrupt_pin(config[CONF_INTERRUPT_PIN])) | ||||||
|  |         else: | ||||||
|  |             cg.add(var.set_polling_interval(config[CONF_POLLING_INTERVAL])) | ||||||
|  |         if _is_framework_spi_polling_mode_supported(): | ||||||
|  |             cg.add_define("USE_ETHERNET_SPI_POLLING_SUPPORT") | ||||||
|         if CONF_RESET_PIN in config: |         if CONF_RESET_PIN in config: | ||||||
|             cg.add(var.set_reset_pin(config[CONF_RESET_PIN])) |             cg.add(var.set_reset_pin(config[CONF_RESET_PIN])) | ||||||
|         cg.add(var.set_clock_speed(config[CONF_CLOCK_SPEED])) |         cg.add(var.set_clock_speed(config[CONF_CLOCK_SPEED])) | ||||||
|   | |||||||
| @@ -116,6 +116,9 @@ void EthernetComponent::setup() { | |||||||
|   eth_w5500_config_t w5500_config = ETH_W5500_DEFAULT_CONFIG(spi_handle); |   eth_w5500_config_t w5500_config = ETH_W5500_DEFAULT_CONFIG(spi_handle); | ||||||
| #endif | #endif | ||||||
|   w5500_config.int_gpio_num = this->interrupt_pin_; |   w5500_config.int_gpio_num = this->interrupt_pin_; | ||||||
|  | #ifdef USE_ETHERNET_SPI_POLLING_SUPPORT | ||||||
|  |   w5500_config.poll_period_ms = this->polling_interval_; | ||||||
|  | #endif | ||||||
|   phy_config.phy_addr = this->phy_addr_spi_; |   phy_config.phy_addr = this->phy_addr_spi_; | ||||||
|   phy_config.reset_gpio_num = this->reset_pin_; |   phy_config.reset_gpio_num = this->reset_pin_; | ||||||
|  |  | ||||||
| @@ -327,7 +330,14 @@ void EthernetComponent::dump_config() { | |||||||
|   ESP_LOGCONFIG(TAG, "  MISO Pin: %u", this->miso_pin_); |   ESP_LOGCONFIG(TAG, "  MISO Pin: %u", this->miso_pin_); | ||||||
|   ESP_LOGCONFIG(TAG, "  MOSI Pin: %u", this->mosi_pin_); |   ESP_LOGCONFIG(TAG, "  MOSI Pin: %u", this->mosi_pin_); | ||||||
|   ESP_LOGCONFIG(TAG, "  CS Pin: %u", this->cs_pin_); |   ESP_LOGCONFIG(TAG, "  CS Pin: %u", this->cs_pin_); | ||||||
|   ESP_LOGCONFIG(TAG, "  IRQ Pin: %u", this->interrupt_pin_); | #ifdef USE_ETHERNET_SPI_POLLING_SUPPORT | ||||||
|  |   if (this->polling_interval_ != 0) { | ||||||
|  |     ESP_LOGCONFIG(TAG, "  Polling Interval: %lu ms", this->polling_interval_); | ||||||
|  |   } else | ||||||
|  | #endif | ||||||
|  |   { | ||||||
|  |     ESP_LOGCONFIG(TAG, "  IRQ Pin: %d", this->interrupt_pin_); | ||||||
|  |   } | ||||||
|   ESP_LOGCONFIG(TAG, "  Reset Pin: %d", this->reset_pin_); |   ESP_LOGCONFIG(TAG, "  Reset Pin: %d", this->reset_pin_); | ||||||
|   ESP_LOGCONFIG(TAG, "  Clock Speed: %d MHz", this->clock_speed_ / 1000000); |   ESP_LOGCONFIG(TAG, "  Clock Speed: %d MHz", this->clock_speed_ / 1000000); | ||||||
| #else | #else | ||||||
| @@ -536,6 +546,9 @@ void EthernetComponent::set_cs_pin(uint8_t cs_pin) { this->cs_pin_ = cs_pin; } | |||||||
| void EthernetComponent::set_interrupt_pin(uint8_t interrupt_pin) { this->interrupt_pin_ = interrupt_pin; } | void EthernetComponent::set_interrupt_pin(uint8_t interrupt_pin) { this->interrupt_pin_ = interrupt_pin; } | ||||||
| void EthernetComponent::set_reset_pin(uint8_t reset_pin) { this->reset_pin_ = reset_pin; } | void EthernetComponent::set_reset_pin(uint8_t reset_pin) { this->reset_pin_ = reset_pin; } | ||||||
| void EthernetComponent::set_clock_speed(int clock_speed) { this->clock_speed_ = clock_speed; } | void EthernetComponent::set_clock_speed(int clock_speed) { this->clock_speed_ = clock_speed; } | ||||||
|  | #ifdef USE_ETHERNET_SPI_POLLING_SUPPORT | ||||||
|  | void EthernetComponent::set_polling_interval(uint32_t polling_interval) { this->polling_interval_ = polling_interval; } | ||||||
|  | #endif | ||||||
| #else | #else | ||||||
| void EthernetComponent::set_phy_addr(uint8_t phy_addr) { this->phy_addr_ = phy_addr; } | void EthernetComponent::set_phy_addr(uint8_t phy_addr) { this->phy_addr_ = phy_addr; } | ||||||
| void EthernetComponent::set_power_pin(int power_pin) { this->power_pin_ = power_pin; } | void EthernetComponent::set_power_pin(int power_pin) { this->power_pin_ = power_pin; } | ||||||
|   | |||||||
| @@ -67,6 +67,9 @@ class EthernetComponent : public Component { | |||||||
|   void set_interrupt_pin(uint8_t interrupt_pin); |   void set_interrupt_pin(uint8_t interrupt_pin); | ||||||
|   void set_reset_pin(uint8_t reset_pin); |   void set_reset_pin(uint8_t reset_pin); | ||||||
|   void set_clock_speed(int clock_speed); |   void set_clock_speed(int clock_speed); | ||||||
|  | #ifdef USE_ETHERNET_SPI_POLLING_SUPPORT | ||||||
|  |   void set_polling_interval(uint32_t polling_interval); | ||||||
|  | #endif | ||||||
| #else | #else | ||||||
|   void set_phy_addr(uint8_t phy_addr); |   void set_phy_addr(uint8_t phy_addr); | ||||||
|   void set_power_pin(int power_pin); |   void set_power_pin(int power_pin); | ||||||
| @@ -108,10 +111,13 @@ class EthernetComponent : public Component { | |||||||
|   uint8_t miso_pin_; |   uint8_t miso_pin_; | ||||||
|   uint8_t mosi_pin_; |   uint8_t mosi_pin_; | ||||||
|   uint8_t cs_pin_; |   uint8_t cs_pin_; | ||||||
|   uint8_t interrupt_pin_; |   int interrupt_pin_{-1}; | ||||||
|   int reset_pin_{-1}; |   int reset_pin_{-1}; | ||||||
|   int phy_addr_spi_{-1}; |   int phy_addr_spi_{-1}; | ||||||
|   int clock_speed_; |   int clock_speed_; | ||||||
|  | #ifdef USE_ETHERNET_SPI_POLLING_SUPPORT | ||||||
|  |   uint32_t polling_interval_{0}; | ||||||
|  | #endif | ||||||
| #else | #else | ||||||
|   uint8_t phy_addr_{0}; |   uint8_t phy_addr_{0}; | ||||||
|   int power_pin_{-1}; |   int power_pin_{-1}; | ||||||
|   | |||||||
| @@ -111,11 +111,11 @@ void EZOSensor::loop() { | |||||||
|   if (buf[0] == 1) { |   if (buf[0] == 1) { | ||||||
|     std::string payload = reinterpret_cast<char *>(&buf[1]); |     std::string payload = reinterpret_cast<char *>(&buf[1]); | ||||||
|     if (!payload.empty()) { |     if (!payload.empty()) { | ||||||
|  |       auto start_location = payload.find(','); | ||||||
|       switch (to_run->command_type) { |       switch (to_run->command_type) { | ||||||
|         case EzoCommandType::EZO_READ: { |         case EzoCommandType::EZO_READ: { | ||||||
|           // some sensors return multiple comma-separated values, terminate string after first one |           // some sensors return multiple comma-separated values, terminate string after first one | ||||||
|           int start_location = 0; |           if (start_location != std::string::npos) { | ||||||
|           if ((start_location = payload.find(',')) != std::string::npos) { |  | ||||||
|             payload.erase(start_location); |             payload.erase(start_location); | ||||||
|           } |           } | ||||||
|           auto val = parse_number<float>(payload); |           auto val = parse_number<float>(payload); | ||||||
| @@ -126,49 +126,37 @@ void EZOSensor::loop() { | |||||||
|           } |           } | ||||||
|           break; |           break; | ||||||
|         } |         } | ||||||
|         case EzoCommandType::EZO_LED: { |         case EzoCommandType::EZO_LED: | ||||||
|           this->led_callback_.call(payload.back() == '1'); |           this->led_callback_.call(payload.back() == '1'); | ||||||
|           break; |           break; | ||||||
|         } |         case EzoCommandType::EZO_DEVICE_INFORMATION: | ||||||
|         case EzoCommandType::EZO_DEVICE_INFORMATION: { |           if (start_location != std::string::npos) { | ||||||
|           int start_location = 0; |  | ||||||
|           if ((start_location = payload.find(',')) != std::string::npos) { |  | ||||||
|             this->device_infomation_callback_.call(payload.substr(start_location + 1)); |             this->device_infomation_callback_.call(payload.substr(start_location + 1)); | ||||||
|           } |           } | ||||||
|           break; |           break; | ||||||
|         } |         case EzoCommandType::EZO_SLOPE: | ||||||
|         case EzoCommandType::EZO_SLOPE: { |           if (start_location != std::string::npos) { | ||||||
|           int start_location = 0; |  | ||||||
|           if ((start_location = payload.find(',')) != std::string::npos) { |  | ||||||
|             this->slope_callback_.call(payload.substr(start_location + 1)); |             this->slope_callback_.call(payload.substr(start_location + 1)); | ||||||
|           } |           } | ||||||
|           break; |           break; | ||||||
|         } |         case EzoCommandType::EZO_CALIBRATION: | ||||||
|         case EzoCommandType::EZO_CALIBRATION: { |           if (start_location != std::string::npos) { | ||||||
|           int start_location = 0; |  | ||||||
|           if ((start_location = payload.find(',')) != std::string::npos) { |  | ||||||
|             this->calibration_callback_.call(payload.substr(start_location + 1)); |             this->calibration_callback_.call(payload.substr(start_location + 1)); | ||||||
|           } |           } | ||||||
|           break; |           break; | ||||||
|         } |         case EzoCommandType::EZO_T: | ||||||
|         case EzoCommandType::EZO_T: { |           if (start_location != std::string::npos) { | ||||||
|           int start_location = 0; |  | ||||||
|           if ((start_location = payload.find(',')) != std::string::npos) { |  | ||||||
|             this->t_callback_.call(payload.substr(start_location + 1)); |             this->t_callback_.call(payload.substr(start_location + 1)); | ||||||
|           } |           } | ||||||
|           break; |           break; | ||||||
|         } |         case EzoCommandType::EZO_CUSTOM: | ||||||
|         case EzoCommandType::EZO_CUSTOM: { |  | ||||||
|           this->custom_callback_.call(payload); |           this->custom_callback_.call(payload); | ||||||
|           break; |           break; | ||||||
|         } |         default: | ||||||
|         default: { |  | ||||||
|           break; |           break; | ||||||
|         } |  | ||||||
|       } |       } | ||||||
|     } |     } | ||||||
|   } |   } | ||||||
|  |  | ||||||
|   this->commands_.pop_front(); |   this->commands_.pop_front(); | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -178,7 +166,7 @@ void EZOSensor::add_command_(const std::string &command, EzoCommandType command_ | |||||||
|   ezo_command->command_type = command_type; |   ezo_command->command_type = command_type; | ||||||
|   ezo_command->delay_ms = delay_ms; |   ezo_command->delay_ms = delay_ms; | ||||||
|   this->commands_.push_back(std::move(ezo_command)); |   this->commands_.push_back(std::move(ezo_command)); | ||||||
| }; | } | ||||||
|  |  | ||||||
| void EZOSensor::set_calibration_point_(EzoCalibrationType type, float value) { | void EZOSensor::set_calibration_point_(EzoCalibrationType type, float value) { | ||||||
|   std::string payload = str_sprintf("Cal,%s,%0.2f", EZO_CALIBRATION_TYPE_STRINGS[type], value); |   std::string payload = str_sprintf("Cal,%s,%0.2f", EZO_CALIBRATION_TYPE_STRINGS[type], value); | ||||||
|   | |||||||
| @@ -1,3 +1,4 @@ | |||||||
|  | from collections.abc import Iterable | ||||||
| import functools | import functools | ||||||
| import hashlib | import hashlib | ||||||
| import logging | import logging | ||||||
| @@ -5,6 +6,8 @@ import os | |||||||
| from pathlib import Path | from pathlib import Path | ||||||
| import re | import re | ||||||
|  |  | ||||||
|  | import freetype | ||||||
|  | import glyphsets | ||||||
| from packaging import version | from packaging import version | ||||||
| import requests | import requests | ||||||
|  |  | ||||||
| @@ -43,6 +46,18 @@ GlyphData = font_ns.struct("GlyphData") | |||||||
| CONF_BPP = "bpp" | CONF_BPP = "bpp" | ||||||
| CONF_EXTRAS = "extras" | CONF_EXTRAS = "extras" | ||||||
| CONF_FONTS = "fonts" | CONF_FONTS = "fonts" | ||||||
|  | CONF_GLYPHSETS = "glyphsets" | ||||||
|  | CONF_IGNORE_MISSING_GLYPHS = "ignore_missing_glyphs" | ||||||
|  |  | ||||||
|  |  | ||||||
|  | # Cache loaded freetype fonts | ||||||
|  | class FontCache(dict): | ||||||
|  |     def __missing__(self, key): | ||||||
|  |         res = self[key] = freetype.Face(key) | ||||||
|  |         return res | ||||||
|  |  | ||||||
|  |  | ||||||
|  | FONT_CACHE = FontCache() | ||||||
|  |  | ||||||
|  |  | ||||||
| def glyph_comparator(x, y): | def glyph_comparator(x, y): | ||||||
| @@ -59,36 +74,106 @@ def glyph_comparator(x, y): | |||||||
|         return -1 |         return -1 | ||||||
|     if len(x_) > len(y_): |     if len(x_) > len(y_): | ||||||
|         return 1 |         return 1 | ||||||
|     raise cv.Invalid(f"Found duplicate glyph {x}") |     return 0 | ||||||
|  |  | ||||||
|  |  | ||||||
| def validate_glyphs(value): | def flatten(lists) -> list: | ||||||
|     if isinstance(value, list): |     """ | ||||||
|         value = cv.Schema([cv.string])(value) |     Given a list of lists, flatten it to a single list of all elements of all lists. | ||||||
|     value = cv.Schema([cv.string])(list(value)) |     This wraps itertools.chain.from_iterable to make it more readable, and return a list | ||||||
|  |     rather than a single use iterable. | ||||||
|  |     """ | ||||||
|  |     from itertools import chain | ||||||
|  |  | ||||||
|     value.sort(key=functools.cmp_to_key(glyph_comparator)) |     return list(chain.from_iterable(lists)) | ||||||
|     return value |  | ||||||
|  |  | ||||||
|  |  | ||||||
| font_map = {} | def check_missing_glyphs(file, codepoints: Iterable, warning: bool = False): | ||||||
|  |     """ | ||||||
|  |     Check that the given font file actually contains the requested glyphs | ||||||
|  |     :param file: A Truetype font file | ||||||
|  |     :param codepoints: A list of codepoints to check | ||||||
|  |     :param warning: If true, log a warning instead of raising an exception | ||||||
|  |     """ | ||||||
|  |  | ||||||
|  |     font = FONT_CACHE[file] | ||||||
| def merge_glyphs(config): |     missing = [chr(x) for x in codepoints if font.get_char_index(x) == 0] | ||||||
|     glyphs = [] |     if missing: | ||||||
|     glyphs.extend(config[CONF_GLYPHS]) |         # Only list up to 10 missing glyphs | ||||||
|     font_list = [(EFont(config[CONF_FILE], config[CONF_SIZE], config[CONF_GLYPHS]))] |         missing.sort(key=functools.cmp_to_key(glyph_comparator)) | ||||||
|     if extras := config.get(CONF_EXTRAS): |         count = len(missing) | ||||||
|         extra_fonts = list( |         missing = missing[:10] | ||||||
|             map( |         missing_str = "\n    ".join( | ||||||
|                 lambda x: EFont(x[CONF_FILE], config[CONF_SIZE], x[CONF_GLYPHS]), extras |             f"{x} ({x.encode('unicode_escape')})" for x in missing | ||||||
|             ) |  | ||||||
|         ) |         ) | ||||||
|         font_list.extend(extra_fonts) |         if count > 10: | ||||||
|         for extra in extras: |             missing_str += f"\n    and {count - 10} more." | ||||||
|             glyphs.extend(extra[CONF_GLYPHS]) |         message = f"Font {Path(file).name} is missing {count} glyph{'s' if count != 1 else ''}:\n    {missing_str}" | ||||||
|         validate_glyphs(glyphs) |         if warning: | ||||||
|     font_map[config[CONF_ID]] = font_list |             _LOGGER.warning(message) | ||||||
|  |         else: | ||||||
|  |             raise cv.Invalid(message) | ||||||
|  |  | ||||||
|  |  | ||||||
|  | def validate_glyphs(config): | ||||||
|  |     """ | ||||||
|  |     Check for duplicate codepoints, then check that all requested codepoints actually | ||||||
|  |     have glyphs defined in the appropriate font file. | ||||||
|  |     """ | ||||||
|  |  | ||||||
|  |     # Collect all glyph codepoints and flatten to a list of chars | ||||||
|  |     glyphspoints = flatten( | ||||||
|  |         [x[CONF_GLYPHS] for x in config[CONF_EXTRAS]] + config[CONF_GLYPHS] | ||||||
|  |     ) | ||||||
|  |     # Convert a list of strings to a list of chars (one char strings) | ||||||
|  |     glyphspoints = flatten([list(x) for x in glyphspoints]) | ||||||
|  |     if len(set(glyphspoints)) != len(glyphspoints): | ||||||
|  |         duplicates = {x for x in glyphspoints if glyphspoints.count(x) > 1} | ||||||
|  |         dup_str = ", ".join(f"{x} ({x.encode('unicode_escape')})" for x in duplicates) | ||||||
|  |         raise cv.Invalid( | ||||||
|  |             f"Found duplicate glyph{'s' if len(duplicates) != 1 else ''}: {dup_str}" | ||||||
|  |         ) | ||||||
|  |     # convert to codepoints | ||||||
|  |     glyphspoints = {ord(x) for x in glyphspoints} | ||||||
|  |     fileconf = config[CONF_FILE] | ||||||
|  |     setpoints = set( | ||||||
|  |         flatten([glyphsets.unicodes_per_glyphset(x) for x in config[CONF_GLYPHSETS]]) | ||||||
|  |     ) | ||||||
|  |     # Make setpoints and glyphspoints disjoint | ||||||
|  |     setpoints.difference_update(glyphspoints) | ||||||
|  |     if fileconf[CONF_TYPE] == TYPE_LOCAL_BITMAP: | ||||||
|  |         # Pillow only allows 256 glyphs per bitmap font. Not sure if that is a Pillow limitation | ||||||
|  |         # or a file format limitation | ||||||
|  |         if any(x >= 256 for x in setpoints.copy().union(glyphspoints)): | ||||||
|  |             raise cv.Invalid("Codepoints in bitmap fonts must be in the range 0-255") | ||||||
|  |     else: | ||||||
|  |         # for TT fonts, check that glyphs are actually present | ||||||
|  |         # Check extras against their own font, exclude from parent font codepoints | ||||||
|  |         for extra in config[CONF_EXTRAS]: | ||||||
|  |             points = {ord(x) for x in flatten(extra[CONF_GLYPHS])} | ||||||
|  |             glyphspoints.difference_update(points) | ||||||
|  |             setpoints.difference_update(points) | ||||||
|  |             check_missing_glyphs(extra[CONF_FILE][CONF_PATH], points) | ||||||
|  |  | ||||||
|  |         # A named glyph that can't be provided is an error | ||||||
|  |         check_missing_glyphs(fileconf[CONF_PATH], glyphspoints) | ||||||
|  |         # A missing glyph from a set is a warning. | ||||||
|  |         if not config[CONF_IGNORE_MISSING_GLYPHS]: | ||||||
|  |             check_missing_glyphs(fileconf[CONF_PATH], setpoints, warning=True) | ||||||
|  |  | ||||||
|  |     # Populate the default after the above checks so that use of the default doesn't trigger errors | ||||||
|  |     if not config[CONF_GLYPHS] and not config[CONF_GLYPHSETS]: | ||||||
|  |         if fileconf[CONF_TYPE] == TYPE_LOCAL_BITMAP: | ||||||
|  |             config[CONF_GLYPHS] = [DEFAULT_GLYPHS] | ||||||
|  |         else: | ||||||
|  |             # set a default glyphset, intersected with what the font actually offers | ||||||
|  |             font = FONT_CACHE[fileconf[CONF_PATH]] | ||||||
|  |             config[CONF_GLYPHS] = [ | ||||||
|  |                 chr(x) | ||||||
|  |                 for x in glyphsets.unicodes_per_glyphset(DEFAULT_GLYPHSET) | ||||||
|  |                 if font.get_char_index(x) != 0 | ||||||
|  |             ] | ||||||
|  |  | ||||||
|     return config |     return config | ||||||
|  |  | ||||||
|  |  | ||||||
| @@ -120,7 +205,7 @@ def validate_truetype_file(value): | |||||||
|         ) |         ) | ||||||
|     if not any(map(value.lower().endswith, FONT_EXTENSIONS)): |     if not any(map(value.lower().endswith, FONT_EXTENSIONS)): | ||||||
|         raise cv.Invalid(f"Only {FONT_EXTENSIONS} files are supported.") |         raise cv.Invalid(f"Only {FONT_EXTENSIONS} files are supported.") | ||||||
|     return cv.file_(value) |     return CORE.relative_config_path(cv.file_(value)) | ||||||
|  |  | ||||||
|  |  | ||||||
| TYPE_LOCAL = "local" | TYPE_LOCAL = "local" | ||||||
| @@ -139,6 +224,10 @@ LOCAL_BITMAP_SCHEMA = cv.Schema( | |||||||
|     } |     } | ||||||
| ) | ) | ||||||
|  |  | ||||||
|  | FULLPATH_SCHEMA = cv.maybe_simple_value( | ||||||
|  |     {cv.Required(CONF_PATH): cv.string}, key=CONF_PATH | ||||||
|  | ) | ||||||
|  |  | ||||||
| CONF_ITALIC = "italic" | CONF_ITALIC = "italic" | ||||||
| FONT_WEIGHTS = { | FONT_WEIGHTS = { | ||||||
|     "thin": 100, |     "thin": 100, | ||||||
| @@ -167,13 +256,13 @@ def _compute_local_font_path(value: dict) -> Path: | |||||||
|     return base_dir / key |     return base_dir / key | ||||||
|  |  | ||||||
|  |  | ||||||
| def get_font_path(value, type) -> Path: | def get_font_path(value, font_type) -> Path: | ||||||
|     if type == TYPE_GFONTS: |     if font_type == TYPE_GFONTS: | ||||||
|         name = f"{value[CONF_FAMILY]}@{value[CONF_WEIGHT]}@{value[CONF_ITALIC]}@v1" |         name = f"{value[CONF_FAMILY]}@{value[CONF_WEIGHT]}@{value[CONF_ITALIC]}@v1" | ||||||
|         return external_files.compute_local_file_dir(DOMAIN) / f"{name}.ttf" |         return external_files.compute_local_file_dir(DOMAIN) / f"{name}.ttf" | ||||||
|     if type == TYPE_WEB: |     if font_type == TYPE_WEB: | ||||||
|         return _compute_local_font_path(value) / "font.ttf" |         return _compute_local_font_path(value) / "font.ttf" | ||||||
|     return None |     assert False | ||||||
|  |  | ||||||
|  |  | ||||||
| def download_gfont(value): | def download_gfont(value): | ||||||
| @@ -203,7 +292,7 @@ def download_gfont(value): | |||||||
|     _LOGGER.debug("download_gfont: ttf_url=%s", ttf_url) |     _LOGGER.debug("download_gfont: ttf_url=%s", ttf_url) | ||||||
|  |  | ||||||
|     external_files.download_content(ttf_url, path) |     external_files.download_content(ttf_url, path) | ||||||
|     return value |     return FULLPATH_SCHEMA(path) | ||||||
|  |  | ||||||
|  |  | ||||||
| def download_web_font(value): | def download_web_font(value): | ||||||
| @@ -212,7 +301,7 @@ def download_web_font(value): | |||||||
|  |  | ||||||
|     external_files.download_content(url, path) |     external_files.download_content(url, path) | ||||||
|     _LOGGER.debug("download_web_font: path=%s", path) |     _LOGGER.debug("download_web_font: path=%s", path) | ||||||
|     return value |     return FULLPATH_SCHEMA(path) | ||||||
|  |  | ||||||
|  |  | ||||||
| EXTERNAL_FONT_SCHEMA = cv.Schema( | EXTERNAL_FONT_SCHEMA = cv.Schema( | ||||||
| @@ -225,7 +314,6 @@ EXTERNAL_FONT_SCHEMA = cv.Schema( | |||||||
|     } |     } | ||||||
| ) | ) | ||||||
|  |  | ||||||
|  |  | ||||||
| GFONTS_SCHEMA = cv.All( | GFONTS_SCHEMA = cv.All( | ||||||
|     EXTERNAL_FONT_SCHEMA.extend( |     EXTERNAL_FONT_SCHEMA.extend( | ||||||
|         { |         { | ||||||
| @@ -259,10 +347,10 @@ def validate_file_shorthand(value): | |||||||
|         } |         } | ||||||
|         if weight is not None: |         if weight is not None: | ||||||
|             data[CONF_WEIGHT] = weight[1:] |             data[CONF_WEIGHT] = weight[1:] | ||||||
|         return FILE_SCHEMA(data) |         return font_file_schema(data) | ||||||
|  |  | ||||||
|     if value.startswith("http://") or value.startswith("https://"): |     if value.startswith("http://") or value.startswith("https://"): | ||||||
|         return FILE_SCHEMA( |         return font_file_schema( | ||||||
|             { |             { | ||||||
|                 CONF_TYPE: TYPE_WEB, |                 CONF_TYPE: TYPE_WEB, | ||||||
|                 CONF_URL: value, |                 CONF_URL: value, | ||||||
| @@ -270,14 +358,15 @@ def validate_file_shorthand(value): | |||||||
|         ) |         ) | ||||||
|  |  | ||||||
|     if value.endswith(".pcf") or value.endswith(".bdf"): |     if value.endswith(".pcf") or value.endswith(".bdf"): | ||||||
|         return FILE_SCHEMA( |         value = convert_bitmap_to_pillow_font( | ||||||
|             { |             CORE.relative_config_path(cv.file_(value)) | ||||||
|                 CONF_TYPE: TYPE_LOCAL_BITMAP, |  | ||||||
|                 CONF_PATH: value, |  | ||||||
|             } |  | ||||||
|         ) |         ) | ||||||
|  |         return { | ||||||
|  |             CONF_TYPE: TYPE_LOCAL_BITMAP, | ||||||
|  |             CONF_PATH: value, | ||||||
|  |         } | ||||||
|  |  | ||||||
|     return FILE_SCHEMA( |     return font_file_schema( | ||||||
|         { |         { | ||||||
|             CONF_TYPE: TYPE_LOCAL, |             CONF_TYPE: TYPE_LOCAL, | ||||||
|             CONF_PATH: value, |             CONF_PATH: value, | ||||||
| @@ -295,31 +384,35 @@ TYPED_FILE_SCHEMA = cv.typed_schema( | |||||||
| ) | ) | ||||||
|  |  | ||||||
|  |  | ||||||
| def _file_schema(value): | def font_file_schema(value): | ||||||
|     if isinstance(value, str): |     if isinstance(value, str): | ||||||
|         return validate_file_shorthand(value) |         return validate_file_shorthand(value) | ||||||
|     return TYPED_FILE_SCHEMA(value) |     return TYPED_FILE_SCHEMA(value) | ||||||
|  |  | ||||||
|  |  | ||||||
| FILE_SCHEMA = cv.All(_file_schema) | # Default if no glyphs or glyphsets are provided | ||||||
|  | DEFAULT_GLYPHSET = "GF_Latin_Kernel" | ||||||
|  | # default for bitmap fonts | ||||||
|  | DEFAULT_GLYPHS = ' !"%()+=,-.:/?0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz<C2><B0>' | ||||||
|  |  | ||||||
| DEFAULT_GLYPHS = ( |  | ||||||
|     ' !"%()+=,-.:/?0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz°' |  | ||||||
| ) |  | ||||||
| CONF_RAW_GLYPH_ID = "raw_glyph_id" | CONF_RAW_GLYPH_ID = "raw_glyph_id" | ||||||
|  |  | ||||||
| FONT_SCHEMA = cv.Schema( | FONT_SCHEMA = cv.Schema( | ||||||
|     { |     { | ||||||
|         cv.Required(CONF_ID): cv.declare_id(Font), |         cv.Required(CONF_ID): cv.declare_id(Font), | ||||||
|         cv.Required(CONF_FILE): FILE_SCHEMA, |         cv.Required(CONF_FILE): font_file_schema, | ||||||
|         cv.Optional(CONF_GLYPHS, default=DEFAULT_GLYPHS): validate_glyphs, |         cv.Optional(CONF_GLYPHS, default=[]): cv.ensure_list(cv.string_strict), | ||||||
|  |         cv.Optional(CONF_GLYPHSETS, default=[]): cv.ensure_list( | ||||||
|  |             cv.one_of(*glyphsets.defined_glyphsets()) | ||||||
|  |         ), | ||||||
|  |         cv.Optional(CONF_IGNORE_MISSING_GLYPHS, default=False): cv.boolean, | ||||||
|         cv.Optional(CONF_SIZE, default=20): cv.int_range(min=1), |         cv.Optional(CONF_SIZE, default=20): cv.int_range(min=1), | ||||||
|         cv.Optional(CONF_BPP, default=1): cv.one_of(1, 2, 4, 8), |         cv.Optional(CONF_BPP, default=1): cv.one_of(1, 2, 4, 8), | ||||||
|         cv.Optional(CONF_EXTRAS): cv.ensure_list( |         cv.Optional(CONF_EXTRAS, default=[]): cv.ensure_list( | ||||||
|             cv.Schema( |             cv.Schema( | ||||||
|                 { |                 { | ||||||
|                     cv.Required(CONF_FILE): FILE_SCHEMA, |                     cv.Required(CONF_FILE): font_file_schema, | ||||||
|                     cv.Required(CONF_GLYPHS): validate_glyphs, |                     cv.Required(CONF_GLYPHS): cv.ensure_list(cv.string_strict), | ||||||
|                 } |                 } | ||||||
|             ) |             ) | ||||||
|         ), |         ), | ||||||
| @@ -328,7 +421,7 @@ FONT_SCHEMA = cv.Schema( | |||||||
|     }, |     }, | ||||||
| ) | ) | ||||||
|  |  | ||||||
| CONFIG_SCHEMA = cv.All(validate_pillow_installed, FONT_SCHEMA, merge_glyphs) | CONFIG_SCHEMA = cv.All(validate_pillow_installed, FONT_SCHEMA, validate_glyphs) | ||||||
|  |  | ||||||
|  |  | ||||||
| # PIL doesn't provide a consistent interface for both TrueType and bitmap | # PIL doesn't provide a consistent interface for both TrueType and bitmap | ||||||
| @@ -344,7 +437,7 @@ class TrueTypeFontWrapper: | |||||||
|         return offset_x, offset_y |         return offset_x, offset_y | ||||||
|  |  | ||||||
|     def getmask(self, glyph, **kwargs): |     def getmask(self, glyph, **kwargs): | ||||||
|         return self.font.getmask(glyph, **kwargs) |         return self.font.getmask(str(glyph), **kwargs) | ||||||
|  |  | ||||||
|     def getmetrics(self, glyphs): |     def getmetrics(self, glyphs): | ||||||
|         return self.font.getmetrics() |         return self.font.getmetrics() | ||||||
| @@ -359,7 +452,7 @@ class BitmapFontWrapper: | |||||||
|         return 0, 0 |         return 0, 0 | ||||||
|  |  | ||||||
|     def getmask(self, glyph, **kwargs): |     def getmask(self, glyph, **kwargs): | ||||||
|         return self.font.getmask(glyph, **kwargs) |         return self.font.getmask(str(glyph), **kwargs) | ||||||
|  |  | ||||||
|     def getmetrics(self, glyphs): |     def getmetrics(self, glyphs): | ||||||
|         max_height = 0 |         max_height = 0 | ||||||
| @@ -367,28 +460,20 @@ class BitmapFontWrapper: | |||||||
|             mask = self.getmask(glyph, mode="1") |             mask = self.getmask(glyph, mode="1") | ||||||
|             _, height = mask.size |             _, height = mask.size | ||||||
|             max_height = max(max_height, height) |             max_height = max(max_height, height) | ||||||
|         return (max_height, 0) |         return max_height, 0 | ||||||
|  |  | ||||||
|  |  | ||||||
| class EFont: | class EFont: | ||||||
|     def __init__(self, file, size, glyphs): |     def __init__(self, file, size, codepoints): | ||||||
|         self.glyphs = glyphs |         self.codepoints = codepoints | ||||||
|  |         path = file[CONF_PATH] | ||||||
|  |         self.name = Path(path).name | ||||||
|         ftype = file[CONF_TYPE] |         ftype = file[CONF_TYPE] | ||||||
|         if ftype == TYPE_LOCAL_BITMAP: |         if ftype == TYPE_LOCAL_BITMAP: | ||||||
|             font = load_bitmap_font(CORE.relative_config_path(file[CONF_PATH])) |             self.font = load_bitmap_font(path) | ||||||
|         elif ftype == TYPE_LOCAL: |  | ||||||
|             path = CORE.relative_config_path(file[CONF_PATH]) |  | ||||||
|             font = load_ttf_font(path, size) |  | ||||||
|         elif ftype in (TYPE_GFONTS, TYPE_WEB): |  | ||||||
|             path = get_font_path(file, ftype) |  | ||||||
|             font = load_ttf_font(path, size) |  | ||||||
|         else: |         else: | ||||||
|             raise cv.Invalid(f"Could not load font: unknown type: {ftype}") |             self.font = load_ttf_font(path, size) | ||||||
|         self.font = font |         self.ascent, self.descent = self.font.getmetrics(codepoints) | ||||||
|         self.ascent, self.descent = font.getmetrics(glyphs) |  | ||||||
|  |  | ||||||
|     def has_glyph(self, glyph): |  | ||||||
|         return glyph in self.glyphs |  | ||||||
|  |  | ||||||
|  |  | ||||||
| def convert_bitmap_to_pillow_font(filepath): | def convert_bitmap_to_pillow_font(filepath): | ||||||
| @@ -400,6 +485,7 @@ def convert_bitmap_to_pillow_font(filepath): | |||||||
|  |  | ||||||
|     copy_file_if_changed(filepath, local_bitmap_font_file) |     copy_file_if_changed(filepath, local_bitmap_font_file) | ||||||
|  |  | ||||||
|  |     local_pil_font_file = local_bitmap_font_file.with_suffix(".pil") | ||||||
|     with open(local_bitmap_font_file, "rb") as fp: |     with open(local_bitmap_font_file, "rb") as fp: | ||||||
|         try: |         try: | ||||||
|             try: |             try: | ||||||
| @@ -409,28 +495,22 @@ def convert_bitmap_to_pillow_font(filepath): | |||||||
|                 p = BdfFontFile.BdfFontFile(fp) |                 p = BdfFontFile.BdfFontFile(fp) | ||||||
|  |  | ||||||
|             # Convert to pillow-formatted fonts, which have a .pil and .pbm extension. |             # Convert to pillow-formatted fonts, which have a .pil and .pbm extension. | ||||||
|             p.save(local_bitmap_font_file) |             p.save(local_pil_font_file) | ||||||
|         except (SyntaxError, OSError) as err: |         except (SyntaxError, OSError) as err: | ||||||
|             raise core.EsphomeError( |             raise core.EsphomeError( | ||||||
|                 f"Failed to parse as bitmap font: '{filepath}': {err}" |                 f"Failed to parse as bitmap font: '{filepath}': {err}" | ||||||
|             ) |             ) | ||||||
|  |  | ||||||
|     local_pil_font_file = os.path.splitext(local_bitmap_font_file)[0] + ".pil" |     return str(local_pil_font_file) | ||||||
|     return cv.file_(local_pil_font_file) |  | ||||||
|  |  | ||||||
|  |  | ||||||
| def load_bitmap_font(filepath): | def load_bitmap_font(filepath): | ||||||
|     from PIL import ImageFont |     from PIL import ImageFont | ||||||
|  |  | ||||||
|     # Convert bpf and pcf files to pillow fonts, first. |  | ||||||
|     pil_font_path = convert_bitmap_to_pillow_font(filepath) |  | ||||||
|  |  | ||||||
|     try: |     try: | ||||||
|         font = ImageFont.load(str(pil_font_path)) |         font = ImageFont.load(str(filepath)) | ||||||
|     except Exception as e: |     except Exception as e: | ||||||
|         raise core.EsphomeError( |         raise core.EsphomeError(f"Failed to load bitmap font file: {filepath}: {e}") | ||||||
|             f"Failed to load bitmap font file: {pil_font_path} : {e}" |  | ||||||
|         ) |  | ||||||
|  |  | ||||||
|     return BitmapFontWrapper(font) |     return BitmapFontWrapper(font) | ||||||
|  |  | ||||||
| @@ -441,7 +521,7 @@ def load_ttf_font(path, size): | |||||||
|     try: |     try: | ||||||
|         font = ImageFont.truetype(str(path), size) |         font = ImageFont.truetype(str(path), size) | ||||||
|     except Exception as e: |     except Exception as e: | ||||||
|         raise core.EsphomeError(f"Could not load truetype file {path}: {e}") |         raise core.EsphomeError(f"Could not load TrueType file {path}: {e}") | ||||||
|  |  | ||||||
|     return TrueTypeFontWrapper(font) |     return TrueTypeFontWrapper(font) | ||||||
|  |  | ||||||
| @@ -456,14 +536,35 @@ class GlyphInfo: | |||||||
|  |  | ||||||
|  |  | ||||||
| async def to_code(config): | async def to_code(config): | ||||||
|     glyph_to_font_map = {} |     """ | ||||||
|     font_list = font_map[config[CONF_ID]] |     Collect all glyph codepoints, construct a map from a codepoint to a font file. | ||||||
|     glyphs = [] |     Codepoints are either explicit (glyphs key in top level or extras) or part of a glyphset. | ||||||
|     for font in font_list: |     Codepoints listed in extras use the extra font and override codepoints from glyphsets. | ||||||
|         glyphs.extend(font.glyphs) |     Achieve this by processing the base codepoints first, then the extras | ||||||
|         for glyph in font.glyphs: |     """ | ||||||
|             glyph_to_font_map[glyph] = font |  | ||||||
|     glyphs.sort(key=functools.cmp_to_key(glyph_comparator)) |     # get the codepoints from glyphsets and flatten to a set of chrs. | ||||||
|  |     point_set: set[str] = { | ||||||
|  |         chr(x) | ||||||
|  |         for x in flatten( | ||||||
|  |             [glyphsets.unicodes_per_glyphset(x) for x in config[CONF_GLYPHSETS]] | ||||||
|  |         ) | ||||||
|  |     } | ||||||
|  |     # get the codepoints from the glyphs key, flatten to a list of chrs and combine with the points from glyphsets | ||||||
|  |     point_set.update(flatten(config[CONF_GLYPHS])) | ||||||
|  |     size = config[CONF_SIZE] | ||||||
|  |     # Create the codepoint to font file map | ||||||
|  |     base_font = EFont(config[CONF_FILE], size, point_set) | ||||||
|  |     point_font_map: dict[str, EFont] = {c: base_font for c in point_set} | ||||||
|  |     # process extras, updating the map and extending the codepoint list | ||||||
|  |     for extra in config[CONF_EXTRAS]: | ||||||
|  |         extra_points = flatten(extra[CONF_GLYPHS]) | ||||||
|  |         point_set.update(extra_points) | ||||||
|  |         extra_font = EFont(extra[CONF_FILE], size, extra_points) | ||||||
|  |         point_font_map.update({c: extra_font for c in extra_points}) | ||||||
|  |  | ||||||
|  |     codepoints = list(point_set) | ||||||
|  |     codepoints.sort(key=functools.cmp_to_key(glyph_comparator)) | ||||||
|     glyph_args = {} |     glyph_args = {} | ||||||
|     data = [] |     data = [] | ||||||
|     bpp = config[CONF_BPP] |     bpp = config[CONF_BPP] | ||||||
| @@ -473,10 +574,11 @@ async def to_code(config): | |||||||
|     else: |     else: | ||||||
|         mode = "L" |         mode = "L" | ||||||
|         scale = 256 // (1 << bpp) |         scale = 256 // (1 << bpp) | ||||||
|     for glyph in glyphs: |     # create the data array for all glyphs | ||||||
|         font = glyph_to_font_map[glyph].font |     for codepoint in codepoints: | ||||||
|         mask = font.getmask(glyph, mode=mode) |         font = point_font_map[codepoint] | ||||||
|         offset_x, offset_y = font.getoffset(glyph) |         mask = font.font.getmask(codepoint, mode=mode) | ||||||
|  |         offset_x, offset_y = font.font.getoffset(codepoint) | ||||||
|         width, height = mask.size |         width, height = mask.size | ||||||
|         glyph_data = [0] * ((height * width * bpp + 7) // 8) |         glyph_data = [0] * ((height * width * bpp + 7) // 8) | ||||||
|         pos = 0 |         pos = 0 | ||||||
| @@ -487,31 +589,34 @@ async def to_code(config): | |||||||
|                     if pixel & (1 << (bpp - bit_num - 1)): |                     if pixel & (1 << (bpp - bit_num - 1)): | ||||||
|                         glyph_data[pos // 8] |= 0x80 >> (pos % 8) |                         glyph_data[pos // 8] |= 0x80 >> (pos % 8) | ||||||
|                     pos += 1 |                     pos += 1 | ||||||
|         glyph_args[glyph] = GlyphInfo(len(data), offset_x, offset_y, width, height) |         glyph_args[codepoint] = GlyphInfo(len(data), offset_x, offset_y, width, height) | ||||||
|         data += glyph_data |         data += glyph_data | ||||||
|  |  | ||||||
|     rhs = [HexInt(x) for x in data] |     rhs = [HexInt(x) for x in data] | ||||||
|     prog_arr = cg.progmem_array(config[CONF_RAW_DATA_ID], rhs) |     prog_arr = cg.progmem_array(config[CONF_RAW_DATA_ID], rhs) | ||||||
|  |  | ||||||
|  |     # Create the glyph table that points to data in the above array. | ||||||
|     glyph_initializer = [] |     glyph_initializer = [] | ||||||
|     for glyph in glyphs: |     for codepoint in codepoints: | ||||||
|         glyph_initializer.append( |         glyph_initializer.append( | ||||||
|             cg.StructInitializer( |             cg.StructInitializer( | ||||||
|                 GlyphData, |                 GlyphData, | ||||||
|                 ( |                 ( | ||||||
|                     "a_char", |                     "a_char", | ||||||
|                     cg.RawExpression(f"(const uint8_t *){cpp_string_escape(glyph)}"), |                     cg.RawExpression( | ||||||
|  |                         f"(const uint8_t *){cpp_string_escape(codepoint)}" | ||||||
|  |                     ), | ||||||
|                 ), |                 ), | ||||||
|                 ( |                 ( | ||||||
|                     "data", |                     "data", | ||||||
|                     cg.RawExpression( |                     cg.RawExpression( | ||||||
|                         f"{str(prog_arr)} + {str(glyph_args[glyph].data_len)}" |                         f"{str(prog_arr)} + {str(glyph_args[codepoint].data_len)}" | ||||||
|                     ), |                     ), | ||||||
|                 ), |                 ), | ||||||
|                 ("offset_x", glyph_args[glyph].offset_x), |                 ("offset_x", glyph_args[codepoint].offset_x), | ||||||
|                 ("offset_y", glyph_args[glyph].offset_y), |                 ("offset_y", glyph_args[codepoint].offset_y), | ||||||
|                 ("width", glyph_args[glyph].width), |                 ("width", glyph_args[codepoint].width), | ||||||
|                 ("height", glyph_args[glyph].height), |                 ("height", glyph_args[codepoint].height), | ||||||
|             ) |             ) | ||||||
|         ) |         ) | ||||||
|  |  | ||||||
| @@ -521,7 +626,7 @@ async def to_code(config): | |||||||
|         config[CONF_ID], |         config[CONF_ID], | ||||||
|         glyphs, |         glyphs, | ||||||
|         len(glyph_initializer), |         len(glyph_initializer), | ||||||
|         font_list[0].ascent, |         base_font.ascent, | ||||||
|         font_list[0].ascent + font_list[0].descent, |         base_font.ascent + base_font.descent, | ||||||
|         bpp, |         bpp, | ||||||
|     ) |     ) | ||||||
|   | |||||||
| @@ -16,7 +16,7 @@ CONFIG_SCHEMA = output.FLOAT_OUTPUT_SCHEMA.extend( | |||||||
|     { |     { | ||||||
|         cv.GenerateID(): cv.declare_id(GP8403Output), |         cv.GenerateID(): cv.declare_id(GP8403Output), | ||||||
|         cv.GenerateID(CONF_GP8403_ID): cv.use_id(GP8403), |         cv.GenerateID(CONF_GP8403_ID): cv.use_id(GP8403), | ||||||
|         cv.Required(CONF_CHANNEL): cv.one_of(0, 1), |         cv.Required(CONF_CHANNEL): cv.int_range(min=0, max=1), | ||||||
|     } |     } | ||||||
| ).extend(cv.COMPONENT_SCHEMA) | ).extend(cv.COMPONENT_SCHEMA) | ||||||
|  |  | ||||||
|   | |||||||
| @@ -36,6 +36,8 @@ CODEOWNERS = ["@MrMDavidson"] | |||||||
|  |  | ||||||
| AUTO_LOAD = ["display_menu_base"] | AUTO_LOAD = ["display_menu_base"] | ||||||
|  |  | ||||||
|  | MULTI_CONF = True | ||||||
|  |  | ||||||
| CONFIG_SCHEMA = DISPLAY_MENU_BASE_SCHEMA.extend( | CONFIG_SCHEMA = DISPLAY_MENU_BASE_SCHEMA.extend( | ||||||
|     cv.Schema( |     cv.Schema( | ||||||
|         { |         { | ||||||
|   | |||||||
| @@ -1069,19 +1069,17 @@ void HonClimate::fill_control_messages_queue_() { | |||||||
|   climate_control = this->current_hvac_settings_; |   climate_control = this->current_hvac_settings_; | ||||||
|   // Beeper command |   // Beeper command | ||||||
|   { |   { | ||||||
|     this->control_messages_queue_.push( |     this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, | ||||||
|         haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, |                                           (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + | ||||||
|                                      (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + |                                               (uint8_t) hon_protocol::DataParameters::BEEPER_STATUS, | ||||||
|                                          (uint8_t) hon_protocol::DataParameters::BEEPER_STATUS, |                                           this->get_beeper_state() ? ZERO_BUF : ONE_BUF, 2); | ||||||
|                                      this->get_beeper_state() ? ZERO_BUF : ONE_BUF, 2)); |  | ||||||
|   } |   } | ||||||
|   // Health mode |   // Health mode | ||||||
|   { |   { | ||||||
|     this->control_messages_queue_.push( |     this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, | ||||||
|         haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, |                                           (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + | ||||||
|                                      (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + |                                               (uint8_t) hon_protocol::DataParameters::HEALTH_MODE, | ||||||
|                                          (uint8_t) hon_protocol::DataParameters::HEALTH_MODE, |                                           this->get_health_mode() ? ONE_BUF : ZERO_BUF, 2); | ||||||
|                                      this->get_health_mode() ? ONE_BUF : ZERO_BUF, 2)); |  | ||||||
|     this->health_mode_ = (SwitchState) ((uint8_t) this->health_mode_ & 0b01); |     this->health_mode_ = (SwitchState) ((uint8_t) this->health_mode_ & 0b01); | ||||||
|   } |   } | ||||||
|   // Climate mode |   // Climate mode | ||||||
| @@ -1099,51 +1097,46 @@ void HonClimate::fill_control_messages_queue_() { | |||||||
|       case CLIMATE_MODE_HEAT_COOL: |       case CLIMATE_MODE_HEAT_COOL: | ||||||
|         new_power = true; |         new_power = true; | ||||||
|         buffer[1] = (uint8_t) hon_protocol::ConditioningMode::AUTO; |         buffer[1] = (uint8_t) hon_protocol::ConditioningMode::AUTO; | ||||||
|         this->control_messages_queue_.push( |         this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, | ||||||
|             haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, |                                               (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + | ||||||
|                                          (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + |                                                   (uint8_t) hon_protocol::DataParameters::AC_MODE, | ||||||
|                                              (uint8_t) hon_protocol::DataParameters::AC_MODE, |                                               buffer, 2); | ||||||
|                                          buffer, 2)); |  | ||||||
|         fan_mode_buf[1] = this->other_modes_fan_speed_; |         fan_mode_buf[1] = this->other_modes_fan_speed_; | ||||||
|         break; |         break; | ||||||
|       case CLIMATE_MODE_HEAT: |       case CLIMATE_MODE_HEAT: | ||||||
|         new_power = true; |         new_power = true; | ||||||
|         buffer[1] = (uint8_t) hon_protocol::ConditioningMode::HEAT; |         buffer[1] = (uint8_t) hon_protocol::ConditioningMode::HEAT; | ||||||
|         this->control_messages_queue_.push( |         this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, | ||||||
|             haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, |                                               (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + | ||||||
|                                          (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + |                                                   (uint8_t) hon_protocol::DataParameters::AC_MODE, | ||||||
|                                              (uint8_t) hon_protocol::DataParameters::AC_MODE, |                                               buffer, 2); | ||||||
|                                          buffer, 2)); |  | ||||||
|         fan_mode_buf[1] = this->other_modes_fan_speed_; |         fan_mode_buf[1] = this->other_modes_fan_speed_; | ||||||
|         break; |         break; | ||||||
|       case CLIMATE_MODE_DRY: |       case CLIMATE_MODE_DRY: | ||||||
|         new_power = true; |         new_power = true; | ||||||
|         buffer[1] = (uint8_t) hon_protocol::ConditioningMode::DRY; |         buffer[1] = (uint8_t) hon_protocol::ConditioningMode::DRY; | ||||||
|         this->control_messages_queue_.push( |         this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, | ||||||
|             haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, |                                               (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + | ||||||
|                                          (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + |                                                   (uint8_t) hon_protocol::DataParameters::AC_MODE, | ||||||
|                                              (uint8_t) hon_protocol::DataParameters::AC_MODE, |                                               buffer, 2); | ||||||
|                                          buffer, 2)); |  | ||||||
|         fan_mode_buf[1] = this->other_modes_fan_speed_; |         fan_mode_buf[1] = this->other_modes_fan_speed_; | ||||||
|         break; |         break; | ||||||
|       case CLIMATE_MODE_FAN_ONLY: |       case CLIMATE_MODE_FAN_ONLY: | ||||||
|         new_power = true; |         new_power = true; | ||||||
|         buffer[1] = (uint8_t) hon_protocol::ConditioningMode::FAN; |         buffer[1] = (uint8_t) hon_protocol::ConditioningMode::FAN; | ||||||
|         this->control_messages_queue_.push( |         this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, | ||||||
|             haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, |                                               (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + | ||||||
|                                          (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + |                                                   (uint8_t) hon_protocol::DataParameters::AC_MODE, | ||||||
|                                              (uint8_t) hon_protocol::DataParameters::AC_MODE, |                                               buffer, 2); | ||||||
|                                          buffer, 2)); |  | ||||||
|         fan_mode_buf[1] = this->other_modes_fan_speed_;  // Auto doesn't work in fan only mode |         fan_mode_buf[1] = this->other_modes_fan_speed_;  // Auto doesn't work in fan only mode | ||||||
|         break; |         break; | ||||||
|       case CLIMATE_MODE_COOL: |       case CLIMATE_MODE_COOL: | ||||||
|         new_power = true; |         new_power = true; | ||||||
|         buffer[1] = (uint8_t) hon_protocol::ConditioningMode::COOL; |         buffer[1] = (uint8_t) hon_protocol::ConditioningMode::COOL; | ||||||
|         this->control_messages_queue_.push( |         this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, | ||||||
|             haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, |                                               (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + | ||||||
|                                          (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + |                                                   (uint8_t) hon_protocol::DataParameters::AC_MODE, | ||||||
|                                              (uint8_t) hon_protocol::DataParameters::AC_MODE, |                                               buffer, 2); | ||||||
|                                          buffer, 2)); |  | ||||||
|         fan_mode_buf[1] = this->other_modes_fan_speed_; |         fan_mode_buf[1] = this->other_modes_fan_speed_; | ||||||
|         break; |         break; | ||||||
|       default: |       default: | ||||||
| @@ -1153,11 +1146,10 @@ void HonClimate::fill_control_messages_queue_() { | |||||||
|   } |   } | ||||||
|   // Climate power |   // Climate power | ||||||
|   { |   { | ||||||
|     this->control_messages_queue_.push( |     this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, | ||||||
|         haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, |                                           (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + | ||||||
|                                      (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + |                                               (uint8_t) hon_protocol::DataParameters::AC_POWER, | ||||||
|                                          (uint8_t) hon_protocol::DataParameters::AC_POWER, |                                           new_power ? ONE_BUF : ZERO_BUF, 2); | ||||||
|                                      new_power ? ONE_BUF : ZERO_BUF, 2)); |  | ||||||
|   } |   } | ||||||
|   // CLimate preset |   // CLimate preset | ||||||
|   { |   { | ||||||
| @@ -1199,36 +1191,32 @@ void HonClimate::fill_control_messages_queue_() { | |||||||
|     } |     } | ||||||
|     auto presets = this->traits_.get_supported_presets(); |     auto presets = this->traits_.get_supported_presets(); | ||||||
|     if (quiet_mode_buf[1] != 0xFF) { |     if (quiet_mode_buf[1] != 0xFF) { | ||||||
|       this->control_messages_queue_.push( |       this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, | ||||||
|           haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, |                                             (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + | ||||||
|                                        (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + |                                                 (uint8_t) hon_protocol::DataParameters::QUIET_MODE, | ||||||
|                                            (uint8_t) hon_protocol::DataParameters::QUIET_MODE, |                                             quiet_mode_buf, 2); | ||||||
|                                        quiet_mode_buf, 2)); |  | ||||||
|     } |     } | ||||||
|     if ((fast_mode_buf[1] != 0xFF) && ((presets.find(climate::ClimatePreset::CLIMATE_PRESET_BOOST) != presets.end()))) { |     if ((fast_mode_buf[1] != 0xFF) && ((presets.find(climate::ClimatePreset::CLIMATE_PRESET_BOOST) != presets.end()))) { | ||||||
|       this->control_messages_queue_.push( |       this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, | ||||||
|           haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, |                                             (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + | ||||||
|                                        (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + |                                                 (uint8_t) hon_protocol::DataParameters::FAST_MODE, | ||||||
|                                            (uint8_t) hon_protocol::DataParameters::FAST_MODE, |                                             fast_mode_buf, 2); | ||||||
|                                        fast_mode_buf, 2)); |  | ||||||
|     } |     } | ||||||
|     if ((away_mode_buf[1] != 0xFF) && ((presets.find(climate::ClimatePreset::CLIMATE_PRESET_AWAY) != presets.end()))) { |     if ((away_mode_buf[1] != 0xFF) && ((presets.find(climate::ClimatePreset::CLIMATE_PRESET_AWAY) != presets.end()))) { | ||||||
|       this->control_messages_queue_.push( |       this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, | ||||||
|           haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, |                                             (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + | ||||||
|                                        (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + |                                                 (uint8_t) hon_protocol::DataParameters::TEN_DEGREE, | ||||||
|                                            (uint8_t) hon_protocol::DataParameters::TEN_DEGREE, |                                             away_mode_buf, 2); | ||||||
|                                        away_mode_buf, 2)); |  | ||||||
|     } |     } | ||||||
|   } |   } | ||||||
|   // Target temperature |   // Target temperature | ||||||
|   if (climate_control.target_temperature.has_value() && (this->mode != ClimateMode::CLIMATE_MODE_FAN_ONLY)) { |   if (climate_control.target_temperature.has_value() && (this->mode != ClimateMode::CLIMATE_MODE_FAN_ONLY)) { | ||||||
|     uint8_t buffer[2] = {0x00, 0x00}; |     uint8_t buffer[2] = {0x00, 0x00}; | ||||||
|     buffer[1] = ((uint8_t) climate_control.target_temperature.value()) - 16; |     buffer[1] = ((uint8_t) climate_control.target_temperature.value()) - 16; | ||||||
|     this->control_messages_queue_.push( |     this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, | ||||||
|         haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, |                                           (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + | ||||||
|                                      (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + |                                               (uint8_t) hon_protocol::DataParameters::SET_POINT, | ||||||
|                                          (uint8_t) hon_protocol::DataParameters::SET_POINT, |                                           buffer, 2); | ||||||
|                                      buffer, 2)); |  | ||||||
|   } |   } | ||||||
|   // Vertical swing mode |   // Vertical swing mode | ||||||
|   if (climate_control.swing_mode.has_value()) { |   if (climate_control.swing_mode.has_value()) { | ||||||
| @@ -1248,16 +1236,14 @@ void HonClimate::fill_control_messages_queue_() { | |||||||
|       case CLIMATE_SWING_BOTH: |       case CLIMATE_SWING_BOTH: | ||||||
|         break; |         break; | ||||||
|     } |     } | ||||||
|     this->control_messages_queue_.push( |     this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, | ||||||
|         haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, |                                           (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + | ||||||
|                                      (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + |                                               (uint8_t) hon_protocol::DataParameters::HORIZONTAL_SWING_MODE, | ||||||
|                                          (uint8_t) hon_protocol::DataParameters::HORIZONTAL_SWING_MODE, |                                           horizontal_swing_buf, 2); | ||||||
|                                      horizontal_swing_buf, 2)); |     this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, | ||||||
|     this->control_messages_queue_.push( |                                           (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + | ||||||
|         haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, |                                               (uint8_t) hon_protocol::DataParameters::VERTICAL_SWING_MODE, | ||||||
|                                      (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + |                                           vertical_swing_buf, 2); | ||||||
|                                          (uint8_t) hon_protocol::DataParameters::VERTICAL_SWING_MODE, |  | ||||||
|                                      vertical_swing_buf, 2)); |  | ||||||
|   } |   } | ||||||
|   // Fan mode |   // Fan mode | ||||||
|   if (climate_control.fan_mode.has_value()) { |   if (climate_control.fan_mode.has_value()) { | ||||||
| @@ -1280,11 +1266,10 @@ void HonClimate::fill_control_messages_queue_() { | |||||||
|         break; |         break; | ||||||
|     } |     } | ||||||
|     if (fan_mode_buf[1] != 0xFF) { |     if (fan_mode_buf[1] != 0xFF) { | ||||||
|       this->control_messages_queue_.push( |       this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, | ||||||
|           haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, |                                             (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + | ||||||
|                                        (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + |                                                 (uint8_t) hon_protocol::DataParameters::FAN_MODE, | ||||||
|                                            (uint8_t) hon_protocol::DataParameters::FAN_MODE, |                                             fan_mode_buf, 2); | ||||||
|                                        fan_mode_buf, 2)); |  | ||||||
|     } |     } | ||||||
|   } |   } | ||||||
| } | } | ||||||
|   | |||||||
| @@ -133,8 +133,10 @@ bool HitachiClimate::get_swing_v_() { | |||||||
| } | } | ||||||
|  |  | ||||||
| void HitachiClimate::set_swing_h_(uint8_t position) { | void HitachiClimate::set_swing_h_(uint8_t position) { | ||||||
|   if (position > HITACHI_AC344_SWINGH_LEFT_MAX) |   if (position > HITACHI_AC344_SWINGH_LEFT_MAX) { | ||||||
|     return set_swing_h_(HITACHI_AC344_SWINGH_MIDDLE); |     set_swing_h_(HITACHI_AC344_SWINGH_MIDDLE); | ||||||
|  |     return; | ||||||
|  |   } | ||||||
|   set_bits(&remote_state_[HITACHI_AC344_SWINGH_BYTE], HITACHI_AC344_SWINGH_OFFSET, HITACHI_AC344_SWINGH_SIZE, position); |   set_bits(&remote_state_[HITACHI_AC344_SWINGH_BYTE], HITACHI_AC344_SWINGH_OFFSET, HITACHI_AC344_SWINGH_SIZE, position); | ||||||
|   set_button_(HITACHI_AC344_BUTTON_SWINGH); |   set_button_(HITACHI_AC344_BUTTON_SWINGH); | ||||||
| } | } | ||||||
|   | |||||||
| @@ -133,8 +133,10 @@ bool HitachiClimate::get_swing_v_() { | |||||||
| } | } | ||||||
|  |  | ||||||
| void HitachiClimate::set_swing_h_(uint8_t position) { | void HitachiClimate::set_swing_h_(uint8_t position) { | ||||||
|   if (position > HITACHI_AC424_SWINGH_LEFT_MAX) |   if (position > HITACHI_AC424_SWINGH_LEFT_MAX) { | ||||||
|     return set_swing_h_(HITACHI_AC424_SWINGH_MIDDLE); |     set_swing_h_(HITACHI_AC424_SWINGH_MIDDLE); | ||||||
|  |     return; | ||||||
|  |   } | ||||||
|   set_bits(&remote_state_[HITACHI_AC424_SWINGH_BYTE], HITACHI_AC424_SWINGH_OFFSET, HITACHI_AC424_SWINGH_SIZE, position); |   set_bits(&remote_state_[HITACHI_AC424_SWINGH_BYTE], HITACHI_AC424_SWINGH_OFFSET, HITACHI_AC424_SWINGH_SIZE, position); | ||||||
|   set_button_(HITACHI_AC424_BUTTON_SWINGH); |   set_button_(HITACHI_AC424_BUTTON_SWINGH); | ||||||
| } | } | ||||||
|   | |||||||
| @@ -27,6 +27,7 @@ void HomeassistantNumber::min_retrieved_(const std::string &min) { | |||||||
|   auto min_value = parse_number<float>(min); |   auto min_value = parse_number<float>(min); | ||||||
|   if (!min_value.has_value()) { |   if (!min_value.has_value()) { | ||||||
|     ESP_LOGE(TAG, "'%s': Can't convert 'min' value '%s' to number!", this->entity_id_.c_str(), min.c_str()); |     ESP_LOGE(TAG, "'%s': Can't convert 'min' value '%s' to number!", this->entity_id_.c_str(), min.c_str()); | ||||||
|  |     return; | ||||||
|   } |   } | ||||||
|   ESP_LOGD(TAG, "'%s': Min retrieved: %s", get_name().c_str(), min.c_str()); |   ESP_LOGD(TAG, "'%s': Min retrieved: %s", get_name().c_str(), min.c_str()); | ||||||
|   this->traits.set_min_value(min_value.value()); |   this->traits.set_min_value(min_value.value()); | ||||||
| @@ -36,6 +37,7 @@ void HomeassistantNumber::max_retrieved_(const std::string &max) { | |||||||
|   auto max_value = parse_number<float>(max); |   auto max_value = parse_number<float>(max); | ||||||
|   if (!max_value.has_value()) { |   if (!max_value.has_value()) { | ||||||
|     ESP_LOGE(TAG, "'%s': Can't convert 'max' value '%s' to number!", this->entity_id_.c_str(), max.c_str()); |     ESP_LOGE(TAG, "'%s': Can't convert 'max' value '%s' to number!", this->entity_id_.c_str(), max.c_str()); | ||||||
|  |     return; | ||||||
|   } |   } | ||||||
|   ESP_LOGD(TAG, "'%s': Max retrieved: %s", get_name().c_str(), max.c_str()); |   ESP_LOGD(TAG, "'%s': Max retrieved: %s", get_name().c_str(), max.c_str()); | ||||||
|   this->traits.set_max_value(max_value.value()); |   this->traits.set_max_value(max_value.value()); | ||||||
| @@ -45,6 +47,7 @@ void HomeassistantNumber::step_retrieved_(const std::string &step) { | |||||||
|   auto step_value = parse_number<float>(step); |   auto step_value = parse_number<float>(step); | ||||||
|   if (!step_value.has_value()) { |   if (!step_value.has_value()) { | ||||||
|     ESP_LOGE(TAG, "'%s': Can't convert 'step' value '%s' to number!", this->entity_id_.c_str(), step.c_str()); |     ESP_LOGE(TAG, "'%s': Can't convert 'step' value '%s' to number!", this->entity_id_.c_str(), step.c_str()); | ||||||
|  |     return; | ||||||
|   } |   } | ||||||
|   ESP_LOGD(TAG, "'%s': Step Retrieved %s", get_name().c_str(), step.c_str()); |   ESP_LOGD(TAG, "'%s': Step Retrieved %s", get_name().c_str(), step.c_str()); | ||||||
|   this->traits.set_step(step_value.value()); |   this->traits.set_step(step_value.value()); | ||||||
|   | |||||||
| @@ -15,7 +15,7 @@ static const char *const TAG = "honeywellabp2"; | |||||||
| void HONEYWELLABP2Sensor::read_sensor_data() { | void HONEYWELLABP2Sensor::read_sensor_data() { | ||||||
|   if (this->read(raw_data_, 7) != i2c::ERROR_OK) { |   if (this->read(raw_data_, 7) != i2c::ERROR_OK) { | ||||||
|     ESP_LOGE(TAG, "Communication with ABP2 failed!"); |     ESP_LOGE(TAG, "Communication with ABP2 failed!"); | ||||||
|     this->mark_failed(); |     this->status_set_warning("couldn't read sensor data"); | ||||||
|     return; |     return; | ||||||
|   } |   } | ||||||
|   float press_counts = encode_uint24(raw_data_[1], raw_data_[2], raw_data_[3]);  // calculate digital pressure counts |   float press_counts = encode_uint24(raw_data_[1], raw_data_[2], raw_data_[3]);  // calculate digital pressure counts | ||||||
| @@ -25,12 +25,13 @@ void HONEYWELLABP2Sensor::read_sensor_data() { | |||||||
|                           (this->max_pressure_ - this->min_pressure_)) + |                           (this->max_pressure_ - this->min_pressure_)) + | ||||||
|                          this->min_pressure_; |                          this->min_pressure_; | ||||||
|   this->last_temperature_ = (temp_counts * 200 / 16777215) - 50; |   this->last_temperature_ = (temp_counts * 200 / 16777215) - 50; | ||||||
|  |   this->status_clear_warning(); | ||||||
| } | } | ||||||
|  |  | ||||||
| void HONEYWELLABP2Sensor::start_measurement() { | void HONEYWELLABP2Sensor::start_measurement() { | ||||||
|   if (this->write(i2c_cmd_, 3) != i2c::ERROR_OK) { |   if (this->write(i2c_cmd_, 3) != i2c::ERROR_OK) { | ||||||
|     ESP_LOGE(TAG, "Communication with ABP2 failed!"); |     ESP_LOGE(TAG, "Communication with ABP2 failed!"); | ||||||
|     this->mark_failed(); |     this->status_set_warning("couldn't start measurement"); | ||||||
|     return; |     return; | ||||||
|   } |   } | ||||||
|   this->measurement_running_ = true; |   this->measurement_running_ = true; | ||||||
| @@ -39,7 +40,7 @@ void HONEYWELLABP2Sensor::start_measurement() { | |||||||
| bool HONEYWELLABP2Sensor::is_measurement_ready() { | bool HONEYWELLABP2Sensor::is_measurement_ready() { | ||||||
|   if (this->read(raw_data_, 1) != i2c::ERROR_OK) { |   if (this->read(raw_data_, 1) != i2c::ERROR_OK) { | ||||||
|     ESP_LOGE(TAG, "Communication with ABP2 failed!"); |     ESP_LOGE(TAG, "Communication with ABP2 failed!"); | ||||||
|     this->mark_failed(); |     this->status_set_warning("couldn't check measurement"); | ||||||
|     return false; |     return false; | ||||||
|   } |   } | ||||||
|   if ((raw_data_[0] & (0x1 << STATUS_BIT_BUSY)) > 0) { |   if ((raw_data_[0] & (0x1 << STATUS_BIT_BUSY)) > 0) { | ||||||
| @@ -52,7 +53,7 @@ bool HONEYWELLABP2Sensor::is_measurement_ready() { | |||||||
| void HONEYWELLABP2Sensor::measurement_timeout() { | void HONEYWELLABP2Sensor::measurement_timeout() { | ||||||
|   ESP_LOGE(TAG, "Timeout!"); |   ESP_LOGE(TAG, "Timeout!"); | ||||||
|   this->measurement_running_ = false; |   this->measurement_running_ = false; | ||||||
|   this->mark_failed(); |   this->status_set_warning("measurement timed out"); | ||||||
| } | } | ||||||
|  |  | ||||||
| float HONEYWELLABP2Sensor::get_pressure() { return this->last_pressure_; } | float HONEYWELLABP2Sensor::get_pressure() { return this->last_pressure_; } | ||||||
| @@ -79,7 +80,7 @@ void HONEYWELLABP2Sensor::update() { | |||||||
|   ESP_LOGV(TAG, "Update Honeywell ABP2 Sensor"); |   ESP_LOGV(TAG, "Update Honeywell ABP2 Sensor"); | ||||||
|  |  | ||||||
|   this->start_measurement(); |   this->start_measurement(); | ||||||
|   this->set_timeout("meas_timeout", 50, [this] { this->measurement_timeout(); }); |   this->set_timeout("meas_timeout", 100, [this] { this->measurement_timeout(); }); | ||||||
| } | } | ||||||
|  |  | ||||||
| void HONEYWELLABP2Sensor::dump_config() { | void HONEYWELLABP2Sensor::dump_config() { | ||||||
|   | |||||||
| @@ -1,5 +1,8 @@ | |||||||
| import logging | import logging | ||||||
|  |  | ||||||
|  | from esphome import pins | ||||||
|  | import esphome.codegen as cg | ||||||
|  | import esphome.config_validation as cv | ||||||
| from esphome.const import ( | from esphome.const import ( | ||||||
|     CONF_ID, |     CONF_ID, | ||||||
|     CONF_INPUT, |     CONF_INPUT, | ||||||
| @@ -11,9 +14,6 @@ from esphome.const import ( | |||||||
|     CONF_PULLDOWN, |     CONF_PULLDOWN, | ||||||
|     CONF_PULLUP, |     CONF_PULLUP, | ||||||
| ) | ) | ||||||
| from esphome import pins |  | ||||||
| import esphome.config_validation as cv |  | ||||||
| import esphome.codegen as cg |  | ||||||
|  |  | ||||||
| from .const import host_ns | from .const import host_ns | ||||||
|  |  | ||||||
| @@ -28,8 +28,10 @@ def _translate_pin(value): | |||||||
|             "This variable only supports pin numbers, not full pin schemas " |             "This variable only supports pin numbers, not full pin schemas " | ||||||
|             "(with inverted and mode)." |             "(with inverted and mode)." | ||||||
|         ) |         ) | ||||||
|     if isinstance(value, int): |     if isinstance(value, int) and not isinstance(value, bool): | ||||||
|         return value |         return value | ||||||
|  |     if not isinstance(value, str): | ||||||
|  |         raise cv.Invalid(f"Invalid pin number: {value}") | ||||||
|     try: |     try: | ||||||
|         return int(value) |         return int(value) | ||||||
|     except ValueError: |     except ValueError: | ||||||
|   | |||||||
| @@ -6,6 +6,7 @@ from esphome.const import ( | |||||||
|     CONF_ESP8266_DISABLE_SSL_SUPPORT, |     CONF_ESP8266_DISABLE_SSL_SUPPORT, | ||||||
|     CONF_ID, |     CONF_ID, | ||||||
|     CONF_METHOD, |     CONF_METHOD, | ||||||
|  |     CONF_ON_ERROR, | ||||||
|     CONF_TIMEOUT, |     CONF_TIMEOUT, | ||||||
|     CONF_TRIGGER_ID, |     CONF_TRIGGER_ID, | ||||||
|     CONF_URL, |     CONF_URL, | ||||||
| @@ -185,6 +186,13 @@ HTTP_REQUEST_ACTION_SCHEMA = cv.Schema( | |||||||
|         cv.Optional(CONF_ON_RESPONSE): automation.validate_automation( |         cv.Optional(CONF_ON_RESPONSE): automation.validate_automation( | ||||||
|             {cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(HttpRequestResponseTrigger)} |             {cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(HttpRequestResponseTrigger)} | ||||||
|         ), |         ), | ||||||
|  |         cv.Optional(CONF_ON_ERROR): automation.validate_automation( | ||||||
|  |             { | ||||||
|  |                 cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id( | ||||||
|  |                     automation.Trigger.template() | ||||||
|  |                 ) | ||||||
|  |             } | ||||||
|  |         ), | ||||||
|         cv.Optional(CONF_MAX_RESPONSE_BUFFER_SIZE, default="1kB"): cv.validate_bytes, |         cv.Optional(CONF_MAX_RESPONSE_BUFFER_SIZE, default="1kB"): cv.validate_bytes, | ||||||
|     } |     } | ||||||
| ) | ) | ||||||
| @@ -272,5 +280,9 @@ async def http_request_action_to_code(config, action_id, template_arg, args): | |||||||
|             ], |             ], | ||||||
|             conf, |             conf, | ||||||
|         ) |         ) | ||||||
|  |     for conf in config.get(CONF_ON_ERROR, []): | ||||||
|  |         trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID]) | ||||||
|  |         cg.add(var.register_error_trigger(trigger)) | ||||||
|  |         await automation.build_automation(trigger, [], conf) | ||||||
|  |  | ||||||
|     return var |     return var | ||||||
|   | |||||||
| @@ -22,6 +22,63 @@ struct Header { | |||||||
|   const char *value; |   const char *value; | ||||||
| }; | }; | ||||||
|  |  | ||||||
|  | // Some common HTTP status codes | ||||||
|  | enum HttpStatus { | ||||||
|  |   HTTP_STATUS_OK = 200, | ||||||
|  |   HTTP_STATUS_NO_CONTENT = 204, | ||||||
|  |   HTTP_STATUS_PARTIAL_CONTENT = 206, | ||||||
|  |  | ||||||
|  |   /* 3xx - Redirection */ | ||||||
|  |   HTTP_STATUS_MULTIPLE_CHOICES = 300, | ||||||
|  |   HTTP_STATUS_MOVED_PERMANENTLY = 301, | ||||||
|  |   HTTP_STATUS_FOUND = 302, | ||||||
|  |   HTTP_STATUS_SEE_OTHER = 303, | ||||||
|  |   HTTP_STATUS_NOT_MODIFIED = 304, | ||||||
|  |   HTTP_STATUS_TEMPORARY_REDIRECT = 307, | ||||||
|  |   HTTP_STATUS_PERMANENT_REDIRECT = 308, | ||||||
|  |  | ||||||
|  |   /* 4XX - CLIENT ERROR */ | ||||||
|  |   HTTP_STATUS_BAD_REQUEST = 400, | ||||||
|  |   HTTP_STATUS_UNAUTHORIZED = 401, | ||||||
|  |   HTTP_STATUS_FORBIDDEN = 403, | ||||||
|  |   HTTP_STATUS_NOT_FOUND = 404, | ||||||
|  |   HTTP_STATUS_METHOD_NOT_ALLOWED = 405, | ||||||
|  |   HTTP_STATUS_NOT_ACCEPTABLE = 406, | ||||||
|  |   HTTP_STATUS_LENGTH_REQUIRED = 411, | ||||||
|  |  | ||||||
|  |   /* 5xx - Server Error */ | ||||||
|  |   HTTP_STATUS_INTERNAL_ERROR = 500 | ||||||
|  | }; | ||||||
|  |  | ||||||
|  | /** | ||||||
|  |  * @brief Returns true if the HTTP status code is a redirect. | ||||||
|  |  * | ||||||
|  |  * @param status the HTTP status code to check | ||||||
|  |  * @return true if the status code is a redirect, false otherwise | ||||||
|  |  */ | ||||||
|  | inline bool is_redirect(int const status) { | ||||||
|  |   switch (status) { | ||||||
|  |     case HTTP_STATUS_MOVED_PERMANENTLY: | ||||||
|  |     case HTTP_STATUS_FOUND: | ||||||
|  |     case HTTP_STATUS_SEE_OTHER: | ||||||
|  |     case HTTP_STATUS_TEMPORARY_REDIRECT: | ||||||
|  |     case HTTP_STATUS_PERMANENT_REDIRECT: | ||||||
|  |       return true; | ||||||
|  |     default: | ||||||
|  |       return false; | ||||||
|  |   } | ||||||
|  | } | ||||||
|  |  | ||||||
|  | /** | ||||||
|  |  * @brief Checks if the given HTTP status code indicates a successful request. | ||||||
|  |  * | ||||||
|  |  * A successful request is one where the status code is in the range 200-299 | ||||||
|  |  * | ||||||
|  |  * @param status the HTTP status code to check | ||||||
|  |  * @return true if the status code indicates a successful request, false otherwise | ||||||
|  |  */ | ||||||
|  | inline bool is_success(int const status) { return status >= HTTP_STATUS_OK && status < HTTP_STATUS_MULTIPLE_CHOICES; } | ||||||
|  |  | ||||||
| class HttpRequestComponent; | class HttpRequestComponent; | ||||||
|  |  | ||||||
| class HttpContainer : public Parented<HttpRequestComponent> { | class HttpContainer : public Parented<HttpRequestComponent> { | ||||||
| @@ -78,8 +135,8 @@ class HttpRequestComponent : public Component { | |||||||
|  |  | ||||||
|  protected: |  protected: | ||||||
|   const char *useragent_{nullptr}; |   const char *useragent_{nullptr}; | ||||||
|   bool follow_redirects_; |   bool follow_redirects_{}; | ||||||
|   uint16_t redirect_limit_; |   uint16_t redirect_limit_{}; | ||||||
|   uint16_t timeout_{4500}; |   uint16_t timeout_{4500}; | ||||||
|   uint32_t watchdog_timeout_{0}; |   uint32_t watchdog_timeout_{0}; | ||||||
| }; | }; | ||||||
| @@ -100,6 +157,8 @@ template<typename... Ts> class HttpRequestSendAction : public Action<Ts...> { | |||||||
|  |  | ||||||
|   void register_response_trigger(HttpRequestResponseTrigger *trigger) { this->response_triggers_.push_back(trigger); } |   void register_response_trigger(HttpRequestResponseTrigger *trigger) { this->response_triggers_.push_back(trigger); } | ||||||
|  |  | ||||||
|  |   void register_error_trigger(Trigger<> *trigger) { this->error_triggers_.push_back(trigger); } | ||||||
|  |  | ||||||
|   void set_max_response_buffer_size(size_t max_response_buffer_size) { |   void set_max_response_buffer_size(size_t max_response_buffer_size) { | ||||||
|     this->max_response_buffer_size_ = max_response_buffer_size; |     this->max_response_buffer_size_ = max_response_buffer_size; | ||||||
|   } |   } | ||||||
| @@ -129,6 +188,8 @@ template<typename... Ts> class HttpRequestSendAction : public Action<Ts...> { | |||||||
|     auto container = this->parent_->start(this->url_.value(x...), this->method_.value(x...), body, headers); |     auto container = this->parent_->start(this->url_.value(x...), this->method_.value(x...), body, headers); | ||||||
|  |  | ||||||
|     if (container == nullptr) { |     if (container == nullptr) { | ||||||
|  |       for (auto *trigger : this->error_triggers_) | ||||||
|  |         trigger->trigger(); | ||||||
|       return; |       return; | ||||||
|     } |     } | ||||||
|  |  | ||||||
| @@ -180,7 +241,8 @@ template<typename... Ts> class HttpRequestSendAction : public Action<Ts...> { | |||||||
|   std::map<const char *, TemplatableValue<const char *, Ts...>> headers_{}; |   std::map<const char *, TemplatableValue<const char *, Ts...>> headers_{}; | ||||||
|   std::map<const char *, TemplatableValue<std::string, Ts...>> json_{}; |   std::map<const char *, TemplatableValue<std::string, Ts...>> json_{}; | ||||||
|   std::function<void(Ts..., JsonObject)> json_func_{nullptr}; |   std::function<void(Ts..., JsonObject)> json_func_{nullptr}; | ||||||
|   std::vector<HttpRequestResponseTrigger *> response_triggers_; |   std::vector<HttpRequestResponseTrigger *> response_triggers_{}; | ||||||
|  |   std::vector<Trigger<> *> error_triggers_{}; | ||||||
|  |  | ||||||
|   size_t max_response_buffer_size_{SIZE_MAX}; |   size_t max_response_buffer_size_{SIZE_MAX}; | ||||||
| }; | }; | ||||||
|   | |||||||
| @@ -104,7 +104,9 @@ std::shared_ptr<HttpContainer> HttpRequestArduino::start(std::string url, std::s | |||||||
|   static const size_t HEADER_COUNT = sizeof(header_keys) / sizeof(header_keys[0]); |   static const size_t HEADER_COUNT = sizeof(header_keys) / sizeof(header_keys[0]); | ||||||
|   container->client_.collectHeaders(header_keys, HEADER_COUNT); |   container->client_.collectHeaders(header_keys, HEADER_COUNT); | ||||||
|  |  | ||||||
|  |   App.feed_wdt(); | ||||||
|   container->status_code = container->client_.sendRequest(method.c_str(), body.c_str()); |   container->status_code = container->client_.sendRequest(method.c_str(), body.c_str()); | ||||||
|  |   App.feed_wdt(); | ||||||
|   if (container->status_code < 0) { |   if (container->status_code < 0) { | ||||||
|     ESP_LOGW(TAG, "HTTP Request failed; URL: %s; Error: %s", url.c_str(), |     ESP_LOGW(TAG, "HTTP Request failed; URL: %s; Error: %s", url.c_str(), | ||||||
|              HTTPClient::errorToString(container->status_code).c_str()); |              HTTPClient::errorToString(container->status_code).c_str()); | ||||||
| @@ -113,11 +115,10 @@ std::shared_ptr<HttpContainer> HttpRequestArduino::start(std::string url, std::s | |||||||
|     return nullptr; |     return nullptr; | ||||||
|   } |   } | ||||||
|  |  | ||||||
|   if (container->status_code < 200 || container->status_code >= 300) { |   if (!is_success(container->status_code)) { | ||||||
|     ESP_LOGE(TAG, "HTTP Request failed; URL: %s; Code: %d", url.c_str(), container->status_code); |     ESP_LOGE(TAG, "HTTP Request failed; URL: %s; Code: %d", url.c_str(), container->status_code); | ||||||
|     this->status_momentary_error("failed", 1000); |     this->status_momentary_error("failed", 1000); | ||||||
|     container->end(); |     // Still return the container, so it can be used to get the status code and error message | ||||||
|     return nullptr; |  | ||||||
|   } |   } | ||||||
|  |  | ||||||
|   int content_length = container->client_.getSize(); |   int content_length = container->client_.getSize(); | ||||||
|   | |||||||
| @@ -6,7 +6,6 @@ | |||||||
| #include "esphome/components/watchdog/watchdog.h" | #include "esphome/components/watchdog/watchdog.h" | ||||||
|  |  | ||||||
| #include "esphome/core/application.h" | #include "esphome/core/application.h" | ||||||
| #include "esphome/core/defines.h" |  | ||||||
| #include "esphome/core/log.h" | #include "esphome/core/log.h" | ||||||
|  |  | ||||||
| #if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE | #if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE | ||||||
| @@ -118,20 +117,17 @@ std::shared_ptr<HttpContainer> HttpRequestIDF::start(std::string url, std::strin | |||||||
|     return nullptr; |     return nullptr; | ||||||
|   } |   } | ||||||
|  |  | ||||||
|   auto is_ok = [](int code) { return code >= HttpStatus_Ok && code < HttpStatus_MultipleChoices; }; |   App.feed_wdt(); | ||||||
|  |  | ||||||
|   container->content_length = esp_http_client_fetch_headers(client); |   container->content_length = esp_http_client_fetch_headers(client); | ||||||
|  |   App.feed_wdt(); | ||||||
|   container->status_code = esp_http_client_get_status_code(client); |   container->status_code = esp_http_client_get_status_code(client); | ||||||
|   if (is_ok(container->status_code)) { |   App.feed_wdt(); | ||||||
|  |   if (is_success(container->status_code)) { | ||||||
|     container->duration_ms = millis() - start; |     container->duration_ms = millis() - start; | ||||||
|     return container; |     return container; | ||||||
|   } |   } | ||||||
|  |  | ||||||
|   if (this->follow_redirects_) { |   if (this->follow_redirects_) { | ||||||
|     auto is_redirect = [](int code) { |  | ||||||
|       return code == HttpStatus_MovedPermanently || code == HttpStatus_Found || code == HttpStatus_SeeOther || |  | ||||||
|              code == HttpStatus_TemporaryRedirect || code == HttpStatus_PermanentRedirect; |  | ||||||
|     }; |  | ||||||
|     auto num_redirects = this->redirect_limit_; |     auto num_redirects = this->redirect_limit_; | ||||||
|     while (is_redirect(container->status_code) && num_redirects > 0) { |     while (is_redirect(container->status_code) && num_redirects > 0) { | ||||||
|       err = esp_http_client_set_redirection(client); |       err = esp_http_client_set_redirection(client); | ||||||
| @@ -142,9 +138,9 @@ std::shared_ptr<HttpContainer> HttpRequestIDF::start(std::string url, std::strin | |||||||
|         return nullptr; |         return nullptr; | ||||||
|       } |       } | ||||||
| #if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE | #if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE | ||||||
|       char url[256]{}; |       char redirect_url[256]{}; | ||||||
|       if (esp_http_client_get_url(client, url, sizeof(url) - 1) == ESP_OK) { |       if (esp_http_client_get_url(client, redirect_url, sizeof(redirect_url) - 1) == ESP_OK) { | ||||||
|         ESP_LOGV(TAG, "redirecting to url: %s", url); |         ESP_LOGV(TAG, "redirecting to url: %s", redirect_url); | ||||||
|       } |       } | ||||||
| #endif | #endif | ||||||
|       err = esp_http_client_open(client, 0); |       err = esp_http_client_open(client, 0); | ||||||
| @@ -155,9 +151,12 @@ std::shared_ptr<HttpContainer> HttpRequestIDF::start(std::string url, std::strin | |||||||
|         return nullptr; |         return nullptr; | ||||||
|       } |       } | ||||||
|  |  | ||||||
|  |       App.feed_wdt(); | ||||||
|       container->content_length = esp_http_client_fetch_headers(client); |       container->content_length = esp_http_client_fetch_headers(client); | ||||||
|  |       App.feed_wdt(); | ||||||
|       container->status_code = esp_http_client_get_status_code(client); |       container->status_code = esp_http_client_get_status_code(client); | ||||||
|       if (is_ok(container->status_code)) { |       App.feed_wdt(); | ||||||
|  |       if (is_success(container->status_code)) { | ||||||
|         container->duration_ms = millis() - start; |         container->duration_ms = millis() - start; | ||||||
|         return container; |         return container; | ||||||
|       } |       } | ||||||
| @@ -172,8 +171,7 @@ std::shared_ptr<HttpContainer> HttpRequestIDF::start(std::string url, std::strin | |||||||
|  |  | ||||||
|   ESP_LOGE(TAG, "HTTP Request failed; URL: %s; Code: %d", url.c_str(), container->status_code); |   ESP_LOGE(TAG, "HTTP Request failed; URL: %s; Code: %d", url.c_str(), container->status_code); | ||||||
|   this->status_momentary_error("failed", 1000); |   this->status_momentary_error("failed", 1000); | ||||||
|   esp_http_client_cleanup(client); |   return container; | ||||||
|   return nullptr; |  | ||||||
| } | } | ||||||
|  |  | ||||||
| int HttpContainerIDF::read(uint8_t *buf, size_t max_len) { | int HttpContainerIDF::read(uint8_t *buf, size_t max_len) { | ||||||
|   | |||||||
| @@ -106,7 +106,7 @@ uint8_t OtaHttpRequestComponent::do_ota_() { | |||||||
|  |  | ||||||
|   auto container = this->parent_->get(url_with_auth); |   auto container = this->parent_->get(url_with_auth); | ||||||
|  |  | ||||||
|   if (container == nullptr) { |   if (container == nullptr || container->status_code != HTTP_STATUS_OK) { | ||||||
|     return OTA_CONNECTION_ERROR; |     return OTA_CONNECTION_ERROR; | ||||||
|   } |   } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -31,7 +31,7 @@ void HttpRequestUpdate::setup() { | |||||||
| void HttpRequestUpdate::update() { | void HttpRequestUpdate::update() { | ||||||
|   auto container = this->request_parent_->get(this->source_url_); |   auto container = this->request_parent_->get(this->source_url_); | ||||||
|  |  | ||||||
|   if (container == nullptr) { |   if (container == nullptr || container->status_code != HTTP_STATUS_OK) { | ||||||
|     std::string msg = str_sprintf("Failed to fetch manifest from %s", this->source_url_.c_str()); |     std::string msg = str_sprintf("Failed to fetch manifest from %s", this->source_url_.c_str()); | ||||||
|     this->status_set_error(msg.c_str()); |     this->status_set_error(msg.c_str()); | ||||||
|     return; |     return; | ||||||
|   | |||||||
| @@ -8,7 +8,7 @@ from esphome.components.esp32.const import ( | |||||||
|     VARIANT_ESP32S3, |     VARIANT_ESP32S3, | ||||||
| ) | ) | ||||||
| import esphome.config_validation as cv | import esphome.config_validation as cv | ||||||
| from esphome.const import CONF_CHANNEL, CONF_ID, CONF_SAMPLE_RATE | from esphome.const import CONF_BITS_PER_SAMPLE, CONF_CHANNEL, CONF_ID, CONF_SAMPLE_RATE | ||||||
| from esphome.cpp_generator import MockObjClass | from esphome.cpp_generator import MockObjClass | ||||||
| import esphome.final_validate as fv | import esphome.final_validate as fv | ||||||
|  |  | ||||||
| @@ -25,13 +25,11 @@ CONF_I2S_LRCLK_PIN = "i2s_lrclk_pin" | |||||||
| CONF_I2S_AUDIO = "i2s_audio" | CONF_I2S_AUDIO = "i2s_audio" | ||||||
| CONF_I2S_AUDIO_ID = "i2s_audio_id" | CONF_I2S_AUDIO_ID = "i2s_audio_id" | ||||||
|  |  | ||||||
| CONF_BITS_PER_SAMPLE = "bits_per_sample" |  | ||||||
| CONF_I2S_MODE = "i2s_mode" | CONF_I2S_MODE = "i2s_mode" | ||||||
| CONF_PRIMARY = "primary" | CONF_PRIMARY = "primary" | ||||||
| CONF_SECONDARY = "secondary" | CONF_SECONDARY = "secondary" | ||||||
|  |  | ||||||
| CONF_USE_APLL = "use_apll" | CONF_USE_APLL = "use_apll" | ||||||
| CONF_BITS_PER_SAMPLE = "bits_per_sample" |  | ||||||
| CONF_BITS_PER_CHANNEL = "bits_per_channel" | CONF_BITS_PER_CHANNEL = "bits_per_channel" | ||||||
| CONF_MONO = "mono" | CONF_MONO = "mono" | ||||||
| CONF_LEFT = "left" | CONF_LEFT = "left" | ||||||
|   | |||||||
| @@ -24,9 +24,10 @@ I2SAudioSpeaker = i2s_audio_ns.class_( | |||||||
|     "I2SAudioSpeaker", cg.Component, speaker.Speaker, I2SAudioOut |     "I2SAudioSpeaker", cg.Component, speaker.Speaker, I2SAudioOut | ||||||
| ) | ) | ||||||
|  |  | ||||||
|  | CONF_BUFFER_DURATION = "buffer_duration" | ||||||
| CONF_DAC_TYPE = "dac_type" | CONF_DAC_TYPE = "dac_type" | ||||||
| CONF_I2S_COMM_FMT = "i2s_comm_fmt" | CONF_I2S_COMM_FMT = "i2s_comm_fmt" | ||||||
|  | CONF_NEVER = "never" | ||||||
|  |  | ||||||
| i2s_dac_mode_t = cg.global_ns.enum("i2s_dac_mode_t") | i2s_dac_mode_t = cg.global_ns.enum("i2s_dac_mode_t") | ||||||
| INTERNAL_DAC_OPTIONS = { | INTERNAL_DAC_OPTIONS = { | ||||||
| @@ -73,8 +74,12 @@ BASE_SCHEMA = ( | |||||||
|     .extend( |     .extend( | ||||||
|         { |         { | ||||||
|             cv.Optional( |             cv.Optional( | ||||||
|                 CONF_TIMEOUT, default="500ms" |                 CONF_BUFFER_DURATION, default="500ms" | ||||||
|             ): cv.positive_time_period_milliseconds, |             ): cv.positive_time_period_milliseconds, | ||||||
|  |             cv.Optional(CONF_TIMEOUT, default="500ms"): cv.Any( | ||||||
|  |                 cv.positive_time_period_milliseconds, | ||||||
|  |                 cv.one_of(CONF_NEVER, lower=True), | ||||||
|  |             ), | ||||||
|         } |         } | ||||||
|     ) |     ) | ||||||
|     .extend(cv.COMPONENT_SCHEMA) |     .extend(cv.COMPONENT_SCHEMA) | ||||||
| @@ -116,4 +121,6 @@ async def to_code(config): | |||||||
|     else: |     else: | ||||||
|         cg.add(var.set_dout_pin(config[CONF_I2S_DOUT_PIN])) |         cg.add(var.set_dout_pin(config[CONF_I2S_DOUT_PIN])) | ||||||
|         cg.add(var.set_i2s_comm_fmt(config[CONF_I2S_COMM_FMT])) |         cg.add(var.set_i2s_comm_fmt(config[CONF_I2S_COMM_FMT])) | ||||||
|     cg.add(var.set_timeout(config[CONF_TIMEOUT])) |     if config[CONF_TIMEOUT] != CONF_NEVER: | ||||||
|  |         cg.add(var.set_timeout(config[CONF_TIMEOUT])) | ||||||
|  |     cg.add(var.set_buffer_duration(config[CONF_BUFFER_DURATION])) | ||||||
|   | |||||||
| @@ -13,21 +13,22 @@ | |||||||
| namespace esphome { | namespace esphome { | ||||||
| namespace i2s_audio { | namespace i2s_audio { | ||||||
|  |  | ||||||
| static const size_t DMA_BUFFER_SIZE = 512; | static const uint8_t DMA_BUFFER_DURATION_MS = 15; | ||||||
| static const size_t DMA_BUFFERS_COUNT = 4; | static const size_t DMA_BUFFERS_COUNT = 4; | ||||||
| static const size_t FRAMES_IN_ALL_DMA_BUFFERS = DMA_BUFFER_SIZE * DMA_BUFFERS_COUNT; |  | ||||||
| static const size_t RING_BUFFER_SAMPLES = 8192; | static const size_t TASK_DELAY_MS = DMA_BUFFER_DURATION_MS * DMA_BUFFERS_COUNT / 2; | ||||||
| static const size_t TASK_DELAY_MS = 10; |  | ||||||
| static const size_t TASK_STACK_SIZE = 4096; | static const size_t TASK_STACK_SIZE = 4096; | ||||||
| static const ssize_t TASK_PRIORITY = 23; | static const ssize_t TASK_PRIORITY = 23; | ||||||
|  |  | ||||||
|  | static const size_t I2S_EVENT_QUEUE_COUNT = DMA_BUFFERS_COUNT + 1; | ||||||
|  |  | ||||||
| static const char *const TAG = "i2s_audio.speaker"; | static const char *const TAG = "i2s_audio.speaker"; | ||||||
|  |  | ||||||
| enum SpeakerEventGroupBits : uint32_t { | enum SpeakerEventGroupBits : uint32_t { | ||||||
|   COMMAND_START = (1 << 0),                           // Starts the main task purpose |   COMMAND_START = (1 << 0),            // starts the speaker task | ||||||
|   COMMAND_STOP = (1 << 1),                            // stops the main task |   COMMAND_STOP = (1 << 1),             // stops the speaker task | ||||||
|   COMMAND_STOP_GRACEFULLY = (1 << 2),                 // Stops the task once all data has been written |   COMMAND_STOP_GRACEFULLY = (1 << 2),  // Stops the speaker task once all data has been written | ||||||
|   MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE = (1 << 5),  // Locks the ring buffer when not set |  | ||||||
|   STATE_STARTING = (1 << 10), |   STATE_STARTING = (1 << 10), | ||||||
|   STATE_RUNNING = (1 << 11), |   STATE_RUNNING = (1 << 11), | ||||||
|   STATE_STOPPING = (1 << 12), |   STATE_STOPPING = (1 << 12), | ||||||
| @@ -91,9 +92,7 @@ static const std::vector<int16_t> Q15_VOLUME_SCALING_FACTORS = { | |||||||
| void I2SAudioSpeaker::setup() { | void I2SAudioSpeaker::setup() { | ||||||
|   ESP_LOGCONFIG(TAG, "Setting up I2S Audio Speaker..."); |   ESP_LOGCONFIG(TAG, "Setting up I2S Audio Speaker..."); | ||||||
|  |  | ||||||
|   if (this->event_group_ == nullptr) { |   this->event_group_ = xEventGroupCreate(); | ||||||
|     this->event_group_ = xEventGroupCreate(); |  | ||||||
|   } |  | ||||||
|  |  | ||||||
|   if (this->event_group_ == nullptr) { |   if (this->event_group_ == nullptr) { | ||||||
|     ESP_LOGE(TAG, "Failed to create event group"); |     ESP_LOGE(TAG, "Failed to create event group"); | ||||||
| @@ -199,23 +198,17 @@ size_t I2SAudioSpeaker::play(const uint8_t *data, size_t length, TickType_t tick | |||||||
|     this->start(); |     this->start(); | ||||||
|   } |   } | ||||||
|  |  | ||||||
|   // Wait for the ring buffer to be available |   size_t bytes_written = 0; | ||||||
|   uint32_t event_bits = |   if ((this->state_ == speaker::STATE_RUNNING) && (this->audio_ring_buffer_.use_count() == 1)) { | ||||||
|       xEventGroupWaitBits(this->event_group_, SpeakerEventGroupBits::MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE, pdFALSE, |     // Only one owner of the ring buffer (the speaker task), so the ring buffer is allocated and no other components are | ||||||
|                           pdFALSE, pdMS_TO_TICKS(TASK_DELAY_MS)); |     // attempting to write to it. | ||||||
|  |  | ||||||
|   if (event_bits & SpeakerEventGroupBits::MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE) { |     // Temporarily share ownership of the ring buffer so it won't be deallocated while writing | ||||||
|     // Ring buffer is available to write |     std::shared_ptr<RingBuffer> temp_ring_buffer = this->audio_ring_buffer_; | ||||||
|  |     bytes_written = temp_ring_buffer->write_without_replacement((void *) data, length, ticks_to_wait); | ||||||
|     // Lock the ring buffer, write to it, then unlock it |  | ||||||
|     xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE); |  | ||||||
|     size_t bytes_written = this->audio_ring_buffer_->write_without_replacement((void *) data, length, ticks_to_wait); |  | ||||||
|     xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE); |  | ||||||
|  |  | ||||||
|     return bytes_written; |  | ||||||
|   } |   } | ||||||
|  |  | ||||||
|   return 0; |   return bytes_written; | ||||||
| } | } | ||||||
|  |  | ||||||
| bool I2SAudioSpeaker::has_buffered_data() const { | bool I2SAudioSpeaker::has_buffered_data() const { | ||||||
| @@ -246,10 +239,12 @@ void I2SAudioSpeaker::speaker_task(void *params) { | |||||||
|   const ssize_t bytes_per_sample = audio_stream_info.get_bytes_per_sample(); |   const ssize_t bytes_per_sample = audio_stream_info.get_bytes_per_sample(); | ||||||
|   const uint8_t number_of_channels = audio_stream_info.channels; |   const uint8_t number_of_channels = audio_stream_info.channels; | ||||||
|  |  | ||||||
|   const size_t dma_buffers_size = FRAMES_IN_ALL_DMA_BUFFERS * bytes_per_sample * number_of_channels; |   const size_t dma_buffers_size = DMA_BUFFERS_COUNT * DMA_BUFFER_DURATION_MS * this_speaker->sample_rate_ / 1000 * | ||||||
|  |                                   bytes_per_sample * number_of_channels; | ||||||
|  |   const size_t ring_buffer_size = | ||||||
|  |       this_speaker->buffer_duration_ms_ * this_speaker->sample_rate_ / 1000 * bytes_per_sample * number_of_channels; | ||||||
|  |  | ||||||
|   if (this_speaker->send_esp_err_to_event_group_( |   if (this_speaker->send_esp_err_to_event_group_(this_speaker->allocate_buffers_(dma_buffers_size, ring_buffer_size))) { | ||||||
|           this_speaker->allocate_buffers_(dma_buffers_size, RING_BUFFER_SAMPLES * bytes_per_sample))) { |  | ||||||
|     // Failed to allocate buffers |     // Failed to allocate buffers | ||||||
|     xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::ERR_ESP_NO_MEM); |     xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::ERR_ESP_NO_MEM); | ||||||
|     this_speaker->delete_task_(dma_buffers_size); |     this_speaker->delete_task_(dma_buffers_size); | ||||||
| @@ -258,9 +253,6 @@ void I2SAudioSpeaker::speaker_task(void *params) { | |||||||
|   if (this_speaker->send_esp_err_to_event_group_(this_speaker->start_i2s_driver_())) { |   if (this_speaker->send_esp_err_to_event_group_(this_speaker->start_i2s_driver_())) { | ||||||
|     // Failed to start I2S driver |     // Failed to start I2S driver | ||||||
|     this_speaker->delete_task_(dma_buffers_size); |     this_speaker->delete_task_(dma_buffers_size); | ||||||
|   } else { |  | ||||||
|     // Ring buffer is allocated, so indicate its can be written to |  | ||||||
|     xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE); |  | ||||||
|   } |   } | ||||||
|  |  | ||||||
|   if (!this_speaker->send_esp_err_to_event_group_(this_speaker->reconfigure_i2s_stream_info_(audio_stream_info))) { |   if (!this_speaker->send_esp_err_to_event_group_(this_speaker->reconfigure_i2s_stream_info_(audio_stream_info))) { | ||||||
| @@ -270,8 +262,10 @@ void I2SAudioSpeaker::speaker_task(void *params) { | |||||||
|  |  | ||||||
|     bool stop_gracefully = false; |     bool stop_gracefully = false; | ||||||
|     uint32_t last_data_received_time = millis(); |     uint32_t last_data_received_time = millis(); | ||||||
|  |     bool tx_dma_underflow = false; | ||||||
|  |  | ||||||
|     while ((millis() - last_data_received_time) <= this_speaker->timeout_) { |     while (!this_speaker->timeout_.has_value() || | ||||||
|  |            (millis() - last_data_received_time) <= this_speaker->timeout_.value()) { | ||||||
|       event_group_bits = xEventGroupGetBits(this_speaker->event_group_); |       event_group_bits = xEventGroupGetBits(this_speaker->event_group_); | ||||||
|  |  | ||||||
|       if (event_group_bits & SpeakerEventGroupBits::COMMAND_STOP) { |       if (event_group_bits & SpeakerEventGroupBits::COMMAND_STOP) { | ||||||
| @@ -281,12 +275,18 @@ void I2SAudioSpeaker::speaker_task(void *params) { | |||||||
|         stop_gracefully = true; |         stop_gracefully = true; | ||||||
|       } |       } | ||||||
|  |  | ||||||
|  |       i2s_event_t i2s_event; | ||||||
|  |       while (xQueueReceive(this_speaker->i2s_event_queue_, &i2s_event, 0)) { | ||||||
|  |         if (i2s_event.type == I2S_EVENT_TX_Q_OVF) { | ||||||
|  |           tx_dma_underflow = true; | ||||||
|  |         } | ||||||
|  |       } | ||||||
|  |  | ||||||
|       size_t bytes_to_read = dma_buffers_size; |       size_t bytes_to_read = dma_buffers_size; | ||||||
|       size_t bytes_read = this_speaker->audio_ring_buffer_->read((void *) this_speaker->data_buffer_, bytes_to_read, |       size_t bytes_read = this_speaker->audio_ring_buffer_->read((void *) this_speaker->data_buffer_, bytes_to_read, | ||||||
|                                                                  pdMS_TO_TICKS(TASK_DELAY_MS)); |                                                                  pdMS_TO_TICKS(TASK_DELAY_MS)); | ||||||
|  |  | ||||||
|       if (bytes_read > 0) { |       if (bytes_read > 0) { | ||||||
|         last_data_received_time = millis(); |  | ||||||
|         size_t bytes_written = 0; |         size_t bytes_written = 0; | ||||||
|  |  | ||||||
|         if ((audio_stream_info.bits_per_sample == 16) && (this_speaker->q15_volume_factor_ < INT16_MAX)) { |         if ((audio_stream_info.bits_per_sample == 16) && (this_speaker->q15_volume_factor_ < INT16_MAX)) { | ||||||
| @@ -307,15 +307,13 @@ void I2SAudioSpeaker::speaker_task(void *params) { | |||||||
|         if (bytes_written != bytes_read) { |         if (bytes_written != bytes_read) { | ||||||
|           xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::ERR_ESP_INVALID_SIZE); |           xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::ERR_ESP_INVALID_SIZE); | ||||||
|         } |         } | ||||||
|  |         tx_dma_underflow = false; | ||||||
|  |         last_data_received_time = millis(); | ||||||
|       } else { |       } else { | ||||||
|         // No data received |         // No data received | ||||||
|  |         if (stop_gracefully && tx_dma_underflow) { | ||||||
|         if (stop_gracefully) { |  | ||||||
|           break; |           break; | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         i2s_zero_dma_buffer(this_speaker->parent_->get_port()); |  | ||||||
|       } |       } | ||||||
|     } |     } | ||||||
|   } else { |   } else { | ||||||
| @@ -326,7 +324,6 @@ void I2SAudioSpeaker::speaker_task(void *params) { | |||||||
|  |  | ||||||
|   xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::STATE_STOPPING); |   xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::STATE_STOPPING); | ||||||
|  |  | ||||||
|   i2s_stop(this_speaker->parent_->get_port()); |  | ||||||
|   i2s_driver_uninstall(this_speaker->parent_->get_port()); |   i2s_driver_uninstall(this_speaker->parent_->get_port()); | ||||||
|  |  | ||||||
|   this_speaker->parent_->unlock(); |   this_speaker->parent_->unlock(); | ||||||
| @@ -334,7 +331,7 @@ void I2SAudioSpeaker::speaker_task(void *params) { | |||||||
| } | } | ||||||
|  |  | ||||||
| void I2SAudioSpeaker::start() { | void I2SAudioSpeaker::start() { | ||||||
|   if (this->is_failed() || this->status_has_error()) |   if (!this->is_ready() || this->is_failed() || this->status_has_error()) | ||||||
|     return; |     return; | ||||||
|   if ((this->state_ == speaker::STATE_STARTING) || (this->state_ == speaker::STATE_RUNNING)) |   if ((this->state_ == speaker::STATE_STARTING) || (this->state_ == speaker::STATE_RUNNING)) | ||||||
|     return; |     return; | ||||||
| @@ -402,8 +399,8 @@ esp_err_t I2SAudioSpeaker::allocate_buffers_(size_t data_buffer_size, size_t rin | |||||||
|     return ESP_ERR_NO_MEM; |     return ESP_ERR_NO_MEM; | ||||||
|   } |   } | ||||||
|  |  | ||||||
|   if (this->audio_ring_buffer_ == nullptr) { |   if (this->audio_ring_buffer_.use_count() == 0) { | ||||||
|     // Allocate ring buffer |     // Allocate ring buffer. Uses a shared_ptr to ensure it isn't improperly deallocated. | ||||||
|     this->audio_ring_buffer_ = RingBuffer::create(ring_buffer_size); |     this->audio_ring_buffer_ = RingBuffer::create(ring_buffer_size); | ||||||
|   } |   } | ||||||
|  |  | ||||||
| @@ -419,6 +416,8 @@ esp_err_t I2SAudioSpeaker::start_i2s_driver_() { | |||||||
|     return ESP_ERR_INVALID_STATE; |     return ESP_ERR_INVALID_STATE; | ||||||
|   } |   } | ||||||
|  |  | ||||||
|  |   int dma_buffer_length = DMA_BUFFER_DURATION_MS * this->sample_rate_ / 1000; | ||||||
|  |  | ||||||
|   i2s_driver_config_t config = { |   i2s_driver_config_t config = { | ||||||
|     .mode = (i2s_mode_t) (this->i2s_mode_ | I2S_MODE_TX), |     .mode = (i2s_mode_t) (this->i2s_mode_ | I2S_MODE_TX), | ||||||
|     .sample_rate = this->sample_rate_, |     .sample_rate = this->sample_rate_, | ||||||
| @@ -427,7 +426,7 @@ esp_err_t I2SAudioSpeaker::start_i2s_driver_() { | |||||||
|     .communication_format = this->i2s_comm_fmt_, |     .communication_format = this->i2s_comm_fmt_, | ||||||
|     .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, |     .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, | ||||||
|     .dma_buf_count = DMA_BUFFERS_COUNT, |     .dma_buf_count = DMA_BUFFERS_COUNT, | ||||||
|     .dma_buf_len = DMA_BUFFER_SIZE, |     .dma_buf_len = dma_buffer_length, | ||||||
|     .use_apll = this->use_apll_, |     .use_apll = this->use_apll_, | ||||||
|     .tx_desc_auto_clear = true, |     .tx_desc_auto_clear = true, | ||||||
|     .fixed_mclk = I2S_PIN_NO_CHANGE, |     .fixed_mclk = I2S_PIN_NO_CHANGE, | ||||||
| @@ -448,7 +447,8 @@ esp_err_t I2SAudioSpeaker::start_i2s_driver_() { | |||||||
|   } |   } | ||||||
| #endif | #endif | ||||||
|  |  | ||||||
|   esp_err_t err = i2s_driver_install(this->parent_->get_port(), &config, 0, nullptr); |   esp_err_t err = | ||||||
|  |       i2s_driver_install(this->parent_->get_port(), &config, I2S_EVENT_QUEUE_COUNT, &this->i2s_event_queue_); | ||||||
|   if (err != ESP_OK) { |   if (err != ESP_OK) { | ||||||
|     // Failed to install the driver, so unlock the I2S port |     // Failed to install the driver, so unlock the I2S port | ||||||
|     this->parent_->unlock(); |     this->parent_->unlock(); | ||||||
| @@ -502,16 +502,7 @@ esp_err_t I2SAudioSpeaker::reconfigure_i2s_stream_info_(audio::AudioStreamInfo & | |||||||
| } | } | ||||||
|  |  | ||||||
| void I2SAudioSpeaker::delete_task_(size_t buffer_size) { | void I2SAudioSpeaker::delete_task_(size_t buffer_size) { | ||||||
|   if (this->audio_ring_buffer_ != nullptr) { |   this->audio_ring_buffer_.reset();  // Releases onwership of the shared_ptr | ||||||
|     xEventGroupWaitBits(this->event_group_, |  | ||||||
|                         MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE,  // Bit message to read |  | ||||||
|                         pdFALSE,                                 // Don't clear the bits on exit |  | ||||||
|                         pdTRUE,                                  // Don't wait for all the bits, |  | ||||||
|                         portMAX_DELAY);                          // Block indefinitely until a command bit is set |  | ||||||
|  |  | ||||||
|     this->audio_ring_buffer_.reset();  // Deallocates the ring buffer stored in the unique_ptr |  | ||||||
|     this->audio_ring_buffer_ = nullptr; |  | ||||||
|   } |  | ||||||
|  |  | ||||||
|   if (this->data_buffer_ != nullptr) { |   if (this->data_buffer_ != nullptr) { | ||||||
|     ExternalRAMAllocator<uint8_t> allocator(ExternalRAMAllocator<uint8_t>::ALLOW_FAILURE); |     ExternalRAMAllocator<uint8_t> allocator(ExternalRAMAllocator<uint8_t>::ALLOW_FAILURE); | ||||||
|   | |||||||
| @@ -7,6 +7,7 @@ | |||||||
| #include <driver/i2s.h> | #include <driver/i2s.h> | ||||||
|  |  | ||||||
| #include <freertos/event_groups.h> | #include <freertos/event_groups.h> | ||||||
|  | #include <freertos/queue.h> | ||||||
| #include <freertos/FreeRTOS.h> | #include <freertos/FreeRTOS.h> | ||||||
|  |  | ||||||
| #include "esphome/components/audio/audio.h" | #include "esphome/components/audio/audio.h" | ||||||
| @@ -22,11 +23,12 @@ namespace i2s_audio { | |||||||
|  |  | ||||||
| class I2SAudioSpeaker : public I2SAudioOut, public speaker::Speaker, public Component { | class I2SAudioSpeaker : public I2SAudioOut, public speaker::Speaker, public Component { | ||||||
|  public: |  public: | ||||||
|   float get_setup_priority() const override { return esphome::setup_priority::LATE; } |   float get_setup_priority() const override { return esphome::setup_priority::PROCESSOR; } | ||||||
|  |  | ||||||
|   void setup() override; |   void setup() override; | ||||||
|   void loop() override; |   void loop() override; | ||||||
|  |  | ||||||
|  |   void set_buffer_duration(uint32_t buffer_duration_ms) { this->buffer_duration_ms_ = buffer_duration_ms; } | ||||||
|   void set_timeout(uint32_t ms) { this->timeout_ = ms; } |   void set_timeout(uint32_t ms) { this->timeout_ = ms; } | ||||||
|   void set_dout_pin(uint8_t pin) { this->dout_pin_ = pin; } |   void set_dout_pin(uint8_t pin) { this->dout_pin_ = pin; } | ||||||
| #if SOC_I2S_SUPPORTS_DAC | #if SOC_I2S_SUPPORTS_DAC | ||||||
| @@ -117,10 +119,14 @@ class I2SAudioSpeaker : public I2SAudioOut, public speaker::Speaker, public Comp | |||||||
|   TaskHandle_t speaker_task_handle_{nullptr}; |   TaskHandle_t speaker_task_handle_{nullptr}; | ||||||
|   EventGroupHandle_t event_group_{nullptr}; |   EventGroupHandle_t event_group_{nullptr}; | ||||||
|  |  | ||||||
|   uint8_t *data_buffer_; |   QueueHandle_t i2s_event_queue_; | ||||||
|   std::unique_ptr<RingBuffer> audio_ring_buffer_; |  | ||||||
|  |  | ||||||
|   uint32_t timeout_; |   uint8_t *data_buffer_; | ||||||
|  |   std::shared_ptr<RingBuffer> audio_ring_buffer_; | ||||||
|  |  | ||||||
|  |   uint32_t buffer_duration_ms_; | ||||||
|  |  | ||||||
|  |   optional<uint32_t> timeout_; | ||||||
|   uint8_t dout_pin_; |   uint8_t dout_pin_; | ||||||
|  |  | ||||||
|   bool task_created_{false}; |   bool task_created_{false}; | ||||||
|   | |||||||
| @@ -196,6 +196,10 @@ CONFIG_SCHEMA = cv.All( | |||||||
|     _validate, |     _validate, | ||||||
| ) | ) | ||||||
|  |  | ||||||
|  | FINAL_VALIDATE_SCHEMA = spi.final_validate_device_schema( | ||||||
|  |     "ili9xxx", require_miso=False, require_mosi=True | ||||||
|  | ) | ||||||
|  |  | ||||||
|  |  | ||||||
| async def to_code(config): | async def to_code(config): | ||||||
|     rhs = MODELS[config[CONF_MODEL]].new() |     rhs = MODELS[config[CONF_MODEL]].new() | ||||||
|   | |||||||
| @@ -313,8 +313,9 @@ void ILI9XXXDisplay::draw_pixels_at(int x_start, int y_start, int w, int h, cons | |||||||
|   // do color conversion pixel-by-pixel into the buffer and draw it later. If this is happening the user has not |   // do color conversion pixel-by-pixel into the buffer and draw it later. If this is happening the user has not | ||||||
|   // configured the renderer well. |   // configured the renderer well. | ||||||
|   if (this->rotation_ != display::DISPLAY_ROTATION_0_DEGREES || bitness != display::COLOR_BITNESS_565 || !big_endian) { |   if (this->rotation_ != display::DISPLAY_ROTATION_0_DEGREES || bitness != display::COLOR_BITNESS_565 || !big_endian) { | ||||||
|     return display::Display::draw_pixels_at(x_start, y_start, w, h, ptr, order, bitness, big_endian, x_offset, y_offset, |     display::Display::draw_pixels_at(x_start, y_start, w, h, ptr, order, bitness, big_endian, x_offset, y_offset, | ||||||
|                                             x_pad); |                                      x_pad); | ||||||
|  |     return; | ||||||
|   } |   } | ||||||
|   this->set_addr_window_(x_start, y_start, x_start + w - 1, y_start + h - 1); |   this->set_addr_window_(x_start, y_start, x_start + w - 1, y_start + h - 1); | ||||||
|   // x_ and y_offset are offsets into the source buffer, unrelated to our own offsets into the display. |   // x_ and y_offset are offsets into the source buffer, unrelated to our own offsets into the display. | ||||||
|   | |||||||
| @@ -8,8 +8,13 @@ extern "C" { | |||||||
| uint8_t temprature_sens_read(); | uint8_t temprature_sens_read(); | ||||||
| } | } | ||||||
| #elif defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6) || \ | #elif defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6) || \ | ||||||
|     defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3) |     defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3) || defined(USE_ESP32_VARIANT_ESP32H2) || \ | ||||||
|  |     defined(USE_ESP32_VARIANT_ESP32C2) | ||||||
|  | #if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) | ||||||
| #include "driver/temp_sensor.h" | #include "driver/temp_sensor.h" | ||||||
|  | #else | ||||||
|  | #include "driver/temperature_sensor.h" | ||||||
|  | #endif  // ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) | ||||||
| #endif  // USE_ESP32_VARIANT | #endif  // USE_ESP32_VARIANT | ||||||
| #endif  // USE_ESP32 | #endif  // USE_ESP32 | ||||||
| #ifdef USE_RP2040 | #ifdef USE_RP2040 | ||||||
| @@ -25,6 +30,13 @@ namespace esphome { | |||||||
| namespace internal_temperature { | namespace internal_temperature { | ||||||
|  |  | ||||||
| static const char *const TAG = "internal_temperature"; | static const char *const TAG = "internal_temperature"; | ||||||
|  | #ifdef USE_ESP32 | ||||||
|  | #if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)) && \ | ||||||
|  |     (defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6) || defined(USE_ESP32_VARIANT_ESP32S2) || \ | ||||||
|  |      defined(USE_ESP32_VARIANT_ESP32S3) || defined(USE_ESP32_VARIANT_ESP32H2) || defined(USE_ESP32_VARIANT_ESP32C2)) | ||||||
|  | static temperature_sensor_handle_t tsensNew = NULL; | ||||||
|  | #endif  // ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0) && USE_ESP32_VARIANT | ||||||
|  | #endif  // USE_ESP32 | ||||||
|  |  | ||||||
| void InternalTemperatureSensor::update() { | void InternalTemperatureSensor::update() { | ||||||
|   float temperature = NAN; |   float temperature = NAN; | ||||||
| @@ -36,7 +48,9 @@ void InternalTemperatureSensor::update() { | |||||||
|   temperature = (raw - 32) / 1.8f; |   temperature = (raw - 32) / 1.8f; | ||||||
|   success = (raw != 128); |   success = (raw != 128); | ||||||
| #elif defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6) || \ | #elif defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6) || \ | ||||||
|     defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3) |     defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3) || defined(USE_ESP32_VARIANT_ESP32H2) || \ | ||||||
|  |     defined(USE_ESP32_VARIANT_ESP32C2) | ||||||
|  | #if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) | ||||||
|   temp_sensor_config_t tsens = TSENS_CONFIG_DEFAULT(); |   temp_sensor_config_t tsens = TSENS_CONFIG_DEFAULT(); | ||||||
|   temp_sensor_set_config(tsens); |   temp_sensor_set_config(tsens); | ||||||
|   temp_sensor_start(); |   temp_sensor_start(); | ||||||
| @@ -47,6 +61,13 @@ void InternalTemperatureSensor::update() { | |||||||
|   esp_err_t result = temp_sensor_read_celsius(&temperature); |   esp_err_t result = temp_sensor_read_celsius(&temperature); | ||||||
|   temp_sensor_stop(); |   temp_sensor_stop(); | ||||||
|   success = (result == ESP_OK); |   success = (result == ESP_OK); | ||||||
|  | #else | ||||||
|  |   esp_err_t result = temperature_sensor_get_celsius(tsensNew, &temperature); | ||||||
|  |   success = (result == ESP_OK); | ||||||
|  |   if (!success) { | ||||||
|  |     ESP_LOGE(TAG, "Failed to get temperature: %d", result); | ||||||
|  |   } | ||||||
|  | #endif  // ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) | ||||||
| #endif  // USE_ESP32_VARIANT | #endif  // USE_ESP32_VARIANT | ||||||
| #endif  // USE_ESP32 | #endif  // USE_ESP32 | ||||||
| #ifdef USE_RP2040 | #ifdef USE_RP2040 | ||||||
| @@ -75,6 +96,32 @@ void InternalTemperatureSensor::update() { | |||||||
|   } |   } | ||||||
| } | } | ||||||
|  |  | ||||||
|  | void InternalTemperatureSensor::setup() { | ||||||
|  | #ifdef USE_ESP32 | ||||||
|  | #if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)) && \ | ||||||
|  |     (defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6) || defined(USE_ESP32_VARIANT_ESP32S2) || \ | ||||||
|  |      defined(USE_ESP32_VARIANT_ESP32S3) || defined(USE_ESP32_VARIANT_ESP32H2) || defined(USE_ESP32_VARIANT_ESP32C2)) | ||||||
|  |   ESP_LOGCONFIG(TAG, "Setting up temperature sensor..."); | ||||||
|  |  | ||||||
|  |   temperature_sensor_config_t tsens_config = TEMPERATURE_SENSOR_CONFIG_DEFAULT(-10, 80); | ||||||
|  |  | ||||||
|  |   esp_err_t result = temperature_sensor_install(&tsens_config, &tsensNew); | ||||||
|  |   if (result != ESP_OK) { | ||||||
|  |     ESP_LOGE(TAG, "Failed to install temperature sensor: %d", result); | ||||||
|  |     this->mark_failed(); | ||||||
|  |     return; | ||||||
|  |   } | ||||||
|  |  | ||||||
|  |   result = temperature_sensor_enable(tsensNew); | ||||||
|  |   if (result != ESP_OK) { | ||||||
|  |     ESP_LOGE(TAG, "Failed to enable temperature sensor: %d", result); | ||||||
|  |     this->mark_failed(); | ||||||
|  |     return; | ||||||
|  |   } | ||||||
|  | #endif  // ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0) && USE_ESP32_VARIANT | ||||||
|  | #endif  // USE_ESP32 | ||||||
|  | } | ||||||
|  |  | ||||||
| void InternalTemperatureSensor::dump_config() { LOG_SENSOR("", "Internal Temperature Sensor", this); } | void InternalTemperatureSensor::dump_config() { LOG_SENSOR("", "Internal Temperature Sensor", this); } | ||||||
|  |  | ||||||
| }  // namespace internal_temperature | }  // namespace internal_temperature | ||||||
|   | |||||||
| @@ -8,6 +8,7 @@ namespace internal_temperature { | |||||||
|  |  | ||||||
| class InternalTemperatureSensor : public sensor::Sensor, public PollingComponent { | class InternalTemperatureSensor : public sensor::Sensor, public PollingComponent { | ||||||
|  public: |  public: | ||||||
|  |   void setup() override; | ||||||
|   void dump_config() override; |   void dump_config() override; | ||||||
|  |  | ||||||
|   void update() override; |   void update() override; | ||||||
|   | |||||||
| @@ -180,7 +180,7 @@ void LD2420Component::apply_config_action() { | |||||||
| } | } | ||||||
|  |  | ||||||
| void LD2420Component::factory_reset_action() { | void LD2420Component::factory_reset_action() { | ||||||
|   ESP_LOGCONFIG(TAG, "Setiing factory defaults..."); |   ESP_LOGCONFIG(TAG, "Setting factory defaults..."); | ||||||
|   if (this->set_config_mode(true) == LD2420_ERROR_TIMEOUT) { |   if (this->set_config_mode(true) == LD2420_ERROR_TIMEOUT) { | ||||||
|     ESP_LOGE(TAG, "LD2420 module has failed to respond, check baud rate and serial connections."); |     ESP_LOGE(TAG, "LD2420 module has failed to respond, check baud rate and serial connections."); | ||||||
|     this->mark_failed(); |     this->mark_failed(); | ||||||
|   | |||||||
| @@ -1,8 +1,8 @@ | |||||||
| import logging | import logging | ||||||
|  |  | ||||||
|  | from esphome import pins | ||||||
| import esphome.codegen as cg | import esphome.codegen as cg | ||||||
| import esphome.config_validation as cv | import esphome.config_validation as cv | ||||||
| from esphome import pins |  | ||||||
| from esphome.const import ( | from esphome.const import ( | ||||||
|     CONF_ANALOG, |     CONF_ANALOG, | ||||||
|     CONF_ID, |     CONF_ID, | ||||||
| @@ -103,8 +103,10 @@ def _translate_pin(value): | |||||||
|             "This variable only supports pin numbers, not full pin schemas " |             "This variable only supports pin numbers, not full pin schemas " | ||||||
|             "(with inverted and mode)." |             "(with inverted and mode)." | ||||||
|         ) |         ) | ||||||
|     if isinstance(value, int): |     if isinstance(value, int) and not isinstance(value, bool): | ||||||
|         return value |         return value | ||||||
|  |     if not isinstance(value, str): | ||||||
|  |         raise cv.Invalid(f"Invalid pin number: {value}") | ||||||
|     try: |     try: | ||||||
|         return int(value) |         return int(value) | ||||||
|     except ValueError: |     except ValueError: | ||||||
|   | |||||||
| @@ -47,7 +47,7 @@ void Logger::write_header_(int level, const char *tag, int line) { | |||||||
|   if (current_task == main_task_) { |   if (current_task == main_task_) { | ||||||
|     this->printf_to_buffer_("%s[%s][%s:%03u]: ", color, letter, tag, line); |     this->printf_to_buffer_("%s[%s][%s:%03u]: ", color, letter, tag, line); | ||||||
|   } else { |   } else { | ||||||
|     const char *thread_name = ""; |     const char *thread_name = "";  // NOLINT(clang-analyzer-deadcode.DeadStores) | ||||||
| #if defined(USE_ESP32) | #if defined(USE_ESP32) | ||||||
|     thread_name = pcTaskGetName(current_task); |     thread_name = pcTaskGetName(current_task); | ||||||
| #elif defined(USE_LIBRETINY) | #elif defined(USE_LIBRETINY) | ||||||
|   | |||||||
| @@ -23,7 +23,7 @@ bool operator==(const GainTimePair &lhs, const GainTimePair &rhs) { | |||||||
| } | } | ||||||
|  |  | ||||||
| bool operator!=(const GainTimePair &lhs, const GainTimePair &rhs) { | bool operator!=(const GainTimePair &lhs, const GainTimePair &rhs) { | ||||||
|   return !(lhs.gain == rhs.gain && lhs.time == rhs.time); |   return lhs.gain != rhs.gain || lhs.time != rhs.time; | ||||||
| } | } | ||||||
|  |  | ||||||
| template<typename T, size_t size> T get_next(const T (&array)[size], const T val) { | template<typename T, size_t size> T get_next(const T (&array)[size], const T val) { | ||||||
|   | |||||||
| @@ -7,6 +7,7 @@ import esphome.config_validation as cv | |||||||
| from esphome.const import ( | from esphome.const import ( | ||||||
|     CONF_AUTO_CLEAR_ENABLED, |     CONF_AUTO_CLEAR_ENABLED, | ||||||
|     CONF_BUFFER_SIZE, |     CONF_BUFFER_SIZE, | ||||||
|  |     CONF_GROUP, | ||||||
|     CONF_ID, |     CONF_ID, | ||||||
|     CONF_LAMBDA, |     CONF_LAMBDA, | ||||||
|     CONF_ON_IDLE, |     CONF_ON_IDLE, | ||||||
| @@ -23,11 +24,17 @@ from esphome.helpers import write_file_if_changed | |||||||
| from . import defines as df, helpers, lv_validation as lvalid | from . import defines as df, helpers, lv_validation as lvalid | ||||||
| from .automation import disp_update, focused_widgets, update_to_code | from .automation import disp_update, focused_widgets, update_to_code | ||||||
| from .defines import add_define | from .defines import add_define | ||||||
| from .encoders import ENCODERS_CONFIG, encoders_to_code, initial_focus_to_code | from .encoders import ( | ||||||
|  |     ENCODERS_CONFIG, | ||||||
|  |     encoders_to_code, | ||||||
|  |     get_default_group, | ||||||
|  |     initial_focus_to_code, | ||||||
|  | ) | ||||||
| from .gradient import GRADIENT_SCHEMA, gradients_to_code | from .gradient import GRADIENT_SCHEMA, gradients_to_code | ||||||
| from .hello_world import get_hello_world | from .hello_world import get_hello_world | ||||||
|  | from .keypads import KEYPADS_CONFIG, keypads_to_code | ||||||
| from .lv_validation import lv_bool, lv_images_used | from .lv_validation import lv_bool, lv_images_used | ||||||
| from .lvcode import LvContext, LvglComponent | from .lvcode import LvContext, LvglComponent, lvgl_static | ||||||
| from .schemas import ( | from .schemas import ( | ||||||
|     DISP_BG_SCHEMA, |     DISP_BG_SCHEMA, | ||||||
|     FLEX_OBJ_SCHEMA, |     FLEX_OBJ_SCHEMA, | ||||||
| @@ -71,6 +78,7 @@ from .widgets.meter import meter_spec | |||||||
| from .widgets.msgbox import MSGBOX_SCHEMA, msgboxes_to_code | from .widgets.msgbox import MSGBOX_SCHEMA, msgboxes_to_code | ||||||
| from .widgets.obj import obj_spec | from .widgets.obj import obj_spec | ||||||
| from .widgets.page import add_pages, generate_page_triggers, page_spec | from .widgets.page import add_pages, generate_page_triggers, page_spec | ||||||
|  | from .widgets.qrcode import qr_code_spec | ||||||
| from .widgets.roller import roller_spec | from .widgets.roller import roller_spec | ||||||
| from .widgets.slider import slider_spec | from .widgets.slider import slider_spec | ||||||
| from .widgets.spinbox import spinbox_spec | from .widgets.spinbox import spinbox_spec | ||||||
| @@ -109,6 +117,7 @@ for w_type in ( | |||||||
|     spinbox_spec, |     spinbox_spec, | ||||||
|     keyboard_spec, |     keyboard_spec, | ||||||
|     tileview_spec, |     tileview_spec, | ||||||
|  |     qr_code_spec, | ||||||
| ): | ): | ||||||
|     WIDGET_TYPES[w_type.name] = w_type |     WIDGET_TYPES[w_type.name] = w_type | ||||||
|  |  | ||||||
| @@ -150,41 +159,78 @@ def generate_lv_conf_h(): | |||||||
|     return LV_CONF_H_FORMAT.format("\n".join(definitions)) |     return LV_CONF_H_FORMAT.format("\n".join(definitions)) | ||||||
|  |  | ||||||
|  |  | ||||||
| def final_validation(config): | def multi_conf_validate(configs: list[dict]): | ||||||
|     if pages := config.get(CONF_PAGES): |     displays = [config[df.CONF_DISPLAYS] for config in configs] | ||||||
|         if all(p[df.CONF_SKIP] for p in pages): |     # flatten the display list | ||||||
|             raise cv.Invalid("At least one page must not be skipped") |     display_list = [disp for disps in displays for disp in disps] | ||||||
|  |     if len(display_list) != len(set(display_list)): | ||||||
|  |         raise cv.Invalid("A display ID may be used in only one LVGL instance") | ||||||
|  |     for config in configs: | ||||||
|  |         for item in (df.CONF_ENCODERS, df.CONF_KEYPADS): | ||||||
|  |             for enc in config.get(item, ()): | ||||||
|  |                 if CONF_GROUP not in enc: | ||||||
|  |                     raise cv.Invalid( | ||||||
|  |                         f"'{item}' must have an explicit group set when using multiple LVGL instances" | ||||||
|  |                     ) | ||||||
|  |     base_config = configs[0] | ||||||
|  |     for config in configs[1:]: | ||||||
|  |         for item in ( | ||||||
|  |             df.CONF_LOG_LEVEL, | ||||||
|  |             df.CONF_COLOR_DEPTH, | ||||||
|  |             df.CONF_BYTE_ORDER, | ||||||
|  |             df.CONF_TRANSPARENCY_KEY, | ||||||
|  |         ): | ||||||
|  |             if base_config[item] != config[item]: | ||||||
|  |                 raise cv.Invalid( | ||||||
|  |                     f"Config item '{item}' must be the same for all LVGL instances" | ||||||
|  |                 ) | ||||||
|  |  | ||||||
|  |  | ||||||
|  | def final_validation(configs): | ||||||
|  |     if len(configs) != 1: | ||||||
|  |         multi_conf_validate(configs) | ||||||
|     global_config = full_config.get() |     global_config = full_config.get() | ||||||
|     for display_id in config[df.CONF_DISPLAYS]: |     for config in configs: | ||||||
|         path = global_config.get_path_for_id(display_id)[:-1] |         if pages := config.get(CONF_PAGES): | ||||||
|         display = global_config.get_config_for_path(path) |             if all(p[df.CONF_SKIP] for p in pages): | ||||||
|         if CONF_LAMBDA in display: |                 raise cv.Invalid("At least one page must not be skipped") | ||||||
|             raise cv.Invalid("Using lambda: in display config not compatible with LVGL") |         for display_id in config[df.CONF_DISPLAYS]: | ||||||
|         if display[CONF_AUTO_CLEAR_ENABLED]: |             path = global_config.get_path_for_id(display_id)[:-1] | ||||||
|             raise cv.Invalid( |             display = global_config.get_config_for_path(path) | ||||||
|                 "Using auto_clear_enabled: true in display config not compatible with LVGL" |             if CONF_LAMBDA in display: | ||||||
|             ) |                 raise cv.Invalid( | ||||||
|     buffer_frac = config[CONF_BUFFER_SIZE] |                     "Using lambda: in display config not compatible with LVGL" | ||||||
|     if CORE.is_esp32 and buffer_frac > 0.5 and "psram" not in global_config: |                 ) | ||||||
|         LOGGER.warning("buffer_size: may need to be reduced without PSRAM") |             if display[CONF_AUTO_CLEAR_ENABLED]: | ||||||
|     for image_id in lv_images_used: |                 raise cv.Invalid( | ||||||
|         path = global_config.get_path_for_id(image_id)[:-1] |                     "Using auto_clear_enabled: true in display config not compatible with LVGL" | ||||||
|         image_conf = global_config.get_config_for_path(path) |                 ) | ||||||
|         if image_conf[CONF_TYPE] in ("RGBA", "RGB24"): |         buffer_frac = config[CONF_BUFFER_SIZE] | ||||||
|             raise cv.Invalid( |         if CORE.is_esp32 and buffer_frac > 0.5 and "psram" not in global_config: | ||||||
|                 "Using RGBA or RGB24 in image config not compatible with LVGL", path |             LOGGER.warning("buffer_size: may need to be reduced without PSRAM") | ||||||
|             ) |         for image_id in lv_images_used: | ||||||
|     for w in focused_widgets: |             path = global_config.get_path_for_id(image_id)[:-1] | ||||||
|         path = global_config.get_path_for_id(w) |             image_conf = global_config.get_config_for_path(path) | ||||||
|         widget_conf = global_config.get_config_for_path(path[:-1]) |             if image_conf[CONF_TYPE] in ("RGBA", "RGB24"): | ||||||
|         if df.CONF_ADJUSTABLE in widget_conf and not widget_conf[df.CONF_ADJUSTABLE]: |                 raise cv.Invalid( | ||||||
|             raise cv.Invalid( |                     "Using RGBA or RGB24 in image config not compatible with LVGL", path | ||||||
|                 "A non adjustable arc may not be focused", |                 ) | ||||||
|                 path, |         for w in focused_widgets: | ||||||
|             ) |             path = global_config.get_path_for_id(w) | ||||||
|  |             widget_conf = global_config.get_config_for_path(path[:-1]) | ||||||
|  |             if ( | ||||||
|  |                 df.CONF_ADJUSTABLE in widget_conf | ||||||
|  |                 and not widget_conf[df.CONF_ADJUSTABLE] | ||||||
|  |             ): | ||||||
|  |                 raise cv.Invalid( | ||||||
|  |                     "A non adjustable arc may not be focused", | ||||||
|  |                     path, | ||||||
|  |                 ) | ||||||
|  |  | ||||||
|  |  | ||||||
| async def to_code(config): | async def to_code(configs): | ||||||
|  |     config_0 = configs[0] | ||||||
|  |     # Global configuration | ||||||
|     cg.add_library("lvgl/lvgl", "8.4.0") |     cg.add_library("lvgl/lvgl", "8.4.0") | ||||||
|     cg.add_define("USE_LVGL") |     cg.add_define("USE_LVGL") | ||||||
|     # suppress default enabling of extra widgets |     # suppress default enabling of extra widgets | ||||||
| @@ -201,53 +247,33 @@ async def to_code(config): | |||||||
|     add_define("LV_MEM_CUSTOM_INCLUDE", '"esphome/components/lvgl/lvgl_hal.h"') |     add_define("LV_MEM_CUSTOM_INCLUDE", '"esphome/components/lvgl/lvgl_hal.h"') | ||||||
|  |  | ||||||
|     add_define( |     add_define( | ||||||
|         "LV_LOG_LEVEL", f"LV_LOG_LEVEL_{df.LV_LOG_LEVELS[config[df.CONF_LOG_LEVEL]]}" |         "LV_LOG_LEVEL", | ||||||
|  |         f"LV_LOG_LEVEL_{df.LV_LOG_LEVELS[config_0[df.CONF_LOG_LEVEL]]}", | ||||||
|     ) |     ) | ||||||
|     cg.add_define( |     cg.add_define( | ||||||
|         "LVGL_LOG_LEVEL", |         "LVGL_LOG_LEVEL", | ||||||
|         cg.RawExpression(f"ESPHOME_LOG_LEVEL_{config[df.CONF_LOG_LEVEL]}"), |         cg.RawExpression(f"ESPHOME_LOG_LEVEL_{config_0[df.CONF_LOG_LEVEL]}"), | ||||||
|     ) |     ) | ||||||
|     add_define("LV_COLOR_DEPTH", config[df.CONF_COLOR_DEPTH]) |     add_define("LV_COLOR_DEPTH", config_0[df.CONF_COLOR_DEPTH]) | ||||||
|     for font in helpers.lv_fonts_used: |     for font in helpers.lv_fonts_used: | ||||||
|         add_define(f"LV_FONT_{font.upper()}") |         add_define(f"LV_FONT_{font.upper()}") | ||||||
|  |  | ||||||
|     if config[df.CONF_COLOR_DEPTH] == 16: |     if config_0[df.CONF_COLOR_DEPTH] == 16: | ||||||
|         add_define( |         add_define( | ||||||
|             "LV_COLOR_16_SWAP", |             "LV_COLOR_16_SWAP", | ||||||
|             "1" if config[df.CONF_BYTE_ORDER] == "big_endian" else "0", |             "1" if config_0[df.CONF_BYTE_ORDER] == "big_endian" else "0", | ||||||
|         ) |         ) | ||||||
|     add_define( |     add_define( | ||||||
|         "LV_COLOR_CHROMA_KEY", |         "LV_COLOR_CHROMA_KEY", | ||||||
|         await lvalid.lv_color.process(config[df.CONF_TRANSPARENCY_KEY]), |         await lvalid.lv_color.process(config_0[df.CONF_TRANSPARENCY_KEY]), | ||||||
|     ) |     ) | ||||||
|     cg.add_build_flag("-Isrc") |     cg.add_build_flag("-Isrc") | ||||||
|  |  | ||||||
|     cg.add_global(lvgl_ns.using) |     cg.add_global(lvgl_ns.using) | ||||||
|     frac = config[CONF_BUFFER_SIZE] |  | ||||||
|     if frac >= 0.75: |  | ||||||
|         frac = 1 |  | ||||||
|     elif frac >= 0.375: |  | ||||||
|         frac = 2 |  | ||||||
|     elif frac > 0.19: |  | ||||||
|         frac = 4 |  | ||||||
|     else: |  | ||||||
|         frac = 8 |  | ||||||
|     displays = [await cg.get_variable(display) for display in config[df.CONF_DISPLAYS]] |  | ||||||
|     lv_component = cg.new_Pvariable( |  | ||||||
|         config[CONF_ID], |  | ||||||
|         displays, |  | ||||||
|         frac, |  | ||||||
|         config[df.CONF_FULL_REFRESH], |  | ||||||
|         config[df.CONF_DRAW_ROUNDING], |  | ||||||
|         config[df.CONF_RESUME_ON_INPUT], |  | ||||||
|     ) |  | ||||||
|     await cg.register_component(lv_component, config) |  | ||||||
|     Widget.create(config[CONF_ID], lv_component, obj_spec, config) |  | ||||||
|  |  | ||||||
|     for font in helpers.esphome_fonts_used: |     for font in helpers.esphome_fonts_used: | ||||||
|         await cg.get_variable(font) |         await cg.get_variable(font) | ||||||
|         cg.new_Pvariable(ID(f"{font}_engine", True, type=FontEngine), MockObj(font)) |         cg.new_Pvariable(ID(f"{font}_engine", True, type=FontEngine), MockObj(font)) | ||||||
|     default_font = config[df.CONF_DEFAULT_FONT] |     default_font = config_0[df.CONF_DEFAULT_FONT] | ||||||
|     if not lvalid.is_lv_font(default_font): |     if not lvalid.is_lv_font(default_font): | ||||||
|         add_define( |         add_define( | ||||||
|             "LV_FONT_CUSTOM_DECLARE", f"LV_FONT_DECLARE(*{df.DEFAULT_ESPHOME_FONT})" |             "LV_FONT_CUSTOM_DECLARE", f"LV_FONT_DECLARE(*{df.DEFAULT_ESPHOME_FONT})" | ||||||
| @@ -263,39 +289,73 @@ async def to_code(config): | |||||||
|         add_define("LV_FONT_DEFAULT", df.DEFAULT_ESPHOME_FONT) |         add_define("LV_FONT_DEFAULT", df.DEFAULT_ESPHOME_FONT) | ||||||
|     else: |     else: | ||||||
|         add_define("LV_FONT_DEFAULT", await lvalid.lv_font.process(default_font)) |         add_define("LV_FONT_DEFAULT", await lvalid.lv_font.process(default_font)) | ||||||
|  |     cg.add(lvgl_static.esphome_lvgl_init()) | ||||||
|  |     default_group = get_default_group(config_0) | ||||||
|  |  | ||||||
|     lv_scr_act = get_scr_act(lv_component) |     for config in configs: | ||||||
|     async with LvContext(lv_component): |         frac = config[CONF_BUFFER_SIZE] | ||||||
|         await touchscreens_to_code(lv_component, config) |         if frac >= 0.75: | ||||||
|         await encoders_to_code(lv_component, config) |             frac = 1 | ||||||
|         await theme_to_code(config) |         elif frac >= 0.375: | ||||||
|         await styles_to_code(config) |             frac = 2 | ||||||
|         await gradients_to_code(config) |         elif frac > 0.19: | ||||||
|         await set_obj_properties(lv_scr_act, config) |             frac = 4 | ||||||
|         await add_widgets(lv_scr_act, config) |         else: | ||||||
|         await add_pages(lv_component, config) |             frac = 8 | ||||||
|         await add_top_layer(lv_component, config) |         displays = [ | ||||||
|         await msgboxes_to_code(lv_component, config) |             await cg.get_variable(display) for display in config[df.CONF_DISPLAYS] | ||||||
|         await disp_update(lv_component.get_disp(), config) |         ] | ||||||
|  |         lv_component = cg.new_Pvariable( | ||||||
|  |             config[CONF_ID], | ||||||
|  |             displays, | ||||||
|  |             frac, | ||||||
|  |             config[df.CONF_FULL_REFRESH], | ||||||
|  |             config[df.CONF_DRAW_ROUNDING], | ||||||
|  |             config[df.CONF_RESUME_ON_INPUT], | ||||||
|  |         ) | ||||||
|  |         await cg.register_component(lv_component, config) | ||||||
|  |         Widget.create(config[CONF_ID], lv_component, obj_spec, config) | ||||||
|  |  | ||||||
|  |         lv_scr_act = get_scr_act(lv_component) | ||||||
|  |         async with LvContext(): | ||||||
|  |             await touchscreens_to_code(lv_component, config) | ||||||
|  |             await encoders_to_code(lv_component, config, default_group) | ||||||
|  |             await keypads_to_code(lv_component, config, default_group) | ||||||
|  |             await theme_to_code(config) | ||||||
|  |             await gradients_to_code(config) | ||||||
|  |             await styles_to_code(config) | ||||||
|  |             await set_obj_properties(lv_scr_act, config) | ||||||
|  |             await add_widgets(lv_scr_act, config) | ||||||
|  |             await add_pages(lv_component, config) | ||||||
|  |             await add_top_layer(lv_component, config) | ||||||
|  |             await msgboxes_to_code(lv_component, config) | ||||||
|  |             await disp_update(lv_component.get_disp(), config) | ||||||
|     # Set this directly since we are limited in how many methods can be added to the Widget class. |     # Set this directly since we are limited in how many methods can be added to the Widget class. | ||||||
|     Widget.widgets_completed = True |     Widget.widgets_completed = True | ||||||
|     async with LvContext(lv_component): |     async with LvContext(): | ||||||
|         await generate_triggers(lv_component) |         await generate_triggers() | ||||||
|         await generate_page_triggers(lv_component, config) |         for config in configs: | ||||||
|         await initial_focus_to_code(config) |             lv_component = await cg.get_variable(config[CONF_ID]) | ||||||
|         for conf in config.get(CONF_ON_IDLE, ()): |             await generate_page_triggers(config) | ||||||
|             templ = await cg.templatable(conf[CONF_TIMEOUT], [], cg.uint32) |             await initial_focus_to_code(config) | ||||||
|             idle_trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], lv_component, templ) |             for conf in config.get(CONF_ON_IDLE, ()): | ||||||
|             await build_automation(idle_trigger, [], conf) |                 templ = await cg.templatable(conf[CONF_TIMEOUT], [], cg.uint32) | ||||||
|         for conf in config.get(df.CONF_ON_PAUSE, ()): |                 idle_trigger = cg.new_Pvariable( | ||||||
|             pause_trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], lv_component, True) |                     conf[CONF_TRIGGER_ID], lv_component, templ | ||||||
|             await build_automation(pause_trigger, [], conf) |                 ) | ||||||
|         for conf in config.get(df.CONF_ON_RESUME, ()): |                 await build_automation(idle_trigger, [], conf) | ||||||
|             resume_trigger = cg.new_Pvariable( |             for conf in config.get(df.CONF_ON_PAUSE, ()): | ||||||
|                 conf[CONF_TRIGGER_ID], lv_component, False |                 pause_trigger = cg.new_Pvariable( | ||||||
|             ) |                     conf[CONF_TRIGGER_ID], lv_component, True | ||||||
|             await build_automation(resume_trigger, [], conf) |                 ) | ||||||
|  |                 await build_automation(pause_trigger, [], conf) | ||||||
|  |             for conf in config.get(df.CONF_ON_RESUME, ()): | ||||||
|  |                 resume_trigger = cg.new_Pvariable( | ||||||
|  |                     conf[CONF_TRIGGER_ID], lv_component, False | ||||||
|  |                 ) | ||||||
|  |                 await build_automation(resume_trigger, [], conf) | ||||||
|  |  | ||||||
|  |     # This must be done after all widgets are created | ||||||
|     for comp in helpers.lvgl_components_required: |     for comp in helpers.lvgl_components_required: | ||||||
|         cg.add_define(f"USE_LVGL_{comp.upper()}") |         cg.add_define(f"USE_LVGL_{comp.upper()}") | ||||||
|     if "transform_angle" in styles_used: |     if "transform_angle" in styles_used: | ||||||
| @@ -310,7 +370,10 @@ async def to_code(config): | |||||||
|  |  | ||||||
| def display_schema(config): | def display_schema(config): | ||||||
|     value = cv.ensure_list(cv.use_id(Display))(config) |     value = cv.ensure_list(cv.use_id(Display))(config) | ||||||
|     return value or [cv.use_id(Display)(config)] |     value = value or [cv.use_id(Display)(config)] | ||||||
|  |     if len(set(value)) != len(value): | ||||||
|  |         raise cv.Invalid("Display IDs must be unique") | ||||||
|  |     return value | ||||||
|  |  | ||||||
|  |  | ||||||
| def add_hello_world(config): | def add_hello_world(config): | ||||||
| @@ -322,7 +385,7 @@ def add_hello_world(config): | |||||||
|  |  | ||||||
| FINAL_VALIDATE_SCHEMA = final_validation | FINAL_VALIDATE_SCHEMA = final_validation | ||||||
|  |  | ||||||
| CONFIG_SCHEMA = ( | LVGL_SCHEMA = ( | ||||||
|     cv.polling_component_schema("1s") |     cv.polling_component_schema("1s") | ||||||
|     .extend(obj_schema(obj_spec)) |     .extend(obj_schema(obj_spec)) | ||||||
|     .extend( |     .extend( | ||||||
| @@ -384,6 +447,7 @@ CONFIG_SCHEMA = ( | |||||||
|             cv.Optional(df.CONF_GRADIENTS): GRADIENT_SCHEMA, |             cv.Optional(df.CONF_GRADIENTS): GRADIENT_SCHEMA, | ||||||
|             cv.Optional(df.CONF_TOUCHSCREENS, default=None): touchscreen_schema, |             cv.Optional(df.CONF_TOUCHSCREENS, default=None): touchscreen_schema, | ||||||
|             cv.Optional(df.CONF_ENCODERS, default=None): ENCODERS_CONFIG, |             cv.Optional(df.CONF_ENCODERS, default=None): ENCODERS_CONFIG, | ||||||
|  |             cv.Optional(df.CONF_KEYPADS, default=None): KEYPADS_CONFIG, | ||||||
|             cv.GenerateID(df.CONF_DEFAULT_GROUP): cv.declare_id(lv_group_t), |             cv.GenerateID(df.CONF_DEFAULT_GROUP): cv.declare_id(lv_group_t), | ||||||
|             cv.Optional(df.CONF_RESUME_ON_INPUT, default=True): cv.boolean, |             cv.Optional(df.CONF_RESUME_ON_INPUT, default=True): cv.boolean, | ||||||
|         } |         } | ||||||
| @@ -391,3 +455,16 @@ CONFIG_SCHEMA = ( | |||||||
|     .extend(DISP_BG_SCHEMA) |     .extend(DISP_BG_SCHEMA) | ||||||
|     .add_extra(add_hello_world) |     .add_extra(add_hello_world) | ||||||
| ) | ) | ||||||
|  |  | ||||||
|  |  | ||||||
|  | def lvgl_config_schema(config): | ||||||
|  |     """ | ||||||
|  |     Can't use cv.ensure_list here because it converts an empty config to an empty list, | ||||||
|  |     rather than a default config. | ||||||
|  |     """ | ||||||
|  |     if not config or isinstance(config, dict): | ||||||
|  |         return [LVGL_SCHEMA(config)] | ||||||
|  |     return cv.Schema([LVGL_SCHEMA])(config) | ||||||
|  |  | ||||||
|  |  | ||||||
|  | CONFIG_SCHEMA = lvgl_config_schema | ||||||
|   | |||||||
| @@ -1,5 +1,4 @@ | |||||||
| from collections.abc import Awaitable | from typing import Any, Callable | ||||||
| from typing import Callable |  | ||||||
|  |  | ||||||
| from esphome import automation | from esphome import automation | ||||||
| import esphome.codegen as cg | import esphome.codegen as cg | ||||||
| @@ -23,7 +22,6 @@ from .lvcode import ( | |||||||
|     UPDATE_EVENT, |     UPDATE_EVENT, | ||||||
|     LambdaContext, |     LambdaContext, | ||||||
|     LocalVariable, |     LocalVariable, | ||||||
|     LvglComponent, |  | ||||||
|     ReturnStatement, |     ReturnStatement, | ||||||
|     add_line_marks, |     add_line_marks, | ||||||
|     lv, |     lv, | ||||||
| @@ -58,7 +56,7 @@ focused_widgets = set() | |||||||
|  |  | ||||||
| async def action_to_code( | async def action_to_code( | ||||||
|     widgets: list[Widget], |     widgets: list[Widget], | ||||||
|     action: Callable[[Widget], Awaitable[None]], |     action: Callable[[Widget], Any], | ||||||
|     action_id, |     action_id, | ||||||
|     template_arg, |     template_arg, | ||||||
|     args, |     args, | ||||||
| @@ -137,20 +135,18 @@ async def disp_update(disp, config: dict): | |||||||
|         cv.maybe_simple_value( |         cv.maybe_simple_value( | ||||||
|             { |             { | ||||||
|                 cv.Required(CONF_ID): cv.use_id(lv_obj_t), |                 cv.Required(CONF_ID): cv.use_id(lv_obj_t), | ||||||
|                 cv.GenerateID(CONF_LVGL_ID): cv.use_id(LvglComponent), |  | ||||||
|             }, |             }, | ||||||
|             key=CONF_ID, |             key=CONF_ID, | ||||||
|         ), |         ), | ||||||
|         cv.Schema( |         LVGL_SCHEMA, | ||||||
|             { |  | ||||||
|                 cv.GenerateID(CONF_LVGL_ID): cv.use_id(LvglComponent), |  | ||||||
|             } |  | ||||||
|         ), |  | ||||||
|     ), |     ), | ||||||
| ) | ) | ||||||
| async def obj_invalidate_to_code(config, action_id, template_arg, args): | async def obj_invalidate_to_code(config, action_id, template_arg, args): | ||||||
|     lv_comp = await cg.get_variable(config[CONF_LVGL_ID]) |     if CONF_LVGL_ID in config: | ||||||
|     widgets = await get_widgets(config) or [get_scr_act(lv_comp)] |         lv_comp = await cg.get_variable(config[CONF_LVGL_ID]) | ||||||
|  |         widgets = [get_scr_act(lv_comp)] | ||||||
|  |     else: | ||||||
|  |         widgets = await get_widgets(config) | ||||||
|  |  | ||||||
|     async def do_invalidate(widget: Widget): |     async def do_invalidate(widget: Widget): | ||||||
|         lv_obj.invalidate(widget.obj) |         lv_obj.invalidate(widget.obj) | ||||||
| @@ -161,14 +157,12 @@ async def obj_invalidate_to_code(config, action_id, template_arg, args): | |||||||
| @automation.register_action( | @automation.register_action( | ||||||
|     "lvgl.update", |     "lvgl.update", | ||||||
|     LvglAction, |     LvglAction, | ||||||
|     DISP_BG_SCHEMA.extend( |     DISP_BG_SCHEMA.extend(LVGL_SCHEMA).add_extra( | ||||||
|         { |         cv.has_at_least_one_key(CONF_DISP_BG_COLOR, CONF_DISP_BG_IMAGE) | ||||||
|             cv.GenerateID(): cv.use_id(LvglComponent), |     ), | ||||||
|         } |  | ||||||
|     ).add_extra(cv.has_at_least_one_key(CONF_DISP_BG_COLOR, CONF_DISP_BG_IMAGE)), |  | ||||||
| ) | ) | ||||||
| async def lvgl_update_to_code(config, action_id, template_arg, args): | async def lvgl_update_to_code(config, action_id, template_arg, args): | ||||||
|     widgets = await get_widgets(config) |     widgets = await get_widgets(config, CONF_LVGL_ID) | ||||||
|     w = widgets[0] |     w = widgets[0] | ||||||
|     disp = literal(f"{w.obj}->get_disp()") |     disp = literal(f"{w.obj}->get_disp()") | ||||||
|     async with LambdaContext(LVGL_COMP_ARG, where=action_id) as context: |     async with LambdaContext(LVGL_COMP_ARG, where=action_id) as context: | ||||||
| @@ -181,32 +175,33 @@ async def lvgl_update_to_code(config, action_id, template_arg, args): | |||||||
| @automation.register_action( | @automation.register_action( | ||||||
|     "lvgl.pause", |     "lvgl.pause", | ||||||
|     LvglAction, |     LvglAction, | ||||||
|     { |     LVGL_SCHEMA.extend( | ||||||
|         cv.GenerateID(): cv.use_id(LvglComponent), |         { | ||||||
|         cv.Optional(CONF_SHOW_SNOW, default=False): lv_bool, |             cv.Optional(CONF_SHOW_SNOW, default=False): lv_bool, | ||||||
|     }, |         } | ||||||
|  |     ), | ||||||
| ) | ) | ||||||
| async def pause_action_to_code(config, action_id, template_arg, args): | async def pause_action_to_code(config, action_id, template_arg, args): | ||||||
|  |     lv_comp = await cg.get_variable(config[CONF_LVGL_ID]) | ||||||
|     async with LambdaContext(LVGL_COMP_ARG) as context: |     async with LambdaContext(LVGL_COMP_ARG) as context: | ||||||
|         add_line_marks(where=action_id) |         add_line_marks(where=action_id) | ||||||
|         lv_add(lvgl_comp.set_paused(True, config[CONF_SHOW_SNOW])) |         lv_add(lvgl_comp.set_paused(True, config[CONF_SHOW_SNOW])) | ||||||
|     var = cg.new_Pvariable(action_id, template_arg, await context.get_lambda()) |     var = cg.new_Pvariable(action_id, template_arg, await context.get_lambda()) | ||||||
|     await cg.register_parented(var, config[CONF_ID]) |     await cg.register_parented(var, lv_comp) | ||||||
|     return var |     return var | ||||||
|  |  | ||||||
|  |  | ||||||
| @automation.register_action( | @automation.register_action( | ||||||
|     "lvgl.resume", |     "lvgl.resume", | ||||||
|     LvglAction, |     LvglAction, | ||||||
|     { |     LVGL_SCHEMA, | ||||||
|         cv.GenerateID(): cv.use_id(LvglComponent), |  | ||||||
|     }, |  | ||||||
| ) | ) | ||||||
| async def resume_action_to_code(config, action_id, template_arg, args): | async def resume_action_to_code(config, action_id, template_arg, args): | ||||||
|  |     lv_comp = await cg.get_variable(config[CONF_LVGL_ID]) | ||||||
|     async with LambdaContext(LVGL_COMP_ARG, where=action_id) as context: |     async with LambdaContext(LVGL_COMP_ARG, where=action_id) as context: | ||||||
|         lv_add(lvgl_comp.set_paused(False, False)) |         lv_add(lvgl_comp.set_paused(False, False)) | ||||||
|     var = cg.new_Pvariable(action_id, template_arg, await context.get_lambda()) |     var = cg.new_Pvariable(action_id, template_arg, await context.get_lambda()) | ||||||
|     await cg.register_parented(var, config[CONF_ID]) |     await cg.register_parented(var, lv_comp) | ||||||
|     return var |     return var | ||||||
|  |  | ||||||
|  |  | ||||||
| @@ -265,14 +260,15 @@ def focused_id(value): | |||||||
|     ObjUpdateAction, |     ObjUpdateAction, | ||||||
|     cv.Any( |     cv.Any( | ||||||
|         cv.maybe_simple_value( |         cv.maybe_simple_value( | ||||||
|             { |             LVGL_SCHEMA.extend( | ||||||
|                 cv.Optional(CONF_GROUP): cv.use_id(lv_group_t), |                 { | ||||||
|                 cv.Required(CONF_ACTION): cv.one_of( |                     cv.Optional(CONF_GROUP): cv.use_id(lv_group_t), | ||||||
|                     "MARK", "RESTORE", "NEXT", "PREVIOUS", upper=True |                     cv.Required(CONF_ACTION): cv.one_of( | ||||||
|                 ), |                         "MARK", "RESTORE", "NEXT", "PREVIOUS", upper=True | ||||||
|                 cv.GenerateID(CONF_LVGL_ID): cv.use_id(LvglComponent), |                     ), | ||||||
|                 cv.Optional(CONF_FREEZE, default=False): cv.boolean, |                     cv.Optional(CONF_FREEZE, default=False): cv.boolean, | ||||||
|             }, |                 } | ||||||
|  |             ), | ||||||
|             key=CONF_ACTION, |             key=CONF_ACTION, | ||||||
|         ), |         ), | ||||||
|         cv.maybe_simple_value( |         cv.maybe_simple_value( | ||||||
|   | |||||||
| @@ -1,4 +1,3 @@ | |||||||
| import esphome.codegen as cg |  | ||||||
| from esphome.components.binary_sensor import ( | from esphome.components.binary_sensor import ( | ||||||
|     BinarySensor, |     BinarySensor, | ||||||
|     binary_sensor_schema, |     binary_sensor_schema, | ||||||
| @@ -6,36 +5,30 @@ from esphome.components.binary_sensor import ( | |||||||
| ) | ) | ||||||
| import esphome.config_validation as cv | import esphome.config_validation as cv | ||||||
|  |  | ||||||
| from ..defines import CONF_LVGL_ID, CONF_WIDGET | from ..defines import CONF_WIDGET | ||||||
| from ..lvcode import EVENT_ARG, LambdaContext, LvContext | from ..lvcode import EVENT_ARG, LambdaContext, LvContext, lvgl_static | ||||||
| from ..schemas import LVGL_SCHEMA |  | ||||||
| from ..types import LV_EVENT, lv_pseudo_button_t | from ..types import LV_EVENT, lv_pseudo_button_t | ||||||
| from ..widgets import Widget, get_widgets, wait_for_widgets | from ..widgets import Widget, get_widgets, wait_for_widgets | ||||||
|  |  | ||||||
| CONFIG_SCHEMA = ( | CONFIG_SCHEMA = binary_sensor_schema(BinarySensor).extend( | ||||||
|     binary_sensor_schema(BinarySensor) |     { | ||||||
|     .extend(LVGL_SCHEMA) |         cv.Required(CONF_WIDGET): cv.use_id(lv_pseudo_button_t), | ||||||
|     .extend( |     } | ||||||
|         { |  | ||||||
|             cv.Required(CONF_WIDGET): cv.use_id(lv_pseudo_button_t), |  | ||||||
|         } |  | ||||||
|     ) |  | ||||||
| ) | ) | ||||||
|  |  | ||||||
|  |  | ||||||
| async def to_code(config): | async def to_code(config): | ||||||
|     sensor = await new_binary_sensor(config) |     sensor = await new_binary_sensor(config) | ||||||
|     paren = await cg.get_variable(config[CONF_LVGL_ID]) |  | ||||||
|     widget = await get_widgets(config, CONF_WIDGET) |     widget = await get_widgets(config, CONF_WIDGET) | ||||||
|     widget = widget[0] |     widget = widget[0] | ||||||
|     assert isinstance(widget, Widget) |     assert isinstance(widget, Widget) | ||||||
|     await wait_for_widgets() |     await wait_for_widgets() | ||||||
|     async with LambdaContext(EVENT_ARG) as pressed_ctx: |     async with LambdaContext(EVENT_ARG) as pressed_ctx: | ||||||
|         pressed_ctx.add(sensor.publish_state(widget.is_pressed())) |         pressed_ctx.add(sensor.publish_state(widget.is_pressed())) | ||||||
|     async with LvContext(paren) as ctx: |     async with LvContext() as ctx: | ||||||
|         ctx.add(sensor.publish_initial_state(widget.is_pressed())) |         ctx.add(sensor.publish_initial_state(widget.is_pressed())) | ||||||
|         ctx.add( |         ctx.add( | ||||||
|             paren.add_event_cb( |             lvgl_static.add_event_cb( | ||||||
|                 widget.obj, |                 widget.obj, | ||||||
|                 await pressed_ctx.get_lambda(), |                 await pressed_ctx.get_lambda(), | ||||||
|                 LV_EVENT.PRESSING, |                 LV_EVENT.PRESSING, | ||||||
|   | |||||||
| @@ -8,7 +8,7 @@ import logging | |||||||
|  |  | ||||||
| from esphome import codegen as cg, config_validation as cv | from esphome import codegen as cg, config_validation as cv | ||||||
| from esphome.const import CONF_ITEMS | from esphome.const import CONF_ITEMS | ||||||
| from esphome.core import Lambda | from esphome.core import ID, Lambda | ||||||
| from esphome.cpp_generator import LambdaExpression, MockObj | from esphome.cpp_generator import LambdaExpression, MockObj | ||||||
| from esphome.cpp_types import uint32 | from esphome.cpp_types import uint32 | ||||||
| from esphome.schema_extractors import SCHEMA_EXTRACT, schema_extractor | from esphome.schema_extractors import SCHEMA_EXTRACT, schema_extractor | ||||||
| @@ -72,6 +72,12 @@ class LValidator: | |||||||
|             ) |             ) | ||||||
|         if self.retmapper is not None: |         if self.retmapper is not None: | ||||||
|             return self.retmapper(value) |             return self.retmapper(value) | ||||||
|  |         if isinstance(value, ID): | ||||||
|  |             return await cg.get_variable(value) | ||||||
|  |         if isinstance(value, list): | ||||||
|  |             value = [ | ||||||
|  |                 await cg.get_variable(x) if isinstance(x, ID) else x for x in value | ||||||
|  |             ] | ||||||
|         return cg.safe_exp(value) |         return cg.safe_exp(value) | ||||||
|  |  | ||||||
|  |  | ||||||
| @@ -438,6 +444,7 @@ CONF_HEADER_MODE = "header_mode" | |||||||
| CONF_HOME = "home" | CONF_HOME = "home" | ||||||
| CONF_INITIAL_FOCUS = "initial_focus" | CONF_INITIAL_FOCUS = "initial_focus" | ||||||
| CONF_KEY_CODE = "key_code" | CONF_KEY_CODE = "key_code" | ||||||
|  | CONF_KEYPADS = "keypads" | ||||||
| CONF_LAYOUT = "layout" | CONF_LAYOUT = "layout" | ||||||
| CONF_LEFT_BUTTON = "left_button" | CONF_LEFT_BUTTON = "left_button" | ||||||
| CONF_LINE_WIDTH = "line_width" | CONF_LINE_WIDTH = "line_width" | ||||||
|   | |||||||
| @@ -17,7 +17,7 @@ from .defines import ( | |||||||
| from .helpers import lvgl_components_required, requires_component | from .helpers import lvgl_components_required, requires_component | ||||||
| from .lvcode import lv, lv_add, lv_assign, lv_expr, lv_Pvariable | from .lvcode import lv, lv_add, lv_assign, lv_expr, lv_Pvariable | ||||||
| from .schemas import ENCODER_SCHEMA | from .schemas import ENCODER_SCHEMA | ||||||
| from .types import lv_group_t, lv_indev_type_t | from .types import lv_group_t, lv_indev_type_t, lv_key_t | ||||||
|  |  | ||||||
| ENCODERS_CONFIG = cv.ensure_list( | ENCODERS_CONFIG = cv.ensure_list( | ||||||
|     ENCODER_SCHEMA.extend( |     ENCODER_SCHEMA.extend( | ||||||
| @@ -39,10 +39,13 @@ ENCODERS_CONFIG = cv.ensure_list( | |||||||
| ) | ) | ||||||
|  |  | ||||||
|  |  | ||||||
| async def encoders_to_code(var, config): | def get_default_group(config): | ||||||
|     default_group = lv_Pvariable(lv_group_t, config[CONF_DEFAULT_GROUP]) |     default_group = cg.Pvariable(config[CONF_DEFAULT_GROUP], lv_expr.group_create()) | ||||||
|     lv_assign(default_group, lv_expr.group_create()) |     cg.add(lv.group_set_default(default_group)) | ||||||
|     lv.group_set_default(default_group) |     return default_group | ||||||
|  |  | ||||||
|  |  | ||||||
|  | async def encoders_to_code(var, config, default_group): | ||||||
|     for enc_conf in config[CONF_ENCODERS]: |     for enc_conf in config[CONF_ENCODERS]: | ||||||
|         lvgl_components_required.add("KEY_LISTENER") |         lvgl_components_required.add("KEY_LISTENER") | ||||||
|         lpt = enc_conf[CONF_LONG_PRESS_TIME].total_milliseconds |         lpt = enc_conf[CONF_LONG_PRESS_TIME].total_milliseconds | ||||||
| @@ -54,14 +57,14 @@ async def encoders_to_code(var, config): | |||||||
|         if sensor_config := enc_conf.get(CONF_SENSOR): |         if sensor_config := enc_conf.get(CONF_SENSOR): | ||||||
|             if isinstance(sensor_config, dict): |             if isinstance(sensor_config, dict): | ||||||
|                 b_sensor = await cg.get_variable(sensor_config[CONF_LEFT_BUTTON]) |                 b_sensor = await cg.get_variable(sensor_config[CONF_LEFT_BUTTON]) | ||||||
|                 cg.add(listener.set_left_button(b_sensor)) |                 cg.add(listener.add_button(b_sensor, lv_key_t.LV_KEY_LEFT)) | ||||||
|                 b_sensor = await cg.get_variable(sensor_config[CONF_RIGHT_BUTTON]) |                 b_sensor = await cg.get_variable(sensor_config[CONF_RIGHT_BUTTON]) | ||||||
|                 cg.add(listener.set_right_button(b_sensor)) |                 cg.add(listener.add_button(b_sensor, lv_key_t.LV_KEY_RIGHT)) | ||||||
|             else: |             else: | ||||||
|                 sensor_config = await cg.get_variable(sensor_config) |                 sensor_config = await cg.get_variable(sensor_config) | ||||||
|                 lv_add(listener.set_sensor(sensor_config)) |                 lv_add(listener.set_sensor(sensor_config)) | ||||||
|         b_sensor = await cg.get_variable(enc_conf[CONF_ENTER_BUTTON]) |         b_sensor = await cg.get_variable(enc_conf[CONF_ENTER_BUTTON]) | ||||||
|         cg.add(listener.set_enter_button(b_sensor)) |         cg.add(listener.add_button(b_sensor, lv_key_t.LV_KEY_ENTER)) | ||||||
|         if group := enc_conf.get(CONF_GROUP): |         if group := enc_conf.get(CONF_GROUP): | ||||||
|             group = lv_Pvariable(lv_group_t, group) |             group = lv_Pvariable(lv_group_t, group) | ||||||
|             lv_assign(group, lv_expr.group_create()) |             lv_assign(group, lv_expr.group_create()) | ||||||
|   | |||||||
							
								
								
									
										77
									
								
								esphome/components/lvgl/keypads.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										77
									
								
								esphome/components/lvgl/keypads.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,77 @@ | |||||||
|  | import esphome.codegen as cg | ||||||
|  | from esphome.components.binary_sensor import BinarySensor | ||||||
|  | import esphome.config_validation as cv | ||||||
|  | from esphome.const import CONF_GROUP, CONF_ID | ||||||
|  |  | ||||||
|  | from .defines import ( | ||||||
|  |     CONF_ENCODERS, | ||||||
|  |     CONF_INITIAL_FOCUS, | ||||||
|  |     CONF_KEYPADS, | ||||||
|  |     CONF_LONG_PRESS_REPEAT_TIME, | ||||||
|  |     CONF_LONG_PRESS_TIME, | ||||||
|  |     literal, | ||||||
|  | ) | ||||||
|  | from .helpers import lvgl_components_required | ||||||
|  | from .lvcode import lv, lv_assign, lv_expr, lv_Pvariable | ||||||
|  | from .schemas import ENCODER_SCHEMA | ||||||
|  | from .types import lv_group_t, lv_indev_type_t | ||||||
|  |  | ||||||
|  | KEYPAD_KEYS = ( | ||||||
|  |     "up", | ||||||
|  |     "down", | ||||||
|  |     "right", | ||||||
|  |     "left", | ||||||
|  |     "esc", | ||||||
|  |     "del", | ||||||
|  |     "backspace", | ||||||
|  |     "enter", | ||||||
|  |     "next", | ||||||
|  |     "prev", | ||||||
|  |     "home", | ||||||
|  |     "end", | ||||||
|  |     "0", | ||||||
|  |     "1", | ||||||
|  |     "2", | ||||||
|  |     "3", | ||||||
|  |     "4", | ||||||
|  |     "5", | ||||||
|  |     "6", | ||||||
|  |     "7", | ||||||
|  |     "8", | ||||||
|  |     "9", | ||||||
|  |     "#", | ||||||
|  |     "*", | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | KEYPADS_CONFIG = cv.ensure_list( | ||||||
|  |     ENCODER_SCHEMA.extend( | ||||||
|  |         {cv.Optional(key): cv.use_id(BinarySensor) for key in KEYPAD_KEYS} | ||||||
|  |     ) | ||||||
|  | ) | ||||||
|  |  | ||||||
|  |  | ||||||
|  | async def keypads_to_code(var, config, default_group): | ||||||
|  |     for enc_conf in config[CONF_KEYPADS]: | ||||||
|  |         lvgl_components_required.add("KEY_LISTENER") | ||||||
|  |         lpt = enc_conf[CONF_LONG_PRESS_TIME].total_milliseconds | ||||||
|  |         lprt = enc_conf[CONF_LONG_PRESS_REPEAT_TIME].total_milliseconds | ||||||
|  |         listener = cg.new_Pvariable( | ||||||
|  |             enc_conf[CONF_ID], lv_indev_type_t.LV_INDEV_TYPE_KEYPAD, lpt, lprt | ||||||
|  |         ) | ||||||
|  |         await cg.register_parented(listener, var) | ||||||
|  |         for key in [x for x in enc_conf if x in KEYPAD_KEYS]: | ||||||
|  |             b_sensor = await cg.get_variable(enc_conf[key]) | ||||||
|  |             cg.add(listener.add_button(b_sensor, literal(f"LV_KEY_{key.upper()}"))) | ||||||
|  |         if group := enc_conf.get(CONF_GROUP): | ||||||
|  |             group = lv_Pvariable(lv_group_t, group) | ||||||
|  |             lv_assign(group, lv_expr.group_create()) | ||||||
|  |         else: | ||||||
|  |             group = default_group | ||||||
|  |         lv.indev_set_group(lv_expr.indev_drv_register(listener.get_drv()), group) | ||||||
|  |  | ||||||
|  |  | ||||||
|  | async def initial_focus_to_code(config): | ||||||
|  |     for enc_conf in config[CONF_ENCODERS]: | ||||||
|  |         if default_focus := enc_conf.get(CONF_INITIAL_FOCUS): | ||||||
|  |             obj = await cg.get_variable(default_focus) | ||||||
|  |             lv.group_focus_obj(obj) | ||||||
| @@ -4,9 +4,8 @@ from esphome.components.light import LightOutput | |||||||
| import esphome.config_validation as cv | import esphome.config_validation as cv | ||||||
| from esphome.const import CONF_GAMMA_CORRECT, CONF_OUTPUT_ID | from esphome.const import CONF_GAMMA_CORRECT, CONF_OUTPUT_ID | ||||||
|  |  | ||||||
| from ..defines import CONF_LVGL_ID, CONF_WIDGET | from ..defines import CONF_WIDGET | ||||||
| from ..lvcode import LvContext | from ..lvcode import LvContext | ||||||
| from ..schemas import LVGL_SCHEMA |  | ||||||
| from ..types import LvType, lvgl_ns | from ..types import LvType, lvgl_ns | ||||||
| from ..widgets import get_widgets, wait_for_widgets | from ..widgets import get_widgets, wait_for_widgets | ||||||
|  |  | ||||||
| @@ -18,16 +17,15 @@ CONFIG_SCHEMA = light.RGB_LIGHT_SCHEMA.extend( | |||||||
|         cv.Required(CONF_WIDGET): cv.use_id(lv_led_t), |         cv.Required(CONF_WIDGET): cv.use_id(lv_led_t), | ||||||
|         cv.GenerateID(CONF_OUTPUT_ID): cv.declare_id(LVLight), |         cv.GenerateID(CONF_OUTPUT_ID): cv.declare_id(LVLight), | ||||||
|     } |     } | ||||||
| ).extend(LVGL_SCHEMA) | ) | ||||||
|  |  | ||||||
|  |  | ||||||
| async def to_code(config): | async def to_code(config): | ||||||
|     var = cg.new_Pvariable(config[CONF_OUTPUT_ID]) |     var = cg.new_Pvariable(config[CONF_OUTPUT_ID]) | ||||||
|     await light.register_light(var, config) |     await light.register_light(var, config) | ||||||
|  |  | ||||||
|     paren = await cg.get_variable(config[CONF_LVGL_ID]) |  | ||||||
|     widget = await get_widgets(config, CONF_WIDGET) |     widget = await get_widgets(config, CONF_WIDGET) | ||||||
|     widget = widget[0] |     widget = widget[0] | ||||||
|     await wait_for_widgets() |     await wait_for_widgets() | ||||||
|     async with LvContext(paren) as ctx: |     async with LvContext() as ctx: | ||||||
|         ctx.add(var.set_obj(widget.obj)) |         ctx.add(var.set_obj(widget.obj)) | ||||||
|   | |||||||
| @@ -1,6 +1,7 @@ | |||||||
| from typing import Union | from typing import Union | ||||||
|  |  | ||||||
| import esphome.codegen as cg | import esphome.codegen as cg | ||||||
|  | from esphome.components import image | ||||||
| from esphome.components.color import CONF_HEX, ColorStruct, from_rgbw | from esphome.components.color import CONF_HEX, ColorStruct, from_rgbw | ||||||
| from esphome.components.font import Font | from esphome.components.font import Font | ||||||
| from esphome.components.image import Image_ | from esphome.components.image import Image_ | ||||||
| @@ -30,8 +31,8 @@ from .defines import ( | |||||||
|     call_lambda, |     call_lambda, | ||||||
|     literal, |     literal, | ||||||
| ) | ) | ||||||
| from .helpers import esphome_fonts_used, lv_fonts_used, requires_component | from .helpers import add_lv_use, esphome_fonts_used, lv_fonts_used, requires_component | ||||||
| from .types import lv_font_t, lv_gradient_t, lv_img_t | from .types import lv_font_t, lv_gradient_t | ||||||
|  |  | ||||||
| opacity_consts = LvConstant("LV_OPA_", "TRANSP", "COVER") | opacity_consts = LvConstant("LV_OPA_", "TRANSP", "COVER") | ||||||
|  |  | ||||||
| @@ -326,13 +327,18 @@ def image_validator(value): | |||||||
|     value = requires_component("image")(value) |     value = requires_component("image")(value) | ||||||
|     value = cv.use_id(Image_)(value) |     value = cv.use_id(Image_)(value) | ||||||
|     lv_images_used.add(value) |     lv_images_used.add(value) | ||||||
|  |     add_lv_use("img", "label") | ||||||
|     return value |     return value | ||||||
|  |  | ||||||
|  |  | ||||||
| lv_image = LValidator( | lv_image = LValidator( | ||||||
|     image_validator, |     image_validator, | ||||||
|     lv_img_t, |     image.Image_.operator("ptr"), | ||||||
|     retmapper=lambda x: MockObj(x, "->").get_lv_img_dsc(), |     requires="image", | ||||||
|  | ) | ||||||
|  | lv_image_list = LValidator( | ||||||
|  |     cv.ensure_list(image_validator), | ||||||
|  |     cg.std_vector.template(image.Image_.operator("ptr")), | ||||||
|     requires="image", |     requires="image", | ||||||
| ) | ) | ||||||
| lv_bool = LValidator(cv.boolean, cg.bool_, retmapper=literal) | lv_bool = LValidator(cv.boolean, cg.bool_, retmapper=literal) | ||||||
|   | |||||||
| @@ -178,10 +178,9 @@ class LvContext(LambdaContext): | |||||||
|  |  | ||||||
|     added_lambda_count = 0 |     added_lambda_count = 0 | ||||||
|  |  | ||||||
|     def __init__(self, lv_component, args=None): |     def __init__(self, args=None): | ||||||
|         self.args = args or LVGL_COMP_ARG |         self.args = args or LVGL_COMP_ARG | ||||||
|         super().__init__(parameters=self.args) |         super().__init__(parameters=self.args) | ||||||
|         self.lv_component = lv_component |  | ||||||
|  |  | ||||||
|     async def __aexit__(self, exc_type, exc_val, exc_tb): |     async def __aexit__(self, exc_type, exc_val, exc_tb): | ||||||
|         await super().__aexit__(exc_type, exc_val, exc_tb) |         await super().__aexit__(exc_type, exc_val, exc_tb) | ||||||
| @@ -298,6 +297,7 @@ lv_expr = LvExpr("lv_") | |||||||
| lv_obj = MockLv("lv_obj_") | lv_obj = MockLv("lv_obj_") | ||||||
| # Operations on the LVGL component | # Operations on the LVGL component | ||||||
| lvgl_comp = MockObj(LVGL_COMP, "->") | lvgl_comp = MockObj(LVGL_COMP, "->") | ||||||
|  | lvgl_static = MockObj("LvglComponent", "::") | ||||||
|  |  | ||||||
|  |  | ||||||
| # equivalent to cg.add() for the current code context | # equivalent to cg.add() for the current code context | ||||||
|   | |||||||
| @@ -98,19 +98,24 @@ void LvglComponent::set_paused(bool paused, bool show_snow) { | |||||||
|   this->pause_callbacks_.call(paused); |   this->pause_callbacks_.call(paused); | ||||||
| } | } | ||||||
|  |  | ||||||
|  | void LvglComponent::esphome_lvgl_init() { | ||||||
|  |   lv_init(); | ||||||
|  |   lv_update_event = static_cast<lv_event_code_t>(lv_event_register_id()); | ||||||
|  |   lv_api_event = static_cast<lv_event_code_t>(lv_event_register_id()); | ||||||
|  | } | ||||||
| void LvglComponent::add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event) { | void LvglComponent::add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event) { | ||||||
|   lv_obj_add_event_cb(obj, callback, event, this); |   lv_obj_add_event_cb(obj, callback, event, nullptr); | ||||||
| } | } | ||||||
| void LvglComponent::add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event1, | void LvglComponent::add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event1, | ||||||
|                                  lv_event_code_t event2) { |                                  lv_event_code_t event2) { | ||||||
|   this->add_event_cb(obj, callback, event1); |   add_event_cb(obj, callback, event1); | ||||||
|   this->add_event_cb(obj, callback, event2); |   add_event_cb(obj, callback, event2); | ||||||
| } | } | ||||||
| void LvglComponent::add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event1, | void LvglComponent::add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event1, | ||||||
|                                  lv_event_code_t event2, lv_event_code_t event3) { |                                  lv_event_code_t event2, lv_event_code_t event3) { | ||||||
|   this->add_event_cb(obj, callback, event1); |   add_event_cb(obj, callback, event1); | ||||||
|   this->add_event_cb(obj, callback, event2); |   add_event_cb(obj, callback, event2); | ||||||
|   this->add_event_cb(obj, callback, event3); |   add_event_cb(obj, callback, event3); | ||||||
| } | } | ||||||
| void LvglComponent::add_page(LvPageType *page) { | void LvglComponent::add_page(LvPageType *page) { | ||||||
|   this->pages_.push_back(page); |   this->pages_.push_back(page); | ||||||
| @@ -218,8 +223,10 @@ PauseTrigger::PauseTrigger(LvglComponent *parent, TemplatableValue<bool> paused) | |||||||
| } | } | ||||||
|  |  | ||||||
| #ifdef USE_LVGL_TOUCHSCREEN | #ifdef USE_LVGL_TOUCHSCREEN | ||||||
| LVTouchListener::LVTouchListener(uint16_t long_press_time, uint16_t long_press_repeat_time) { | LVTouchListener::LVTouchListener(uint16_t long_press_time, uint16_t long_press_repeat_time, LvglComponent *parent) { | ||||||
|  |   this->set_parent(parent); | ||||||
|   lv_indev_drv_init(&this->drv_); |   lv_indev_drv_init(&this->drv_); | ||||||
|  |   this->drv_.disp = parent->get_disp(); | ||||||
|   this->drv_.long_press_repeat_time = long_press_repeat_time; |   this->drv_.long_press_repeat_time = long_press_repeat_time; | ||||||
|   this->drv_.long_press_time = long_press_time; |   this->drv_.long_press_time = long_press_time; | ||||||
|   this->drv_.type = LV_INDEV_TYPE_POINTER; |   this->drv_.type = LV_INDEV_TYPE_POINTER; | ||||||
| @@ -235,6 +242,7 @@ LVTouchListener::LVTouchListener(uint16_t long_press_time, uint16_t long_press_r | |||||||
|     } |     } | ||||||
|   }; |   }; | ||||||
| } | } | ||||||
|  |  | ||||||
| void LVTouchListener::update(const touchscreen::TouchPoints_t &tpoints) { | void LVTouchListener::update(const touchscreen::TouchPoints_t &tpoints) { | ||||||
|   this->touch_pressed_ = !this->parent_->is_paused() && !tpoints.empty(); |   this->touch_pressed_ = !this->parent_->is_paused() && !tpoints.empty(); | ||||||
|   if (this->touch_pressed_) |   if (this->touch_pressed_) | ||||||
| @@ -271,7 +279,7 @@ std::string LvSelectable::get_selected_text() { | |||||||
| static std::string join_string(std::vector<std::string> options) { | static std::string join_string(std::vector<std::string> options) { | ||||||
|   return std::accumulate( |   return std::accumulate( | ||||||
|       options.begin(), options.end(), std::string(), |       options.begin(), options.end(), std::string(), | ||||||
|       [](const std::string &a, const std::string &b) -> std::string { return a + (a.length() > 0 ? "\n" : "") + b; }); |       [](const std::string &a, const std::string &b) -> std::string { return a + (!a.empty() ? "\n" : "") + b; }); | ||||||
| } | } | ||||||
|  |  | ||||||
| void LvSelectable::set_selected_text(const std::string &text, lv_anim_enable_t anim) { | void LvSelectable::set_selected_text(const std::string &text, lv_anim_enable_t anim) { | ||||||
| @@ -405,9 +413,6 @@ LvglComponent::LvglComponent(std::vector<display::Display *> displays, float buf | |||||||
|       buffer_frac_(buffer_frac), |       buffer_frac_(buffer_frac), | ||||||
|       full_refresh_(full_refresh), |       full_refresh_(full_refresh), | ||||||
|       resume_on_input_(resume_on_input) { |       resume_on_input_(resume_on_input) { | ||||||
|   lv_init(); |  | ||||||
|   lv_update_event = static_cast<lv_event_code_t>(lv_event_register_id()); |  | ||||||
|   lv_api_event = static_cast<lv_event_code_t>(lv_event_register_id()); |  | ||||||
|   auto *display = this->displays_[0]; |   auto *display = this->displays_[0]; | ||||||
|   size_t buffer_pixels = display->get_width() * display->get_height() / this->buffer_frac_; |   size_t buffer_pixels = display->get_width() * display->get_height() / this->buffer_frac_; | ||||||
|   auto buf_bytes = buffer_pixels * LV_COLOR_DEPTH / 8; |   auto buf_bytes = buffer_pixels * LV_COLOR_DEPTH / 8; | ||||||
|   | |||||||
| @@ -57,6 +57,22 @@ inline void lv_img_set_src(lv_obj_t *obj, esphome::image::Image *image) { | |||||||
|   lv_img_set_src(obj, image->get_lv_img_dsc()); |   lv_img_set_src(obj, image->get_lv_img_dsc()); | ||||||
| } | } | ||||||
| #endif  // USE_LVGL_IMAGE | #endif  // USE_LVGL_IMAGE | ||||||
|  | #ifdef USE_LVGL_ANIMIMG | ||||||
|  | inline void lv_animimg_set_src(lv_obj_t *img, std::vector<image::Image *> images) { | ||||||
|  |   auto *dsc = static_cast<std::vector<lv_img_dsc_t *> *>(lv_obj_get_user_data(img)); | ||||||
|  |   if (dsc == nullptr) { | ||||||
|  |     // object will be lazily allocated but never freed. | ||||||
|  |     dsc = new std::vector<lv_img_dsc_t *>(images.size());  // NOLINT | ||||||
|  |     lv_obj_set_user_data(img, dsc); | ||||||
|  |   } | ||||||
|  |   dsc->clear(); | ||||||
|  |   for (auto &image : images) { | ||||||
|  |     dsc->push_back(image->get_lv_img_dsc()); | ||||||
|  |   } | ||||||
|  |   lv_animimg_set_src(img, (const void **) dsc->data(), dsc->size()); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | #endif  // USE_LVGL_ANIMIMG | ||||||
|  |  | ||||||
| // Parent class for things that wrap an LVGL object | // Parent class for things that wrap an LVGL object | ||||||
| class LvCompound { | class LvCompound { | ||||||
| @@ -146,10 +162,14 @@ class LvglComponent : public PollingComponent { | |||||||
|     } |     } | ||||||
|   } |   } | ||||||
|  |  | ||||||
|   void add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event); |   /** | ||||||
|   void add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event1, lv_event_code_t event2); |    * Initialize the LVGL library and register custom events. | ||||||
|   void add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event1, lv_event_code_t event2, |    */ | ||||||
|                     lv_event_code_t event3); |   static void esphome_lvgl_init(); | ||||||
|  |   static void add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event); | ||||||
|  |   static void add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event1, lv_event_code_t event2); | ||||||
|  |   static void add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event1, lv_event_code_t event2, | ||||||
|  |                            lv_event_code_t event3); | ||||||
|   void add_page(LvPageType *page); |   void add_page(LvPageType *page); | ||||||
|   void show_page(size_t index, lv_scr_load_anim_t anim, uint32_t time); |   void show_page(size_t index, lv_scr_load_anim_t anim, uint32_t time); | ||||||
|   void show_next_page(lv_scr_load_anim_t anim, uint32_t time); |   void show_next_page(lv_scr_load_anim_t anim, uint32_t time); | ||||||
| @@ -231,7 +251,7 @@ template<typename... Ts> class LvglCondition : public Condition<Ts...>, public P | |||||||
| #ifdef USE_LVGL_TOUCHSCREEN | #ifdef USE_LVGL_TOUCHSCREEN | ||||||
| class LVTouchListener : public touchscreen::TouchListener, public Parented<LvglComponent> { | class LVTouchListener : public touchscreen::TouchListener, public Parented<LvglComponent> { | ||||||
|  public: |  public: | ||||||
|   LVTouchListener(uint16_t long_press_time, uint16_t long_press_repeat_time); |   LVTouchListener(uint16_t long_press_time, uint16_t long_press_repeat_time, LvglComponent *parent); | ||||||
|   void update(const touchscreen::TouchPoints_t &tpoints) override; |   void update(const touchscreen::TouchPoints_t &tpoints) override; | ||||||
|   void release() override { |   void release() override { | ||||||
|     touch_pressed_ = false; |     touch_pressed_ = false; | ||||||
| @@ -252,15 +272,8 @@ class LVEncoderListener : public Parented<LvglComponent> { | |||||||
|   LVEncoderListener(lv_indev_type_t type, uint16_t lpt, uint16_t lprt); |   LVEncoderListener(lv_indev_type_t type, uint16_t lpt, uint16_t lprt); | ||||||
|  |  | ||||||
| #ifdef USE_BINARY_SENSOR | #ifdef USE_BINARY_SENSOR | ||||||
|   void set_left_button(binary_sensor::BinarySensor *left_button) { |   void add_button(binary_sensor::BinarySensor *button, lv_key_t key) { | ||||||
|     left_button->add_on_state_callback([this](bool state) { this->event(LV_KEY_LEFT, state); }); |     button->add_on_state_callback([this, key](bool state) { this->event(key, state); }); | ||||||
|   } |  | ||||||
|   void set_right_button(binary_sensor::BinarySensor *right_button) { |  | ||||||
|     right_button->add_on_state_callback([this](bool state) { this->event(LV_KEY_RIGHT, state); }); |  | ||||||
|   } |  | ||||||
|  |  | ||||||
|   void set_enter_button(binary_sensor::BinarySensor *enter_button) { |  | ||||||
|     enter_button->add_on_state_callback([this](bool state) { this->event(LV_KEY_ENTER, state); }); |  | ||||||
|   } |   } | ||||||
| #endif | #endif | ||||||
|  |  | ||||||
|   | |||||||
| @@ -3,7 +3,7 @@ from esphome.components import number | |||||||
| import esphome.config_validation as cv | import esphome.config_validation as cv | ||||||
| from esphome.cpp_generator import MockObj | from esphome.cpp_generator import MockObj | ||||||
|  |  | ||||||
| from ..defines import CONF_ANIMATED, CONF_LVGL_ID, CONF_UPDATE_ON_RELEASE, CONF_WIDGET | from ..defines import CONF_ANIMATED, CONF_UPDATE_ON_RELEASE, CONF_WIDGET | ||||||
| from ..lv_validation import animated | from ..lv_validation import animated | ||||||
| from ..lvcode import ( | from ..lvcode import ( | ||||||
|     API_EVENT, |     API_EVENT, | ||||||
| @@ -13,28 +13,23 @@ from ..lvcode import ( | |||||||
|     LvContext, |     LvContext, | ||||||
|     lv, |     lv, | ||||||
|     lv_add, |     lv_add, | ||||||
|  |     lvgl_static, | ||||||
| ) | ) | ||||||
| from ..schemas import LVGL_SCHEMA |  | ||||||
| from ..types import LV_EVENT, LvNumber, lvgl_ns | from ..types import LV_EVENT, LvNumber, lvgl_ns | ||||||
| from ..widgets import get_widgets, wait_for_widgets | from ..widgets import get_widgets, wait_for_widgets | ||||||
|  |  | ||||||
| LVGLNumber = lvgl_ns.class_("LVGLNumber", number.Number) | LVGLNumber = lvgl_ns.class_("LVGLNumber", number.Number) | ||||||
|  |  | ||||||
| CONFIG_SCHEMA = ( | CONFIG_SCHEMA = number.number_schema(LVGLNumber).extend( | ||||||
|     number.number_schema(LVGLNumber) |     { | ||||||
|     .extend(LVGL_SCHEMA) |         cv.Required(CONF_WIDGET): cv.use_id(LvNumber), | ||||||
|     .extend( |         cv.Optional(CONF_ANIMATED, default=True): animated, | ||||||
|         { |         cv.Optional(CONF_UPDATE_ON_RELEASE, default=False): cv.boolean, | ||||||
|             cv.Required(CONF_WIDGET): cv.use_id(LvNumber), |     } | ||||||
|             cv.Optional(CONF_ANIMATED, default=True): animated, |  | ||||||
|             cv.Optional(CONF_UPDATE_ON_RELEASE, default=False): cv.boolean, |  | ||||||
|         } |  | ||||||
|     ) |  | ||||||
| ) | ) | ||||||
|  |  | ||||||
|  |  | ||||||
| async def to_code(config): | async def to_code(config): | ||||||
|     paren = await cg.get_variable(config[CONF_LVGL_ID]) |  | ||||||
|     widget = await get_widgets(config, CONF_WIDGET) |     widget = await get_widgets(config, CONF_WIDGET) | ||||||
|     widget = widget[0] |     widget = widget[0] | ||||||
|     var = await number.new_number( |     var = await number.new_number( | ||||||
| @@ -58,10 +53,10 @@ async def to_code(config): | |||||||
|         if not config[CONF_UPDATE_ON_RELEASE] |         if not config[CONF_UPDATE_ON_RELEASE] | ||||||
|         else LV_EVENT.RELEASED |         else LV_EVENT.RELEASED | ||||||
|     ) |     ) | ||||||
|     async with LvContext(paren): |     async with LvContext(): | ||||||
|         lv_add(var.set_control_lambda(await control.get_lambda())) |         lv_add(var.set_control_lambda(await control.get_lambda())) | ||||||
|         lv_add( |         lv_add( | ||||||
|             paren.add_event_cb( |             lvgl_static.add_event_cb( | ||||||
|                 widget.obj, await event.get_lambda(), UPDATE_EVENT, event_code |                 widget.obj, await event.get_lambda(), UPDATE_EVENT, event_code | ||||||
|             ) |             ) | ||||||
|         ) |         ) | ||||||
|   | |||||||
| @@ -341,6 +341,7 @@ FLEX_OBJ_SCHEMA = { | |||||||
|     cv.Optional(df.CONF_FLEX_GROW): cv.int_, |     cv.Optional(df.CONF_FLEX_GROW): cv.int_, | ||||||
| } | } | ||||||
|  |  | ||||||
|  |  | ||||||
| DISP_BG_SCHEMA = cv.Schema( | DISP_BG_SCHEMA = cv.Schema( | ||||||
|     { |     { | ||||||
|         cv.Optional(df.CONF_DISP_BG_IMAGE): lv_image, |         cv.Optional(df.CONF_DISP_BG_IMAGE): lv_image, | ||||||
| @@ -391,7 +392,9 @@ def container_validator(schema, widget_type: WidgetType): | |||||||
|             add_lv_use(ltype) |             add_lv_use(ltype) | ||||||
|         if value == SCHEMA_EXTRACT: |         if value == SCHEMA_EXTRACT: | ||||||
|             return result |             return result | ||||||
|         result = result.extend(LAYOUT_SCHEMAS[ltype.lower()]) |         result = result.extend( | ||||||
|  |             LAYOUT_SCHEMAS.get(ltype.lower(), LAYOUT_SCHEMAS[df.TYPE_NONE]) | ||||||
|  |         ) | ||||||
|         return result(value) |         return result(value) | ||||||
|  |  | ||||||
|     return validator |     return validator | ||||||
|   | |||||||
| @@ -1,25 +1,19 @@ | |||||||
| import esphome.codegen as cg |  | ||||||
| from esphome.components import select | from esphome.components import select | ||||||
| import esphome.config_validation as cv | import esphome.config_validation as cv | ||||||
| from esphome.const import CONF_OPTIONS | from esphome.const import CONF_OPTIONS | ||||||
|  |  | ||||||
| from ..defines import CONF_ANIMATED, CONF_LVGL_ID, CONF_WIDGET, literal | from ..defines import CONF_ANIMATED, CONF_WIDGET, literal | ||||||
| from ..lvcode import LvContext | from ..lvcode import LvContext | ||||||
| from ..schemas import LVGL_SCHEMA |  | ||||||
| from ..types import LvSelect, lvgl_ns | from ..types import LvSelect, lvgl_ns | ||||||
| from ..widgets import get_widgets, wait_for_widgets | from ..widgets import get_widgets, wait_for_widgets | ||||||
|  |  | ||||||
| LVGLSelect = lvgl_ns.class_("LVGLSelect", select.Select) | LVGLSelect = lvgl_ns.class_("LVGLSelect", select.Select) | ||||||
|  |  | ||||||
| CONFIG_SCHEMA = ( | CONFIG_SCHEMA = select.select_schema(LVGLSelect).extend( | ||||||
|     select.select_schema(LVGLSelect) |     { | ||||||
|     .extend(LVGL_SCHEMA) |         cv.Required(CONF_WIDGET): cv.use_id(LvSelect), | ||||||
|     .extend( |         cv.Optional(CONF_ANIMATED, default=False): cv.boolean, | ||||||
|         { |     } | ||||||
|             cv.Required(CONF_WIDGET): cv.use_id(LvSelect), |  | ||||||
|             cv.Optional(CONF_ANIMATED, default=False): cv.boolean, |  | ||||||
|         } |  | ||||||
|     ) |  | ||||||
| ) | ) | ||||||
|  |  | ||||||
|  |  | ||||||
| @@ -28,9 +22,8 @@ async def to_code(config): | |||||||
|     widget = widget[0] |     widget = widget[0] | ||||||
|     options = widget.config.get(CONF_OPTIONS, []) |     options = widget.config.get(CONF_OPTIONS, []) | ||||||
|     selector = await select.new_select(config, options=options) |     selector = await select.new_select(config, options=options) | ||||||
|     paren = await cg.get_variable(config[CONF_LVGL_ID]) |  | ||||||
|     await wait_for_widgets() |     await wait_for_widgets() | ||||||
|     async with LvContext(paren) as ctx: |     async with LvContext() as ctx: | ||||||
|         ctx.add( |         ctx.add( | ||||||
|             selector.set_widget( |             selector.set_widget( | ||||||
|                 widget.var, |                 widget.var, | ||||||
|   | |||||||
| @@ -1,8 +1,7 @@ | |||||||
| import esphome.codegen as cg |  | ||||||
| from esphome.components.sensor import Sensor, new_sensor, sensor_schema | from esphome.components.sensor import Sensor, new_sensor, sensor_schema | ||||||
| import esphome.config_validation as cv | import esphome.config_validation as cv | ||||||
|  |  | ||||||
| from ..defines import CONF_LVGL_ID, CONF_WIDGET | from ..defines import CONF_WIDGET | ||||||
| from ..lvcode import ( | from ..lvcode import ( | ||||||
|     API_EVENT, |     API_EVENT, | ||||||
|     EVENT_ARG, |     EVENT_ARG, | ||||||
| @@ -11,34 +10,29 @@ from ..lvcode import ( | |||||||
|     LambdaContext, |     LambdaContext, | ||||||
|     LvContext, |     LvContext, | ||||||
|     lv_add, |     lv_add, | ||||||
|  |     lvgl_static, | ||||||
| ) | ) | ||||||
| from ..schemas import LVGL_SCHEMA |  | ||||||
| from ..types import LV_EVENT, LvNumber | from ..types import LV_EVENT, LvNumber | ||||||
| from ..widgets import Widget, get_widgets, wait_for_widgets | from ..widgets import Widget, get_widgets, wait_for_widgets | ||||||
|  |  | ||||||
| CONFIG_SCHEMA = ( | CONFIG_SCHEMA = sensor_schema(Sensor).extend( | ||||||
|     sensor_schema(Sensor) |     { | ||||||
|     .extend(LVGL_SCHEMA) |         cv.Required(CONF_WIDGET): cv.use_id(LvNumber), | ||||||
|     .extend( |     } | ||||||
|         { |  | ||||||
|             cv.Required(CONF_WIDGET): cv.use_id(LvNumber), |  | ||||||
|         } |  | ||||||
|     ) |  | ||||||
| ) | ) | ||||||
|  |  | ||||||
|  |  | ||||||
| async def to_code(config): | async def to_code(config): | ||||||
|     sensor = await new_sensor(config) |     sensor = await new_sensor(config) | ||||||
|     paren = await cg.get_variable(config[CONF_LVGL_ID]) |  | ||||||
|     widget = await get_widgets(config, CONF_WIDGET) |     widget = await get_widgets(config, CONF_WIDGET) | ||||||
|     widget = widget[0] |     widget = widget[0] | ||||||
|     assert isinstance(widget, Widget) |     assert isinstance(widget, Widget) | ||||||
|     await wait_for_widgets() |     await wait_for_widgets() | ||||||
|     async with LambdaContext(EVENT_ARG) as lamb: |     async with LambdaContext(EVENT_ARG) as lamb: | ||||||
|         lv_add(sensor.publish_state(widget.get_value())) |         lv_add(sensor.publish_state(widget.get_value())) | ||||||
|     async with LvContext(paren, LVGL_COMP_ARG): |     async with LvContext(LVGL_COMP_ARG): | ||||||
|         lv_add( |         lv_add( | ||||||
|             paren.add_event_cb( |             lvgl_static.add_event_cb( | ||||||
|                 widget.obj, |                 widget.obj, | ||||||
|                 await lamb.get_lambda(), |                 await lamb.get_lambda(), | ||||||
|                 LV_EVENT.VALUE_CHANGED, |                 LV_EVENT.VALUE_CHANGED, | ||||||
|   | |||||||
| @@ -3,7 +3,7 @@ from esphome.components.switch import Switch, new_switch, switch_schema | |||||||
| import esphome.config_validation as cv | import esphome.config_validation as cv | ||||||
| from esphome.cpp_generator import MockObj | from esphome.cpp_generator import MockObj | ||||||
|  |  | ||||||
| from ..defines import CONF_LVGL_ID, CONF_WIDGET, literal | from ..defines import CONF_WIDGET, literal | ||||||
| from ..lvcode import ( | from ..lvcode import ( | ||||||
|     API_EVENT, |     API_EVENT, | ||||||
|     EVENT_ARG, |     EVENT_ARG, | ||||||
| @@ -13,26 +13,21 @@ from ..lvcode import ( | |||||||
|     LvContext, |     LvContext, | ||||||
|     lv, |     lv, | ||||||
|     lv_add, |     lv_add, | ||||||
|  |     lvgl_static, | ||||||
| ) | ) | ||||||
| from ..schemas import LVGL_SCHEMA |  | ||||||
| from ..types import LV_EVENT, LV_STATE, lv_pseudo_button_t, lvgl_ns | from ..types import LV_EVENT, LV_STATE, lv_pseudo_button_t, lvgl_ns | ||||||
| from ..widgets import get_widgets, wait_for_widgets | from ..widgets import get_widgets, wait_for_widgets | ||||||
|  |  | ||||||
| LVGLSwitch = lvgl_ns.class_("LVGLSwitch", Switch) | LVGLSwitch = lvgl_ns.class_("LVGLSwitch", Switch) | ||||||
| CONFIG_SCHEMA = ( | CONFIG_SCHEMA = switch_schema(LVGLSwitch).extend( | ||||||
|     switch_schema(LVGLSwitch) |     { | ||||||
|     .extend(LVGL_SCHEMA) |         cv.Required(CONF_WIDGET): cv.use_id(lv_pseudo_button_t), | ||||||
|     .extend( |     } | ||||||
|         { |  | ||||||
|             cv.Required(CONF_WIDGET): cv.use_id(lv_pseudo_button_t), |  | ||||||
|         } |  | ||||||
|     ) |  | ||||||
| ) | ) | ||||||
|  |  | ||||||
|  |  | ||||||
| async def to_code(config): | async def to_code(config): | ||||||
|     switch = await new_switch(config) |     switch = await new_switch(config) | ||||||
|     paren = await cg.get_variable(config[CONF_LVGL_ID]) |  | ||||||
|     widget = await get_widgets(config, CONF_WIDGET) |     widget = await get_widgets(config, CONF_WIDGET) | ||||||
|     widget = widget[0] |     widget = widget[0] | ||||||
|     await wait_for_widgets() |     await wait_for_widgets() | ||||||
| @@ -45,10 +40,10 @@ async def to_code(config): | |||||||
|             widget.clear_state(LV_STATE.CHECKED) |             widget.clear_state(LV_STATE.CHECKED) | ||||||
|         lv.event_send(widget.obj, API_EVENT, cg.nullptr) |         lv.event_send(widget.obj, API_EVENT, cg.nullptr) | ||||||
|         control.add(switch.publish_state(literal("v"))) |         control.add(switch.publish_state(literal("v"))) | ||||||
|     async with LvContext(paren) as ctx: |     async with LvContext() as ctx: | ||||||
|         lv_add(switch.set_control_lambda(await control.get_lambda())) |         lv_add(switch.set_control_lambda(await control.get_lambda())) | ||||||
|         ctx.add( |         ctx.add( | ||||||
|             paren.add_event_cb( |             lvgl_static.add_event_cb( | ||||||
|                 widget.obj, |                 widget.obj, | ||||||
|                 await checked_ctx.get_lambda(), |                 await checked_ctx.get_lambda(), | ||||||
|                 LV_EVENT.VALUE_CHANGED, |                 LV_EVENT.VALUE_CHANGED, | ||||||
|   | |||||||
| @@ -3,7 +3,7 @@ from esphome.components import text | |||||||
| from esphome.components.text import new_text | from esphome.components.text import new_text | ||||||
| import esphome.config_validation as cv | import esphome.config_validation as cv | ||||||
|  |  | ||||||
| from ..defines import CONF_LVGL_ID, CONF_WIDGET | from ..defines import CONF_WIDGET | ||||||
| from ..lvcode import ( | from ..lvcode import ( | ||||||
|     API_EVENT, |     API_EVENT, | ||||||
|     EVENT_ARG, |     EVENT_ARG, | ||||||
| @@ -12,14 +12,14 @@ from ..lvcode import ( | |||||||
|     LvContext, |     LvContext, | ||||||
|     lv, |     lv, | ||||||
|     lv_add, |     lv_add, | ||||||
|  |     lvgl_static, | ||||||
| ) | ) | ||||||
| from ..schemas import LVGL_SCHEMA |  | ||||||
| from ..types import LV_EVENT, LvText, lvgl_ns | from ..types import LV_EVENT, LvText, lvgl_ns | ||||||
| from ..widgets import get_widgets, wait_for_widgets | from ..widgets import get_widgets, wait_for_widgets | ||||||
|  |  | ||||||
| LVGLText = lvgl_ns.class_("LVGLText", text.Text) | LVGLText = lvgl_ns.class_("LVGLText", text.Text) | ||||||
|  |  | ||||||
| CONFIG_SCHEMA = text.TEXT_SCHEMA.extend(LVGL_SCHEMA).extend( | CONFIG_SCHEMA = text.TEXT_SCHEMA.extend( | ||||||
|     { |     { | ||||||
|         cv.GenerateID(): cv.declare_id(LVGLText), |         cv.GenerateID(): cv.declare_id(LVGLText), | ||||||
|         cv.Required(CONF_WIDGET): cv.use_id(LvText), |         cv.Required(CONF_WIDGET): cv.use_id(LvText), | ||||||
| @@ -29,7 +29,6 @@ CONFIG_SCHEMA = text.TEXT_SCHEMA.extend(LVGL_SCHEMA).extend( | |||||||
|  |  | ||||||
| async def to_code(config): | async def to_code(config): | ||||||
|     textvar = await new_text(config) |     textvar = await new_text(config) | ||||||
|     paren = await cg.get_variable(config[CONF_LVGL_ID]) |  | ||||||
|     widget = await get_widgets(config, CONF_WIDGET) |     widget = await get_widgets(config, CONF_WIDGET) | ||||||
|     widget = widget[0] |     widget = widget[0] | ||||||
|     await wait_for_widgets() |     await wait_for_widgets() | ||||||
| @@ -39,10 +38,10 @@ async def to_code(config): | |||||||
|         control.add(textvar.publish_state(widget.get_value())) |         control.add(textvar.publish_state(widget.get_value())) | ||||||
|     async with LambdaContext(EVENT_ARG) as lamb: |     async with LambdaContext(EVENT_ARG) as lamb: | ||||||
|         lv_add(textvar.publish_state(widget.get_value())) |         lv_add(textvar.publish_state(widget.get_value())) | ||||||
|     async with LvContext(paren): |     async with LvContext(): | ||||||
|         lv_add(textvar.set_control_lambda(await control.get_lambda())) |         lv_add(textvar.set_control_lambda(await control.get_lambda())) | ||||||
|         lv_add( |         lv_add( | ||||||
|             paren.add_event_cb( |             lvgl_static.add_event_cb( | ||||||
|                 widget.obj, |                 widget.obj, | ||||||
|                 await lamb.get_lambda(), |                 await lamb.get_lambda(), | ||||||
|                 LV_EVENT.VALUE_CHANGED, |                 LV_EVENT.VALUE_CHANGED, | ||||||
|   | |||||||
| @@ -1,4 +1,3 @@ | |||||||
| import esphome.codegen as cg |  | ||||||
| from esphome.components.text_sensor import ( | from esphome.components.text_sensor import ( | ||||||
|     TextSensor, |     TextSensor, | ||||||
|     new_text_sensor, |     new_text_sensor, | ||||||
| @@ -6,34 +5,35 @@ from esphome.components.text_sensor import ( | |||||||
| ) | ) | ||||||
| import esphome.config_validation as cv | import esphome.config_validation as cv | ||||||
|  |  | ||||||
| from ..defines import CONF_LVGL_ID, CONF_WIDGET | from ..defines import CONF_WIDGET | ||||||
| from ..lvcode import API_EVENT, EVENT_ARG, UPDATE_EVENT, LambdaContext, LvContext | from ..lvcode import ( | ||||||
| from ..schemas import LVGL_SCHEMA |     API_EVENT, | ||||||
|  |     EVENT_ARG, | ||||||
|  |     UPDATE_EVENT, | ||||||
|  |     LambdaContext, | ||||||
|  |     LvContext, | ||||||
|  |     lvgl_static, | ||||||
|  | ) | ||||||
| from ..types import LV_EVENT, LvText | from ..types import LV_EVENT, LvText | ||||||
| from ..widgets import get_widgets, wait_for_widgets | from ..widgets import get_widgets, wait_for_widgets | ||||||
|  |  | ||||||
| CONFIG_SCHEMA = ( | CONFIG_SCHEMA = text_sensor_schema(TextSensor).extend( | ||||||
|     text_sensor_schema(TextSensor) |     { | ||||||
|     .extend(LVGL_SCHEMA) |         cv.Required(CONF_WIDGET): cv.use_id(LvText), | ||||||
|     .extend( |     } | ||||||
|         { |  | ||||||
|             cv.Required(CONF_WIDGET): cv.use_id(LvText), |  | ||||||
|         } |  | ||||||
|     ) |  | ||||||
| ) | ) | ||||||
|  |  | ||||||
|  |  | ||||||
| async def to_code(config): | async def to_code(config): | ||||||
|     sensor = await new_text_sensor(config) |     sensor = await new_text_sensor(config) | ||||||
|     paren = await cg.get_variable(config[CONF_LVGL_ID]) |  | ||||||
|     widget = await get_widgets(config, CONF_WIDGET) |     widget = await get_widgets(config, CONF_WIDGET) | ||||||
|     widget = widget[0] |     widget = widget[0] | ||||||
|     await wait_for_widgets() |     await wait_for_widgets() | ||||||
|     async with LambdaContext(EVENT_ARG) as pressed_ctx: |     async with LambdaContext(EVENT_ARG) as pressed_ctx: | ||||||
|         pressed_ctx.add(sensor.publish_state(widget.get_value())) |         pressed_ctx.add(sensor.publish_state(widget.get_value())) | ||||||
|     async with LvContext(paren) as ctx: |     async with LvContext() as ctx: | ||||||
|         ctx.add( |         ctx.add( | ||||||
|             paren.add_event_cb( |             lvgl_static.add_event_cb( | ||||||
|                 widget.obj, |                 widget.obj, | ||||||
|                 await pressed_ctx.get_lambda(), |                 await pressed_ctx.get_lambda(), | ||||||
|                 LV_EVENT.VALUE_CHANGED, |                 LV_EVENT.VALUE_CHANGED, | ||||||
|   | |||||||
| @@ -33,13 +33,12 @@ def touchscreen_schema(config): | |||||||
|     return [TOUCHSCREENS_CONFIG(config)] |     return [TOUCHSCREENS_CONFIG(config)] | ||||||
|  |  | ||||||
|  |  | ||||||
| async def touchscreens_to_code(var, config): | async def touchscreens_to_code(lv_component, config): | ||||||
|     for tconf in config[CONF_TOUCHSCREENS]: |     for tconf in config[CONF_TOUCHSCREENS]: | ||||||
|         lvgl_components_required.add(CONF_TOUCHSCREEN) |         lvgl_components_required.add(CONF_TOUCHSCREEN) | ||||||
|         touchscreen = await cg.get_variable(tconf[CONF_TOUCHSCREEN_ID]) |         touchscreen = await cg.get_variable(tconf[CONF_TOUCHSCREEN_ID]) | ||||||
|         lpt = tconf[CONF_LONG_PRESS_TIME].total_milliseconds |         lpt = tconf[CONF_LONG_PRESS_TIME].total_milliseconds | ||||||
|         lprt = tconf[CONF_LONG_PRESS_REPEAT_TIME].total_milliseconds |         lprt = tconf[CONF_LONG_PRESS_REPEAT_TIME].total_milliseconds | ||||||
|         listener = cg.new_Pvariable(tconf[CONF_ID], lpt, lprt) |         listener = cg.new_Pvariable(tconf[CONF_ID], lpt, lprt, lv_component) | ||||||
|         await cg.register_parented(listener, var) |  | ||||||
|         lv.indev_drv_register(listener.get_drv()) |         lv.indev_drv_register(listener.get_drv()) | ||||||
|         cg.add(touchscreen.register_listener(listener)) |         cg.add(touchscreen.register_listener(listener)) | ||||||
|   | |||||||
| @@ -20,17 +20,16 @@ from .lvcode import ( | |||||||
|     lv, |     lv, | ||||||
|     lv_add, |     lv_add, | ||||||
|     lv_event_t_ptr, |     lv_event_t_ptr, | ||||||
|  |     lvgl_static, | ||||||
| ) | ) | ||||||
| from .types import LV_EVENT | from .types import LV_EVENT | ||||||
| from .widgets import widget_map | from .widgets import widget_map | ||||||
|  |  | ||||||
|  |  | ||||||
| async def generate_triggers(lv_component): | async def generate_triggers(): | ||||||
|     """ |     """ | ||||||
|     Generate LVGL triggers for all defined widgets |     Generate LVGL triggers for all defined widgets | ||||||
|     Must be done after all widgets completed |     Must be done after all widgets completed | ||||||
|     :param lv_component:  The parent component |  | ||||||
|     :return: |  | ||||||
|     """ |     """ | ||||||
|  |  | ||||||
|     for w in widget_map.values(): |     for w in widget_map.values(): | ||||||
| @@ -43,11 +42,10 @@ async def generate_triggers(lv_component): | |||||||
|                 conf = conf[0] |                 conf = conf[0] | ||||||
|                 w.add_flag("LV_OBJ_FLAG_CLICKABLE") |                 w.add_flag("LV_OBJ_FLAG_CLICKABLE") | ||||||
|                 event = literal("LV_EVENT_" + LV_EVENT_MAP[event[3:].upper()]) |                 event = literal("LV_EVENT_" + LV_EVENT_MAP[event[3:].upper()]) | ||||||
|                 await add_trigger(conf, lv_component, w, event) |                 await add_trigger(conf, w, event) | ||||||
|             for conf in w.config.get(CONF_ON_VALUE, ()): |             for conf in w.config.get(CONF_ON_VALUE, ()): | ||||||
|                 await add_trigger( |                 await add_trigger( | ||||||
|                     conf, |                     conf, | ||||||
|                     lv_component, |  | ||||||
|                     w, |                     w, | ||||||
|                     LV_EVENT.VALUE_CHANGED, |                     LV_EVENT.VALUE_CHANGED, | ||||||
|                     API_EVENT, |                     API_EVENT, | ||||||
| @@ -63,7 +61,7 @@ async def generate_triggers(lv_component): | |||||||
|                 lv.obj_align_to(w.obj, target, align, x, y) |                 lv.obj_align_to(w.obj, target, align, x, y) | ||||||
|  |  | ||||||
|  |  | ||||||
| async def add_trigger(conf, lv_component, w, *events): | async def add_trigger(conf, w, *events): | ||||||
|     tid = conf[CONF_TRIGGER_ID] |     tid = conf[CONF_TRIGGER_ID] | ||||||
|     trigger = cg.new_Pvariable(tid) |     trigger = cg.new_Pvariable(tid) | ||||||
|     args = w.get_args() + [(lv_event_t_ptr, "event")] |     args = w.get_args() + [(lv_event_t_ptr, "event")] | ||||||
| @@ -72,4 +70,4 @@ async def add_trigger(conf, lv_component, w, *events): | |||||||
|     async with LambdaContext(EVENT_ARG, where=tid) as context: |     async with LambdaContext(EVENT_ARG, where=tid) as context: | ||||||
|         with LvConditional(w.is_selected()): |         with LvConditional(w.is_selected()): | ||||||
|             lv_add(trigger.trigger(*value, literal("event"))) |             lv_add(trigger.trigger(*value, literal("event"))) | ||||||
|     lv_add(lv_component.add_event_cb(w.obj, await context.get_lambda(), *events)) |     lv_add(lvgl_static.add_event_cb(w.obj, await context.get_lambda(), *events)) | ||||||
|   | |||||||
| @@ -40,6 +40,7 @@ void_ptr = cg.void.operator("ptr") | |||||||
| lv_coord_t = cg.global_ns.namespace("lv_coord_t") | lv_coord_t = cg.global_ns.namespace("lv_coord_t") | ||||||
| lv_event_code_t = cg.global_ns.enum("lv_event_code_t") | lv_event_code_t = cg.global_ns.enum("lv_event_code_t") | ||||||
| lv_indev_type_t = cg.global_ns.enum("lv_indev_type_t") | lv_indev_type_t = cg.global_ns.enum("lv_indev_type_t") | ||||||
|  | lv_key_t = cg.global_ns.enum("lv_key_t") | ||||||
| FontEngine = lvgl_ns.class_("FontEngine") | FontEngine = lvgl_ns.class_("FontEngine") | ||||||
| IdleTrigger = lvgl_ns.class_("IdleTrigger", automation.Trigger.template()) | IdleTrigger = lvgl_ns.class_("IdleTrigger", automation.Trigger.template()) | ||||||
| PauseTrigger = lvgl_ns.class_("PauseTrigger", automation.Trigger.template()) | PauseTrigger = lvgl_ns.class_("PauseTrigger", automation.Trigger.template()) | ||||||
|   | |||||||
| @@ -1,20 +1,18 @@ | |||||||
| from esphome import automation | from esphome import automation | ||||||
| import esphome.codegen as cg |  | ||||||
| import esphome.config_validation as cv | import esphome.config_validation as cv | ||||||
| from esphome.const import CONF_DURATION, CONF_ID | from esphome.const import CONF_DURATION, CONF_ID | ||||||
|  |  | ||||||
| from ..automation import action_to_code | from ..automation import action_to_code | ||||||
| from ..defines import CONF_AUTO_START, CONF_MAIN, CONF_REPEAT_COUNT, CONF_SRC | from ..defines import CONF_AUTO_START, CONF_MAIN, CONF_REPEAT_COUNT, CONF_SRC | ||||||
| from ..helpers import lvgl_components_required | from ..helpers import lvgl_components_required | ||||||
| from ..lv_validation import lv_image, lv_milliseconds | from ..lv_validation import lv_image_list, lv_milliseconds | ||||||
| from ..lvcode import lv | from ..lvcode import lv | ||||||
| from ..types import LvType, ObjUpdateAction, void_ptr | from ..types import LvType, ObjUpdateAction | ||||||
| from . import Widget, WidgetType, get_widgets | from . import Widget, WidgetType, get_widgets | ||||||
| from .img import CONF_IMAGE | from .img import CONF_IMAGE | ||||||
| from .label import CONF_LABEL | from .label import CONF_LABEL | ||||||
|  |  | ||||||
| CONF_ANIMIMG = "animimg" | CONF_ANIMIMG = "animimg" | ||||||
| CONF_SRC_LIST_ID = "src_list_id" |  | ||||||
|  |  | ||||||
|  |  | ||||||
| def lv_repeat_count(value): | def lv_repeat_count(value): | ||||||
| @@ -32,14 +30,14 @@ ANIMIMG_BASE_SCHEMA = cv.Schema( | |||||||
| ANIMIMG_SCHEMA = ANIMIMG_BASE_SCHEMA.extend( | ANIMIMG_SCHEMA = ANIMIMG_BASE_SCHEMA.extend( | ||||||
|     { |     { | ||||||
|         cv.Required(CONF_DURATION): lv_milliseconds, |         cv.Required(CONF_DURATION): lv_milliseconds, | ||||||
|         cv.Required(CONF_SRC): cv.ensure_list(lv_image), |         cv.Required(CONF_SRC): lv_image_list, | ||||||
|         cv.GenerateID(CONF_SRC_LIST_ID): cv.declare_id(void_ptr), |  | ||||||
|     } |     } | ||||||
| ) | ) | ||||||
|  |  | ||||||
| ANIMIMG_MODIFY_SCHEMA = ANIMIMG_BASE_SCHEMA.extend( | ANIMIMG_MODIFY_SCHEMA = ANIMIMG_BASE_SCHEMA.extend( | ||||||
|     { |     { | ||||||
|         cv.Optional(CONF_DURATION): lv_milliseconds, |         cv.Optional(CONF_DURATION): lv_milliseconds, | ||||||
|  |         cv.Optional(CONF_SRC): lv_image_list, | ||||||
|     } |     } | ||||||
| ) | ) | ||||||
|  |  | ||||||
| @@ -59,16 +57,14 @@ class AnimimgType(WidgetType): | |||||||
|     async def to_code(self, w: Widget, config): |     async def to_code(self, w: Widget, config): | ||||||
|         lvgl_components_required.add(CONF_IMAGE) |         lvgl_components_required.add(CONF_IMAGE) | ||||||
|         lvgl_components_required.add(CONF_ANIMIMG) |         lvgl_components_required.add(CONF_ANIMIMG) | ||||||
|         if CONF_SRC in config: |         if srcs := config.get(CONF_SRC): | ||||||
|             for x in config[CONF_SRC]: |             srcs = await lv_image_list.process(srcs) | ||||||
|                 await cg.get_variable(x) |             lv.animimg_set_src(w.obj, srcs) | ||||||
|             srcs = [await lv_image.process(x) for x in config[CONF_SRC]] |         if repeat_count := config.get(CONF_REPEAT_COUNT): | ||||||
|             src_id = cg.static_const_array(config[CONF_SRC_LIST_ID], srcs) |             lv.animimg_set_repeat_count(w.obj, repeat_count) | ||||||
|             count = len(config[CONF_SRC]) |         if duration := config.get(CONF_DURATION): | ||||||
|             lv.animimg_set_src(w.obj, src_id, count) |             lv.animimg_set_duration(w.obj, duration) | ||||||
|         lv.animimg_set_repeat_count(w.obj, config[CONF_REPEAT_COUNT]) |         if config[CONF_AUTO_START]: | ||||||
|         lv.animimg_set_duration(w.obj, config[CONF_DURATION]) |  | ||||||
|         if config.get(CONF_AUTO_START): |  | ||||||
|             lv.animimg_start(w.obj) |             lv.animimg_start(w.obj) | ||||||
|  |  | ||||||
|     def get_uses(self): |     def get_uses(self): | ||||||
|   | |||||||
| @@ -39,7 +39,10 @@ LINE_SCHEMA = { | |||||||
| class LineType(WidgetType): | class LineType(WidgetType): | ||||||
|     def __init__(self): |     def __init__(self): | ||||||
|         super().__init__( |         super().__init__( | ||||||
|             CONF_LINE, LvType("lv_line_t"), (CONF_MAIN,), LINE_SCHEMA, modify_schema={} |             CONF_LINE, | ||||||
|  |             LvType("lv_line_t"), | ||||||
|  |             (CONF_MAIN,), | ||||||
|  |             LINE_SCHEMA, | ||||||
|         ) |         ) | ||||||
|  |  | ||||||
|     async def to_code(self, w: Widget, config): |     async def to_code(self, w: Widget, config): | ||||||
|   | |||||||
| @@ -20,6 +20,7 @@ from ..lvcode import ( | |||||||
|     add_line_marks, |     add_line_marks, | ||||||
|     lv_add, |     lv_add, | ||||||
|     lvgl_comp, |     lvgl_comp, | ||||||
|  |     lvgl_static, | ||||||
| ) | ) | ||||||
| from ..schemas import LVGL_SCHEMA | from ..schemas import LVGL_SCHEMA | ||||||
| from ..types import LvglAction, lv_page_t | from ..types import LvglAction, lv_page_t | ||||||
| @@ -139,7 +140,7 @@ async def add_pages(lv_component, config): | |||||||
|         await add_widgets(page, pconf) |         await add_widgets(page, pconf) | ||||||
|  |  | ||||||
|  |  | ||||||
| async def generate_page_triggers(lv_component, config): | async def generate_page_triggers(config): | ||||||
|     for pconf in config.get(CONF_PAGES, ()): |     for pconf in config.get(CONF_PAGES, ()): | ||||||
|         page = (await get_widgets(pconf))[0] |         page = (await get_widgets(pconf))[0] | ||||||
|         for ev in (CONF_ON_LOAD, CONF_ON_UNLOAD): |         for ev in (CONF_ON_LOAD, CONF_ON_UNLOAD): | ||||||
| @@ -149,7 +150,7 @@ async def generate_page_triggers(lv_component, config): | |||||||
|                 async with LambdaContext(EVENT_ARG, where=id) as context: |                 async with LambdaContext(EVENT_ARG, where=id) as context: | ||||||
|                     lv_add(trigger.trigger()) |                     lv_add(trigger.trigger()) | ||||||
|                 lv_add( |                 lv_add( | ||||||
|                     lv_component.add_event_cb( |                     lvgl_static.add_event_cb( | ||||||
|                         page.obj, |                         page.obj, | ||||||
|                         await context.get_lambda(), |                         await context.get_lambda(), | ||||||
|                         literal(f"LV_EVENT_SCREEN_{ev[3:].upper()}_START"), |                         literal(f"LV_EVENT_SCREEN_{ev[3:].upper()}_START"), | ||||||
|   | |||||||
							
								
								
									
										54
									
								
								esphome/components/lvgl/widgets/qrcode.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										54
									
								
								esphome/components/lvgl/widgets/qrcode.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,54 @@ | |||||||
|  | import esphome.codegen as cg | ||||||
|  | import esphome.config_validation as cv | ||||||
|  | from esphome.const import CONF_SIZE, CONF_TEXT | ||||||
|  | from esphome.cpp_generator import MockObjClass | ||||||
|  |  | ||||||
|  | from ..defines import CONF_MAIN, literal | ||||||
|  | from ..lv_validation import color, color_retmapper, lv_text | ||||||
|  | from ..lvcode import LocalVariable, lv, lv_expr | ||||||
|  | from ..schemas import TEXT_SCHEMA | ||||||
|  | from ..types import WidgetType, lv_obj_t | ||||||
|  | from . import Widget | ||||||
|  |  | ||||||
|  | CONF_QRCODE = "qrcode" | ||||||
|  | CONF_DARK_COLOR = "dark_color" | ||||||
|  | CONF_LIGHT_COLOR = "light_color" | ||||||
|  |  | ||||||
|  | QRCODE_SCHEMA = TEXT_SCHEMA.extend( | ||||||
|  |     { | ||||||
|  |         cv.Optional(CONF_DARK_COLOR, default="black"): color, | ||||||
|  |         cv.Optional(CONF_LIGHT_COLOR, default="white"): color, | ||||||
|  |         cv.Required(CONF_SIZE): cv.int_, | ||||||
|  |     } | ||||||
|  | ) | ||||||
|  |  | ||||||
|  |  | ||||||
|  | class QrCodeType(WidgetType): | ||||||
|  |     def __init__(self): | ||||||
|  |         super().__init__( | ||||||
|  |             CONF_QRCODE, | ||||||
|  |             lv_obj_t, | ||||||
|  |             (CONF_MAIN,), | ||||||
|  |             QRCODE_SCHEMA, | ||||||
|  |             modify_schema=TEXT_SCHEMA, | ||||||
|  |         ) | ||||||
|  |  | ||||||
|  |     def get_uses(self): | ||||||
|  |         return ("canvas", "img") | ||||||
|  |  | ||||||
|  |     def obj_creator(self, parent: MockObjClass, config: dict): | ||||||
|  |         dark_color = color_retmapper(config[CONF_DARK_COLOR]) | ||||||
|  |         light_color = color_retmapper(config[CONF_LIGHT_COLOR]) | ||||||
|  |         size = config[CONF_SIZE] | ||||||
|  |         return lv_expr.call("qrcode_create", parent, size, dark_color, light_color) | ||||||
|  |  | ||||||
|  |     async def to_code(self, w: Widget, config): | ||||||
|  |         if (value := config.get(CONF_TEXT)) is not None: | ||||||
|  |             value = await lv_text.process(value) | ||||||
|  |             with LocalVariable( | ||||||
|  |                 "qr_text", cg.const_char_ptr, value, modifier="" | ||||||
|  |             ) as str_obj: | ||||||
|  |                 lv.qrcode_update(w.obj, str_obj, literal(f"strlen({str_obj})")) | ||||||
|  |  | ||||||
|  |  | ||||||
|  | qr_code_spec = QrCodeType() | ||||||
| @@ -1,8 +1,8 @@ | |||||||
|  | from esphome import automation, pins | ||||||
| import esphome.codegen as cg | import esphome.codegen as cg | ||||||
| import esphome.config_validation as cv |  | ||||||
| from esphome import pins |  | ||||||
| from esphome.components import key_provider | from esphome.components import key_provider | ||||||
| from esphome.const import CONF_ID, CONF_PIN | import esphome.config_validation as cv | ||||||
|  | from esphome.const import CONF_ID, CONF_ON_KEY, CONF_PIN, CONF_TRIGGER_ID | ||||||
|  |  | ||||||
| CODEOWNERS = ["@ssieb"] | CODEOWNERS = ["@ssieb"] | ||||||
|  |  | ||||||
| @@ -14,6 +14,9 @@ matrix_keypad_ns = cg.esphome_ns.namespace("matrix_keypad") | |||||||
| MatrixKeypad = matrix_keypad_ns.class_( | MatrixKeypad = matrix_keypad_ns.class_( | ||||||
|     "MatrixKeypad", key_provider.KeyProvider, cg.Component |     "MatrixKeypad", key_provider.KeyProvider, cg.Component | ||||||
| ) | ) | ||||||
|  | MatrixKeyTrigger = matrix_keypad_ns.class_( | ||||||
|  |     "MatrixKeyTrigger", automation.Trigger.template(cg.uint8) | ||||||
|  | ) | ||||||
|  |  | ||||||
| CONF_KEYPAD_ID = "keypad_id" | CONF_KEYPAD_ID = "keypad_id" | ||||||
| CONF_ROWS = "rows" | CONF_ROWS = "rows" | ||||||
| @@ -47,6 +50,11 @@ CONFIG_SCHEMA = cv.All( | |||||||
|             cv.Optional(CONF_DEBOUNCE_TIME, default=1): cv.int_range(min=1, max=100), |             cv.Optional(CONF_DEBOUNCE_TIME, default=1): cv.int_range(min=1, max=100), | ||||||
|             cv.Optional(CONF_HAS_DIODES): cv.boolean, |             cv.Optional(CONF_HAS_DIODES): cv.boolean, | ||||||
|             cv.Optional(CONF_HAS_PULLDOWNS): cv.boolean, |             cv.Optional(CONF_HAS_PULLDOWNS): cv.boolean, | ||||||
|  |             cv.Optional(CONF_ON_KEY): automation.validate_automation( | ||||||
|  |                 { | ||||||
|  |                     cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(MatrixKeyTrigger), | ||||||
|  |                 } | ||||||
|  |             ), | ||||||
|         } |         } | ||||||
|     ), |     ), | ||||||
|     check_keys, |     check_keys, | ||||||
| @@ -73,3 +81,7 @@ async def to_code(config): | |||||||
|         cg.add(var.set_has_diodes(config[CONF_HAS_DIODES])) |         cg.add(var.set_has_diodes(config[CONF_HAS_DIODES])) | ||||||
|     if CONF_HAS_PULLDOWNS in config: |     if CONF_HAS_PULLDOWNS in config: | ||||||
|         cg.add(var.set_has_pulldowns(config[CONF_HAS_PULLDOWNS])) |         cg.add(var.set_has_pulldowns(config[CONF_HAS_PULLDOWNS])) | ||||||
|  |     for conf in config.get(CONF_ON_KEY, []): | ||||||
|  |         trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID]) | ||||||
|  |         cg.add(var.register_key_trigger(trigger)) | ||||||
|  |         await automation.build_automation(trigger, [(cg.uint8, "x")], conf) | ||||||
|   | |||||||
Some files were not shown because too many files have changed in this diff Show More
		Reference in New Issue
	
	Block a user