Merge branch 'dev' into gp8403

This commit is contained in:
SeByDocKy 2024-11-06 22:10:35 +01:00 committed by GitHub
commit b2d1bab168
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
123 changed files with 10169 additions and 898 deletions

View File

@ -75,6 +75,9 @@ target/
# pyenv # pyenv
.python-version .python-version
# asdf
.tool-versions
# celery beat schedule file # celery beat schedule file
celerybeat-schedule celerybeat-schedule

View File

@ -65,7 +65,7 @@ jobs:
pip3 install build pip3 install build
python3 -m build python3 -m build
- name: Publish - name: Publish
uses: pypa/gh-action-pypi-publish@v1.10.3 uses: pypa/gh-action-pypi-publish@v1.11.0
deploy-docker: deploy-docker:
name: Build ESPHome ${{ matrix.platform }} name: Build ESPHome ${{ matrix.platform }}

3
.gitignore vendored
View File

@ -75,6 +75,9 @@ cov.xml
# pyenv # pyenv
.python-version .python-version
# asdf
.tool-versions
# Environments # Environments
.env .env
.venv .venv

View File

@ -85,6 +85,7 @@ esphome/components/bmp581/* @kahrendt
esphome/components/bp1658cj/* @Cossid esphome/components/bp1658cj/* @Cossid
esphome/components/bp5758d/* @Cossid esphome/components/bp5758d/* @Cossid
esphome/components/button/* @esphome/core esphome/components/button/* @esphome/core
esphome/components/bytebuffer/* @clydebarrow
esphome/components/canbus/* @danielschramm @mvturnho esphome/components/canbus/* @danielschramm @mvturnho
esphome/components/cap1188/* @mreditor97 esphome/components/cap1188/* @mreditor97
esphome/components/captive_portal/* @OttoWinter esphome/components/captive_portal/* @OttoWinter
@ -130,6 +131,7 @@ esphome/components/ens160_base/* @latonita @vincentscode
esphome/components/ens160_i2c/* @latonita esphome/components/ens160_i2c/* @latonita
esphome/components/ens160_spi/* @latonita esphome/components/ens160_spi/* @latonita
esphome/components/ens210/* @itn3rd77 esphome/components/ens210/* @itn3rd77
esphome/components/es8311/* @kahrendt @kroimon
esphome/components/esp32/* @esphome/core esphome/components/esp32/* @esphome/core
esphome/components/esp32_ble/* @Rapsssito @jesserockz esphome/components/esp32_ble/* @Rapsssito @jesserockz
esphome/components/esp32_ble_client/* @jesserockz esphome/components/esp32_ble_client/* @jesserockz

View File

@ -40,25 +40,6 @@ RUN \
libcairo2=1.16.0-7 \ libcairo2=1.16.0-7 \
libmagic1=1:5.44-3 \ libmagic1=1:5.44-3 \
patch=2.7.6-7 \ patch=2.7.6-7 \
&& ( \
( \
[ "$TARGETARCH$TARGETVARIANT" = "armv7" ] && \
apt-get install -y --no-install-recommends \
build-essential=12.9 \
python3-dev=3.11.2-1+b1 \
zlib1g-dev=1:1.2.13.dfsg-1 \
libjpeg-dev=1:2.1.5-2 \
libfreetype-dev=2.12.1+dfsg-5+deb12u3 \
libssl-dev=3.0.14-1~deb12u2 \
libffi-dev=3.4.4-1 \
libopenjp2-7=2.5.0-2 \
libtiff6=4.5.0-6+deb12u1 \
cargo=0.66.0+ds1-1 \
pkg-config=1.8.1-1 \
gcc-arm-linux-gnueabihf=4:12.2.0-3 \
) \
|| [ "$TARGETARCH$TARGETVARIANT" != "armv7" ] \
) \
&& rm -rf \ && rm -rf \
/tmp/* \ /tmp/* \
/var/{cache,log}/* \ /var/{cache,log}/* \
@ -97,15 +78,48 @@ RUN \
# tmpfs is for https://github.com/rust-lang/cargo/issues/8719 # tmpfs is for https://github.com/rust-lang/cargo/issues/8719
COPY requirements.txt requirements_optional.txt / COPY requirements.txt requirements_optional.txt /
RUN --mount=type=tmpfs,target=/root/.cargo if [ "$TARGETARCH$TARGETVARIANT" = "armv7" ]; then \ RUN --mount=type=tmpfs,target=/root/.cargo <<END-OF-RUN
curl -L https://www.piwheels.org/cp311/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl -o /tmp/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl \ # Fail on any non-zero status
&& pip3 install --break-system-packages --no-cache-dir /tmp/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl \ set -e
&& rm /tmp/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl \
&& export PIP_EXTRA_INDEX_URL="https://www.piwheels.org/simple"; \ if [ "$TARGETARCH$TARGETVARIANT" = "armv7" ]
fi; \ then
CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse CARGO_HOME=/root/.cargo \ curl -L https://www.piwheels.org/cp311/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl -o /tmp/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl
pip3 install \ pip3 install --break-system-packages --no-cache-dir /tmp/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl
--break-system-packages --no-cache-dir -r /requirements.txt -r /requirements_optional.txt rm /tmp/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl
export PIP_EXTRA_INDEX_URL="https://www.piwheels.org/simple";
fi
# install build tools in case wheels are not available
BUILD_DEPS="
build-essential=12.9
python3-dev=3.11.2-1+b1
zlib1g-dev=1:1.2.13.dfsg-1
libjpeg-dev=1:2.1.5-2
libfreetype-dev=2.12.1+dfsg-5+deb12u3
libssl-dev=3.0.14-1~deb12u2
libffi-dev=3.4.4-1
libopenjp2-7=2.5.0-2
libtiff6=4.5.0-6+deb12u1
cargo=0.66.0+ds1-1
pkg-config=1.8.1-1
"
if [ "$TARGETARCH$TARGETVARIANT" = "arm64" ] || [ "$TARGETARCH$TARGETVARIANT" = "armv7" ]
then
apt-get update
apt-get install -y --no-install-recommends $BUILD_DEPS
fi
CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse CARGO_HOME=/root/.cargo
pip3 install --break-system-packages --no-cache-dir -r /requirements.txt -r /requirements_optional.txt
if [ "$TARGETARCH$TARGETVARIANT" = "arm64" ] || [ "$TARGETARCH$TARGETVARIANT" = "armv7" ]
then
apt-get remove -y --purge --auto-remove $BUILD_DEPS
rm -rf /tmp/* /var/{cache,log}/* /var/lib/apt/lists/*
fi
END-OF-RUN
COPY script/platformio_install_deps.py platformio.ini / COPY script/platformio_install_deps.py platformio.ini /
RUN /platformio_install_deps.py /platformio.ini --libraries RUN /platformio_install_deps.py /platformio.ini --libraries

View File

@ -0,0 +1,5 @@
CODEOWNERS = ["@clydebarrow"]
# Allows bytebuffer to be configured in yaml, to allow use of the C++ api.
CONFIG_SCHEMA = {}

View File

@ -0,0 +1,421 @@
#pragma once
#include <utility>
#include <vector>
#include <cinttypes>
#include <cstddef>
#include "esphome/core/helpers.h"
namespace esphome {
namespace bytebuffer {
enum Endian { LITTLE, BIG };
/**
* A class modelled on the Java ByteBuffer class. It wraps a vector of bytes and permits putting and getting
* items of various sizes, with an automatically incremented position.
*
* There are three variables maintained pointing into the buffer:
*
* capacity: the maximum amount of data that can be stored - set on construction and cannot be changed
* limit: the limit of the data currently available to get or put
* position: the current insert or extract position
*
* 0 <= position <= limit <= capacity
*
* In addition a mark can be set to the current position with mark(). A subsequent call to reset() will restore
* the position to the mark.
*
* The buffer can be marked to be little-endian (default) or big-endian. All subsequent operations will use that order.
*
* The flip() operation will reset the position to 0 and limit to the current position. This is useful for reading
* data from a buffer after it has been written.
*
* The code is defined here in the header file rather than in a .cpp file, so that it does not get compiled if not used.
* The templated functions ensure that only those typed functions actually used are compiled. The functions
* are implicitly inline-able which will aid performance.
*/
class ByteBuffer {
public:
// Default constructor (compatibility with TEMPLATABLE_VALUE)
// Creates a zero-length ByteBuffer which is little use to anybody.
ByteBuffer() : ByteBuffer(std::vector<uint8_t>()) {}
/**
* Create a new Bytebuffer with the given capacity
*/
ByteBuffer(size_t capacity, Endian endianness = LITTLE)
: data_(std::vector<uint8_t>(capacity)), endianness_(endianness), limit_(capacity){};
// templated functions to implement putting and getting data of various types. There are two flavours of all
// functions - one that uses the position as the offset, and updates the position accordingly, and one that
// takes an explicit offset and does not update the position.
// Separate temnplates are provided for types that fit into 32 bits and those that are bigger. These delegate
// the actual put/get to common code based around those sizes.
// This reduces the code size and execution time for smaller types. A similar structure for e.g. 16 bits is unlikely
// to provide any further benefit given that all target platforms are native 32 bit.
template<typename T>
T get(typename std::enable_if<std::is_integral<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) {
// integral types that fit into 32 bit
return static_cast<T>(this->get_uint32_(sizeof(T)));
}
template<typename T>
T get(size_t offset, typename std::enable_if<std::is_integral<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) {
return static_cast<T>(this->get_uint32_(offset, sizeof(T)));
}
template<typename T>
void put(const T &value, typename std::enable_if<std::is_integral<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) {
this->put_uint32_(static_cast<uint32_t>(value), sizeof(T));
}
template<typename T>
void put(const T &value, size_t offset, typename std::enable_if<std::is_integral<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) {
this->put_uint32_(static_cast<uint32_t>(value), offset, sizeof(T));
}
// integral types that do not fit into 32 bit (basically only 64 bit types)
template<typename T>
T get(typename std::enable_if<std::is_integral<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
return static_cast<T>(this->get_uint64_(sizeof(T)));
}
template<typename T>
T get(size_t offset, typename std::enable_if<std::is_integral<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
return static_cast<T>(this->get_uint64_(offset, sizeof(T)));
}
template<typename T>
void put(const T &value, typename std::enable_if<std::is_integral<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
this->put_uint64_(value, sizeof(T));
}
template<typename T>
void put(const T &value, size_t offset, typename std::enable_if<std::is_integral<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
this->put_uint64_(static_cast<uint64_t>(value), offset, sizeof(T));
}
// floating point types. Caters for 32 and 64 bit floating point.
template<typename T>
T get(typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint32_t)), T>::type * = 0) {
return bit_cast<T>(this->get_uint32_(sizeof(T)));
}
template<typename T>
T get(typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
return bit_cast<T>(this->get_uint64_(sizeof(T)));
}
template<typename T>
T get(size_t offset, typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint32_t)), T>::type * = 0) {
return bit_cast<T>(this->get_uint32_(offset, sizeof(T)));
}
template<typename T>
T get(size_t offset, typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
return bit_cast<T>(this->get_uint64_(offset, sizeof(T)));
}
template<typename T>
void put(const T &value, typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) {
this->put_uint32_(bit_cast<uint32_t>(value), sizeof(T));
}
template<typename T>
void put(const T &value, typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
this->put_uint64_(bit_cast<uint64_t>(value), sizeof(T));
}
template<typename T>
void put(const T &value, size_t offset, typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) {
this->put_uint32_(bit_cast<uint32_t>(value), offset, sizeof(T));
}
template<typename T>
void put(const T &value, size_t offset, typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
this->put_uint64_(bit_cast<uint64_t>(value), offset, sizeof(T));
}
template<typename T> static ByteBuffer wrap(T value, Endian endianness = LITTLE) {
ByteBuffer buffer = ByteBuffer(sizeof(T), endianness);
buffer.put(value);
buffer.flip();
return buffer;
}
static ByteBuffer wrap(std::vector<uint8_t> const &data, Endian endianness = LITTLE) {
ByteBuffer buffer = {data};
buffer.endianness_ = endianness;
return buffer;
}
static ByteBuffer wrap(const uint8_t *ptr, size_t len, Endian endianness = LITTLE) {
return wrap(std::vector<uint8_t>(ptr, ptr + len), endianness);
}
// convenience functions with explicit types named..
void put_float(float value) { this->put(value); }
void put_double(double value) { this->put(value); }
uint8_t get_uint8() { return this->data_[this->position_++]; }
// Get a 16 bit unsigned value, increment by 2
uint16_t get_uint16() { return this->get<uint16_t>(); }
// Get a 24 bit unsigned value, increment by 3
uint32_t get_uint24() { return this->get_uint32_(3); };
// Get a 32 bit unsigned value, increment by 4
uint32_t get_uint32() { return this->get<uint32_t>(); };
// Get a 64 bit unsigned value, increment by 8
uint64_t get_uint64() { return this->get<uint64_t>(); };
// Signed versions of the get functions
uint8_t get_int8() { return static_cast<int8_t>(this->get_uint8()); };
int16_t get_int16() { return this->get<uint16_t>(); }
int32_t get_int32() { return this->get<int32_t>(); }
int64_t get_int64() { return this->get<int64_t>(); }
// Get a float value, increment by 4
float get_float() { return this->get<float>(); }
// Get a double value, increment by 8
double get_double() { return this->get<double>(); }
// Get a bool value, increment by 1
bool get_bool() { return static_cast<bool>(this->get_uint8()); }
uint32_t get_int24(size_t offset) {
auto value = this->get_uint24(offset);
uint32_t mask = (~static_cast<uint32_t>(0)) << 23;
if ((value & mask) != 0)
value |= mask;
return value;
}
uint32_t get_int24() {
auto value = this->get_uint24();
uint32_t mask = (~static_cast<uint32_t>(0)) << 23;
if ((value & mask) != 0)
value |= mask;
return value;
}
std::vector<uint8_t> get_vector(size_t length, size_t offset) {
auto start = this->data_.begin() + offset;
return {start, start + length};
}
std::vector<uint8_t> get_vector(size_t length) {
auto result = this->get_vector(length, this->position_);
this->position_ += length;
return result;
}
// Convenience named functions
void put_uint8(uint8_t value) { this->data_[this->position_++] = value; }
void put_uint16(uint16_t value) { this->put(value); }
void put_uint24(uint32_t value) { this->put_uint32_(value, 3); }
void put_uint32(uint32_t value) { this->put(value); }
void put_uint64(uint64_t value) { this->put(value); }
// Signed versions of the put functions
void put_int8(int8_t value) { this->put_uint8(static_cast<uint8_t>(value)); }
void put_int16(int16_t value) { this->put(value); }
void put_int24(int32_t value) { this->put_uint32_(value, 3); }
void put_int32(int32_t value) { this->put(value); }
void put_int64(int64_t value) { this->put(value); }
// Extra put functions
void put_bool(bool value) { this->put_uint8(value); }
// versions of the above with an offset, these do not update the position
uint64_t get_uint64(size_t offset) { return this->get<uint64_t>(offset); }
uint32_t get_uint24(size_t offset) { return this->get_uint32_(offset, 3); };
double get_double(size_t offset) { return get<double>(offset); }
// Get one byte from the buffer, increment position by 1
uint8_t get_uint8(size_t offset) { return this->data_[offset]; }
// Get a 16 bit unsigned value, increment by 2
uint16_t get_uint16(size_t offset) { return get<uint16_t>(offset); }
// Get a 24 bit unsigned value, increment by 3
uint32_t get_uint32(size_t offset) { return this->get<uint32_t>(offset); };
// Get a 64 bit unsigned value, increment by 8
uint8_t get_int8(size_t offset) { return get<int8_t>(offset); }
int16_t get_int16(size_t offset) { return get<int16_t>(offset); }
int32_t get_int32(size_t offset) { return get<int32_t>(offset); }
int64_t get_int64(size_t offset) { return get<int64_t>(offset); }
// Get a float value, increment by 4
float get_float(size_t offset) { return get<float>(offset); }
// Get a double value, increment by 8
// Get a bool value, increment by 1
bool get_bool(size_t offset) { return this->get_uint8(offset); }
void put_uint8(uint8_t value, size_t offset) { this->data_[offset] = value; }
void put_uint16(uint16_t value, size_t offset) { this->put(value, offset); }
void put_uint24(uint32_t value, size_t offset) { this->put(value, offset); }
void put_uint32(uint32_t value, size_t offset) { this->put(value, offset); }
void put_uint64(uint64_t value, size_t offset) { this->put(value, offset); }
// Signed versions of the put functions
void put_int8(int8_t value, size_t offset) { this->put_uint8(static_cast<uint8_t>(value), offset); }
void put_int16(int16_t value, size_t offset) { this->put(value, offset); }
void put_int24(int32_t value, size_t offset) { this->put_uint32_(value, offset, 3); }
void put_int32(int32_t value, size_t offset) { this->put(value, offset); }
void put_int64(int64_t value, size_t offset) { this->put(value, offset); }
// Extra put functions
void put_float(float value, size_t offset) { this->put(value, offset); }
void put_double(double value, size_t offset) { this->put(value, offset); }
void put_bool(bool value, size_t offset) { this->put_uint8(value, offset); }
void put(const std::vector<uint8_t> &value, size_t offset) {
std::copy(value.begin(), value.end(), this->data_.begin() + offset);
}
void put_vector(const std::vector<uint8_t> &value, size_t offset) { this->put(value, offset); }
void put(const std::vector<uint8_t> &value) {
this->put_vector(value, this->position_);
this->position_ += value.size();
}
void put_vector(const std::vector<uint8_t> &value) { this->put(value); }
// Getters
inline size_t get_capacity() const { return this->data_.size(); }
inline size_t get_position() const { return this->position_; }
inline size_t get_limit() const { return this->limit_; }
inline size_t get_remaining() const { return this->get_limit() - this->get_position(); }
inline Endian get_endianness() const { return this->endianness_; }
inline void mark() { this->mark_ = this->position_; }
inline void big_endian() { this->endianness_ = BIG; }
inline void little_endian() { this->endianness_ = LITTLE; }
// retrieve a pointer to the underlying data.
std::vector<uint8_t> get_data() { return this->data_; };
void get_bytes(void *dest, size_t length) {
std::copy(this->data_.begin() + this->position_, this->data_.begin() + this->position_ + length, (uint8_t *) dest);
this->position_ += length;
}
void get_bytes(void *dest, size_t length, size_t offset) {
std::copy(this->data_.begin() + offset, this->data_.begin() + offset + length, (uint8_t *) dest);
}
void rewind() { this->position_ = 0; }
void reset() { this->position_ = this->mark_; }
void set_limit(size_t limit) { this->limit_ = limit; }
void set_position(size_t position) { this->position_ = position; }
void clear() {
this->limit_ = this->get_capacity();
this->position_ = 0;
}
void flip() {
this->limit_ = this->position_;
this->position_ = 0;
}
protected:
uint64_t get_uint64_(size_t offset, size_t length) const {
uint64_t value = 0;
if (this->endianness_ == LITTLE) {
offset += length;
while (length-- != 0) {
value <<= 8;
value |= this->data_[--offset];
}
} else {
while (length-- != 0) {
value <<= 8;
value |= this->data_[offset++];
}
}
return value;
}
uint64_t get_uint64_(size_t length) {
auto result = this->get_uint64_(this->position_, length);
this->position_ += length;
return result;
}
uint32_t get_uint32_(size_t offset, size_t length) const {
uint32_t value = 0;
if (this->endianness_ == LITTLE) {
offset += length;
while (length-- != 0) {
value <<= 8;
value |= this->data_[--offset];
}
} else {
while (length-- != 0) {
value <<= 8;
value |= this->data_[offset++];
}
}
return value;
}
uint32_t get_uint32_(size_t length) {
auto result = this->get_uint32_(this->position_, length);
this->position_ += length;
return result;
}
/// Putters
void put_uint64_(uint64_t value, size_t length) {
this->put_uint64_(value, this->position_, length);
this->position_ += length;
}
void put_uint32_(uint32_t value, size_t length) {
this->put_uint32_(value, this->position_, length);
this->position_ += length;
}
void put_uint64_(uint64_t value, size_t offset, size_t length) {
if (this->endianness_ == LITTLE) {
while (length-- != 0) {
this->data_[offset++] = static_cast<uint8_t>(value);
value >>= 8;
}
} else {
offset += length;
while (length-- != 0) {
this->data_[--offset] = static_cast<uint8_t>(value);
value >>= 8;
}
}
}
void put_uint32_(uint32_t value, size_t offset, size_t length) {
if (this->endianness_ == LITTLE) {
while (length-- != 0) {
this->data_[offset++] = static_cast<uint8_t>(value);
value >>= 8;
}
} else {
offset += length;
while (length-- != 0) {
this->data_[--offset] = static_cast<uint8_t>(value);
value >>= 8;
}
}
}
ByteBuffer(std::vector<uint8_t> const &data) : data_(data), limit_(data.size()) {}
std::vector<uint8_t> data_;
Endian endianness_{LITTLE};
size_t position_{0};
size_t mark_{0};
size_t limit_{0};
};
} // namespace bytebuffer
} // namespace esphome

View File

@ -119,10 +119,21 @@ visual_temperature = cv.float_with_unit(
) )
def single_visual_temperature(value): VISUAL_TEMPERATURE_STEP_SCHEMA = cv.Schema(
if isinstance(value, dict): {
return value cv.Required(CONF_TARGET_TEMPERATURE): visual_temperature,
cv.Required(CONF_CURRENT_TEMPERATURE): visual_temperature,
}
)
def visual_temperature_step(value):
# Allow defining target/current temperature steps separately
if isinstance(value, dict):
return VISUAL_TEMPERATURE_STEP_SCHEMA(value)
# Otherwise, use the single value for both properties
value = visual_temperature(value) value = visual_temperature(value)
return VISUAL_TEMPERATURE_STEP_SCHEMA( return VISUAL_TEMPERATURE_STEP_SCHEMA(
{ {
@ -141,16 +152,6 @@ ControlTrigger = climate_ns.class_(
"ControlTrigger", automation.Trigger.template(ClimateCall.operator("ref")) "ControlTrigger", automation.Trigger.template(ClimateCall.operator("ref"))
) )
VISUAL_TEMPERATURE_STEP_SCHEMA = cv.Any(
single_visual_temperature,
cv.Schema(
{
cv.Required(CONF_TARGET_TEMPERATURE): visual_temperature,
cv.Required(CONF_CURRENT_TEMPERATURE): visual_temperature,
}
),
)
CLIMATE_SCHEMA = ( CLIMATE_SCHEMA = (
cv.ENTITY_BASE_SCHEMA.extend(web_server.WEBSERVER_SORTING_SCHEMA) cv.ENTITY_BASE_SCHEMA.extend(web_server.WEBSERVER_SORTING_SCHEMA)
.extend(cv.MQTT_COMMAND_COMPONENT_SCHEMA) .extend(cv.MQTT_COMMAND_COMPONENT_SCHEMA)
@ -162,7 +163,7 @@ CLIMATE_SCHEMA = (
{ {
cv.Optional(CONF_MIN_TEMPERATURE): cv.temperature, cv.Optional(CONF_MIN_TEMPERATURE): cv.temperature,
cv.Optional(CONF_MAX_TEMPERATURE): cv.temperature, cv.Optional(CONF_MAX_TEMPERATURE): cv.temperature,
cv.Optional(CONF_TEMPERATURE_STEP): VISUAL_TEMPERATURE_STEP_SCHEMA, cv.Optional(CONF_TEMPERATURE_STEP): visual_temperature_step,
cv.Optional(CONF_MIN_HUMIDITY): cv.percentage_int, cv.Optional(CONF_MIN_HUMIDITY): cv.percentage_int,
cv.Optional(CONF_MAX_HUMIDITY): cv.percentage_int, cv.Optional(CONF_MAX_HUMIDITY): cv.percentage_int,
} }

View File

@ -70,8 +70,6 @@ def _validate_time_present(config):
_DATETIME_SCHEMA = cv.ENTITY_BASE_SCHEMA.extend( _DATETIME_SCHEMA = cv.ENTITY_BASE_SCHEMA.extend(
web_server.WEBSERVER_SORTING_SCHEMA,
cv.MQTT_COMMAND_COMPONENT_SCHEMA,
cv.Schema( cv.Schema(
{ {
cv.Optional(CONF_ON_VALUE): automation.validate_automation( cv.Optional(CONF_ON_VALUE): automation.validate_automation(
@ -81,7 +79,9 @@ _DATETIME_SCHEMA = cv.ENTITY_BASE_SCHEMA.extend(
), ),
cv.Optional(CONF_TIME_ID): cv.use_id(time.RealTimeClock), cv.Optional(CONF_TIME_ID): cv.use_id(time.RealTimeClock),
} }
), )
.extend(web_server.WEBSERVER_SORTING_SCHEMA)
.extend(cv.MQTT_COMMAND_COMPONENT_SCHEMA)
).add_extra(_validate_time_present) ).add_extra(_validate_time_present)

View File

View File

@ -0,0 +1,70 @@
import esphome.codegen as cg
from esphome.components import i2c
from esphome.components.audio_dac import AudioDac
import esphome.config_validation as cv
from esphome.const import CONF_BITS_PER_SAMPLE, CONF_ID, CONF_SAMPLE_RATE
CODEOWNERS = ["@kroimon", "@kahrendt"]
DEPENDENCIES = ["i2c"]
es8311_ns = cg.esphome_ns.namespace("es8311")
ES8311 = es8311_ns.class_("ES8311", AudioDac, cg.Component, i2c.I2CDevice)
CONF_MIC_GAIN = "mic_gain"
CONF_USE_MCLK = "use_mclk"
CONF_USE_MICROPHONE = "use_microphone"
es8311_resolution = es8311_ns.enum("ES8311Resolution")
ES8311_BITS_PER_SAMPLE_ENUM = {
16: es8311_resolution.ES8311_RESOLUTION_16,
24: es8311_resolution.ES8311_RESOLUTION_24,
32: es8311_resolution.ES8311_RESOLUTION_32,
}
es8311_mic_gain = es8311_ns.enum("ES8311MicGain")
ES8311_MIC_GAIN_ENUM = {
"MIN": es8311_mic_gain.ES8311_MIC_GAIN_MIN,
"0DB": es8311_mic_gain.ES8311_MIC_GAIN_0DB,
"6DB": es8311_mic_gain.ES8311_MIC_GAIN_6DB,
"12DB": es8311_mic_gain.ES8311_MIC_GAIN_12DB,
"18DB": es8311_mic_gain.ES8311_MIC_GAIN_18DB,
"24DB": es8311_mic_gain.ES8311_MIC_GAIN_24DB,
"30DB": es8311_mic_gain.ES8311_MIC_GAIN_30DB,
"36DB": es8311_mic_gain.ES8311_MIC_GAIN_36DB,
"42DB": es8311_mic_gain.ES8311_MIC_GAIN_42DB,
"MAX": es8311_mic_gain.ES8311_MIC_GAIN_MAX,
}
_validate_bits = cv.float_with_unit("bits", "bit")
CONFIG_SCHEMA = (
cv.Schema(
{
cv.GenerateID(): cv.declare_id(ES8311),
cv.Optional(CONF_BITS_PER_SAMPLE, default="16bit"): cv.All(
_validate_bits, cv.enum(ES8311_BITS_PER_SAMPLE_ENUM)
),
cv.Optional(CONF_MIC_GAIN, default="42DB"): cv.enum(
ES8311_MIC_GAIN_ENUM, upper=True
),
cv.Optional(CONF_SAMPLE_RATE, default=16000): cv.int_range(min=1),
cv.Optional(CONF_USE_MCLK, default=True): cv.boolean,
cv.Optional(CONF_USE_MICROPHONE, default=False): cv.boolean,
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(i2c.i2c_device_schema(0x18))
)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
await i2c.register_i2c_device(var, config)
cg.add(var.set_bits_per_sample(config[CONF_BITS_PER_SAMPLE]))
cg.add(var.set_mic_gain(config[CONF_MIC_GAIN]))
cg.add(var.set_sample_frequency(config[CONF_SAMPLE_RATE]))
cg.add(var.set_use_mclk(config[CONF_USE_MCLK]))
cg.add(var.set_use_mic(config[CONF_USE_MICROPHONE]))

View File

@ -0,0 +1,227 @@
#include "es8311.h"
#include "es8311_const.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
#include <cinttypes>
namespace esphome {
namespace es8311 {
static const char *const TAG = "es8311";
// Mark the component as failed; use only in setup
#define ES8311_ERROR_FAILED(func) \
if (!(func)) { \
this->mark_failed(); \
return; \
}
// Return false; use outside of setup
#define ES8311_ERROR_CHECK(func) \
if (!(func)) { \
return false; \
}
void ES8311::setup() {
ESP_LOGCONFIG(TAG, "Setting up ES8311...");
// Reset
ES8311_ERROR_FAILED(this->write_byte(ES8311_REG00_RESET, 0x1F));
ES8311_ERROR_FAILED(this->write_byte(ES8311_REG00_RESET, 0x00));
ES8311_ERROR_FAILED(this->configure_clock_());
ES8311_ERROR_FAILED(this->configure_format_());
ES8311_ERROR_FAILED(this->configure_mic_());
// Set initial volume
this->set_volume(0.75); // 0.75 = 0xBF = 0dB
// Power up analog circuitry
ES8311_ERROR_FAILED(this->write_byte(ES8311_REG0D_SYSTEM, 0x01));
// Enable analog PGA, enable ADC modulator
ES8311_ERROR_FAILED(this->write_byte(ES8311_REG0E_SYSTEM, 0x02));
// Power up DAC
ES8311_ERROR_FAILED(this->write_byte(ES8311_REG12_SYSTEM, 0x00));
// Enable output to HP drive
ES8311_ERROR_FAILED(this->write_byte(ES8311_REG13_SYSTEM, 0x10));
// ADC Equalizer bypass, cancel DC offset in digital domain
ES8311_ERROR_FAILED(this->write_byte(ES8311_REG1C_ADC, 0x6A));
// Bypass DAC equalizer
ES8311_ERROR_FAILED(this->write_byte(ES8311_REG37_DAC, 0x08));
// Power On
ES8311_ERROR_FAILED(this->write_byte(ES8311_REG00_RESET, 0x80));
}
void ES8311::dump_config() {
ESP_LOGCONFIG(TAG, "ES8311 Audio Codec:");
ESP_LOGCONFIG(TAG, " Use MCLK: %s", YESNO(this->use_mclk_));
ESP_LOGCONFIG(TAG, " Use Microphone: %s", YESNO(this->use_mic_));
ESP_LOGCONFIG(TAG, " DAC Bits per Sample: %" PRIu8, this->resolution_out_);
ESP_LOGCONFIG(TAG, " Sample Rate: %" PRIu32, this->sample_frequency_);
if (this->is_failed()) {
ESP_LOGCONFIG(TAG, " Failed to initialize!");
return;
}
}
bool ES8311::set_volume(float volume) {
volume = clamp(volume, 0.0f, 1.0f);
uint8_t reg32 = remap<uint8_t, float>(volume, 0.0f, 1.0f, 0, 255);
return this->write_byte(ES8311_REG32_DAC, reg32);
}
float ES8311::volume() {
uint8_t reg32;
this->read_byte(ES8311_REG32_DAC, &reg32);
return remap<float, uint8_t>(reg32, 0, 255, 0.0f, 1.0f);
}
uint8_t ES8311::calculate_resolution_value(ES8311Resolution resolution) {
switch (resolution) {
case ES8311_RESOLUTION_16:
return (3 << 2);
case ES8311_RESOLUTION_18:
return (2 << 2);
case ES8311_RESOLUTION_20:
return (1 << 2);
case ES8311_RESOLUTION_24:
return (0 << 2);
case ES8311_RESOLUTION_32:
return (4 << 2);
default:
return 0;
}
}
const ES8311Coefficient *ES8311::get_coefficient(uint32_t mclk, uint32_t rate) {
for (const auto &coefficient : ES8311_COEFFICIENTS) {
if (coefficient.mclk == mclk && coefficient.rate == rate)
return &coefficient;
}
return nullptr;
}
bool ES8311::configure_clock_() {
// Register 0x01: select clock source for internal MCLK and determine its frequency
uint8_t reg01 = 0x3F; // Enable all clocks
uint32_t mclk_frequency = this->sample_frequency_ * this->mclk_multiple_;
if (!this->use_mclk_) {
reg01 |= BIT(7); // Use SCLK
mclk_frequency = this->sample_frequency_ * (int) this->resolution_out_ * 2;
}
if (this->mclk_inverted_) {
reg01 |= BIT(6); // Invert MCLK pin
}
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG01_CLK_MANAGER, reg01));
// Get clock coefficients from coefficient table
auto *coefficient = get_coefficient(mclk_frequency, this->sample_frequency_);
if (coefficient == nullptr) {
ESP_LOGE(TAG, "Unable to configure sample rate %" PRIu32 "Hz with %" PRIu32 "Hz MCLK", this->sample_frequency_,
mclk_frequency);
return false;
}
// Register 0x02
uint8_t reg02;
ES8311_ERROR_CHECK(this->read_byte(ES8311_REG02_CLK_MANAGER, &reg02));
reg02 &= 0x07;
reg02 |= (coefficient->pre_div - 1) << 5;
reg02 |= coefficient->pre_mult << 3;
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG02_CLK_MANAGER, reg02));
// Register 0x03
const uint8_t reg03 = (coefficient->fs_mode << 6) | coefficient->adc_osr;
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG03_CLK_MANAGER, reg03));
// Register 0x04
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG04_CLK_MANAGER, coefficient->dac_osr));
// Register 0x05
const uint8_t reg05 = ((coefficient->adc_div - 1) << 4) | (coefficient->dac_div - 1);
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG05_CLK_MANAGER, reg05));
// Register 0x06
uint8_t reg06;
ES8311_ERROR_CHECK(this->read_byte(ES8311_REG06_CLK_MANAGER, &reg06));
if (this->sclk_inverted_) {
reg06 |= BIT(5);
} else {
reg06 &= ~BIT(5);
}
reg06 &= 0xE0;
if (coefficient->bclk_div < 19) {
reg06 |= (coefficient->bclk_div - 1) << 0;
} else {
reg06 |= (coefficient->bclk_div) << 0;
}
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG06_CLK_MANAGER, reg06));
// Register 0x07
uint8_t reg07;
ES8311_ERROR_CHECK(this->read_byte(ES8311_REG07_CLK_MANAGER, &reg07));
reg07 &= 0xC0;
reg07 |= coefficient->lrck_h << 0;
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG07_CLK_MANAGER, reg07));
// Register 0x08
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG08_CLK_MANAGER, coefficient->lrck_l));
// Successfully configured the clock
return true;
}
bool ES8311::configure_format_() {
// Configure I2S mode and format
uint8_t reg00;
ES8311_ERROR_CHECK(this->read_byte(ES8311_REG00_RESET, &reg00));
reg00 &= 0xBF;
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG00_RESET, reg00));
// Configure SDP in resolution
uint8_t reg09 = calculate_resolution_value(this->resolution_in_);
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG09_SDPIN, reg09));
// Configure SDP out resolution
uint8_t reg0a = calculate_resolution_value(this->resolution_out_);
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG0A_SDPOUT, reg0a));
// Successfully configured the format
return true;
}
bool ES8311::configure_mic_() {
uint8_t reg14 = 0x1A; // Enable analog MIC and max PGA gain
if (this->use_mic_) {
reg14 |= BIT(6); // Enable PDM digital microphone
}
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG14_SYSTEM, reg14));
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG16_ADC, this->mic_gain_)); // ADC gain scale up
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG17_ADC, 0xC8)); // Set ADC gain
// Successfully configured the microphones
return true;
}
bool ES8311::set_mute_state_(bool mute_state) {
uint8_t reg31;
this->is_muted_ = mute_state;
if (!this->read_byte(ES8311_REG31_DAC, &reg31)) {
return false;
}
if (mute_state) {
reg31 |= BIT(6) | BIT(5);
} else {
reg31 &= ~(BIT(6) | BIT(5));
}
return this->write_byte(ES8311_REG31_DAC, reg31);
}
} // namespace es8311
} // namespace esphome

