Compare commits

..

90 Commits

Author SHA1 Message Date
Otto Winter
1ca241615d Bump version to v1.13.6 2019-06-14 12:55:23 +02:00
Otto Winter
b8aa84002a Re-add CustomMQTTDevice class (#640)
* Re-add CustomMQTTDevice class

Fixes https://github.com/esphome/issues/issues/427

* Fix
2019-06-14 12:55:20 +02:00
Otto Winter
10cc0b1d5b Fix remote_receiver raw binary sensor (#639)
* Fix remote_receiver raw binary sensor

Fixes https://github.com/esphome/issues/issues/439

* Lint
2019-06-14 12:55:19 +02:00
Otto Winter
11d9c203c1 Fix version.h file (#630)
* Fix version.h file

* Lint
2019-06-14 12:55:19 +02:00
Otto Winter
c9ab454c3c Fix globals.set (#635)
* Fix globals.set

* Update __init__.py
2019-06-14 12:55:19 +02:00
Otto Winter
4a55692885 Fix russia timezone detection (#637)
Fixes https://github.com/esphome/issues/issues/378#issuecomment-500219634
2019-06-14 12:55:19 +02:00
Otto Winter
88c129e705 Fix ESP32 RCSwitch Dump Stack Smash Protection (#636)
Fixes https://github.com/esphome/issues/issues/366
2019-06-14 12:55:19 +02:00
Otto Winter
80b48f01fb Fix esp8266_restore_from_flash (#638)
Fixes https://github.com/esphome/issues/issues/424
2019-06-14 12:36:30 +02:00
Otto Winter
642bc91a76 Update esp32_ble_tracker.cpp 2019-06-08 17:06:29 +02:00
Otto Winter
d69926ee56 Bump version to v1.13.5 2019-06-08 16:49:04 +02:00
Otto Winter
4758403d44 Work around ESP32 core WiFi Bug (#627)
* Work around ESP32 WiFi Bug

* Lint
2019-06-08 16:49:00 +02:00
Otto Winter
4b0ec5c28a Work around ESP32 BLE issue (#626) 2019-06-08 16:49:00 +02:00
Otto Winter
4b2a9e5e49 Fix status binary sensor for MQTT (#628)
Fixes https://github.com/esphome/issues/issues/417
2019-06-08 16:48:59 +02:00
Otto Winter
1449c51d49 Update base image to 1.8.3 (#625) 2019-06-08 16:48:59 +02:00
Otto Winter
a451705e0b Fix sun default elevation (#620) 2019-06-08 16:48:58 +02:00
Otto Winter
2e6db39173 Fix integration sensor, add test (#619)
* Fix integration sensor, add test

* Fix

* Fix
2019-06-08 16:48:58 +02:00
Otto Winter
373f75253c Update docker base image to 1.8.0 (#618) 2019-06-08 16:48:58 +02:00
Otto Winter
724842084e Make ForCondition a component (#616)
Fixes https://github.com/esphome/issues/issues/396
2019-06-08 16:48:57 +02:00
Otto Winter
8f3635b167 Fix remote_receiver always shows sony (#617)
Fixes https://github.com/esphome/issues/issues/383#issuecomment-498370572
2019-06-08 16:48:57 +02:00
Otto Winter
11605a36f7 Fix Hass.io addon SSL (#613)
Fixes https://github.com/esphome/issues/issues/404
2019-06-08 16:48:56 +02:00
Otto Winter
533f81d625 Template Cover don't auto-set current_operation (#612)
Fixes https://github.com/esphome/issues/issues/408
2019-06-08 16:48:56 +02:00
Otto Winter
aacb9e44e8 DHT22 ignore invalid values (#614)
Fixes https://github.com/esphome/issues/issues/397
2019-06-08 16:48:55 +02:00
Peter Tatrai
c6e3f1bca6 Fix ForCondition time duration check (#610)
According documentation ForCondition should evaluate to true if a nested condition is true for at least the specified time duration and not the less.
2019-06-08 16:48:55 +02:00
Otto Winter
a933d4aeb6 Move ESPHome version define (#607)
* Move ESPHome version define

* Lint
2019-06-08 16:48:55 +02:00
Otto Winter
caa5b20791 Bump version to v1.13.4 2019-06-03 15:24:10 +02:00
Otto Winter
e2ad9ed746 ESP8266 connect fixes (#605)
* ESP8266 Connection Fixes

* Update client.py

* Update mqtt_client.cpp

* Update mqtt_client.cpp

* Fix ping

* Async dump config

* Update base image to 1.7.0

* Update helpers.py

* Updates

* Update Dockerfile.lint
2019-06-03 15:23:57 +02:00
Otto Winter
32c0e7c2ae Fix ADS1115 calculation (#606)
Fixes https://github.com/esphome/issues/issues/393
2019-06-03 15:23:56 +02:00
Otto Winter
6c564c7b7f Fix validation infinite loop with empty platform block (#598)
* Fix validation infinite loop with empty platform block

* Update util.py
2019-06-03 15:23:56 +02:00
Otto Winter
c81e3a3be4 Fix hx711 (#602)
* Fix HX711

* Use signed value

* Update hx711.cpp
2019-06-03 15:23:56 +02:00
Otto Winter
6b1b9ef7ec Fix color wipe effect (#599) 2019-06-03 15:23:56 +02:00
Otto Winter
c26a8b8718 Allow old remote_transmitter repeat schema (#601)
Fixes https://github.com/esphome/issues/issues/389
2019-06-03 15:23:56 +02:00
Otto Winter
4a89a475bd Add better esphomeyaml migration path (#600)
Fixes https://github.com/esphome/issues/issues/387
2019-06-03 15:23:55 +02:00
Otto Winter
8cf15c7f5c Bump version to v1.13.3 2019-06-01 22:02:10 +02:00
Otto Winter
adc76ca1b8 Fix dashboard for Py3 installs (#596)
Fixes https://github.com/esphome/issues/issues/368
2019-06-01 22:02:05 +02:00
Otto Winter
8f8892440c Fix medium fan speed (#595) 2019-06-01 22:02:04 +02:00
Otto Winter
570843150d Fix flicker light effect turning itself off (#594)
Fixes https://github.com/esphome/issues/issues/382
2019-06-01 22:02:04 +02:00
Otto Winter
f3fc9e4142 Fix remote_receiver binary_sensor (#592)
Fixes https://github.com/esphome/issues/issues/369
2019-06-01 22:02:04 +02:00
Otto Winter
075fcb77a8 Fix timezone detection (#586)
* Fix timezone detection

* Update __init__.py
2019-06-01 22:02:04 +02:00
Otto Winter
e5899ff717 Fix scripts circular dependency (#591)
Fixes https://github.com/esphome/issues/issues/370
2019-06-01 22:02:04 +02:00
Otto Winter
2fb3970027 Fix addressable effects (#590) 2019-06-01 22:02:03 +02:00
Marc-Antoine Courteau
1a4efa1b8c List the correct boards when building for ESP32 (#589)
* List the ESP32 boards for ESP32 builds.

* Sort the list of valid boards.
2019-06-01 22:02:03 +02:00
Otto Winter
72f656ffef Bump version to v1.13.2 2019-05-31 16:37:56 +02:00
Otto Winter
b60239d5e5 Fix i2c setup priority (#585)
Fixes https://github.com/esphome/issues/issues/314
2019-05-31 16:37:49 +02:00
Otto Winter
d02e280c3c Fix light partition (#584)
* Fix light partition

Fixes https://github.com/esphome/issues/issues/365

* Lint
2019-05-31 16:37:48 +02:00
Otto Winter
6535b0966e Fix MQTT on_message trigger (#583)
Fixes https://github.com/esphome/issues/issues/363
Fixes https://github.com/esphome/issues/issues/364
2019-05-31 16:37:48 +02:00
Otto Winter
82dbacbee5 Fix travis build (#582) 2019-05-31 16:37:48 +02:00
Otto Winter
2432901974 Fix Rotary Encoder (#580)
Fixes https://github.com/esphome/issues/issues/360
2019-05-31 16:37:48 +02:00
Otto Winter
ebb5d58c14 Fix MQTT client_id changed (#579)
Fixes https://github.com/esphome/issues/issues/323
2019-05-31 16:37:48 +02:00
Otto Winter
605e365405 Fix remote_receiver binary_sensor schema (#578)
Fixes https://github.com/esphome/issues/issues/353#issuecomment-497491863
2019-05-31 16:37:47 +02:00
Otto Winter
5ab995d8ca Bump version to v1.13.1 2019-05-30 22:31:56 +02:00
Otto Winter
4248741b11 Fix waveshare 7.5in model (#576)
* Fix waveshare 7.5in model

Fixes https://github.com/esphome/issues/issues/357

* Fix platformio travis errors
2019-05-30 22:31:54 +02:00
Otto Winter
4b8ecc7634 Dashboard work around Hass.io bug (#575)
* Dashboard work around Hass.io bug

Ref https://github.com/home-assistant/hassio/issues/1103

* Lint
2019-05-30 22:31:53 +02:00
Otto Winter
25d04c759c Fix Sun Trigger (#572)
* Fix Sun Trigger

* Fix cwww lights
2019-05-30 22:31:53 +02:00
Otto Winter
b4ec84030e Fix validation TypeError (#574) 2019-05-30 22:31:53 +02:00
Otto Winter
29e8761373 Fix merge 2019-05-30 14:20:06 +02:00
Otto Winter
a04299c59e Bump version to v1.13.0 2019-05-30 14:15:41 +02:00
Otto Winter
d7bf3c51d9 Merge branch 'beta' 2019-05-30 14:15:28 +02:00
Otto Winter
3ddf5a4ec7 Bump version to v1.13.0b7 2019-05-30 13:13:40 +02:00
Otto Winter
f2d6817d8a Register light conditions (#570) 2019-05-30 13:13:37 +02:00
Jesse Hills
31821e6309 Correctly set warm white variables (#569) 2019-05-30 13:13:36 +02:00
Otto Winter
7f507935b1 Bump version to v1.13.0b6 2019-05-29 19:38:32 +02:00
Otto Winter
3b1ba27043 Add uart.write action (#567)
* Add uart.write action

* Lint
2019-05-29 19:38:29 +02:00
Otto Winter
4b7c5aa05c Use copy for custom includes (#568) 2019-05-29 19:38:29 +02:00
Otto Winter
5fca02c712 Fix TSL2561 invalid default (#566)
Ref https://github.com/esphome/issues/issues/352#issuecomment-496883794
2019-05-29 19:38:28 +02:00
Otto Winter
e4bbb56f6b Apply removed patch 2019-05-29 11:36:31 +02:00
Otto Winter
96d30e28d4 Bump version to v1.13.0b5 2019-05-29 11:22:10 +02:00
Jesse Hills
41b73ff892 Add CT Clamp component (#559)
* Add CT Clamp component

* Update lint

* Some more fixes

* Make updates to work as an analog sensor consumer

* Remove unused imports
Update lint suggestions

* Move setup_priority to header

* Remove unused calibration value

* Remove Unique ID

- Will be auto generated

* Update to use loop and not slow down main loop

Co-authored-by: Otto Winter <otto@otto-winter.com>
2019-05-29 11:22:00 +02:00
Otto Winter
afc4e45fb0 Warn if a component does long-running work in loop thread (#565)
* Warn if a component does long-running work in loop thread

* Update application.cpp
2019-05-29 11:21:15 +02:00
gitolicious
8778ddd5c5 Renamed upload button (#563)
* Renamed upload button

* Renamed upload button in code
2019-05-29 11:17:56 +02:00
Otto Winter
23f1798d20 Bump version to v1.13.0b4 2019-05-28 21:37:31 +02:00
gitolicious
6f3c126805 added download, edit and retry buttons to upload modal (#557)
* added download, edit and retry buttons to upload modal

* changed hide for disabled, resorted buttons

* moved upload action buttons to menu

* button changes

moved edit button from menu in upload modal
swapped validation button for upload in edit modal
2019-05-28 21:37:28 +02:00
Otto Winter
a9ae70cff1 Fix CWWW/RGBWW lights (#562) 2019-05-28 21:37:28 +02:00
Michiel van Turnhout
d7a8c50c98 Binary sensor map implementation (#551)
* add binary_sensor_map c code

* add python file

* fixed python and C++ code for new framework

* renamed add_sensor to add_channel

* travis

* Updates

- Use struct for channels_ array - heap allocation is not really necessary here.
- any_active can also be written as mask != 0
- Update setup priority to DATA
- Use shorter TAG (name is already long; not important)
- Quotes around name
- Add icon to sensor
- Use new cv.typed_schema
- Change CONF_CHANNEL to CONF_BINARY_SENSOR - makes it clearer that this option accepts a binary sensor (and not for example an int)
- Add test


Co-authored-by: Otto Winter <otto@otto-winter.com>
2019-05-28 21:37:27 +02:00
Michiel van Turnhout
9e56318498 Mpr121 added debounce and thresholds config (#558)
* fixed code issues from previous PR

* travis line to long

* travis

* more travis

* Update esphome/components/mpr121/mpr121.h

Co-Authored-By: Otto Winter <otto@otto-winter.com>

* fixed issues

* fixed issues

* fixes remove duplicate line
remove threshold settings

* fixed touch release thresholds mixup
2019-05-28 21:37:27 +02:00
Otto Winter
2570f2d6f2 Waveshare enter deep sleep mode on shutdown (#561)
Fixes https://github.com/esphome/issues/issues/307

Only enters deep sleep mode when node turns off - not between updates because entering+exiting deep sleep takes some time (could be added later)
2019-05-28 21:37:27 +02:00
Otto Winter
359f54d3c1 Bump version to v1.13.0b3 2019-05-28 16:35:55 +02:00
Otto Winter
68ce1b18c4 Add NTC and resistance sensor (#560)
* Add NTC and resistance sensor

Fixes https://github.com/esphome/feature-requests/issues/248

* Fix

* Fix platformio4 moved get_project_dir
2019-05-28 16:35:50 +02:00
Otto Winter
76d7802650 Do not recompile on version change 2019-05-28 12:11:46 +02:00
Otto Winter
9be16916b7 Fix gitlab 2019-05-28 12:01:32 +02:00
Otto Winter
0ced5509fc Bump version to v1.13.0b2 2019-05-28 10:48:48 +02:00
gitolicious
bd6b9ff1da added link from dashboard to web server, if configured (#556)
* added link from dashboard to web server, if configured

* linter fixes

* simplified integration lookup

* included loaded_integration in storage json

* included loaded_integration in storage json

* fixed loaded_integrations

plus linter changes

* fixed comment: List

Co-Authored-By: Otto Winter <otto@otto-winter.com>

* return empty list

Co-Authored-By: Otto Winter <otto@otto-winter.com>

* convert to list

Co-Authored-By: Otto Winter <otto@otto-winter.com>

* default to empty list on missing loaded_integrations

Co-Authored-By: Otto Winter <otto@otto-winter.com>

* None check no longer needed

Co-Authored-By: Otto Winter <otto@otto-winter.com>

* None check no longer needed

Co-Authored-By: Otto Winter <otto@otto-winter.com>

* removed newline
2019-05-28 10:48:45 +02:00
Otto Winter
edee28acf0 Use lint image for tests 2019-05-28 10:41:19 +02:00
Otto Winter
53e8b3ed3e Update gitlab CI script, add cpp lint 2019-05-28 10:24:13 +02:00
Otto Winter
ac0b095941 Bump version to v1.12.2 2019-03-31 13:13:12 +02:00
Otto Winter
cda9bad233 Upgrade docker base image to 1.4.3 (#499) 2019-03-31 13:13:09 +02:00
Otto Winter
41db8a1264 Fix text sensor MQTT settings (#495)
Fixes https://github.com/esphome/issues/issues/170
2019-03-31 13:13:09 +02:00
Otto Winter
e7e785fd60 Fix dashboard wizard unicode (#494)
* Fix dashboard wizard unicode

Fixes https://github.com/esphome/issues/issues/169

* Fix password md5
2019-03-31 13:13:08 +02:00
Otto Winter
300d3a1f46 Upgrade ESPAsyncTCP to 1.2.0 (#497) 2019-03-31 13:13:08 +02:00
Otto Winter
356554c08d ESP8266 SDK 2.3.0 compat (#490) 2019-03-31 13:13:08 +02:00
Guillermo Ruffino
ced28ad006 Better symlink support under Windows (#487)
* Better symlink support under Windows

* Conditional loading of ctypes wintypes module

* Shortening comment line for pylint

* Adding plint bypass for Python 3
2019-03-31 13:13:08 +02:00
113 changed files with 1944 additions and 604 deletions

View File

@@ -3,6 +3,8 @@
variables:
DOCKER_DRIVER: overlay2
DOCKER_HOST: tcp://docker:2375/
BASE_VERSION: '1.8.3'
TZ: UTC
stages:
- lint
@@ -10,7 +12,7 @@ stages:
- deploy
.lint: &lint
image: esphome/esphome-base-amd64
image: esphome/esphome-lint:latest
stage: lint
before_script:
- script/setup
@@ -18,14 +20,12 @@ stages:
- docker
.test: &test
image: esphome/esphome-base-amd64
image: esphome/esphome-lint:latest
stage: test
before_script:
- script/setup
tags:
- docker
variables:
TZ: UTC
.docker-base: &docker-base
image: esphome/esphome-base-builder
@@ -40,11 +40,11 @@ stages:
- |
if [[ "${IS_HASSIO}" == "YES" ]]; then
BUILD_FROM=esphome/esphome-hassio-base-${BUILD_ARCH}:1.5.1
BUILD_FROM=esphome/esphome-hassio-base-${BUILD_ARCH}:${BASE_VERSION}
BUILD_TO=esphome/esphome-hassio-${BUILD_ARCH}
DOCKERFILE=docker/Dockerfile.hassio
else
BUILD_FROM=esphome/esphome-base-${BUILD_ARCH}:1.5.1
BUILD_FROM=esphome/esphome-base-${BUILD_ARCH}:${BASE_VERSION}
if [[ "${BUILD_ARCH}" == "amd64" ]]; then
BUILD_TO=esphome/esphome
else
@@ -93,12 +93,33 @@ stages:
- docker
stage: deploy
lint-python:
lint-custom:
<<: *lint
script:
- script/ci-custom.py
lint-python:
<<: *lint
script:
- script/lint-python
lint-tidy:
<<: *lint
script:
- pio init --ide atom
- |
if ! patch -R -p0 -s -f --dry-run <script/.neopixelbus.patch; then
patch -p0 < script/.neopixelbus.patch
fi
- script/clang-tidy --all-headers --fix
- script/ci-suggest-changes
lint-format:
<<: *lint
script:
- script/clang-format -i
- script/ci-suggest-changes
test1:
<<: *test
script:
@@ -115,16 +136,12 @@ test3:
- esphome tests/test3.yaml compile
.deploy-pypi: &deploy-pypi
<<: *lint
stage: deploy
image: python:2.7
before_script:
- pip install -e .
- pip install twine
script:
- python setup.py sdist bdist_wheel
- twine upload dist/*
tags:
- docker
- pip install twine wheel
- python setup.py sdist bdist_wheel
- twine upload dist/*
deploy-release:pypi:
<<: *deploy-pypi
@@ -143,77 +160,64 @@ deploy-beta:pypi:
.latest: &latest
<<: *docker-base
only:
- /^v([0-9\.]+)$/
- /^v([0-9\.]+)$/
except:
- branches
.latest-vars: &latest-vars
RELEASE: YES
LATEST: YES
# Also push to beta tag
BETA: YES
- branches
.beta: &beta
<<: *docker-base
only:
- /^v([0-9\.]+b\d+)$/
- /^v([0-9\.]+b\d+)$/
except:
- branches
.beta-vars: &beta-vars
RELEASE: YES
BETA: YES
- branches
.dev: &dev
<<: *docker-base
only:
- dev
- dev
.dev-vars: &dev-vars
DEV: YES
#aarch64-beta-docker:
# <<: *beta
# variables:
# BETA: "YES"
# BUILD_ARCH: aarch64
# IS_HASSIO: "NO"
# RELEASE: "YES"
#aarch64-beta-hassio:
# <<: *beta
# variables:
# BETA: "YES"
# BUILD_ARCH: aarch64
# IS_HASSIO: "YES"
# RELEASE: "YES"
#aarch64-dev-docker:
# <<: *dev
# variables:
# BUILD_ARCH: aarch64
# DEV: "YES"
# IS_HASSIO: "NO"
#aarch64-dev-hassio:
# <<: *dev
# variables:
# BUILD_ARCH: aarch64
# DEV: "YES"
# IS_HASSIO: "YES"
#aarch64-latest-docker:
# <<: *latest
# variables:
# BETA: "YES"
# BUILD_ARCH: aarch64
# IS_HASSIO: "NO"
# LATEST: "YES"
# RELEASE: "YES"
#aarch64-latest-hassio:
# <<: *latest
# variables:
# BETA: "YES"
# BUILD_ARCH: aarch64
# IS_HASSIO: "YES"
# LATEST: "YES"
# RELEASE: "YES"
aarch64-beta-docker:
<<: *beta
variables:
BETA: "YES"
BUILD_ARCH: aarch64
IS_HASSIO: "NO"
RELEASE: "YES"
aarch64-beta-hassio:
<<: *beta
variables:
BETA: "YES"
BUILD_ARCH: aarch64
IS_HASSIO: "YES"
RELEASE: "YES"
aarch64-dev-docker:
<<: *dev
variables:
BUILD_ARCH: aarch64
DEV: "YES"
IS_HASSIO: "NO"
aarch64-dev-hassio:
<<: *dev
variables:
BUILD_ARCH: aarch64
DEV: "YES"
IS_HASSIO: "YES"
aarch64-latest-docker:
<<: *latest
variables:
BETA: "YES"
BUILD_ARCH: aarch64
IS_HASSIO: "NO"
LATEST: "YES"
RELEASE: "YES"
aarch64-latest-hassio:
<<: *latest
variables:
BETA: "YES"
BUILD_ARCH: aarch64
IS_HASSIO: "YES"
LATEST: "YES"
RELEASE: "YES"
amd64-beta-docker:
<<: *beta
variables:
@@ -256,45 +260,45 @@ amd64-latest-hassio:
IS_HASSIO: "YES"
LATEST: "YES"
RELEASE: "YES"
armhf-beta-docker:
armv7-beta-docker:
<<: *beta
variables:
BETA: "YES"
BUILD_ARCH: armhf
BUILD_ARCH: armv7
IS_HASSIO: "NO"
RELEASE: "YES"
armhf-beta-hassio:
armv7-beta-hassio:
<<: *beta
variables:
BETA: "YES"
BUILD_ARCH: armhf
BUILD_ARCH: armv7
IS_HASSIO: "YES"
RELEASE: "YES"
armhf-dev-docker:
armv7-dev-docker:
<<: *dev
variables:
BUILD_ARCH: armhf
BUILD_ARCH: armv7
DEV: "YES"
IS_HASSIO: "NO"
armhf-dev-hassio:
armv7-dev-hassio:
<<: *dev
variables:
BUILD_ARCH: armhf
BUILD_ARCH: armv7
DEV: "YES"
IS_HASSIO: "YES"
armhf-latest-docker:
armv7-latest-docker:
<<: *latest
variables:
BETA: "YES"
BUILD_ARCH: armhf
BUILD_ARCH: armv7
IS_HASSIO: "NO"
LATEST: "YES"
RELEASE: "YES"
armhf-latest-hassio:
armv7-latest-hassio:
<<: *latest
variables:
BETA: "YES"
BUILD_ARCH: armhf
BUILD_ARCH: armv7
IS_HASSIO: "YES"
LATEST: "YES"
RELEASE: "YES"

View File

@@ -1,5 +1,6 @@
sudo: false
language: python
python: '2.7'
install: script/setup
cache:
directories:

View File

@@ -1,4 +1,4 @@
ARG BUILD_FROM=esphome/esphome-base-amd64:1.5.1
ARG BUILD_FROM=esphome/esphome-base-amd64:1.8.3
FROM ${BUILD_FROM}
COPY . .

View File

@@ -1,6 +1,18 @@
FROM python:2.7
FROM esphome/esphome-base-amd64:1.8.3
COPY requirements.txt /requirements.txt
RUN \
apt-get update \
&& apt-get install -y --no-install-recommends \
clang-format-7 \
clang-tidy-7 \
patch \
&& rm -rf \
/tmp/* \
/var/{cache,log}/* \
/var/lib/apt/lists/*
RUN pip install -r /requirements.txt && \
pip install flake8==3.6.0 pylint==1.9.4 pillow
COPY requirements_test.txt /requirements_test.txt
RUN pip2 install --no-cache-dir wheel && pip2 install --no-cache-dir -r /requirements_test.txt
VOLUME ["/esphome"]
WORKDIR /esphome

View File

@@ -1,21 +0,0 @@
FROM ubuntu:bionic
RUN apt-get update && apt-get install -y --no-install-recommends \
python \
python-pip \
python-setuptools \
python-pil \
git \
&& apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/*rm -rf /var/lib/apt/lists/* /tmp/* && \
pip install --no-cache-dir platformio && \
platformio settings set enable_telemetry No && \
platformio settings set check_libraries_interval 1000000 && \
platformio settings set check_platformio_interval 1000000 && \
platformio settings set check_platforms_interval 1000000
COPY docker/platformio.ini /pio/platformio.ini
RUN platformio run -d /pio; rm -rf /pio
COPY requirements.txt /requirements.txt
RUN pip install --no-cache-dir -r /requirements.txt

View File

@@ -1,12 +0,0 @@
; This file allows the docker build file to install the required platformio
; platforms
[env:espressif8266]
platform = espressif8266@1.8.0
board = nodemcuv2
framework = arduino
[env:espressif32]
platform = espressif32@1.5.0
board = nodemcu-32s
framework = arduino

View File

@@ -4,6 +4,11 @@ server {
include /etc/nginx/includes/server_params.conf;
include /etc/nginx/includes/proxy_params.conf;
include /etc/nginx/includes/ssl_params.conf;
ssl on;
ssl_certificate /ssl/%%certfile%%;
ssl_certificate_key /ssl/%%keyfile%%;
# Clear Hass.io Ingress header
proxy_set_header X-Hassio-Ingress "";

View File

@@ -127,7 +127,10 @@ def wrap_to_code(name, comp):
def wrapped(conf):
cg.add(cg.LineComment(u"{}:".format(name)))
if comp.config_schema is not None:
cg.add(cg.LineComment(indent(yaml_util.dump(conf).decode('utf-8'))))
conf_str = yaml_util.dump(conf)
if IS_PY2:
conf_str = conf_str.decode('utf-8')
cg.add(cg.LineComment(indent(conf_str)))
yield coro(conf)
return wrapped

View File

@@ -108,7 +108,6 @@ class APIClient(threading.Thread):
self._message_handlers = []
self._keepalive = 5
self._ping_timer = None
self._refresh_ping()
self.on_disconnect = None
self.on_connect = None
@@ -132,8 +131,8 @@ class APIClient(threading.Thread):
if self._connected:
try:
self.ping()
except APIConnectionError:
self._fatal_error()
except APIConnectionError as err:
self._fatal_error(err)
else:
self._refresh_ping()
@@ -175,7 +174,7 @@ class APIClient(threading.Thread):
raise APIConnectionError("You need to call start() first!")
if self._connected:
raise APIConnectionError("Already connected!")
self.disconnect(on_disconnect=False)
try:
ip = resolve_ip_address(self._address)
@@ -193,8 +192,9 @@ class APIClient(threading.Thread):
try:
self._socket.connect((ip, self._port))
except socket.error as err:
self._fatal_error()
raise APIConnectionError("Error connecting to {}: {}".format(ip, err))
err = APIConnectionError("Error connecting to {}: {}".format(ip, err))
self._fatal_error(err)
raise err
self._socket.settimeout(0.1)
self._socket_open_event.set()
@@ -204,18 +204,20 @@ class APIClient(threading.Thread):
try:
resp = self._send_message_await_response(hello, pb.HelloResponse)
except APIConnectionError as err:
self._fatal_error()
self._fatal_error(err)
raise err
_LOGGER.debug("Successfully connected to %s ('%s' API=%s.%s)", self._address,
resp.server_info, resp.api_version_major, resp.api_version_minor)
self._connected = True
self._refresh_ping()
if self.on_connect is not None:
self.on_connect()
def _check_connected(self):
if not self._connected:
self._fatal_error()
raise APIConnectionError("Must be connected!")
err = APIConnectionError("Must be connected!")
self._fatal_error(err)
raise err
def login(self):
self._check_connected()
@@ -233,13 +235,13 @@ class APIClient(threading.Thread):
if self.on_login is not None:
self.on_login()
def _fatal_error(self):
def _fatal_error(self, err):
was_connected = self._connected
self._close_socket()
if was_connected and self.on_disconnect is not None:
self.on_disconnect()
self.on_disconnect(err)
def _write(self, data): # type: (bytes) -> None
if self._socket is None:
@@ -250,8 +252,9 @@ class APIClient(threading.Thread):
try:
self._socket.sendall(data)
except socket.error as err:
self._fatal_error()
raise APIConnectionError("Error while writing data: {}".format(err))
err = APIConnectionError("Error while writing data: {}".format(err))
self._fatal_error(err)
raise err
def _send_message(self, msg):
# type: (message.Message) -> None
@@ -271,7 +274,6 @@ class APIClient(threading.Thread):
req += _varuint_to_bytes(message_type)
req += encoded
self._write(req)
self._refresh_ping()
def _send_message_await_response_complex(self, send_msg, do_append, do_stop, timeout=1):
event = threading.Event()
@@ -309,7 +311,7 @@ class APIClient(threading.Thread):
self._check_connected()
return self._send_message_await_response(pb.PingRequest(), pb.PingResponse)
def disconnect(self):
def disconnect(self, on_disconnect=True):
self._check_connected()
try:
@@ -318,7 +320,7 @@ class APIClient(threading.Thread):
pass
self._close_socket()
if self.on_disconnect is not None:
if self.on_disconnect is not None and on_disconnect:
self.on_disconnect()
def _check_authenticated(self):
@@ -387,7 +389,6 @@ class APIClient(threading.Thread):
for msg_handler in self._message_handlers[:]:
msg_handler(msg)
self._handle_internal_messages(msg)
self._refresh_ping()
def run(self):
self._running_event.set()
@@ -399,7 +400,7 @@ class APIClient(threading.Thread):
break
if self._connected:
_LOGGER.error("Error while reading incoming messages: %s", err)
self._fatal_error()
self._fatal_error(err)
self._running_event.clear()
def _handle_internal_messages(self, msg):
@@ -431,12 +432,12 @@ def run_logs(config, address):
has_connects = []
def try_connect(tries=0, is_disconnect=True):
def try_connect(err, tries=0):
if stopping:
return
if is_disconnect:
_LOGGER.warning(u"Disconnected from API.")
if err:
_LOGGER.warning(u"Disconnected from API: %s", err)
while retry_timer:
retry_timer.pop(0).cancel()
@@ -445,8 +446,8 @@ def run_logs(config, address):
try:
cli.connect()
cli.login()
except APIConnectionError as err: # noqa
error = err
except APIConnectionError as err2: # noqa
error = err2
if error is None:
_LOGGER.info("Successfully connected to %s", address)
@@ -460,7 +461,7 @@ def run_logs(config, address):
else:
_LOGGER.warning(u"Couldn't connect to API (%s). Trying to reconnect in %s seconds",
error, wait_time)
timer = threading.Timer(wait_time, functools.partial(try_connect, tries + 1, is_disconnect))
timer = threading.Timer(wait_time, functools.partial(try_connect, None, tries + 1))
timer.start()
retry_timer.append(timer)
@@ -484,7 +485,7 @@ def run_logs(config, address):
cli.start()
try:
try_connect(is_disconnect=False)
try_connect(None)
while True:
time.sleep(1)
except KeyboardInterrupt:

View File

@@ -55,7 +55,7 @@ UpdateComponentAction = cg.esphome_ns.class_('UpdateComponentAction', Action)
Automation = cg.esphome_ns.class_('Automation')
LambdaCondition = cg.esphome_ns.class_('LambdaCondition', Condition)
ForCondition = cg.esphome_ns.class_('ForCondition', Condition)
ForCondition = cg.esphome_ns.class_('ForCondition', Condition, cg.Component)
def validate_automation(extra_schema=None, extra_validators=None, single=False):

View File

@@ -144,7 +144,7 @@ float ADS1115Component::request_measurement(ADS1115Sensor *sensor) {
}
this->status_clear_warning();
return millivolts / 1e4f;
return millivolts / 1e3f;
}
uint8_t ADS1115Sensor::get_multiplexer() const { return this->multiplexer_; }

View File

@@ -6,6 +6,7 @@
#include "esphome/core/application.h"
#include "esphome/core/util.h"
#include "esphome/core/defines.h"
#include "esphome/core/version.h"
#ifdef USE_DEEP_SLEEP
#include "esphome/components/deep_sleep/deep_sleep_component.h"
@@ -712,12 +713,12 @@ bool APIConnection::send_buffer(APIMessageType type) {
size_t needed_space = this->send_buffer_.size() + header_len;
if (needed_space > this->client_->space()) {
delay(5);
delay(0);
if (needed_space > this->client_->space()) {
if (type != APIMessageType::SUBSCRIBE_LOGS_RESPONSE) {
ESP_LOGV(TAG, "Cannot send message because of TCP buffer space");
}
delay(5);
delay(0);
return false;
}
}

View File

@@ -0,0 +1,60 @@
#include "binary_sensor_map.h"
#include "esphome/core/log.h"
namespace esphome {
namespace binary_sensor_map {
static const char *TAG = "binary_sensor_map";
void BinarySensorMap::dump_config() { LOG_SENSOR(" ", "binary_sensor_map", this); }
void BinarySensorMap::loop() {
switch (this->sensor_type_) {
case BINARY_SENSOR_MAP_TYPE_GROUP:
this->process_group_();
break;
}
}
void BinarySensorMap::process_group_() {
float total_current_value = 0.0;
uint8_t num_active_sensors = 0;
uint64_t mask = 0x00;
// check all binary_sensors for its state. when active add its value to total_current_value.
// create a bitmask for the binary_sensor status on all channels
for (size_t i = 0; i < this->channels_.size(); i++) {
auto bs = this->channels_[i];
if (bs.binary_sensor->state) {
num_active_sensors++;
total_current_value += bs.sensor_value;
mask |= 1 << i;
}
}
// check if the sensor map was touched
if (mask != 0ULL) {
// did the bit_mask change or is it a new sensor touch
if (this->last_mask_ != mask) {
float publish_value = total_current_value / num_active_sensors;
ESP_LOGD(TAG, "'%s' - Publishing %.2f", this->name_.c_str(), publish_value);
this->publish_state(publish_value);
}
} else if (this->last_mask_ != 0ULL) {
// is this a new sensor release
ESP_LOGD(TAG, "'%s' - No binary sensor active, publishing NAN", this->name_.c_str());
this->publish_state(NAN);
}
this->last_mask_ = mask;
}
void BinarySensorMap::add_channel(binary_sensor::BinarySensor *sensor, float value) {
BinarySensorMapChannel sensor_channel{
.binary_sensor = sensor,
.sensor_value = value,
};
this->channels_.push_back(sensor_channel);
}
void BinarySensorMap::set_sensor_type(BinarySensorMapType sensor_type) { this->sensor_type_ = sensor_type; }
} // namespace binary_sensor_map
} // namespace esphome

View File

@@ -0,0 +1,58 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/binary_sensor/binary_sensor.h"
#include "esphome/components/sensor/sensor.h"
namespace esphome {
namespace binary_sensor_map {
enum BinarySensorMapType {
BINARY_SENSOR_MAP_TYPE_GROUP,
};
struct BinarySensorMapChannel {
binary_sensor::BinarySensor *binary_sensor;
float sensor_value;
};
/** Class to group binary_sensors to one Sensor.
*
* Each binary sensor represents a float value in the group.
*/
class BinarySensorMap : public sensor::Sensor, public Component {
public:
void dump_config() override;
/**
* The loop checks all binary_sensor states
* When the binary_sensor reports a true value for its state, then the float value it represents is added to the
* total_current_value
*
* Only when the total_current_value changed and at least one sensor reports an active state we publish the sensors
* average value. When the value changed and no sensors ar active we publish NAN.
* */
void loop() override;
float get_setup_priority() const override { return setup_priority::DATA; }
/** Add binary_sensors to the group.
* Each binary_sensor represents a float value when its state is true
*
* @param *sensor The binary sensor.
* @param value The value this binary_sensor represents
*/
void add_channel(binary_sensor::BinarySensor *sensor, float value);
void set_sensor_type(BinarySensorMapType sensor_type);
protected:
std::vector<BinarySensorMapChannel> channels_{};
BinarySensorMapType sensor_type_{BINARY_SENSOR_MAP_TYPE_GROUP};
// this gives max 64 channels per binary_sensor_map
uint64_t last_mask_{0x00};
/**
* methods to process the types of binary_sensor_maps
* GROUP: process_group_() just map to a value
* */
void process_group_();
};
} // namespace binary_sensor_map
} // namespace esphome

View File

@@ -0,0 +1,42 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import sensor, binary_sensor
from esphome.const import CONF_ID, CONF_CHANNELS, CONF_VALUE, CONF_TYPE, UNIT_EMPTY, \
ICON_CHECK_CIRCLE_OUTLINE, CONF_BINARY_SENSOR
DEPENDENCIES = ['binary_sensor']
binary_sensor_map_ns = cg.esphome_ns.namespace('binary_sensor_map')
BinarySensorMap = binary_sensor_map_ns.class_('BinarySensorMap', cg.Component, sensor.Sensor)
SensorMapType = binary_sensor_map_ns.enum('SensorMapType')
CONF_GROUP = 'group'
SENSOR_MAP_TYPES = {
CONF_GROUP: SensorMapType.BINARY_SENSOR_MAP_TYPE_GROUP,
}
entry = {
cv.Required(CONF_BINARY_SENSOR): cv.use_id(binary_sensor.BinarySensor),
cv.Required(CONF_VALUE): cv.float_,
}
CONFIG_SCHEMA = cv.typed_schema({
CONF_GROUP: sensor.sensor_schema(UNIT_EMPTY, ICON_CHECK_CIRCLE_OUTLINE, 0).extend({
cv.GenerateID(): cv.declare_id(BinarySensorMap),
cv.Required(CONF_CHANNELS): cv.All(cv.ensure_list(entry), cv.Length(min=1)),
}),
}, lower=True)
def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
yield cg.register_component(var, config)
yield sensor.register_sensor(var, config)
constant = SENSOR_MAP_TYPES[config[CONF_TYPE]]
cg.add(var.set_sensor_type(constant))
for ch in config[CONF_CHANNELS]:
input_var = yield cg.get_variable(ch[CONF_BINARY_SENSOR])
cg.add(var.add_channel(input_var, ch[CONF_VALUE]))

View File

View File

@@ -0,0 +1,67 @@
#include "ct_clamp_sensor.h"
#include "esphome/core/log.h"
#include <cmath>
namespace esphome {
namespace ct_clamp {
static const char *TAG = "ct_clamp";
void CTClampSensor::dump_config() {
LOG_SENSOR("", "CT Clamp Sensor", this);
ESP_LOGCONFIG(TAG, " Sample Duration: %.2fs", this->sample_duration_ / 1e3f);
LOG_UPDATE_INTERVAL(this);
}
void CTClampSensor::update() {
// Update only starts the sampling phase, in loop() the actual sampling is happening.
// Request a high loop() execution interval during sampling phase.
this->high_freq_.start();
// Set timeout for ending sampling phase
this->set_timeout("read", this->sample_duration_, [this]() {
this->is_sampling_ = false;
this->high_freq_.stop();
if (this->num_samples_ == 0) {
// Shouldn't happen, but let's not crash if it does.
this->publish_state(NAN);
return;
}
float raw = this->sample_sum_ / this->num_samples_;
float irms = std::sqrt(raw);
ESP_LOGD(TAG, "'%s' - Raw Value: %.2fA", this->name_.c_str(), irms);
this->publish_state(irms);
});
// Set sampling values
this->is_sampling_ = true;
this->num_samples_ = 0;
this->sample_sum_ = 0.0f;
}
void CTClampSensor::loop() {
if (!this->is_sampling_)
return;
// Perform a single sample
float value = this->source_->sample();
// Adjust DC offset via low pass filter (exponential moving average)
const float alpha = 0.001f;
this->offset_ = this->offset_ * (1 - alpha) + value * alpha;
// Filtered value centered around the mid-point (0V)
float filtered = value - this->offset_;
// IRMS is sqrt(∑v_i²)
float sq = filtered * filtered;
this->sample_sum_ += sq;
this->num_samples_++;
}
} // namespace ct_clamp
} // namespace esphome

View File

@@ -0,0 +1,46 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/esphal.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/voltage_sampler/voltage_sampler.h"
namespace esphome {
namespace ct_clamp {
class CTClampSensor : public sensor::Sensor, public PollingComponent {
public:
void update() override;
void loop() override;
void dump_config() override;
float get_setup_priority() const override { return setup_priority::DATA; }
void set_sample_duration(uint32_t sample_duration) { sample_duration_ = sample_duration; }
void set_source(voltage_sampler::VoltageSampler *source) { source_ = source; }
protected:
/// High Frequency loop() requester used during sampling phase.
HighFrequencyLoopRequester high_freq_;
/// Duration in ms of the sampling phase.
uint32_t sample_duration_;
/// The sampling source to read values from.
voltage_sampler::VoltageSampler *source_;
/** The DC offset of the circuit.
*
* Diagram: https://learn.openenergymonitor.org/electricity-monitoring/ct-sensors/interface-with-arduino
*
* This is automatically calculated with an exponential moving average/digital low pass filter.
*
* 0.5 is a good initial approximation to start with for most ESP8266 setups.
*/
float offset_ = 0.5f;
float sample_sum_ = 0.0f;
uint32_t num_samples_ = 0;
bool is_sampling_ = false;
};
} // namespace ct_clamp
} // namespace esphome

View File

@@ -0,0 +1,27 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import sensor, voltage_sampler
from esphome.const import CONF_SENSOR, CONF_ID, ICON_FLASH, UNIT_AMPERE
AUTO_LOAD = ['voltage_sampler']
CONF_SAMPLE_DURATION = 'sample_duration'
ct_clamp_ns = cg.esphome_ns.namespace('ct_clamp')
CTClampSensor = ct_clamp_ns.class_('CTClampSensor', sensor.Sensor, cg.PollingComponent)
CONFIG_SCHEMA = sensor.sensor_schema(UNIT_AMPERE, ICON_FLASH, 2).extend({
cv.GenerateID(): cv.declare_id(CTClampSensor),
cv.Required(CONF_SENSOR): cv.use_id(voltage_sampler.VoltageSampler),
cv.Optional(CONF_SAMPLE_DURATION, default='200ms'): cv.positive_time_period_milliseconds,
}).extend(cv.polling_component_schema('60s'))
def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
yield cg.register_component(var, config)
yield sensor.register_sensor(var, config)
sens = yield cg.get_variable(config[CONF_SENSOR])
cg.add(var.set_source(sens))
cg.add(var.set_sample_duration(config[CONF_SAMPLE_DURATION]))

View File

@@ -19,6 +19,8 @@ class CWWWLightOutput : public light::LightOutput {
traits.set_supports_rgb(false);
traits.set_supports_rgb_white_value(false);
traits.set_supports_color_temperature(true);
traits.set_min_mireds(this->cold_white_temperature_);
traits.set_max_mireds(this->warm_white_temperature_);
return traits;
}
void write_state(light::LightState *state) override {

View File

@@ -25,4 +25,4 @@ def to_code(config):
wwhite = yield cg.get_variable(config[CONF_WARM_WHITE])
cg.add(var.set_warm_white(wwhite))
cg.add(var.set_warm_white_temperature(config[CONF_COLD_WHITE_COLOR_TEMPERATURE]))
cg.add(var.set_warm_white_temperature(config[CONF_WARM_WHITE_COLOR_TEMPERATURE]))

View File

@@ -2,6 +2,7 @@
#include "esphome/core/log.h"
#include "esphome/core/helpers.h"
#include "esphome/core/defines.h"
#include "esphome/core/version.h"
#ifdef ARDUINO_ARCH_ESP32
#include <rom/rtc.h>
@@ -19,7 +20,7 @@ void DebugComponent::dump_config() {
return;
#endif
ESP_LOGD(TAG, "ESPHome Core version %s", ESPHOME_VERSION);
ESP_LOGD(TAG, "ESPHome version %s", ESPHOME_VERSION);
this->free_heap_ = ESP.getFreeHeap();
ESP_LOGD(TAG, "Free Heap Size: %u bytes", this->free_heap_);

View File

@@ -87,7 +87,7 @@ void DeepSleepComponent::begin_sleep(bool manual) {
ESP.deepSleep(*this->sleep_duration_);
#endif
}
float DeepSleepComponent::get_setup_priority() const { return -100.0f; }
float DeepSleepComponent::get_setup_priority() const { return setup_priority::LATE; }
void DeepSleepComponent::prevent_deep_sleep() { this->prevent_ = true; }
} // namespace deep_sleep

View File

@@ -164,11 +164,18 @@ bool HOT DHT::read_sensor_(float *temperature, float *humidity, bool report_erro
} else {
uint16_t raw_humidity = (uint16_t(data[0] & 0xFF) << 8) | (data[1] & 0xFF);
uint16_t raw_temperature = (uint16_t(data[2] & 0xFF) << 8) | (data[3] & 0xFF);
*humidity = raw_humidity * 0.1f;
if ((raw_temperature & 0x8000) != 0)
raw_temperature = ~(raw_temperature & 0x7FFF);
if (raw_temperature == 1 && raw_humidity == 10) {
if (report_errors) {
ESP_LOGE(TAG, "Invalid temperature+humidity! Sensor reported 1°C and 1%% Hum");
}
return false;
}
*humidity = raw_humidity * 0.1f;
*temperature = int16_t(raw_temperature) * 0.1f;
}

View File

@@ -1,5 +1,6 @@
#include "esp32_ble_tracker.h"
#include "esphome/core/log.h"
#include "esphome/core/application.h"
#ifdef ARDUINO_ARCH_ESP32
@@ -162,6 +163,11 @@ void ESP32BLETracker::start_scan(bool first) {
esp_ble_gap_set_scan_params(&this->scan_params_);
esp_ble_gap_start_scanning(this->scan_interval_);
this->set_timeout("scan", this->scan_interval_ * 2000, []() {
ESP_LOGW(TAG, "ESP-IDF BLE scan never terminated, rebooting to restore BLE stack...");
App.reboot();
});
}
void ESP32BLETracker::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {

View File

@@ -23,7 +23,7 @@ FanSpeed = fan_ns.enum('FanSpeed')
FAN_SPEEDS = {
'OFF': FanSpeed.FAN_SPEED_OFF,
'LOW': FanSpeed.FAN_SPEED_LOW,
'MEDIuM': FanSpeed.FAN_SPEED_MEDIUM,
'MEDIUM': FanSpeed.FAN_SPEED_MEDIUM,
'HIGH': FanSpeed.FAN_SPEED_HIGH,
}

View File

@@ -5,8 +5,7 @@ from esphome.const import CONF_OUTPUT_ID, CONF_NUM_LEDS, CONF_RGB_ORDER, CONF_MA
from esphome.core import coroutine
fastled_base_ns = cg.esphome_ns.namespace('fastled_base')
FastLEDLightOutput = fastled_base_ns.class_('FastLEDLightOutput', cg.Component,
light.AddressableLight)
FastLEDLightOutput = fastled_base_ns.class_('FastLEDLightOutput', light.AddressableLight)
RGB_ORDERS = [
'RGB',

View File

@@ -16,7 +16,7 @@
namespace esphome {
namespace fastled_base {
class FastLEDLightOutput : public Component, public light::AddressableLight {
class FastLEDLightOutput : public light::AddressableLight {
public:
/// Only for custom effects: Get the internal controller.
CLEDController *get_controller() const { return this->controller_; }

View File

@@ -50,6 +50,7 @@ def globals_set_to_code(config, action_id, template_arg, args):
full_id, paren = yield cg.get_variable_with_full_id(config[CONF_ID])
template_arg = cg.TemplateArguments(full_id.type, *template_arg)
var = cg.new_Pvariable(action_id, template_arg, paren)
templ = yield cg.templatable(config[CONF_VALUE], args, None)
templ = yield cg.templatable(config[CONF_VALUE], args, None,
to_exp=cg.RawExpression)
cg.add(var.set_value(templ))
yield var

View File

@@ -1,5 +1,6 @@
#include "hx711.h"
#include "esphome/core/log.h"
#include "esphome/core/helpers.h"
namespace esphome {
namespace hx711 {
@@ -10,6 +11,7 @@ void HX711Sensor::setup() {
ESP_LOGCONFIG(TAG, "Setting up HX711 '%s'...", this->name_.c_str());
this->sck_pin_->setup();
this->dout_pin_->setup();
this->sck_pin_->digital_write(false);
// Read sensor once without publishing to set the gain
this->read_sensor_(nullptr);
@@ -25,8 +27,9 @@ float HX711Sensor::get_setup_priority() const { return setup_priority::DATA; }
void HX711Sensor::update() {
uint32_t result;
if (this->read_sensor_(&result)) {
ESP_LOGD(TAG, "'%s': Got value %u", this->name_.c_str(), result);
this->publish_state(result);
int32_t value = static_cast<int32_t>(result);
ESP_LOGD(TAG, "'%s': Got value %d", this->name_.c_str(), value);
this->publish_state(value);
}
}
bool HX711Sensor::read_sensor_(uint32_t *result) {
@@ -39,10 +42,11 @@ bool HX711Sensor::read_sensor_(uint32_t *result) {
this->status_clear_warning();
uint32_t data = 0;
disable_interrupts();
for (uint8_t i = 0; i < 24; i++) {
this->sck_pin_->digital_write(true);
delayMicroseconds(1);
data |= uint32_t(this->dout_pin_->digital_read()) << (24 - i);
data |= uint32_t(this->dout_pin_->digital_read()) << (23 - i);
this->sck_pin_->digital_write(false);
delayMicroseconds(1);
}
@@ -50,10 +54,16 @@ bool HX711Sensor::read_sensor_(uint32_t *result) {
// Cycle clock pin for gain setting
for (uint8_t i = 0; i < this->gain_; i++) {
this->sck_pin_->digital_write(true);
delayMicroseconds(1);
this->sck_pin_->digital_write(false);
delayMicroseconds(1);
}
enable_interrupts();
if (data & 0x800000ULL) {
data |= 0xFF000000ULL;
}
data ^= 0x800000;
if (result != nullptr)
*result = data;
return true;

View File

@@ -50,7 +50,7 @@ void I2CComponent::dump_config() {
}
}
}
float I2CComponent::get_setup_priority() const { return setup_priority::HARDWARE; }
float I2CComponent::get_setup_priority() const { return setup_priority::BUS; }
void I2CComponent::raw_begin_transmission(uint8_t address) {
ESP_LOGVV(TAG, "Beginning Transmission to 0x%02X:", address);

View File

@@ -2,7 +2,7 @@ import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import automation
from esphome.components import sensor
from esphome.const import CONF_ID, CONF_TIME_ID, CONF_SENSOR, CONF_RESTORE
from esphome.const import CONF_ID, CONF_SENSOR, CONF_RESTORE
integration_ns = cg.esphome_ns.namespace('integration')
IntegrationSensor = integration_ns.class_('IntegrationSensor', sensor.Sensor, cg.Component)
@@ -26,7 +26,6 @@ INTEGRATION_METHODS = {
CONF_TIME_UNIT = 'time_unit'
CONF_INTEGRATION_METHOD = 'integration_method'
CONFIG_SCHEMA = sensor.SENSOR_SCHEMA.extend({
cv.GenerateID(): cv.declare_id(IntegrationSensor),
cv.Required(CONF_SENSOR): cv.use_id(sensor.Sensor),
@@ -45,7 +44,7 @@ def to_code(config):
sens = yield cg.get_variable(config[CONF_SENSOR])
cg.add(var.set_sensor(sens))
cg.add(var.set_time(config[CONF_TIME_ID]))
cg.add(var.set_time(config[CONF_TIME_UNIT]))
cg.add(var.set_method(config[CONF_INTEGRATION_METHOD]))
cg.add(var.set_restore(config[CONF_RESTORE]))

View File

@@ -4,6 +4,8 @@
namespace esphome {
namespace light {
static const char *TAG = "light.addressable";
const ESPColor ESPColor::BLACK = ESPColor(0, 0, 0, 0);
const ESPColor ESPColor::WHITE = ESPColor(255, 255, 255, 255);
@@ -80,11 +82,78 @@ void ESPRangeView::set(const ESPColor &color) {
}
}
ESPColorView ESPRangeView::operator[](int32_t index) const {
index = interpret_index(index, this->size());
index = interpret_index(index, this->size()) + this->begin_;
return (*this->parent_)[index];
}
ESPRangeIterator ESPRangeView::begin() { return {*this, this->begin_}; }
ESPRangeIterator ESPRangeView::end() { return {*this, this->end_}; }
void ESPRangeView::set_red(uint8_t red) {
for (auto c : *this)
c.set_red(red);
}
void ESPRangeView::set_green(uint8_t green) {
for (auto c : *this)
c.set_green(green);
}
void ESPRangeView::set_blue(uint8_t blue) {
for (auto c : *this)
c.set_blue(blue);
}
void ESPRangeView::set_white(uint8_t white) {
for (auto c : *this)
c.set_white(white);
}
void ESPRangeView::set_effect_data(uint8_t effect_data) {
for (auto c : *this)
c.set_effect_data(effect_data);
}
void ESPRangeView::fade_to_white(uint8_t amnt) {
for (auto c : *this)
c.fade_to_white(amnt);
}
void ESPRangeView::fade_to_black(uint8_t amnt) {
for (auto c : *this)
c.fade_to_white(amnt);
}
void ESPRangeView::lighten(uint8_t delta) {
for (auto c : *this)
c.lighten(delta);
}
void ESPRangeView::darken(uint8_t delta) {
for (auto c : *this)
c.darken(delta);
}
ESPRangeView &ESPRangeView::operator=(const ESPRangeView &rhs) {
// If size doesn't match, error (todo warning)
if (rhs.size() != this->size())
return *this;
ESPColorView ESPRangeView::Iterator::operator*() const { return (*this->range_->parent_)[this->i_]; }
if (this->parent_ != rhs.parent_) {
for (int32_t i = 0; i < this->size(); i++)
(*this)[i].set(rhs[i].get());
return *this;
}
// If both equal, already done
if (rhs.begin_ == this->begin_)
return *this;
if (rhs.begin_ > this->begin_) {
// Copy from left
for (int32_t i = 0; i < this->size(); i++) {
(*this)[i].set(rhs[i].get());
}
} else {
// Copy from right
for (int32_t i = this->size() - 1; i >= 0; i--) {
(*this)[i].set(rhs[i].get());
}
}
return *this;
}
ESPColorView ESPRangeIterator::operator*() const { return this->range_.parent_->get(this->i_); }
int32_t HOT interpret_index(int32_t index, int32_t size) {
if (index < 0)
@@ -92,5 +161,24 @@ int32_t HOT interpret_index(int32_t index, int32_t size) {
return index;
}
void AddressableLight::call_setup() {
this->setup_internal_();
this->setup();
#ifdef ESPHOME_LOG_HAS_VERY_VERBOSE
this->set_interval(5000, [this]() {
const char *name = this->state_parent_ == nullptr ? "" : this->state_parent_->get_name().c_str();
ESP_LOGVV(TAG, "Addressable Light '%s' (effect_active=%s next_show=%s)", name, YESNO(this->effect_active_),
YESNO(this->next_show_));
for (int i = 0; i < this->size(); i++) {
auto color = this->get(i);
ESP_LOGVV(TAG, " [%2d] Color: R=%3u G=%3u B=%3u W=%3u", i, color.get_red_raw(), color.get_green_raw(),
color.get_blue_raw(), color.get_white_raw());
}
ESP_LOGVV(TAG, "");
});
#endif
}
} // namespace light
} // namespace esphome

View File

@@ -335,13 +335,21 @@ class ESPColorView : public ESPColorSettable {
void darken(uint8_t delta) override { this->set(this->get().darken(delta)); }
ESPColor get() const { return ESPColor(this->get_red(), this->get_green(), this->get_blue(), this->get_white()); }
uint8_t get_red() const { return this->color_correction_->color_uncorrect_red(*this->red_); }
uint8_t get_red_raw() const { return *this->red_; }
uint8_t get_green() const { return this->color_correction_->color_uncorrect_green(*this->green_); }
uint8_t get_green_raw() const { return *this->green_; }
uint8_t get_blue() const { return this->color_correction_->color_uncorrect_blue(*this->blue_); }
uint8_t get_blue_raw() const { return *this->blue_; }
uint8_t get_white() const {
if (this->white_ == nullptr)
return 0;
return this->color_correction_->color_uncorrect_white(*this->white_);
}
uint8_t get_white_raw() const {
if (this->white_ == nullptr)
return 0;
return *this->white_;
}
uint8_t get_effect_data() const {
if (this->effect_data_ == nullptr)
return 0;
@@ -364,23 +372,10 @@ class AddressableLight;
int32_t interpret_index(int32_t index, int32_t size);
class ESPRangeIterator;
class ESPRangeView : public ESPColorSettable {
public:
class Iterator {
public:
Iterator(ESPRangeView *range, int32_t i) : range_(range), i_(i) {}
Iterator operator++() {
this->i_++;
return *this;
}
bool operator!=(const Iterator &other) const { return this->i_ != other.i_; }
ESPColorView operator*() const;
protected:
ESPRangeView *range_;
int32_t i_;
};
ESPRangeView(AddressableLight *parent, int32_t begin, int32_t an_end) : parent_(parent), begin_(begin), end_(an_end) {
if (this->end_ < this->begin_) {
this->end_ = this->begin_;
@@ -388,8 +383,8 @@ class ESPRangeView : public ESPColorSettable {
}
ESPColorView operator[](int32_t index) const;
Iterator begin() { return {this, this->begin_}; }
Iterator end() { return {this, this->end_}; }
ESPRangeIterator begin();
ESPRangeIterator end();
void set(const ESPColor &color) override;
ESPRangeView &operator=(const ESPColor &rhs) {
@@ -404,78 +399,42 @@ class ESPRangeView : public ESPColorSettable {
this->set_hsv(rhs);
return *this;
}
ESPRangeView &operator=(const ESPRangeView &rhs) {
// If size doesn't match, error (todo warning)
if (rhs.size() != this->size())
return *this;
if (this->parent_ != rhs.parent_) {
for (int32_t i = 0; i < this->size(); i++)
(*this)[i].set(rhs[i].get());
return *this;
}
// If both equal, already done
if (rhs.begin_ == this->begin_)
return *this;
if (rhs.begin_ < this->begin_) {
// Copy into rhs
for (int32_t i = 0; i < this->size(); i++)
rhs[i].set((*this)[i].get());
} else {
// Copy into this
for (int32_t i = 0; i < this->size(); i++)
(*this)[i].set(rhs[i].get());
}
return *this;
}
void set_red(uint8_t red) override {
for (auto c : *this)
c.set_red(red);
}
void set_green(uint8_t green) override {
for (auto c : *this)
c.set_green(green);
}
void set_blue(uint8_t blue) override {
for (auto c : *this)
c.set_blue(blue);
}
void set_white(uint8_t white) override {
for (auto c : *this)
c.set_white(white);
}
void set_effect_data(uint8_t effect_data) override {
for (auto c : *this)
c.set_effect_data(effect_data);
}
void fade_to_white(uint8_t amnt) override {
for (auto c : *this)
c.fade_to_white(amnt);
}
void fade_to_black(uint8_t amnt) override {
for (auto c : *this)
c.fade_to_white(amnt);
}
void lighten(uint8_t delta) override {
for (auto c : *this)
c.lighten(delta);
}
void darken(uint8_t delta) override {
for (auto c : *this)
c.darken(delta);
}
ESPRangeView &operator=(const ESPRangeView &rhs);
void set_red(uint8_t red) override;
void set_green(uint8_t green) override;
void set_blue(uint8_t blue) override;
void set_white(uint8_t white) override;
void set_effect_data(uint8_t effect_data) override;
void fade_to_white(uint8_t amnt) override;
void fade_to_black(uint8_t amnt) override;
void lighten(uint8_t delta) override;
void darken(uint8_t delta) override;
int32_t size() const { return this->end_ - this->begin_; }
protected:
friend ESPRangeIterator;
AddressableLight *parent_;
int32_t begin_;
int32_t end_;
};
class AddressableLight : public LightOutput {
class ESPRangeIterator {
public:
ESPRangeIterator(const ESPRangeView &range, int32_t i) : range_(range), i_(i) {}
ESPRangeIterator operator++() {
this->i_++;
return *this;
}
bool operator!=(const ESPRangeIterator &other) const { return this->i_ != other.i_; }
ESPColorView operator*() const;
protected:
ESPRangeView range_;
int32_t i_;
};
class AddressableLight : public LightOutput, public Component {
public:
virtual int32_t size() const = 0;
ESPColorView operator[](int32_t index) const { return this->get_view_internal(interpret_index(index, this->size())); }
@@ -487,8 +446,8 @@ class AddressableLight : public LightOutput {
return ESPRangeView(this, from, to);
}
ESPRangeView all() { return ESPRangeView(this, 0, this->size()); }
ESPRangeView::Iterator begin() { return this->all().begin(); }
ESPRangeView::Iterator end() { return this->all().end(); }
ESPRangeIterator begin() { return this->all().begin(); }
ESPRangeIterator end() { return this->all().end(); }
void shift_left(int32_t amnt) {
if (amnt < 0) {
this->shift_right(-amnt);
@@ -530,13 +489,18 @@ class AddressableLight : public LightOutput {
this->correction_.set_max_brightness(ESPColor(uint8_t(roundf(red * 255.0f)), uint8_t(roundf(green * 255.0f)),
uint8_t(roundf(blue * 255.0f)), uint8_t(roundf(white * 255.0f))));
}
void setup_state(LightState *state) override { this->correction_.calculate_gamma_table(state->get_gamma_correct()); }
void setup_state(LightState *state) override {
this->correction_.calculate_gamma_table(state->get_gamma_correct());
this->state_parent_ = state;
}
void schedule_show() { this->next_show_ = true; }
#ifdef USE_POWER_SUPPLY
void set_power_supply(power_supply::PowerSupply *power_supply) { this->power_.set_parent(power_supply); }
#endif
void call_setup() override;
protected:
bool should_show_() const { return this->effect_active_ || this->next_show_; }
void mark_shown_() {
@@ -559,6 +523,7 @@ class AddressableLight : public LightOutput {
#ifdef USE_POWER_SUPPLY
power_supply::PowerSupplyRequester power_;
#endif
LightState *state_parent_{nullptr};
};
} // namespace light

View File

@@ -113,7 +113,7 @@ class AddressableColorWipeEffect : public AddressableLightEffect {
it.shift_right(1);
const AddressableColorWipeEffectColor color = this->colors_[this->at_color_];
const ESPColor esp_color = ESPColor(color.r, color.g, color.b, color.w);
if (!this->reverse_)
if (this->reverse_)
it[-1] = esp_color;
else
it[0] = esp_color;
@@ -308,14 +308,15 @@ class AddressableFlickerEffect : public AddressableLightEffect {
explicit AddressableFlickerEffect(const std::string &name) : AddressableLightEffect(name) {}
void apply(AddressableLight &it, const ESPColor &current_color) override {
const uint32_t now = millis();
const uint8_t delta_intensity = 255 - this->intensity_;
const uint8_t intensity = this->intensity_;
const uint8_t inv_intensity = 255 - intensity;
if (now - this->last_update_ < this->update_interval_)
return;
this->last_update_ = now;
fast_random_set_seed(random_uint32());
for (auto var : it) {
const uint8_t flicker = fast_random_8() % this->intensity_;
var = (var.get() * delta_intensity) + (current_color * flicker);
const uint8_t flicker = fast_random_8() % intensity;
var = (var.get() * inv_intensity) + (current_color * flicker);
}
}
void set_update_interval(uint32_t update_interval) { this->update_interval_ = update_interval; }

View File

@@ -89,7 +89,7 @@ template<typename... Ts> class LightIsOnCondition : public Condition<Ts...> {
protected:
LightState *state_;
};
template<typename... Ts> class LightIsOffCondition : public Condition<LightState, Ts...> {
template<typename... Ts> class LightIsOffCondition : public Condition<Ts...> {
public:
explicit LightIsOffCondition(LightState *state) : state_(state) {}
bool check(Ts... x) override { return !this->state_->current_values.is_on(); }

View File

@@ -5,7 +5,7 @@ from esphome.const import CONF_ID, CONF_TRANSITION_LENGTH, CONF_STATE, CONF_FLAS
CONF_EFFECT, CONF_BRIGHTNESS, CONF_RED, CONF_GREEN, CONF_BLUE, CONF_WHITE, \
CONF_COLOR_TEMPERATURE, CONF_RANGE_FROM, CONF_RANGE_TO
from .types import DimRelativeAction, ToggleAction, LightState, LightControlAction, \
AddressableLightState, AddressableSet
AddressableLightState, AddressableSet, LightIsOnCondition, LightIsOffCondition
@automation.register_action('light.toggle', ToggleAction, automation.maybe_simple_id({
@@ -145,3 +145,16 @@ def light_addressable_set_to_code(config, action_id, template_arg, args):
templ = yield cg.templatable(config[CONF_WHITE], args, cg.uint8, to_exp=rgbw_to_exp)
cg.add(var.set_white(templ))
yield var
@automation.register_condition('light.is_on', LightIsOnCondition,
automation.maybe_simple_id({
cv.Required(CONF_ID): cv.use_id(LightState),
}))
@automation.register_condition('light.is_off', LightIsOffCondition,
automation.maybe_simple_id({
cv.Required(CONF_ID): cv.use_id(LightState),
}))
def light_is_on_off_to_code(config, condition_id, template_arg, args):
paren = yield cg.get_variable(config[CONF_ID])
yield cg.new_Pvariable(condition_id, template_arg, paren)

View File

@@ -129,7 +129,7 @@ class FlickerLightEffect : public LightEffect {
LightColorValues out;
const float alpha = this->alpha_;
const float beta = 1.0f - alpha;
out.set_state(remote.get_state());
out.set_state(true);
out.set_brightness(remote.get_brightness() * beta + current.get_brightness() * alpha +
(random_cubic_float() * this->intensity_));
out.set_red(remote.get_red() * beta + current.get_red() * alpha + (random_cubic_float() * this->intensity_));
@@ -144,6 +144,7 @@ class FlickerLightEffect : public LightEffect {
if (traits.get_supports_brightness())
call.set_transition_length(0);
call.from_light_color_values(out);
call.set_state(true);
call.perform();
}

View File

@@ -7,7 +7,7 @@ LightState = light_ns.class_('LightState', cg.Nameable, cg.Component)
# Fake class for addressable lights
AddressableLightState = light_ns.class_('LightState', LightState)
LightOutput = light_ns.class_('LightOutput')
AddressableLight = light_ns.class_('AddressableLight')
AddressableLight = light_ns.class_('AddressableLight', cg.Component)
AddressableLightRef = AddressableLight.operator('ref')
LightColorValues = light_ns.class_('LightColorValues')
@@ -16,6 +16,8 @@ ToggleAction = light_ns.class_('ToggleAction', automation.Action)
LightControlAction = light_ns.class_('LightControlAction', automation.Action)
DimRelativeAction = light_ns.class_('DimRelativeAction', automation.Action)
AddressableSet = light_ns.class_('AddressableSet', automation.Action)
LightIsOnCondition = light_ns.class_('LightIsOnCondition', automation.Condition)
LightIsOffCondition = light_ns.class_('LightIsOffCondition', automation.Condition)
# Effects
LightEffect = light_ns.class_('LightEffect')

View File

@@ -3,6 +3,11 @@ import esphome.config_validation as cv
from esphome.components import i2c
from esphome.const import CONF_ID
CONF_TOUCH_THRESHOLD = "touch_threshold"
CONF_RELEASE_THRESHOLD = "release_threshold"
CONF_TOUCH_DEBOUNCE = "touch_debounce"
CONF_RELEASE_DEBOUNCE = "release_debounce"
DEPENDENCIES = ['i2c']
AUTO_LOAD = ['binary_sensor']
@@ -13,10 +18,18 @@ MPR121Component = mpr121_ns.class_('MPR121Component', cg.Component, i2c.I2CDevic
MULTI_CONF = True
CONFIG_SCHEMA = cv.Schema({
cv.GenerateID(): cv.declare_id(MPR121Component),
cv.Optional(CONF_RELEASE_DEBOUNCE, default=0): cv.int_range(min=0, max=7),
cv.Optional(CONF_TOUCH_DEBOUNCE, default=0): cv.int_range(min=0, max=7),
cv.Optional(CONF_TOUCH_THRESHOLD, default=0x0b): cv.int_range(min=0x05, max=0x30),
cv.Optional(CONF_RELEASE_THRESHOLD, default=0x06): cv.int_range(min=0x05, max=0x30),
}).extend(cv.COMPONENT_SCHEMA).extend(i2c.i2c_device_schema(0x5A))
def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
cg.add(var.set_touch_debounce(config[CONF_TOUCH_DEBOUNCE]))
cg.add(var.set_release_debounce(config[CONF_RELEASE_DEBOUNCE]))
cg.add(var.set_touch_threshold(config[CONF_TOUCH_THRESHOLD]))
cg.add(var.set_release_threshold(config[CONF_RELEASE_THRESHOLD]))
yield cg.register_component(var, config)
yield i2c.register_i2c_device(var, config)

View File

@@ -2,7 +2,8 @@ import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import binary_sensor
from esphome.const import CONF_CHANNEL, CONF_ID
from . import mpr121_ns, MPR121Component, CONF_MPR121_ID
from . import mpr121_ns, MPR121Component, CONF_MPR121_ID, CONF_TOUCH_THRESHOLD, \
CONF_RELEASE_THRESHOLD
DEPENDENCIES = ['mpr121']
MPR121Channel = mpr121_ns.class_('MPR121Channel', binary_sensor.BinarySensor)
@@ -11,14 +12,20 @@ CONFIG_SCHEMA = binary_sensor.BINARY_SENSOR_SCHEMA.extend({
cv.GenerateID(): cv.declare_id(MPR121Channel),
cv.GenerateID(CONF_MPR121_ID): cv.use_id(MPR121Component),
cv.Required(CONF_CHANNEL): cv.int_range(min=0, max=11),
cv.Optional(CONF_TOUCH_THRESHOLD): cv.int_range(min=0x05, max=0x30),
cv.Optional(CONF_RELEASE_THRESHOLD): cv.int_range(min=0x05, max=0x30),
})
def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
yield binary_sensor.register_binary_sensor(var, config)
hub = yield cg.get_variable(config[CONF_MPR121_ID])
cg.add(var.set_channel(config[CONF_CHANNEL]))
hub = yield cg.get_variable(config[CONF_MPR121_ID])
if CONF_TOUCH_THRESHOLD in config:
cg.add(var.set_touch_threshold(config[CONF_TOUCH_THRESHOLD]))
if CONF_RELEASE_THRESHOLD in config:
cg.add(var.set_release_threshold(config[CONF_RELEASE_THRESHOLD]))
cg.add(hub.register_channel(var))

View File

@@ -18,9 +18,11 @@ void MPR121Component::setup() {
}
// set touch sensitivity for all 12 channels
for (uint8_t i = 0; i < 12; i++) {
this->write_byte(MPR121_TOUCHTH_0 + 2 * i, 12);
this->write_byte(MPR121_RELEASETH_0 + 2 * i, 6);
for (auto *channel : this->channels_) {
this->write_byte(MPR121_TOUCHTH_0 + 2 * channel->channel_,
channel->touch_threshold_.value_or(this->touch_threshold_));
this->write_byte(MPR121_RELEASETH_0 + 2 * channel->channel_,
channel->release_threshold_.value_or(this->release_threshold_));
}
this->write_byte(MPR121_MHDR, 0x01);
this->write_byte(MPR121_NHDR, 0x01);
@@ -44,6 +46,19 @@ void MPR121Component::setup() {
// start with first 5 bits of baseline tracking
this->write_byte(MPR121_ECR, 0x8F);
}
void MPR121Component::set_touch_debounce(uint8_t debounce) {
uint8_t mask = debounce << 4;
this->debounce_ &= 0x0f;
this->debounce_ |= mask;
}
void MPR121Component::set_release_debounce(uint8_t debounce) {
uint8_t mask = debounce & 0x0f;
this->debounce_ &= 0xf0;
this->debounce_ |= mask;
};
void MPR121Component::dump_config() {
ESP_LOGCONFIG(TAG, "MPR121:");
LOG_I2C_DEVICE(this);

View File

@@ -46,17 +46,29 @@ enum {
};
class MPR121Channel : public binary_sensor::BinarySensor {
friend class MPR121Component;
public:
void set_channel(uint8_t channel) { channel_ = channel; }
void process(uint16_t data) { this->publish_state(static_cast<bool>(data & (1 << this->channel_))); }
void set_touch_threshold(uint8_t touch_threshold) { this->touch_threshold_ = touch_threshold; };
void set_release_threshold(uint8_t release_threshold) { this->release_threshold_ = release_threshold; };
protected:
uint8_t channel_{0};
optional<uint8_t> touch_threshold_{};
optional<uint8_t> release_threshold_{};
};
class MPR121Component : public Component, public i2c::I2CDevice {
public:
void register_channel(MPR121Channel *channel) { this->channels_.push_back(channel); }
void set_touch_debounce(uint8_t debounce);
void set_release_debounce(uint8_t debounce);
void set_touch_threshold(uint8_t touch_threshold) { this->touch_threshold_ = touch_threshold; };
void set_release_threshold(uint8_t release_threshold) { this->release_threshold_ = release_threshold; };
uint8_t get_touch_threshold() { return this->touch_threshold_; };
uint8_t get_release_threshold() { return this->release_threshold_; };
void setup() override;
void dump_config() override;
float get_setup_priority() const override { return setup_priority::DATA; }
@@ -64,6 +76,9 @@ class MPR121Component : public Component, public i2c::I2CDevice {
protected:
std::vector<MPR121Channel *> channels_{};
uint8_t debounce_{0};
uint8_t touch_threshold_{};
uint8_t release_threshold_{};
enum ErrorCode {
NONE = 0,
COMMUNICATION_FAILED,

View File

@@ -41,7 +41,8 @@ MQTTClientComponent = mqtt_ns.class_('MQTTClientComponent', cg.Component)
MQTTPublishAction = mqtt_ns.class_('MQTTPublishAction', automation.Action)
MQTTPublishJsonAction = mqtt_ns.class_('MQTTPublishJsonAction', automation.Action)
MQTTMessageTrigger = mqtt_ns.class_('MQTTMessageTrigger',
automation.Trigger.template(cg.std_string))
automation.Trigger.template(cg.std_string),
cg.Component)
MQTTJsonMessageTrigger = mqtt_ns.class_('MQTTJsonMessageTrigger',
automation.Trigger.template(cg.JsonObjectConstRef))
MQTTComponent = mqtt_ns.class_('MQTTComponent', cg.Component)
@@ -104,7 +105,7 @@ CONFIG_SCHEMA = cv.All(cv.Schema({
cv.Optional(CONF_PORT, default=1883): cv.port,
cv.Optional(CONF_USERNAME, default=''): cv.string,
cv.Optional(CONF_PASSWORD, default=''): cv.string,
cv.Optional(CONF_CLIENT_ID, default=lambda: CORE.name): cv.string,
cv.Optional(CONF_CLIENT_ID): cv.string,
cv.Optional(CONF_DISCOVERY, default=True): cv.Any(cv.boolean, cv.one_of("CLEAN", upper=True)),
cv.Optional(CONF_DISCOVERY_RETAIN, default=True): cv.boolean,
cv.Optional(CONF_DISCOVERY_PREFIX, default="homeassistant"): cv.publish_topic,
@@ -161,7 +162,8 @@ def to_code(config):
cg.add(var.set_broker_port(config[CONF_PORT]))
cg.add(var.set_username(config[CONF_USERNAME]))
cg.add(var.set_password(config[CONF_PASSWORD]))
cg.add(var.set_client_id(config[CONF_CLIENT_ID]))
if CONF_CLIENT_ID in config:
cg.add(var.set_client_id(config[CONF_CLIENT_ID]))
discovery = config[CONF_DISCOVERY]
discovery_retain = config[CONF_DISCOVERY_RETAIN]
@@ -216,6 +218,7 @@ def to_code(config):
cg.add(trig.set_qos(conf[CONF_QOS]))
if CONF_PAYLOAD in conf:
cg.add(trig.set_payload(conf[CONF_PAYLOAD]))
yield cg.register_component(trig, conf)
yield automation.build_automation(trig, [(cg.std_string, 'x')], conf)
for conf in config.get(CONF_ON_JSON_MESSAGE, []):

View File

@@ -0,0 +1,30 @@
#include "custom_mqtt_device.h"
#include "esphome/core/log.h"
namespace esphome {
namespace mqtt {
static const char *TAG = "mqtt.custom";
bool CustomMQTTDevice::publish(const std::string &topic, const std::string &payload, uint8_t qos, bool retain) {
return global_mqtt_client->publish(topic, payload, qos, retain);
}
bool CustomMQTTDevice::publish(const std::string &topic, float value, int8_t number_decimals) {
auto str = value_accuracy_to_string(value, number_decimals);
return this->publish(topic, str);
}
bool CustomMQTTDevice::publish(const std::string &topic, int value) {
char buffer[24];
sprintf(buffer, "%d", value);
return this->publish(topic, buffer);
}
bool CustomMQTTDevice::publish_json(const std::string &topic, const json::json_build_t &f, uint8_t qos, bool retain) {
return global_mqtt_client->publish_json(topic, f, qos, retain);
}
bool CustomMQTTDevice::publish_json(const std::string &topic, const json::json_build_t &f) {
return this->publish_json(topic, f, 0, false);
}
bool CustomMQTTDevice::is_connected() { return global_mqtt_client != nullptr && global_mqtt_client->is_connected(); }
} // namespace mqtt
} // namespace esphome

View File

@@ -0,0 +1,217 @@
#pragma once
#include "esphome/core/component.h"
#include "mqtt_client.h"
namespace esphome {
namespace mqtt {
/** This class is a helper class for custom components that communicate using
* MQTT. It has 5 helper functions that you can use (square brackets indicate optional):
*
* - `subscribe(topic, function_pointer, [qos])`
* - `subscribe_json(topic, function_pointer, [qos])`
* - `publish(topic, payload, [qos], [retain])`
* - `publish_json(topic, payload_builder, [qos], [retain])`
* - `is_connected()`
*/
class CustomMQTTDevice {
public:
/** Subscribe to an MQTT topic with the given Quality of Service.
*
* Example:
*
* ```cpp
* class MyCustomMQTTDevice : public Component, public mqtt:CustomMQTTDevice {
* public:
* void setup() override {
* subscribe("the/topic", &MyCustomMQTTDevice::on_message);
* pinMode(5, OUTPUT);
* }
*
* // topic and payload parameters can be removed if not needed
* // e.g: void on_message() {
*
* void on_message(const std::string &topic, const std::string &payload) {
* // do something with topic and payload
* if (payload == "ON") {
* digitalWrite(5, HIGH);
* } else {
* digitalWrite(5, LOW);
* }
* }
* };
* ```
*
* @tparam T A C++ template argument for determining the type of the callback.
* @param topic The topic to subscribe to. Re-subscription on re-connects is automatically handled.
* @param callback The callback (must be a class member) to subscribe with.
* @param qos The Quality of Service to subscribe with. Defaults to 0.
*/
template<typename T>
void subscribe(const std::string &topic, void (T::*callback)(const std::string &, const std::string &),
uint8_t qos = 0);
template<typename T>
void subscribe(const std::string &topic, void (T::*callback)(const std::string &), uint8_t qos = 0);
template<typename T> void subscribe(const std::string &topic, void (T::*callback)(), uint8_t qos = 0);
/** Subscribe to an MQTT topic and call the callback if the payload can be decoded
* as JSON with the given Quality of Service.
*
* Example:
*
* ```cpp
* class MyCustomMQTTDevice : public Component, public mqtt:CustomMQTTDevice {
* public:
* void setup() override {
* subscribe_json("the/topic", &MyCustomMQTTDevice::on_json_message);
* pinMode(5, OUTPUT);
* }
*
* // topic parameter can be remove if not needed:
* // e.g.: void on_json_message(JsonObject &payload) {
*
* void on_json_message(const std::string &topic, JsonObject &payload) {
* // do something with topic and payload
* if (payload["number"] == 1) {
* digitalWrite(5, HIGH);
* } else {
* digitalWrite(5, LOW);
* }
* }
* };
* ```
*
* @tparam T A C++ template argument for determining the type of the callback.
* @param topic The topic to subscribe to. Re-subscription on re-connects is automatically handled.
* @param callback The callback (must be a class member) to subscribe with.
* @param qos The Quality of Service to subscribe with. Defaults to 0.
*/
template<typename T>
void subscribe_json(const std::string &topic, void (T::*callback)(const std::string &, JsonObject &),
uint8_t qos = 0);
template<typename T>
void subscribe_json(const std::string &topic, void (T::*callback)(JsonObject &), uint8_t qos = 0);
/** Publish an MQTT message with the given payload and QoS and retain settings.
*
* Example:
*
* ```cpp
* void in_some_method() {
* publish("the/topic", "The Payload", 0, true);
* }
* ```
*
* @param topic The topic to publish to.
* @param payload The payload to publish.
* @param qos The Quality of Service to publish with. Defaults to 0
* @param retain Whether to retain the message. Defaults to false.
*/
bool publish(const std::string &topic, const std::string &payload, uint8_t qos = 0, bool retain = false);
/** Publish an MQTT message with the given floating point number and number of decimals.
*
* Example:
*
* ```cpp
* void in_some_method() {
* publish("the/topic", 1.0);
* // with two digits after the decimal point
* publish("the/topic", 1.0, 2);
* }
* ```
*
* @param topic The topic to publish to.
* @param payload The payload to publish.
* @param number_decimals The number of digits after the decimal point to round to, defaults to 3 digits.
*/
bool publish(const std::string &topic, float value, int8_t number_decimals = 3);
/** Publish an MQTT message with the given integer as payload.
*
* Example:
*
* ```cpp
* void in_some_method() {
* publish("the/topic", 42);
* }
* ```
*
* @param topic The topic to publish to.
* @param payload The payload to publish.
*/
bool publish(const std::string &topic, int value);
/** Publish a JSON-encoded MQTT message with the given Quality of Service and retain settings.
*
* Example:
*
* ```cpp
* void in_some_method() {
* publish("the/topic", [=](JsonObject &root) {
* root["the_key"] = "Hello World!";
* }, 0, false);
* }
* ```
*
* @param topic The topic to publish to.
* @param payload The payload to publish.
* @param qos The Quality of Service to publish with.
* @param retain Whether to retain the message.
*/
bool publish_json(const std::string &topic, const json::json_build_t &f, uint8_t qos, bool retain);
/** Publish a JSON-encoded MQTT message.
*
* Example:
*
* ```cpp
* void in_some_method() {
* publish("the/topic", [=](JsonObject &root) {
* root["the_key"] = "Hello World!";
* });
* }
* ```
*
* @param topic The topic to publish to.
* @param payload The payload to publish.
*/
bool publish_json(const std::string &topic, const json::json_build_t &f);
/// Check whether the MQTT client is currently connected and messages can be published.
bool is_connected();
};
template<typename T>
void CustomMQTTDevice::subscribe(const std::string &topic,
void (T::*callback)(const std::string &, const std::string &), uint8_t qos) {
auto f = std::bind(callback, (T *) this, std::placeholders::_1, std::placeholders::_2);
global_mqtt_client->subscribe(topic, f, qos);
}
template<typename T>
void CustomMQTTDevice::subscribe(const std::string &topic, void (T::*callback)(const std::string &), uint8_t qos) {
auto f = std::bind(callback, (T *) this, std::placeholders::_2);
global_mqtt_client->subscribe(topic, f, qos);
}
template<typename T> void CustomMQTTDevice::subscribe(const std::string &topic, void (T::*callback)(), uint8_t qos) {
auto f = std::bind(callback, (T *) this);
global_mqtt_client->subscribe(topic, f, qos);
}
template<typename T>
void CustomMQTTDevice::subscribe_json(const std::string &topic, void (T::*callback)(const std::string &, JsonObject &),
uint8_t qos) {
auto f = std::bind(callback, (T *) this, std::placeholders::_1, std::placeholders::_2);
global_mqtt_client->subscribe_json(topic, f, qos);
}
template<typename T>
void CustomMQTTDevice::subscribe_json(const std::string &topic, void (T::*callback)(JsonObject &), uint8_t qos) {
auto f = std::bind(callback, (T *) this, std::placeholders::_2);
global_mqtt_client->subscribe_json(topic, f, qos);
}
} // namespace mqtt
} // namespace esphome

View File

@@ -19,15 +19,19 @@ void MQTTBinarySensorComponent::dump_config() {
LOG_MQTT_COMPONENT(true, false)
}
MQTTBinarySensorComponent::MQTTBinarySensorComponent(binary_sensor::BinarySensor *binary_sensor)
: MQTTComponent(), binary_sensor_(binary_sensor) {}
: MQTTComponent(), binary_sensor_(binary_sensor) {
if (this->binary_sensor_->is_status_binary_sensor()) {
this->set_custom_state_topic(mqtt::global_mqtt_client->get_availability().topic);
}
}
std::string MQTTBinarySensorComponent::friendly_name() const { return this->binary_sensor_->get_name(); }
void MQTTBinarySensorComponent::send_discovery(JsonObject &root, mqtt::SendDiscoveryConfig &config) {
if (!this->binary_sensor_->get_device_class().empty())
root["device_class"] = this->binary_sensor_->get_device_class();
if (this->is_status_)
if (this->binary_sensor_->is_status_binary_sensor())
root["payload_on"] = mqtt::global_mqtt_client->get_availability().payload_available;
if (this->is_status_)
if (this->binary_sensor_->is_status_binary_sensor())
root["payload_off"] = mqtt::global_mqtt_client->get_availability().payload_not_available;
config.command_topic = false;
}
@@ -40,13 +44,12 @@ bool MQTTBinarySensorComponent::send_initial_state() {
}
bool MQTTBinarySensorComponent::is_internal() { return this->binary_sensor_->is_internal(); }
bool MQTTBinarySensorComponent::publish_state(bool state) {
if (this->is_status_)
if (this->binary_sensor_->is_status_binary_sensor())
return true;
const char *state_s = state ? "ON" : "OFF";
return this->publish(this->get_state_topic_(), state_s);
}
void MQTTBinarySensorComponent::set_is_status(bool status) { this->is_status_ = status; }
} // namespace mqtt
} // namespace esphome

View File

@@ -35,7 +35,6 @@ class MQTTBinarySensorComponent : public mqtt::MQTTComponent {
std::string component_type() const override;
binary_sensor::BinarySensor *binary_sensor_;
bool is_status_{false};
};
} // namespace mqtt

View File

@@ -15,7 +15,10 @@ namespace mqtt {
static const char *TAG = "mqtt";
MQTTClientComponent::MQTTClientComponent() { global_mqtt_client = this; }
MQTTClientComponent::MQTTClientComponent() {
global_mqtt_client = this;
this->credentials_.client_id = App.get_name() + "-" + get_mac_address();
}
// Connection
void MQTTClientComponent::setup() {
@@ -357,18 +360,19 @@ bool MQTTClientComponent::publish(const std::string &topic, const char *payload,
}
bool logging_topic = topic == this->log_message_.topic;
uint16_t ret = this->mqtt_client_.publish(topic.c_str(), qos, retain, payload, payload_length);
yield();
delay(0);
if (ret == 0 && !logging_topic && this->is_connected()) {
delay(5);
delay(0);
ret = this->mqtt_client_.publish(topic.c_str(), qos, retain, payload, payload_length);
yield();
delay(0);
}
if (!logging_topic) {
if (ret != 0) {
ESP_LOGV(TAG, "Publish(topic='%s' payload='%s' retain=%d)", topic.c_str(), payload, retain);
} else {
ESP_LOGW(TAG, "Publish failed for topic='%s' will retry later..", topic.c_str());
ESP_LOGV(TAG, "Publish failed for topic='%s' (len=%u). will retry later..", topic.c_str(),
payload_length); // NOLINT
this->status_momentary_warning("publish", 1000);
}
}

View File

@@ -2,6 +2,7 @@
#include "esphome/core/log.h"
#include "esphome/core/application.h"
#include "esphome/core/helpers.h"
#include "esphome/core/version.h"
namespace esphome {
namespace mqtt {

View File

@@ -7,7 +7,7 @@ from esphome.const import CONF_CLOCK_PIN, CONF_DATA_PIN, CONF_METHOD, CONF_NUM_L
from esphome.core import CORE
neopixelbus_ns = cg.esphome_ns.namespace('neopixelbus')
NeoPixelBusLightOutputBase = neopixelbus_ns.class_('NeoPixelBusLightOutputBase', cg.Component,
NeoPixelBusLightOutputBase = neopixelbus_ns.class_('NeoPixelBusLightOutputBase',
light.AddressableLight)
NeoPixelRGBLightOutput = neopixelbus_ns.class_('NeoPixelRGBLightOutput', NeoPixelBusLightOutputBase)
NeoPixelRGBWLightOutput = neopixelbus_ns.class_('NeoPixelRGBWLightOutput',

View File

@@ -48,7 +48,7 @@ enum class ESPNeoPixelOrder {
};
template<typename T_METHOD, typename T_COLOR_FEATURE>
class NeoPixelBusLightOutputBase : public Component, public light::AddressableLight {
class NeoPixelBusLightOutputBase : public light::AddressableLight {
public:
NeoPixelBus<T_COLOR_FEATURE, T_METHOD> *get_controller() const { return this->controller_; }

View File

View File

@@ -0,0 +1,31 @@
#include "ntc.h"
#include "esphome/core/log.h"
namespace esphome {
namespace ntc {
static const char *TAG = "ntc";
void NTC::setup() {
this->sensor_->add_on_state_callback([this](float value) { this->process_(value); });
if (this->sensor_->has_state())
this->process_(this->sensor_->state);
}
void NTC::dump_config() { LOG_SENSOR("", "NTC Sensor", this) }
float NTC::get_setup_priority() const { return setup_priority::DATA; }
void NTC::process_(float value) {
if (isnan(value)) {
this->publish_state(NAN);
return;
}
float lr = logf(value);
float v = this->a_ + this->b_ * lr + this->c_ * lr * lr * lr;
float temp = 1 / v - 273.15f;
ESP_LOGD(TAG, "'%s' - Temperature: %.1f°C", this->name_.c_str(), temp);
this->publish_state(temp);
}
} // namespace ntc
} // namespace esphome

View File

@@ -0,0 +1,29 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/sensor/sensor.h"
namespace esphome {
namespace ntc {
class NTC : public Component, public sensor::Sensor {
public:
void set_sensor(Sensor *sensor) { sensor_ = sensor; }
void set_a(float a) { a_ = a; }
void set_b(float b) { b_ = b; }
void set_c(float c) { c_ = c; }
void setup() override;
void dump_config() override;
float get_setup_priority() const override;
protected:
void process_(float value);
sensor::Sensor *sensor_;
float a_;
float b_;
float c_;
};
} // namespace ntc
} // namespace esphome

View File

@@ -0,0 +1,120 @@
# coding=utf-8
from math import log
import esphome.config_validation as cv
import esphome.codegen as cg
from esphome.components import sensor
from esphome.const import UNIT_CELSIUS, ICON_THERMOMETER, CONF_SENSOR, CONF_TEMPERATURE, \
CONF_VALUE, CONF_CALIBRATION, CONF_ID
ntc_ns = cg.esphome_ns.namespace('ntc')
NTC = ntc_ns.class_('NTC', cg.Component, sensor.Sensor)
CONF_B_CONSTANT = 'b_constant'
CONF_REFERENCE_TEMPERATURE = 'reference_temperature'
CONF_REFERENCE_RESISTANCE = 'reference_resistance'
CONF_A = 'a'
CONF_B = 'b'
CONF_C = 'c'
ZERO_POINT = 273.15
def validate_calibration_parameter(value):
if isinstance(value, dict):
return cv.Schema({
cv.Required(CONF_TEMPERATURE): cv.float_,
cv.Required(CONF_VALUE): cv.float_,
})(value)
value = cv.string(value)
parts = value.split('->')
if len(parts) != 2:
raise cv.Invalid(u"Calibration parameter must be of form 3000 -> 23°C")
voltage = cv.resistance(parts[0].strip())
temperature = cv.temperature(parts[1].strip())
return validate_calibration_parameter({
CONF_TEMPERATURE: temperature,
CONF_VALUE: voltage,
})
def calc_steinhart_hart(value):
r1 = value[0][CONF_VALUE]
r2 = value[1][CONF_VALUE]
r3 = value[2][CONF_VALUE]
t1 = value[0][CONF_TEMPERATURE] + ZERO_POINT
t2 = value[1][CONF_TEMPERATURE] + ZERO_POINT
t3 = value[2][CONF_TEMPERATURE] + ZERO_POINT
l1 = log(r1)
l2 = log(r2)
l3 = log(r3)
y1 = 1/t1
y2 = 1/t2
y3 = 1/t3
g2 = (y2-y1)/(l2-l1)
g3 = (y3-y1)/(l3-l1)
c = (g3-g2)/(l3-l2) * 1/(l1+l2+l3)
b = g2 - c*(l1*l1 + l1*l2 + l2*l2)
a = y1 - (b + l1*l1*c) * l1
return a, b, c
def calc_b(value):
beta = value[CONF_B_CONSTANT]
t0 = value[CONF_REFERENCE_TEMPERATURE] + ZERO_POINT
r0 = value[CONF_REFERENCE_RESISTANCE]
a = (1/t0) - (1/beta) * log(r0)
b = 1/beta
c = 0
return a, b, c
def process_calibration(value):
if isinstance(value, dict):
value = cv.Schema({
cv.Required(CONF_B_CONSTANT): cv.float_,
cv.Required(CONF_REFERENCE_TEMPERATURE): cv.temperature,
cv.Required(CONF_REFERENCE_RESISTANCE): cv.resistance,
})(value)
a, b, c = calc_b(value)
elif isinstance(value, list):
if len(value) != 3:
raise cv.Invalid("SteinhartHart Calibration must consist of exactly three values")
value = cv.Schema([validate_calibration_parameter])(value)
a, b, c = calc_steinhart_hart(value)
else:
raise cv.Invalid("Calibration parameter accepts either a list for steinhart-hart "
"calibration, or mapping for b-constant calibration, "
"not {}".format(type(value)))
return {
CONF_A: a,
CONF_B: b,
CONF_C: c,
}
CONFIG_SCHEMA = sensor.sensor_schema(UNIT_CELSIUS, ICON_THERMOMETER, 1).extend({
cv.GenerateID(): cv.declare_id(NTC),
cv.Required(CONF_SENSOR): cv.use_id(sensor.Sensor),
cv.Required(CONF_CALIBRATION): process_calibration,
}).extend(cv.COMPONENT_SCHEMA)
def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
yield cg.register_component(var, config)
yield sensor.register_sensor(var, config)
sens = yield cg.get_variable(config[CONF_SENSOR])
cg.add(var.set_sensor(sens))
calib = config[CONF_CALIBRATION]
cg.add(var.set_a(calib[CONF_A]))
cg.add(var.set_b(calib[CONF_B]))
cg.add(var.set_c(calib[CONF_C]))

View File

@@ -33,4 +33,5 @@ def to_code(config):
conf[CONF_TO] - conf[CONF_FROM] + 1))
var = cg.new_Pvariable(config[CONF_OUTPUT_ID], segments)
yield cg.register_component(var, config)
yield light.register_light(var, config)

View File

@@ -24,7 +24,7 @@ class AddressableSegment {
int32_t dst_offset_;
};
class PartitionLightOutput : public light::AddressableLight, public Component {
class PartitionLightOutput : public light::AddressableLight {
public:
explicit PartitionLightOutput(std::vector<AddressableSegment> segments) : segments_(segments) {
int32_t off = 0;

View File

@@ -2,7 +2,7 @@ import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import automation
from esphome.components import binary_sensor
from esphome.const import CONF_DATA, CONF_ID, CONF_TRIGGER_ID, CONF_NBITS, CONF_ADDRESS, \
from esphome.const import CONF_DATA, CONF_TRIGGER_ID, CONF_NBITS, CONF_ADDRESS, \
CONF_COMMAND, CONF_CODE, CONF_PULSE_LENGTH, CONF_SYNC, CONF_ZERO, CONF_ONE, CONF_INVERTED, \
CONF_PROTOCOL, CONF_GROUP, CONF_DEVICE, CONF_STATE, CONF_CHANNEL, CONF_FAMILY, CONF_REPEAT, \
CONF_WAIT_TIME, CONF_TIMES, CONF_TYPE_ID, CONF_CARRIER_FREQUENCY
@@ -83,14 +83,20 @@ def register_dumper(name, type):
return decorator
def register_action(name, type_, schema):
validator = templatize(schema).extend({
cv.GenerateID(CONF_TRANSMITTER_ID): cv.use_id(RemoteTransmitterBase),
cv.Optional(CONF_REPEAT): cv.Schema({
def validate_repeat(value):
if isinstance(value, dict):
return cv.Schema({
cv.Required(CONF_TIMES): cv.templatable(cv.positive_int),
cv.Optional(CONF_WAIT_TIME, default='10ms'):
cv.templatable(cv.positive_time_period_milliseconds),
}),
})(value)
return validate_repeat({CONF_TIMES: value})
def register_action(name, type_, schema):
validator = templatize(schema).extend({
cv.GenerateID(CONF_TRANSMITTER_ID): cv.use_id(RemoteTransmitterBase),
cv.Optional(CONF_REPEAT): validate_repeat,
})
registerer = automation.register_action('remote_transmitter.transmit_{}'.format(name),
type_, validator)
@@ -344,7 +350,7 @@ RAW_SCHEMA = cv.Schema({
@register_binary_sensor('raw', RawBinarySensor, RAW_SCHEMA)
def raw_binary_sensor(var, config):
code_ = config[CONF_CODE]
arr = cg.progmem_array(config[CONF_ID], code_)
arr = cg.progmem_array(config[CONF_CODE_STORAGE_ID], code_)
cg.add(var.set_data(arr))
cg.add(var.set_len(len(code_)))

View File

@@ -232,7 +232,7 @@ bool RCSwitchDumper::dump(RemoteReceiveData src) {
uint8_t out_nbits;
RCSwitchBase *protocol = &rc_switch_protocols[i];
if (protocol->decode(src, &out_data, &out_nbits) && out_nbits >= 3) {
char buffer[32];
char buffer[33];
for (uint8_t j = 0; j < out_nbits; j++)
buffer[j] = (out_data & (1 << (out_nbits - j - 1))) ? '1' : '0';

View File

@@ -293,7 +293,7 @@ template<typename T, typename D> class RemoteReceiverBinarySensor : public Remot
bool matches(RemoteReceiveData src) override {
auto proto = T();
auto res = proto.decode(src);
return res.has_value();
return res.has_value() && *res == this->data_;
}
public:

View File

@@ -31,7 +31,7 @@ optional<SonyData> SonyProtocol::decode(RemoteReceiveData src) {
.nbits = 0,
};
if (!src.expect_item(HEADER_HIGH_US, HEADER_LOW_US))
return out;
return {};
for (; out.nbits < 20; out.nbits++) {
uint32_t bit;

View File

@@ -0,0 +1,42 @@
#include "resistance_sensor.h"
#include "esphome/core/log.h"
namespace esphome {
namespace resistance {
static const char *TAG = "resistance";
void ResistanceSensor::dump_config() {
LOG_SENSOR("", "Resistance Sensor", this);
ESP_LOGCONFIG(TAG, " Configuration: %s", this->configuration_ == UPSTREAM ? "UPSTREAM" : "DOWNSTREAM");
ESP_LOGCONFIG(TAG, " Resistor: %.2fΩ", this->resistor_);
ESP_LOGCONFIG(TAG, " Reference Voltage: %.1fV", this->reference_voltage_);
}
void ResistanceSensor::process_(float value) {
if (isnan(value)) {
this->publish_state(NAN);
return;
}
float res = 0;
switch (this->configuration_) {
case UPSTREAM:
if (value == 0.0f)
res = NAN;
else
res = (this->reference_voltage_ - value) / value;
break;
case DOWNSTREAM:
if (value == this->reference_voltage_)
res = NAN;
else
res = value / (this->reference_voltage_ - value);
break;
}
res *= this->resistor_;
ESP_LOGD(TAG, "'%s' - Resistance %.1fΩ", this->name_.c_str(), res);
this->publish_state(res);
}
} // namespace resistance
} // namespace esphome

View File

@@ -0,0 +1,38 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/sensor/sensor.h"
namespace esphome {
namespace resistance {
enum ResistanceConfiguration {
UPSTREAM,
DOWNSTREAM,
};
class ResistanceSensor : public Component, public sensor::Sensor {
public:
void set_sensor(Sensor *sensor) { sensor_ = sensor; }
void set_configuration(ResistanceConfiguration configuration) { configuration_ = configuration; }
void set_resistor(float resistor) { resistor_ = resistor; }
void set_reference_voltage(float reference_voltage) { reference_voltage_ = reference_voltage; }
void setup() override {
this->sensor_->add_on_state_callback([this](float value) { this->process_(value); });
if (this->sensor_->has_state())
this->process_(this->sensor_->state);
}
void dump_config() override;
float get_setup_priority() const override { return setup_priority::DATA; }
protected:
void process_(float value);
sensor::Sensor *sensor_;
ResistanceConfiguration configuration_;
float resistor_;
float reference_voltage_;
};
} // namespace resistance
} // namespace esphome

View File

@@ -0,0 +1,37 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import sensor
from esphome.const import CONF_SENSOR, UNIT_OHM, ICON_FLASH, CONF_ID
resistance_ns = cg.esphome_ns.namespace('resistance')
ResistanceSensor = resistance_ns.class_('ResistanceSensor', cg.Component, sensor.Sensor)
CONF_REFERENCE_VOLTAGE = 'reference_voltage'
CONF_CONFIGURATION = 'configuration'
CONF_RESISTOR = 'resistor'
ResistanceConfiguration = resistance_ns.enum('ResistanceConfiguration')
CONFIGURATIONS = {
'DOWNSTREAM': ResistanceConfiguration.DOWNSTREAM,
'UPSTREAM': ResistanceConfiguration.UPSTREAM,
}
CONFIG_SCHEMA = sensor.sensor_schema(UNIT_OHM, ICON_FLASH, 1).extend({
cv.GenerateID(): cv.declare_id(ResistanceSensor),
cv.Required(CONF_SENSOR): cv.use_id(sensor.Sensor),
cv.Required(CONF_CONFIGURATION): cv.enum(CONFIGURATIONS, upper=True),
cv.Required(CONF_RESISTOR): cv.resistance,
cv.Optional(CONF_REFERENCE_VOLTAGE, default='3.3V'): cv.voltage,
}).extend(cv.COMPONENT_SCHEMA)
def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
yield cg.register_component(var, config)
yield sensor.register_sensor(var, config)
sens = yield cg.get_variable(config[CONF_SENSOR])
cg.add(var.set_sensor(sens))
cg.add(var.set_configuration(config[CONF_CONFIGURATION]))
cg.add(var.set_resistor(config[CONF_RESISTOR]))
cg.add(var.set_reference_voltage(config[CONF_REFERENCE_VOLTAGE]))

View File

@@ -37,4 +37,4 @@ def to_code(config):
wwhite = yield cg.get_variable(config[CONF_WARM_WHITE])
cg.add(var.set_warm_white(wwhite))
cg.add(var.set_warm_white_temperature(config[CONF_COLD_WHITE_COLOR_TEMPERATURE]))
cg.add(var.set_warm_white_temperature(config[CONF_WARM_WHITE_COLOR_TEMPERATURE]))

View File

@@ -22,6 +22,8 @@ class RGBWWLightOutput : public light::LightOutput {
traits.set_supports_rgb(true);
traits.set_supports_rgb_white_value(true);
traits.set_supports_color_temperature(true);
traits.set_min_mireds(this->cold_white_temperature_);
traits.set_max_mireds(this->warm_white_temperature_);
return traits;
}
void write_state(light::LightState *state) override {

View File

@@ -101,15 +101,15 @@ void RotaryEncoderSensor::setup() {
ESP_LOGCONFIG(TAG, "Setting up Rotary Encoder '%s'...", this->name_.c_str());
this->pin_a_->setup();
this->store_.pin_a = this->pin_a_->to_isr();
this->pin_a_->attach_interrupt(RotaryEncoderSensorStore::gpio_intr, &this->store_, CHANGE);
this->pin_b_->setup();
this->store_.pin_b = this->pin_b_->to_isr();
this->pin_b_->attach_interrupt(RotaryEncoderSensorStore::gpio_intr, &this->store_, CHANGE);
if (this->pin_i_ != nullptr) {
this->pin_i_->setup();
}
this->pin_a_->attach_interrupt(RotaryEncoderSensorStore::gpio_intr, &this->store_, CHANGE);
this->pin_b_->attach_interrupt(RotaryEncoderSensorStore::gpio_intr, &this->store_, CHANGE);
}
void RotaryEncoderSensor::dump_config() {
LOG_SENSOR("", "Rotary Encoder", this);

View File

@@ -36,7 +36,7 @@ CONFIG_SCHEMA = cv.All(sensor.sensor_schema(UNIT_STEPS, ICON_ROTATE_RIGHT, 0).ex
pins.validate_has_interrupt),
cv.Required(CONF_PIN_B): cv.All(pins.internal_gpio_input_pin_schema,
pins.validate_has_interrupt),
cv.Optional(CONF_PIN_RESET): pins.internal_gpio_input_pin_schema,
cv.Optional(CONF_PIN_RESET): pins.internal_gpio_output_pin_schema,
cv.Optional(CONF_RESOLUTION, default=1): cv.enum(RESOLUTIONS, int=True),
cv.Optional(CONF_MIN_VALUE): cv.int_,
cv.Optional(CONF_MAX_VALUE): cv.int_,
@@ -50,7 +50,7 @@ def to_code(config):
pin_a = yield cg.gpio_pin_expression(config[CONF_PIN_A])
cg.add(var.set_pin_a(pin_a))
pin_b = yield cg.gpio_pin_expression(config[CONF_PIN_B])
cg.add(var.set_pin_a(pin_b))
cg.add(var.set_pin_b(pin_b))
if CONF_PIN_RESET in config:
pin_i = yield cg.gpio_pin_expression(config[CONF_PIN_RESET])

View File

@@ -16,8 +16,13 @@ CONFIG_SCHEMA = automation.validate_automation({
def to_code(config):
# Register all variables first, so that scripts can use other scripts
triggers = []
for conf in config:
trigger = cg.new_Pvariable(conf[CONF_ID])
triggers.append((trigger, conf))
for trigger, conf in triggers:
yield automation.build_automation(trigger, [], conf)

View File

@@ -17,6 +17,10 @@ CONF_ELEVATION = 'elevation'
CONF_ON_SUNRISE = 'on_sunrise'
CONF_ON_SUNSET = 'on_sunset'
# Default sun elevation is a bit below horizon because sunset
# means time when the entire sun disk is below the horizon
DEFAULT_ELEVATION = -0.883
ELEVATION_MAP = {
'sunrise': 0.0,
'sunset': 0.0,
@@ -44,11 +48,11 @@ CONFIG_SCHEMA = cv.Schema({
cv.Optional(CONF_ON_SUNRISE): automation.validate_automation({
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(SunTrigger),
cv.Optional(CONF_ELEVATION, default=0.0): elevation,
cv.Optional(CONF_ELEVATION, default=DEFAULT_ELEVATION): elevation,
}),
cv.Optional(CONF_ON_SUNSET): automation.validate_automation({
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(SunTrigger),
cv.Optional(CONF_ELEVATION, default=0.0): elevation,
cv.Optional(CONF_ELEVATION, default=DEFAULT_ELEVATION): elevation,
}),
})
@@ -79,7 +83,7 @@ def to_code(config):
@automation.register_condition('sun.is_above_horizon', SunCondition, cv.Schema({
cv.GenerateID(): cv.use_id(Sun),
cv.Optional(CONF_ELEVATION, default=0): cv.templatable(elevation),
cv.Optional(CONF_ELEVATION, default=DEFAULT_ELEVATION): cv.templatable(elevation),
}))
def sun_above_horizon_to_code(config, condition_id, template_arg, args):
var = cg.new_Pvariable(condition_id, template_arg)
@@ -92,7 +96,7 @@ def sun_above_horizon_to_code(config, condition_id, template_arg, args):
@automation.register_condition('sun.is_below_horizon', SunCondition, cv.Schema({
cv.GenerateID(): cv.use_id(Sun),
cv.Optional(CONF_ELEVATION, default=0): cv.templatable(elevation),
cv.Optional(CONF_ELEVATION, default=DEFAULT_ELEVATION): cv.templatable(elevation),
}))
def sun_below_horizon_to_code(config, condition_id, template_arg, args):
var = cg.new_Pvariable(condition_id, template_arg)

View File

@@ -103,7 +103,7 @@ class SunTrigger : public Trigger<>, public PollingComponent, public Parented<Su
crossed = this->last_elevation_ >= this->elevation_ && this->elevation_ > current;
}
if (crossed) {
if (crossed && !isnan(this->last_elevation_)) {
this->trigger();
}
this->last_elevation_ = current;
@@ -111,7 +111,7 @@ class SunTrigger : public Trigger<>, public PollingComponent, public Parented<Su
protected:
bool sunrise_;
double last_elevation_;
double last_elevation_{NAN};
double elevation_;
};

View File

@@ -3,7 +3,7 @@ import esphome.config_validation as cv
import esphome.codegen as cg
from esphome.const import CONF_ICON, ICON_WEATHER_SUNSET_DOWN, ICON_WEATHER_SUNSET_UP, CONF_TYPE, \
CONF_ID, CONF_FORMAT
from .. import sun_ns, CONF_SUN_ID, Sun, CONF_ELEVATION, elevation
from .. import sun_ns, CONF_SUN_ID, Sun, CONF_ELEVATION, elevation, DEFAULT_ELEVATION
DEPENDENCIES = ['sun']
@@ -28,7 +28,7 @@ CONFIG_SCHEMA = cv.All(text_sensor.TEXT_SENSOR_SCHEMA.extend({
cv.GenerateID(): cv.declare_id(SunTextSensor),
cv.GenerateID(CONF_SUN_ID): cv.use_id(Sun),
cv.Required(CONF_TYPE): cv.one_of(*SUN_TYPES, lower=True),
cv.Optional(CONF_ELEVATION, default=0): elevation,
cv.Optional(CONF_ELEVATION, default=DEFAULT_ELEVATION): elevation,
cv.Optional(CONF_FORMAT, default='%X'): cv.string_strict,
}).extend(cv.polling_component_schema('60s')), validate_optional_icon)

View File

@@ -74,19 +74,12 @@ void TemplateCover::control(const CoverCall &call) {
this->stop_prev_trigger_();
this->stop_trigger_->trigger();
this->prev_command_trigger_ = this->stop_trigger_;
this->current_operation = COVER_OPERATION_IDLE;
this->publish_state();
}
if (call.get_position().has_value()) {
auto pos = *call.get_position();
this->stop_prev_trigger_();
if (pos < this->position) {
this->current_operation = COVER_OPERATION_CLOSING;
} else if (pos > this->position) {
this->current_operation = COVER_OPERATION_OPENING;
}
if (pos == COVER_OPEN) {
this->open_trigger_->trigger();
this->prev_command_trigger_ = this->open_trigger_;

View File

@@ -52,6 +52,15 @@ def _tz_dst_str(dt):
_tz_timedelta(td))
def _non_dst_tz(tz, dt):
tzname = tz.tzname(dt)
utcoffset = tz.utcoffset(dt)
_LOGGER.info("Detected timezone '%s' with UTC offset %s",
tzname, _tz_timedelta(utcoffset))
tzbase = '{}{}'.format(tzname, _tz_timedelta(-1 * utcoffset))
return tzbase
def convert_tz(pytz_obj):
tz = pytz_obj
@@ -59,23 +68,29 @@ def convert_tz(pytz_obj):
first_january = datetime.datetime(year=now.year, month=1, day=1)
if not isinstance(tz, pytz.tzinfo.DstTzInfo):
tzname = tz.tzname(first_january)
utcoffset = tz.utcoffset(first_january)
_LOGGER.info("Detected timezone '%s' with UTC offset %s",
tzname, _tz_timedelta(utcoffset))
tzbase = '{}{}'.format(tzname, _tz_timedelta(-1 * utcoffset))
return tzbase
return _non_dst_tz(tz, first_january)
# pylint: disable=protected-access
transition_times = tz._utc_transition_times
transition_info = tz._transition_info
idx = max(0, bisect.bisect_right(transition_times, now))
if idx >= len(transition_times):
return _non_dst_tz(tz, now)
idx1, idx2 = idx, idx + 1
dstoffset1 = transition_info[idx1][1]
if dstoffset1 == datetime.timedelta(seconds=0):
# Normalize to 1 being DST on
idx1, idx2 = idx + 1, idx + 2
if idx2 >= len(transition_times):
return _non_dst_tz(tz, now)
if transition_times[idx2].year > now.year + 1:
# Next transition is scheduled after this year
# Probably a scheduler timezone change.
return _non_dst_tz(tz, now)
utcoffset_on, _, tzname_on = transition_info[idx1]
utcoffset_off, _, tzname_off = transition_info[idx2]
dst_begins_utc = transition_times[idx1]
@@ -244,10 +259,12 @@ def validate_tz(value):
value = cv.string_strict(value)
try:
return convert_tz(pytz.timezone(value))
except Exception: # pylint: disable=broad-except
pytz_obj = pytz.timezone(value)
except pytz.UnknownTimeZoneError: # pylint: disable=broad-except
return value
return convert_tz(pytz_obj)
TIME_SCHEMA = cv.Schema({
cv.Optional(CONF_TIMEZONE, default=detect_tz): validate_tz,

View File

@@ -32,7 +32,7 @@ TSL2561Sensor = tsl2561_ns.class_('TSL2561Sensor', sensor.Sensor, cg.PollingComp
CONFIG_SCHEMA = sensor.sensor_schema(UNIT_LUX, ICON_BRIGHTNESS_5, 1).extend({
cv.GenerateID(): cv.declare_id(TSL2561Sensor),
cv.Optional(CONF_INTEGRATION_TIME, default=402): validate_integration_time,
cv.Optional(CONF_INTEGRATION_TIME, default='402ms'): validate_integration_time,
cv.Optional(CONF_GAIN, default='1X'): cv.enum(GAINS, upper=True),
cv.Optional(CONF_IS_CS_PACKAGE, default=False): cv.boolean,
}).extend(cv.polling_component_schema('60s')).extend(i2c.i2c_device_schema(0x39))

View File

@@ -1,15 +1,27 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins
from esphome.const import CONF_BAUD_RATE, CONF_ID, CONF_RX_PIN, CONF_TX_PIN, CONF_UART_ID
from esphome import pins, automation
from esphome.const import CONF_BAUD_RATE, CONF_ID, CONF_RX_PIN, CONF_TX_PIN, CONF_UART_ID, CONF_DATA
from esphome.core import CORE, coroutine
from esphome.py_compat import text_type, binary_type, char_to_byte
uart_ns = cg.esphome_ns.namespace('uart')
UARTComponent = uart_ns.class_('UARTComponent', cg.Component)
UARTDevice = uart_ns.class_('UARTDevice')
UARTWriteAction = uart_ns.class_('UARTWriteAction', automation.Action)
MULTI_CONF = True
def validate_raw_data(value):
if isinstance(value, text_type):
return value.encode('utf-8')
if isinstance(value, str):
return value
if isinstance(value, list):
return cv.Schema([cv.hex_uint8_t])(value)
raise cv.Invalid("data must either be a string wrapped in quotes or a list of bytes")
def validate_rx_pin(value):
value = pins.input_pin(value)
if CORE.is_esp8266 and value >= 16:
@@ -51,3 +63,22 @@ def register_uart_device(var, config):
"""
parent = yield cg.get_variable(config[CONF_UART_ID])
cg.add(var.set_uart_parent(parent))
@automation.register_action('uart.write', UARTWriteAction, cv.maybe_simple_value({
cv.GenerateID(): cv.use_id(UARTComponent),
cv.Required(CONF_DATA): cv.templatable(validate_raw_data),
}, key=CONF_DATA))
def uart_write_to_code(config, action_id, template_arg, args):
var = cg.new_Pvariable(action_id, template_arg)
yield cg.register_parented(var, config[CONF_ID])
data = config[CONF_DATA]
if isinstance(data, binary_type):
data = [char_to_byte(x) for x in data]
if cg.is_template(data):
templ = yield cg.templatable(data, args, cg.std_vector.template(cg.uint8))
cg.add(var.set_data_template(templ))
else:
cg.add(var.set_data_static(data))
yield var

View File

@@ -0,0 +1,36 @@
#pragma once
#include "uart.h"
#include "esphome/core/automation.h"
namespace esphome {
namespace uart {
template<typename... Ts> class UARTWriteAction : public Action<Ts...>, public Parented<UARTComponent> {
public:
void set_data_template(std::function<std::vector<uint8_t>(Ts...)> func) {
this->data_func_ = func;
this->static_ = false;
}
void set_data_static(const std::vector<uint8_t> &data) {
this->data_static_ = data;
this->static_ = true;
}
void play(Ts... x) override {
if (this->static_) {
this->parent_->write_array(this->data_static_);
} else {
auto val = this->data_func_(x...);
this->parent_->write_array(val);
}
}
protected:
bool static_{false};
std::function<std::vector<uint8_t>(Ts...)> data_func_{};
std::vector<uint8_t> data_static_{};
};
} // namespace uart
} // namespace esphome

View File

@@ -3,27 +3,17 @@ import esphome.config_validation as cv
from esphome.components import switch, uart
from esphome.const import CONF_DATA, CONF_ID, CONF_INVERTED
from esphome.core import HexInt
from esphome.py_compat import text_type, binary_type, char_to_byte
from .. import uart_ns
from esphome.py_compat import binary_type, char_to_byte
from .. import uart_ns, validate_raw_data
DEPENDENCIES = ['uart']
UARTSwitch = uart_ns.class_('UARTSwitch', switch.Switch, uart.UARTDevice, cg.Component)
def validate_data(value):
if isinstance(value, text_type):
return value.encode('utf-8')
if isinstance(value, str):
return value
if isinstance(value, list):
return cv.Schema([cv.hex_uint8_t])(value)
raise cv.Invalid("data must either be a string wrapped in quotes or a list of bytes")
CONFIG_SCHEMA = switch.SWITCH_SCHEMA.extend({
cv.GenerateID(): cv.declare_id(UARTSwitch),
cv.Required(CONF_DATA): validate_data,
cv.Required(CONF_DATA): validate_raw_data,
cv.Optional(CONF_INVERTED): cv.invalid("UART switches do not support inverted mode!"),
}).extend(uart.UART_DEVICE_SCHEMA).extend(cv.COMPONENT_SCHEMA)

View File

@@ -49,6 +49,7 @@ class UARTComponent : public Component, public Stream {
void write_byte(uint8_t data);
void write_array(const uint8_t *data, size_t len);
void write_array(const std::vector<uint8_t> &data) { this->write_array(&data[0], data.size()); }
void write_str(const char *str);
@@ -97,6 +98,7 @@ class UARTDevice : public Stream {
void write_byte(uint8_t data) { this->parent_->write_byte(data); }
void write_array(const uint8_t *data, size_t len) { this->parent_->write_array(data, len); }
void write_array(const std::vector<uint8_t> &data) { this->parent_->write_array(data); }
void write_str(const char *str) { this->parent_->write_str(str); }

View File

@@ -1,6 +1,7 @@
#include "version_text_sensor.h"
#include "esphome/core/log.h"
#include "esphome/core/application.h"
#include "esphome/core/version.h"
namespace esphome {
namespace version {

View File

@@ -24,7 +24,7 @@ MODELS = {
'2.90in': ('a', WaveshareEPaperTypeAModel.WAVESHARE_EPAPER_2_9_IN),
'2.70in': ('b', WaveshareEPaper2P7In),
'4.20in': ('b', WaveshareEPaper4P2In),
'7.50in': ('b', WaveshareEPaperTypeBModel),
'7.50in': ('b', WaveshareEPaper7P5In),
}

View File

@@ -8,29 +8,6 @@ namespace waveshare_epaper {
static const char *TAG = "waveshare_epaper";
static const uint8_t WAVESHARE_EPAPER_COMMAND_DRIVER_OUTPUT_CONTROL = 0x01;
static const uint8_t WAVESHARE_EPAPER_COMMAND_BOOSTER_SOFT_START_CONTROL = 0x0C;
// static const uint8_t WAVESHARE_EPAPER_COMMAND_GATE_SCAN_START_POSITION = 0x0F;
// static const uint8_t WAVESHARE_EPAPER_COMMAND_DEEP_SLEEP_MODE = 0x10;
static const uint8_t WAVESHARE_EPAPER_COMMAND_DATA_ENTRY_MODE_SETTING = 0x11;
// static const uint8_t WAVESHARE_EPAPER_COMMAND_SW_RESET = 0x12;
// static const uint8_t WAVESHARE_EPAPER_COMMAND_TEMPERATURE_SENSOR_CONTROL = 0x1A;
static const uint8_t WAVESHARE_EPAPER_COMMAND_MASTER_ACTIVATION = 0x20;
// static const uint8_t WAVESHARE_EPAPER_COMMAND_DISPLAY_UPDATE_CONTROL_1 = 0x21;
static const uint8_t WAVESHARE_EPAPER_COMMAND_DISPLAY_UPDATE_CONTROL_2 = 0x22;
static const uint8_t WAVESHARE_EPAPER_COMMAND_WRITE_RAM = 0x24;
static const uint8_t WAVESHARE_EPAPER_COMMAND_WRITE_VCOM_REGISTER = 0x2C;
static const uint8_t WAVESHARE_EPAPER_COMMAND_WRITE_LUT_REGISTER = 0x32;
static const uint8_t WAVESHARE_EPAPER_COMMAND_SET_DUMMY_LINE_PERIOD = 0x3A;
static const uint8_t WAVESHARE_EPAPER_COMMAND_SET_GATE_TIME = 0x3B;
static const uint8_t WAVESHARE_EPAPER_COMMAND_BORDER_WAVEFORM_CONTROL = 0x3C;
static const uint8_t WAVESHARE_EPAPER_COMMAND_SET_RAM_X_ADDRESS_START_END_POSITION = 0x44;
static const uint8_t WAVESHARE_EPAPER_COMMAND_SET_RAM_Y_ADDRESS_START_END_POSITION = 0x45;
static const uint8_t WAVESHARE_EPAPER_COMMAND_SET_RAM_X_ADDRESS_COUNTER = 0x4E;
static const uint8_t WAVESHARE_EPAPER_COMMAND_SET_RAM_Y_ADDRESS_COUNTER = 0x4F;
static const uint8_t WAVESHARE_EPAPER_COMMAND_TERMINATE_FRAME_READ_WRITE = 0xFF;
// not in .text section since only 30 bytes
static const uint8_t FULL_UPDATE_LUT[30] = {0x02, 0x02, 0x01, 0x11, 0x12, 0x12, 0x22, 0x22, 0x66, 0x69,
0x69, 0x59, 0x58, 0x99, 0x99, 0x88, 0x00, 0x00, 0x00, 0x00,
0xF8, 0xB4, 0x13, 0x51, 0x35, 0x51, 0x51, 0x19, 0x01, 0x00};
@@ -52,13 +29,7 @@ void WaveshareEPaper::setup_pins_() {
}
this->spi_setup();
// Reset
if (this->reset_pin_ != nullptr) {
this->reset_pin_->digital_write(false);
delay(200);
this->reset_pin_->digital_write(true);
delay(200);
}
this->reset_();
}
float WaveshareEPaper::get_setup_priority() const { return setup_priority::PROCESSOR; }
void WaveshareEPaper::command(uint8_t value) {
@@ -121,34 +92,39 @@ void WaveshareEPaper::start_data_() {
this->enable();
}
void WaveshareEPaper::end_data_() { this->disable(); }
void WaveshareEPaper::on_safe_shutdown() { this->deep_sleep(); }
// ========================================================
// Type A
// ========================================================
void WaveshareEPaperTypeA::setup() {
this->setup_pins_();
this->command(WAVESHARE_EPAPER_COMMAND_DRIVER_OUTPUT_CONTROL);
void WaveshareEPaperTypeA::initialize() {
// COMMAND DRIVER OUTPUT CONTROL
this->command(0x01);
this->data(this->get_height_internal() - 1);
this->data((this->get_height_internal() - 1) >> 8);
this->data(0x00); // ? GD = 0, SM = 0, TB = 0
this->command(WAVESHARE_EPAPER_COMMAND_BOOSTER_SOFT_START_CONTROL); // ?
// COMMAND BOOSTER SOFT START CONTROL
this->command(0x0C);
this->data(0xD7);
this->data(0xD6);
this->data(0x9D);
this->command(WAVESHARE_EPAPER_COMMAND_WRITE_VCOM_REGISTER); // ?
// COMMAND WRITE VCOM REGISTER
this->command(0x2C);
this->data(0xA8);
this->command(WAVESHARE_EPAPER_COMMAND_SET_DUMMY_LINE_PERIOD); // ?
// COMMAND SET DUMMY LINE PERIOD
this->command(0x3A);
this->data(0x1A);
this->command(WAVESHARE_EPAPER_COMMAND_SET_GATE_TIME); // 2µs per row
this->data(0x08);
// COMMAND SET GATE TIME
this->command(0x3B);
this->data(0x08); // 2µs per row
this->command(WAVESHARE_EPAPER_COMMAND_DATA_ENTRY_MODE_SETTING);
// COMMAND DATA ENTRY MODE SETTING
this->command(0x11);
this->data(0x03); // from top left to bottom right
}
void WaveshareEPaperTypeA::dump_config() {
@@ -186,18 +162,22 @@ void HOT WaveshareEPaperTypeA::display() {
}
// Set x & y regions we want to write to (full)
this->command(WAVESHARE_EPAPER_COMMAND_SET_RAM_X_ADDRESS_START_END_POSITION);
// COMMAND SET RAM X ADDRESS START END POSITION
this->command(0x44);
this->data(0x00);
this->data((this->get_width_internal() - 1) >> 3);
this->command(WAVESHARE_EPAPER_COMMAND_SET_RAM_Y_ADDRESS_START_END_POSITION);
// COMMAND SET RAM Y ADDRESS START END POSITION
this->command(0x45);
this->data(0x00);
this->data(0x00);
this->data(this->get_height_internal() - 1);
this->data((this->get_height_internal() - 1) >> 8);
this->command(WAVESHARE_EPAPER_COMMAND_SET_RAM_X_ADDRESS_COUNTER);
// COMMAND SET RAM X ADDRESS COUNTER
this->command(0x4E);
this->data(0x00);
this->command(WAVESHARE_EPAPER_COMMAND_SET_RAM_Y_ADDRESS_COUNTER);
// COMMAND SET RAM Y ADDRESS COUNTER
this->command(0x4F);
this->data(0x00);
this->data(0x00);
@@ -206,15 +186,19 @@ void HOT WaveshareEPaperTypeA::display() {
return;
}
this->command(WAVESHARE_EPAPER_COMMAND_WRITE_RAM);
// COMMAND WRITE RAM
this->command(0x24);
this->start_data_();
this->write_array(this->buffer_, this->get_buffer_length_());
this->end_data_();
this->command(WAVESHARE_EPAPER_COMMAND_DISPLAY_UPDATE_CONTROL_2);
// COMMAND DISPLAY UPDATE CONTROL 2
this->command(0x22);
this->data(0xC4);
this->command(WAVESHARE_EPAPER_COMMAND_MASTER_ACTIVATION);
this->command(WAVESHARE_EPAPER_COMMAND_TERMINATE_FRAME_READ_WRITE);
// COMMAND MASTER ACTIVATION
this->command(0x20);
// COMMAND TERMINATE FRAME READ WRITE
this->command(0xFF);
this->status_clear_warning();
}
@@ -241,7 +225,8 @@ int WaveshareEPaperTypeA::get_height_internal() {
return 0;
}
void WaveshareEPaperTypeA::write_lut_(const uint8_t *lut) {
this->command(WAVESHARE_EPAPER_COMMAND_WRITE_LUT_REGISTER);
// COMMAND WRITE LUT REGISTER
this->command(0x32);
for (uint8_t i = 0; i < 30; i++)
this->data(lut[i]);
}
@@ -253,47 +238,9 @@ void WaveshareEPaperTypeA::set_full_update_every(uint32_t full_update_every) {
// ========================================================
// Type B
// ========================================================
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PANEL_SETTING = 0x00;
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_POWER_SETTING = 0x01;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_POWER_OFF = 0x02;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_POWER_OFF_SEQUENCE_SETTING = 0x03;
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_POWER_ON = 0x04;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_POWER_MEASURE = 0x05;
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_BOOSTER_SOFT_START = 0x06;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_DEEP_SLEEP = 0x07;
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_DATA_START_TRANSMISSION_1 = 0x10;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_DATA_STOP = 0x11;
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_DISPLAY_REFRESH = 0x12;
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_DATA_START_TRANSMISSION_2 = 0x13;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PARTIAL_DATA_START_TRANSMISSION_1 = 0x14;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PARTIAL_DATA_START_TRANSMISSION_2 = 0x15;
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PARTIAL_DISPLAY_REFRESH = 0x16;
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_LUT_FOR_VCOM = 0x20;
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_LUT_WHITE_TO_WHITE = 0x21;
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_LUT_BLACK_TO_WHITE = 0x22;
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_LUT_WHITE_TO_BLACK = 0x23;
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_LUT_BLACK_TO_BLACK = 0x24;
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PLL_CONTROL = 0x30;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_TEMPERATURE_SENSOR_COMMAND = 0x40;
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_TEMPERATURE_SENSOR_CALIBRATION = 0x41;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_TEMPERATURE_SENSOR_WRITE = 0x42;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_TEMPERATURE_SENSOR_READ = 0x43;
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_VCOM_AND_DATA_INTERVAL_SETTING = 0x50;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_LOW_POWER_DETECTION = 0x51;
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_TCON_SETTING = 0x60;
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_RESOLUTION_SETTING = 0x61;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_GET_STATUS = 0x71;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_AUTO_MEASURE_VCOM = 0x80;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_VCOM_VALUE = 0x81;
static const uint8_t WAVESHARE_EPAPER_B_COMMAND_VCM_DC_SETTING_REGISTER = 0x82;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PARTIAL_WINDOW = 0x90;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PARTIAL_IN = 0x91;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PARTIAL_OUT = 0x92;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PROGRAM_MODE = 0xA0;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_ACTIVE_PROGRAM = 0xA1;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_READ_OTP_DATA = 0xA2;
// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_POWER_SAVING = 0xE3;
// Datasheet:
// - https://www.waveshare.com/w/upload/7/7f/4.2inch-e-paper-b-specification.pdf
// - https://github.com/soonuse/epd-library-arduino/blob/master/4.2inch_e-paper/epd4in2/
static const uint8_t LUT_VCOM_DC_2_7[44] = {
0x00, 0x00, 0x00, 0x0F, 0x0F, 0x00, 0x00, 0x05, 0x00, 0x32, 0x32, 0x00, 0x00, 0x02, 0x00,
@@ -325,18 +272,17 @@ static const uint8_t LUT_BLACK_TO_BLACK_2_7[42] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
void WaveshareEPaper2P7In::setup() {
this->setup_pins_();
// this->buffer_.init(this->get_width_(), this->get_height_());
this->command(WAVESHARE_EPAPER_B_COMMAND_POWER_SETTING);
void WaveshareEPaper2P7In::initialize() {
// command power setting
this->command(0x01);
this->data(0x03); // VDS_EN, VDG_EN
this->data(0x00); // VCOM_HV, VGHL_LV[1], VGHL_LV[0]
this->data(0x2B); // VDH
this->data(0x2B); // VDL
this->data(0x09); // VDHR
this->command(WAVESHARE_EPAPER_B_COMMAND_BOOSTER_SOFT_START);
// command booster soft start
this->command(0x06);
this->data(0x07);
this->data(0x07);
this->data(0x17);
@@ -364,51 +310,66 @@ void WaveshareEPaper2P7In::setup() {
this->data(0x73);
this->data(0x41);
this->command(WAVESHARE_EPAPER_B_COMMAND_PARTIAL_DISPLAY_REFRESH);
// command partial display refresh
this->command(0x16);
this->data(0x00);
this->command(WAVESHARE_EPAPER_B_COMMAND_POWER_ON);
// command power on
this->command(0x04);
this->wait_until_idle_();
delay(10);
this->command(WAVESHARE_EPAPER_B_COMMAND_PANEL_SETTING);
// Command panel setting
this->command(0x00);
this->data(0xAF); // KW-BF KWR-AF BWROTP 0f
this->command(WAVESHARE_EPAPER_B_COMMAND_PLL_CONTROL);
// command pll control
this->command(0x30);
this->data(0x3A); // 3A 100HZ 29 150Hz 39 200HZ 31 171HZ
this->command(WAVESHARE_EPAPER_B_COMMAND_VCM_DC_SETTING_REGISTER);
// COMMAND VCM DC SETTING
this->command(0x82);
this->data(0x12);
delay(2);
this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_FOR_VCOM);
// COMMAND LUT FOR VCOM
this->command(0x20);
for (uint8_t i : LUT_VCOM_DC_2_7)
this->data(i);
this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_WHITE_TO_WHITE);
// COMMAND LUT WHITE TO WHITE
this->command(0x21);
for (uint8_t i : LUT_WHITE_TO_WHITE_2_7)
this->data(i);
this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_BLACK_TO_WHITE);
// COMMAND LUT BLACK TO WHITE
this->command(0x22);
for (uint8_t i : LUT_BLACK_TO_WHITE_2_7)
this->data(i);
this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_WHITE_TO_BLACK);
// COMMAND LUT WHITE TO BLACK
this->command(0x23);
for (uint8_t i : LUT_WHITE_TO_BLACK_2_7)
this->data(i);
this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_BLACK_TO_BLACK);
// COMMAND LUT BLACK TO BLACK
this->command(0x24);
for (uint8_t i : LUT_BLACK_TO_BLACK_2_7)
this->data(i);
}
void HOT WaveshareEPaper2P7In::display() {
// TODO check active frame buffer to only transmit once / use partial transmits
this->command(WAVESHARE_EPAPER_B_COMMAND_DATA_START_TRANSMISSION_1);
// COMMAND DATA START TRANSMISSION 1
this->command(0x10);
delay(2);
this->start_data_();
this->write_array(this->buffer_, this->get_buffer_length_());
this->end_data_();
delay(2);
this->command(WAVESHARE_EPAPER_B_COMMAND_DATA_START_TRANSMISSION_2);
// COMMAND DATA START TRANSMISSION 2
this->command(0x13);
delay(2);
this->start_data_();
this->write_array(this->buffer_, this->get_buffer_length_());
this->end_data_();
this->command(WAVESHARE_EPAPER_B_COMMAND_DISPLAY_REFRESH);
// COMMAND DISPLAY REFRESH
this->command(0x12);
}
int WaveshareEPaper2P7In::get_width_internal() { return 176; }
int WaveshareEPaper2P7In::get_height_internal() { return 264; }
@@ -449,73 +410,88 @@ static const uint8_t LUT_WHITE_TO_BLACK_4_2[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
void WaveshareEPaper4P2In::setup() {
this->setup_pins_();
void WaveshareEPaper4P2In::initialize() {
// https://www.waveshare.com/w/upload/7/7f/4.2inch-e-paper-b-specification.pdf - page 8
this->command(WAVESHARE_EPAPER_B_COMMAND_POWER_SETTING);
// COMMAND POWER SETTING
this->command(0x01);
this->data(0x03); // VDS_EN, VDG_EN
this->data(0x00); // VCOM_HV, VGHL_LV[1], VGHL_LV[0]
this->data(0x2B); // VDH
this->data(0x2B); // VDL
this->data(0xFF); // VDHR
this->command(WAVESHARE_EPAPER_B_COMMAND_BOOSTER_SOFT_START);
this->data(0x17);
this->data(0x17);
this->data(0x17);
// COMMAND BOOSTER SOFT START
this->command(0x06);
this->data(0x17); // PHA
this->data(0x17); // PHB
this->data(0x17); // PHC
this->command(WAVESHARE_EPAPER_B_COMMAND_POWER_ON);
// COMMAND POWER ON
this->command(0x04);
this->wait_until_idle_();
delay(10);
this->command(WAVESHARE_EPAPER_B_COMMAND_PANEL_SETTING);
// COMMAND PANEL SETTING
this->command(0x00);
this->data(0xBF); // KW-BF KWR-AF BWROTP 0f
this->data(0x0B);
this->command(WAVESHARE_EPAPER_B_COMMAND_PLL_CONTROL);
// COMMAND PLL CONTROL
this->command(0x30);
this->data(0x3C); // 3A 100HZ 29 150Hz 39 200HZ 31 171HZ
delay(2);
this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_FOR_VCOM);
// COMMAND LUT FOR VCOM
this->command(0x20);
for (uint8_t i : LUT_VCOM_DC_4_2)
this->data(i);
this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_WHITE_TO_WHITE);
// COMMAND LUT WHITE TO WHITE
this->command(0x21);
for (uint8_t i : LUT_WHITE_TO_WHITE_4_2)
this->data(i);
this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_BLACK_TO_WHITE);
// COMMAND LUT BLACK TO WHITE
this->command(0x22);
for (uint8_t i : LUT_BLACK_TO_WHITE_4_2)
this->data(i);
this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_WHITE_TO_BLACK);
// COMMAND LUT WHITE TO BLACK
this->command(0x23);
for (uint8_t i : LUT_WHITE_TO_BLACK_4_2)
this->data(i);
this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_BLACK_TO_BLACK);
// COMMAND LUT BLACK TO BLACK
this->command(0x24);
for (uint8_t i : LUT_BLACK_TO_BLACK_4_2)
this->data(i);
}
void HOT WaveshareEPaper4P2In::display() {
this->command(WAVESHARE_EPAPER_B_COMMAND_RESOLUTION_SETTING);
// COMMAND RESOLUTION SETTING
this->command(0x61);
this->data(0x01);
this->data(0x90);
this->data(0x01);
this->data(0x2C);
this->command(WAVESHARE_EPAPER_B_COMMAND_VCM_DC_SETTING_REGISTER);
// COMMAND VCM DC SETTING REGISTER
this->command(0x82);
this->data(0x12);
this->command(WAVESHARE_EPAPER_B_COMMAND_VCOM_AND_DATA_INTERVAL_SETTING);
// COMMAND VCOM AND DATA INTERVAL SETTING
this->command(0x50);
this->data(0x97);
// TODO check active frame buffer to only transmit once / use partial transmits
this->command(WAVESHARE_EPAPER_B_COMMAND_DATA_START_TRANSMISSION_1);
// COMMAND DATA START TRANSMISSION 1
this->command(0x10);
delay(2);
this->start_data_();
this->write_array(this->buffer_, this->get_buffer_length_());
this->end_data_();
delay(2);
this->command(WAVESHARE_EPAPER_B_COMMAND_DATA_START_TRANSMISSION_2);
// COMMAND DATA START TRANSMISSION 2
this->command(0x13);
delay(2);
this->start_data_();
this->write_array(this->buffer_, this->get_buffer_length_());
this->end_data_();
this->command(WAVESHARE_EPAPER_B_COMMAND_DISPLAY_REFRESH);
// COMMAND DISPLAY REFRESH
this->command(0x12);
}
int WaveshareEPaper4P2In::get_width_internal() { return 400; }
int WaveshareEPaper4P2In::get_height_internal() { return 300; }
@@ -529,52 +505,61 @@ void WaveshareEPaper4P2In::dump_config() {
LOG_UPDATE_INTERVAL(this);
}
void WaveshareEPaper7P5In::setup() {
this->setup_pins_();
this->command(WAVESHARE_EPAPER_B_COMMAND_POWER_SETTING);
void WaveshareEPaper7P5In::initialize() {
// COMMAND POWER SETTING
this->command(0x01);
this->data(0x37);
this->data(0x00);
this->command(WAVESHARE_EPAPER_B_COMMAND_PANEL_SETTING);
// COMMAND PANEL SETTING
this->command(0x00);
this->data(0xCF);
this->data(0x0B);
this->command(WAVESHARE_EPAPER_B_COMMAND_BOOSTER_SOFT_START);
// COMMAND BOOSTER SOFT START
this->command(0x06);
this->data(0xC7);
this->data(0xCC);
this->data(0x28);
this->command(WAVESHARE_EPAPER_B_COMMAND_POWER_ON);
// COMMAND POWER ON
this->command(0x04);
this->wait_until_idle_();
delay(10);
this->command(WAVESHARE_EPAPER_B_COMMAND_PLL_CONTROL);
// COMMAND PLL CONTROL
this->command(0x30);
this->data(0x3C);
this->command(WAVESHARE_EPAPER_B_COMMAND_TEMPERATURE_SENSOR_CALIBRATION);
// COMMAND TEMPERATURE SENSOR CALIBRATION
this->command(0x41);
this->data(0x00);
this->command(WAVESHARE_EPAPER_B_COMMAND_VCOM_AND_DATA_INTERVAL_SETTING);
// COMMAND VCOM AND DATA INTERVAL SETTING
this->command(0x50);
this->data(0x77);
this->command(WAVESHARE_EPAPER_B_COMMAND_TCON_SETTING);
// COMMAND TCON SETTING
this->command(0x60);
this->data(0x22);
this->command(WAVESHARE_EPAPER_B_COMMAND_RESOLUTION_SETTING);
// COMMAND RESOLUTION SETTING
this->command(0x61);
this->data(0x02);
this->data(0x80);
this->data(0x01);
this->data(0x80);
this->command(WAVESHARE_EPAPER_B_COMMAND_VCM_DC_SETTING_REGISTER);
// COMMAND VCM DC SETTING REGISTER
this->command(0x82);
this->data(0x1E);
this->command(0xE5);
this->data(0x03);
}
void HOT WaveshareEPaper7P5In::display() {
this->command(WAVESHARE_EPAPER_B_COMMAND_DATA_START_TRANSMISSION_1);
// COMMAND DATA START TRANSMISSION 1
this->command(0x10);
this->start_data_();
for (size_t i = 0; i < this->get_buffer_length_(); i++) {
@@ -601,7 +586,8 @@ void HOT WaveshareEPaper7P5In::display() {
}
this->end_data_();
this->command(WAVESHARE_EPAPER_B_COMMAND_DISPLAY_REFRESH);
// COMMAND DISPLAY REFRESH
this->command(0x12);
}
int WaveshareEPaper7P5In::get_width_internal() { return 640; }
int WaveshareEPaper7P5In::get_height_internal() { return 384; }

View File

@@ -19,11 +19,20 @@ class WaveshareEPaper : public PollingComponent, public spi::SPIDevice, public d
void data(uint8_t value);
virtual void display() = 0;
virtual void initialize() = 0;
virtual void deep_sleep() = 0;
void update() override;
void fill(int color) override;
void setup() override {
this->setup_pins_();
this->initialize();
}
void on_safe_shutdown() override;
protected:
void draw_absolute_pixel_internal(int x, int y, int color) override;
@@ -31,6 +40,15 @@ class WaveshareEPaper : public PollingComponent, public spi::SPIDevice, public d
void setup_pins_();
void reset_() {
if (this->reset_pin_ != nullptr) {
this->reset_pin_->digital_write(false);
delay(200);
this->reset_pin_->digital_write(true);
delay(200);
}
}
uint32_t get_buffer_length_();
bool is_device_high_speed() override;
@@ -55,12 +73,18 @@ class WaveshareEPaperTypeA : public WaveshareEPaper {
public:
WaveshareEPaperTypeA(WaveshareEPaperTypeAModel model);
void setup() override;
void initialize() override;
void dump_config() override;
void display() override;
void deep_sleep() override {
// COMMAND DEEP SLEEP MODE
this->command(0x10);
this->wait_until_idle_();
}
void set_full_update_every(uint32_t full_update_every);
protected:
@@ -83,12 +107,18 @@ enum WaveshareEPaperTypeBModel {
class WaveshareEPaper2P7In : public WaveshareEPaper {
public:
void setup() override;
void initialize() override;
void display() override;
void dump_config() override;
void deep_sleep() override {
// COMMAND DEEP SLEEP
this->command(0x07);
this->data(0xA5); // check byte
}
protected:
int get_width_internal() override;
@@ -97,12 +127,41 @@ class WaveshareEPaper2P7In : public WaveshareEPaper {
class WaveshareEPaper4P2In : public WaveshareEPaper {
public:
void setup() override;
void initialize() override;
void display() override;
void dump_config() override;
void deep_sleep() override {
// COMMAND VCOM AND DATA INTERVAL SETTING
this->command(0x50);
this->data(0x17); // border floating
// COMMAND VCM DC SETTING
this->command(0x82);
// COMMAND PANEL SETTING
this->command(0x00);
delay(100);
// COMMAND POWER SETTING
this->command(0x01);
this->data(0x00);
this->data(0x00);
this->data(0x00);
this->data(0x00);
this->data(0x00);
delay(100);
// COMMAND POWER OFF
this->command(0x02);
this->wait_until_idle_();
// COMMAND DEEP SLEEP
this->command(0x07);
this->data(0xA5); // check byte
}
protected:
int get_width_internal() override;
@@ -113,12 +172,21 @@ class WaveshareEPaper4P2In : public WaveshareEPaper {
class WaveshareEPaper7P5In : public WaveshareEPaper {
public:
void setup() override;
void initialize() override;
void display() override;
void dump_config() override;
void deep_sleep() override {
// COMMAND POWER OFF
this->command(0x02);
this->wait_until_idle_();
// COMMAND DEEP SLEEP
this->command(0x07);
this->data(0xA5); // check byte
}
protected:
int get_width_internal() override;

View File

@@ -246,7 +246,11 @@ void print_signal_bars(int8_t rssi, char *buf) {
}
void WiFiComponent::print_connect_params_() {
uint8_t *bssid = WiFi.BSSID();
uint8_t bssid[6] = {};
uint8_t *raw_bssid = WiFi.BSSID();
if (raw_bssid != nullptr)
memcpy(bssid, raw_bssid, sizeof(bssid));
ESP_LOGCONFIG(TAG, " SSID: " LOG_SECRET("'%s'"), WiFi.SSID().c_str());
ESP_LOGCONFIG(TAG, " IP Address: %s", WiFi.localIP().toString().c_str());
ESP_LOGCONFIG(TAG, " BSSID: " LOG_SECRET("%02X:%02X:%02X:%02X:%02X:%02X"), bssid[0], bssid[1], bssid[2], bssid[3],
@@ -421,6 +425,7 @@ void WiFiComponent::check_connecting_finished() {
}
void WiFiComponent::retry_connect() {
delay(10);
if (this->num_retried_ > 5 || this->error_from_callback_) {
// If retry failed for more than 5 times, let's restart STA
ESP_LOGW(TAG, "Restarting WiFi adapter...");

View File

@@ -330,7 +330,6 @@ const char *get_disconnect_reason_str(uint8_t reason) {
}
void WiFiComponent::wifi_event_callback(System_Event_t *event) {
#ifdef ESPHOME_LOG_HAS_VERBOSE
// TODO: this callback is called while in cont context, so delay will fail
// We need to defer the log messages until we're out of this context
// only affects verbose log level
@@ -351,7 +350,7 @@ void WiFiComponent::wifi_event_callback(System_Event_t *event) {
char buf[33];
memcpy(buf, it.ssid, it.ssid_len);
buf[it.ssid_len] = '\0';
ESP_LOGV(TAG, "Event: Disconnected ssid='%s' bssid=%s reason='%s'", buf, format_mac_addr(it.bssid).c_str(),
ESP_LOGW(TAG, "Event: Disconnected ssid='%s' bssid=%s reason='%s'", buf, format_mac_addr(it.bssid).c_str(),
get_disconnect_reason_str(it.reason));
break;
}
@@ -403,7 +402,6 @@ void WiFiComponent::wifi_event_callback(System_Event_t *event) {
default:
break;
}
#endif
if (event->event == EVENT_STAMODE_DISCONNECTED) {
global_wifi_component->error_from_callback_ = true;
@@ -476,6 +474,7 @@ void WiFiComponent::wifi_scan_done_callback_(void *arg, STATUS status) {
if (status != OK) {
ESP_LOGV(TAG, "Scan failed! %d", status);
this->retry_connect();
return;
}
auto *head = reinterpret_cast<bss_info *>(arg);

View File

@@ -115,7 +115,7 @@ bool XiaomiListener::parse_device(const esp32_ble_tracker::ESPBTDevice &device)
const char *name = res->type == XiaomiParseResult::TYPE_MIFLORA ? "Mi Flora" : "Mi Jia";
ESP_LOGD(TAG, "Got Xiaomi %s:", name);
ESP_LOGD(TAG, "Got Xiaomi %s (%s):", name, device.address_str().c_str());
if (res->temperature.has_value()) {
ESP_LOGD(TAG, " Temperature: %.1f°C", *res->temperature);

View File

@@ -393,6 +393,16 @@ def validate_config(config):
result.add_error(err)
return result
if 'esphomeyaml' in config:
_LOGGER.warning("The esphomeyaml section has been renamed to esphome in 1.11.0. "
"Please replace 'esphomeyaml:' in your configuration with 'esphome:'.")
config[CONF_ESPHOME] = config.pop('esphomeyaml')
if CONF_ESPHOME not in config:
result.add_str_error("'esphome' section missing from configuration. Please make sure "
"your configuration has an 'esphome:' line in it.", [])
return result
# 2. Load partial core config
result[CONF_ESPHOME] = config[CONF_ESPHOME]
result.add_output_path([CONF_ESPHOME], CONF_ESPHOME)
@@ -612,9 +622,9 @@ def _format_vol_invalid(ex, config):
else:
message += u'[{}] is an invalid option for [{}]. Please check the indentation.'.format(
ex.path[-1], paren)
elif u'extra keys not allowed' in ex.error_message:
elif u'extra keys not allowed' in text_type(ex):
message += u'[{}] is an invalid option for [{}].'.format(ex.path[-1], paren)
elif u'required key not provided' in ex.error_message:
elif u'required key not provided' in text_type(ex):
message += u"'{}' is a required option for [{}].".format(ex.path[-1], paren)
else:
message += humanize_error(config, ex)

View File

@@ -20,7 +20,7 @@ from esphome.const import CONF_AVAILABILITY, CONF_COMMAND_TOPIC, CONF_DISCOVERY,
from esphome.core import CORE, HexInt, IPAddress, Lambda, TimePeriod, TimePeriodMicroseconds, \
TimePeriodMilliseconds, TimePeriodSeconds, TimePeriodMinutes
from esphome.helpers import list_starts_with
from esphome.py_compat import integer_types, string_types, text_type, IS_PY2
from esphome.py_compat import integer_types, string_types, text_type, IS_PY2, decode_text
from esphome.voluptuous_schema import _Schema
_LOGGER = logging.getLogger(__name__)
@@ -61,6 +61,7 @@ RESERVED_IDS = [
'App', 'pinMode', 'delay', 'delayMicroseconds', 'digitalRead', 'digitalWrite', 'INPUT',
'OUTPUT',
'uint8_t', 'uint16_t', 'uint32_t', 'uint64_t', 'int8_t', 'int16_t', 'int32_t', 'int64_t',
'close', 'pause', 'sleep', 'open',
]
@@ -616,9 +617,9 @@ if IS_PY2:
# Override voluptuous invalid to unicode for py2
def _vol_invalid_unicode(self):
path = u' @ data[%s]' % u']['.join(map(repr, self.path)) \
if self.path else ''
if self.path else u''
# pylint: disable=no-member
output = self.message
output = decode_text(self.message)
if self.error_type:
output += u' for ' + self.error_type
return output + path
@@ -1174,7 +1175,6 @@ def validate_registry_entry(name, registry):
if not isinstance(value, dict):
raise Invalid(u"{} must consist of key-value mapping! Got {}"
u"".format(name.title(), value))
value = base_schema(value)
key = next((x for x in value if x not in ignore_keys), None)
if key is None:
raise Invalid(u"Key missing from {}! Got {}".format(name, value))
@@ -1209,13 +1209,14 @@ def validate_registry(name, registry):
return ensure_list(validate_registry_entry(name, registry))
def maybe_simple_value(*validators):
def maybe_simple_value(*validators, **kwargs):
key = kwargs.pop('key', CONF_VALUE)
validator = All(*validators)
def validate(value):
if isinstance(value, dict) and CONF_VALUE in value:
if isinstance(value, dict) and key in value:
return validator(value)
return validator({CONF_VALUE: value})
return validator({key: value})
return validate

View File

@@ -3,7 +3,7 @@
MAJOR_VERSION = 1
MINOR_VERSION = 13
PATCH_VERSION = '0b1'
PATCH_VERSION = '6'
__short_version__ = '{}.{}'.format(MAJOR_VERSION, MINOR_VERSION)
__version__ = '{}.{}'.format(__short_version__, PATCH_VERSION)
@@ -62,6 +62,7 @@ CONF_BUILD_PATH = 'build_path'
CONF_BUSY_PIN = 'busy_pin'
CONF_BUS_VOLTAGE = 'bus_voltage'
CONF_CALIBRATE_LINEAR = 'calibrate_linear'
CONF_CALIBRATION = 'calibration'
CONF_CARRIER_DUTY_PERCENT = 'carrier_duty_percent'
CONF_CARRIER_FREQUENCY = 'carrier_frequency'
CONF_CHANGE_MODE_EVERY = 'change_mode_every'
@@ -201,6 +202,7 @@ CONF_LEVEL = 'level'
CONF_LG = 'lg'
CONF_LIBRARIES = 'libraries'
CONF_LIGHT = 'light'
CONF_LOADED_INTEGRATIONS = 'loaded_integrations'
CONF_LOCAL = 'local'
CONF_LOGGER = 'logger'
CONF_LOGS = 'logs'
@@ -456,6 +458,7 @@ ICON_BATTERY = 'mdi:battery'
ICON_BRIEFCASE_DOWNLOAD = 'mdi:briefcase-download'
ICON_BRIGHTNESS_5 = 'mdi:brightness-5'
ICON_CHEMICAL_WEAPON = 'mdi:chemical-weapon'
ICON_CHECK_CIRCLE_OUTLINE = 'mdi:check-circle-outline'
ICON_EMPTY = ''
ICON_FLASH = 'mdi:flash'
ICON_FLOWER = 'mdi:flower'

View File

@@ -1,5 +1,6 @@
#include "esphome/core/application.h"
#include "esphome/core/log.h"
#include "esphome/core/version.h"
#ifdef USE_STATUS_LED
#include "esphome/components/status_led/status_led.h"
@@ -57,13 +58,46 @@ void Application::setup() {
}
ESP_LOGI(TAG, "setup() finished successfully!");
this->dump_config();
this->schedule_dump_config();
}
void Application::dump_config() {
ESP_LOGI(TAG, "esphome version " ESPHOME_VERSION " compiled on %s", this->compilation_time_.c_str());
void Application::loop() {
uint32_t new_app_state = 0;
const uint32_t start = millis();
for (Component *component : this->components_) {
if (!component->is_failed()) {
component->call_loop();
}
new_app_state |= component->get_component_state();
this->app_state_ |= new_app_state;
this->feed_wdt();
}
this->app_state_ = new_app_state;
const uint32_t end = millis();
if (end - start > 200) {
ESP_LOGV(TAG, "A component took a long time in a loop() cycle (%.1f s).", (end - start) / 1e3f);
ESP_LOGV(TAG, "Components should block for at most 20-30ms in loop().");
ESP_LOGV(TAG, "This will become a warning soon.");
}
for (auto component : this->components_) {
component->dump_config();
const uint32_t now = millis();
if (HighFrequencyLoopRequester::is_high_frequency()) {
yield();
} else {
uint32_t delay_time = this->loop_interval_;
if (now - this->last_loop_ < this->loop_interval_)
delay_time = this->loop_interval_ - (now - this->last_loop_);
delay(delay_time);
}
this->last_loop_ = now;
if (this->dump_config_at_ >= 0 && this->dump_config_at_ < this->components_.size()) {
if (this->dump_config_at_ == 0) {
ESP_LOGI(TAG, "esphome version " ESPHOME_VERSION " compiled on %s", this->compilation_time_.c_str());
}
this->components_[this->dump_config_at_]->dump_config();
this->dump_config_at_++;
}
}

View File

@@ -87,34 +87,7 @@ class Application {
void setup();
/// Make a loop iteration. Call this in your loop() function.
void loop() {
uint32_t new_app_state = 0;
for (Component *component : this->components_) {
if (!component->is_failed()) {
component->call_loop();
}
new_app_state |= component->get_component_state();
this->app_state_ |= new_app_state;
this->feed_wdt();
}
this->app_state_ = new_app_state;
const uint32_t now = millis();
if (HighFrequencyLoopRequester::is_high_frequency()) {
yield();
} else {
uint32_t delay_time = this->loop_interval_;
if (now - this->last_loop_ < this->loop_interval_)
delay_time = this->loop_interval_ - (now - this->last_loop_);
delay(delay_time);
}
this->last_loop_ = now;
if (this->dump_config_scheduled_) {
this->dump_config();
this->dump_config_scheduled_ = false;
}
}
void loop();
/// Get the name of this Application set by set_name().
const std::string &get_name() const { return this->name_; }
@@ -136,8 +109,7 @@ class Application {
*/
void set_loop_interval(uint32_t loop_interval) { this->loop_interval_ = loop_interval; }
void dump_config();
void schedule_dump_config() { this->dump_config_scheduled_ = true; }
void schedule_dump_config() { this->dump_config_at_ = 0; }
void feed_wdt();
@@ -261,7 +233,7 @@ class Application {
std::string compilation_time_;
uint32_t last_loop_{0};
uint32_t loop_interval_{16};
bool dump_config_scheduled_{false};
int dump_config_at_{-1};
uint32_t app_state_{0};
};

View File

@@ -73,7 +73,7 @@ template<typename... Ts> class ForCondition : public Condition<Ts...>, public Co
bool check(Ts... x) override {
if (!this->check_internal())
return false;
return millis() - this->last_inactive_ < this->time_.value(x...);
return millis() - this->last_inactive_ >= this->time_.value(x...);
}
protected:

View File

@@ -1,8 +1,6 @@
#pragma once
// This file is auto-generated! Do not edit!
#define ESPHOME_VERSION "dev"
#define USE_API
#define USE_LOGGER
#define USE_BINARY_SENSOR

View File

@@ -7,6 +7,7 @@
#endif
#include "esphome/core/esphal.h"
#include "esphome/core/defines.h"
namespace esphome {

View File

@@ -1,6 +1,7 @@
#include "esphome/core/util.h"
#include "esphome/core/defines.h"
#include "esphome/core/application.h"
#include "esphome/core/version.h"
#ifdef USE_WIFI
#include "esphome/components/wifi/wifi_component.h"

3
esphome/core/version.h Normal file
View File

@@ -0,0 +1,3 @@
#pragma once
// This file is auto-generated! Do not edit!
#define ESPHOME_VERSION "dev"

View File

@@ -10,9 +10,10 @@ from esphome.const import ARDUINO_VERSION_ESP32_DEV, ARDUINO_VERSION_ESP8266_DEV
CONF_ESPHOME, CONF_INCLUDES, CONF_LIBRARIES, \
CONF_NAME, CONF_ON_BOOT, CONF_ON_LOOP, CONF_ON_SHUTDOWN, CONF_PLATFORM, \
CONF_PLATFORMIO_OPTIONS, CONF_PRIORITY, CONF_TRIGGER_ID, \
CONF_ESP8266_RESTORE_FROM_FLASH, __version__, ARDUINO_VERSION_ESP8266_2_3_0, \
CONF_ESP8266_RESTORE_FROM_FLASH, ARDUINO_VERSION_ESP8266_2_3_0, \
ARDUINO_VERSION_ESP8266_2_5_0, ARDUINO_VERSION_ESP8266_2_5_1, ARDUINO_VERSION_ESP8266_2_5_2
from esphome.core import CORE, coroutine_with_priority
from esphome.helpers import copy_file_if_changed, walk_files
from esphome.pins import ESP8266_FLASH_SIZES, ESP8266_LD_SCRIPTS
_LOGGER = logging.getLogger(__name__)
@@ -37,7 +38,7 @@ def validate_board(value):
if value not in board_pins:
raise cv.Invalid(u"Could not find board '{}'. Valid boards are {}".format(
value, u', '.join(pins.ESP8266_BOARD_PINS.keys())))
value, u', '.join(sorted(board_pins.keys()))))
return value
@@ -59,6 +60,7 @@ PLATFORMIO_ESP8266_LUT = {
PLATFORMIO_ESP32_LUT = {
'1.0.0': 'espressif32@1.4.0',
'1.0.1': 'espressif32@1.6.0',
'1.0.2': 'espressif32@1.8.0',
'RECOMMENDED': 'espressif32@1.6.0',
'LATEST': 'espressif32',
'DEV': ARDUINO_VERSION_ESP32_DEV,
@@ -91,6 +93,22 @@ def default_build_path():
return CORE.name
VALID_INCLUDE_EXTS = {'.h', '.hpp', '.tcc', '.ino', '.cpp', '.c'}
def valid_include(value):
try:
return cv.directory(value)
except cv.Invalid:
pass
value = cv.file_(value)
_, ext = os.path.splitext(value)
if ext not in VALID_INCLUDE_EXTS:
raise cv.Invalid(u"Include has invalid file extension {} - valid extensions are {}"
u"".format(ext, ', '.join(VALID_INCLUDE_EXTS)))
return value
CONFIG_SCHEMA = cv.Schema({
cv.Required(CONF_NAME): cv.valid_name,
cv.Required(CONF_PLATFORM): cv.one_of('ESP8266', 'ESP32', upper=True),
@@ -115,7 +133,7 @@ CONFIG_SCHEMA = cv.Schema({
cv.Optional(CONF_ON_LOOP): automation.validate_automation({
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(LoopTrigger),
}),
cv.Optional(CONF_INCLUDES, default=[]): cv.ensure_list(cv.file_),
cv.Optional(CONF_INCLUDES, default=[]): cv.ensure_list(valid_include),
cv.Optional(CONF_LIBRARIES, default=[]): cv.ensure_list(cv.string_strict),
cv.Optional('esphome_core_version'): cv.invalid("The esphome_core_version option has been "
@@ -153,19 +171,36 @@ def preload_core_config(config):
CORE.build_path = CORE.relative_config_path(out2[CONF_BUILD_PATH])
def include_file(path, basename):
parts = basename.split(os.path.sep)
dst = CORE.relative_src_path(*parts)
copy_file_if_changed(path, dst)
_, ext = os.path.splitext(path)
if ext in ['.h', '.hpp', '.tcc']:
# Header, add include statement
cg.add_global(cg.RawStatement(u'#include "{}"'.format(basename)))
@coroutine_with_priority(-1000.0)
def add_includes(includes):
# Add includes at the very end, so that the included files can access global variables
for include in includes:
path = CORE.relative_config_path(include)
res = os.path.relpath(path, CORE.relative_build_path('src')).replace(os.path.sep, '/')
cg.add_global(cg.RawStatement(u'#include "{}"'.format(res)))
if os.path.isdir(path):
# Directory, copy tree
for p in walk_files(path):
basename = os.path.relpath(p, os.path.dirname(path))
include_file(p, basename)
else:
# Copy file
basename = os.path.basename(path)
include_file(path, basename)
@coroutine_with_priority(100.0)
def to_code(config):
cg.add_global(cg.global_ns.namespace('esphome').using)
cg.add_define('ESPHOME_VERSION', __version__)
cg.add(cg.App.pre_setup(config[CONF_NAME], cg.RawExpression('__DATE__ ", " __TIME__')))
for conf in config.get(CONF_ON_BOOT, []):

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