View File

@ -0,0 +1,135 @@
#pragma once
#include "esphome/components/audio_dac/audio_dac.h"
#include "esphome/components/i2c/i2c.h"
#include "esphome/core/component.h"
namespace esphome {
namespace es8311 {
enum ES8311MicGain {
ES8311_MIC_GAIN_MIN = -1,
ES8311_MIC_GAIN_0DB,
ES8311_MIC_GAIN_6DB,
ES8311_MIC_GAIN_12DB,
ES8311_MIC_GAIN_18DB,
ES8311_MIC_GAIN_24DB,
ES8311_MIC_GAIN_30DB,
ES8311_MIC_GAIN_36DB,
ES8311_MIC_GAIN_42DB,
ES8311_MIC_GAIN_MAX
};
enum ES8311Resolution : uint8_t {
ES8311_RESOLUTION_16 = 16,
ES8311_RESOLUTION_18 = 18,
ES8311_RESOLUTION_20 = 20,
ES8311_RESOLUTION_24 = 24,
ES8311_RESOLUTION_32 = 32
};
struct ES8311Coefficient {
uint32_t mclk; // mclk frequency
uint32_t rate; // sample rate
uint8_t pre_div; // the pre divider with range from 1 to 8
uint8_t pre_mult; // the pre multiplier with x1, x2, x4 and x8 selection
uint8_t adc_div; // adcclk divider
uint8_t dac_div; // dacclk divider
uint8_t fs_mode; // single speed (0) or double speed (1)
uint8_t lrck_h; // adc lrck divider and dac lrck divider
uint8_t lrck_l; //
uint8_t bclk_div; // sclk divider
uint8_t adc_osr; // adc osr
uint8_t dac_osr; // dac osr
};
class ES8311 : public audio_dac::AudioDac, public Component, public i2c::I2CDevice {
public:
/////////////////////////
// Component overrides //
/////////////////////////
void setup() override;
float get_setup_priority() const override { return setup_priority::DATA; }
void dump_config() override;
////////////////////////
// AudioDac overrides //
////////////////////////
/// @brief Writes the volume out to the DAC
/// @param volume floating point between 0.0 and 1.0
/// @return True if successful and false otherwise
bool set_volume(float volume) override;
/// @brief Gets the current volume out from the DAC
/// @return floating point between 0.0 and 1.0
float volume() override;
/// @brief Disables mute for audio out
/// @return True if successful and false otherwise
bool set_mute_off() override { return this->set_mute_state_(false); }
/// @brief Enables mute for audio out
/// @return True if successful and false otherwise
bool set_mute_on() override { return this->set_mute_state_(true); }
bool is_muted() override { return this->is_muted_; }
//////////////////////////////////
// ES8311 configuration setters //
//////////////////////////////////
void set_use_mclk(bool use_mclk) { this->use_mclk_ = use_mclk; }
void set_bits_per_sample(ES8311Resolution resolution) {
this->resolution_in_ = resolution;
this->resolution_out_ = resolution;
}
void set_sample_frequency(uint32_t sample_frequency) { this->sample_frequency_ = sample_frequency; }
void set_use_mic(bool use_mic) { this->use_mic_ = use_mic; }
void set_mic_gain(ES8311MicGain mic_gain) { this->mic_gain_ = mic_gain; }
protected:
/// @brief Computes the register value for the configured resolution (bits per sample)
/// @param resolution bits per sample enum for both audio in and audio out
/// @return register value
static uint8_t calculate_resolution_value(ES8311Resolution resolution);
/// @brief Retrieves the appropriate registers values for the configured mclk and rate
/// @param mclk mlck frequency in Hz
/// @param rate sample rate frequency in Hz
/// @return ES8311Coeffecient containing appropriate register values to configure the ES8311 or nullptr if impossible
static const ES8311Coefficient *get_coefficient(uint32_t mclk, uint32_t rate);
/// @brief Configures the ES8311 registers for the chosen sample rate
/// @return True if successful and false otherwise
bool configure_clock_();
/// @brief Configures the ES8311 registers for the chosen bits per sample
/// @return True if successful and false otherwise
bool configure_format_();
/// @brief Configures the ES8311 microphone registers
/// @return True if successful and false otherwise
bool configure_mic_();
/// @brief Mutes or unmute the DAC audio out
/// @param mute_state True to mute, false to unmute
/// @return
bool set_mute_state_(bool mute_state);
bool use_mic_;
ES8311MicGain mic_gain_;
bool use_mclk_; // true = use dedicated MCLK pin, false = use SCLK
bool sclk_inverted_{false}; // SCLK is inverted
bool mclk_inverted_{false}; // MCLK is inverted (ignored if use_mclk_ == false)
uint32_t mclk_multiple_{256}; // MCLK frequency is sample rate * mclk_multiple_ (ignored if use_mclk_ == false)
uint32_t sample_frequency_; // in Hz
ES8311Resolution resolution_in_;
ES8311Resolution resolution_out_;
};
} // namespace es8311
} // namespace esphome

View File

@ -0,0 +1,195 @@
#pragma once
#include "es8311.h"
namespace esphome {
namespace es8311 {
// ES8311 register addresses
static const uint8_t ES8311_REG00_RESET = 0x00; // Reset
static const uint8_t ES8311_REG01_CLK_MANAGER = 0x01; // Clock Manager: select clk src for mclk, enable clock for codec
static const uint8_t ES8311_REG02_CLK_MANAGER = 0x02; // Clock Manager: clk divider and clk multiplier
static const uint8_t ES8311_REG03_CLK_MANAGER = 0x03; // Clock Manager: adc fsmode and osr
static const uint8_t ES8311_REG04_CLK_MANAGER = 0x04; // Clock Manager: dac osr
static const uint8_t ES8311_REG05_CLK_MANAGER = 0x05; // Clock Manager: clk divider for adc and dac
static const uint8_t ES8311_REG06_CLK_MANAGER = 0x06; // Clock Manager: bclk inverter BIT(5) and divider
static const uint8_t ES8311_REG07_CLK_MANAGER = 0x07; // Clock Manager: tri-state, lrck divider
static const uint8_t ES8311_REG08_CLK_MANAGER = 0x08; // Clock Manager: lrck divider
static const uint8_t ES8311_REG09_SDPIN = 0x09; // Serial Digital Port: DAC
static const uint8_t ES8311_REG0A_SDPOUT = 0x0A; // Serial Digital Port: ADC
static const uint8_t ES8311_REG0B_SYSTEM = 0x0B; // System
static const uint8_t ES8311_REG0C_SYSTEM = 0x0C; // System
static const uint8_t ES8311_REG0D_SYSTEM = 0x0D; // System: power up/down
static const uint8_t ES8311_REG0E_SYSTEM = 0x0E; // System: power up/down
static const uint8_t ES8311_REG0F_SYSTEM = 0x0F; // System: low power
static const uint8_t ES8311_REG10_SYSTEM = 0x10; // System
static const uint8_t ES8311_REG11_SYSTEM = 0x11; // System
static const uint8_t ES8311_REG12_SYSTEM = 0x12; // System: Enable DAC
static const uint8_t ES8311_REG13_SYSTEM = 0x13; // System
static const uint8_t ES8311_REG14_SYSTEM = 0x14; // System: select DMIC, select analog pga gain
static const uint8_t ES8311_REG15_ADC = 0x15; // ADC: adc ramp rate, dmic sense
static const uint8_t ES8311_REG16_ADC = 0x16; // ADC
static const uint8_t ES8311_REG17_ADC = 0x17; // ADC: volume
static const uint8_t ES8311_REG18_ADC = 0x18; // ADC: alc enable and winsize
static const uint8_t ES8311_REG19_ADC = 0x19; // ADC: alc maxlevel
static const uint8_t ES8311_REG1A_ADC = 0x1A; // ADC: alc automute
static const uint8_t ES8311_REG1B_ADC = 0x1B; // ADC: alc automute, adc hpf s1
static const uint8_t ES8311_REG1C_ADC = 0x1C; // ADC: equalizer, hpf s2
static const uint8_t ES8311_REG1D_ADCEQ = 0x1D; // ADCEQ: equalizer B0
static const uint8_t ES8311_REG1E_ADCEQ = 0x1E; // ADCEQ: equalizer B0
static const uint8_t ES8311_REG1F_ADCEQ = 0x1F; // ADCEQ: equalizer B0
static const uint8_t ES8311_REG20_ADCEQ = 0x20; // ADCEQ: equalizer B0
static const uint8_t ES8311_REG21_ADCEQ = 0x21; // ADCEQ: equalizer A1
static const uint8_t ES8311_REG22_ADCEQ = 0x22; // ADCEQ: equalizer A1
static const uint8_t ES8311_REG23_ADCEQ = 0x23; // ADCEQ: equalizer A1
static const uint8_t ES8311_REG24_ADCEQ = 0x24; // ADCEQ: equalizer A1
static const uint8_t ES8311_REG25_ADCEQ = 0x25; // ADCEQ: equalizer A2
static const uint8_t ES8311_REG26_ADCEQ = 0x26; // ADCEQ: equalizer A2
static const uint8_t ES8311_REG27_ADCEQ = 0x27; // ADCEQ: equalizer A2
static const uint8_t ES8311_REG28_ADCEQ = 0x28; // ADCEQ: equalizer A2
static const uint8_t ES8311_REG29_ADCEQ = 0x29; // ADCEQ: equalizer B1
static const uint8_t ES8311_REG2A_ADCEQ = 0x2A; // ADCEQ: equalizer B1
static const uint8_t ES8311_REG2B_ADCEQ = 0x2B; // ADCEQ: equalizer B1
static const uint8_t ES8311_REG2C_ADCEQ = 0x2C; // ADCEQ: equalizer B1
static const uint8_t ES8311_REG2D_ADCEQ = 0x2D; // ADCEQ: equalizer B2
static const uint8_t ES8311_REG2E_ADCEQ = 0x2E; // ADCEQ: equalizer B2
static const uint8_t ES8311_REG2F_ADCEQ = 0x2F; // ADCEQ: equalizer B2
static const uint8_t ES8311_REG30_ADCEQ = 0x30; // ADCEQ: equalizer B2
static const uint8_t ES8311_REG31_DAC = 0x31; // DAC: mute
static const uint8_t ES8311_REG32_DAC = 0x32; // DAC: volume
static const uint8_t ES8311_REG33_DAC = 0x33; // DAC: offset
static const uint8_t ES8311_REG34_DAC = 0x34; // DAC: drc enable, drc winsize
static const uint8_t ES8311_REG35_DAC = 0x35; // DAC: drc maxlevel, minilevel
static const uint8_t ES8311_REG36_DAC = 0x36; // DAC
static const uint8_t ES8311_REG37_DAC = 0x37; // DAC: ramprate
static const uint8_t ES8311_REG38_DACEQ = 0x38; // DACEQ: equalizer B0
static const uint8_t ES8311_REG39_DACEQ = 0x39; // DACEQ: equalizer B0
static const uint8_t ES8311_REG3A_DACEQ = 0x3A; // DACEQ: equalizer B0
static const uint8_t ES8311_REG3B_DACEQ = 0x3B; // DACEQ: equalizer B0
static const uint8_t ES8311_REG3C_DACEQ = 0x3C; // DACEQ: equalizer B1
static const uint8_t ES8311_REG3D_DACEQ = 0x3D; // DACEQ: equalizer B1
static const uint8_t ES8311_REG3E_DACEQ = 0x3E; // DACEQ: equalizer B1
static const uint8_t ES8311_REG3F_DACEQ = 0x3F; // DACEQ: equalizer B1
static const uint8_t ES8311_REG40_DACEQ = 0x40; // DACEQ: equalizer A1
static const uint8_t ES8311_REG41_DACEQ = 0x41; // DACEQ: equalizer A1
static const uint8_t ES8311_REG42_DACEQ = 0x42; // DACEQ: equalizer A1
static const uint8_t ES8311_REG43_DACEQ = 0x43; // DACEQ: equalizer A1
static const uint8_t ES8311_REG44_GPIO = 0x44; // GPIO: dac2adc for test
static const uint8_t ES8311_REG45_GP = 0x45; // GPIO: GP control
static const uint8_t ES8311_REGFA_I2C = 0xFA; // I2C: reset registers
static const uint8_t ES8311_REGFC_FLAG = 0xFC; // Flag
static const uint8_t ES8311_REGFD_CHD1 = 0xFD; // Chip: ID1
static const uint8_t ES8311_REGFE_CHD2 = 0xFE; // Chip: ID2
static const uint8_t ES8311_REGFF_CHVER = 0xFF; // Chip: Version
// ES8311 clock divider coefficients
static const ES8311Coefficient ES8311_COEFFICIENTS[] = {
// clang-format off
// mclk, rate, pre_ pre_ adc_ dac_ fs_ lrck lrck bclk_ adc_ dac_
// div, mult, div, div, mode, _h, _l, div, osr, osr
// 8k
{12288000, 8000, 0x06, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{18432000, 8000, 0x03, 0x02, 0x03, 0x03, 0x00, 0x05, 0xff, 0x18, 0x10, 0x20},
{16384000, 8000, 0x08, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 8192000, 8000, 0x04, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 6144000, 8000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 4096000, 8000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 3072000, 8000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 2048000, 8000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 1536000, 8000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 1024000, 8000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
// 11.025k
{11289600, 11025, 0x04, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 5644800, 11025, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 2822400, 11025, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 1411200, 11025, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
// 12k
{12288000, 12000, 0x04, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 6144000, 12000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 3072000, 12000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 1536000, 12000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
// 16k
{12288000, 16000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{18432000, 16000, 0x03, 0x02, 0x03, 0x03, 0x00, 0x02, 0xff, 0x0c, 0x10, 0x20},
{16384000, 16000, 0x04, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 8192000, 16000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 6144000, 16000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 4096000, 16000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 3072000, 16000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 2048000, 16000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 1536000, 16000, 0x03, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 1024000, 16000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
// 22.05k
{11289600, 22050, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 5644800, 22050, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 2822400, 22050, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 1411200, 22050, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
// 24k
{12288000, 24000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 24000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 6144000, 24000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 3072000, 24000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 1536000, 24000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
// 32k
{12288000, 32000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 32000, 0x03, 0x04, 0x03, 0x03, 0x00, 0x02, 0xff, 0x0c, 0x10, 0x10},
{16384000, 32000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 8192000, 32000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 6144000, 32000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 4096000, 32000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 3072000, 32000, 0x03, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 2048000, 32000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 1536000, 32000, 0x03, 0x08, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
{ 1024000, 32000, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
// 44.1k
{11289600, 44100, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 5644800, 44100, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 2822400, 44100, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 1411200, 44100, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
// 48k
{12288000, 48000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 48000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 6144000, 48000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 3072000, 48000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 1536000, 48000, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
// 64k
{12288000, 64000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 64000, 0x03, 0x04, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10},
{16384000, 64000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 8192000, 64000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 6144000, 64000, 0x01, 0x04, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10},
{ 4096000, 64000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 3072000, 64000, 0x01, 0x08, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10},
{ 2048000, 64000, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 1536000, 64000, 0x01, 0x08, 0x01, 0x01, 0x01, 0x00, 0xbf, 0x03, 0x18, 0x18},
{ 1024000, 64000, 0x01, 0x08, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
// 88.2k
{11289600, 88200, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 5644800, 88200, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 2822400, 88200, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 1411200, 88200, 0x01, 0x08, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
// 96k
{12288000, 96000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 96000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 6144000, 96000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 3072000, 96000, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 1536000, 96000, 0x01, 0x08, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
// clang-format on
};
} // namespace es8311
} // namespace esphome

View File

@ -67,8 +67,10 @@ def _translate_pin(value):
"This variable only supports pin numbers, not full pin schemas " "This variable only supports pin numbers, not full pin schemas "
"(with inverted and mode)." "(with inverted and mode)."
) )
if isinstance(value, int): if isinstance(value, int) and not isinstance(value, bool):
return value return value
if not isinstance(value, str):
raise cv.Invalid(f"Invalid pin number: {value}")
try: try:
return int(value) return int(value)
except ValueError: except ValueError:

View File

@ -35,7 +35,7 @@ class BLEClientBase : public espbt::ESPBTClient, public Component {
void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override; void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override;
void connect() override; void connect() override;
esp_err_t pair(); esp_err_t pair();
void disconnect(); void disconnect() override;
void release_services(); void release_services();
bool connected() { return this->state_ == espbt::ClientState::ESTABLISHED; } bool connected() { return this->state_ == espbt::ClientState::ESTABLISHED; }

View File

@ -11,9 +11,9 @@
#ifdef USE_ESP32 #ifdef USE_ESP32
#include <esp_bt_defs.h>
#include <esp_gap_ble_api.h> #include <esp_gap_ble_api.h>
#include <esp_gattc_api.h> #include <esp_gattc_api.h>
#include <esp_bt_defs.h>
#include <freertos/FreeRTOS.h> #include <freertos/FreeRTOS.h>
#include <freertos/semphr.h> #include <freertos/semphr.h>
@ -172,6 +172,7 @@ class ESPBTClient : public ESPBTDeviceListener {
esp_ble_gattc_cb_param_t *param) = 0; esp_ble_gattc_cb_param_t *param) = 0;
virtual void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) = 0; virtual void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) = 0;
virtual void connect() = 0; virtual void connect() = 0;
virtual void disconnect() = 0;
virtual void set_state(ClientState st) { this->state_ = st; } virtual void set_state(ClientState st) { this->state_ = st; }
ClientState state() const { return state_; } ClientState state() const { return state_; }
int app_id; int app_id;

View File

@ -1,6 +1,9 @@
import logging
from dataclasses import dataclass from dataclasses import dataclass
import logging
from esphome import pins
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import ( from esphome.const import (
CONF_ANALOG, CONF_ANALOG,
CONF_ID, CONF_ID,
@ -14,10 +17,7 @@ from esphome.const import (
CONF_PULLUP, CONF_PULLUP,
PLATFORM_ESP8266, PLATFORM_ESP8266,
) )
from esphome import pins
from esphome.core import CORE, coroutine_with_priority from esphome.core import CORE, coroutine_with_priority
import esphome.config_validation as cv
import esphome.codegen as cg
from . import boards from . import boards
from .const import KEY_BOARD, KEY_ESP8266, KEY_PIN_INITIAL_STATES, esp8266_ns from .const import KEY_BOARD, KEY_ESP8266, KEY_PIN_INITIAL_STATES, esp8266_ns
@ -48,8 +48,10 @@ def _translate_pin(value):
"This variable only supports pin numbers, not full pin schemas " "This variable only supports pin numbers, not full pin schemas "
"(with inverted and mode)." "(with inverted and mode)."
) )
if isinstance(value, int): if isinstance(value, int) and not isinstance(value, bool):
return value return value
if not isinstance(value, str):
raise cv.Invalid(f"Invalid pin number: {value}")
try: try:
return int(value) return int(value)
except ValueError: except ValueError:

View File

@ -1,3 +1,4 @@
import logging
from esphome import pins from esphome import pins
import esphome.codegen as cg import esphome.codegen as cg
from esphome.components.esp32 import add_idf_sdkconfig_option, get_esp32_variant from esphome.components.esp32 import add_idf_sdkconfig_option, get_esp32_variant
@ -23,6 +24,7 @@ from esphome.const import (
CONF_MISO_PIN, CONF_MISO_PIN,
CONF_MOSI_PIN, CONF_MOSI_PIN,
CONF_PAGE_ID, CONF_PAGE_ID,
CONF_POLLING_INTERVAL,
CONF_RESET_PIN, CONF_RESET_PIN,
CONF_SPI, CONF_SPI,
CONF_STATIC_IP, CONF_STATIC_IP,
@ -30,13 +32,16 @@ from esphome.const import (
CONF_TYPE, CONF_TYPE,
CONF_USE_ADDRESS, CONF_USE_ADDRESS,
CONF_VALUE, CONF_VALUE,
KEY_CORE,
KEY_FRAMEWORK_VERSION,
) )
from esphome.core import CORE, coroutine_with_priority from esphome.core import CORE, TimePeriodMilliseconds, coroutine_with_priority
import esphome.final_validate as fv import esphome.final_validate as fv
CONFLICTS_WITH = ["wifi"] CONFLICTS_WITH = ["wifi"]
DEPENDENCIES = ["esp32"] DEPENDENCIES = ["esp32"]
AUTO_LOAD = ["network"] AUTO_LOAD = ["network"]
LOGGER = logging.getLogger(__name__)
ethernet_ns = cg.esphome_ns.namespace("ethernet") ethernet_ns = cg.esphome_ns.namespace("ethernet")
PHYRegister = ethernet_ns.struct("PHYRegister") PHYRegister = ethernet_ns.struct("PHYRegister")
@ -63,6 +68,7 @@ ETHERNET_TYPES = {
} }
SPI_ETHERNET_TYPES = ["W5500"] SPI_ETHERNET_TYPES = ["W5500"]
SPI_ETHERNET_DEFAULT_POLLING_INTERVAL = TimePeriodMilliseconds(milliseconds=10)
emac_rmii_clock_mode_t = cg.global_ns.enum("emac_rmii_clock_mode_t") emac_rmii_clock_mode_t = cg.global_ns.enum("emac_rmii_clock_mode_t")
emac_rmii_clock_gpio_t = cg.global_ns.enum("emac_rmii_clock_gpio_t") emac_rmii_clock_gpio_t = cg.global_ns.enum("emac_rmii_clock_gpio_t")
@ -100,6 +106,24 @@ EthernetComponent = ethernet_ns.class_("EthernetComponent", cg.Component)
ManualIP = ethernet_ns.struct("ManualIP") ManualIP = ethernet_ns.struct("ManualIP")
def _is_framework_spi_polling_mode_supported():
# SPI Ethernet without IRQ feature is added in
# esp-idf >= (5.3+ ,5.2.1+, 5.1.4) and arduino-esp32 >= 3.0.0
framework_version = CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION]
if CORE.using_esp_idf:
if framework_version >= cv.Version(5, 3, 0):
return True
if cv.Version(5, 3, 0) > framework_version >= cv.Version(5, 2, 1):
return True
if cv.Version(5, 2, 0) > framework_version >= cv.Version(5, 1, 4):
return True
return False
if CORE.using_arduino:
return framework_version >= cv.Version(3, 0, 0)
# fail safe: Unknown framework
return False
def _validate(config): def _validate(config):
if CONF_USE_ADDRESS not in config: if CONF_USE_ADDRESS not in config:
if CONF_MANUAL_IP in config: if CONF_MANUAL_IP in config:
@ -107,6 +131,27 @@ def _validate(config):
else: else:
use_address = CORE.name + config[CONF_DOMAIN] use_address = CORE.name + config[CONF_DOMAIN]
config[CONF_USE_ADDRESS] = use_address config[CONF_USE_ADDRESS] = use_address
if config[CONF_TYPE] in SPI_ETHERNET_TYPES:
if _is_framework_spi_polling_mode_supported():
if CONF_POLLING_INTERVAL in config and CONF_INTERRUPT_PIN in config:
raise cv.Invalid(
f"Cannot specify more than one of {CONF_INTERRUPT_PIN}, {CONF_POLLING_INTERVAL}"
)
if CONF_POLLING_INTERVAL not in config and CONF_INTERRUPT_PIN not in config:
config[CONF_POLLING_INTERVAL] = SPI_ETHERNET_DEFAULT_POLLING_INTERVAL
else:
if CONF_POLLING_INTERVAL in config:
raise cv.Invalid(
"In this version of the framework "
f"({CORE.target_framework} {CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION]}), "
f"'{CONF_POLLING_INTERVAL}' is not supported."
)
if CONF_INTERRUPT_PIN not in config:
raise cv.Invalid(
"In this version of the framework "
f"({CORE.target_framework} {CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION]}), "
f"'{CONF_INTERRUPT_PIN}' is a required option for [ethernet]."
)
return config return config
@ -157,6 +202,11 @@ SPI_SCHEMA = BASE_SCHEMA.extend(
cv.Optional(CONF_CLOCK_SPEED, default="26.67MHz"): cv.All( cv.Optional(CONF_CLOCK_SPEED, default="26.67MHz"): cv.All(
cv.frequency, cv.int_range(int(8e6), int(80e6)) cv.frequency, cv.int_range(int(8e6), int(80e6))
), ),
# Set default value (SPI_ETHERNET_DEFAULT_POLLING_INTERVAL) at _validate()
cv.Optional(CONF_POLLING_INTERVAL): cv.All(
cv.positive_time_period_milliseconds,
cv.Range(min=TimePeriodMilliseconds(milliseconds=1)),
),
} }
), ),
) )
@ -234,6 +284,10 @@ async def to_code(config):
cg.add(var.set_cs_pin(config[CONF_CS_PIN])) cg.add(var.set_cs_pin(config[CONF_CS_PIN]))
if CONF_INTERRUPT_PIN in config: if CONF_INTERRUPT_PIN in config:
cg.add(var.set_interrupt_pin(config[CONF_INTERRUPT_PIN])) cg.add(var.set_interrupt_pin(config[CONF_INTERRUPT_PIN]))
else:
cg.add(var.set_polling_interval(config[CONF_POLLING_INTERVAL]))
if _is_framework_spi_polling_mode_supported():
cg.add_define("USE_ETHERNET_SPI_POLLING_SUPPORT")
if CONF_RESET_PIN in config: if CONF_RESET_PIN in config:
cg.add(var.set_reset_pin(config[CONF_RESET_PIN])) cg.add(var.set_reset_pin(config[CONF_RESET_PIN]))
cg.add(var.set_clock_speed(config[CONF_CLOCK_SPEED])) cg.add(var.set_clock_speed(config[CONF_CLOCK_SPEED]))

View File

@ -116,6 +116,9 @@ void EthernetComponent::setup() {
eth_w5500_config_t w5500_config = ETH_W5500_DEFAULT_CONFIG(spi_handle); eth_w5500_config_t w5500_config = ETH_W5500_DEFAULT_CONFIG(spi_handle);
#endif #endif
w5500_config.int_gpio_num = this->interrupt_pin_; w5500_config.int_gpio_num = this->interrupt_pin_;
#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
w5500_config.poll_period_ms = this->polling_interval_;
#endif
phy_config.phy_addr = this->phy_addr_spi_; phy_config.phy_addr = this->phy_addr_spi_;
phy_config.reset_gpio_num = this->reset_pin_; phy_config.reset_gpio_num = this->reset_pin_;
@ -327,7 +330,14 @@ void EthernetComponent::dump_config() {
ESP_LOGCONFIG(TAG, " MISO Pin: %u", this->miso_pin_); ESP_LOGCONFIG(TAG, " MISO Pin: %u", this->miso_pin_);
ESP_LOGCONFIG(TAG, " MOSI Pin: %u", this->mosi_pin_); ESP_LOGCONFIG(TAG, " MOSI Pin: %u", this->mosi_pin_);
ESP_LOGCONFIG(TAG, " CS Pin: %u", this->cs_pin_); ESP_LOGCONFIG(TAG, " CS Pin: %u", this->cs_pin_);
ESP_LOGCONFIG(TAG, " IRQ Pin: %u", this->interrupt_pin_); #ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
if (this->polling_interval_ != 0) {
ESP_LOGCONFIG(TAG, " Polling Interval: %lu ms", this->polling_interval_);
} else
#endif
{
ESP_LOGCONFIG(TAG, " IRQ Pin: %d", this->interrupt_pin_);
}
ESP_LOGCONFIG(TAG, " Reset Pin: %d", this->reset_pin_); ESP_LOGCONFIG(TAG, " Reset Pin: %d", this->reset_pin_);
ESP_LOGCONFIG(TAG, " Clock Speed: %d MHz", this->clock_speed_ / 1000000); ESP_LOGCONFIG(TAG, " Clock Speed: %d MHz", this->clock_speed_ / 1000000);
#else #else
@ -536,6 +546,9 @@ void EthernetComponent::set_cs_pin(uint8_t cs_pin) { this->cs_pin_ = cs_pin; }
void EthernetComponent::set_interrupt_pin(uint8_t interrupt_pin) { this->interrupt_pin_ = interrupt_pin; } void EthernetComponent::set_interrupt_pin(uint8_t interrupt_pin) { this->interrupt_pin_ = interrupt_pin; }
void EthernetComponent::set_reset_pin(uint8_t reset_pin) { this->reset_pin_ = reset_pin; } void EthernetComponent::set_reset_pin(uint8_t reset_pin) { this->reset_pin_ = reset_pin; }
void EthernetComponent::set_clock_speed(int clock_speed) { this->clock_speed_ = clock_speed; } void EthernetComponent::set_clock_speed(int clock_speed) { this->clock_speed_ = clock_speed; }
#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
void EthernetComponent::set_polling_interval(uint32_t polling_interval) { this->polling_interval_ = polling_interval; }
#endif
#else #else
void EthernetComponent::set_phy_addr(uint8_t phy_addr) { this->phy_addr_ = phy_addr; } void EthernetComponent::set_phy_addr(uint8_t phy_addr) { this->phy_addr_ = phy_addr; }
void EthernetComponent::set_power_pin(int power_pin) { this->power_pin_ = power_pin; } void EthernetComponent::set_power_pin(int power_pin) { this->power_pin_ = power_pin; }

View File

@ -67,6 +67,9 @@ class EthernetComponent : public Component {
void set_interrupt_pin(uint8_t interrupt_pin); void set_interrupt_pin(uint8_t interrupt_pin);
void set_reset_pin(uint8_t reset_pin); void set_reset_pin(uint8_t reset_pin);
void set_clock_speed(int clock_speed); void set_clock_speed(int clock_speed);
#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
void set_polling_interval(uint32_t polling_interval);
#endif
#else #else
void set_phy_addr(uint8_t phy_addr); void set_phy_addr(uint8_t phy_addr);
void set_power_pin(int power_pin); void set_power_pin(int power_pin);
@ -108,10 +111,13 @@ class EthernetComponent : public Component {
uint8_t miso_pin_; uint8_t miso_pin_;
uint8_t mosi_pin_; uint8_t mosi_pin_;
uint8_t cs_pin_; uint8_t cs_pin_;
uint8_t interrupt_pin_; int interrupt_pin_{-1};
int reset_pin_{-1}; int reset_pin_{-1};
int phy_addr_spi_{-1}; int phy_addr_spi_{-1};
int clock_speed_; int clock_speed_;
#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
uint32_t polling_interval_{0};
#endif
#else #else
uint8_t phy_addr_{0}; uint8_t phy_addr_{0};
int power_pin_{-1}; int power_pin_{-1};

View File

@ -1,3 +1,4 @@
from collections.abc import Iterable
import functools import functools
import hashlib import hashlib
import logging import logging
@ -5,6 +6,8 @@ import os
from pathlib import Path from pathlib import Path
import re import re
import freetype
import glyphsets
from packaging import version from packaging import version
import requests import requests
@ -43,6 +46,18 @@ GlyphData = font_ns.struct("GlyphData")
CONF_BPP = "bpp" CONF_BPP = "bpp"
CONF_EXTRAS = "extras" CONF_EXTRAS = "extras"
CONF_FONTS = "fonts" CONF_FONTS = "fonts"
CONF_GLYPHSETS = "glyphsets"
CONF_IGNORE_MISSING_GLYPHS = "ignore_missing_glyphs"
# Cache loaded freetype fonts
class FontCache(dict):
def __missing__(self, key):
res = self[key] = freetype.Face(key)
return res
FONT_CACHE = FontCache()
def glyph_comparator(x, y): def glyph_comparator(x, y):
@ -59,36 +74,106 @@ def glyph_comparator(x, y):
return -1 return -1
if len(x_) > len(y_): if len(x_) > len(y_):
return 1 return 1
raise cv.Invalid(f"Found duplicate glyph {x}") return 0
def validate_glyphs(value): def flatten(lists) -> list:
if isinstance(value, list): """
value = cv.Schema([cv.string])(value) Given a list of lists, flatten it to a single list of all elements of all lists.
value = cv.Schema([cv.string])(list(value)) This wraps itertools.chain.from_iterable to make it more readable, and return a list
rather than a single use iterable.
"""
from itertools import chain
value.sort(key=functools.cmp_to_key(glyph_comparator)) return list(chain.from_iterable(lists))
return value
font_map = {} def check_missing_glyphs(file, codepoints: Iterable, warning: bool = False):
"""
Check that the given font file actually contains the requested glyphs
:param file: A Truetype font file
:param codepoints: A list of codepoints to check
:param warning: If true, log a warning instead of raising an exception
"""
font = FONT_CACHE[file]
def merge_glyphs(config): missing = [chr(x) for x in codepoints if font.get_char_index(x) == 0]
glyphs = [] if missing:
glyphs.extend(config[CONF_GLYPHS]) # Only list up to 10 missing glyphs
font_list = [(EFont(config[CONF_FILE], config[CONF_SIZE], config[CONF_GLYPHS]))] missing.sort(key=functools.cmp_to_key(glyph_comparator))
if extras := config.get(CONF_EXTRAS): count = len(missing)
extra_fonts = list( missing = missing[:10]
map( missing_str = "\n ".join(
lambda x: EFont(x[CONF_FILE], config[CONF_SIZE], x[CONF_GLYPHS]), extras f"{x} ({x.encode('unicode_escape')})" for x in missing
)
) )
font_list.extend(extra_fonts) if count > 10:
for extra in extras: missing_str += f"\n and {count - 10} more."
glyphs.extend(extra[CONF_GLYPHS]) message = f"Font {Path(file).name} is missing {count} glyph{'s' if count != 1 else ''}:\n {missing_str}"
validate_glyphs(glyphs) if warning:
font_map[config[CONF_ID]] = font_list _LOGGER.warning(message)
else:
raise cv.Invalid(message)
def validate_glyphs(config):
"""
Check for duplicate codepoints, then check that all requested codepoints actually
have glyphs defined in the appropriate font file.
"""
# Collect all glyph codepoints and flatten to a list of chars
glyphspoints = flatten(
[x[CONF_GLYPHS] for x in config[CONF_EXTRAS]] + config[CONF_GLYPHS]
)
# Convert a list of strings to a list of chars (one char strings)
glyphspoints = flatten([list(x) for x in glyphspoints])
if len(set(glyphspoints)) != len(glyphspoints):
duplicates = {x for x in glyphspoints if glyphspoints.count(x) > 1}
dup_str = ", ".join(f"{x} ({x.encode('unicode_escape')})" for x in duplicates)
raise cv.Invalid(
f"Found duplicate glyph{'s' if len(duplicates) != 1 else ''}: {dup_str}"
)
# convert to codepoints
glyphspoints = {ord(x) for x in glyphspoints}
fileconf = config[CONF_FILE]
setpoints = set(
flatten([glyphsets.unicodes_per_glyphset(x) for x in config[CONF_GLYPHSETS]])
)
# Make setpoints and glyphspoints disjoint
setpoints.difference_update(glyphspoints)
if fileconf[CONF_TYPE] == TYPE_LOCAL_BITMAP:
# Pillow only allows 256 glyphs per bitmap font. Not sure if that is a Pillow limitation
# or a file format limitation
if any(x >= 256 for x in setpoints.copy().union(glyphspoints)):
raise cv.Invalid("Codepoints in bitmap fonts must be in the range 0-255")
else:
# for TT fonts, check that glyphs are actually present
# Check extras against their own font, exclude from parent font codepoints
for extra in config[CONF_EXTRAS]:
points = {ord(x) for x in flatten(extra[CONF_GLYPHS])}
glyphspoints.difference_update(points)
setpoints.difference_update(points)
check_missing_glyphs(extra[CONF_FILE][CONF_PATH], points)
# A named glyph that can't be provided is an error
check_missing_glyphs(fileconf[CONF_PATH], glyphspoints)
# A missing glyph from a set is a warning.
if not config[CONF_IGNORE_MISSING_GLYPHS]:
check_missing_glyphs(fileconf[CONF_PATH], setpoints, warning=True)
# Populate the default after the above checks so that use of the default doesn't trigger errors
if not config[CONF_GLYPHS] and not config[CONF_GLYPHSETS]:
if fileconf[CONF_TYPE] == TYPE_LOCAL_BITMAP:
config[CONF_GLYPHS] = [DEFAULT_GLYPHS]
else:
# set a default glyphset, intersected with what the font actually offers
font = FONT_CACHE[fileconf[CONF_PATH]]
config[CONF_GLYPHS] = [
chr(x)
for x in glyphsets.unicodes_per_glyphset(DEFAULT_GLYPHSET)
if font.get_char_index(x) != 0
]
return config return config
@ -120,7 +205,7 @@ def validate_truetype_file(value):
) )
if not any(map(value.lower().endswith, FONT_EXTENSIONS)): if not any(map(value.lower().endswith, FONT_EXTENSIONS)):
raise cv.Invalid(f"Only {FONT_EXTENSIONS} files are supported.") raise cv.Invalid(f"Only {FONT_EXTENSIONS} files are supported.")
return cv.file_(value) return CORE.relative_config_path(cv.file_(value))
TYPE_LOCAL = "local" TYPE_LOCAL = "local"
@ -139,6 +224,10 @@ LOCAL_BITMAP_SCHEMA = cv.Schema(
} }
) )
FULLPATH_SCHEMA = cv.maybe_simple_value(
{cv.Required(CONF_PATH): cv.string}, key=CONF_PATH
)
CONF_ITALIC = "italic" CONF_ITALIC = "italic"
FONT_WEIGHTS = { FONT_WEIGHTS = {
"thin": 100, "thin": 100,
@ -167,13 +256,13 @@ def _compute_local_font_path(value: dict) -> Path:
return base_dir / key return base_dir / key
def get_font_path(value, type) -> Path: def get_font_path(value, font_type) -> Path:
if type == TYPE_GFONTS: if font_type == TYPE_GFONTS:
name = f"{value[CONF_FAMILY]}@{value[CONF_WEIGHT]}@{value[CONF_ITALIC]}@v1" name = f"{value[CONF_FAMILY]}@{value[CONF_WEIGHT]}@{value[CONF_ITALIC]}@v1"
return external_files.compute_local_file_dir(DOMAIN) / f"{name}.ttf" return external_files.compute_local_file_dir(DOMAIN) / f"{name}.ttf"
if type == TYPE_WEB: if font_type == TYPE_WEB:
return _compute_local_font_path(value) / "font.ttf" return _compute_local_font_path(value) / "font.ttf"
return None assert False
def download_gfont(value): def download_gfont(value):
@ -203,7 +292,7 @@ def download_gfont(value):
_LOGGER.debug("download_gfont: ttf_url=%s", ttf_url) _LOGGER.debug("download_gfont: ttf_url=%s", ttf_url)
external_files.download_content(ttf_url, path) external_files.download_content(ttf_url, path)
return value return FULLPATH_SCHEMA(path)
def download_web_font(value): def download_web_font(value):
@ -212,7 +301,7 @@ def download_web_font(value):
external_files.download_content(url, path) external_files.download_content(url, path)
_LOGGER.debug("download_web_font: path=%s", path) _LOGGER.debug("download_web_font: path=%s", path)
return value return FULLPATH_SCHEMA(path)
EXTERNAL_FONT_SCHEMA = cv.Schema( EXTERNAL_FONT_SCHEMA = cv.Schema(
@ -225,7 +314,6 @@ EXTERNAL_FONT_SCHEMA = cv.Schema(
} }
) )
GFONTS_SCHEMA = cv.All( GFONTS_SCHEMA = cv.All(
EXTERNAL_FONT_SCHEMA.extend( EXTERNAL_FONT_SCHEMA.extend(
{ {
@ -259,10 +347,10 @@ def validate_file_shorthand(value):
} }
if weight is not None: if weight is not None:
data[CONF_WEIGHT] = weight[1:] data[CONF_WEIGHT] = weight[1:]
return FILE_SCHEMA(data) return font_file_schema(data)
if value.startswith("http://") or value.startswith("https://"): if value.startswith("http://") or value.startswith("https://"):
return FILE_SCHEMA( return font_file_schema(
{ {
CONF_TYPE: TYPE_WEB, CONF_TYPE: TYPE_WEB,
CONF_URL: value, CONF_URL: value,
@ -270,14 +358,15 @@ def validate_file_shorthand(value):
) )
if value.endswith(".pcf") or value.endswith(".bdf"): if value.endswith(".pcf") or value.endswith(".bdf"):
return FILE_SCHEMA( value = convert_bitmap_to_pillow_font(
{ CORE.relative_config_path(cv.file_(value))
CONF_TYPE: TYPE_LOCAL_BITMAP,
CONF_PATH: value,
}
) )
return {
CONF_TYPE: TYPE_LOCAL_BITMAP,
CONF_PATH: value,
}
return FILE_SCHEMA( return font_file_schema(
{ {
CONF_TYPE: TYPE_LOCAL, CONF_TYPE: TYPE_LOCAL,
CONF_PATH: value, CONF_PATH: value,
@ -295,31 +384,35 @@ TYPED_FILE_SCHEMA = cv.typed_schema(
) )
def _file_schema(value): def font_file_schema(value):
if isinstance(value, str): if isinstance(value, str):
return validate_file_shorthand(value) return validate_file_shorthand(value)
return TYPED_FILE_SCHEMA(value) return TYPED_FILE_SCHEMA(value)
FILE_SCHEMA = cv.All(_file_schema) # Default if no glyphs or glyphsets are provided
DEFAULT_GLYPHSET = "GF_Latin_Kernel"
# default for bitmap fonts
DEFAULT_GLYPHS = ' !"%()+=,-.:/?0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz<C2><B0>'
DEFAULT_GLYPHS = (
' !"%()+=,-.:/?0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz°'
)
CONF_RAW_GLYPH_ID = "raw_glyph_id" CONF_RAW_GLYPH_ID = "raw_glyph_id"
FONT_SCHEMA = cv.Schema( FONT_SCHEMA = cv.Schema(
{ {
cv.Required(CONF_ID): cv.declare_id(Font), cv.Required(CONF_ID): cv.declare_id(Font),
cv.Required(CONF_FILE): FILE_SCHEMA, cv.Required(CONF_FILE): font_file_schema,
cv.Optional(CONF_GLYPHS, default=DEFAULT_GLYPHS): validate_glyphs, cv.Optional(CONF_GLYPHS, default=[]): cv.ensure_list(cv.string_strict),
cv.Optional(CONF_GLYPHSETS, default=[]): cv.ensure_list(
cv.one_of(*glyphsets.defined_glyphsets())
),
cv.Optional(CONF_IGNORE_MISSING_GLYPHS, default=False): cv.boolean,
cv.Optional(CONF_SIZE, default=20): cv.int_range(min=1), cv.Optional(CONF_SIZE, default=20): cv.int_range(min=1),
cv.Optional(CONF_BPP, default=1): cv.one_of(1, 2, 4, 8), cv.Optional(CONF_BPP, default=1): cv.one_of(1, 2, 4, 8),
cv.Optional(CONF_EXTRAS): cv.ensure_list( cv.Optional(CONF_EXTRAS, default=[]): cv.ensure_list(
cv.Schema( cv.Schema(
{ {
cv.Required(CONF_FILE): FILE_SCHEMA, cv.Required(CONF_FILE): font_file_schema,
cv.Required(CONF_GLYPHS): validate_glyphs, cv.Required(CONF_GLYPHS): cv.ensure_list(cv.string_strict),
} }
) )
), ),
@ -328,7 +421,7 @@ FONT_SCHEMA = cv.Schema(
}, },
) )
CONFIG_SCHEMA = cv.All(validate_pillow_installed, FONT_SCHEMA, merge_glyphs) CONFIG_SCHEMA = cv.All(validate_pillow_installed, FONT_SCHEMA, validate_glyphs)
# PIL doesn't provide a consistent interface for both TrueType and bitmap # PIL doesn't provide a consistent interface for both TrueType and bitmap
@ -344,7 +437,7 @@ class TrueTypeFontWrapper:
return offset_x, offset_y return offset_x, offset_y
def getmask(self, glyph, **kwargs): def getmask(self, glyph, **kwargs):
return self.font.getmask(glyph, **kwargs) return self.font.getmask(str(glyph), **kwargs)
def getmetrics(self, glyphs): def getmetrics(self, glyphs):
return self.font.getmetrics() return self.font.getmetrics()
@ -359,7 +452,7 @@ class BitmapFontWrapper:
return 0, 0 return 0, 0
def getmask(self, glyph, **kwargs): def getmask(self, glyph, **kwargs):
return self.font.getmask(glyph, **kwargs) return self.font.getmask(str(glyph), **kwargs)
def getmetrics(self, glyphs): def getmetrics(self, glyphs):
max_height = 0 max_height = 0
@ -367,28 +460,20 @@ class BitmapFontWrapper:
mask = self.getmask(glyph, mode="1") mask = self.getmask(glyph, mode="1")
_, height = mask.size _, height = mask.size
max_height = max(max_height, height) max_height = max(max_height, height)
return (max_height, 0) return max_height, 0
class EFont: class EFont:
def __init__(self, file, size, glyphs): def __init__(self, file, size, codepoints):
self.glyphs = glyphs self.codepoints = codepoints
path = file[CONF_PATH]
self.name = Path(path).name
ftype = file[CONF_TYPE] ftype = file[CONF_TYPE]
if ftype == TYPE_LOCAL_BITMAP: if ftype == TYPE_LOCAL_BITMAP:
font = load_bitmap_font(CORE.relative_config_path(file[CONF_PATH])) self.font = load_bitmap_font(path)
elif ftype == TYPE_LOCAL:
path = CORE.relative_config_path(file[CONF_PATH])
font = load_ttf_font(path, size)
elif ftype in (TYPE_GFONTS, TYPE_WEB):
path = get_font_path(file, ftype)
font = load_ttf_font(path, size)
else: else:
raise cv.Invalid(f"Could not load font: unknown type: {ftype}") self.font = load_ttf_font(path, size)
self.font = font self.ascent, self.descent = self.font.getmetrics(codepoints)
self.ascent, self.descent = font.getmetrics(glyphs)
def has_glyph(self, glyph):
return glyph in self.glyphs
def convert_bitmap_to_pillow_font(filepath): def convert_bitmap_to_pillow_font(filepath):
@ -400,6 +485,7 @@ def convert_bitmap_to_pillow_font(filepath):
copy_file_if_changed(filepath, local_bitmap_font_file) copy_file_if_changed(filepath, local_bitmap_font_file)
local_pil_font_file = local_bitmap_font_file.with_suffix(".pil")
with open(local_bitmap_font_file, "rb") as fp: with open(local_bitmap_font_file, "rb") as fp:
try: try:
try: try:
@ -409,28 +495,22 @@ def convert_bitmap_to_pillow_font(filepath):
p = BdfFontFile.BdfFontFile(fp) p = BdfFontFile.BdfFontFile(fp)
# Convert to pillow-formatted fonts, which have a .pil and .pbm extension. # Convert to pillow-formatted fonts, which have a .pil and .pbm extension.
p.save(local_bitmap_font_file) p.save(local_pil_font_file)
except (SyntaxError, OSError) as err: except (SyntaxError, OSError) as err:
raise core.EsphomeError( raise core.EsphomeError(
f"Failed to parse as bitmap font: '{filepath}': {err}" f"Failed to parse as bitmap font: '{filepath}': {err}"
) )
local_pil_font_file = os.path.splitext(local_bitmap_font_file)[0] + ".pil" return str(local_pil_font_file)
return cv.file_(local_pil_font_file)
def load_bitmap_font(filepath): def load_bitmap_font(filepath):
from PIL import ImageFont from PIL import ImageFont
# Convert bpf and pcf files to pillow fonts, first.
pil_font_path = convert_bitmap_to_pillow_font(filepath)
try: try:
font = ImageFont.load(str(pil_font_path)) font = ImageFont.load(str(filepath))
except Exception as e: except Exception as e:
raise core.EsphomeError( raise core.EsphomeError(f"Failed to load bitmap font file: {filepath}: {e}")
f"Failed to load bitmap font file: {pil_font_path} : {e}"
)
return BitmapFontWrapper(font) return BitmapFontWrapper(font)
@ -441,7 +521,7 @@ def load_ttf_font(path, size):
try: try:
font = ImageFont.truetype(str(path), size) font = ImageFont.truetype(str(path), size)
except Exception as e: except Exception as e:
raise core.EsphomeError(f"Could not load truetype file {path}: {e}") raise core.EsphomeError(f"Could not load TrueType file {path}: {e}")
return TrueTypeFontWrapper(font) return TrueTypeFontWrapper(font)
@ -456,14 +536,35 @@ class GlyphInfo:
async def to_code(config): async def to_code(config):
glyph_to_font_map = {} """
font_list = font_map[config[CONF_ID]] Collect all glyph codepoints, construct a map from a codepoint to a font file.
glyphs = [] Codepoints are either explicit (glyphs key in top level or extras) or part of a glyphset.
for font in font_list: Codepoints listed in extras use the extra font and override codepoints from glyphsets.
glyphs.extend(font.glyphs) Achieve this by processing the base codepoints first, then the extras
for glyph in font.glyphs: """
glyph_to_font_map[glyph] = font
glyphs.sort(key=functools.cmp_to_key(glyph_comparator)) # get the codepoints from glyphsets and flatten to a set of chrs.
point_set: set[str] = {
chr(x)
for x in flatten(
[glyphsets.unicodes_per_glyphset(x) for x in config[CONF_GLYPHSETS]]
)
}
# get the codepoints from the glyphs key, flatten to a list of chrs and combine with the points from glyphsets
point_set.update(flatten(config[CONF_GLYPHS]))
size = config[CONF_SIZE]
# Create the codepoint to font file map
base_font = EFont(config[CONF_FILE], size, point_set)
point_font_map: dict[str, EFont] = {c: base_font for c in point_set}
# process extras, updating the map and extending the codepoint list
for extra in config[CONF_EXTRAS]:
extra_points = flatten(extra[CONF_GLYPHS])
point_set.update(extra_points)
extra_font = EFont(extra[CONF_FILE], size, extra_points)
point_font_map.update({c: extra_font for c in extra_points})
codepoints = list(point_set)
codepoints.sort(key=functools.cmp_to_key(glyph_comparator))
glyph_args = {} glyph_args = {}
data = [] data = []
bpp = config[CONF_BPP] bpp = config[CONF_BPP]
@ -473,10 +574,11 @@ async def to_code(config):
else: else:
mode = "L" mode = "L"
scale = 256 // (1 << bpp) scale = 256 // (1 << bpp)
for glyph in glyphs: # create the data array for all glyphs
font = glyph_to_font_map[glyph].font for codepoint in codepoints:
mask = font.getmask(glyph, mode=mode) font = point_font_map[codepoint]
offset_x, offset_y = font.getoffset(glyph) mask = font.font.getmask(codepoint, mode=mode)
offset_x, offset_y = font.font.getoffset(codepoint)
width, height = mask.size width, height = mask.size
glyph_data = [0] * ((height * width * bpp + 7) // 8) glyph_data = [0] * ((height * width * bpp + 7) // 8)
pos = 0 pos = 0
@ -487,31 +589,34 @@ async def to_code(config):
if pixel & (1 << (bpp - bit_num - 1)): if pixel & (1 << (bpp - bit_num - 1)):
glyph_data[pos // 8] |= 0x80 >> (pos % 8) glyph_data[pos // 8] |= 0x80 >> (pos % 8)
pos += 1 pos += 1
glyph_args[glyph] = GlyphInfo(len(data), offset_x, offset_y, width, height) glyph_args[codepoint] = GlyphInfo(len(data), offset_x, offset_y, width, height)
data += glyph_data data += glyph_data
rhs = [HexInt(x) for x in data] rhs = [HexInt(x) for x in data]
prog_arr = cg.progmem_array(config[CONF_RAW_DATA_ID], rhs) prog_arr = cg.progmem_array(config[CONF_RAW_DATA_ID], rhs)
# Create the glyph table that points to data in the above array.
glyph_initializer = [] glyph_initializer = []
for glyph in glyphs: for codepoint in codepoints:
glyph_initializer.append( glyph_initializer.append(
cg.StructInitializer( cg.StructInitializer(
GlyphData, GlyphData,
( (
"a_char", "a_char",
cg.RawExpression(f"(const uint8_t *){cpp_string_escape(glyph)}"), cg.RawExpression(
f"(const uint8_t *){cpp_string_escape(codepoint)}"
),
), ),
( (
"data", "data",
cg.RawExpression( cg.RawExpression(
f"{str(prog_arr)} + {str(glyph_args[glyph].data_len)}" f"{str(prog_arr)} + {str(glyph_args[codepoint].data_len)}"
), ),
), ),
("offset_x", glyph_args[glyph].offset_x), ("offset_x", glyph_args[codepoint].offset_x),
("offset_y", glyph_args[glyph].offset_y), ("offset_y", glyph_args[codepoint].offset_y),
("width", glyph_args[glyph].width), ("width", glyph_args[codepoint].width),
("height", glyph_args[glyph].height), ("height", glyph_args[codepoint].height),
) )
) )
@ -521,7 +626,7 @@ async def to_code(config):
config[CONF_ID], config[CONF_ID],
glyphs, glyphs,
len(glyph_initializer), len(glyph_initializer),
font_list[0].ascent, base_font.ascent,
font_list[0].ascent + font_list[0].descent, base_font.ascent + base_font.descent,
bpp, bpp,
) )

View File

@ -1,5 +1,8 @@
import logging import logging
from esphome import pins
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import ( from esphome.const import (
CONF_ID, CONF_ID,
CONF_INPUT, CONF_INPUT,
@ -11,9 +14,6 @@ from esphome.const import (
CONF_PULLDOWN, CONF_PULLDOWN,
CONF_PULLUP, CONF_PULLUP,
) )
from esphome import pins
import esphome.config_validation as cv
import esphome.codegen as cg
from .const import host_ns from .const import host_ns
@ -28,8 +28,10 @@ def _translate_pin(value):
"This variable only supports pin numbers, not full pin schemas " "This variable only supports pin numbers, not full pin schemas "
"(with inverted and mode)." "(with inverted and mode)."
) )
if isinstance(value, int): if isinstance(value, int) and not isinstance(value, bool):
return value return value
if not isinstance(value, str):
raise cv.Invalid(f"Invalid pin number: {value}")
try: try:
return int(value) return int(value)
except ValueError: except ValueError:

View File

@ -6,6 +6,7 @@ from esphome.const import (
CONF_ESP8266_DISABLE_SSL_SUPPORT, CONF_ESP8266_DISABLE_SSL_SUPPORT,
CONF_ID, CONF_ID,
CONF_METHOD, CONF_METHOD,
CONF_ON_ERROR,
CONF_TIMEOUT, CONF_TIMEOUT,
CONF_TRIGGER_ID, CONF_TRIGGER_ID,
CONF_URL, CONF_URL,
@ -185,6 +186,13 @@ HTTP_REQUEST_ACTION_SCHEMA = cv.Schema(
cv.Optional(CONF_ON_RESPONSE): automation.validate_automation( cv.Optional(CONF_ON_RESPONSE): automation.validate_automation(
{cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(HttpRequestResponseTrigger)} {cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(HttpRequestResponseTrigger)}
), ),
cv.Optional(CONF_ON_ERROR): automation.validate_automation(
{
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(
automation.Trigger.template()
)
}
),
cv.Optional(CONF_MAX_RESPONSE_BUFFER_SIZE, default="1kB"): cv.validate_bytes, cv.Optional(CONF_MAX_RESPONSE_BUFFER_SIZE, default="1kB"): cv.validate_bytes,
} }
) )
@ -272,5 +280,9 @@ async def http_request_action_to_code(config, action_id, template_arg, args):
], ],
conf, conf,
) )
for conf in config.get(CONF_ON_ERROR, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID])
cg.add(var.register_error_trigger(trigger))
await automation.build_automation(trigger, [], conf)
return var return var

View File

@ -22,6 +22,63 @@ struct Header {
const char *value; const char *value;
}; };
// Some common HTTP status codes
enum HttpStatus {
HTTP_STATUS_OK = 200,
HTTP_STATUS_NO_CONTENT = 204,
HTTP_STATUS_PARTIAL_CONTENT = 206,
/* 3xx - Redirection */
HTTP_STATUS_MULTIPLE_CHOICES = 300,
HTTP_STATUS_MOVED_PERMANENTLY = 301,
HTTP_STATUS_FOUND = 302,
HTTP_STATUS_SEE_OTHER = 303,
HTTP_STATUS_NOT_MODIFIED = 304,
HTTP_STATUS_TEMPORARY_REDIRECT = 307,
HTTP_STATUS_PERMANENT_REDIRECT = 308,
/* 4XX - CLIENT ERROR */
HTTP_STATUS_BAD_REQUEST = 400,
HTTP_STATUS_UNAUTHORIZED = 401,
HTTP_STATUS_FORBIDDEN = 403,
HTTP_STATUS_NOT_FOUND = 404,
HTTP_STATUS_METHOD_NOT_ALLOWED = 405,
HTTP_STATUS_NOT_ACCEPTABLE = 406,
HTTP_STATUS_LENGTH_REQUIRED = 411,
/* 5xx - Server Error */
HTTP_STATUS_INTERNAL_ERROR = 500
};
/**
* @brief Returns true if the HTTP status code is a redirect.
*
* @param status the HTTP status code to check
* @return true if the status code is a redirect, false otherwise
*/
inline bool is_redirect(int const status) {
switch (status) {
case HTTP_STATUS_MOVED_PERMANENTLY:
case HTTP_STATUS_FOUND:
case HTTP_STATUS_SEE_OTHER:
case HTTP_STATUS_TEMPORARY_REDIRECT:
case HTTP_STATUS_PERMANENT_REDIRECT:
return true;
default:
return false;
}
}
/**
* @brief Checks if the given HTTP status code indicates a successful request.
*
* A successful request is one where the status code is in the range 200-299
*
* @param status the HTTP status code to check
* @return true if the status code indicates a successful request, false otherwise
*/
inline bool is_success(int const status) { return status >= HTTP_STATUS_OK && status < HTTP_STATUS_MULTIPLE_CHOICES; }
class HttpRequestComponent; class HttpRequestComponent;
class HttpContainer : public Parented<HttpRequestComponent> { class HttpContainer : public Parented<HttpRequestComponent> {
@ -78,8 +135,8 @@ class HttpRequestComponent : public Component {
protected: protected:
const char *useragent_{nullptr}; const char *useragent_{nullptr};
bool follow_redirects_; bool follow_redirects_{};
uint16_t redirect_limit_; uint16_t redirect_limit_{};
uint16_t timeout_{4500}; uint16_t timeout_{4500};
uint32_t watchdog_timeout_{0}; uint32_t watchdog_timeout_{0};
}; };
@ -100,6 +157,8 @@ template<typename... Ts> class HttpRequestSendAction : public Action<Ts...> {
void register_response_trigger(HttpRequestResponseTrigger *trigger) { this->response_triggers_.push_back(trigger); } void register_response_trigger(HttpRequestResponseTrigger *trigger) { this->response_triggers_.push_back(trigger); }
void register_error_trigger(Trigger<> *trigger) { this->error_triggers_.push_back(trigger); }
void set_max_response_buffer_size(size_t max_response_buffer_size) { void set_max_response_buffer_size(size_t max_response_buffer_size) {
this->max_response_buffer_size_ = max_response_buffer_size; this->max_response_buffer_size_ = max_response_buffer_size;
} }
@ -129,6 +188,8 @@ template<typename... Ts> class HttpRequestSendAction : public Action<Ts...> {
auto container = this->parent_->start(this->url_.value(x...), this->method_.value(x...), body, headers); auto container = this->parent_->start(this->url_.value(x...), this->method_.value(x...), body, headers);
if (container == nullptr) { if (container == nullptr) {
for (auto *trigger : this->error_triggers_)
trigger->trigger(x...);
return; return;
} }
@ -180,7 +241,8 @@ template<typename... Ts> class HttpRequestSendAction : public Action<Ts...> {
std::map<const char *, TemplatableValue<const char *, Ts...>> headers_{}; std::map<const char *, TemplatableValue<const char *, Ts...>> headers_{};
std::map<const char *, TemplatableValue<std::string, Ts...>> json_{}; std::map<const char *, TemplatableValue<std::string, Ts...>> json_{};
std::function<void(Ts..., JsonObject)> json_func_{nullptr}; std::function<void(Ts..., JsonObject)> json_func_{nullptr};
std::vector<HttpRequestResponseTrigger *> response_triggers_; std::vector<HttpRequestResponseTrigger *> response_triggers_{};
std::vector<Trigger<> *> error_triggers_{};
size_t max_response_buffer_size_{SIZE_MAX}; size_t max_response_buffer_size_{SIZE_MAX};
}; };

View File

@ -113,11 +113,10 @@ std::shared_ptr<HttpContainer> HttpRequestArduino::start(std::string url, std::s
return nullptr; return nullptr;
} }
if (container->status_code < 200 || container->status_code >= 300) { if (!is_success(container->status_code)) {
ESP_LOGE(TAG, "HTTP Request failed; URL: %s; Code: %d", url.c_str(), container->status_code); ESP_LOGE(TAG, "HTTP Request failed; URL: %s; Code: %d", url.c_str(), container->status_code);
this->status_momentary_error("failed", 1000); this->status_momentary_error("failed", 1000);
container->end(); // Still return the container, so it can be used to get the status code and error message
return nullptr;
} }
int content_length = container->client_.getSize(); int content_length = container->client_.getSize();

View File

@ -6,7 +6,6 @@
#include "esphome/components/watchdog/watchdog.h" #include "esphome/components/watchdog/watchdog.h"
#include "esphome/core/application.h" #include "esphome/core/application.h"
#include "esphome/core/defines.h"
#include "esphome/core/log.h" #include "esphome/core/log.h"
#if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE #if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
@ -118,20 +117,14 @@ std::shared_ptr<HttpContainer> HttpRequestIDF::start(std::string url, std::strin
return nullptr; return nullptr;
} }
auto is_ok = [](int code) { return code >= HttpStatus_Ok && code < HttpStatus_MultipleChoices; };
container->content_length = esp_http_client_fetch_headers(client); container->content_length = esp_http_client_fetch_headers(client);
container->status_code = esp_http_client_get_status_code(client); container->status_code = esp_http_client_get_status_code(client);
if (is_ok(container->status_code)) { if (is_success(container->status_code)) {
container->duration_ms = millis() - start; container->duration_ms = millis() - start;
return container; return container;
} }
if (this->follow_redirects_) { if (this->follow_redirects_) {
auto is_redirect = [](int code) {
return code == HttpStatus_MovedPermanently || code == HttpStatus_Found || code == HttpStatus_SeeOther ||
code == HttpStatus_TemporaryRedirect || code == HttpStatus_PermanentRedirect;
};
auto num_redirects = this->redirect_limit_; auto num_redirects = this->redirect_limit_;
while (is_redirect(container->status_code) && num_redirects > 0) { while (is_redirect(container->status_code) && num_redirects > 0) {
err = esp_http_client_set_redirection(client); err = esp_http_client_set_redirection(client);
@ -142,9 +135,9 @@ std::shared_ptr<HttpContainer> HttpRequestIDF::start(std::string url, std::strin
return nullptr; return nullptr;
} }
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE #if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char url[256]{}; char redirect_url[256]{};
if (esp_http_client_get_url(client, url, sizeof(url) - 1) == ESP_OK) { if (esp_http_client_get_url(client, redirect_url, sizeof(redirect_url) - 1) == ESP_OK) {
ESP_LOGV(TAG, "redirecting to url: %s", url); ESP_LOGV(TAG, "redirecting to url: %s", redirect_url);
} }
#endif #endif
err = esp_http_client_open(client, 0); err = esp_http_client_open(client, 0);
@ -157,7 +150,7 @@ std::shared_ptr<HttpContainer> HttpRequestIDF::start(std::string url, std::strin
container->content_length = esp_http_client_fetch_headers(client); container->content_length = esp_http_client_fetch_headers(client);
container->status_code = esp_http_client_get_status_code(client); container->status_code = esp_http_client_get_status_code(client);
if (is_ok(container->status_code)) { if (is_success(container->status_code)) {
container->duration_ms = millis() - start; container->duration_ms = millis() - start;
return container; return container;
} }
@ -172,8 +165,7 @@ std::shared_ptr<HttpContainer> HttpRequestIDF::start(std::string url, std::strin
ESP_LOGE(TAG, "HTTP Request failed; URL: %s; Code: %d", url.c_str(), container->status_code); ESP_LOGE(TAG, "HTTP Request failed; URL: %s; Code: %d", url.c_str(), container->status_code);
this->status_momentary_error("failed", 1000); this->status_momentary_error("failed", 1000);
esp_http_client_cleanup(client); return container;
return nullptr;
} }
int HttpContainerIDF::read(uint8_t *buf, size_t max_len) { int HttpContainerIDF::read(uint8_t *buf, size_t max_len) {

View File

@ -106,7 +106,7 @@ uint8_t OtaHttpRequestComponent::do_ota_() {
auto container = this->parent_->get(url_with_auth); auto container = this->parent_->get(url_with_auth);
if (container == nullptr) { if (container == nullptr || container->status_code != HTTP_STATUS_OK) {
return OTA_CONNECTION_ERROR; return OTA_CONNECTION_ERROR;
} }

View File

@ -31,7 +31,7 @@ void HttpRequestUpdate::setup() {
void HttpRequestUpdate::update() { void HttpRequestUpdate::update() {
auto container = this->request_parent_->get(this->source_url_); auto container = this->request_parent_->get(this->source_url_);
if (container == nullptr) { if (container == nullptr || container->status_code != HTTP_STATUS_OK) {
std::string msg = str_sprintf("Failed to fetch manifest from %s", this->source_url_.c_str()); std::string msg = str_sprintf("Failed to fetch manifest from %s", this->source_url_.c_str());
this->status_set_error(msg.c_str()); this->status_set_error(msg.c_str());
return; return;

View File

@ -8,7 +8,7 @@ from esphome.components.esp32.const import (
VARIANT_ESP32S3, VARIANT_ESP32S3,
) )
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome.const import CONF_CHANNEL, CONF_ID, CONF_SAMPLE_RATE from esphome.const import CONF_BITS_PER_SAMPLE, CONF_CHANNEL, CONF_ID, CONF_SAMPLE_RATE
from esphome.cpp_generator import MockObjClass from esphome.cpp_generator import MockObjClass
import esphome.final_validate as fv import esphome.final_validate as fv
@ -25,13 +25,11 @@ CONF_I2S_LRCLK_PIN = "i2s_lrclk_pin"
CONF_I2S_AUDIO = "i2s_audio" CONF_I2S_AUDIO = "i2s_audio"
CONF_I2S_AUDIO_ID = "i2s_audio_id" CONF_I2S_AUDIO_ID = "i2s_audio_id"
CONF_BITS_PER_SAMPLE = "bits_per_sample"
CONF_I2S_MODE = "i2s_mode" CONF_I2S_MODE = "i2s_mode"
CONF_PRIMARY = "primary" CONF_PRIMARY = "primary"
CONF_SECONDARY = "secondary" CONF_SECONDARY = "secondary"
CONF_USE_APLL = "use_apll" CONF_USE_APLL = "use_apll"
CONF_BITS_PER_SAMPLE = "bits_per_sample"
CONF_BITS_PER_CHANNEL = "bits_per_channel" CONF_BITS_PER_CHANNEL = "bits_per_channel"
CONF_MONO = "mono" CONF_MONO = "mono"
CONF_LEFT = "left" CONF_LEFT = "left"

View File

@ -196,6 +196,10 @@ CONFIG_SCHEMA = cv.All(
_validate, _validate,
) )
FINAL_VALIDATE_SCHEMA = spi.final_validate_device_schema(
"ili9xxx", require_miso=False, require_mosi=True
)
async def to_code(config): async def to_code(config):
rhs = MODELS[config[CONF_MODEL]].new() rhs = MODELS[config[CONF_MODEL]].new()

View File

@ -1,8 +1,8 @@
import logging import logging
from esphome import pins
import esphome.codegen as cg import esphome.codegen as cg
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome import pins
from esphome.const import ( from esphome.const import (
CONF_ANALOG, CONF_ANALOG,
CONF_ID, CONF_ID,
@ -103,8 +103,10 @@ def _translate_pin(value):
"This variable only supports pin numbers, not full pin schemas " "This variable only supports pin numbers, not full pin schemas "
"(with inverted and mode)." "(with inverted and mode)."
) )
if isinstance(value, int): if isinstance(value, int) and not isinstance(value, bool):
return value return value
if not isinstance(value, str):
raise cv.Invalid(f"Invalid pin number: {value}")
try: try:
return int(value) return int(value)
except ValueError: except ValueError:

View File

@ -71,6 +71,7 @@ from .widgets.meter import meter_spec
from .widgets.msgbox import MSGBOX_SCHEMA, msgboxes_to_code from .widgets.msgbox import MSGBOX_SCHEMA, msgboxes_to_code
from .widgets.obj import obj_spec from .widgets.obj import obj_spec
from .widgets.page import add_pages, generate_page_triggers, page_spec from .widgets.page import add_pages, generate_page_triggers, page_spec
from .widgets.qrcode import qr_code_spec
from .widgets.roller import roller_spec from .widgets.roller import roller_spec
from .widgets.slider import slider_spec from .widgets.slider import slider_spec
from .widgets.spinbox import spinbox_spec from .widgets.spinbox import spinbox_spec
@ -109,6 +110,7 @@ for w_type in (
spinbox_spec, spinbox_spec,
keyboard_spec, keyboard_spec,
tileview_spec, tileview_spec,
qr_code_spec,
): ):
WIDGET_TYPES[w_type.name] = w_type WIDGET_TYPES[w_type.name] = w_type

View File

@ -391,7 +391,9 @@ def container_validator(schema, widget_type: WidgetType):
add_lv_use(ltype) add_lv_use(ltype)
if value == SCHEMA_EXTRACT: if value == SCHEMA_EXTRACT:
return result return result
result = result.extend(LAYOUT_SCHEMAS[ltype.lower()]) result = result.extend(
LAYOUT_SCHEMAS.get(ltype.lower(), LAYOUT_SCHEMAS[df.TYPE_NONE])
)
return result(value) return result(value)
return validator return validator

View File

@ -60,9 +60,10 @@ class AnimimgType(WidgetType):
lvgl_components_required.add(CONF_IMAGE) lvgl_components_required.add(CONF_IMAGE)
lvgl_components_required.add(CONF_ANIMIMG) lvgl_components_required.add(CONF_ANIMIMG)
if CONF_SRC in config: if CONF_SRC in config:
for x in config[CONF_SRC]: srcs = [
await cg.get_variable(x) await lv_image.process(await cg.get_variable(x))
srcs = [await lv_image.process(x) for x in config[CONF_SRC]] for x in config[CONF_SRC]
]
src_id = cg.static_const_array(config[CONF_SRC_LIST_ID], srcs) src_id = cg.static_const_array(config[CONF_SRC_LIST_ID], srcs)
count = len(config[CONF_SRC]) count = len(config[CONF_SRC])
lv.animimg_set_src(w.obj, src_id, count) lv.animimg_set_src(w.obj, src_id, count)

View File

@ -1,3 +1,4 @@
import esphome.codegen as cg
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome.const import CONF_ANGLE, CONF_MODE from esphome.const import CONF_ANGLE, CONF_MODE
@ -64,6 +65,7 @@ class ImgType(WidgetType):
async def to_code(self, w: Widget, config): async def to_code(self, w: Widget, config):
if src := config.get(CONF_SRC): if src := config.get(CONF_SRC):
src = await cg.get_variable(src)
lv.img_set_src(w.obj, await lv_image.process(src)) lv.img_set_src(w.obj, await lv_image.process(src))
if (cf_angle := config.get(CONF_ANGLE)) is not None: if (cf_angle := config.get(CONF_ANGLE)) is not None:
pivot_x = config[CONF_PIVOT_X] pivot_x = config[CONF_PIVOT_X]

View File

@ -0,0 +1,54 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import CONF_SIZE, CONF_TEXT
from esphome.cpp_generator import MockObjClass
from ..defines import CONF_MAIN, literal
from ..lv_validation import color, color_retmapper, lv_text
from ..lvcode import LocalVariable, lv, lv_expr
from ..schemas import TEXT_SCHEMA
from ..types import WidgetType, lv_obj_t
from . import Widget
CONF_QRCODE = "qrcode"
CONF_DARK_COLOR = "dark_color"
CONF_LIGHT_COLOR = "light_color"
QRCODE_SCHEMA = TEXT_SCHEMA.extend(
{
cv.Optional(CONF_DARK_COLOR, default="black"): color,
cv.Optional(CONF_LIGHT_COLOR, default="white"): color,
cv.Required(CONF_SIZE): cv.int_,
}
)
class QrCodeType(WidgetType):
def __init__(self):
super().__init__(
CONF_QRCODE,
lv_obj_t,
(CONF_MAIN,),
QRCODE_SCHEMA,
modify_schema=TEXT_SCHEMA,
)
def get_uses(self):
return ("canvas", "img")
def obj_creator(self, parent: MockObjClass, config: dict):
dark_color = color_retmapper(config[CONF_DARK_COLOR])
light_color = color_retmapper(config[CONF_LIGHT_COLOR])
size = config[CONF_SIZE]
return lv_expr.call("qrcode_create", parent, size, dark_color, light_color)
async def to_code(self, w: Widget, config):
if (value := config.get(CONF_TEXT)) is not None:
value = await lv_text.process(value)
with LocalVariable(
"qr_text", cg.const_char_ptr, value, modifier=""
) as str_obj:
lv.qrcode_update(w.obj, str_obj, literal(f"strlen({str_obj})"))
qr_code_spec = QrCodeType()

View File

@ -15,23 +15,33 @@ void Modbus::setup() {
void Modbus::loop() { void Modbus::loop() {
const uint32_t now = millis(); const uint32_t now = millis();
if (now - this->last_modbus_byte_ > 50) {
this->rx_buffer_.clear();
this->last_modbus_byte_ = now;
}
// stop blocking new send commands after send_wait_time_ ms regardless if a response has been received since then
if (now - this->last_send_ > send_wait_time_) {
waiting_for_response = 0;
}
while (this->available()) { while (this->available()) {
uint8_t byte; uint8_t byte;
this->read_byte(&byte); this->read_byte(&byte);
if (this->parse_modbus_byte_(byte)) { if (this->parse_modbus_byte_(byte)) {
this->last_modbus_byte_ = now; this->last_modbus_byte_ = now;
} else { } else {
size_t at = this->rx_buffer_.size();
if (at > 0) {
ESP_LOGV(TAG, "Clearing buffer of %d bytes - parse failed", at);
this->rx_buffer_.clear();
}
}
}
if (now - this->last_modbus_byte_ > 50) {
size_t at = this->rx_buffer_.size();
if (at > 0) {
ESP_LOGV(TAG, "Clearing buffer of %d bytes - timeout", at);
this->rx_buffer_.clear(); this->rx_buffer_.clear();
} }
// stop blocking new send commands after sent_wait_time_ ms after response received
if (now - this->last_send_ > send_wait_time_) {
if (waiting_for_response > 0)
ESP_LOGV(TAG, "Stop waiting for response from %d", waiting_for_response);
waiting_for_response = 0;
}
} }
} }
@ -39,7 +49,7 @@ bool Modbus::parse_modbus_byte_(uint8_t byte) {
size_t at = this->rx_buffer_.size(); size_t at = this->rx_buffer_.size();
this->rx_buffer_.push_back(byte); this->rx_buffer_.push_back(byte);
const uint8_t *raw = &this->rx_buffer_[0]; const uint8_t *raw = &this->rx_buffer_[0];
ESP_LOGV(TAG, "Modbus received Byte %d (0X%x)", byte, byte); ESP_LOGVV(TAG, "Modbus received Byte %d (0X%x)", byte, byte);
// Byte 0: modbus address (match all) // Byte 0: modbus address (match all)
if (at == 0) if (at == 0)
return true; return true;
@ -144,8 +154,10 @@ bool Modbus::parse_modbus_byte_(uint8_t byte) {
ESP_LOGW(TAG, "Got Modbus frame from unknown address 0x%02X! ", address); ESP_LOGW(TAG, "Got Modbus frame from unknown address 0x%02X! ", address);
} }
// return false to reset buffer // reset buffer
return false; ESP_LOGV(TAG, "Clearing buffer of %d bytes - parse succeeded", at);
this->rx_buffer_.clear();
return true;
} }
void Modbus::dump_config() { void Modbus::dump_config() {

View File

@ -17,6 +17,8 @@ void MopekaProCheck::dump_config() {
LOG_SENSOR(" ", "Temperature", this->temperature_); LOG_SENSOR(" ", "Temperature", this->temperature_);
LOG_SENSOR(" ", "Battery Level", this->battery_level_); LOG_SENSOR(" ", "Battery Level", this->battery_level_);
LOG_SENSOR(" ", "Reading Distance", this->distance_); LOG_SENSOR(" ", "Reading Distance", this->distance_);
LOG_SENSOR(" ", "Read Quality", this->read_quality_);
LOG_SENSOR(" ", "Ignored Reads", this->ignored_reads_);
} }
/** /**
@ -66,34 +68,49 @@ bool MopekaProCheck::parse_device(const esp32_ble_tracker::ESPBTDevice &device)
this->battery_level_->publish_state(level); this->battery_level_->publish_state(level);
} }
// Get the quality value
SensorReadQuality quality_value = this->parse_read_quality_(manu_data.data);
if (this->read_quality_ != nullptr) {
this->read_quality_->publish_state(static_cast<int>(quality_value));
}
// Determine if we have a good enough quality of read to report level and distance
// sensors. This sensor is reported regardless of distance or level sensors being enabled
if (quality_value < this->min_signal_quality_) {
ESP_LOGW(TAG, "Read Quality too low to report distance or level");
this->ignored_read_count_++;
} else {
// reset to zero since read quality was sufficient
this->ignored_read_count_ = 0;
}
// Report number of contiguous ignored reads if sensor defined
if (this->ignored_reads_ != nullptr) {
this->ignored_reads_->publish_state(this->ignored_read_count_);
}
// Get distance and level if either are sensors // Get distance and level if either are sensors
if ((this->distance_ != nullptr) || (this->level_ != nullptr)) { if ((this->distance_ != nullptr) || (this->level_ != nullptr)) {
uint32_t distance_value = this->parse_distance_(manu_data.data); uint32_t distance_value = this->parse_distance_(manu_data.data);
SensorReadQuality quality_value = this->parse_read_quality_(manu_data.data);
ESP_LOGD(TAG, "Distance Sensor: Quality (0x%X) Distance (%" PRId32 "mm)", quality_value, distance_value); ESP_LOGD(TAG, "Distance Sensor: Quality (0x%X) Distance (%" PRId32 "mm)", quality_value, distance_value);
if (quality_value < QUALITY_HIGH) {
ESP_LOGW(TAG, "Poor read quality.");
}
if (quality_value < QUALITY_MED) {
// if really bad reading set to 0
ESP_LOGW(TAG, "Setting distance to 0");
distance_value = 0;
}
// update distance sensor // only update distance and level sensors if read quality was sufficient. This can be determined by
if (this->distance_ != nullptr) { // if the ignored_read_count is zero.
this->distance_->publish_state(distance_value); if (this->ignored_read_count_ == 0) {
} // update distance sensor
if (this->distance_ != nullptr) {
// update level sensor this->distance_->publish_state(distance_value);
if (this->level_ != nullptr) { }
uint8_t tank_level = 0;
if (distance_value >= this->full_mm_) { // update level sensor
tank_level = 100; // cap at 100% if (this->level_ != nullptr) {
} else if (distance_value > this->empty_mm_) { uint8_t tank_level = 0;
tank_level = ((100.0f / (this->full_mm_ - this->empty_mm_)) * (distance_value - this->empty_mm_)); if (distance_value >= this->full_mm_) {
tank_level = 100; // cap at 100%
} else if (distance_value > this->empty_mm_) {
tank_level = ((100.0f / (this->full_mm_ - this->empty_mm_)) * (distance_value - this->empty_mm_));
}
this->level_->publish_state(tank_level);
} }
this->level_->publish_state(tank_level);
} }
} }
@ -131,6 +148,8 @@ uint32_t MopekaProCheck::parse_distance_(const std::vector<uint8_t> &message) {
uint8_t MopekaProCheck::parse_temperature_(const std::vector<uint8_t> &message) { return (message[2] & 0x7F) - 40; } uint8_t MopekaProCheck::parse_temperature_(const std::vector<uint8_t> &message) { return (message[2] & 0x7F) - 40; }
SensorReadQuality MopekaProCheck::parse_read_quality_(const std::vector<uint8_t> &message) { SensorReadQuality MopekaProCheck::parse_read_quality_(const std::vector<uint8_t> &message) {
// Since a 8 bit value is being shifted and truncated to 2 bits all possible values are defined as enumeration
// value and the static cast is safe.
return static_cast<SensorReadQuality>(message[4] >> 6); return static_cast<SensorReadQuality>(message[4] >> 6);
} }

View File

@ -24,9 +24,9 @@ enum SensorType {
}; };
// Sensor read quality. If sensor is poorly placed or tank level // Sensor read quality. If sensor is poorly placed or tank level
// gets too low the read quality will show and the distanace // gets too low the read quality will show and the distance
// measurement may be inaccurate. // measurement may be inaccurate.
enum SensorReadQuality { QUALITY_HIGH = 0x3, QUALITY_MED = 0x2, QUALITY_LOW = 0x1, QUALITY_NONE = 0x0 }; enum SensorReadQuality { QUALITY_HIGH = 0x3, QUALITY_MED = 0x2, QUALITY_LOW = 0x1, QUALITY_ZERO = 0x0 };
class MopekaProCheck : public Component, public esp32_ble_tracker::ESPBTDeviceListener { class MopekaProCheck : public Component, public esp32_ble_tracker::ESPBTDeviceListener {
public: public:
@ -35,11 +35,14 @@ class MopekaProCheck : public Component, public esp32_ble_tracker::ESPBTDeviceLi
bool parse_device(const esp32_ble_tracker::ESPBTDevice &device) override; bool parse_device(const esp32_ble_tracker::ESPBTDevice &device) override;
void dump_config() override; void dump_config() override;
float get_setup_priority() const override { return setup_priority::DATA; } float get_setup_priority() const override { return setup_priority::DATA; }
void set_min_signal_quality(SensorReadQuality min) { this->min_signal_quality_ = min; };
void set_level(sensor::Sensor *level) { level_ = level; }; void set_level(sensor::Sensor *level) { level_ = level; };
void set_temperature(sensor::Sensor *temperature) { temperature_ = temperature; }; void set_temperature(sensor::Sensor *temperature) { temperature_ = temperature; };
void set_battery_level(sensor::Sensor *bat) { battery_level_ = bat; }; void set_battery_level(sensor::Sensor *bat) { battery_level_ = bat; };
void set_distance(sensor::Sensor *distance) { distance_ = distance; }; void set_distance(sensor::Sensor *distance) { distance_ = distance; };
void set_signal_quality(sensor::Sensor *rq) { read_quality_ = rq; };
void set_ignored_reads(sensor::Sensor *ir) { ignored_reads_ = ir; };
void set_tank_full(float full) { full_mm_ = full; }; void set_tank_full(float full) { full_mm_ = full; };
void set_tank_empty(float empty) { empty_mm_ = empty; }; void set_tank_empty(float empty) { empty_mm_ = empty; };
@ -49,9 +52,13 @@ class MopekaProCheck : public Component, public esp32_ble_tracker::ESPBTDeviceLi
sensor::Sensor *temperature_{nullptr}; sensor::Sensor *temperature_{nullptr};
sensor::Sensor *distance_{nullptr}; sensor::Sensor *distance_{nullptr};
sensor::Sensor *battery_level_{nullptr}; sensor::Sensor *battery_level_{nullptr};
sensor::Sensor *read_quality_{nullptr};
sensor::Sensor *ignored_reads_{nullptr};
uint32_t full_mm_; uint32_t full_mm_;
uint32_t empty_mm_; uint32_t empty_mm_;
uint32_t ignored_read_count_ = 0;
SensorReadQuality min_signal_quality_ = QUALITY_MED;
uint8_t parse_battery_level_(const std::vector<uint8_t> &message); uint8_t parse_battery_level_(const std::vector<uint8_t> &message);
uint32_t parse_distance_(const std::vector<uint8_t> &message); uint32_t parse_distance_(const std::vector<uint8_t> &message);

View File

@ -5,9 +5,12 @@ from esphome.const import (
CONF_DISTANCE, CONF_DISTANCE,
CONF_MAC_ADDRESS, CONF_MAC_ADDRESS,
CONF_ID, CONF_ID,
ICON_COUNTER,
ICON_THERMOMETER, ICON_THERMOMETER,
ICON_RULER, ICON_RULER,
ICON_SIGNAL,
UNIT_PERCENT, UNIT_PERCENT,
UNIT_EMPTY,
CONF_LEVEL, CONF_LEVEL,
CONF_TEMPERATURE, CONF_TEMPERATURE,
DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_TEMPERATURE,
@ -16,11 +19,15 @@ from esphome.const import (
STATE_CLASS_MEASUREMENT, STATE_CLASS_MEASUREMENT,
CONF_BATTERY_LEVEL, CONF_BATTERY_LEVEL,
DEVICE_CLASS_BATTERY, DEVICE_CLASS_BATTERY,
ENTITY_CATEGORY_DIAGNOSTIC,
) )
CONF_TANK_TYPE = "tank_type" CONF_TANK_TYPE = "tank_type"
CONF_CUSTOM_DISTANCE_FULL = "custom_distance_full" CONF_CUSTOM_DISTANCE_FULL = "custom_distance_full"
CONF_CUSTOM_DISTANCE_EMPTY = "custom_distance_empty" CONF_CUSTOM_DISTANCE_EMPTY = "custom_distance_empty"
CONF_SIGNAL_QUALITY = "signal_quality"
CONF_MINIMUM_SIGNAL_QUALITY = "minimum_signal_quality"
CONF_IGNORED_READS = "ignored_reads"
ICON_PROPANE_TANK = "mdi:propane-tank" ICON_PROPANE_TANK = "mdi:propane-tank"
@ -56,6 +63,14 @@ MopekaProCheck = mopeka_pro_check_ns.class_(
"MopekaProCheck", esp32_ble_tracker.ESPBTDeviceListener, cg.Component "MopekaProCheck", esp32_ble_tracker.ESPBTDeviceListener, cg.Component
) )
SensorReadQuality = mopeka_pro_check_ns.enum("SensorReadQuality")
SIGNAL_QUALITIES = {
"ZERO": SensorReadQuality.QUALITY_ZERO,
"LOW": SensorReadQuality.QUALITY_LOW,
"MEDIUM": SensorReadQuality.QUALITY_MED,
"HIGH": SensorReadQuality.QUALITY_HIGH,
}
CONFIG_SCHEMA = ( CONFIG_SCHEMA = (
cv.Schema( cv.Schema(
{ {
@ -89,6 +104,21 @@ CONFIG_SCHEMA = (
device_class=DEVICE_CLASS_BATTERY, device_class=DEVICE_CLASS_BATTERY,
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
), ),
cv.Optional(CONF_SIGNAL_QUALITY): sensor.sensor_schema(
unit_of_measurement=UNIT_EMPTY,
icon=ICON_SIGNAL,
accuracy_decimals=0,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_IGNORED_READS): sensor.sensor_schema(
unit_of_measurement=UNIT_EMPTY,
icon=ICON_COUNTER,
accuracy_decimals=0,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
cv.Optional(CONF_MINIMUM_SIGNAL_QUALITY, default="MEDIUM"): cv.enum(
SIGNAL_QUALITIES, upper=True
),
} }
) )
.extend(esp32_ble_tracker.ESP_BLE_DEVICE_SCHEMA) .extend(esp32_ble_tracker.ESP_BLE_DEVICE_SCHEMA)
@ -119,6 +149,11 @@ async def to_code(config):
cg.add(var.set_tank_empty(CONF_SUPPORTED_TANKS_MAP[t][0])) cg.add(var.set_tank_empty(CONF_SUPPORTED_TANKS_MAP[t][0]))
cg.add(var.set_tank_full(CONF_SUPPORTED_TANKS_MAP[t][1])) cg.add(var.set_tank_full(CONF_SUPPORTED_TANKS_MAP[t][1]))
if (
minimum_signal_quality := config.get(CONF_MINIMUM_SIGNAL_QUALITY, None)
) is not None:
cg.add(var.set_min_signal_quality(minimum_signal_quality))
if CONF_TEMPERATURE in config: if CONF_TEMPERATURE in config:
sens = await sensor.new_sensor(config[CONF_TEMPERATURE]) sens = await sensor.new_sensor(config[CONF_TEMPERATURE])
cg.add(var.set_temperature(sens)) cg.add(var.set_temperature(sens))
@ -131,3 +166,9 @@ async def to_code(config):
if CONF_BATTERY_LEVEL in config: if CONF_BATTERY_LEVEL in config:
sens = await sensor.new_sensor(config[CONF_BATTERY_LEVEL]) sens = await sensor.new_sensor(config[CONF_BATTERY_LEVEL])
cg.add(var.set_battery_level(sens)) cg.add(var.set_battery_level(sens))
if CONF_SIGNAL_QUALITY in config:
sens = await sensor.new_sensor(config[CONF_SIGNAL_QUALITY])
cg.add(var.set_signal_quality(sens))
if CONF_IGNORED_READS in config:
sens = await sensor.new_sensor(config[CONF_IGNORED_READS])
cg.add(var.set_ignored_reads(sens))

View File

@ -22,6 +22,7 @@ from esphome.const import (
CONF_DISCOVERY_PREFIX, CONF_DISCOVERY_PREFIX,
CONF_DISCOVERY_RETAIN, CONF_DISCOVERY_RETAIN,
CONF_DISCOVERY_UNIQUE_ID_GENERATOR, CONF_DISCOVERY_UNIQUE_ID_GENERATOR,
CONF_ENABLE_ON_BOOT,
CONF_ID, CONF_ID,
CONF_KEEPALIVE, CONF_KEEPALIVE,
CONF_LEVEL, CONF_LEVEL,
@ -99,6 +100,8 @@ MQTTMessage = mqtt_ns.struct("MQTTMessage")
MQTTClientComponent = mqtt_ns.class_("MQTTClientComponent", cg.Component) MQTTClientComponent = mqtt_ns.class_("MQTTClientComponent", cg.Component)
MQTTPublishAction = mqtt_ns.class_("MQTTPublishAction", automation.Action) MQTTPublishAction = mqtt_ns.class_("MQTTPublishAction", automation.Action)
MQTTPublishJsonAction = mqtt_ns.class_("MQTTPublishJsonAction", automation.Action) MQTTPublishJsonAction = mqtt_ns.class_("MQTTPublishJsonAction", automation.Action)
MQTTEnableAction = mqtt_ns.class_("MQTTEnableAction", automation.Action)
MQTTDisableAction = mqtt_ns.class_("MQTTDisableAction", automation.Action)
MQTTMessageTrigger = mqtt_ns.class_( MQTTMessageTrigger = mqtt_ns.class_(
"MQTTMessageTrigger", automation.Trigger.template(cg.std_string), cg.Component "MQTTMessageTrigger", automation.Trigger.template(cg.std_string), cg.Component
) )
@ -208,6 +211,7 @@ CONFIG_SCHEMA = cv.All(
{ {
cv.GenerateID(): cv.declare_id(MQTTClientComponent), cv.GenerateID(): cv.declare_id(MQTTClientComponent),
cv.Required(CONF_BROKER): cv.string_strict, cv.Required(CONF_BROKER): cv.string_strict,
cv.Optional(CONF_ENABLE_ON_BOOT, default=True): cv.boolean,
cv.Optional(CONF_PORT, default=1883): cv.port, cv.Optional(CONF_PORT, default=1883): cv.port,
cv.Optional(CONF_USERNAME, default=""): cv.string, cv.Optional(CONF_USERNAME, default=""): cv.string,
cv.Optional(CONF_PASSWORD, default=""): cv.string, cv.Optional(CONF_PASSWORD, default=""): cv.string,
@ -325,6 +329,7 @@ async def to_code(config):
cg.add_global(mqtt_ns.using) cg.add_global(mqtt_ns.using)
cg.add(var.set_broker_address(config[CONF_BROKER])) cg.add(var.set_broker_address(config[CONF_BROKER]))
cg.add(var.set_enable_on_boot(config[CONF_ENABLE_ON_BOOT]))
cg.add(var.set_broker_port(config[CONF_PORT])) cg.add(var.set_broker_port(config[CONF_PORT]))
cg.add(var.set_username(config[CONF_USERNAME])) cg.add(var.set_username(config[CONF_USERNAME]))
cg.add(var.set_password(config[CONF_PASSWORD])) cg.add(var.set_password(config[CONF_PASSWORD]))
@ -555,3 +560,31 @@ async def register_mqtt_component(var, config):
async def mqtt_connected_to_code(config, condition_id, template_arg, args): async def mqtt_connected_to_code(config, condition_id, template_arg, args):
paren = await cg.get_variable(config[CONF_ID]) paren = await cg.get_variable(config[CONF_ID])
return cg.new_Pvariable(condition_id, template_arg, paren) return cg.new_Pvariable(condition_id, template_arg, paren)
@automation.register_action(
"mqtt.enable",
MQTTEnableAction,
cv.Schema(
{
cv.GenerateID(): cv.use_id(MQTTClientComponent),
}
),
)
async def mqtt_enable_to_code(config, action_id, template_arg, args):
paren = await cg.get_variable(config[CONF_ID])
return cg.new_Pvariable(action_id, template_arg, paren)
@automation.register_action(
"mqtt.disable",
MQTTDisableAction,
cv.Schema(
{
cv.GenerateID(): cv.use_id(MQTTClientComponent),
}
),
)
async def mqtt_disable_to_code(config, action_id, template_arg, args):
paren = await cg.get_variable(config[CONF_ID])
return cg.new_Pvariable(action_id, template_arg, paren)

View File

@ -50,6 +50,8 @@ void MQTTClientComponent::setup() {
} }
}); });
this->mqtt_backend_.set_on_disconnect([this](MQTTClientDisconnectReason reason) { this->mqtt_backend_.set_on_disconnect([this](MQTTClientDisconnectReason reason) {
if (this->state_ == MQTT_CLIENT_DISABLED)
return;
this->state_ = MQTT_CLIENT_DISCONNECTED; this->state_ = MQTT_CLIENT_DISCONNECTED;
this->disconnect_reason_ = reason; this->disconnect_reason_ = reason;
}); });
@ -77,8 +79,9 @@ void MQTTClientComponent::setup() {
topic, [this](const std::string &topic, const std::string &payload) { this->send_device_info_(); }, 2); topic, [this](const std::string &topic, const std::string &payload) { this->send_device_info_(); }, 2);
} }
this->last_connected_ = millis(); if (this->enable_on_boot_) {
this->start_dnslookup_(); this->enable();
}
} }
void MQTTClientComponent::send_device_info_() { void MQTTClientComponent::send_device_info_() {
@ -163,7 +166,9 @@ void MQTTClientComponent::dump_config() {
ESP_LOGCONFIG(TAG, " Availability: '%s'", this->availability_.topic.c_str()); ESP_LOGCONFIG(TAG, " Availability: '%s'", this->availability_.topic.c_str());
} }
} }
bool MQTTClientComponent::can_proceed() { return network::is_disabled() || this->is_connected(); } bool MQTTClientComponent::can_proceed() {
return network::is_disabled() || this->state_ == MQTT_CLIENT_DISABLED || this->is_connected();
}
void MQTTClientComponent::start_dnslookup_() { void MQTTClientComponent::start_dnslookup_() {
for (auto &subscription : this->subscriptions_) { for (auto &subscription : this->subscriptions_) {
@ -339,6 +344,8 @@ void MQTTClientComponent::loop() {
const uint32_t now = millis(); const uint32_t now = millis();
switch (this->state_) { switch (this->state_) {
case MQTT_CLIENT_DISABLED:
return; // Return to avoid a reboot when disabled
case MQTT_CLIENT_DISCONNECTED: case MQTT_CLIENT_DISCONNECTED:
if (now - this->connect_begin_ > 5000) { if (now - this->connect_begin_ > 5000) {
this->start_dnslookup_(); this->start_dnslookup_();
@ -501,6 +508,23 @@ bool MQTTClientComponent::publish_json(const std::string &topic, const json::jso
return this->publish(topic, message, qos, retain); return this->publish(topic, message, qos, retain);
} }
void MQTTClientComponent::enable() {
if (this->state_ != MQTT_CLIENT_DISABLED)
return;
ESP_LOGD(TAG, "Enabling MQTT...");
this->state_ = MQTT_CLIENT_DISCONNECTED;
this->last_connected_ = millis();
this->start_dnslookup_();
}
void MQTTClientComponent::disable() {
if (this->state_ == MQTT_CLIENT_DISABLED)
return;
ESP_LOGD(TAG, "Disabling MQTT...");
this->state_ = MQTT_CLIENT_DISABLED;
this->on_shutdown();
}
/** Check if the message topic matches the given subscription topic /** Check if the message topic matches the given subscription topic
* *
* INFO: MQTT spec mandates that topics must not be empty and must be valid NULL-terminated UTF-8 strings. * INFO: MQTT spec mandates that topics must not be empty and must be valid NULL-terminated UTF-8 strings.

View File

@ -87,7 +87,8 @@ struct MQTTDiscoveryInfo {
}; };
enum MQTTClientState { enum MQTTClientState {
MQTT_CLIENT_DISCONNECTED = 0, MQTT_CLIENT_DISABLED = 0,
MQTT_CLIENT_DISCONNECTED,
MQTT_CLIENT_RESOLVING_ADDRESS, MQTT_CLIENT_RESOLVING_ADDRESS,
MQTT_CLIENT_CONNECTING, MQTT_CLIENT_CONNECTING,
MQTT_CLIENT_CONNECTED, MQTT_CLIENT_CONNECTED,
@ -247,6 +248,9 @@ class MQTTClientComponent : public Component {
void register_mqtt_component(MQTTComponent *component); void register_mqtt_component(MQTTComponent *component);
bool is_connected(); bool is_connected();
void set_enable_on_boot(bool enable_on_boot) { this->enable_on_boot_ = enable_on_boot; }
void enable();
void disable();
void on_shutdown() override; void on_shutdown() override;
@ -314,10 +318,11 @@ class MQTTClientComponent : public Component {
MQTTBackendLibreTiny mqtt_backend_; MQTTBackendLibreTiny mqtt_backend_;
#endif #endif
MQTTClientState state_{MQTT_CLIENT_DISCONNECTED}; MQTTClientState state_{MQTT_CLIENT_DISABLED};
network::IPAddress ip_; network::IPAddress ip_;
bool dns_resolved_{false}; bool dns_resolved_{false};
bool dns_resolve_error_{false}; bool dns_resolve_error_{false};
bool enable_on_boot_{true};
std::vector<MQTTComponent *> children_; std::vector<MQTTComponent *> children_;
uint32_t reboot_timeout_{300000}; uint32_t reboot_timeout_{300000};
uint32_t connect_begin_; uint32_t connect_begin_;
@ -414,6 +419,26 @@ template<typename... Ts> class MQTTConnectedCondition : public Condition<Ts...>
MQTTClientComponent *parent_; MQTTClientComponent *parent_;
}; };
template<typename... Ts> class MQTTEnableAction : public Action<Ts...> {
public:
MQTTEnableAction(MQTTClientComponent *parent) : parent_(parent) {}
void play(Ts... x) override { this->parent_->enable(); }
protected:
MQTTClientComponent *parent_;
};
template<typename... Ts> class MQTTDisableAction : public Action<Ts...> {
public:
MQTTDisableAction(MQTTClientComponent *parent) : parent_(parent) {}
void play(Ts... x) override { this->parent_->disable(); }
protected:
MQTTClientComponent *parent_;
};
} // namespace mqtt } // namespace mqtt
} // namespace esphome } // namespace esphome

View File

@ -71,8 +71,10 @@ void MQTTClimateComponent::send_discovery(JsonObject root, mqtt::SendDiscoveryCo
root[MQTT_MIN_TEMP] = traits.get_visual_min_temperature(); root[MQTT_MIN_TEMP] = traits.get_visual_min_temperature();
// max_temp // max_temp
root[MQTT_MAX_TEMP] = traits.get_visual_max_temperature(); root[MQTT_MAX_TEMP] = traits.get_visual_max_temperature();
// temp_step // target_temp_step
root["temp_step"] = traits.get_visual_target_temperature_step(); root[MQTT_TARGET_TEMPERATURE_STEP] = traits.get_visual_target_temperature_step();
// current_temp_step
root[MQTT_CURRENT_TEMPERATURE_STEP] = traits.get_visual_current_temperature_step();
// temperature units are always coerced to Celsius internally // temperature units are always coerced to Celsius internally
root[MQTT_TEMPERATURE_UNIT] = "C"; root[MQTT_TEMPERATURE_UNIT] = "C";

View File

@ -51,6 +51,7 @@ constexpr const char *const MQTT_COMMAND_TOPIC = "cmd_t";
constexpr const char *const MQTT_CONFIGURATION_URL = "cu"; constexpr const char *const MQTT_CONFIGURATION_URL = "cu";
constexpr const char *const MQTT_CURRENT_HUMIDITY_TEMPLATE = "curr_hum_tpl"; constexpr const char *const MQTT_CURRENT_HUMIDITY_TEMPLATE = "curr_hum_tpl";
constexpr const char *const MQTT_CURRENT_HUMIDITY_TOPIC = "curr_hum_t"; constexpr const char *const MQTT_CURRENT_HUMIDITY_TOPIC = "curr_hum_t";
constexpr const char *const MQTT_CURRENT_TEMPERATURE_STEP = "precision";
constexpr const char *const MQTT_CURRENT_TEMPERATURE_TEMPLATE = "curr_temp_tpl"; constexpr const char *const MQTT_CURRENT_TEMPERATURE_TEMPLATE = "curr_temp_tpl";
constexpr const char *const MQTT_CURRENT_TEMPERATURE_TOPIC = "curr_temp_t"; constexpr const char *const MQTT_CURRENT_TEMPERATURE_TOPIC = "curr_temp_t";
constexpr const char *const MQTT_DEVICE = "dev"; constexpr const char *const MQTT_DEVICE = "dev";
@ -232,6 +233,7 @@ constexpr const char *const MQTT_TARGET_HUMIDITY_COMMAND_TEMPLATE = "hum_cmd_tpl
constexpr const char *const MQTT_TARGET_HUMIDITY_COMMAND_TOPIC = "hum_cmd_t"; constexpr const char *const MQTT_TARGET_HUMIDITY_COMMAND_TOPIC = "hum_cmd_t";
constexpr const char *const MQTT_TARGET_HUMIDITY_STATE_TEMPLATE = "hum_state_tpl"; constexpr const char *const MQTT_TARGET_HUMIDITY_STATE_TEMPLATE = "hum_state_tpl";
constexpr const char *const MQTT_TARGET_HUMIDITY_STATE_TOPIC = "hum_stat_t"; constexpr const char *const MQTT_TARGET_HUMIDITY_STATE_TOPIC = "hum_stat_t";
constexpr const char *const MQTT_TARGET_TEMPERATURE_STEP = "temp_step";
constexpr const char *const MQTT_TEMPERATURE_COMMAND_TEMPLATE = "temp_cmd_tpl"; constexpr const char *const MQTT_TEMPERATURE_COMMAND_TEMPLATE = "temp_cmd_tpl";
constexpr const char *const MQTT_TEMPERATURE_COMMAND_TOPIC = "temp_cmd_t"; constexpr const char *const MQTT_TEMPERATURE_COMMAND_TOPIC = "temp_cmd_t";
constexpr const char *const MQTT_TEMPERATURE_HIGH_COMMAND_TEMPLATE = "temp_hi_cmd_tpl"; constexpr const char *const MQTT_TEMPERATURE_HIGH_COMMAND_TEMPLATE = "temp_hi_cmd_tpl";
@ -313,6 +315,7 @@ constexpr const char *const MQTT_COMMAND_TOPIC = "command_topic";
constexpr const char *const MQTT_CONFIGURATION_URL = "configuration_url"; constexpr const char *const MQTT_CONFIGURATION_URL = "configuration_url";
constexpr const char *const MQTT_CURRENT_HUMIDITY_TEMPLATE = "current_humidity_template"; constexpr const char *const MQTT_CURRENT_HUMIDITY_TEMPLATE = "current_humidity_template";
constexpr const char *const MQTT_CURRENT_HUMIDITY_TOPIC = "current_humidity_topic"; constexpr const char *const MQTT_CURRENT_HUMIDITY_TOPIC = "current_humidity_topic";
constexpr const char *const MQTT_CURRENT_TEMPERATURE_STEP = "precision";
constexpr const char *const MQTT_CURRENT_TEMPERATURE_TEMPLATE = "current_temperature_template"; constexpr const char *const MQTT_CURRENT_TEMPERATURE_TEMPLATE = "current_temperature_template";
constexpr const char *const MQTT_CURRENT_TEMPERATURE_TOPIC = "current_temperature_topic"; constexpr const char *const MQTT_CURRENT_TEMPERATURE_TOPIC = "current_temperature_topic";
constexpr const char *const MQTT_DEVICE = "device"; constexpr const char *const MQTT_DEVICE = "device";
@ -494,6 +497,7 @@ constexpr const char *const MQTT_TARGET_HUMIDITY_COMMAND_TEMPLATE = "target_humi
constexpr const char *const MQTT_TARGET_HUMIDITY_COMMAND_TOPIC = "target_humidity_command_topic"; constexpr const char *const MQTT_TARGET_HUMIDITY_COMMAND_TOPIC = "target_humidity_command_topic";
constexpr const char *const MQTT_TARGET_HUMIDITY_STATE_TEMPLATE = "target_humidity_state_template"; constexpr const char *const MQTT_TARGET_HUMIDITY_STATE_TEMPLATE = "target_humidity_state_template";
constexpr const char *const MQTT_TARGET_HUMIDITY_STATE_TOPIC = "target_humidity_state_topic"; constexpr const char *const MQTT_TARGET_HUMIDITY_STATE_TOPIC = "target_humidity_state_topic";
constexpr const char *const MQTT_TARGET_TEMPERATURE_STEP = "temp_step";
constexpr const char *const MQTT_TEMPERATURE_COMMAND_TEMPLATE = "temperature_command_template"; constexpr const char *const MQTT_TEMPERATURE_COMMAND_TEMPLATE = "temperature_command_template";
constexpr const char *const MQTT_TEMPERATURE_COMMAND_TOPIC = "temperature_command_topic"; constexpr const char *const MQTT_TEMPERATURE_COMMAND_TOPIC = "temperature_command_topic";
constexpr const char *const MQTT_TEMPERATURE_HIGH_COMMAND_TEMPLATE = "temperature_high_command_template"; constexpr const char *const MQTT_TEMPERATURE_HIGH_COMMAND_TEMPLATE = "temperature_high_command_template";

View File

@ -1,15 +1,15 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins from esphome import pins
import esphome.codegen as cg
from esphome.components import display, spi from esphome.components import display, spi
import esphome.config_validation as cv
from esphome.const import ( from esphome.const import (
CONF_CONTRAST,
CONF_CS_PIN,
CONF_DC_PIN, CONF_DC_PIN,
CONF_ID, CONF_ID,
CONF_LAMBDA, CONF_LAMBDA,
CONF_PAGES, CONF_PAGES,
CONF_RESET_PIN, CONF_RESET_PIN,
CONF_CS_PIN,
CONF_CONTRAST,
) )
DEPENDENCIES = ["spi"] DEPENDENCIES = ["spi"]
@ -35,6 +35,10 @@ CONFIG_SCHEMA = cv.All(
cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA), cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA),
) )
FINAL_VALIDATE_SCHEMA = spi.final_validate_device_schema(
"pcd8544", require_miso=False, require_mosi=True
)
async def to_code(config): async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID]) var = cg.new_Pvariable(config[CONF_ID])

View File

@ -7,47 +7,56 @@ namespace prometheus {
void PrometheusHandler::handleRequest(AsyncWebServerRequest *req) { void PrometheusHandler::handleRequest(AsyncWebServerRequest *req) {
AsyncResponseStream *stream = req->beginResponseStream("text/plain; version=0.0.4; charset=utf-8"); AsyncResponseStream *stream = req->beginResponseStream("text/plain; version=0.0.4; charset=utf-8");
std::string area = App.get_area();
std::string node = App.get_name();
std::string friendly_name = App.get_friendly_name();
#ifdef USE_SENSOR #ifdef USE_SENSOR
this->sensor_type_(stream); this->sensor_type_(stream);
for (auto *obj : App.get_sensors()) for (auto *obj : App.get_sensors())
this->sensor_row_(stream, obj); this->sensor_row_(stream, obj, area, node, friendly_name);
#endif #endif
#ifdef USE_BINARY_SENSOR #ifdef USE_BINARY_SENSOR
this->binary_sensor_type_(stream); this->binary_sensor_type_(stream);
for (auto *obj : App.get_binary_sensors()) for (auto *obj : App.get_binary_sensors())
this->binary_sensor_row_(stream, obj); this->binary_sensor_row_(stream, obj, area, node, friendly_name);
#endif #endif
#ifdef USE_FAN #ifdef USE_FAN
this->fan_type_(stream); this->fan_type_(stream);
for (auto *obj : App.get_fans()) for (auto *obj : App.get_fans())
this->fan_row_(stream, obj); this->fan_row_(stream, obj, area, node, friendly_name);
#endif #endif
#ifdef USE_LIGHT #ifdef USE_LIGHT
this->light_type_(stream); this->light_type_(stream);
for (auto *obj : App.get_lights()) for (auto *obj : App.get_lights())
this->light_row_(stream, obj); this->light_row_(stream, obj, area, node, friendly_name);
#endif #endif
#ifdef USE_COVER #ifdef USE_COVER
this->cover_type_(stream); this->cover_type_(stream);
for (auto *obj : App.get_covers()) for (auto *obj : App.get_covers())
this->cover_row_(stream, obj); this->cover_row_(stream, obj, area, node, friendly_name);
#endif #endif
#ifdef USE_SWITCH #ifdef USE_SWITCH
this->switch_type_(stream); this->switch_type_(stream);
for (auto *obj : App.get_switches()) for (auto *obj : App.get_switches())
this->switch_row_(stream, obj); this->switch_row_(stream, obj, area, node, friendly_name);
#endif #endif
#ifdef USE_LOCK #ifdef USE_LOCK
this->lock_type_(stream); this->lock_type_(stream);
for (auto *obj : App.get_locks()) for (auto *obj : App.get_locks())
this->lock_row_(stream, obj); this->lock_row_(stream, obj, area, node, friendly_name);
#endif
#ifdef USE_TEXT_SENSOR
this->text_sensor_type_(stream);
for (auto *obj : App.get_text_sensors())
this->text_sensor_row_(stream, obj, area, node, friendly_name);
#endif #endif
req->send(stream); req->send(stream);
@ -63,25 +72,53 @@ std::string PrometheusHandler::relabel_name_(EntityBase *obj) {
return item == relabel_map_name_.end() ? obj->get_name() : item->second; return item == relabel_map_name_.end() ? obj->get_name() : item->second;
} }
void PrometheusHandler::add_area_label_(AsyncResponseStream *stream, std::string &area) {
if (!area.empty()) {
stream->print(F("\",area=\""));
stream->print(area.c_str());
}
}
void PrometheusHandler::add_node_label_(AsyncResponseStream *stream, std::string &node) {
if (!node.empty()) {
stream->print(F("\",node=\""));
stream->print(node.c_str());
}
}
void PrometheusHandler::add_friendly_name_label_(AsyncResponseStream *stream, std::string &friendly_name) {
if (!friendly_name.empty()) {
stream->print(F("\",friendly_name=\""));
stream->print(friendly_name.c_str());
}
}
// Type-specific implementation // Type-specific implementation
#ifdef USE_SENSOR #ifdef USE_SENSOR
void PrometheusHandler::sensor_type_(AsyncResponseStream *stream) { void PrometheusHandler::sensor_type_(AsyncResponseStream *stream) {
stream->print(F("#TYPE esphome_sensor_value gauge\n")); stream->print(F("#TYPE esphome_sensor_value gauge\n"));
stream->print(F("#TYPE esphome_sensor_failed gauge\n")); stream->print(F("#TYPE esphome_sensor_failed gauge\n"));
} }
void PrometheusHandler::sensor_row_(AsyncResponseStream *stream, sensor::Sensor *obj) { void PrometheusHandler::sensor_row_(AsyncResponseStream *stream, sensor::Sensor *obj, std::string &area,
std::string &node, std::string &friendly_name) {
if (obj->is_internal() && !this->include_internal_) if (obj->is_internal() && !this->include_internal_)
return; return;
if (!std::isnan(obj->state)) { if (!std::isnan(obj->state)) {
// We have a valid value, output this value // We have a valid value, output this value
stream->print(F("esphome_sensor_failed{id=\"")); stream->print(F("esphome_sensor_failed{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} 0\n")); stream->print(F("\"} 0\n"));
// Data itself // Data itself
stream->print(F("esphome_sensor_value{id=\"")); stream->print(F("esphome_sensor_value{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\",unit=\"")); stream->print(F("\",unit=\""));
@ -93,6 +130,9 @@ void PrometheusHandler::sensor_row_(AsyncResponseStream *stream, sensor::Sensor
// Invalid state // Invalid state
stream->print(F("esphome_sensor_failed{id=\"")); stream->print(F("esphome_sensor_failed{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} 1\n")); stream->print(F("\"} 1\n"));
@ -106,19 +146,26 @@ void PrometheusHandler::binary_sensor_type_(AsyncResponseStream *stream) {
stream->print(F("#TYPE esphome_binary_sensor_value gauge\n")); stream->print(F("#TYPE esphome_binary_sensor_value gauge\n"));
stream->print(F("#TYPE esphome_binary_sensor_failed gauge\n")); stream->print(F("#TYPE esphome_binary_sensor_failed gauge\n"));
} }
void PrometheusHandler::binary_sensor_row_(AsyncResponseStream *stream, binary_sensor::BinarySensor *obj) { void PrometheusHandler::binary_sensor_row_(AsyncResponseStream *stream, binary_sensor::BinarySensor *obj,
std::string &area, std::string &node, std::string &friendly_name) {
if (obj->is_internal() && !this->include_internal_) if (obj->is_internal() && !this->include_internal_)
return; return;
if (obj->has_state()) { if (obj->has_state()) {
// We have a valid value, output this value // We have a valid value, output this value
stream->print(F("esphome_binary_sensor_failed{id=\"")); stream->print(F("esphome_binary_sensor_failed{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} 0\n")); stream->print(F("\"} 0\n"));
// Data itself // Data itself
stream->print(F("esphome_binary_sensor_value{id=\"")); stream->print(F("esphome_binary_sensor_value{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} ")); stream->print(F("\"} "));
@ -128,6 +175,9 @@ void PrometheusHandler::binary_sensor_row_(AsyncResponseStream *stream, binary_s
// Invalid state // Invalid state
stream->print(F("esphome_binary_sensor_failed{id=\"")); stream->print(F("esphome_binary_sensor_failed{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} 1\n")); stream->print(F("\"} 1\n"));
@ -142,17 +192,24 @@ void PrometheusHandler::fan_type_(AsyncResponseStream *stream) {
stream->print(F("#TYPE esphome_fan_speed gauge\n")); stream->print(F("#TYPE esphome_fan_speed gauge\n"));
stream->print(F("#TYPE esphome_fan_oscillation gauge\n")); stream->print(F("#TYPE esphome_fan_oscillation gauge\n"));
} }
void PrometheusHandler::fan_row_(AsyncResponseStream *stream, fan::Fan *obj) { void PrometheusHandler::fan_row_(AsyncResponseStream *stream, fan::Fan *obj, std::string &area, std::string &node,
std::string &friendly_name) {
if (obj->is_internal() && !this->include_internal_) if (obj->is_internal() && !this->include_internal_)
return; return;
stream->print(F("esphome_fan_failed{id=\"")); stream->print(F("esphome_fan_failed{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} 0\n")); stream->print(F("\"} 0\n"));
// Data itself // Data itself
stream->print(F("esphome_fan_value{id=\"")); stream->print(F("esphome_fan_value{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} ")); stream->print(F("\"} "));
@ -162,6 +219,9 @@ void PrometheusHandler::fan_row_(AsyncResponseStream *stream, fan::Fan *obj) {
if (obj->get_traits().supports_speed()) { if (obj->get_traits().supports_speed()) {
stream->print(F("esphome_fan_speed{id=\"")); stream->print(F("esphome_fan_speed{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} ")); stream->print(F("\"} "));
@ -172,6 +232,9 @@ void PrometheusHandler::fan_row_(AsyncResponseStream *stream, fan::Fan *obj) {
if (obj->get_traits().supports_oscillation()) { if (obj->get_traits().supports_oscillation()) {
stream->print(F("esphome_fan_oscillation{id=\"")); stream->print(F("esphome_fan_oscillation{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} ")); stream->print(F("\"} "));
@ -187,12 +250,16 @@ void PrometheusHandler::light_type_(AsyncResponseStream *stream) {
stream->print(F("#TYPE esphome_light_color gauge\n")); stream->print(F("#TYPE esphome_light_color gauge\n"));
stream->print(F("#TYPE esphome_light_effect_active gauge\n")); stream->print(F("#TYPE esphome_light_effect_active gauge\n"));
} }
void PrometheusHandler::light_row_(AsyncResponseStream *stream, light::LightState *obj) { void PrometheusHandler::light_row_(AsyncResponseStream *stream, light::LightState *obj, std::string &area,
std::string &node, std::string &friendly_name) {
if (obj->is_internal() && !this->include_internal_) if (obj->is_internal() && !this->include_internal_)
return; return;
// State // State
stream->print(F("esphome_light_state{id=\"")); stream->print(F("esphome_light_state{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} ")); stream->print(F("\"} "));
@ -205,6 +272,9 @@ void PrometheusHandler::light_row_(AsyncResponseStream *stream, light::LightStat
color.as_rgbw(&r, &g, &b, &w); color.as_rgbw(&r, &g, &b, &w);
stream->print(F("esphome_light_color{id=\"")); stream->print(F("esphome_light_color{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\",channel=\"brightness\"} ")); stream->print(F("\",channel=\"brightness\"} "));
@ -212,6 +282,9 @@ void PrometheusHandler::light_row_(AsyncResponseStream *stream, light::LightStat
stream->print(F("\n")); stream->print(F("\n"));
stream->print(F("esphome_light_color{id=\"")); stream->print(F("esphome_light_color{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\",channel=\"r\"} ")); stream->print(F("\",channel=\"r\"} "));
@ -219,6 +292,9 @@ void PrometheusHandler::light_row_(AsyncResponseStream *stream, light::LightStat
stream->print(F("\n")); stream->print(F("\n"));
stream->print(F("esphome_light_color{id=\"")); stream->print(F("esphome_light_color{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\",channel=\"g\"} ")); stream->print(F("\",channel=\"g\"} "));
@ -226,6 +302,9 @@ void PrometheusHandler::light_row_(AsyncResponseStream *stream, light::LightStat
stream->print(F("\n")); stream->print(F("\n"));
stream->print(F("esphome_light_color{id=\"")); stream->print(F("esphome_light_color{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\",channel=\"b\"} ")); stream->print(F("\",channel=\"b\"} "));
@ -233,6 +312,9 @@ void PrometheusHandler::light_row_(AsyncResponseStream *stream, light::LightStat
stream->print(F("\n")); stream->print(F("\n"));
stream->print(F("esphome_light_color{id=\"")); stream->print(F("esphome_light_color{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\",channel=\"w\"} ")); stream->print(F("\",channel=\"w\"} "));
@ -243,12 +325,18 @@ void PrometheusHandler::light_row_(AsyncResponseStream *stream, light::LightStat
if (effect == "None") { if (effect == "None") {
stream->print(F("esphome_light_effect_active{id=\"")); stream->print(F("esphome_light_effect_active{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\",effect=\"None\"} 0\n")); stream->print(F("\",effect=\"None\"} 0\n"));
} else { } else {
stream->print(F("esphome_light_effect_active{id=\"")); stream->print(F("esphome_light_effect_active{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\",effect=\"")); stream->print(F("\",effect=\""));
@ -263,19 +351,26 @@ void PrometheusHandler::cover_type_(AsyncResponseStream *stream) {
stream->print(F("#TYPE esphome_cover_value gauge\n")); stream->print(F("#TYPE esphome_cover_value gauge\n"));
stream->print(F("#TYPE esphome_cover_failed gauge\n")); stream->print(F("#TYPE esphome_cover_failed gauge\n"));
} }
void PrometheusHandler::cover_row_(AsyncResponseStream *stream, cover::Cover *obj) { void PrometheusHandler::cover_row_(AsyncResponseStream *stream, cover::Cover *obj, std::string &area, std::string &node,
std::string &friendly_name) {
if (obj->is_internal() && !this->include_internal_) if (obj->is_internal() && !this->include_internal_)
return; return;
if (!std::isnan(obj->position)) { if (!std::isnan(obj->position)) {
// We have a valid value, output this value // We have a valid value, output this value
stream->print(F("esphome_cover_failed{id=\"")); stream->print(F("esphome_cover_failed{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} 0\n")); stream->print(F("\"} 0\n"));
// Data itself // Data itself
stream->print(F("esphome_cover_value{id=\"")); stream->print(F("esphome_cover_value{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} ")); stream->print(F("\"} "));
@ -284,6 +379,9 @@ void PrometheusHandler::cover_row_(AsyncResponseStream *stream, cover::Cover *ob
if (obj->get_traits().get_supports_tilt()) { if (obj->get_traits().get_supports_tilt()) {
stream->print(F("esphome_cover_tilt{id=\"")); stream->print(F("esphome_cover_tilt{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} ")); stream->print(F("\"} "));
@ -294,6 +392,9 @@ void PrometheusHandler::cover_row_(AsyncResponseStream *stream, cover::Cover *ob
// Invalid state // Invalid state
stream->print(F("esphome_cover_failed{id=\"")); stream->print(F("esphome_cover_failed{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} 1\n")); stream->print(F("\"} 1\n"));
@ -306,17 +407,24 @@ void PrometheusHandler::switch_type_(AsyncResponseStream *stream) {
stream->print(F("#TYPE esphome_switch_value gauge\n")); stream->print(F("#TYPE esphome_switch_value gauge\n"));
stream->print(F("#TYPE esphome_switch_failed gauge\n")); stream->print(F("#TYPE esphome_switch_failed gauge\n"));
} }
void PrometheusHandler::switch_row_(AsyncResponseStream *stream, switch_::Switch *obj) { void PrometheusHandler::switch_row_(AsyncResponseStream *stream, switch_::Switch *obj, std::string &area,
std::string &node, std::string &friendly_name) {
if (obj->is_internal() && !this->include_internal_) if (obj->is_internal() && !this->include_internal_)
return; return;
stream->print(F("esphome_switch_failed{id=\"")); stream->print(F("esphome_switch_failed{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} 0\n")); stream->print(F("\"} 0\n"));
// Data itself // Data itself
stream->print(F("esphome_switch_value{id=\"")); stream->print(F("esphome_switch_value{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} ")); stream->print(F("\"} "));
@ -330,17 +438,24 @@ void PrometheusHandler::lock_type_(AsyncResponseStream *stream) {
stream->print(F("#TYPE esphome_lock_value gauge\n")); stream->print(F("#TYPE esphome_lock_value gauge\n"));
stream->print(F("#TYPE esphome_lock_failed gauge\n")); stream->print(F("#TYPE esphome_lock_failed gauge\n"));
} }
void PrometheusHandler::lock_row_(AsyncResponseStream *stream, lock::Lock *obj) { void PrometheusHandler::lock_row_(AsyncResponseStream *stream, lock::Lock *obj, std::string &area, std::string &node,
std::string &friendly_name) {
if (obj->is_internal() && !this->include_internal_) if (obj->is_internal() && !this->include_internal_)
return; return;
stream->print(F("esphome_lock_failed{id=\"")); stream->print(F("esphome_lock_failed{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} 0\n")); stream->print(F("\"} 0\n"));
// Data itself // Data itself
stream->print(F("esphome_lock_value{id=\"")); stream->print(F("esphome_lock_value{id=\""));
stream->print(relabel_id_(obj).c_str()); stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\"")); stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str()); stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} ")); stream->print(F("\"} "));
@ -349,6 +464,53 @@ void PrometheusHandler::lock_row_(AsyncResponseStream *stream, lock::Lock *obj)
} }
#endif #endif
// Type-specific implementation
#ifdef USE_TEXT_SENSOR
void PrometheusHandler::text_sensor_type_(AsyncResponseStream *stream) {
stream->print(F("#TYPE esphome_text_sensor_value gauge\n"));
stream->print(F("#TYPE esphome_text_sensor_failed gauge\n"));
}
void PrometheusHandler::text_sensor_row_(AsyncResponseStream *stream, text_sensor::TextSensor *obj, std::string &area,
std::string &node, std::string &friendly_name) {
if (obj->is_internal() && !this->include_internal_)
return;
if (obj->has_state()) {
// We have a valid value, output this value
stream->print(F("esphome_text_sensor_failed{id=\""));
stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} 0\n"));
// Data itself
stream->print(F("esphome_text_sensor_value{id=\""));
stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str());
stream->print(F("\",value=\""));
stream->print(obj->state.c_str());
stream->print(F("\"} "));
stream->print(F("1.0"));
stream->print(F("\n"));
} else {
// Invalid state
stream->print(F("esphome_text_sensor_failed{id=\""));
stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} 1\n"));
}
}
#endif
} // namespace prometheus } // namespace prometheus
} // namespace esphome } // namespace esphome
#endif #endif

View File

@ -60,54 +60,72 @@ class PrometheusHandler : public AsyncWebHandler, public Component {
protected: protected:
std::string relabel_id_(EntityBase *obj); std::string relabel_id_(EntityBase *obj);
std::string relabel_name_(EntityBase *obj); std::string relabel_name_(EntityBase *obj);
void add_area_label_(AsyncResponseStream *stream, std::string &area);
void add_node_label_(AsyncResponseStream *stream, std::string &node);
void add_friendly_name_label_(AsyncResponseStream *stream, std::string &friendly_name);
#ifdef USE_SENSOR #ifdef USE_SENSOR
/// Return the type for prometheus /// Return the type for prometheus
void sensor_type_(AsyncResponseStream *stream); void sensor_type_(AsyncResponseStream *stream);
/// Return the sensor state as prometheus data point /// Return the sensor state as prometheus data point
void sensor_row_(AsyncResponseStream *stream, sensor::Sensor *obj); void sensor_row_(AsyncResponseStream *stream, sensor::Sensor *obj, std::string &area, std::string &node,
std::string &friendly_name);
#endif #endif
#ifdef USE_BINARY_SENSOR #ifdef USE_BINARY_SENSOR
/// Return the type for prometheus /// Return the type for prometheus
void binary_sensor_type_(AsyncResponseStream *stream); void binary_sensor_type_(AsyncResponseStream *stream);
/// Return the sensor state as prometheus data point /// Return the sensor state as prometheus data point
void binary_sensor_row_(AsyncResponseStream *stream, binary_sensor::BinarySensor *obj); void binary_sensor_row_(AsyncResponseStream *stream, binary_sensor::BinarySensor *obj, std::string &area,
std::string &node, std::string &friendly_name);
#endif #endif
#ifdef USE_FAN #ifdef USE_FAN
/// Return the type for prometheus /// Return the type for prometheus
void fan_type_(AsyncResponseStream *stream); void fan_type_(AsyncResponseStream *stream);
/// Return the sensor state as prometheus data point /// Return the sensor state as prometheus data point
void fan_row_(AsyncResponseStream *stream, fan::Fan *obj); void fan_row_(AsyncResponseStream *stream, fan::Fan *obj, std::string &area, std::string &node,
std::string &friendly_name);
#endif #endif
#ifdef USE_LIGHT #ifdef USE_LIGHT
/// Return the type for prometheus /// Return the type for prometheus
void light_type_(AsyncResponseStream *stream); void light_type_(AsyncResponseStream *stream);
/// Return the Light Values state as prometheus data point /// Return the Light Values state as prometheus data point
void light_row_(AsyncResponseStream *stream, light::LightState *obj); void light_row_(AsyncResponseStream *stream, light::LightState *obj, std::string &area, std::string &node,
std::string &friendly_name);
#endif #endif
#ifdef USE_COVER #ifdef USE_COVER
/// Return the type for prometheus /// Return the type for prometheus
void cover_type_(AsyncResponseStream *stream); void cover_type_(AsyncResponseStream *stream);
/// Return the switch Values state as prometheus data point /// Return the switch Values state as prometheus data point
void cover_row_(AsyncResponseStream *stream, cover::Cover *obj); void cover_row_(AsyncResponseStream *stream, cover::Cover *obj, std::string &area, std::string &node,
std::string &friendly_name);
#endif #endif
#ifdef USE_SWITCH #ifdef USE_SWITCH
/// Return the type for prometheus /// Return the type for prometheus
void switch_type_(AsyncResponseStream *stream); void switch_type_(AsyncResponseStream *stream);
/// Return the switch Values state as prometheus data point /// Return the switch Values state as prometheus data point
void switch_row_(AsyncResponseStream *stream, switch_::Switch *obj); void switch_row_(AsyncResponseStream *stream, switch_::Switch *obj, std::string &area, std::string &node,
std::string &friendly_name);
#endif #endif
#ifdef USE_LOCK #ifdef USE_LOCK
/// Return the type for prometheus /// Return the type for prometheus
void lock_type_(AsyncResponseStream *stream); void lock_type_(AsyncResponseStream *stream);
/// Return the lock Values state as prometheus data point /// Return the lock Values state as prometheus data point
void lock_row_(AsyncResponseStream *stream, lock::Lock *obj); void lock_row_(AsyncResponseStream *stream, lock::Lock *obj, std::string &area, std::string &node,
std::string &friendly_name);
#endif
#ifdef USE_TEXT_SENSOR
/// Return the type for prometheus
void text_sensor_type_(AsyncResponseStream *stream);
/// Return the lock Values state as prometheus data point
void text_sensor_row_(AsyncResponseStream *stream, text_sensor::TextSensor *obj, std::string &area, std::string &node,
std::string &friendly_name);
#endif #endif
web_server_base::WebServerBase *base_; web_server_base::WebServerBase *base_;

View File

@ -1,6 +1,8 @@
from esphome import pins
import esphome.codegen as cg import esphome.codegen as cg
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome.const import ( from esphome.const import (
CONF_ANALOG,
CONF_ID, CONF_ID,
CONF_INPUT, CONF_INPUT,
CONF_INVERTED, CONF_INVERTED,
@ -10,10 +12,8 @@ from esphome.const import (
CONF_OUTPUT, CONF_OUTPUT,
CONF_PULLDOWN, CONF_PULLDOWN,
CONF_PULLUP, CONF_PULLUP,
CONF_ANALOG,
) )
from esphome.core import CORE from esphome.core import CORE
from esphome import pins
from . import boards from . import boards
from .const import KEY_BOARD, KEY_RP2040, rp2040_ns from .const import KEY_BOARD, KEY_RP2040, rp2040_ns
@ -41,8 +41,10 @@ def _translate_pin(value):
"This variable only supports pin numbers, not full pin schemas " "This variable only supports pin numbers, not full pin schemas "
"(with inverted and mode)." "(with inverted and mode)."
) )
if isinstance(value, int): if isinstance(value, int) and not isinstance(value, bool):
return value return value
if not isinstance(value, str):
raise cv.Invalid(f"Invalid pin number: {value}")
try: try:
return int(value) return int(value)
except ValueError: except ValueError:

View File

@ -84,6 +84,26 @@ void RpiDpiRgb::draw_pixels_at(int x_start, int y_start, int w, int h, const uin
ESP_LOGE(TAG, "lcd_lcd_panel_draw_bitmap failed: %s", esp_err_to_name(err)); ESP_LOGE(TAG, "lcd_lcd_panel_draw_bitmap failed: %s", esp_err_to_name(err));
} }
int RpiDpiRgb::get_width() {
switch (this->rotation_) {
case display::DISPLAY_ROTATION_90_DEGREES:
case display::DISPLAY_ROTATION_270_DEGREES:
return this->get_height_internal();
default:
return this->get_width_internal();
}
}
int RpiDpiRgb::get_height() {
switch (this->rotation_) {
case display::DISPLAY_ROTATION_90_DEGREES:
case display::DISPLAY_ROTATION_270_DEGREES:
return this->get_width_internal();
default:
return this->get_height_internal();
}
}
void RpiDpiRgb::draw_pixel_at(int x, int y, Color color) { void RpiDpiRgb::draw_pixel_at(int x, int y, Color color) {
if (!this->get_clipping().inside(x, y)) if (!this->get_clipping().inside(x, y))
return; // NOLINT return; // NOLINT

View File

@ -24,6 +24,7 @@ class RpiDpiRgb : public display::Display {
void update() override { this->do_update_(); } void update() override { this->do_update_(); }
void setup() override; void setup() override;
void loop() override; void loop() override;
float get_setup_priority() const override { return setup_priority::HARDWARE; }
void draw_pixels_at(int x_start, int y_start, int w, int h, const uint8_t *ptr, display::ColorOrder order, void draw_pixels_at(int x_start, int y_start, int w, int h, const uint8_t *ptr, display::ColorOrder order,
display::ColorBitness bitness, bool big_endian, int x_offset, int y_offset, int x_pad) override; display::ColorBitness bitness, bool big_endian, int x_offset, int y_offset, int x_pad) override;
void draw_pixel_at(int x, int y, Color color) override; void draw_pixel_at(int x, int y, Color color) override;
@ -44,8 +45,8 @@ class RpiDpiRgb : public display::Display {
this->width_ = width; this->width_ = width;
this->height_ = height; this->height_ = height;
} }
int get_width() override { return this->width_; } int get_width() override;
int get_height() override { return this->height_; } int get_height() override;
void set_hsync_back_porch(uint16_t hsync_back_porch) { this->hsync_back_porch_ = hsync_back_porch; } void set_hsync_back_porch(uint16_t hsync_back_porch) { this->hsync_back_porch_ = hsync_back_porch; }
void set_hsync_front_porch(uint16_t hsync_front_porch) { this->hsync_front_porch_ = hsync_front_porch; } void set_hsync_front_porch(uint16_t hsync_front_porch) { this->hsync_front_porch_ = hsync_front_porch; }
void set_hsync_pulse_width(uint16_t hsync_pulse_width) { this->hsync_pulse_width_ = hsync_pulse_width; } void set_hsync_pulse_width(uint16_t hsync_pulse_width) { this->hsync_pulse_width_ = hsync_pulse_width; }

View File

@ -9,8 +9,9 @@ void Sdl::setup() {
ESP_LOGD(TAG, "Starting setup"); ESP_LOGD(TAG, "Starting setup");
SDL_Init(SDL_INIT_VIDEO); SDL_Init(SDL_INIT_VIDEO);
this->window_ = SDL_CreateWindow(App.get_name().c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, this->window_ = SDL_CreateWindow(App.get_name().c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
this->width_, this->height_, 0); this->width_, this->height_, SDL_WINDOW_RESIZABLE);
this->renderer_ = SDL_CreateRenderer(this->window_, -1, SDL_RENDERER_SOFTWARE); this->renderer_ = SDL_CreateRenderer(this->window_, -1, SDL_RENDERER_SOFTWARE);
SDL_RenderSetLogicalSize(this->renderer_, this->width_, this->height_);
this->texture_ = this->texture_ =
SDL_CreateTexture(this->renderer_, SDL_PIXELFORMAT_RGB565, SDL_TEXTUREACCESS_STATIC, this->width_, this->height_); SDL_CreateTexture(this->renderer_, SDL_PIXELFORMAT_RGB565, SDL_TEXTUREACCESS_STATIC, this->width_, this->height_);
SDL_SetTextureBlendMode(this->texture_, SDL_BLENDMODE_BLEND); SDL_SetTextureBlendMode(this->texture_, SDL_BLENDMODE_BLEND);
@ -25,6 +26,10 @@ void Sdl::update() {
this->y_low_ = this->height_; this->y_low_ = this->height_;
this->x_high_ = 0; this->x_high_ = 0;
this->y_high_ = 0; this->y_high_ = 0;
this->redraw_(rect);
}
void Sdl::redraw_(SDL_Rect &rect) {
SDL_RenderCopy(this->renderer_, this->texture_, &rect, &rect); SDL_RenderCopy(this->renderer_, this->texture_, &rect, &rect);
SDL_RenderPresent(this->renderer_); SDL_RenderPresent(this->renderer_);
} }
@ -33,15 +38,13 @@ void Sdl::draw_pixels_at(int x_start, int y_start, int w, int h, const uint8_t *
display::ColorBitness bitness, bool big_endian, int x_offset, int y_offset, int x_pad) { display::ColorBitness bitness, bool big_endian, int x_offset, int y_offset, int x_pad) {
SDL_Rect rect{x_start, y_start, w, h}; SDL_Rect rect{x_start, y_start, w, h};
if (this->rotation_ != display::DISPLAY_ROTATION_0_DEGREES || bitness != display::COLOR_BITNESS_565 || big_endian) { if (this->rotation_ != display::DISPLAY_ROTATION_0_DEGREES || bitness != display::COLOR_BITNESS_565 || big_endian) {
display::Display::draw_pixels_at(x_start, y_start, w, h, ptr, order, bitness, big_endian, x_offset, y_offset, Display::draw_pixels_at(x_start, y_start, w, h, ptr, order, bitness, big_endian, x_offset, y_offset, x_pad);
x_pad);
} else { } else {
auto stride = x_offset + w + x_pad; auto stride = x_offset + w + x_pad;
auto data = ptr + (stride * y_offset + x_offset) * 2; auto data = ptr + (stride * y_offset + x_offset) * 2;
SDL_UpdateTexture(this->texture_, &rect, data, stride * 2); SDL_UpdateTexture(this->texture_, &rect, data, stride * 2);
} }
SDL_RenderCopy(this->renderer_, this->texture_, &rect, &rect); this->redraw_(rect);
SDL_RenderPresent(this->renderer_);
} }
void Sdl::draw_pixel_at(int x, int y, Color color) { void Sdl::draw_pixel_at(int x, int y, Color color) {
@ -84,6 +87,20 @@ void Sdl::loop() {
} }
break; break;
case SDL_WINDOWEVENT:
switch (e.window.event) {
case SDL_WINDOWEVENT_SIZE_CHANGED:
case SDL_WINDOWEVENT_EXPOSED:
case SDL_WINDOWEVENT_RESIZED: {
SDL_Rect rect{0, 0, this->width_, this->height_};
this->redraw_(rect);
break;
}
default:
break;
}
break;
default: default:
ESP_LOGV(TAG, "Event %d", e.type); ESP_LOGV(TAG, "Event %d", e.type);
break; break;

View File

@ -38,6 +38,7 @@ class Sdl : public display::Display {
protected: protected:
int get_width_internal() override { return this->width_; } int get_width_internal() override { return this->width_; }
int get_height_internal() override { return this->height_; } int get_height_internal() override { return this->height_; }
void redraw_(SDL_Rect &rect);
int width_{}; int width_{};
int height_{}; int height_{};
SDL_Renderer *renderer_{}; SDL_Renderer *renderer_{};

View File

@ -111,7 +111,7 @@ void SGP4xComponent::setup() {
number of records reported from being overwhelming. number of records reported from being overwhelming.
*/ */
ESP_LOGD(TAG, "Component requires sampling of 1Hz, setting up background sampler"); ESP_LOGD(TAG, "Component requires sampling of 1Hz, setting up background sampler");
this->set_interval(1000, [this]() { this->update_gas_indices(); }); this->set_interval(1000, [this]() { this->take_sample(); });
} }
void SGP4xComponent::self_test_() { void SGP4xComponent::self_test_() {
@ -146,31 +146,15 @@ void SGP4xComponent::self_test_() {
}); });
} }
/** void SGP4xComponent::update_gas_indices_() {
* @brief Combined the measured gasses, temperature, and humidity this->voc_index_ = this->voc_algorithm_.process(this->voc_sraw_);
* to calculate the VOC Index if (this->nox_sensor_ != nullptr)
* this->nox_index_ = this->nox_algorithm_.process(this->nox_sraw_);
* @param temperature The measured temperature in degrees C ESP_LOGV(TAG, "VOC = %" PRId32 ", NOx = %" PRId32, this->voc_index_, this->nox_index_);
* @param humidity The measured relative humidity in % rH
* @return int32_t The VOC Index
*/
bool SGP4xComponent::measure_gas_indices_(int32_t &voc, int32_t &nox) {
uint16_t voc_sraw;
uint16_t nox_sraw;
if (!measure_raw_(voc_sraw, nox_sraw))
return false;
this->status_clear_warning();
voc = voc_algorithm_.process(voc_sraw);
if (nox_sensor_) {
nox = nox_algorithm_.process(nox_sraw);
}
ESP_LOGV(TAG, "VOC = %" PRId32 ", NOx = %" PRId32, voc, nox);
// Store baselines after defined interval or if the difference between current and stored baseline becomes too // Store baselines after defined interval or if the difference between current and stored baseline becomes too
// much // much
if (this->store_baseline_ && this->seconds_since_last_store_ > SHORTEST_BASELINE_STORE_INTERVAL) { if (this->store_baseline_ && this->seconds_since_last_store_ > SHORTEST_BASELINE_STORE_INTERVAL) {
voc_algorithm_.get_states(this->voc_state0_, this->voc_state1_); this->voc_algorithm_.get_states(this->voc_state0_, this->voc_state1_);
if (std::abs(this->voc_baselines_storage_.state0 - this->voc_state0_) > MAXIMUM_STORAGE_DIFF || if (std::abs(this->voc_baselines_storage_.state0 - this->voc_state0_) > MAXIMUM_STORAGE_DIFF ||
std::abs(this->voc_baselines_storage_.state1 - this->voc_state1_) > MAXIMUM_STORAGE_DIFF) { std::abs(this->voc_baselines_storage_.state1 - this->voc_state1_) > MAXIMUM_STORAGE_DIFF) {
this->seconds_since_last_store_ = 0; this->seconds_since_last_store_ = 0;
@ -179,29 +163,27 @@ bool SGP4xComponent::measure_gas_indices_(int32_t &voc, int32_t &nox) {
if (this->pref_.save(&this->voc_baselines_storage_)) { if (this->pref_.save(&this->voc_baselines_storage_)) {
ESP_LOGI(TAG, "Stored VOC baseline state0: 0x%04" PRIX32 " ,state1: 0x%04" PRIX32, ESP_LOGI(TAG, "Stored VOC baseline state0: 0x%04" PRIX32 " ,state1: 0x%04" PRIX32,
this->voc_baselines_storage_.state0, voc_baselines_storage_.state1); this->voc_baselines_storage_.state0, this->voc_baselines_storage_.state1);
} else { } else {
ESP_LOGW(TAG, "Could not store VOC baselines"); ESP_LOGW(TAG, "Could not store VOC baselines");
} }
} }
} }
return true; if (this->samples_read_ < this->samples_to_stabilize_) {
this->samples_read_++;
ESP_LOGD(TAG, "Sensor has not collected enough samples yet. (%d/%d) VOC index is: %" PRIu32, this->samples_read_,
this->samples_to_stabilize_, this->voc_index_);
}
} }
/**
* @brief Return the raw gas measurement void SGP4xComponent::measure_raw_() {
*
* @param temperature The measured temperature in degrees C
* @param humidity The measured relative humidity in % rH
* @return uint16_t The current raw gas measurement
*/
bool SGP4xComponent::measure_raw_(uint16_t &voc_raw, uint16_t &nox_raw) {
float humidity = NAN; float humidity = NAN;
static uint32_t nox_conditioning_start = millis(); static uint32_t nox_conditioning_start = millis();
if (!this->self_test_complete_) { if (!this->self_test_complete_) {
ESP_LOGD(TAG, "Self-test not yet complete"); ESP_LOGD(TAG, "Self-test not yet complete");
return false; return;
} }
if (this->humidity_sensor_ != nullptr) { if (this->humidity_sensor_ != nullptr) {
humidity = this->humidity_sensor_->state; humidity = this->humidity_sensor_->state;
@ -243,61 +225,45 @@ bool SGP4xComponent::measure_raw_(uint16_t &voc_raw, uint16_t &nox_raw) {
data[1] = tempticks; data[1] = tempticks;
if (!this->write_command(command, data, 2)) { if (!this->write_command(command, data, 2)) {
this->status_set_warning();
ESP_LOGD(TAG, "write error (%d)", this->last_error_); ESP_LOGD(TAG, "write error (%d)", this->last_error_);
return false; this->status_set_warning("measurement request failed");
return;
} }
delay(measure_time_);
uint16_t raw_data[2]; this->set_timeout(this->measure_time_, [this, response_words]() {
raw_data[1] = 0; uint16_t raw_data[2];
if (!this->read_data(raw_data, response_words)) { raw_data[1] = 0;
this->status_set_warning(); if (!this->read_data(raw_data, response_words)) {
ESP_LOGD(TAG, "read error (%d)", this->last_error_); ESP_LOGD(TAG, "read error (%d)", this->last_error_);
return false; this->status_set_warning("measurement read failed");
} this->voc_index_ = this->nox_index_ = UINT16_MAX;
voc_raw = raw_data[0]; return;
nox_raw = raw_data[1]; // either 0 or the measured NOx ticks }
return true; this->voc_sraw_ = raw_data[0];
this->nox_sraw_ = raw_data[1]; // either 0 or the measured NOx ticks
this->status_clear_warning();
this->update_gas_indices_();
});
} }
void SGP4xComponent::update_gas_indices() { void SGP4xComponent::take_sample() {
if (!this->self_test_complete_) if (!this->self_test_complete_)
return; return;
this->seconds_since_last_store_ += 1; this->seconds_since_last_store_ += 1;
if (!this->measure_gas_indices_(this->voc_index_, this->nox_index_)) { this->measure_raw_();
// Set values to UINT16_MAX to indicate failure
this->voc_index_ = this->nox_index_ = UINT16_MAX;
ESP_LOGE(TAG, "measure gas indices failed");
return;
}
if (this->samples_read_ < this->samples_to_stabilize_) {
this->samples_read_++;
ESP_LOGD(TAG, "Sensor has not collected enough samples yet. (%d/%d) VOC index is: %" PRIu32, this->samples_read_,
this->samples_to_stabilize_, this->voc_index_);
return;
}
} }
void SGP4xComponent::update() { void SGP4xComponent::update() {
if (this->samples_read_ < this->samples_to_stabilize_) { if (this->samples_read_ < this->samples_to_stabilize_) {
return; return;
} }
if (this->voc_sensor_) { if (this->voc_sensor_ != nullptr) {
if (this->voc_index_ != UINT16_MAX) { if (this->voc_index_ != UINT16_MAX)
this->status_clear_warning();
this->voc_sensor_->publish_state(this->voc_index_); this->voc_sensor_->publish_state(this->voc_index_);
} else {
this->status_set_warning();
}
} }
if (this->nox_sensor_) { if (this->nox_sensor_ != nullptr) {
if (this->nox_index_ != UINT16_MAX) { if (this->nox_index_ != UINT16_MAX)
this->status_clear_warning();
this->nox_sensor_->publish_state(this->nox_index_); this->nox_sensor_->publish_state(this->nox_index_);
} else {
this->status_set_warning();
}
} }
} }
@ -329,7 +295,7 @@ void SGP4xComponent::dump_config() {
} }
LOG_UPDATE_INTERVAL(this); LOG_UPDATE_INTERVAL(this);
if (this->humidity_sensor_ != nullptr && this->temperature_sensor_ != nullptr) { if (this->humidity_sensor_ != nullptr || this->temperature_sensor_ != nullptr) {
ESP_LOGCONFIG(TAG, " Compensation:"); ESP_LOGCONFIG(TAG, " Compensation:");
LOG_SENSOR(" ", "Temperature Source:", this->temperature_sensor_); LOG_SENSOR(" ", "Temperature Source:", this->temperature_sensor_);
LOG_SENSOR(" ", "Humidity Source:", this->humidity_sensor_); LOG_SENSOR(" ", "Humidity Source:", this->humidity_sensor_);

View File

@ -73,7 +73,7 @@ class SGP4xComponent : public PollingComponent, public sensor::Sensor, public se
void setup() override; void setup() override;
void update() override; void update() override;
void update_gas_indices(); void take_sample();
void dump_config() override; void dump_config() override;
float get_setup_priority() const override { return setup_priority::DATA; } float get_setup_priority() const override { return setup_priority::DATA; }
void set_store_baseline(bool store_baseline) { store_baseline_ = store_baseline; } void set_store_baseline(bool store_baseline) { store_baseline_ = store_baseline; }
@ -108,8 +108,10 @@ class SGP4xComponent : public PollingComponent, public sensor::Sensor, public se
sensor::Sensor *temperature_sensor_{nullptr}; sensor::Sensor *temperature_sensor_{nullptr};
int16_t sensirion_init_sensors_(); int16_t sensirion_init_sensors_();
bool measure_gas_indices_(int32_t &voc, int32_t &nox); void update_gas_indices_();
bool measure_raw_(uint16_t &voc_raw, uint16_t &nox_raw); void measure_raw_();
uint16_t voc_sraw_;
uint16_t nox_sraw_;
SgpType sgp_type_{SGP40}; SgpType sgp_type_{SGP40};
uint64_t serial_number_; uint64_t serial_number_;

View File

@ -1,40 +1,37 @@
import re import re
from esphome import pins
import esphome.codegen as cg import esphome.codegen as cg
import esphome.config_validation as cv
import esphome.final_validate as fv
from esphome.components.esp32.const import ( from esphome.components.esp32.const import (
KEY_ESP32, KEY_ESP32,
VARIANT_ESP32S2,
VARIANT_ESP32S3,
VARIANT_ESP32C2, VARIANT_ESP32C2,
VARIANT_ESP32C3, VARIANT_ESP32C3,
VARIANT_ESP32C6, VARIANT_ESP32C6,
VARIANT_ESP32H2, VARIANT_ESP32H2,
VARIANT_ESP32S2,
VARIANT_ESP32S3,
) )
from esphome import pins import esphome.config_validation as cv
from esphome.const import ( from esphome.const import (
CONF_CLK_PIN, CONF_CLK_PIN,
CONF_CS_PIN,
CONF_DATA_PINS,
CONF_DATA_RATE,
CONF_ID, CONF_ID,
CONF_INVERTED,
CONF_MISO_PIN, CONF_MISO_PIN,
CONF_MOSI_PIN, CONF_MOSI_PIN,
CONF_SPI_ID,
CONF_CS_PIN,
CONF_NUMBER, CONF_NUMBER,
CONF_INVERTED, CONF_SPI_ID,
KEY_CORE, KEY_CORE,
KEY_TARGET_PLATFORM, KEY_TARGET_PLATFORM,
KEY_VARIANT, KEY_VARIANT,
CONF_DATA_RATE,
PLATFORM_ESP32, PLATFORM_ESP32,
PLATFORM_ESP8266, PLATFORM_ESP8266,
PLATFORM_RP2040, PLATFORM_RP2040,
CONF_DATA_PINS,
)
from esphome.core import (
coroutine_with_priority,
CORE,
) )
from esphome.core import CORE, coroutine_with_priority
import esphome.final_validate as fv
CODEOWNERS = ["@esphome/core", "@clydebarrow"] CODEOWNERS = ["@esphome/core", "@clydebarrow"]
spi_ns = cg.esphome_ns.namespace("spi") spi_ns = cg.esphome_ns.namespace("spi")
@ -69,6 +66,10 @@ SPI_MODE_OPTIONS = {
1: SPIMode.MODE1, 1: SPIMode.MODE1,
2: SPIMode.MODE2, 2: SPIMode.MODE2,
3: SPIMode.MODE3, 3: SPIMode.MODE3,
"0": SPIMode.MODE0,
"1": SPIMode.MODE1,
"2": SPIMode.MODE2,
"3": SPIMode.MODE3,
} }
CONF_SPI_MODE = "spi_mode" CONF_SPI_MODE = "spi_mode"

View File

@ -1,6 +1,6 @@
import esphome.codegen as cg import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import spi from esphome.components import spi
import esphome.config_validation as cv
from esphome.const import CONF_ID, CONF_MODE from esphome.const import CONF_ID, CONF_MODE
DEPENDENCIES = ["spi"] DEPENDENCIES = ["spi"]
@ -11,18 +11,6 @@ spi_device_ns = cg.esphome_ns.namespace("spi_device")
spi_device = spi_device_ns.class_("SPIDeviceComponent", cg.Component, spi.SPIDevice) spi_device = spi_device_ns.class_("SPIDeviceComponent", cg.Component, spi.SPIDevice)
Mode = spi.spi_ns.enum("SPIMode")
MODES = {
"0": Mode.MODE0,
"1": Mode.MODE1,
"2": Mode.MODE2,
"3": Mode.MODE3,
"MODE0": Mode.MODE0,
"MODE1": Mode.MODE1,
"MODE2": Mode.MODE2,
"MODE3": Mode.MODE3,
}
BitOrder = spi.spi_ns.enum("SPIBitOrder") BitOrder = spi.spi_ns.enum("SPIBitOrder")
ORDERS = { ORDERS = {
"msb_first": BitOrder.BIT_ORDER_MSB_FIRST, "msb_first": BitOrder.BIT_ORDER_MSB_FIRST,
@ -34,7 +22,9 @@ CONFIG_SCHEMA = cv.Schema(
{ {
cv.GenerateID(CONF_ID): cv.declare_id(spi_device), cv.GenerateID(CONF_ID): cv.declare_id(spi_device),
cv.Optional(CONF_BIT_ORDER, default="msb_first"): cv.enum(ORDERS, lower=True), cv.Optional(CONF_BIT_ORDER, default="msb_first"): cv.enum(ORDERS, lower=True),
cv.Optional(CONF_MODE, default="0"): cv.enum(MODES, upper=True), cv.Optional(CONF_MODE): cv.invalid(
"The 'mode' option has been renamed to 'spi_mode'."
),
} }
).extend(spi.spi_device_schema(False, "1MHz")) ).extend(spi.spi_device_schema(False, "1MHz"))
@ -42,6 +32,5 @@ CONFIG_SCHEMA = cv.Schema(
async def to_code(config): async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID]) var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config) await cg.register_component(var, config)
cg.add(var.set_mode(config[CONF_MODE]))
cg.add(var.set_bit_order(config[CONF_BIT_ORDER])) cg.add(var.set_bit_order(config[CONF_BIT_ORDER]))
await spi.register_spi_device(var, config) await spi.register_spi_device(var, config)

View File

@ -1,8 +1,8 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins from esphome import pins
import esphome.codegen as cg
from esphome.components import spi, ssd1306_base from esphome.components import spi, ssd1306_base
from esphome.components.ssd1306_base import _validate from esphome.components.ssd1306_base import _validate
import esphome.config_validation as cv
from esphome.const import CONF_DC_PIN, CONF_ID, CONF_LAMBDA, CONF_PAGES from esphome.const import CONF_DC_PIN, CONF_ID, CONF_LAMBDA, CONF_PAGES
AUTO_LOAD = ["ssd1306_base"] AUTO_LOAD = ["ssd1306_base"]
@ -24,6 +24,10 @@ CONFIG_SCHEMA = cv.All(
_validate, _validate,
) )
FINAL_VALIDATE_SCHEMA = spi.final_validate_device_schema(
"ssd1306_spi", require_miso=False, require_mosi=True
)
async def to_code(config): async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID]) var = cg.new_Pvariable(config[CONF_ID])

View File

@ -1,7 +1,7 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins from esphome import pins
import esphome.codegen as cg
from esphome.components import spi, ssd1322_base from esphome.components import spi, ssd1322_base
import esphome.config_validation as cv
from esphome.const import CONF_DC_PIN, CONF_ID, CONF_LAMBDA, CONF_PAGES from esphome.const import CONF_DC_PIN, CONF_ID, CONF_LAMBDA, CONF_PAGES
CODEOWNERS = ["@kbx81"] CODEOWNERS = ["@kbx81"]
@ -24,6 +24,10 @@ CONFIG_SCHEMA = cv.All(
cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA), cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA),
) )
FINAL_VALIDATE_SCHEMA = spi.final_validate_device_schema(
"ssd1322_spi", require_miso=False, require_mosi=True
)
async def to_code(config): async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID]) var = cg.new_Pvariable(config[CONF_ID])

View File

@ -1,7 +1,7 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins from esphome import pins
import esphome.codegen as cg
from esphome.components import spi, ssd1325_base from esphome.components import spi, ssd1325_base
import esphome.config_validation as cv
from esphome.const import CONF_DC_PIN, CONF_ID, CONF_LAMBDA, CONF_PAGES from esphome.const import CONF_DC_PIN, CONF_ID, CONF_LAMBDA, CONF_PAGES
CODEOWNERS = ["@kbx81"] CODEOWNERS = ["@kbx81"]
@ -24,6 +24,10 @@ CONFIG_SCHEMA = cv.All(
cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA), cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA),
) )
FINAL_VALIDATE_SCHEMA = spi.final_validate_device_schema(
"ssd1325_spi", require_miso=False, require_mosi=True
)
async def to_code(config): async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID]) var = cg.new_Pvariable(config[CONF_ID])

View File

@ -1,7 +1,7 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins from esphome import pins
import esphome.codegen as cg
from esphome.components import spi, ssd1327_base from esphome.components import spi, ssd1327_base
import esphome.config_validation as cv
from esphome.const import CONF_DC_PIN, CONF_ID, CONF_LAMBDA, CONF_PAGES from esphome.const import CONF_DC_PIN, CONF_ID, CONF_LAMBDA, CONF_PAGES
CODEOWNERS = ["@kbx81"] CODEOWNERS = ["@kbx81"]
@ -24,6 +24,10 @@ CONFIG_SCHEMA = cv.All(
cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA), cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA),
) )
FINAL_VALIDATE_SCHEMA = spi.final_validate_device_schema(
"ssd1327_spi", require_miso=False, require_mosi=True
)
async def to_code(config): async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID]) var = cg.new_Pvariable(config[CONF_ID])

View File

@ -1,7 +1,7 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins from esphome import pins
import esphome.codegen as cg
from esphome.components import spi, ssd1331_base from esphome.components import spi, ssd1331_base
import esphome.config_validation as cv
from esphome.const import CONF_DC_PIN, CONF_ID, CONF_LAMBDA, CONF_PAGES from esphome.const import CONF_DC_PIN, CONF_ID, CONF_LAMBDA, CONF_PAGES
CODEOWNERS = ["@kbx81"] CODEOWNERS = ["@kbx81"]
@ -24,6 +24,10 @@ CONFIG_SCHEMA = cv.All(
cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA), cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA),
) )
FINAL_VALIDATE_SCHEMA = spi.final_validate_device_schema(
"ssd1331_spi", require_miso=False, require_mosi=True
)
async def to_code(config): async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID]) var = cg.new_Pvariable(config[CONF_ID])

View File

@ -1,7 +1,7 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins from esphome import pins
import esphome.codegen as cg
from esphome.components import spi, ssd1351_base from esphome.components import spi, ssd1351_base
import esphome.config_validation as cv
from esphome.const import CONF_DC_PIN, CONF_ID, CONF_LAMBDA, CONF_PAGES from esphome.const import CONF_DC_PIN, CONF_ID, CONF_LAMBDA, CONF_PAGES
CODEOWNERS = ["@kbx81"] CODEOWNERS = ["@kbx81"]
@ -24,6 +24,10 @@ CONFIG_SCHEMA = cv.All(
cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA), cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA),
) )
FINAL_VALIDATE_SCHEMA = spi.final_validate_device_schema(
"ssd1351_spi", require_miso=False, require_mosi=True
)
async def to_code(config): async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID]) var = cg.new_Pvariable(config[CONF_ID])

View File

@ -1,7 +1,7 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins from esphome import pins
import esphome.codegen as cg
from esphome.components import spi, st7567_base from esphome.components import spi, st7567_base
import esphome.config_validation as cv
from esphome.const import CONF_DC_PIN, CONF_ID, CONF_LAMBDA, CONF_PAGES from esphome.const import CONF_DC_PIN, CONF_ID, CONF_LAMBDA, CONF_PAGES
CODEOWNERS = ["@latonita"] CODEOWNERS = ["@latonita"]
@ -24,6 +24,10 @@ CONFIG_SCHEMA = cv.All(
cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA), cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA),
) )
FINAL_VALIDATE_SCHEMA = spi.final_validate_device_schema(
"st7567_spi", require_miso=False, require_mosi=True
)
async def to_code(config): async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID]) var = cg.new_Pvariable(config[CONF_ID])

View File

@ -167,6 +167,10 @@ CONFIG_SCHEMA = cv.All(
cv.only_with_esp_idf, cv.only_with_esp_idf,
) )
FINAL_VALIDATE_SCHEMA = spi.final_validate_device_schema(
"st7701s", require_miso=False, require_mosi=True
)
async def to_code(config): async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID]) var = cg.new_Pvariable(config[CONF_ID])

View File

@ -1,17 +1,17 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins from esphome import pins
from esphome.components import spi import esphome.codegen as cg
from esphome.components import display from esphome.components import display, spi
import esphome.config_validation as cv
from esphome.const import ( from esphome.const import (
CONF_DC_PIN, CONF_DC_PIN,
CONF_ID, CONF_ID,
CONF_INVERT_COLORS,
CONF_LAMBDA, CONF_LAMBDA,
CONF_MODEL, CONF_MODEL,
CONF_RESET_PIN,
CONF_PAGES, CONF_PAGES,
CONF_INVERT_COLORS, CONF_RESET_PIN,
) )
from . import st7735_ns from . import st7735_ns
CODEOWNERS = ["@SenexCrenshaw"] CODEOWNERS = ["@SenexCrenshaw"]
@ -68,6 +68,11 @@ CONFIG_SCHEMA = cv.All(
) )
FINAL_VALIDATE_SCHEMA = spi.final_validate_device_schema(
"st7735", require_miso=False, require_mosi=True
)
async def setup_st7735(var, config): async def setup_st7735(var, config):
await display.register_display(var, config) await display.register_display(var, config)

View File

@ -1,22 +1,23 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins from esphome import pins
from esphome.components import display, spi, power_supply import esphome.codegen as cg
from esphome.components import display, power_supply, spi
import esphome.config_validation as cv
from esphome.const import ( from esphome.const import (
CONF_BACKLIGHT_PIN, CONF_BACKLIGHT_PIN,
CONF_CS_PIN,
CONF_DC_PIN, CONF_DC_PIN,
CONF_HEIGHT, CONF_HEIGHT,
CONF_ID, CONF_ID,
CONF_LAMBDA, CONF_LAMBDA,
CONF_MODEL, CONF_MODEL,
CONF_RESET_PIN,
CONF_WIDTH,
CONF_POWER_SUPPLY,
CONF_ROTATION,
CONF_CS_PIN,
CONF_OFFSET_HEIGHT, CONF_OFFSET_HEIGHT,
CONF_OFFSET_WIDTH, CONF_OFFSET_WIDTH,
CONF_POWER_SUPPLY,
CONF_RESET_PIN,
CONF_ROTATION,
CONF_WIDTH,
) )
from . import st7789v_ns from . import st7789v_ns
CONF_EIGHTBITCOLOR = "eightbitcolor" CONF_EIGHTBITCOLOR = "eightbitcolor"
@ -168,6 +169,10 @@ CONFIG_SCHEMA = cv.All(
validate_st7789v, validate_st7789v,
) )
FINAL_VALIDATE_SCHEMA = spi.final_validate_device_schema(
"st7789v", require_miso=False, require_mosi=True
)
async def to_code(config): async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID]) var = cg.new_Pvariable(config[CONF_ID])

View File

@ -1,21 +1,18 @@
import esphome.config_validation as cv
import esphome.codegen as cg
from esphome.components import display
from esphome import automation from esphome import automation
import esphome.codegen as cg
from esphome.components import display
import esphome.config_validation as cv
from esphome.const import ( from esphome.const import (
CONF_CALIBRATION,
CONF_DISPLAY, CONF_DISPLAY,
CONF_ON_TOUCH,
CONF_ON_RELEASE,
CONF_ON_UPDATE,
CONF_SWAP_XY,
CONF_MIRROR_X, CONF_MIRROR_X,
CONF_MIRROR_Y, CONF_MIRROR_Y,
CONF_ON_RELEASE,
CONF_ON_TOUCH,
CONF_ON_UPDATE,
CONF_SWAP_XY,
CONF_TRANSFORM, CONF_TRANSFORM,
CONF_CALIBRATION,
) )
from esphome.core import coroutine_with_priority from esphome.core import coroutine_with_priority
CODEOWNERS = ["@jesserockz", "@nielsnl68"] CODEOWNERS = ["@jesserockz", "@nielsnl68"]
@ -43,51 +40,45 @@ CONF_Y_MIN = "y_min"
CONF_Y_MAX = "y_max" CONF_Y_MAX = "y_max"
def validate_calibration(config): def validate_calibration(calibration_config):
if CONF_CALIBRATION in config: x_min = calibration_config[CONF_X_MIN]
calibration_config = config[CONF_CALIBRATION] x_max = calibration_config[CONF_X_MAX]
if ( y_min = calibration_config[CONF_Y_MIN]
cv.int_([CONF_X_MIN]) != 0 y_max = calibration_config[CONF_Y_MAX]
and cv.int_(calibration_config[CONF_X_MAX]) != 0 if x_max < x_min:
and abs( raise cv.Invalid(
cv.int_(calibration_config[CONF_X_MIN]) "x_min must be smaller than x_max. To mirror the direction use the 'transform' options"
- cv.int_(calibration_config[CONF_X_MAX]) )
) if y_max < y_min:
< 10 raise cv.Invalid(
): "y_min must be smaller than y_max. To mirror the direction use the 'transform' options"
raise cv.Invalid("Calibration X values difference must be more than 10") )
x_delta = x_max - x_min
if ( y_delta = y_max - y_min
cv.int_(calibration_config[CONF_Y_MIN]) != 0 if x_delta < 10 or y_delta < 10:
and cv.int_(calibration_config[CONF_Y_MAX]) != 0 raise cv.Invalid("Calibration value range must be greater than 10")
and abs( return calibration_config
cv.int_(calibration_config[CONF_Y_MIN])
- cv.int_(calibration_config[CONF_Y_MAX])
)
< 10
):
raise cv.Invalid("Calibration Y values difference must be more than 10")
return config
def calibration_schema(default_max_values): CALIBRATION_SCHEMA = cv.All(
return cv.Schema( cv.Schema(
{ {
cv.Optional(CONF_X_MIN, default=0): cv.int_range(min=0, max=4095), cv.Required(CONF_X_MIN): cv.int_range(min=0, max=4095),
cv.Optional(CONF_X_MAX, default=default_max_values): cv.int_range( cv.Required(CONF_X_MAX): cv.int_range(min=0, max=4095),
min=0, max=4095 cv.Required(CONF_Y_MIN): cv.int_range(min=0, max=4095),
), cv.Required(CONF_Y_MAX): cv.int_range(min=0, max=4095),
cv.Optional(CONF_Y_MIN, default=0): cv.int_range(min=0, max=4095), }
cv.Optional(CONF_Y_MAX, default=default_max_values): cv.int_range( ),
min=0, max=4095 validate_calibration,
), )
},
validate_calibration,
def touchscreen_schema(default_touch_timeout=cv.UNDEFINED, calibration_required=False):
calibration = (
cv.Required(CONF_CALIBRATION)
if calibration_required
else cv.Optional(CONF_CALIBRATION)
) )
def touchscreen_schema(default_touch_timeout):
return cv.Schema( return cv.Schema(
{ {
cv.GenerateID(CONF_DISPLAY): cv.use_id(display.Display), cv.GenerateID(CONF_DISPLAY): cv.use_id(display.Display),
@ -102,7 +93,7 @@ def touchscreen_schema(default_touch_timeout):
cv.positive_time_period_milliseconds, cv.positive_time_period_milliseconds,
cv.Range(max=cv.TimePeriod(milliseconds=65535)), cv.Range(max=cv.TimePeriod(milliseconds=65535)),
), ),
cv.Optional(CONF_CALIBRATION): calibration_schema(0), calibration: CALIBRATION_SCHEMA,
cv.Optional(CONF_ON_TOUCH): automation.validate_automation(single=True), cv.Optional(CONF_ON_TOUCH): automation.validate_automation(single=True),
cv.Optional(CONF_ON_UPDATE): automation.validate_automation(single=True), cv.Optional(CONF_ON_UPDATE): automation.validate_automation(single=True),
cv.Optional(CONF_ON_RELEASE): automation.validate_automation(single=True), cv.Optional(CONF_ON_RELEASE): automation.validate_automation(single=True),

View File

@ -53,14 +53,10 @@ class Touchscreen : public PollingComponent {
void set_swap_xy(bool swap) { this->swap_x_y_ = swap; } void set_swap_xy(bool swap) { this->swap_x_y_ = swap; }
void set_calibration(int16_t x_min, int16_t x_max, int16_t y_min, int16_t y_max) { void set_calibration(int16_t x_min, int16_t x_max, int16_t y_min, int16_t y_max) {
this->x_raw_min_ = std::min(x_min, x_max); this->x_raw_min_ = x_min;
this->x_raw_max_ = std::max(x_min, x_max); this->x_raw_max_ = x_max;
this->y_raw_min_ = std::min(y_min, y_max); this->y_raw_min_ = y_min;
this->y_raw_max_ = std::max(y_min, y_max); this->y_raw_max_ = y_max;
if (x_min > x_max)
this->invert_x_ = true;
if (y_min > y_max)
this->invert_y_ = true;
} }
Trigger<TouchPoint, const TouchPoints_t &> *get_touch_trigger() { return &this->touch_trigger_; } Trigger<TouchPoint, const TouchPoints_t &> *get_touch_trigger() { return &this->touch_trigger_; }

View File

@ -1,7 +1,7 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import core, pins from esphome import core, pins
import esphome.codegen as cg
from esphome.components import display, spi from esphome.components import display, spi
import esphome.config_validation as cv
from esphome.const import ( from esphome.const import (
CONF_BUSY_PIN, CONF_BUSY_PIN,
CONF_DC_PIN, CONF_DC_PIN,
@ -187,6 +187,10 @@ CONFIG_SCHEMA = cv.All(
cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA), cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA),
) )
FINAL_VALIDATE_SCHEMA = spi.final_validate_device_schema(
"waveshare_epaper", require_miso=False, require_mosi=True
)
async def to_code(config): async def to_code(config):
model_type, model = MODELS[config[CONF_MODEL]] model_type, model = MODELS[config[CONF_MODEL]]

View File

@ -297,8 +297,8 @@ void WiFiComponent::set_sta(const WiFiAP &ap) {
void WiFiComponent::clear_sta() { this->sta_.clear(); } void WiFiComponent::clear_sta() { this->sta_.clear(); }
void WiFiComponent::save_wifi_sta(const std::string &ssid, const std::string &password) { void WiFiComponent::save_wifi_sta(const std::string &ssid, const std::string &password) {
SavedWifiSettings save{}; SavedWifiSettings save{};
strncpy(save.ssid, ssid.c_str(), sizeof(save.ssid)); snprintf(save.ssid, sizeof(save.ssid), "%s", ssid.c_str());
strncpy(save.password, password.c_str(), sizeof(save.password)); snprintf(save.password, sizeof(save.password), "%s", password.c_str());
this->pref_.save(&save); this->pref_.save(&save);
// ensure it's written immediately // ensure it's written immediately
global_preferences->sync(); global_preferences->sync();

View File

@ -137,8 +137,8 @@ bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) {
// https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv417wifi_sta_config_t // https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv417wifi_sta_config_t
wifi_config_t conf; wifi_config_t conf;
memset(&conf, 0, sizeof(conf)); memset(&conf, 0, sizeof(conf));
strncpy(reinterpret_cast<char *>(conf.sta.ssid), ap.get_ssid().c_str(), sizeof(conf.sta.ssid)); snprintf(reinterpret_cast<char *>(conf.sta.ssid), sizeof(conf.sta.ssid), "%s", ap.get_ssid().c_str());
strncpy(reinterpret_cast<char *>(conf.sta.password), ap.get_password().c_str(), sizeof(conf.sta.password)); snprintf(reinterpret_cast<char *>(conf.sta.password), sizeof(conf.sta.password), "%s", ap.get_password().c_str());
// The weakest authmode to accept in the fast scan mode // The weakest authmode to accept in the fast scan mode
if (ap.get_password().empty()) { if (ap.get_password().empty()) {
@ -746,7 +746,7 @@ bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
wifi_config_t conf; wifi_config_t conf;
memset(&conf, 0, sizeof(conf)); memset(&conf, 0, sizeof(conf));
strncpy(reinterpret_cast<char *>(conf.ap.ssid), ap.get_ssid().c_str(), sizeof(conf.ap.ssid)); snprintf(reinterpret_cast<char *>(conf.ap.ssid), sizeof(conf.ap.ssid), "%s", ap.get_ssid().c_str());
conf.ap.channel = ap.get_channel().value_or(1); conf.ap.channel = ap.get_channel().value_or(1);
conf.ap.ssid_hidden = ap.get_ssid().size(); conf.ap.ssid_hidden = ap.get_ssid().size();
conf.ap.max_connection = 5; conf.ap.max_connection = 5;
@ -757,7 +757,7 @@ bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
*conf.ap.password = 0; *conf.ap.password = 0;
} else { } else {
conf.ap.authmode = WIFI_AUTH_WPA2_PSK; conf.ap.authmode = WIFI_AUTH_WPA2_PSK;
strncpy(reinterpret_cast<char *>(conf.ap.password), ap.get_password().c_str(), sizeof(conf.ap.password)); snprintf(reinterpret_cast<char *>(conf.ap.password), sizeof(conf.ap.password), "%s", ap.get_password().c_str());
} }
// pairwise cipher of SoftAP, group cipher will be derived using this. // pairwise cipher of SoftAP, group cipher will be derived using this.

View File

@ -236,8 +236,8 @@ bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) {
struct station_config conf {}; struct station_config conf {};
memset(&conf, 0, sizeof(conf)); memset(&conf, 0, sizeof(conf));
strncpy(reinterpret_cast<char *>(conf.ssid), ap.get_ssid().c_str(), sizeof(conf.ssid)); snprintf(reinterpret_cast<char *>(conf.ssid), sizeof(conf.ssid), "%s", ap.get_ssid().c_str());
strncpy(reinterpret_cast<char *>(conf.password), ap.get_password().c_str(), sizeof(conf.password)); snprintf(reinterpret_cast<char *>(conf.password), sizeof(conf.password), "%s", ap.get_password().c_str());
if (ap.get_bssid().has_value()) { if (ap.get_bssid().has_value()) {
conf.bssid_set = 1; conf.bssid_set = 1;
@ -775,7 +775,7 @@ bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
return false; return false;
struct softap_config conf {}; struct softap_config conf {};
strncpy(reinterpret_cast<char *>(conf.ssid), ap.get_ssid().c_str(), sizeof(conf.ssid)); snprintf(reinterpret_cast<char *>(conf.ssid), sizeof(conf.ssid), "%s", ap.get_ssid().c_str());
conf.ssid_len = static_cast<uint8>(ap.get_ssid().size()); conf.ssid_len = static_cast<uint8>(ap.get_ssid().size());
conf.channel = ap.get_channel().value_or(1); conf.channel = ap.get_channel().value_or(1);
conf.ssid_hidden = ap.get_hidden(); conf.ssid_hidden = ap.get_hidden();
@ -787,7 +787,7 @@ bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
*conf.password = 0; *conf.password = 0;
} else { } else {
conf.authmode = AUTH_WPA2_PSK; conf.authmode = AUTH_WPA2_PSK;
strncpy(reinterpret_cast<char *>(conf.password), ap.get_password().c_str(), sizeof(conf.password)); snprintf(reinterpret_cast<char *>(conf.password), sizeof(conf.password), "%s", ap.get_password().c_str());
} }
ETS_UART_INTR_DISABLE(); ETS_UART_INTR_DISABLE();

View File

@ -289,8 +289,8 @@ bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) {
// https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv417wifi_sta_config_t // https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv417wifi_sta_config_t
wifi_config_t conf; wifi_config_t conf;
memset(&conf, 0, sizeof(conf)); memset(&conf, 0, sizeof(conf));
strncpy(reinterpret_cast<char *>(conf.sta.ssid), ap.get_ssid().c_str(), sizeof(conf.sta.ssid)); snprintf(reinterpret_cast<char *>(conf.sta.ssid), sizeof(conf.sta.ssid), "%s", ap.get_ssid().c_str());
strncpy(reinterpret_cast<char *>(conf.sta.password), ap.get_password().c_str(), sizeof(conf.sta.password)); snprintf(reinterpret_cast<char *>(conf.sta.password), sizeof(conf.sta.password), "%s", ap.get_password().c_str());
// The weakest authmode to accept in the fast scan mode // The weakest authmode to accept in the fast scan mode
if (ap.get_password().empty()) { if (ap.get_password().empty()) {

View File

@ -1,9 +1,8 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins from esphome import pins
import esphome.codegen as cg
from esphome.components import spi, touchscreen from esphome.components import spi, touchscreen
from esphome.const import CONF_ID, CONF_THRESHOLD, CONF_INTERRUPT_PIN import esphome.config_validation as cv
from esphome.const import CONF_ID, CONF_INTERRUPT_PIN, CONF_THRESHOLD
CODEOWNERS = ["@numo68", "@nielsnl68"] CODEOWNERS = ["@numo68", "@nielsnl68"]
DEPENDENCIES = ["spi"] DEPENDENCIES = ["spi"]
@ -15,13 +14,9 @@ XPT2046Component = XPT2046_ns.class_(
spi.SPIDevice, spi.SPIDevice,
) )
CONF_CALIBRATION_X_MIN = "calibration_x_min"
CONF_CALIBRATION_X_MAX = "calibration_x_max"
CONF_CALIBRATION_Y_MIN = "calibration_y_min"
CONF_CALIBRATION_Y_MAX = "calibration_y_max"
CONFIG_SCHEMA = cv.All( CONFIG_SCHEMA = cv.All(
touchscreen.TOUCHSCREEN_SCHEMA.extend( touchscreen.touchscreen_schema(calibration_required=True)
.extend(
cv.Schema( cv.Schema(
{ {
cv.GenerateID(): cv.declare_id(XPT2046Component), cv.GenerateID(): cv.declare_id(XPT2046Component),
@ -29,30 +24,10 @@ CONFIG_SCHEMA = cv.All(
pins.internal_gpio_input_pin_schema pins.internal_gpio_input_pin_schema
), ),
cv.Optional(CONF_THRESHOLD, default=400): cv.int_range(min=0, max=4095), cv.Optional(CONF_THRESHOLD, default=400): cv.int_range(min=0, max=4095),
cv.Optional(
touchscreen.CONF_CALIBRATION
): touchscreen.calibration_schema(4095),
cv.Optional(CONF_CALIBRATION_X_MIN): cv.invalid(
"Deprecated: use the new 'calibration' configuration variable"
),
cv.Optional(CONF_CALIBRATION_X_MAX): cv.invalid(
"Deprecated: use the new 'calibration' configuration variable"
),
cv.Optional(CONF_CALIBRATION_Y_MIN): cv.invalid(
"Deprecated: use the new 'calibration' configuration variable"
),
cv.Optional(CONF_CALIBRATION_Y_MAX): cv.invalid(
"Deprecated: use the new 'calibration' configuration variable"
),
cv.Optional(CONF_CALIBRATION_Y_MAX): cv.invalid(
"Deprecated: use the new 'calibration' configuration variable"
),
cv.Optional("report_interval"): cv.invalid(
"Deprecated: use the 'update_interval' configuration variable"
),
}, },
) )
).extend(spi.spi_device_schema()), )
.extend(spi.spi_device_schema()),
) )

View File

@ -92,6 +92,7 @@ CONF_BINARY_SENSORS = "binary_sensors"
CONF_BINDKEY = "bindkey" CONF_BINDKEY = "bindkey"
CONF_BIRTH_MESSAGE = "birth_message" CONF_BIRTH_MESSAGE = "birth_message"
CONF_BIT_DEPTH = "bit_depth" CONF_BIT_DEPTH = "bit_depth"
CONF_BITS_PER_SAMPLE = "bits_per_sample"
CONF_BLOCK = "block" CONF_BLOCK = "block"
CONF_BLUE = "blue" CONF_BLUE = "blue"
CONF_BOARD = "board" CONF_BOARD = "board"
@ -666,6 +667,7 @@ CONF_PMC_1_0 = "pmc_1_0"
CONF_PMC_10_0 = "pmc_10_0" CONF_PMC_10_0 = "pmc_10_0"
CONF_PMC_2_5 = "pmc_2_5" CONF_PMC_2_5 = "pmc_2_5"
CONF_PMC_4_0 = "pmc_4_0" CONF_PMC_4_0 = "pmc_4_0"
CONF_POLLING_INTERVAL = "polling_interval"
CONF_PORT = "port" CONF_PORT = "port"
CONF_POSITION = "position" CONF_POSITION = "position"
CONF_POSITION_ACTION = "position_action" CONF_POSITION_ACTION = "position_action"

View File

@ -1,167 +0,0 @@
#include "bytebuffer.h"
#include <cassert>
#include "esphome/core/helpers.h"
#include <list>
#include <vector>
namespace esphome {
ByteBuffer ByteBuffer::wrap(const uint8_t *ptr, size_t len, Endian endianness) {
// there is a double copy happening here, could be optimized but at cost of clarity.
std::vector<uint8_t> data(ptr, ptr + len);
ByteBuffer buffer = {data};
buffer.endianness_ = endianness;
return buffer;
}
ByteBuffer ByteBuffer::wrap(std::vector<uint8_t> const &data, Endian endianness) {
ByteBuffer buffer = {data};
buffer.endianness_ = endianness;
return buffer;
}
ByteBuffer ByteBuffer::wrap(uint8_t value) {
ByteBuffer buffer = ByteBuffer(1);
buffer.put_uint8(value);
buffer.flip();
return buffer;
}
ByteBuffer ByteBuffer::wrap(uint16_t value, Endian endianness) {
ByteBuffer buffer = ByteBuffer(2, endianness);
buffer.put_uint16(value);
buffer.flip();
return buffer;
}
ByteBuffer ByteBuffer::wrap(uint32_t value, Endian endianness) {
ByteBuffer buffer = ByteBuffer(4, endianness);
buffer.put_uint32(value);
buffer.flip();
return buffer;
}
ByteBuffer ByteBuffer::wrap(uint64_t value, Endian endianness) {
ByteBuffer buffer = ByteBuffer(8, endianness);
buffer.put_uint64(value);
buffer.flip();
return buffer;
}
ByteBuffer ByteBuffer::wrap(float value, Endian endianness) {
ByteBuffer buffer = ByteBuffer(sizeof(float), endianness);
buffer.put_float(value);
buffer.flip();
return buffer;
}
ByteBuffer ByteBuffer::wrap(double value, Endian endianness) {
ByteBuffer buffer = ByteBuffer(sizeof(double), endianness);
buffer.put_double(value);
buffer.flip();
return buffer;
}
void ByteBuffer::set_limit(size_t limit) {
assert(limit <= this->get_capacity());
this->limit_ = limit;
}
void ByteBuffer::set_position(size_t position) {
assert(position <= this->get_limit());
this->position_ = position;
}
void ByteBuffer::clear() {
this->limit_ = this->get_capacity();
this->position_ = 0;
}
void ByteBuffer::flip() {
this->limit_ = this->position_;
this->position_ = 0;
}
/// Getters
uint8_t ByteBuffer::get_uint8() {
assert(this->get_remaining() >= 1);
return this->data_[this->position_++];
}
uint64_t ByteBuffer::get_uint(size_t length) {
assert(this->get_remaining() >= length);
uint64_t value = 0;
if (this->endianness_ == LITTLE) {
this->position_ += length;
auto index = this->position_;
while (length-- != 0) {
value <<= 8;
value |= this->data_[--index];
}
} else {
while (length-- != 0) {
value <<= 8;
value |= this->data_[this->position_++];
}
}
return value;
}
uint32_t ByteBuffer::get_int24() {
auto value = this->get_uint24();
uint32_t mask = (~static_cast<uint32_t>(0)) << 23;
if ((value & mask) != 0)
value |= mask;
return value;
}
float ByteBuffer::get_float() {
assert(this->get_remaining() >= sizeof(float));
return bit_cast<float>(this->get_uint32());
}
double ByteBuffer::get_double() {
assert(this->get_remaining() >= sizeof(double));
return bit_cast<double>(this->get_uint64());
}
std::vector<uint8_t> ByteBuffer::get_vector(size_t length) {
assert(this->get_remaining() >= length);
auto start = this->data_.begin() + this->position_;
this->position_ += length;
return {start, start + length};
}
/// Putters
void ByteBuffer::put_uint8(uint8_t value) {
assert(this->get_remaining() >= 1);
this->data_[this->position_++] = value;
}
void ByteBuffer::put_uint(uint64_t value, size_t length) {
assert(this->get_remaining() >= length);
if (this->endianness_ == LITTLE) {
while (length-- != 0) {
this->data_[this->position_++] = static_cast<uint8_t>(value);
value >>= 8;
}
} else {
this->position_ += length;
auto index = this->position_;
while (length-- != 0) {
this->data_[--index] = static_cast<uint8_t>(value);
value >>= 8;
}
}
}
void ByteBuffer::put_float(float value) {
static_assert(sizeof(float) == sizeof(uint32_t), "Float sizes other than 32 bit not supported");
assert(this->get_remaining() >= sizeof(float));
this->put_uint32(bit_cast<uint32_t>(value));
}
void ByteBuffer::put_double(double value) {
static_assert(sizeof(double) == sizeof(uint64_t), "Double sizes other than 64 bit not supported");
assert(this->get_remaining() >= sizeof(double));
this->put_uint64(bit_cast<uint64_t>(value));
}
void ByteBuffer::put_vector(const std::vector<uint8_t> &value) {
assert(this->get_remaining() >= value.size());
std::copy(value.begin(), value.end(), this->data_.begin() + this->position_);
this->position_ += value.size();
}
} // namespace esphome

View File

@ -1,144 +0,0 @@
#pragma once
#include <utility>
#include <vector>
#include <cinttypes>
#include <cstddef>
namespace esphome {
enum Endian { LITTLE, BIG };
/**
* A class modelled on the Java ByteBuffer class. It wraps a vector of bytes and permits putting and getting
* items of various sizes, with an automatically incremented position.
*
* There are three variables maintained pointing into the buffer:
*
* capacity: the maximum amount of data that can be stored - set on construction and cannot be changed
* limit: the limit of the data currently available to get or put
* position: the current insert or extract position
*
* 0 <= position <= limit <= capacity
*
* In addition a mark can be set to the current position with mark(). A subsequent call to reset() will restore
* the position to the mark.
*
* The buffer can be marked to be little-endian (default) or big-endian. All subsequent operations will use that order.
*
* The flip() operation will reset the position to 0 and limit to the current position. This is useful for reading
* data from a buffer after it has been written.
*
*/
class ByteBuffer {
public:
// Default constructor (compatibility with TEMPLATABLE_VALUE)
ByteBuffer() : ByteBuffer(std::vector<uint8_t>()) {}
/**
* Create a new Bytebuffer with the given capacity
*/
ByteBuffer(size_t capacity, Endian endianness = LITTLE)
: data_(std::vector<uint8_t>(capacity)), endianness_(endianness), limit_(capacity){};
/**
* Wrap an existing vector in a ByteBufffer
*/
static ByteBuffer wrap(std::vector<uint8_t> const &data, Endian endianness = LITTLE);
/**
* Wrap an existing array in a ByteBuffer. Note that this will create a copy of the data.
*/
static ByteBuffer wrap(const uint8_t *ptr, size_t len, Endian endianness = LITTLE);
// Convenience functions to create a ByteBuffer from a value
static ByteBuffer wrap(uint8_t value);
static ByteBuffer wrap(uint16_t value, Endian endianness = LITTLE);
static ByteBuffer wrap(uint32_t value, Endian endianness = LITTLE);
static ByteBuffer wrap(uint64_t value, Endian endianness = LITTLE);
static ByteBuffer wrap(int8_t value) { return wrap(static_cast<uint8_t>(value)); }
static ByteBuffer wrap(int16_t value, Endian endianness = LITTLE) {
return wrap(static_cast<uint16_t>(value), endianness);
}
static ByteBuffer wrap(int32_t value, Endian endianness = LITTLE) {
return wrap(static_cast<uint32_t>(value), endianness);
}
static ByteBuffer wrap(int64_t value, Endian endianness = LITTLE) {
return wrap(static_cast<uint64_t>(value), endianness);
}
static ByteBuffer wrap(float value, Endian endianness = LITTLE);
static ByteBuffer wrap(double value, Endian endianness = LITTLE);
static ByteBuffer wrap(bool value) { return wrap(static_cast<uint8_t>(value)); }
// Get an integral value from the buffer, increment position by length
uint64_t get_uint(size_t length);
// Get one byte from the buffer, increment position by 1
uint8_t get_uint8();
// Get a 16 bit unsigned value, increment by 2
uint16_t get_uint16() { return static_cast<uint16_t>(this->get_uint(sizeof(uint16_t))); };
// Get a 24 bit unsigned value, increment by 3
uint32_t get_uint24() { return static_cast<uint32_t>(this->get_uint(3)); };
// Get a 32 bit unsigned value, increment by 4
uint32_t get_uint32() { return static_cast<uint32_t>(this->get_uint(sizeof(uint32_t))); };
// Get a 64 bit unsigned value, increment by 8
uint64_t get_uint64() { return this->get_uint(sizeof(uint64_t)); };
// Signed versions of the get functions
uint8_t get_int8() { return static_cast<int8_t>(this->get_uint8()); };
int16_t get_int16() { return static_cast<int16_t>(this->get_uint(sizeof(int16_t))); }
uint32_t get_int24();
int32_t get_int32() { return static_cast<int32_t>(this->get_uint(sizeof(int32_t))); }
int64_t get_int64() { return static_cast<int64_t>(this->get_uint(sizeof(int64_t))); }
// Get a float value, increment by 4
float get_float();
// Get a double value, increment by 8
double get_double();
// Get a bool value, increment by 1
bool get_bool() { return this->get_uint8(); }
// Get vector of bytes, increment by length
std::vector<uint8_t> get_vector(size_t length);
// Put values into the buffer, increment the position accordingly
// put any integral value, length represents the number of bytes
void put_uint(uint64_t value, size_t length);
void put_uint8(uint8_t value);
void put_uint16(uint16_t value) { this->put_uint(value, sizeof(uint16_t)); }
void put_uint24(uint32_t value) { this->put_uint(value, 3); }
void put_uint32(uint32_t value) { this->put_uint(value, sizeof(uint32_t)); }
void put_uint64(uint64_t value) { this->put_uint(value, sizeof(uint64_t)); }
// Signed versions of the put functions
void put_int8(int8_t value) { this->put_uint8(static_cast<uint8_t>(value)); }
void put_int16(int32_t value) { this->put_uint(static_cast<uint16_t>(value), sizeof(uint16_t)); }
void put_int24(int32_t value) { this->put_uint(static_cast<uint32_t>(value), 3); }
void put_int32(int32_t value) { this->put_uint(static_cast<uint32_t>(value), sizeof(uint32_t)); }
void put_int64(int64_t value) { this->put_uint(static_cast<uint64_t>(value), sizeof(uint64_t)); }
// Extra put functions
void put_float(float value);
void put_double(double value);
void put_bool(bool value) { this->put_uint8(value); }
void put_vector(const std::vector<uint8_t> &value);
inline size_t get_capacity() const { return this->data_.size(); }
inline size_t get_position() const { return this->position_; }
inline size_t get_limit() const { return this->limit_; }
inline size_t get_remaining() const { return this->get_limit() - this->get_position(); }
inline Endian get_endianness() const { return this->endianness_; }
inline void mark() { this->mark_ = this->position_; }
inline void big_endian() { this->endianness_ = BIG; }
inline void little_endian() { this->endianness_ = LITTLE; }
void set_limit(size_t limit);
void set_position(size_t position);
// set position to 0, limit to capacity.
void clear();
// set limit to current position, postition to zero. Used when swapping from write to read operations.
void flip();
// retrieve a pointer to the underlying data.
std::vector<uint8_t> get_data() { return this->data_; };
void rewind() { this->position_ = 0; }
void reset() { this->position_ = this->mark_; }
protected:
ByteBuffer(std::vector<uint8_t> const &data) : data_(data), limit_(data.size()) {}
std::vector<uint8_t> data_;
Endian endianness_{LITTLE};
size_t position_{0};
size_t mark_{0};
size_t limit_{0};
};
} // namespace esphome

View File

@ -86,8 +86,6 @@
#ifdef USE_ARDUINO #ifdef USE_ARDUINO
#define USE_CAPTIVE_PORTAL #define USE_CAPTIVE_PORTAL
#define USE_PROMETHEUS #define USE_PROMETHEUS
#define USE_WEBSERVER
#define USE_WEBSERVER_PORT 80 // NOLINT
#define USE_WIFI_WPA2_EAP #define USE_WIFI_WPA2_EAP
#endif #endif
@ -111,6 +109,8 @@
#define USE_SPEAKER #define USE_SPEAKER
#define USE_SPI #define USE_SPI
#define USE_VOICE_ASSISTANT #define USE_VOICE_ASSISTANT
#define USE_WEBSERVER
#define USE_WEBSERVER_PORT 80 // NOLINT
#define USE_WIFI_11KV_SUPPORT #define USE_WIFI_11KV_SUPPORT
#ifdef USE_ARDUINO #ifdef USE_ARDUINO
@ -147,6 +147,8 @@
#define USE_SHD_FIRMWARE_DATA \ #define USE_SHD_FIRMWARE_DATA \
{} {}
#define USE_WEBSERVER
#define USE_WEBSERVER_PORT 80 // NOLINT
#endif #endif
#ifdef USE_RP2040 #ifdef USE_RP2040
@ -158,6 +160,8 @@
#ifdef USE_LIBRETINY #ifdef USE_LIBRETINY
#define USE_SOCKET_IMPL_LWIP_SOCKETS #define USE_SOCKET_IMPL_LWIP_SOCKETS
#define USE_WEBSERVER
#define USE_WEBSERVER_PORT 80 // NOLINT
#endif #endif
#ifdef USE_HOST #ifdef USE_HOST

View File

@ -10,6 +10,7 @@
#include <cstdarg> #include <cstdarg>
#include <cstdio> #include <cstdio>
#include <cstring> #include <cstring>
#include <strings.h>
#ifdef USE_HOST #ifdef USE_HOST
#ifndef _WIN32 #ifndef _WIN32
@ -188,37 +189,39 @@ uint32_t fnv1_hash(const std::string &str) {
return hash; return hash;
} }
uint32_t random_uint32() {
#ifdef USE_ESP32 #ifdef USE_ESP32
return esp_random(); uint32_t random_uint32() { return esp_random(); }
#elif defined(USE_ESP8266) #elif defined(USE_ESP8266)
return os_random(); uint32_t random_uint32() { return os_random(); }
#elif defined(USE_RP2040) #elif defined(USE_RP2040)
uint32_t random_uint32() {
uint32_t result = 0; uint32_t result = 0;
for (uint8_t i = 0; i < 32; i++) { for (uint8_t i = 0; i < 32; i++) {
result <<= 1; result <<= 1;
result |= rosc_hw->randombit; result |= rosc_hw->randombit;
} }
return result; return result;
}
#elif defined(USE_LIBRETINY) #elif defined(USE_LIBRETINY)
return rand(); uint32_t random_uint32() { return rand(); }
#elif defined(USE_HOST) #elif defined(USE_HOST)
uint32_t random_uint32() {
std::random_device dev; std::random_device dev;
std::mt19937 rng(dev()); std::mt19937 rng(dev());
std::uniform_int_distribution<uint32_t> dist(0, std::numeric_limits<uint32_t>::max()); std::uniform_int_distribution<uint32_t> dist(0, std::numeric_limits<uint32_t>::max());
return dist(rng); return dist(rng);
#else
#error "No random source available for this configuration."
#endif
} }
#endif
float random_float() { return static_cast<float>(random_uint32()) / static_cast<float>(UINT32_MAX); } float random_float() { return static_cast<float>(random_uint32()) / static_cast<float>(UINT32_MAX); }
bool random_bytes(uint8_t *data, size_t len) {
#ifdef USE_ESP32 #ifdef USE_ESP32
bool random_bytes(uint8_t *data, size_t len) {
esp_fill_random(data, len); esp_fill_random(data, len);
return true; return true;
}
#elif defined(USE_ESP8266) #elif defined(USE_ESP8266)
return os_get_random(data, len) == 0; bool random_bytes(uint8_t *data, size_t len) { return os_get_random(data, len) == 0; }
#elif defined(USE_RP2040) #elif defined(USE_RP2040)
bool random_bytes(uint8_t *data, size_t len) {
while (len-- != 0) { while (len-- != 0) {
uint8_t result = 0; uint8_t result = 0;
for (uint8_t i = 0; i < 8; i++) { for (uint8_t i = 0; i < 8; i++) {
@ -228,10 +231,14 @@ bool random_bytes(uint8_t *data, size_t len) {
*data++ = result; *data++ = result;
} }
return true; return true;
}
#elif defined(USE_LIBRETINY) #elif defined(USE_LIBRETINY)
bool random_bytes(uint8_t *data, size_t len) {
lt_rand_bytes(data, len); lt_rand_bytes(data, len);
return true; return true;
}
#elif defined(USE_HOST) #elif defined(USE_HOST)
bool random_bytes(uint8_t *data, size_t len) {
FILE *fp = fopen("/dev/urandom", "r"); FILE *fp = fopen("/dev/urandom", "r");
if (fp == nullptr) { if (fp == nullptr) {
ESP_LOGW(TAG, "Could not open /dev/urandom, errno=%d", errno); ESP_LOGW(TAG, "Could not open /dev/urandom, errno=%d", errno);
@ -244,10 +251,8 @@ bool random_bytes(uint8_t *data, size_t len) {
} }
fclose(fp); fclose(fp);
return true; return true;
#else
#error "No random source available for this configuration."
#endif
} }
#endif
// Strings // Strings
@ -619,11 +624,13 @@ void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green
#if defined(USE_ESP8266) || defined(USE_RP2040) || defined(USE_HOST) #if defined(USE_ESP8266) || defined(USE_RP2040) || defined(USE_HOST)
// ESP8266 doesn't have mutexes, but that shouldn't be an issue as it's single-core and non-preemptive OS. // ESP8266 doesn't have mutexes, but that shouldn't be an issue as it's single-core and non-preemptive OS.
Mutex::Mutex() {} Mutex::Mutex() {}
Mutex::~Mutex() {}
void Mutex::lock() {} void Mutex::lock() {}
bool Mutex::try_lock() { return true; } bool Mutex::try_lock() { return true; }
void Mutex::unlock() {} void Mutex::unlock() {}
#elif defined(USE_ESP32) || defined(USE_LIBRETINY) #elif defined(USE_ESP32) || defined(USE_LIBRETINY)
Mutex::Mutex() { handle_ = xSemaphoreCreateMutex(); } Mutex::Mutex() { handle_ = xSemaphoreCreateMutex(); }
Mutex::~Mutex() {}
void Mutex::lock() { xSemaphoreTake(this->handle_, portMAX_DELAY); } void Mutex::lock() { xSemaphoreTake(this->handle_, portMAX_DELAY); }
bool Mutex::try_lock() { return xSemaphoreTake(this->handle_, 0) == pdTRUE; } bool Mutex::try_lock() { return xSemaphoreTake(this->handle_, 0) == pdTRUE; }
void Mutex::unlock() { xSemaphoreGive(this->handle_); } void Mutex::unlock() { xSemaphoreGive(this->handle_); }
@ -657,11 +664,13 @@ void HighFrequencyLoopRequester::stop() {
} }
bool HighFrequencyLoopRequester::is_high_frequency() { return num_requests > 0; } bool HighFrequencyLoopRequester::is_high_frequency() { return num_requests > 0; }
void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter)
#if defined(USE_HOST) #if defined(USE_HOST)
void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter)
static const uint8_t esphome_host_mac_address[6] = USE_ESPHOME_HOST_MAC_ADDRESS; static const uint8_t esphome_host_mac_address[6] = USE_ESPHOME_HOST_MAC_ADDRESS;
memcpy(mac, esphome_host_mac_address, sizeof(esphome_host_mac_address)); memcpy(mac, esphome_host_mac_address, sizeof(esphome_host_mac_address));
}
#elif defined(USE_ESP32) #elif defined(USE_ESP32)
void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter)
#if defined(CONFIG_SOC_IEEE802154_SUPPORTED) #if defined(CONFIG_SOC_IEEE802154_SUPPORTED)
// When CONFIG_SOC_IEEE802154_SUPPORTED is defined, esp_efuse_mac_get_default // When CONFIG_SOC_IEEE802154_SUPPORTED is defined, esp_efuse_mac_get_default
// returns the 802.15.4 EUI-64 address, so we read directly from eFuse instead. // returns the 802.15.4 EUI-64 address, so we read directly from eFuse instead.
@ -677,16 +686,22 @@ void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parame
esp_efuse_mac_get_default(mac); esp_efuse_mac_get_default(mac);
} }
#endif #endif
}
#elif defined(USE_ESP8266) #elif defined(USE_ESP8266)
void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter)
wifi_get_macaddr(STATION_IF, mac); wifi_get_macaddr(STATION_IF, mac);
#elif defined(USE_RP2040) && defined(USE_WIFI) }
#elif defined(USE_RP2040)
void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter)
#ifdef USE_WIFI
WiFi.macAddress(mac); WiFi.macAddress(mac);
#elif defined(USE_LIBRETINY)
WiFi.macAddress(mac);
#else
// this should be an error, but that messes with CI checks. #error No mac address method defined
#endif #endif
} }
#elif defined(USE_LIBRETINY)
void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter)
WiFi.macAddress(mac);
}
#endif
std::string get_mac_address() { std::string get_mac_address() {
uint8_t mac[6]; uint8_t mac[6];

View File

@ -7,6 +7,7 @@
#include <string> #include <string>
#include <type_traits> #include <type_traits>
#include <vector> #include <vector>
#include <limits>
#include "esphome/core/optional.h" #include "esphome/core/optional.h"
@ -545,6 +546,7 @@ class Mutex {
public: public:
Mutex(); Mutex();
Mutex(const Mutex &) = delete; Mutex(const Mutex &) = delete;
~Mutex();
void lock(); void lock();
bool try_lock(); bool try_lock();
void unlock(); void unlock();
@ -554,6 +556,8 @@ class Mutex {
private: private:
#if defined(USE_ESP32) || defined(USE_LIBRETINY) #if defined(USE_ESP32) || defined(USE_LIBRETINY)
SemaphoreHandle_t handle_; SemaphoreHandle_t handle_;
#else
void *handle_; // d-pointer to store private data on new platforms
#endif #endif
}; };

View File

@ -17,6 +17,9 @@ aioesphomeapi==24.6.2
zeroconf==0.132.2 zeroconf==0.132.2
puremagic==1.27 puremagic==1.27
ruamel.yaml==0.18.6 # dashboard_import ruamel.yaml==0.18.6 # dashboard_import
glyphsets==1.0.0
pillow==10.4.0
freetype-py==2.5.1
# esp-idf requires this, but doesn't bundle it by default # esp-idf requires this, but doesn't bundle it by default
# https://github.com/espressif/esp-idf/blob/220590d599e134d7a5e7f1e683cc4550349ffbf8/requirements.txt#L24 # https://github.com/espressif/esp-idf/blob/220590d599e134d7a5e7f1e683cc4550349ffbf8/requirements.txt#L24

View File

@ -1,2 +1 @@
pillow==10.4.0
cairosvg==2.7.1 cairosvg==2.7.1

View File

@ -58,7 +58,7 @@ file_types = (
) )
cpp_include = ("*.h", "*.c", "*.cpp", "*.tcc") cpp_include = ("*.h", "*.c", "*.cpp", "*.tcc")
py_include = ("*.py",) py_include = ("*.py",)
ignore_types = (".ico", ".png", ".woff", ".woff2", "", ".ttf", ".otf") ignore_types = (".ico", ".png", ".woff", ".woff2", "", ".ttf", ".otf", ".pcf")
LINT_FILE_CHECKS = [] LINT_FILE_CHECKS = []
LINT_CONTENT_CHECKS = [] LINT_CONTENT_CHECKS = []

View File

@ -0,0 +1,161 @@
bytebuffer:
esphome:
on_boot:
- lambda: |-
using namespace bytebuffer;
auto buf = ByteBuffer(16);
assert(buf.get_endianness() == LITTLE);
assert(buf.get_remaining() == 16);
buf.set_limit(10);
assert(buf.get_capacity() == 16);
buf.put_uint8(1);
assert(buf.get_remaining() == 9);
buf.put_uint16(0xABCD);
auto da = buf.get_data();
assert(buf.get_uint8(0) == 1);
auto x = buf.get_uint16(1);
assert(buf.get_uint16(1) == 0xABCD);
assert(buf.get_remaining() == 7);
buf.put_uint32(0x12345678UL);
assert(buf.get_uint32(3) == 0x12345678UL);
assert(buf.get_remaining() == 3);
assert(buf.get_data()[1] == 0xCD);
assert(buf.get_data()[2] == 0xAB);
assert(buf.get_data()[3] == 0x78);
assert(buf.get_data()[4] == 0x56);
assert(buf.get_data()[5] == 0x34);
assert(buf.get_data()[6] == 0x12);
buf.flip();
assert(buf.get_capacity() == 16);
assert(buf.get_uint32(3) == 0x12345678UL);
assert(buf.get_uint8(0) == 1);
assert(buf.get_uint16(1) == 0xABCD);
buf.put_uint16(0x1234, 1);
assert(buf.get_uint16(1) == 0x1234);
assert(buf.get_remaining() == 7);
assert(buf.get_uint8() == 1);
assert(buf.get_uint16() == 0x1234);
assert(buf.get_uint32() == 0x12345678ul);
assert(buf.get_remaining() == 0);
assert(buf.get_remaining() == 0);
buf.rewind();
buf.big_endian();
assert(buf.get_remaining() == 7);
assert(buf.get_uint8() == 1);
assert(buf.get_uint16() == 0x3412);
buf.mark();
assert(buf.get_uint32() == 0x78563412ul);
assert(buf.get_remaining() == 0);
buf.reset();
assert(buf.get_remaining() == 4);
assert(buf.get_uint32() == 0x78563412ul);
auto buf1 = ByteBuffer::wrap(buf.get_data().data(), buf.get_limit());
buf.clear();
assert(buf.get_position() == 0);
assert(buf.get_capacity() == 16);
assert(buf.get_limit() == 16);
assert(buf1.get_remaining() == 7);
assert(buf1.get_capacity() == 7);
buf1.set_position(3);
assert(buf1.get_uint32() == 0x12345678ul);
buf1.clear();
assert(buf1.get_limit() == 7);
assert(buf1.get_capacity() == 7);
assert(buf1.get_position() == 0);
float f = 1.2345;
buf1.put_float(f);
buf1.flip();
assert(buf1.get_remaining() == 4);
assert(buf1.get_float() == f);
buf1.clear();
buf1.put_uint16(-32760);
buf1.put_uint24(-302760);
buf1.flip();
assert(buf1.get_int16() == -32760);
assert(buf1.get_int24() == -302760);
uint8_t arr[4] = {0x10, 0x20, 0x30, 0x40};
buf1 = ByteBuffer::wrap(arr, 4);
assert(buf1.get_capacity() == 4);
assert(buf1.get_limit() == 4);
assert(buf1.get_position() == 0);
assert(buf1.get_uint32() == 0x40302010UL);
assert(buf1.get_position() == 4);
assert(buf1.get_remaining() == 0);
std::vector<uint8_t> vec{};
vec.push_back(0x10);
vec.push_back(0x20);
vec.push_back(0x30);
vec.push_back(0x40);
buf1 = ByteBuffer::wrap(vec);
assert(buf1.get_capacity() == 4);
assert(buf1.get_limit() == 4);
assert(buf1.get_position() == 0);
buf1.mark();
buf1.reset();
assert(buf1.get_uint32() == 0x40302010UL);
buf = ByteBuffer::wrap(true);
assert(buf.get_bool() == true);
buf = ByteBuffer::wrap((uint8_t)0xFE);
assert(buf.get_uint8() == 0xFE);
buf = ByteBuffer::wrap((uint16_t)0xA5A6, BIG);
assert(buf.get_remaining() == 2);
assert(buf.get_position() == 0);
assert(buf.get_capacity() == 2);
assert(buf.get_endianness() == BIG);
assert(buf.get_data()[0] == 0xA5);
assert(buf.get_uint16() == 0xA5A6);
buf.flip();
buf.little_endian();
assert(buf.get_uint16() == 0xA6A5);
buf = ByteBuffer::wrap(f, BIG);
assert(buf.get_float() == f);
double d = 1.2345678E7;
buf = ByteBuffer::wrap(d, BIG);
assert(buf.get_double() == d);
buf = ByteBuffer::wrap({1, 2, 3, 4}, BIG);
assert(buf.get_endianness() == BIG);
assert(buf.get_remaining() == 4);
assert(buf.get_data()[2] == 3);
buf.little_endian();
assert(buf.get_data()[2] == 3);
assert(buf.get_uint16() == 0x0201);
buf.big_endian();
assert(buf.get_uint16() == 0x0304);
buf.rewind();
vec = buf.get_vector(3);
assert(buf.get_remaining() == 1);
assert(vec[0] == 1);
assert(vec.size() == 3);
buf = ByteBuffer(10);
buf.put_vector(vec);
assert(buf.get_remaining() == 7);
buf.flip();
assert(buf.get_remaining() == 3);
assert(buf.get_uint24() == 0x030201);
buf = ByteBuffer(64);
buf.put_uint8(1, 1);
buf.put_uint16(16, 2);
buf.put_uint32(1232, 4);
buf.put_uint64(123432ul, 8);
buf.put_float(1.2f, 16);
buf.put_int24(0x678, 20);
assert(buf.get_uint8(1) == 1);
assert(buf.get<uint8_t>(1) == 1);
assert(buf.get_uint16(2) == 16);
assert(buf.get<uint16_t>(2) == 16);
assert(buf.get_uint32(4) == 1232);
assert(buf.get<uint32_t>(4) == 1232);
assert(buf.get_uint64(8) == 123432ul);
assert(buf.get<uint64_t>(8) == 123432ul);
assert(buf.get_float(16) == 1.2f);
assert(buf.get<float>(16) == 1.2f);
assert(buf.get_int24(20) == 0x678);
buf.clear();
buf.put(1.234, 10);
double dx = buf.get<double>(10);
assert(dx == 1.234);
buf.put((uint16_t)1, 10);
assert(buf.get_uint16(10) == 1);
ESP_LOGD("bytebuffer", "******************** All tests succeeded");

View File

@ -0,0 +1 @@
!include common.yaml

View File

@ -0,0 +1 @@
!include common.yaml

View File

@ -0,0 +1 @@
!include common.yaml

View File

@ -0,0 +1 @@
!include common.yaml

View File

@ -0,0 +1 @@
!include common.yaml

View File

@ -0,0 +1 @@
!include common.yaml

View File

@ -0,0 +1 @@
!include common.yaml

View File

@ -0,0 +1,15 @@
esphome:
on_boot:
then:
- audio_dac.mute_off:
- audio_dac.mute_on:
- audio_dac.set_volume:
volume: 50%
i2c:
- id: i2c_aic3204
scl: ${scl_pin}
sda: ${sda_pin}
audio_dac:
- platform: es8311

View File

@ -0,0 +1,5 @@
substitutions:
scl_pin: GPIO16
sda_pin: GPIO17
<<: !include common.yaml

View File

@ -0,0 +1,5 @@
substitutions:
scl_pin: GPIO5
sda_pin: GPIO4
<<: !include common.yaml

View File

@ -0,0 +1,5 @@
substitutions:
scl_pin: GPIO5
sda_pin: GPIO4
<<: !include common.yaml

View File

@ -0,0 +1,5 @@
substitutions:
scl_pin: GPIO16
sda_pin: GPIO17
<<: !include common.yaml

View File

@ -0,0 +1,5 @@
substitutions:
scl_pin: GPIO5
sda_pin: GPIO4
<<: !include common.yaml

2
tests/components/font/.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
*.pcf -text

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