Merge branch 'dev' into custom_ble_server_111

This commit is contained in:
Rodrigo Martín 2024-08-23 11:56:41 +02:00 committed by GitHub
commit 240de01205
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
80 changed files with 830 additions and 375 deletions

View file

@ -397,7 +397,7 @@ jobs:
file: ${{ fromJson(needs.list-components.outputs.components) }} file: ${{ fromJson(needs.list-components.outputs.components) }}
steps: steps:
- name: Install dependencies - name: Install dependencies
run: sudo apt-get install libsodium-dev libsdl2-dev run: sudo apt-get install libsdl2-dev
- name: Check out code from GitHub - name: Check out code from GitHub
uses: actions/checkout@v4.1.7 uses: actions/checkout@v4.1.7
@ -451,7 +451,7 @@ jobs:
run: echo ${{ matrix.components }} run: echo ${{ matrix.components }}
- name: Install dependencies - name: Install dependencies
run: sudo apt-get install libsodium-dev libsdl2-dev run: sudo apt-get install libsdl2-dev
- name: Check out code from GitHub - name: Check out code from GitHub
uses: actions/checkout@v4.1.7 uses: actions/checkout@v4.1.7

View file

@ -169,6 +169,7 @@ esphome/components/he60r/* @clydebarrow
esphome/components/heatpumpir/* @rob-deutsch esphome/components/heatpumpir/* @rob-deutsch
esphome/components/hitachi_ac424/* @sourabhjaiswal esphome/components/hitachi_ac424/* @sourabhjaiswal
esphome/components/hm3301/* @freekode esphome/components/hm3301/* @freekode
esphome/components/hmac_md5/* @dwmw2
esphome/components/homeassistant/* @OttoWinter @esphome/core esphome/components/homeassistant/* @OttoWinter @esphome/core
esphome/components/homeassistant/number/* @landonr esphome/components/homeassistant/number/* @landonr
esphome/components/homeassistant/switch/* @Links2004 esphome/components/homeassistant/switch/* @Links2004

View file

@ -38,7 +38,7 @@ from esphome.const import (
SECRETS_FILES, SECRETS_FILES,
) )
from esphome.core import CORE, EsphomeError, coroutine from esphome.core import CORE, EsphomeError, coroutine
from esphome.helpers import indent, is_ip_address from esphome.helpers import indent, is_ip_address, get_bool_env
from esphome.log import Fore, color, setup_log from esphome.log import Fore, color, setup_log
from esphome.util import ( from esphome.util import (
get_serial_ports, get_serial_ports,
@ -731,7 +731,11 @@ POST_CONFIG_ACTIONS = {
def parse_args(argv): def parse_args(argv):
options_parser = argparse.ArgumentParser(add_help=False) options_parser = argparse.ArgumentParser(add_help=False)
options_parser.add_argument( options_parser.add_argument(
"-v", "--verbose", help="Enable verbose ESPHome logs.", action="store_true" "-v",
"--verbose",
help="Enable verbose ESPHome logs.",
action="store_true",
default=get_bool_env("ESPHOME_VERBOSE"),
) )
options_parser.add_argument( options_parser.add_argument(
"-q", "--quiet", help="Disable all ESPHome logs.", action="store_true" "-q", "--quiet", help="Disable all ESPHome logs.", action="store_true"

View file

@ -155,7 +155,7 @@ async def to_code(config):
decoded = base64.b64decode(encryption_config[CONF_KEY]) decoded = base64.b64decode(encryption_config[CONF_KEY])
cg.add(var.set_noise_psk(list(decoded))) cg.add(var.set_noise_psk(list(decoded)))
cg.add_define("USE_API_NOISE") cg.add_define("USE_API_NOISE")
cg.add_library("esphome/noise-c", "0.1.4") cg.add_library("esphome/noise-c", "0.1.6")
else: else:
cg.add_define("USE_API_PLAINTEXT") cg.add_define("USE_API_PLAINTEXT")

View file

@ -1,4 +1,5 @@
#include "captive_portal.h" #include "captive_portal.h"
#ifdef USE_CAPTIVE_PORTAL
#include "esphome/core/log.h" #include "esphome/core/log.h"
#include "esphome/core/application.h" #include "esphome/core/application.h"
#include "esphome/components/wifi/wifi_component.h" #include "esphome/components/wifi/wifi_component.h"
@ -91,3 +92,4 @@ CaptivePortal *global_captive_portal = nullptr; // NOLINT(cppcoreguidelines-avo
} // namespace captive_portal } // namespace captive_portal
} // namespace esphome } // namespace esphome
#endif

View file

@ -1,5 +1,6 @@
#pragma once #pragma once
#include "esphome/core/defines.h"
#ifdef USE_CAPTIVE_PORTAL
#include <memory> #include <memory>
#ifdef USE_ARDUINO #ifdef USE_ARDUINO
#include <DNSServer.h> #include <DNSServer.h>
@ -71,3 +72,4 @@ extern CaptivePortal *global_captive_portal; // NOLINT(cppcoreguidelines-avoid-
} // namespace captive_portal } // namespace captive_portal
} // namespace esphome } // namespace esphome
#endif

View file

@ -1,4 +1,5 @@
#include "e131.h" #include "e131.h"
#ifdef USE_NETWORK
#include "e131_addressable_light_effect.h" #include "e131_addressable_light_effect.h"
#include "esphome/core/log.h" #include "esphome/core/log.h"
@ -118,3 +119,4 @@ bool E131Component::process_(int universe, const E131Packet &packet) {
} // namespace e131 } // namespace e131
} // namespace esphome } // namespace esphome
#endif

View file

@ -1,5 +1,6 @@
#pragma once #pragma once
#include "esphome/core/defines.h"
#ifdef USE_NETWORK
#include "esphome/components/socket/socket.h" #include "esphome/components/socket/socket.h"
#include "esphome/core/component.h" #include "esphome/core/component.h"
@ -53,3 +54,4 @@ class E131Component : public esphome::Component {
} // namespace e131 } // namespace e131
} // namespace esphome } // namespace esphome
#endif

View file

@ -1,5 +1,6 @@
#include "e131_addressable_light_effect.h" #include "e131_addressable_light_effect.h"
#include "e131.h" #include "e131.h"
#ifdef USE_NETWORK
#include "esphome/core/log.h" #include "esphome/core/log.h"
namespace esphome { namespace esphome {
@ -90,3 +91,4 @@ bool E131AddressableLightEffect::process_(int universe, const E131Packet &packet
} // namespace e131 } // namespace e131
} // namespace esphome } // namespace esphome
#endif

View file

@ -2,7 +2,7 @@
#include "esphome/core/component.h" #include "esphome/core/component.h"
#include "esphome/components/light/addressable_light_effect.h" #include "esphome/components/light/addressable_light_effect.h"
#ifdef USE_NETWORK
namespace esphome { namespace esphome {
namespace e131 { namespace e131 {
@ -42,3 +42,4 @@ class E131AddressableLightEffect : public light::AddressableLightEffect {
} // namespace e131 } // namespace e131
} // namespace esphome } // namespace esphome
#endif

View file

@ -1,5 +1,6 @@
#include <cstring> #include <cstring>
#include "e131.h" #include "e131.h"
#ifdef USE_NETWORK
#include "esphome/components/network/ip_address.h" #include "esphome/components/network/ip_address.h"
#include "esphome/core/log.h" #include "esphome/core/log.h"
#include "esphome/core/util.h" #include "esphome/core/util.h"
@ -137,3 +138,4 @@ bool E131Component::packet_(const std::vector<uint8_t> &data, int &universe, E13
} // namespace e131 } // namespace e131
} // namespace esphome } // namespace esphome
#endif

View file

@ -172,6 +172,19 @@ def add_idf_component(
KEY_COMPONENTS: components, KEY_COMPONENTS: components,
KEY_SUBMODULES: submodules, KEY_SUBMODULES: submodules,
} }
else:
component_config = CORE.data[KEY_ESP32][KEY_COMPONENTS][name]
if components is not None:
component_config[KEY_COMPONENTS] = list(
set(component_config[KEY_COMPONENTS] + components)
)
if submodules is not None:
if component_config[KEY_SUBMODULES] is None:
component_config[KEY_SUBMODULES] = submodules
else:
component_config[KEY_SUBMODULES] = list(
set(component_config[KEY_SUBMODULES] + submodules)
)
def add_extra_script(stage: str, filename: str, path: str): def add_extra_script(stage: str, filename: str, path: str):

View file

@ -1,5 +1,5 @@
#include "ota_esphome.h" #include "ota_esphome.h"
#ifdef USE_OTA
#include "esphome/components/md5/md5.h" #include "esphome/components/md5/md5.h"
#include "esphome/components/network/util.h" #include "esphome/components/network/util.h"
#include "esphome/components/ota/ota_backend.h" #include "esphome/components/ota/ota_backend.h"
@ -410,3 +410,4 @@ float ESPHomeOTAComponent::get_setup_priority() const { return setup_priority::A
uint16_t ESPHomeOTAComponent::get_port() const { return this->port_; } uint16_t ESPHomeOTAComponent::get_port() const { return this->port_; }
void ESPHomeOTAComponent::set_port(uint16_t port) { this->port_ = port; } void ESPHomeOTAComponent::set_port(uint16_t port) { this->port_ = port; }
} // namespace esphome } // namespace esphome
#endif

View file

@ -1,6 +1,7 @@
#pragma once #pragma once
#include "esphome/core/defines.h" #include "esphome/core/defines.h"
#ifdef USE_OTA
#include "esphome/core/helpers.h" #include "esphome/core/helpers.h"
#include "esphome/core/preferences.h" #include "esphome/core/preferences.h"
#include "esphome/components/ota/ota_backend.h" #include "esphome/components/ota/ota_backend.h"
@ -41,3 +42,4 @@ class ESPHomeOTAComponent : public ota::OTAComponent {
}; };
} // namespace esphome } // namespace esphome
#endif

View file

@ -0,0 +1,2 @@
AUTO_LOAD = ["md5"]
CODEOWNERS = ["@dwmw2"]

View file

@ -0,0 +1,56 @@
#include <cstdio>
#include <cstring>
#include "hmac_md5.h"
#include "esphome/core/helpers.h"
namespace esphome {
namespace hmac_md5 {
void HmacMD5::init(const uint8_t *key, size_t len) {
uint8_t ipad[64], opad[64];
memset(ipad, 0, sizeof(ipad));
if (len > 64) {
md5::MD5Digest keymd5;
keymd5.init();
keymd5.add(key, len);
keymd5.calculate();
keymd5.get_bytes(ipad);
} else {
memcpy(ipad, key, len);
}
memcpy(opad, ipad, sizeof(opad));
for (int i = 0; i < 64; i++) {
ipad[i] ^= 0x36;
opad[i] ^= 0x5c;
}
this->ihash_.init();
this->ihash_.add(ipad, sizeof(ipad));
this->ohash_.init();
this->ohash_.add(opad, sizeof(opad));
}
void HmacMD5::add(const uint8_t *data, size_t len) { this->ihash_.add(data, len); }
void HmacMD5::calculate() {
uint8_t ibytes[16];
this->ihash_.calculate();
this->ihash_.get_bytes(ibytes);
this->ohash_.add(ibytes, sizeof(ibytes));
this->ohash_.calculate();
}
void HmacMD5::get_bytes(uint8_t *output) { this->ohash_.get_bytes(output); }
void HmacMD5::get_hex(char *output) { this->ohash_.get_hex(output); }
bool HmacMD5::equals_bytes(const uint8_t *expected) { return this->ohash_.equals_bytes(expected); }
bool HmacMD5::equals_hex(const char *expected) { return this->ohash_.equals_hex(expected); }
} // namespace hmac_md5
} // namespace esphome

View file

@ -0,0 +1,48 @@
#pragma once
#include "esphome/core/defines.h"
#include "esphome/components/md5/md5.h"
#include <string>
namespace esphome {
namespace hmac_md5 {
class HmacMD5 {
public:
HmacMD5() = default;
~HmacMD5() = default;
/// Initialize a new MD5 digest computation.
void init(const uint8_t *key, size_t len);
void init(const char *key, size_t len) { this->init((const uint8_t *) key, len); }
void init(const std::string &key) { this->init(key.c_str(), key.length()); }
/// Add bytes of data for the digest.
void add(const uint8_t *data, size_t len);
void add(const char *data, size_t len) { this->add((const uint8_t *) data, len); }
/// Compute the digest, based on the provided data.
void calculate();
/// Retrieve the HMAC-MD5 digest as bytes.
/// The output must be able to hold 16 bytes or more.
void get_bytes(uint8_t *output);
/// Retrieve the HMAC-MD5 digest as hex characters.
/// The output must be able to hold 32 bytes or more.
void get_hex(char *output);
/// Compare the digest against a provided byte-encoded digest (16 bytes).
bool equals_bytes(const uint8_t *expected);
/// Compare the digest against a provided hex-encoded digest (32 bytes).
bool equals_hex(const char *expected);
protected:
md5::MD5Digest ihash_;
md5::MD5Digest ohash_;
};
} // namespace hmac_md5
} // namespace esphome

View file

@ -1,15 +1,14 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import ( from esphome.const import (
CONF_MAC_ADDRESS,
KEY_CORE, KEY_CORE,
KEY_FRAMEWORK_VERSION, KEY_FRAMEWORK_VERSION,
KEY_TARGET_FRAMEWORK, KEY_TARGET_FRAMEWORK,
KEY_TARGET_PLATFORM, KEY_TARGET_PLATFORM,
PLATFORM_HOST, PLATFORM_HOST,
CONF_MAC_ADDRESS,
) )
from esphome.core import CORE from esphome.core import CORE
from esphome.helpers import IS_MACOS
import esphome.config_validation as cv
import esphome.codegen as cg
from .const import KEY_HOST from .const import KEY_HOST
@ -42,8 +41,5 @@ async def to_code(config):
cg.add_build_flag("-DUSE_HOST") cg.add_build_flag("-DUSE_HOST")
cg.add_define("USE_ESPHOME_HOST_MAC_ADDRESS", config[CONF_MAC_ADDRESS].parts) cg.add_define("USE_ESPHOME_HOST_MAC_ADDRESS", config[CONF_MAC_ADDRESS].parts)
cg.add_build_flag("-std=c++17") cg.add_build_flag("-std=c++17")
cg.add_build_flag("-lsodium")
if IS_MACOS:
cg.add_build_flag("-L/opt/homebrew/lib")
cg.add_define("ESPHOME_BOARD", "host") cg.add_define("ESPHOME_BOARD", "host")
cg.add_platformio_option("platform", "platformio/native") cg.add_platformio_option("platform", "platformio/native")

View file

@ -1,5 +1,5 @@
#include "improv_serial_component.h" #include "improv_serial_component.h"
#ifdef USE_WIFI
#include "esphome/core/application.h" #include "esphome/core/application.h"
#include "esphome/core/defines.h" #include "esphome/core/defines.h"
#include "esphome/core/hal.h" #include "esphome/core/hal.h"
@ -313,3 +313,4 @@ ImprovSerialComponent *global_improv_serial_component = // NOLINT(cppcoreguidel
} // namespace improv_serial } // namespace improv_serial
} // namespace esphome } // namespace esphome
#endif

View file

@ -5,7 +5,7 @@
#include "esphome/core/component.h" #include "esphome/core/component.h"
#include "esphome/core/defines.h" #include "esphome/core/defines.h"
#include "esphome/core/helpers.h" #include "esphome/core/helpers.h"
#ifdef USE_WIFI
#include <improv.h> #include <improv.h>
#include <vector> #include <vector>
@ -78,3 +78,4 @@ extern ImprovSerialComponent
} // namespace improv_serial } // namespace improv_serial
} // namespace esphome } // namespace esphome
#endif

View file

@ -41,29 +41,29 @@ class ESPColorCorrection {
if (this->max_brightness_.red == 0 || this->local_brightness_ == 0) if (this->max_brightness_.red == 0 || this->local_brightness_ == 0)
return 0; return 0;
uint16_t uncorrected = this->gamma_reverse_table_[red] * 255UL; uint16_t uncorrected = this->gamma_reverse_table_[red] * 255UL;
uint8_t res = ((uncorrected / this->max_brightness_.red) * 255UL) / this->local_brightness_; uint16_t res = ((uncorrected / this->max_brightness_.red) * 255UL) / this->local_brightness_;
return res; return (uint8_t) std::min(res, uint16_t(255));
} }
inline uint8_t color_uncorrect_green(uint8_t green) const ESPHOME_ALWAYS_INLINE { inline uint8_t color_uncorrect_green(uint8_t green) const ESPHOME_ALWAYS_INLINE {
if (this->max_brightness_.green == 0 || this->local_brightness_ == 0) if (this->max_brightness_.green == 0 || this->local_brightness_ == 0)
return 0; return 0;
uint16_t uncorrected = this->gamma_reverse_table_[green] * 255UL; uint16_t uncorrected = this->gamma_reverse_table_[green] * 255UL;
uint8_t res = ((uncorrected / this->max_brightness_.green) * 255UL) / this->local_brightness_; uint16_t res = ((uncorrected / this->max_brightness_.green) * 255UL) / this->local_brightness_;
return res; return (uint8_t) std::min(res, uint16_t(255));
} }
inline uint8_t color_uncorrect_blue(uint8_t blue) const ESPHOME_ALWAYS_INLINE { inline uint8_t color_uncorrect_blue(uint8_t blue) const ESPHOME_ALWAYS_INLINE {
if (this->max_brightness_.blue == 0 || this->local_brightness_ == 0) if (this->max_brightness_.blue == 0 || this->local_brightness_ == 0)
return 0; return 0;
uint16_t uncorrected = this->gamma_reverse_table_[blue] * 255UL; uint16_t uncorrected = this->gamma_reverse_table_[blue] * 255UL;
uint8_t res = ((uncorrected / this->max_brightness_.blue) * 255UL) / this->local_brightness_; uint16_t res = ((uncorrected / this->max_brightness_.blue) * 255UL) / this->local_brightness_;
return res; return (uint8_t) std::min(res, uint16_t(255));
} }
inline uint8_t color_uncorrect_white(uint8_t white) const ESPHOME_ALWAYS_INLINE { inline uint8_t color_uncorrect_white(uint8_t white) const ESPHOME_ALWAYS_INLINE {
if (this->max_brightness_.white == 0 || this->local_brightness_ == 0) if (this->max_brightness_.white == 0 || this->local_brightness_ == 0)
return 0; return 0;
uint16_t uncorrected = this->gamma_reverse_table_[white] * 255UL; uint16_t uncorrected = this->gamma_reverse_table_[white] * 255UL;
uint8_t res = ((uncorrected / this->max_brightness_.white) * 255UL) / this->local_brightness_; uint16_t res = ((uncorrected / this->max_brightness_.white) * 255UL) / this->local_brightness_;
return res; return (uint8_t) std::min(res, uint16_t(255));
} }
protected: protected:

View file

@ -5,6 +5,7 @@ from esphome import automation
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 CONF_ID, CONF_TIMEOUT from esphome.const import CONF_ID, CONF_TIMEOUT
from esphome.cpp_generator import RawExpression
from esphome.cpp_types import nullptr from esphome.cpp_types import nullptr
from .defines import ( from .defines import (
@ -26,6 +27,7 @@ from .lvcode import (
add_line_marks, add_line_marks,
lv, lv,
lv_add, lv_add,
lv_expr,
lv_obj, lv_obj,
lvgl_comp, lvgl_comp,
) )
@ -38,7 +40,13 @@ from .types import (
lv_disp_t, lv_disp_t,
lv_obj_t, lv_obj_t,
) )
from .widgets import Widget, get_widgets, lv_scr_act, set_obj_properties from .widgets import (
Widget,
get_widgets,
lv_scr_act,
set_obj_properties,
wait_for_widgets,
)
async def action_to_code( async def action_to_code(
@ -48,9 +56,11 @@ async def action_to_code(
template_arg, template_arg,
args, args,
): ):
await wait_for_widgets()
async with LambdaContext(parameters=args, where=action_id) as context: async with LambdaContext(parameters=args, where=action_id) as context:
with LvConditional(lv_expr.is_pre_initialise()):
context.add(RawExpression("return"))
for widget in widgets: for widget in widgets:
with LvConditional(widget.obj != nullptr):
await action(widget) await action(widget)
var = cg.new_Pvariable(action_id, template_arg, await context.get_lambda()) var = cg.new_Pvariable(action_id, template_arg, await context.get_lambda())
return var return var

View file

@ -6,8 +6,8 @@ Constants already defined in esphome.const are not duplicated here and must be i
from esphome import codegen as cg, config_validation as cv from esphome import codegen as cg, config_validation as cv
from esphome.const import CONF_ITEMS from esphome.const import CONF_ITEMS
from esphome.core import ID, Lambda from esphome.core import Lambda
from esphome.cpp_generator import MockObj from esphome.cpp_generator import LambdaExpression, MockObj
from esphome.cpp_types import uint32 from esphome.cpp_types import uint32
from esphome.schema_extractors import SCHEMA_EXTRACT, schema_extractor from esphome.schema_extractors import SCHEMA_EXTRACT, schema_extractor
@ -22,19 +22,22 @@ def literal(arg):
return arg return arg
def call_lambda(lamb: LambdaExpression):
expr = lamb.content.strip()
if expr.startswith("return") and expr.endswith(";"):
return expr[7:][:-1]
return f"{lamb}()"
class LValidator: class LValidator:
""" """
A validator for a particular type used in LVGL. Usable in configs as a validator, also A validator for a particular type used in LVGL. Usable in configs as a validator, also
has `process()` to convert a value during code generation has `process()` to convert a value during code generation
""" """
def __init__( def __init__(self, validator, rtype, retmapper=None, requires=None):
self, validator, rtype, idtype=None, idexpr=None, retmapper=None, requires=None
):
self.validator = validator self.validator = validator
self.rtype = rtype self.rtype = rtype
self.idtype = idtype
self.idexpr = idexpr
self.retmapper = retmapper self.retmapper = retmapper
self.requires = requires self.requires = requires
@ -43,8 +46,6 @@ class LValidator:
value = requires_component(self.requires)(value) value = requires_component(self.requires)(value)
if isinstance(value, cv.Lambda): if isinstance(value, cv.Lambda):
return cv.returning_lambda(value) return cv.returning_lambda(value)
if self.idtype is not None and isinstance(value, ID):
return cv.use_id(self.idtype)(value)
return self.validator(value) return self.validator(value)
async def process(self, value, args=()): async def process(self, value, args=()):
@ -52,10 +53,10 @@ class LValidator:
return None return None
if isinstance(value, Lambda): if isinstance(value, Lambda):
return cg.RawExpression( return cg.RawExpression(
f"{await cg.process_lambda(value, args, return_type=self.rtype)}()" call_lambda(
await cg.process_lambda(value, args, return_type=self.rtype)
)
) )
if self.idtype is not None and isinstance(value, ID):
return cg.RawExpression(f"{value}->{self.idexpr}")
if self.retmapper is not None: if self.retmapper is not None:
return self.retmapper(value) return self.retmapper(value)
return cg.safe_exp(value) return cg.safe_exp(value)
@ -89,7 +90,7 @@ class LvConstant(LValidator):
cv.ensure_list(self.one_of), uint32, retmapper=self.mapper cv.ensure_list(self.one_of), uint32, retmapper=self.mapper
) )
def mapper(self, value, args=()): def mapper(self, value):
if not isinstance(value, list): if not isinstance(value, list):
value = [value] value = [value]
return literal( return literal(
@ -103,7 +104,7 @@ class LvConstant(LValidator):
def extend(self, *choices): def extend(self, *choices):
""" """
Extend an LVCconstant with additional choices. Extend an LVconstant with additional choices.
:param choices: The extra choices :param choices: The extra choices
:return: A new LVConstant instance :return: A new LVConstant instance
""" """
@ -431,6 +432,8 @@ CONF_ONE_LINE = "one_line"
CONF_ON_SELECT = "on_select" CONF_ON_SELECT = "on_select"
CONF_ONE_CHECKED = "one_checked" CONF_ONE_CHECKED = "one_checked"
CONF_NEXT = "next" CONF_NEXT = "next"
CONF_PAD_ROW = "pad_row"
CONF_PAD_COLUMN = "pad_column"
CONF_PAGE = "page" CONF_PAGE = "page"
CONF_PAGE_WRAP = "page_wrap" CONF_PAGE_WRAP = "page_wrap"
CONF_PASSWORD_MODE = "password_mode" CONF_PASSWORD_MODE = "password_mode"
@ -462,6 +465,7 @@ CONF_SKIP = "skip"
CONF_SYMBOL = "symbol" CONF_SYMBOL = "symbol"
CONF_TAB_ID = "tab_id" CONF_TAB_ID = "tab_id"
CONF_TABS = "tabs" CONF_TABS = "tabs"
CONF_TIME_FORMAT = "time_format"
CONF_TILE = "tile" CONF_TILE = "tile"
CONF_TILE_ID = "tile_id" CONF_TILE_ID = "tile_id"
CONF_TILES = "tiles" CONF_TILES = "tiles"

View file

@ -1,17 +1,14 @@
from typing import Union from typing import Union
import esphome.codegen as cg import esphome.codegen as cg
from esphome.components.binary_sensor import BinarySensor
from esphome.components.color import ColorStruct from esphome.components.color import ColorStruct
from esphome.components.font import Font from esphome.components.font import Font
from esphome.components.image import Image_ from esphome.components.image import Image_
from esphome.components.sensor import Sensor
from esphome.components.text_sensor import TextSensor
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome.const import CONF_ARGS, CONF_COLOR, CONF_FORMAT, CONF_VALUE from esphome.const import CONF_ARGS, CONF_COLOR, CONF_FORMAT, CONF_TIME, CONF_VALUE
from esphome.core import HexInt from esphome.core import HexInt, Lambda
from esphome.cpp_generator import MockObj from esphome.cpp_generator import MockObj
from esphome.cpp_types import uint32 from esphome.cpp_types import ESPTime, uint32
from esphome.helpers import cpp_string_escape from esphome.helpers import cpp_string_escape
from esphome.schema_extractors import SCHEMA_EXTRACT, schema_extractor from esphome.schema_extractors import SCHEMA_EXTRACT, schema_extractor
@ -19,9 +16,11 @@ from . import types as ty
from .defines import ( from .defines import (
CONF_END_VALUE, CONF_END_VALUE,
CONF_START_VALUE, CONF_START_VALUE,
CONF_TIME_FORMAT,
LV_FONTS, LV_FONTS,
LValidator, LValidator,
LvConstant, LvConstant,
call_lambda,
literal, literal,
) )
from .helpers import ( from .helpers import (
@ -110,13 +109,13 @@ def angle(value):
def size_validator(value): def size_validator(value):
"""A size in one axis - one of "size_content", a number (pixels) or a percentage""" """A size in one axis - one of "size_content", a number (pixels) or a percentage"""
if value == SCHEMA_EXTRACT: if value == SCHEMA_EXTRACT:
return ["size_content", "pixels", "..%"] return ["SIZE_CONTENT", "number of pixels", "percentage"]
if isinstance(value, str) and value.lower().endswith("px"): if isinstance(value, str) and value.lower().endswith("px"):
value = cv.int_(value[:-2]) value = cv.int_(value[:-2])
if isinstance(value, str) and not value.endswith("%"): if isinstance(value, str) and not value.endswith("%"):
if value.upper() == "SIZE_CONTENT": if value.upper() == "SIZE_CONTENT":
return "LV_SIZE_CONTENT" return "LV_SIZE_CONTENT"
raise cv.Invalid("must be 'size_content', a pixel position or a percentage") raise cv.Invalid("must be 'size_content', a percentage or an integer (pixels)")
if isinstance(value, int): if isinstance(value, int):
return cv.int_(value) return cv.int_(value)
# Will throw an exception if not a percentage. # Will throw an exception if not a percentage.
@ -125,6 +124,15 @@ def size_validator(value):
size = LValidator(size_validator, uint32, retmapper=literal) size = LValidator(size_validator, uint32, retmapper=literal)
def pixels_validator(value):
if isinstance(value, str) and value.lower().endswith("px"):
return cv.int_(value[:-2])
return cv.int_(value)
pixels = LValidator(pixels_validator, uint32, retmapper=literal)
radius_consts = LvConstant("LV_RADIUS_", "CIRCLE") radius_consts = LvConstant("LV_RADIUS_", "CIRCLE")
@ -167,9 +175,7 @@ lv_image = LValidator(
retmapper=lambda x: lv_expr.img_from(MockObj(x)), retmapper=lambda x: lv_expr.img_from(MockObj(x)),
requires="image", requires="image",
) )
lv_bool = LValidator( lv_bool = LValidator(cv.boolean, cg.bool_, retmapper=literal)
cv.boolean, cg.bool_, BinarySensor, "get_state()", retmapper=literal
)
def lv_pct(value: Union[int, float]): def lv_pct(value: Union[int, float]):
@ -185,42 +191,60 @@ def lvms_validator_(value):
lv_milliseconds = LValidator( lv_milliseconds = LValidator(
lvms_validator_, lvms_validator_, cg.int32, retmapper=lambda x: x.total_milliseconds
cg.int32,
retmapper=lambda x: x.total_milliseconds,
) )
class TextValidator(LValidator): class TextValidator(LValidator):
def __init__(self): def __init__(self):
super().__init__( super().__init__(cv.string, cg.std_string, lambda s: cg.safe_exp(f"{s}"))
cv.string,
cg.const_char_ptr,
TextSensor,
"get_state().c_str()",
lambda s: cg.safe_exp(f"{s}"),
)
def __call__(self, value): def __call__(self, value):
if isinstance(value, dict): if isinstance(value, dict) and CONF_FORMAT in value:
return value return value
return super().__call__(value) return super().__call__(value)
async def process(self, value, args=()): async def process(self, value, args=()):
if isinstance(value, dict): if isinstance(value, dict):
if format_str := value.get(CONF_FORMAT):
args = [str(x) for x in value[CONF_ARGS]] args = [str(x) for x in value[CONF_ARGS]]
arg_expr = cg.RawExpression(",".join(args)) arg_expr = cg.RawExpression(",".join(args))
format_str = cpp_string_escape(value[CONF_FORMAT]) format_str = cpp_string_escape(format_str)
return literal(f"str_sprintf({format_str}, {arg_expr}).c_str()") return literal(f"str_sprintf({format_str}, {arg_expr}).c_str()")
if time_format := value.get(CONF_TIME_FORMAT):
source = value[CONF_TIME]
if isinstance(source, Lambda):
time_format = cpp_string_escape(time_format)
return cg.RawExpression(
call_lambda(
await cg.process_lambda(source, args, return_type=ESPTime)
)
+ f".strftime({time_format}).c_str()"
)
# must be an ID
source = await cg.get_variable(source)
return source.now().strftime(time_format).c_str()
if isinstance(value, Lambda):
value = call_lambda(
await cg.process_lambda(value, args, return_type=self.rtype)
)
# Was the lambda call reduced to a string?
if value.endswith("c_str()") or (
value.endswith('"') and value.startswith('"')
):
pass
else:
# Either a std::string or a lambda call returning that. We need const char*
value = f"({value}).c_str()"
return cg.RawExpression(value)
return await super().process(value, args) return await super().process(value, args)
lv_text = TextValidator() lv_text = TextValidator()
lv_float = LValidator(cv.float_, cg.float_, Sensor, "get_state()") lv_float = LValidator(cv.float_, cg.float_)
lv_int = LValidator(cv.int_, cg.int_, Sensor, "get_state()") lv_int = LValidator(cv.int_, cg.int_)
lv_brightness = LValidator( lv_brightness = LValidator(cv.percentage, cg.float_, retmapper=lambda x: int(x * 255))
cv.percentage, cg.float_, Sensor, "get_state()", retmapper=lambda x: int(x * 255)
)
def is_lv_font(font): def is_lv_font(font):

View file

@ -294,6 +294,13 @@ void LvglComponent::loop() {
} }
lv_timer_handler_run_in_period(5); lv_timer_handler_run_in_period(5);
} }
bool lv_is_pre_initialise() {
if (!lv_is_initialized()) {
ESP_LOGE(TAG, "LVGL call before component is initialised");
return true;
}
return false;
}
#ifdef USE_LVGL_IMAGE #ifdef USE_LVGL_IMAGE
lv_img_dsc_t *lv_img_from(image::Image *src, lv_img_dsc_t *img_dsc) { lv_img_dsc_t *lv_img_from(image::Image *src, lv_img_dsc_t *img_dsc) {

View file

@ -40,6 +40,7 @@ namespace lvgl {
extern lv_event_code_t lv_api_event; // NOLINT extern lv_event_code_t lv_api_event; // NOLINT
extern lv_event_code_t lv_update_event; // NOLINT extern lv_event_code_t lv_update_event; // NOLINT
extern bool lv_is_pre_initialise();
#ifdef USE_LVGL_COLOR #ifdef USE_LVGL_COLOR
inline lv_color_t lv_color_from(Color color) { return lv_color_make(color.red, color.green, color.blue); } inline lv_color_t lv_color_from(Color color) { return lv_color_make(color.red, color.green, color.blue); }
#endif // USE_LVGL_COLOR #endif // USE_LVGL_COLOR

View file

@ -1,5 +1,7 @@
#pragma once #pragma once
#include <utility>
#include "esphome/components/number/number.h" #include "esphome/components/number/number.h"
#include "esphome/core/automation.h" #include "esphome/core/automation.h"
#include "esphome/core/component.h" #include "esphome/core/component.h"
@ -11,7 +13,7 @@ namespace lvgl {
class LVGLNumber : public number::Number { class LVGLNumber : public number::Number {
public: public:
void set_control_lambda(std::function<void(float)> control_lambda) { void set_control_lambda(std::function<void(float)> control_lambda) {
this->control_lambda_ = control_lambda; this->control_lambda_ = std::move(control_lambda);
if (this->initial_state_.has_value()) { if (this->initial_state_.has_value()) {
this->control_lambda_(this->initial_state_.value()); this->control_lambda_(this->initial_state_.value());
this->initial_state_.reset(); this->initial_state_.reset();

View file

@ -1,5 +1,6 @@
from esphome import config_validation as cv from esphome import config_validation as cv
from esphome.automation import Trigger, validate_automation from esphome.automation import Trigger, validate_automation
from esphome.components.time import RealTimeClock
from esphome.const import ( from esphome.const import (
CONF_ARGS, CONF_ARGS,
CONF_FORMAT, CONF_FORMAT,
@ -8,6 +9,7 @@ from esphome.const import (
CONF_ON_VALUE, CONF_ON_VALUE,
CONF_STATE, CONF_STATE,
CONF_TEXT, CONF_TEXT,
CONF_TIME,
CONF_TRIGGER_ID, CONF_TRIGGER_ID,
CONF_TYPE, CONF_TYPE,
) )
@ -15,6 +17,7 @@ from esphome.core import TimePeriod
from esphome.schema_extractors import SCHEMA_EXTRACT from esphome.schema_extractors import SCHEMA_EXTRACT
from . import defines as df, lv_validation as lvalid from . import defines as df, lv_validation as lvalid
from .defines import CONF_TIME_FORMAT
from .helpers import add_lv_use, requires_component, validate_printf from .helpers import add_lv_use, requires_component, validate_printf
from .lv_validation import lv_color, lv_font, lv_image from .lv_validation import lv_color, lv_font, lv_image
from .lvcode import LvglComponent from .lvcode import LvglComponent
@ -46,7 +49,13 @@ TEXT_SCHEMA = cv.Schema(
), ),
validate_printf, validate_printf,
), ),
lvalid.lv_text, cv.Schema(
{
cv.Required(CONF_TIME_FORMAT): cv.string,
cv.GenerateID(CONF_TIME): cv.templatable(cv.use_id(RealTimeClock)),
}
),
cv.templatable(cv.string),
) )
} }
) )
@ -116,15 +125,13 @@ STYLE_PROPS = {
"opa_layered": lvalid.opacity, "opa_layered": lvalid.opacity,
"outline_color": lvalid.lv_color, "outline_color": lvalid.lv_color,
"outline_opa": lvalid.opacity, "outline_opa": lvalid.opacity,
"outline_pad": lvalid.size, "outline_pad": lvalid.pixels,
"outline_width": lvalid.size, "outline_width": lvalid.pixels,
"pad_all": lvalid.size, "pad_all": lvalid.pixels,
"pad_bottom": lvalid.size, "pad_bottom": lvalid.pixels,
"pad_column": lvalid.size, "pad_left": lvalid.pixels,
"pad_left": lvalid.size, "pad_right": lvalid.pixels,
"pad_right": lvalid.size, "pad_top": lvalid.pixels,
"pad_row": lvalid.size,
"pad_top": lvalid.size,
"shadow_color": lvalid.lv_color, "shadow_color": lvalid.lv_color,
"shadow_ofs_x": cv.int_, "shadow_ofs_x": cv.int_,
"shadow_ofs_y": cv.int_, "shadow_ofs_y": cv.int_,
@ -304,6 +311,8 @@ LAYOUT_SCHEMA = {
cv.Required(df.CONF_GRID_COLUMNS): [grid_spec], cv.Required(df.CONF_GRID_COLUMNS): [grid_spec],
cv.Optional(df.CONF_GRID_COLUMN_ALIGN): grid_alignments, cv.Optional(df.CONF_GRID_COLUMN_ALIGN): grid_alignments,
cv.Optional(df.CONF_GRID_ROW_ALIGN): grid_alignments, cv.Optional(df.CONF_GRID_ROW_ALIGN): grid_alignments,
cv.Optional(df.CONF_PAD_ROW): lvalid.pixels,
cv.Optional(df.CONF_PAD_COLUMN): lvalid.pixels,
}, },
df.TYPE_FLEX: { df.TYPE_FLEX: {
cv.Optional( cv.Optional(
@ -312,6 +321,8 @@ LAYOUT_SCHEMA = {
cv.Optional(df.CONF_FLEX_ALIGN_MAIN, default="start"): flex_alignments, cv.Optional(df.CONF_FLEX_ALIGN_MAIN, default="start"): flex_alignments,
cv.Optional(df.CONF_FLEX_ALIGN_CROSS, default="start"): flex_alignments, cv.Optional(df.CONF_FLEX_ALIGN_CROSS, default="start"): flex_alignments,
cv.Optional(df.CONF_FLEX_ALIGN_TRACK, default="start"): flex_alignments, cv.Optional(df.CONF_FLEX_ALIGN_TRACK, default="start"): flex_alignments,
cv.Optional(df.CONF_PAD_ROW): lvalid.pixels,
cv.Optional(df.CONF_PAD_COLUMN): lvalid.pixels,
}, },
}, },
lower=True, lower=True,
@ -338,7 +349,6 @@ DISP_BG_SCHEMA = cv.Schema(
} }
) )
# A style schema that can include text # A style schema that can include text
STYLED_TEXT_SCHEMA = cv.maybe_simple_value( STYLED_TEXT_SCHEMA = cv.maybe_simple_value(
STYLE_SCHEMA.extend(TEXT_SCHEMA), key=CONF_TEXT STYLE_SCHEMA.extend(TEXT_SCHEMA), key=CONF_TEXT

View file

@ -1,5 +1,7 @@
#pragma once #pragma once
#include <utility>
#include "esphome/components/select/select.h" #include "esphome/components/select/select.h"
#include "esphome/core/automation.h" #include "esphome/core/automation.h"
#include "esphome/core/component.h" #include "esphome/core/component.h"
@ -28,7 +30,7 @@ static std::vector<std::string> split_string(const std::string &str) {
class LVGLSelect : public select::Select { class LVGLSelect : public select::Select {
public: public:
void set_control_lambda(std::function<void(size_t)> lambda) { void set_control_lambda(std::function<void(size_t)> lambda) {
this->control_lambda_ = lambda; this->control_lambda_ = std::move(lambda);
if (this->initial_state_.has_value()) { if (this->initial_state_.has_value()) {
this->control(this->initial_state_.value()); this->control(this->initial_state_.value());
this->initial_state_.reset(); this->initial_state_.reset();

View file

@ -1,5 +1,7 @@
#pragma once #pragma once
#include <utility>
#include "esphome/components/switch/switch.h" #include "esphome/components/switch/switch.h"
#include "esphome/core/automation.h" #include "esphome/core/automation.h"
#include "esphome/core/component.h" #include "esphome/core/component.h"
@ -11,7 +13,7 @@ namespace lvgl {
class LVGLSwitch : public switch_::Switch { class LVGLSwitch : public switch_::Switch {
public: public:
void set_control_lambda(std::function<void(bool)> state_lambda) { void set_control_lambda(std::function<void(bool)> state_lambda) {
this->state_lambda_ = state_lambda; this->state_lambda_ = std::move(state_lambda);
if (this->initial_state_.has_value()) { if (this->initial_state_.has_value()) {
this->state_lambda_(this->initial_state_.value()); this->state_lambda_(this->initial_state_.value());
this->initial_state_.reset(); this->initial_state_.reset();

View file

@ -1,5 +1,7 @@
#pragma once #pragma once
#include <utility>
#include "esphome/components/text/text.h" #include "esphome/components/text/text.h"
#include "esphome/core/automation.h" #include "esphome/core/automation.h"
#include "esphome/core/component.h" #include "esphome/core/component.h"
@ -11,7 +13,7 @@ namespace lvgl {
class LVGLText : public text::Text { class LVGLText : public text::Text {
public: public:
void set_control_lambda(std::function<void(const std::string)> control_lambda) { void set_control_lambda(std::function<void(const std::string)> control_lambda) {
this->control_lambda_ = control_lambda; this->control_lambda_ = std::move(control_lambda);
if (this->initial_state_.has_value()) { if (this->initial_state_.has_value()) {
this->control_lambda_(this->initial_state_.value()); this->control_lambda_(this->initial_state_.value());
this->initial_state_.reset(); this->initial_state_.reset();

View file

@ -1,3 +1,4 @@
import asyncio
import sys import sys
from typing import Any, Union from typing import Any, Union
@ -20,6 +21,8 @@ from ..defines import (
CONF_GRID_ROWS, CONF_GRID_ROWS,
CONF_LAYOUT, CONF_LAYOUT,
CONF_MAIN, CONF_MAIN,
CONF_PAD_COLUMN,
CONF_PAD_ROW,
CONF_SCROLLBAR_MODE, CONF_SCROLLBAR_MODE,
CONF_STYLES, CONF_STYLES,
CONF_WIDGETS, CONF_WIDGETS,
@ -29,6 +32,7 @@ from ..defines import (
TYPE_FLEX, TYPE_FLEX,
TYPE_GRID, TYPE_GRID,
LValidator, LValidator,
call_lambda,
join_enums, join_enums,
literal, literal,
) )
@ -220,6 +224,11 @@ async def get_widget_(wid: Widget):
return await FakeAwaitable(get_widget_generator(wid)) return await FakeAwaitable(get_widget_generator(wid))
async def wait_for_widgets():
while not Widget.widgets_completed:
await asyncio.sleep(0)
async def get_widgets(config: Union[dict, list], id: str = CONF_ID) -> list[Widget]: async def get_widgets(config: Union[dict, list], id: str = CONF_ID) -> list[Widget]:
if not config: if not config:
return [] return []
@ -273,6 +282,10 @@ async def set_obj_properties(w: Widget, config):
layout_type: str = layout[CONF_TYPE] layout_type: str = layout[CONF_TYPE]
add_lv_use(layout_type) add_lv_use(layout_type)
lv_obj.set_layout(w.obj, literal(f"LV_LAYOUT_{layout_type.upper()}")) lv_obj.set_layout(w.obj, literal(f"LV_LAYOUT_{layout_type.upper()}"))
if (pad_row := layout.get(CONF_PAD_ROW)) is not None:
w.set_style(CONF_PAD_ROW, pad_row, 0)
if (pad_column := layout.get(CONF_PAD_COLUMN)) is not None:
w.set_style(CONF_PAD_COLUMN, pad_column, 0)
if layout_type == TYPE_GRID: if layout_type == TYPE_GRID:
wid = config[CONF_ID] wid = config[CONF_ID]
rows = [str(x) for x in layout[CONF_GRID_ROWS]] rows = [str(x) for x in layout[CONF_GRID_ROWS]]
@ -316,8 +329,13 @@ async def set_obj_properties(w: Widget, config):
flag_clr = set() flag_clr = set()
flag_set = set() flag_set = set()
props = parts[CONF_MAIN][CONF_DEFAULT] props = parts[CONF_MAIN][CONF_DEFAULT]
lambs = {}
flag_set = set()
flag_clr = set()
for prop, value in {k: v for k, v in props.items() if k in OBJ_FLAGS}.items(): for prop, value in {k: v for k, v in props.items() if k in OBJ_FLAGS}.items():
if value: if isinstance(value, cv.Lambda):
lambs[prop] = value
elif value:
flag_set.add(prop) flag_set.add(prop)
else: else:
flag_clr.add(prop) flag_clr.add(prop)
@ -327,6 +345,13 @@ async def set_obj_properties(w: Widget, config):
if flag_clr: if flag_clr:
clrs = join_enums(flag_clr, "LV_OBJ_FLAG_") clrs = join_enums(flag_clr, "LV_OBJ_FLAG_")
w.clear_flag(clrs) w.clear_flag(clrs)
for key, value in lambs.items():
lamb = await cg.process_lambda(value, [], return_type=cg.bool_)
flag = f"LV_OBJ_FLAG_{key.upper()}"
with LvConditional(call_lambda(lamb)) as cond:
w.add_flag(flag)
cond.else_()
w.clear_flag(flag)
if states := config.get(CONF_STATE): if states := config.get(CONF_STATE):
adds = set() adds = set()
@ -348,7 +373,7 @@ async def set_obj_properties(w: Widget, config):
for key, value in lambs.items(): for key, value in lambs.items():
lamb = await cg.process_lambda(value, [], return_type=cg.bool_) lamb = await cg.process_lambda(value, [], return_type=cg.bool_)
state = f"LV_STATE_{key.upper()}" state = f"LV_STATE_{key.upper()}"
with LvConditional(f"{lamb}()") as cond: with LvConditional(call_lambda(lamb)) as cond:
w.add_state(state) w.add_state(state)
cond.else_() cond.else_()
w.clear_state(state) w.clear_state(state)

View file

@ -3,7 +3,7 @@ import functools
import esphome.codegen as cg import esphome.codegen as cg
import esphome.config_validation as cv import esphome.config_validation as cv
from ..defines import CONF_MAIN, literal from ..defines import CONF_MAIN
from ..lvcode import lv from ..lvcode import lv
from ..types import LvType from ..types import LvType
from . import Widget, WidgetType from . import Widget, WidgetType
@ -38,11 +38,13 @@ LINE_SCHEMA = {
class LineType(WidgetType): class LineType(WidgetType):
def __init__(self): def __init__(self):
super().__init__(CONF_LINE, LvType("lv_line_t"), (CONF_MAIN,), LINE_SCHEMA) super().__init__(
CONF_LINE, LvType("lv_line_t"), (CONF_MAIN,), LINE_SCHEMA, modify_schema={}
)
async def to_code(self, w: Widget, config): async def to_code(self, w: Widget, config):
"""For a line object, create and add the points""" """For a line object, create and add the points"""
data = literal(config[CONF_POINTS]) if data := config.get(CONF_POINTS):
points = cg.static_const_array(config[CONF_POINT_LIST_ID], data) points = cg.static_const_array(config[CONF_POINT_LIST_ID], data)
lv.line_set_points(w.obj, points, len(data)) lv.line_set_points(w.obj, points, len(data))

View file

@ -13,7 +13,7 @@ from ..defines import (
TYPE_FLEX, TYPE_FLEX,
literal, literal,
) )
from ..helpers import add_lv_use from ..helpers import add_lv_use, lvgl_components_required
from ..lv_validation import lv_bool, lv_pct, lv_text from ..lv_validation import lv_bool, lv_pct, lv_text
from ..lvcode import ( from ..lvcode import (
EVENT_ARG, EVENT_ARG,
@ -72,6 +72,7 @@ async def msgbox_to_code(conf):
*buttonmatrix_spec.get_uses(), *buttonmatrix_spec.get_uses(),
*button_spec.get_uses(), *button_spec.get_uses(),
) )
lvgl_components_required.add("BUTTONMATRIX")
messagebox_id = conf[CONF_ID] messagebox_id = conf[CONF_ID]
outer = lv_Pvariable(lv_obj_t, messagebox_id.id) outer = lv_Pvariable(lv_obj_t, messagebox_id.id)
buttonmatrix = new_Pvariable( buttonmatrix = new_Pvariable(

View file

@ -1,6 +1,9 @@
#pragma once #pragma once
#include "esphome/core/entity_base.h" #include <cstddef>
#include <cstdint>
#include <functional>
#include <vector>
#include "esphome/core/helpers.h" #include "esphome/core/helpers.h"
namespace esphome { namespace esphome {

View file

@ -24,7 +24,11 @@ CONFIG_SCHEMA = cv.Schema(
esp32=False, esp32=False,
rp2040=False, rp2040=False,
): cv.All( ): cv.All(
cv.boolean, cv.only_on([PLATFORM_ESP32, PLATFORM_ESP8266, PLATFORM_RP2040]) cv.boolean,
cv.Any(
cv.only_on([PLATFORM_ESP32, PLATFORM_ESP8266, PLATFORM_RP2040]),
cv.boolean_false,
),
), ),
cv.Optional(CONF_MIN_IPV6_ADDR_COUNT, default=0): cv.positive_int, cv.Optional(CONF_MIN_IPV6_ADDR_COUNT, default=0): cv.positive_int,
} }

View file

@ -136,6 +136,9 @@ void Pipsolar::loop() {
if (this->output_source_priority_battery_switch_) { if (this->output_source_priority_battery_switch_) {
this->output_source_priority_battery_switch_->publish_state(value_output_source_priority_ == 2); this->output_source_priority_battery_switch_->publish_state(value_output_source_priority_ == 2);
} }
if (this->output_source_priority_hybrid_switch_) {
this->output_source_priority_hybrid_switch_->publish_state(value_output_source_priority_ == 3);
}
if (this->charger_source_priority_) { if (this->charger_source_priority_) {
this->charger_source_priority_->publish_state(value_charger_source_priority_); this->charger_source_priority_->publish_state(value_charger_source_priority_);
} }

View file

@ -174,6 +174,7 @@ class Pipsolar : public uart::UARTDevice, public PollingComponent {
PIPSOLAR_SWITCH(output_source_priority_utility_switch, QPIRI) PIPSOLAR_SWITCH(output_source_priority_utility_switch, QPIRI)
PIPSOLAR_SWITCH(output_source_priority_solar_switch, QPIRI) PIPSOLAR_SWITCH(output_source_priority_solar_switch, QPIRI)
PIPSOLAR_SWITCH(output_source_priority_battery_switch, QPIRI) PIPSOLAR_SWITCH(output_source_priority_battery_switch, QPIRI)
PIPSOLAR_SWITCH(output_source_priority_hybrid_switch, QPIRI)
PIPSOLAR_SWITCH(input_voltage_range_switch, QPIRI) PIPSOLAR_SWITCH(input_voltage_range_switch, QPIRI)
PIPSOLAR_SWITCH(pv_ok_condition_for_parallel_switch, QPIRI) PIPSOLAR_SWITCH(pv_ok_condition_for_parallel_switch, QPIRI)
PIPSOLAR_SWITCH(pv_power_balance_switch, QPIRI) PIPSOLAR_SWITCH(pv_power_balance_switch, QPIRI)

View file

@ -9,6 +9,7 @@ DEPENDENCIES = ["uart"]
CONF_OUTPUT_SOURCE_PRIORITY_UTILITY = "output_source_priority_utility" CONF_OUTPUT_SOURCE_PRIORITY_UTILITY = "output_source_priority_utility"
CONF_OUTPUT_SOURCE_PRIORITY_SOLAR = "output_source_priority_solar" CONF_OUTPUT_SOURCE_PRIORITY_SOLAR = "output_source_priority_solar"
CONF_OUTPUT_SOURCE_PRIORITY_BATTERY = "output_source_priority_battery" CONF_OUTPUT_SOURCE_PRIORITY_BATTERY = "output_source_priority_battery"
CONF_OUTPUT_SOURCE_PRIORITY_HYBRID = "output_source_priority_hybrid"
CONF_INPUT_VOLTAGE_RANGE = "input_voltage_range" CONF_INPUT_VOLTAGE_RANGE = "input_voltage_range"
CONF_PV_OK_CONDITION_FOR_PARALLEL = "pv_ok_condition_for_parallel" CONF_PV_OK_CONDITION_FOR_PARALLEL = "pv_ok_condition_for_parallel"
CONF_PV_POWER_BALANCE = "pv_power_balance" CONF_PV_POWER_BALANCE = "pv_power_balance"
@ -17,6 +18,7 @@ TYPES = {
CONF_OUTPUT_SOURCE_PRIORITY_UTILITY: ("POP00", None), CONF_OUTPUT_SOURCE_PRIORITY_UTILITY: ("POP00", None),
CONF_OUTPUT_SOURCE_PRIORITY_SOLAR: ("POP01", None), CONF_OUTPUT_SOURCE_PRIORITY_SOLAR: ("POP01", None),
CONF_OUTPUT_SOURCE_PRIORITY_BATTERY: ("POP02", None), CONF_OUTPUT_SOURCE_PRIORITY_BATTERY: ("POP02", None),
CONF_OUTPUT_SOURCE_PRIORITY_HYBRID: ("POP03", None),
CONF_INPUT_VOLTAGE_RANGE: ("PGR01", "PGR00"), CONF_INPUT_VOLTAGE_RANGE: ("PGR01", "PGR00"),
CONF_PV_OK_CONDITION_FOR_PARALLEL: ("PPVOKC1", "PPVOKC0"), CONF_PV_OK_CONDITION_FOR_PARALLEL: ("PPVOKC1", "PPVOKC0"),
CONF_PV_POWER_BALANCE: ("PSPB1", "PSPB0"), CONF_PV_POWER_BALANCE: ("PSPB1", "PSPB0"),

View file

@ -1,4 +1,5 @@
#include "prometheus_handler.h" #include "prometheus_handler.h"
#ifdef USE_NETWORK
#include "esphome/core/application.h" #include "esphome/core/application.h"
namespace esphome { namespace esphome {
@ -350,3 +351,4 @@ void PrometheusHandler::lock_row_(AsyncResponseStream *stream, lock::Lock *obj)
} // namespace prometheus } // namespace prometheus
} // namespace esphome } // namespace esphome
#endif

View file

@ -1,5 +1,6 @@
#pragma once #pragma once
#include "esphome/core/defines.h"
#ifdef USE_NETWORK
#include <map> #include <map>
#include <utility> #include <utility>
@ -117,3 +118,4 @@ class PrometheusHandler : public AsyncWebHandler, public Component {
} // namespace prometheus } // namespace prometheus
} // namespace esphome } // namespace esphome
#endif

View file

@ -201,9 +201,6 @@ std::string ProntoProtocol::compensate_and_dump_sequence_(const RawTimings &data
out += dump_duration_(t_duration, timebase); out += dump_duration_(t_duration, timebase);
} }
// append minimum gap
out += dump_duration_(PRONTO_DEFAULT_GAP, timebase, true);
return out; return out;
} }

View file

@ -7,8 +7,10 @@
#include <hardware/clocks.h> #include <hardware/clocks.h>
#include <hardware/dma.h> #include <hardware/dma.h>
#include <hardware/irq.h>
#include <hardware/pio.h> #include <hardware/pio.h>
#include <pico/stdlib.h> #include <pico/stdlib.h>
#include <pico/sem.h>
namespace esphome { namespace esphome {
namespace rp2040_pio_led_strip { namespace rp2040_pio_led_strip {
@ -23,6 +25,19 @@ static std::map<Chipset, bool> conf_count_ = {
{CHIPSET_WS2812, false}, {CHIPSET_WS2812B, false}, {CHIPSET_SK6812, false}, {CHIPSET_WS2812, false}, {CHIPSET_WS2812B, false}, {CHIPSET_SK6812, false},
{CHIPSET_SM16703, false}, {CHIPSET_CUSTOM, false}, {CHIPSET_SM16703, false}, {CHIPSET_CUSTOM, false},
}; };
static bool dma_chan_active_[12];
static struct semaphore dma_write_complete_sem_[12];
// DMA interrupt service routine
void RP2040PIOLEDStripLightOutput::dma_write_complete_handler_() {
uint32_t channel = dma_hw->ints0;
for (uint dma_chan = 0; dma_chan < 12; ++dma_chan) {
if (RP2040PIOLEDStripLightOutput::dma_chan_active_[dma_chan] && (channel & (1u << dma_chan))) {
dma_hw->ints0 = (1u << dma_chan); // Clear the interrupt
sem_release(&RP2040PIOLEDStripLightOutput::dma_write_complete_sem_[dma_chan]); // Handle the interrupt
}
}
}
void RP2040PIOLEDStripLightOutput::setup() { void RP2040PIOLEDStripLightOutput::setup() {
ESP_LOGCONFIG(TAG, "Setting up RP2040 LED Strip..."); ESP_LOGCONFIG(TAG, "Setting up RP2040 LED Strip...");
@ -57,22 +72,22 @@ void RP2040PIOLEDStripLightOutput::setup() {
// but there are only 4 state machines on each PIO so we can only have 4 strips per PIO // but there are only 4 state machines on each PIO so we can only have 4 strips per PIO
uint offset = 0; uint offset = 0;
if (num_instance_[this->pio_ == pio0 ? 0 : 1] > 4) { if (RP2040PIOLEDStripLightOutput::num_instance_[this->pio_ == pio0 ? 0 : 1] > 4) {
ESP_LOGE(TAG, "Too many instances of PIO program"); ESP_LOGE(TAG, "Too many instances of PIO program");
this->mark_failed(); this->mark_failed();
return; return;
} }
// keep track of how many instances of the PIO program are running on each PIO // keep track of how many instances of the PIO program are running on each PIO
num_instance_[this->pio_ == pio0 ? 0 : 1]++; RP2040PIOLEDStripLightOutput::num_instance_[this->pio_ == pio0 ? 0 : 1]++;
// if there are multiple strips of the same chipset, we can reuse the same PIO program and save space // if there are multiple strips of the same chipset, we can reuse the same PIO program and save space
if (this->conf_count_[this->chipset_]) { if (this->conf_count_[this->chipset_]) {
offset = chipset_offsets_[this->chipset_]; offset = RP2040PIOLEDStripLightOutput::chipset_offsets_[this->chipset_];
} else { } else {
// Load the assembled program into the PIO and get its location in the PIO's instruction memory and save it // Load the assembled program into the PIO and get its location in the PIO's instruction memory and save it
offset = pio_add_program(this->pio_, this->program_); offset = pio_add_program(this->pio_, this->program_);
chipset_offsets_[this->chipset_] = offset; RP2040PIOLEDStripLightOutput::chipset_offsets_[this->chipset_] = offset;
conf_count_[this->chipset_] = true; RP2040PIOLEDStripLightOutput::conf_count_[this->chipset_] = true;
} }
// Configure the state machine's PIO, and start it // Configure the state machine's PIO, and start it
@ -93,6 +108,9 @@ void RP2040PIOLEDStripLightOutput::setup() {
return; return;
} }
// Mark the DMA channel as active
RP2040PIOLEDStripLightOutput::dma_chan_active_[this->dma_chan_] = true;
this->dma_config_ = dma_channel_get_default_config(this->dma_chan_); this->dma_config_ = dma_channel_get_default_config(this->dma_chan_);
channel_config_set_transfer_data_size( channel_config_set_transfer_data_size(
&this->dma_config_, &this->dma_config_,
@ -109,6 +127,13 @@ void RP2040PIOLEDStripLightOutput::setup() {
false // don't start yet false // don't start yet
); );
// Initialize the semaphore for this DMA channel
sem_init(&RP2040PIOLEDStripLightOutput::dma_write_complete_sem_[this->dma_chan_], 1, 1);
irq_set_exclusive_handler(DMA_IRQ_0, dma_write_complete_handler_); // after DMA all data, raise an interrupt
dma_channel_set_irq0_enabled(this->dma_chan_, true); // map DMA channel to interrupt
irq_set_enabled(DMA_IRQ_0, true); // enable interrupt
this->init_(this->pio_, this->sm_, offset, this->pin_, this->max_refresh_rate_); this->init_(this->pio_, this->sm_, offset, this->pin_, this->max_refresh_rate_);
} }
@ -126,6 +151,7 @@ void RP2040PIOLEDStripLightOutput::write_state(light::LightState *state) {
} }
// the bits are already in the correct order for the pio program so we can just copy the buffer using DMA // the bits are already in the correct order for the pio program so we can just copy the buffer using DMA
sem_acquire_blocking(&RP2040PIOLEDStripLightOutput::dma_write_complete_sem_[this->dma_chan_]);
dma_channel_transfer_from_buffer_now(this->dma_chan_, this->buf_, this->get_buffer_size_()); dma_channel_transfer_from_buffer_now(this->dma_chan_, this->buf_, this->get_buffer_size_());
} }

View file

@ -13,6 +13,7 @@
#include <hardware/pio.h> #include <hardware/pio.h>
#include <hardware/structs/pio.h> #include <hardware/structs/pio.h>
#include <pico/stdio.h> #include <pico/stdio.h>
#include <pico/sem.h>
#include <map> #include <map>
namespace esphome { namespace esphome {
@ -95,6 +96,8 @@ class RP2040PIOLEDStripLightOutput : public light::AddressableLight {
size_t get_buffer_size_() const { return this->num_leds_ * (3 + this->is_rgbw_); } size_t get_buffer_size_() const { return this->num_leds_ * (3 + this->is_rgbw_); }
static void dma_write_complete_handler_();
uint8_t *buf_{nullptr}; uint8_t *buf_{nullptr};
uint8_t *effect_data_{nullptr}; uint8_t *effect_data_{nullptr};
@ -120,6 +123,8 @@ class RP2040PIOLEDStripLightOutput : public light::AddressableLight {
inline static int num_instance_[2]; inline static int num_instance_[2];
inline static std::map<Chipset, bool> conf_count_; inline static std::map<Chipset, bool> conf_count_;
inline static std::map<Chipset, int> chipset_offsets_; inline static std::map<Chipset, int> chipset_offsets_;
inline static bool dma_chan_active_[12];
inline static struct semaphore dma_write_complete_sem_[12];
}; };
} // namespace rp2040_pio_led_strip } // namespace rp2040_pio_led_strip

View file

@ -29,6 +29,13 @@ inline double deg2rad(double degrees) {
void Rtttl::dump_config() { ESP_LOGCONFIG(TAG, "Rtttl"); } void Rtttl::dump_config() { ESP_LOGCONFIG(TAG, "Rtttl"); }
void Rtttl::play(std::string rtttl) { void Rtttl::play(std::string rtttl) {
if (this->state_ != State::STATE_STOPPED && this->state_ != State::STATE_STOPPING) {
int pos = this->rtttl_.find(':');
auto name = this->rtttl_.substr(0, pos);
ESP_LOGW(TAG, "RTTTL Component is already playing: %s", name.c_str());
return;
}
this->rtttl_ = std::move(rtttl); this->rtttl_ = std::move(rtttl);
this->default_duration_ = 4; this->default_duration_ = 4;
@ -98,16 +105,24 @@ void Rtttl::play(std::string rtttl) {
this->note_duration_ = 1; this->note_duration_ = 1;
#ifdef USE_SPEAKER #ifdef USE_SPEAKER
if (this->speaker_ != nullptr) {
this->set_state_(State::STATE_INIT);
this->samples_sent_ = 0; this->samples_sent_ = 0;
this->samples_count_ = 0; this->samples_count_ = 0;
}
#endif
#ifdef USE_OUTPUT
if (this->output_ != nullptr) {
this->set_state_(State::STATE_RUNNING);
}
#endif #endif
} }
void Rtttl::stop() { void Rtttl::stop() {
this->note_duration_ = 0;
#ifdef USE_OUTPUT #ifdef USE_OUTPUT
if (this->output_ != nullptr) { if (this->output_ != nullptr) {
this->output_->set_level(0.0); this->output_->set_level(0.0);
this->set_state_(STATE_STOPPED);
} }
#endif #endif
#ifdef USE_SPEAKER #ifdef USE_SPEAKER
@ -115,18 +130,37 @@ void Rtttl::stop() {
if (this->speaker_->is_running()) { if (this->speaker_->is_running()) {
this->speaker_->stop(); this->speaker_->stop();
} }
this->set_state_(STATE_STOPPING);
} }
#endif #endif
this->note_duration_ = 0;
} }
void Rtttl::loop() { void Rtttl::loop() {
if (this->note_duration_ == 0) if (this->note_duration_ == 0 || this->state_ == State::STATE_STOPPED)
return; return;
#ifdef USE_SPEAKER #ifdef USE_SPEAKER
if (this->speaker_ != nullptr) { if (this->speaker_ != nullptr) {
if (this->state_ == State::STATE_STOPPING) {
if (this->speaker_->is_stopped()) {
this->set_state_(State::STATE_STOPPED);
}
} else if (this->state_ == State::STATE_INIT) {
if (this->speaker_->is_stopped()) {
this->speaker_->start();
this->set_state_(State::STATE_STARTING);
}
} else if (this->state_ == State::STATE_STARTING) {
if (this->speaker_->is_running()) {
this->set_state_(State::STATE_RUNNING);
}
}
if (!this->speaker_->is_running()) {
return;
}
if (this->samples_sent_ != this->samples_count_) { if (this->samples_sent_ != this->samples_count_) {
SpeakerSample sample[SAMPLE_BUFFER_SIZE + 1]; SpeakerSample sample[SAMPLE_BUFFER_SIZE + 2];
int x = 0; int x = 0;
double rem = 0.0; double rem = 0.0;
@ -136,7 +170,7 @@ void Rtttl::loop() {
if (this->samples_per_wave_ != 0 && this->samples_sent_ >= this->samples_gap_) { // Play note// if (this->samples_per_wave_ != 0 && this->samples_sent_ >= this->samples_gap_) { // Play note//
rem = ((this->samples_sent_ << 10) % this->samples_per_wave_) * (360.0 / this->samples_per_wave_); rem = ((this->samples_sent_ << 10) % this->samples_per_wave_) * (360.0 / this->samples_per_wave_);
int16_t val = (49152 * this->gain_) * sin(deg2rad(rem)); int16_t val = (127 * this->gain_) * sin(deg2rad(rem)); // 16bit = 49152
sample[x].left = val; sample[x].left = val;
sample[x].right = val; sample[x].right = val;
@ -153,9 +187,9 @@ void Rtttl::loop() {
x++; x++;
} }
if (x > 0) { if (x > 0) {
int send = this->speaker_->play((uint8_t *) (&sample), x * 4); int send = this->speaker_->play((uint8_t *) (&sample), x * 2);
if (send != x * 4) { if (send != x * 4) {
this->samples_sent_ -= (x - (send / 4)); this->samples_sent_ -= (x - (send / 2));
} }
return; return;
} }
@ -167,14 +201,7 @@ void Rtttl::loop() {
return; return;
#endif #endif
if (!this->rtttl_[position_]) { if (!this->rtttl_[position_]) {
this->note_duration_ = 0; this->finish_();
#ifdef USE_OUTPUT
if (this->output_ != nullptr) {
this->output_->set_level(0.0);
}
#endif
ESP_LOGD(TAG, "Playback finished");
this->on_finished_playback_callback_.call();
return; return;
} }
@ -213,6 +240,7 @@ void Rtttl::loop() {
case 'a': case 'a':
note = 10; note = 10;
break; break;
case 'h':
case 'b': case 'b':
note = 12; note = 12;
break; break;
@ -238,14 +266,21 @@ void Rtttl::loop() {
uint8_t scale = get_integer_(); uint8_t scale = get_integer_();
if (scale == 0) if (scale == 0)
scale = this->default_octave_; scale = this->default_octave_;
if (scale < 4 || scale > 7) {
ESP_LOGE(TAG, "Octave out of valid range. Should be between 4 and 7. (Octave: %d)", scale);
this->finish_();
return;
}
bool need_note_gap = false; bool need_note_gap = false;
// Now play the note // Now play the note
if (note) { if (note) {
auto note_index = (scale - 4) * 12 + note; auto note_index = (scale - 4) * 12 + note;
if (note_index < 0 || note_index >= (int) sizeof(NOTES)) { if (note_index < 0 || note_index >= (int) sizeof(NOTES)) {
ESP_LOGE(TAG, "Note out of valid range"); ESP_LOGE(TAG, "Note out of valid range (note: %d, scale: %d, index: %d, max: %d)", note, scale, note_index,
this->note_duration_ = 0; (int) sizeof(NOTES));
this->finish_();
return; return;
} }
auto freq = NOTES[note_index]; auto freq = NOTES[note_index];
@ -285,14 +320,17 @@ void Rtttl::loop() {
this->samples_gap_ = (this->sample_rate_ * DOUBLE_NOTE_GAP_MS) / 1600; //(ms); this->samples_gap_ = (this->sample_rate_ * DOUBLE_NOTE_GAP_MS) / 1600; //(ms);
} }
if (this->output_freq_ != 0) { if (this->output_freq_ != 0) {
// make sure there is enough samples to add a full last sinus.
uint16_t samples_wish = this->samples_count_;
this->samples_per_wave_ = (this->sample_rate_ << 10) / this->output_freq_; this->samples_per_wave_ = (this->sample_rate_ << 10) / this->output_freq_;
// make sure there is enough samples to add a full last sinus.
uint16_t division = ((this->samples_count_ << 10) / this->samples_per_wave_) + 1; uint16_t division = ((this->samples_count_ << 10) / this->samples_per_wave_) + 1;
uint16_t x = this->samples_count_;
this->samples_count_ = (division * this->samples_per_wave_); this->samples_count_ = (division * this->samples_per_wave_);
ESP_LOGD(TAG, "play time old: %d div: %d new: %d %d", x, division, this->samples_count_, this->samples_per_wave_);
this->samples_count_ = this->samples_count_ >> 10; this->samples_count_ = this->samples_count_ >> 10;
ESP_LOGVV(TAG, "- Calc play time: wish: %d gets: %d (div: %d spw: %d)", samples_wish, this->samples_count_,
division, this->samples_per_wave_);
} }
// Convert from frequency in Hz to high and low samples in fixed point // Convert from frequency in Hz to high and low samples in fixed point
} }
@ -301,5 +339,54 @@ void Rtttl::loop() {
this->last_note_ = millis(); this->last_note_ = millis();
} }
void Rtttl::finish_() {
#ifdef USE_OUTPUT
if (this->output_ != nullptr) {
this->output_->set_level(0.0);
this->set_state_(State::STATE_STOPPED);
}
#endif
#ifdef USE_SPEAKER
if (this->speaker_ != nullptr) {
SpeakerSample sample[2];
sample[0].left = 0;
sample[0].right = 0;
sample[1].left = 0;
sample[1].right = 0;
this->speaker_->play((uint8_t *) (&sample), 8);
this->speaker_->finish();
this->set_state_(State::STATE_STOPPING);
}
#endif
this->note_duration_ = 0;
this->on_finished_playback_callback_.call();
ESP_LOGD(TAG, "Playback finished");
}
static const LogString *state_to_string(State state) {
switch (state) {
case STATE_STOPPED:
return LOG_STR("STATE_STOPPED");
case STATE_STARTING:
return LOG_STR("STATE_STARTING");
case STATE_RUNNING:
return LOG_STR("STATE_RUNNING");
case STATE_STOPPING:
return LOG_STR("STATE_STOPPING");
case STATE_INIT:
return LOG_STR("STATE_INIT");
default:
return LOG_STR("UNKNOWN");
}
};
void Rtttl::set_state_(State state) {
State old_state = this->state_;
this->state_ = state;
ESP_LOGD(TAG, "State changed from %s to %s", LOG_STR_ARG(state_to_string(old_state)),
LOG_STR_ARG(state_to_string(state)));
}
} // namespace rtttl } // namespace rtttl
} // namespace esphome } // namespace esphome

View file

@ -14,12 +14,20 @@
namespace esphome { namespace esphome {
namespace rtttl { namespace rtttl {
enum State : uint8_t {
STATE_STOPPED = 0,
STATE_INIT,
STATE_STARTING,
STATE_RUNNING,
STATE_STOPPING,
};
#ifdef USE_SPEAKER #ifdef USE_SPEAKER
static const size_t SAMPLE_BUFFER_SIZE = 512; static const size_t SAMPLE_BUFFER_SIZE = 2048;
struct SpeakerSample { struct SpeakerSample {
int16_t left{0}; int8_t left{0};
int16_t right{0}; int8_t right{0};
}; };
#endif #endif
@ -42,7 +50,7 @@ class Rtttl : public Component {
void stop(); void stop();
void dump_config() override; void dump_config() override;
bool is_playing() { return this->note_duration_ != 0; } bool is_playing() { return this->state_ != State::STATE_STOPPED; }
void loop() override; void loop() override;
void add_on_finished_playback_callback(std::function<void()> callback) { void add_on_finished_playback_callback(std::function<void()> callback) {
@ -57,6 +65,8 @@ class Rtttl : public Component {
} }
return ret; return ret;
} }
void finish_();
void set_state_(State state);
std::string rtttl_{""}; std::string rtttl_{""};
size_t position_{0}; size_t position_{0};
@ -68,13 +78,12 @@ class Rtttl : public Component {
uint32_t output_freq_; uint32_t output_freq_;
float gain_{0.6f}; float gain_{0.6f};
State state_{State::STATE_STOPPED};
#ifdef USE_OUTPUT #ifdef USE_OUTPUT
output::FloatOutput *output_; output::FloatOutput *output_;
#endif #endif
void play_output_();
#ifdef USE_SPEAKER #ifdef USE_SPEAKER
speaker::Speaker *speaker_{nullptr}; speaker::Speaker *speaker_{nullptr};
int sample_rate_{16000}; int sample_rate_{16000};

View file

@ -1,4 +1,5 @@
#include "socket.h" #include "socket.h"
#if defined(USE_SOCKET_IMPL_LWIP_TCP) || defined(USE_SOCKET_IMPL_LWIP_SOCKETS) || defined(USE_SOCKET_IMPL_BSD_SOCKETS)
#include <cerrno> #include <cerrno>
#include <cstring> #include <cstring>
#include <string> #include <string>
@ -74,3 +75,4 @@ socklen_t set_sockaddr_any(struct sockaddr *addr, socklen_t addrlen, uint16_t po
} }
} // namespace socket } // namespace socket
} // namespace esphome } // namespace esphome
#endif

View file

@ -5,6 +5,7 @@
#include "esphome/core/optional.h" #include "esphome/core/optional.h"
#include "headers.h" #include "headers.h"
#if defined(USE_SOCKET_IMPL_LWIP_TCP) || defined(USE_SOCKET_IMPL_LWIP_SOCKETS) || defined(USE_SOCKET_IMPL_BSD_SOCKETS)
namespace esphome { namespace esphome {
namespace socket { namespace socket {
@ -57,3 +58,4 @@ socklen_t set_sockaddr_any(struct sockaddr *addr, socklen_t addrlen, uint16_t po
} // namespace socket } // namespace socket
} // namespace esphome } // namespace esphome
#endif

View file

@ -1,5 +1,9 @@
#pragma once #pragma once
#include <cstddef>
#include <cstdint>
#include <vector>
namespace esphome { namespace esphome {
namespace speaker { namespace speaker {

View file

@ -15,6 +15,7 @@ CONF_DATAPOINT_TYPE = "datapoint_type"
CONF_STATUS_PIN = "status_pin" CONF_STATUS_PIN = "status_pin"
tuya_ns = cg.esphome_ns.namespace("tuya") tuya_ns = cg.esphome_ns.namespace("tuya")
TuyaDatapointType = tuya_ns.enum("TuyaDatapointType", is_class=True)
Tuya = tuya_ns.class_("Tuya", cg.Component, uart.UARTDevice) Tuya = tuya_ns.class_("Tuya", cg.Component, uart.UARTDevice)
DPTYPE_ANY = "any" DPTYPE_ANY = "any"

View file

@ -8,18 +8,36 @@ from esphome.const import (
CONF_MIN_VALUE, CONF_MIN_VALUE,
CONF_MULTIPLY, CONF_MULTIPLY,
CONF_STEP, CONF_STEP,
CONF_INITIAL_VALUE,
) )
from .. import tuya_ns, CONF_TUYA_ID, Tuya from .. import tuya_ns, CONF_TUYA_ID, Tuya, TuyaDatapointType
DEPENDENCIES = ["tuya"] DEPENDENCIES = ["tuya"]
CODEOWNERS = ["@frankiboy1"] CODEOWNERS = ["@frankiboy1"]
CONF_DATAPOINT_HIDDEN = "datapoint_hidden"
CONF_DATAPOINT_TYPE = "datapoint_type"
TuyaNumber = tuya_ns.class_("TuyaNumber", number.Number, cg.Component) TuyaNumber = tuya_ns.class_("TuyaNumber", number.Number, cg.Component)
DATAPOINT_TYPES = {
"int": TuyaDatapointType.INTEGER,
"uint": TuyaDatapointType.INTEGER,
"enum": TuyaDatapointType.ENUM,
}
def validate_min_max(config): def validate_min_max(config):
if config[CONF_MAX_VALUE] <= config[CONF_MIN_VALUE]: max_value = config[CONF_MAX_VALUE]
min_value = config[CONF_MIN_VALUE]
if max_value <= min_value:
raise cv.Invalid("max_value must be greater than min_value") raise cv.Invalid("max_value must be greater than min_value")
if hidden_config := config.get(CONF_DATAPOINT_HIDDEN):
if (initial_value := hidden_config.get(CONF_INITIAL_VALUE, None)) is not None:
if (initial_value > max_value) or (initial_value < min_value):
raise cv.Invalid(
f"{CONF_INITIAL_VALUE} must be a value between {CONF_MAX_VALUE} and {CONF_MIN_VALUE}"
)
return config return config
@ -33,6 +51,16 @@ CONFIG_SCHEMA = cv.All(
cv.Required(CONF_MIN_VALUE): cv.float_, cv.Required(CONF_MIN_VALUE): cv.float_,
cv.Required(CONF_STEP): cv.positive_float, cv.Required(CONF_STEP): cv.positive_float,
cv.Optional(CONF_MULTIPLY, default=1.0): cv.float_, cv.Optional(CONF_MULTIPLY, default=1.0): cv.float_,
cv.Optional(CONF_DATAPOINT_HIDDEN): cv.All(
cv.Schema(
{
cv.Required(CONF_DATAPOINT_TYPE): cv.enum(
DATAPOINT_TYPES, lower=True
),
cv.Optional(CONF_INITIAL_VALUE): cv.float_,
}
)
),
} }
) )
.extend(cv.COMPONENT_SCHEMA), .extend(cv.COMPONENT_SCHEMA),
@ -56,3 +84,9 @@ async def to_code(config):
cg.add(var.set_tuya_parent(parent)) cg.add(var.set_tuya_parent(parent))
cg.add(var.set_number_id(config[CONF_NUMBER_DATAPOINT])) cg.add(var.set_number_id(config[CONF_NUMBER_DATAPOINT]))
if hidden_config := config.get(CONF_DATAPOINT_HIDDEN):
cg.add(var.set_datapoint_type(hidden_config[CONF_DATAPOINT_TYPE]))
if (
hidden_init_value := hidden_config.get(CONF_INITIAL_VALUE, None)
) is not None:
cg.add(var.set_datapoint_initial_value(hidden_init_value))

View file

@ -15,8 +15,18 @@ void TuyaNumber::setup() {
ESP_LOGV(TAG, "MCU reported number %u is: %u", datapoint.id, datapoint.value_enum); ESP_LOGV(TAG, "MCU reported number %u is: %u", datapoint.id, datapoint.value_enum);
this->publish_state(datapoint.value_enum); this->publish_state(datapoint.value_enum);
} }
if ((this->type_) && (this->type_ != datapoint.type)) {
ESP_LOGW(TAG, "Reported type (%d) different than previously set (%d)!", static_cast<int>(datapoint.type),
static_cast<int>(*this->type_));
}
this->type_ = datapoint.type; this->type_ = datapoint.type;
}); });
this->parent_->add_on_initialized_callback([this] {
if ((this->initial_value_) && (this->type_)) {
this->control(*this->initial_value_);
}
});
} }
void TuyaNumber::control(float value) { void TuyaNumber::control(float value) {
@ -33,6 +43,15 @@ void TuyaNumber::control(float value) {
void TuyaNumber::dump_config() { void TuyaNumber::dump_config() {
LOG_NUMBER("", "Tuya Number", this); LOG_NUMBER("", "Tuya Number", this);
ESP_LOGCONFIG(TAG, " Number has datapoint ID %u", this->number_id_); ESP_LOGCONFIG(TAG, " Number has datapoint ID %u", this->number_id_);
if (this->type_) {
ESP_LOGCONFIG(TAG, " Datapoint type is %d", static_cast<int>(*this->type_));
} else {
ESP_LOGCONFIG(TAG, " Datapoint type is unknown");
}
if (this->initial_value_) {
ESP_LOGCONFIG(TAG, " Initial Value: %f", *this->initial_value_);
}
} }
} // namespace tuya } // namespace tuya

View file

@ -3,6 +3,7 @@
#include "esphome/core/component.h" #include "esphome/core/component.h"
#include "esphome/components/tuya/tuya.h" #include "esphome/components/tuya/tuya.h"
#include "esphome/components/number/number.h" #include "esphome/components/number/number.h"
#include "esphome/core/optional.h"
namespace esphome { namespace esphome {
namespace tuya { namespace tuya {
@ -13,6 +14,8 @@ class TuyaNumber : public number::Number, public Component {
void dump_config() override; void dump_config() override;
void set_number_id(uint8_t number_id) { this->number_id_ = number_id; } void set_number_id(uint8_t number_id) { this->number_id_ = number_id; }
void set_write_multiply(float factor) { multiply_by_ = factor; } void set_write_multiply(float factor) { multiply_by_ = factor; }
void set_datapoint_type(TuyaDatapointType type) { type_ = type; }
void set_datapoint_initial_value(float value) { this->initial_value_ = value; }
void set_tuya_parent(Tuya *parent) { this->parent_ = parent; } void set_tuya_parent(Tuya *parent) { this->parent_ = parent; }
@ -22,7 +25,8 @@ class TuyaNumber : public number::Number, public Component {
Tuya *parent_; Tuya *parent_;
uint8_t number_id_{0}; uint8_t number_id_{0};
float multiply_by_{1.0}; float multiply_by_{1.0};
TuyaDatapointType type_{}; optional<TuyaDatapointType> type_{};
optional<float> initial_value_{};
}; };
} // namespace tuya } // namespace tuya

View file

@ -480,7 +480,7 @@ void HOT WaveshareEPaperTypeA::display() {
this->start_data_(); this->start_data_();
switch (this->model_) { switch (this->model_) {
case TTGO_EPAPER_2_13_IN_B1: { // block needed because of variable initializations case TTGO_EPAPER_2_13_IN_B1: { // block needed because of variable initializations
int16_t wb = ((this->get_width_internal()) >> 3); int16_t wb = ((this->get_width_controller()) >> 3);
for (int i = 0; i < this->get_height_internal(); i++) { for (int i = 0; i < this->get_height_internal(); i++) {
for (int j = 0; j < wb; j++) { for (int j = 0; j < wb; j++) {
int idx = j + (this->get_height_internal() - 1 - i) * wb; int idx = j + (this->get_height_internal() - 1 - i) * wb;
@ -766,7 +766,7 @@ void WaveshareEPaper2P7InV2::initialize() {
// XRAM_START_AND_END_POSITION // XRAM_START_AND_END_POSITION
this->command(0x44); this->command(0x44);
this->data(0x00); this->data(0x00);
this->data(((get_width_internal() - 1) >> 3) & 0xFF); this->data(((this->get_width_controller() - 1) >> 3) & 0xFF);
// YRAM_START_AND_END_POSITION // YRAM_START_AND_END_POSITION
this->command(0x45); this->command(0x45);
this->data(0x00); this->data(0x00);
@ -928,8 +928,8 @@ void HOT WaveshareEPaper2P7InB::display() {
// TCON_RESOLUTION // TCON_RESOLUTION
this->command(0x61); this->command(0x61);
this->data(this->get_width_internal() >> 8); this->data(this->get_width_controller() >> 8);
this->data(this->get_width_internal() & 0xff); // 176 this->data(this->get_width_controller() & 0xff); // 176
this->data(this->get_height_internal() >> 8); this->data(this->get_height_internal() >> 8);
this->data(this->get_height_internal() & 0xff); // 264 this->data(this->get_height_internal() & 0xff); // 264
@ -994,7 +994,7 @@ void WaveshareEPaper2P7InBV2::initialize() {
// self.SetWindows(0, 0, self.width-1, self.height-1) // self.SetWindows(0, 0, self.width-1, self.height-1)
// SetWindows(self, Xstart, Ystart, Xend, Yend): // SetWindows(self, Xstart, Ystart, Xend, Yend):
uint32_t xend = this->get_width_internal() - 1; uint32_t xend = this->get_width_controller() - 1;
uint32_t yend = this->get_height_internal() - 1; uint32_t yend = this->get_height_internal() - 1;
this->command(0x44); this->command(0x44);
this->data(0x00); this->data(0x00);

View file

@ -1,19 +1,20 @@
import re
import ipaddress import ipaddress
import re
from esphome import automation
import esphome.codegen as cg import esphome.codegen as cg
from esphome.components import time
from esphome.components.esp32 import CORE, add_idf_sdkconfig_option
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome.const import ( from esphome.const import (
CONF_ID,
CONF_TIME_ID,
CONF_ADDRESS, CONF_ADDRESS,
CONF_ID,
CONF_REBOOT_TIMEOUT, CONF_REBOOT_TIMEOUT,
CONF_TIME_ID,
KEY_CORE, KEY_CORE,
KEY_FRAMEWORK_VERSION, KEY_FRAMEWORK_VERSION,
) )
from esphome.components.esp32 import CORE, add_idf_sdkconfig_option
from esphome.components import time
from esphome.core import TimePeriod from esphome.core import TimePeriod
from esphome import automation
CONF_NETMASK = "netmask" CONF_NETMASK = "netmask"
CONF_PRIVATE_KEY = "private_key" CONF_PRIVATE_KEY = "private_key"
@ -91,6 +92,8 @@ 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])
cg.add_define("USE_WIREGUARD")
cg.add(var.set_address(str(config[CONF_ADDRESS]))) cg.add(var.set_address(str(config[CONF_ADDRESS])))
cg.add(var.set_netmask(str(config[CONF_NETMASK]))) cg.add(var.set_netmask(str(config[CONF_NETMASK])))
cg.add(var.set_private_key(config[CONF_PRIVATE_KEY])) cg.add(var.set_private_key(config[CONF_PRIVATE_KEY]))

View file

@ -1,5 +1,5 @@
#include "wireguard.h" #include "wireguard.h"
#ifdef USE_WIREGUARD
#include <cinttypes> #include <cinttypes>
#include <ctime> #include <ctime>
#include <functional> #include <functional>
@ -289,3 +289,4 @@ std::string mask_key(const std::string &key) { return (key.substr(0, 5) + "[...]
} // namespace wireguard } // namespace wireguard
} // namespace esphome } // namespace esphome
#endif

View file

@ -1,5 +1,6 @@
#pragma once #pragma once
#include "esphome/core/defines.h"
#ifdef USE_WIREGUARD
#include <ctime> #include <ctime>
#include <vector> #include <vector>
#include <tuple> #include <tuple>
@ -170,3 +171,4 @@ template<typename... Ts> class WireguardDisableAction : public Action<Ts...>, pu
} // namespace wireguard } // namespace wireguard
} // namespace esphome } // namespace esphome
#endif

View file

@ -370,6 +370,20 @@ def boolean(value):
) )
def boolean_false(value):
"""Validate the given config option to be a boolean, set to False.
This option allows a bunch of different ways of expressing boolean values:
- instance of boolean
- 'true'/'false'
- 'yes'/'no'
- 'enable'/disable
"""
if boolean(value):
raise Invalid("Expected boolean value to be false")
return False
@schema_extractor_list @schema_extractor_list
def ensure_list(*validators): def ensure_list(*validators):
"""Validate this configuration option to be a list. """Validate this configuration option to be a list.

View file

@ -1043,6 +1043,7 @@ UNIT_KILOVOLT_AMPS_REACTIVE = "kVAR"
UNIT_KILOVOLT_AMPS_REACTIVE_HOURS = "kVARh" UNIT_KILOVOLT_AMPS_REACTIVE_HOURS = "kVARh"
UNIT_KILOWATT = "kW" UNIT_KILOWATT = "kW"
UNIT_KILOWATT_HOURS = "kWh" UNIT_KILOWATT_HOURS = "kWh"
UNIT_LITRE = "L"
UNIT_LUX = "lx" UNIT_LUX = "lx"
UNIT_METER = "m" UNIT_METER = "m"
UNIT_METER_PER_SECOND_SQUARED = "m/s²" UNIT_METER_PER_SECOND_SQUARED = "m/s²"

View file

@ -4,63 +4,57 @@
namespace esphome { namespace esphome {
ByteBuffer ByteBuffer::create(size_t capacity, Endian endianness) {
std::vector<uint8_t> data(capacity);
ByteBuffer buffer = {data};
buffer.endianness_ = endianness;
return buffer;
}
ByteBuffer ByteBuffer::wrap(const uint8_t *ptr, size_t len, Endian endianness) { 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); std::vector<uint8_t> data(ptr, ptr + len);
ByteBuffer buffer = {data}; ByteBuffer buffer = {data};
buffer.endianness_ = endianness; buffer.endianness_ = endianness;
return buffer; return buffer;
} }
ByteBuffer ByteBuffer::wrap(std::vector<uint8_t> data, Endian endianness) { ByteBuffer ByteBuffer::wrap(std::vector<uint8_t> const &data, Endian endianness) {
ByteBuffer buffer = {std::move(data)}; ByteBuffer buffer = {data};
buffer.endianness_ = endianness; buffer.endianness_ = endianness;
return buffer; return buffer;
} }
ByteBuffer ByteBuffer::wrap(uint8_t value) { ByteBuffer ByteBuffer::wrap(uint8_t value) {
ByteBuffer buffer = ByteBuffer::create(1); ByteBuffer buffer = ByteBuffer(1);
buffer.put_uint8(value); buffer.put_uint8(value);
buffer.flip(); buffer.flip();
return buffer; return buffer;
} }
ByteBuffer ByteBuffer::wrap(uint16_t value, Endian endianness) { ByteBuffer ByteBuffer::wrap(uint16_t value, Endian endianness) {
ByteBuffer buffer = ByteBuffer::create(2, endianness); ByteBuffer buffer = ByteBuffer(2, endianness);
buffer.put_uint16(value); buffer.put_uint16(value);
buffer.flip(); buffer.flip();
return buffer; return buffer;
} }
ByteBuffer ByteBuffer::wrap(uint32_t value, Endian endianness) { ByteBuffer ByteBuffer::wrap(uint32_t value, Endian endianness) {
ByteBuffer buffer = ByteBuffer::create(4, endianness); ByteBuffer buffer = ByteBuffer(4, endianness);
buffer.put_uint32(value); buffer.put_uint32(value);
buffer.flip(); buffer.flip();
return buffer; return buffer;
} }
ByteBuffer ByteBuffer::wrap(uint64_t value, Endian endianness) { ByteBuffer ByteBuffer::wrap(uint64_t value, Endian endianness) {
ByteBuffer buffer = ByteBuffer::create(8, endianness); ByteBuffer buffer = ByteBuffer(8, endianness);
buffer.put_uint64(value); buffer.put_uint64(value);
buffer.flip(); buffer.flip();
return buffer; return buffer;
} }
ByteBuffer ByteBuffer::wrap(float value, Endian endianness) { ByteBuffer ByteBuffer::wrap(float value, Endian endianness) {
ByteBuffer buffer = ByteBuffer::create(sizeof(float), endianness); ByteBuffer buffer = ByteBuffer(sizeof(float), endianness);
buffer.put_float(value); buffer.put_float(value);
buffer.flip(); buffer.flip();
return buffer; return buffer;
} }
ByteBuffer ByteBuffer::wrap(double value, Endian endianness) { ByteBuffer ByteBuffer::wrap(double value, Endian endianness) {
ByteBuffer buffer = ByteBuffer::create(sizeof(double), endianness); ByteBuffer buffer = ByteBuffer(sizeof(double), endianness);
buffer.put_double(value); buffer.put_double(value);
buffer.flip(); buffer.flip();
return buffer; return buffer;
@ -88,111 +82,52 @@ uint8_t ByteBuffer::get_uint8() {
assert(this->get_remaining() >= 1); assert(this->get_remaining() >= 1);
return this->data_[this->position_++]; return this->data_[this->position_++];
} }
uint16_t ByteBuffer::get_uint16() { uint64_t ByteBuffer::get_uint(size_t length) {
assert(this->get_remaining() >= 2); assert(this->get_remaining() >= length);
uint16_t value; uint64_t value = 0;
if (endianness_ == LITTLE) { if (this->endianness_ == LITTLE) {
value = this->data_[this->position_++]; this->position_ += length;
value |= this->data_[this->position_++] << 8; auto index = this->position_;
while (length-- != 0) {
value <<= 8;
value |= this->data_[--index];
}
} else { } else {
value = this->data_[this->position_++] << 8; while (length-- != 0) {
value |= this->data_[this->position_++]; value <<= 8;
}
return value;
}
uint32_t ByteBuffer::get_uint24() {
assert(this->get_remaining() >= 3);
uint32_t value;
if (endianness_ == LITTLE) {
value = this->data_[this->position_++];
value |= this->data_[this->position_++] << 8;
value |= this->data_[this->position_++] << 16;
} else {
value = this->data_[this->position_++] << 16;
value |= this->data_[this->position_++] << 8;
value |= this->data_[this->position_++]; value |= this->data_[this->position_++];
} }
}
return value; return value;
} }
uint32_t ByteBuffer::get_int24() { uint32_t ByteBuffer::get_int24() {
auto value = this->get_uint24(); auto value = this->get_uint24();
uint32_t mask = (~(uint32_t) 0) << 23; uint32_t mask = (~static_cast<uint32_t>(0)) << 23;
if ((value & mask) != 0) if ((value & mask) != 0)
value |= mask; value |= mask;
return value; return value;
} }
uint32_t ByteBuffer::get_uint32() {
assert(this->get_remaining() >= 4);
uint32_t value;
if (endianness_ == LITTLE) {
value = this->data_[this->position_++];
value |= this->data_[this->position_++] << 8;
value |= this->data_[this->position_++] << 16;
value |= this->data_[this->position_++] << 24;
} else {
value = this->data_[this->position_++] << 24;
value |= this->data_[this->position_++] << 16;
value |= this->data_[this->position_++] << 8;
value |= this->data_[this->position_++];
}
return value;
}
uint64_t ByteBuffer::get_uint64() {
assert(this->get_remaining() >= 8);
uint64_t value;
if (endianness_ == LITTLE) {
value = this->data_[this->position_++];
value |= (uint64_t) this->data_[this->position_++] << 8;
value |= (uint64_t) this->data_[this->position_++] << 16;
value |= (uint64_t) this->data_[this->position_++] << 24;
value |= (uint64_t) this->data_[this->position_++] << 32;
value |= (uint64_t) this->data_[this->position_++] << 40;
value |= (uint64_t) this->data_[this->position_++] << 48;
value |= (uint64_t) this->data_[this->position_++] << 56;
} else {
value = (uint64_t) this->data_[this->position_++] << 56;
value |= (uint64_t) this->data_[this->position_++] << 48;
value |= (uint64_t) this->data_[this->position_++] << 40;
value |= (uint64_t) this->data_[this->position_++] << 32;
value |= (uint64_t) this->data_[this->position_++] << 24;
value |= (uint64_t) this->data_[this->position_++] << 16;
value |= (uint64_t) this->data_[this->position_++] << 8;
value |= this->data_[this->position_++];
}
return value;
}
float ByteBuffer::get_float() { float ByteBuffer::get_float() {
assert(this->get_remaining() >= sizeof(float)); assert(this->get_remaining() >= sizeof(float));
uint8_t byte_array[sizeof(float)]; auto ui_value = this->get_uint32();
if (this->endianness_ == LITTLE) {
for (uint8_t &byte_part : byte_array) {
byte_part = this->data_[this->position_++];
}
} else {
for (size_t i = sizeof(float); i > 0; i--) {
byte_array[i - 1] = this->data_[this->position_++];
}
}
float value; float value;
std::memcpy(&value, byte_array, sizeof(float)); memcpy(&value, &ui_value, sizeof(float));
return value; return value;
} }
double ByteBuffer::get_double() { double ByteBuffer::get_double() {
assert(this->get_remaining() >= sizeof(double)); assert(this->get_remaining() >= sizeof(double));
uint8_t byte_array[sizeof(double)]; auto ui_value = this->get_uint64();
if (this->endianness_ == LITTLE) {
for (uint8_t &byte_part : byte_array) {
byte_part = this->data_[this->position_++];
}
} else {
for (size_t i = sizeof(double); i > 0; i--) {
byte_array[i - 1] = this->data_[this->position_++];
}
}
double value; double value;
std::memcpy(&value, byte_array, sizeof(double)); memcpy(&value, &ui_value, sizeof(double));
return value; return value;
} }
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 /// Putters
void ByteBuffer::put_uint8(uint8_t value) { void ByteBuffer::put_uint8(uint8_t value) {
@ -200,90 +135,39 @@ void ByteBuffer::put_uint8(uint8_t value) {
this->data_[this->position_++] = value; this->data_[this->position_++] = value;
} }
void ByteBuffer::put_uint16(uint16_t value) { void ByteBuffer::put_uint(uint64_t value, size_t length) {
assert(this->get_remaining() >= 2); assert(this->get_remaining() >= length);
if (this->endianness_ == LITTLE) { if (this->endianness_ == LITTLE) {
this->data_[this->position_++] = (uint8_t) value; while (length-- != 0) {
this->data_[this->position_++] = (uint8_t) (value >> 8); this->data_[this->position_++] = static_cast<uint8_t>(value);
} else { value >>= 8;
this->data_[this->position_++] = (uint8_t) (value >> 8);
this->data_[this->position_++] = (uint8_t) value;
} }
}
void ByteBuffer::put_uint24(uint32_t value) {
assert(this->get_remaining() >= 3);
if (this->endianness_ == LITTLE) {
this->data_[this->position_++] = (uint8_t) value;
this->data_[this->position_++] = (uint8_t) (value >> 8);
this->data_[this->position_++] = (uint8_t) (value >> 16);
} else { } else {
this->data_[this->position_++] = (uint8_t) (value >> 16); this->position_ += length;
this->data_[this->position_++] = (uint8_t) (value >> 8); auto index = this->position_;
this->data_[this->position_++] = (uint8_t) value; while (length-- != 0) {
this->data_[--index] = static_cast<uint8_t>(value);
value >>= 8;
} }
}
void ByteBuffer::put_uint32(uint32_t value) {
assert(this->get_remaining() >= 4);
if (this->endianness_ == LITTLE) {
this->data_[this->position_++] = (uint8_t) value;
this->data_[this->position_++] = (uint8_t) (value >> 8);
this->data_[this->position_++] = (uint8_t) (value >> 16);
this->data_[this->position_++] = (uint8_t) (value >> 24);
} else {
this->data_[this->position_++] = (uint8_t) (value >> 24);
this->data_[this->position_++] = (uint8_t) (value >> 16);
this->data_[this->position_++] = (uint8_t) (value >> 8);
this->data_[this->position_++] = (uint8_t) value;
}
}
void ByteBuffer::put_uint64(uint64_t value) {
assert(this->get_remaining() >= 8);
if (this->endianness_ == LITTLE) {
this->data_[this->position_++] = (uint8_t) value;
this->data_[this->position_++] = (uint8_t) (value >> 8);
this->data_[this->position_++] = (uint8_t) (value >> 16);
this->data_[this->position_++] = (uint8_t) (value >> 24);
this->data_[this->position_++] = (uint8_t) (value >> 32);
this->data_[this->position_++] = (uint8_t) (value >> 40);
this->data_[this->position_++] = (uint8_t) (value >> 48);
this->data_[this->position_++] = (uint8_t) (value >> 56);
} else {
this->data_[this->position_++] = (uint8_t) (value >> 56);
this->data_[this->position_++] = (uint8_t) (value >> 48);
this->data_[this->position_++] = (uint8_t) (value >> 40);
this->data_[this->position_++] = (uint8_t) (value >> 32);
this->data_[this->position_++] = (uint8_t) (value >> 24);
this->data_[this->position_++] = (uint8_t) (value >> 16);
this->data_[this->position_++] = (uint8_t) (value >> 8);
this->data_[this->position_++] = (uint8_t) value;
} }
} }
void ByteBuffer::put_float(float value) { 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)); assert(this->get_remaining() >= sizeof(float));
uint8_t byte_array[sizeof(float)]; uint32_t ui_value;
std::memcpy(byte_array, &value, sizeof(float)); memcpy(&ui_value, &value, sizeof(float)); // this work-around required to silence compiler warnings
if (this->endianness_ == LITTLE) { this->put_uint32(ui_value);
for (uint8_t byte_part : byte_array) {
this->data_[this->position_++] = byte_part;
}
} else {
for (size_t i = sizeof(float); i > 0; i--) {
this->data_[this->position_++] = byte_array[i - 1];
}
}
} }
void ByteBuffer::put_double(double 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)); assert(this->get_remaining() >= sizeof(double));
uint8_t byte_array[sizeof(double)]; uint64_t ui_value;
std::memcpy(byte_array, &value, sizeof(double)); memcpy(&ui_value, &value, sizeof(double));
if (this->endianness_ == LITTLE) { this->put_uint64(ui_value);
for (uint8_t byte_part : byte_array) { }
this->data_[this->position_++] = byte_part; void ByteBuffer::put_vector(const std::vector<uint8_t> &value) {
} assert(this->get_remaining() >= value.size());
} else { std::copy(value.begin(), value.end(), this->data_.begin() + this->position_);
for (size_t i = sizeof(double); i > 0; i--) { this->position_ += value.size();
this->data_[this->position_++] = byte_array[i - 1];
}
}
} }
} // namespace esphome } // namespace esphome

View file

@ -15,17 +15,20 @@ enum Endian { LITTLE, BIG };
* *
* There are three variables maintained pointing into the buffer: * There are three variables maintained pointing into the buffer:
* *
* 0 <= position <= limit <= capacity * capacity: the maximum amount of data that can be stored - set on construction and cannot be changed
*
* capacity: the maximum amount of data that can be stored
* limit: the limit of the data currently available to get or put * limit: the limit of the data currently available to get or put
* position: the current insert or extract position * 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 * 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 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 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 { class ByteBuffer {
public: public:
@ -34,13 +37,14 @@ class ByteBuffer {
/** /**
* Create a new Bytebuffer with the given capacity * Create a new Bytebuffer with the given capacity
*/ */
static ByteBuffer create(size_t capacity, Endian endianness = LITTLE); ByteBuffer(size_t capacity, Endian endianness = LITTLE)
: data_(std::vector<uint8_t>(capacity)), endianness_(endianness), limit_(capacity){};
/** /**
* Wrap an existing vector in a ByteBufffer * Wrap an existing vector in a ByteBufffer
*/ */
static ByteBuffer wrap(std::vector<uint8_t> data, Endian endianness = LITTLE); static ByteBuffer wrap(std::vector<uint8_t> const &data, Endian endianness = LITTLE);
/** /**
* Wrap an existing array in a ByteBufffer * 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); static ByteBuffer wrap(const uint8_t *ptr, size_t len, Endian endianness = LITTLE);
// Convenience functions to create a ByteBuffer from a value // Convenience functions to create a ByteBuffer from a value
@ -48,55 +52,66 @@ class ByteBuffer {
static ByteBuffer wrap(uint16_t value, Endian endianness = LITTLE); static ByteBuffer wrap(uint16_t value, Endian endianness = LITTLE);
static ByteBuffer wrap(uint32_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(uint64_t value, Endian endianness = LITTLE);
static ByteBuffer wrap(int8_t value) { return wrap((uint8_t) value); } static ByteBuffer wrap(int8_t value) { return wrap(static_cast<uint8_t>(value)); }
static ByteBuffer wrap(int16_t value, Endian endianness = LITTLE) { return wrap((uint16_t) value, endianness); } static ByteBuffer wrap(int16_t value, Endian endianness = LITTLE) {
static ByteBuffer wrap(int32_t value, Endian endianness = LITTLE) { return wrap((uint32_t) value, endianness); } return wrap(static_cast<uint16_t>(value), endianness);
static ByteBuffer wrap(int64_t value, Endian endianness = LITTLE) { return wrap((uint64_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(float value, Endian endianness = LITTLE);
static ByteBuffer wrap(double value, Endian endianness = LITTLE); static ByteBuffer wrap(double value, Endian endianness = LITTLE);
static ByteBuffer wrap(bool value) { return wrap(value ? (uint8_t) 1 : (uint8_t) 0); } static ByteBuffer wrap(bool value) { return wrap(static_cast<uint8_t>(value)); }
static ByteBuffer wrap(std::initializer_list<uint8_t> values, Endian endianness = LITTLE) {
return wrap(std::vector<uint8_t>(values), endianness);
}
// 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 // Get one byte from the buffer, increment position by 1
uint8_t get_uint8(); uint8_t get_uint8();
// Get a 16 bit unsigned value, increment by 2 // Get a 16 bit unsigned value, increment by 2
uint16_t get_uint16(); uint16_t get_uint16() { return static_cast<uint16_t>(this->get_uint(sizeof(uint16_t))); };
// Get a 24 bit unsigned value, increment by 3 // Get a 24 bit unsigned value, increment by 3
uint32_t get_uint24(); uint32_t get_uint24() { return static_cast<uint32_t>(this->get_uint(3)); };
// Get a 32 bit unsigned value, increment by 4 // Get a 32 bit unsigned value, increment by 4
uint32_t get_uint32(); uint32_t get_uint32() { return static_cast<uint32_t>(this->get_uint(sizeof(uint32_t))); };
// Get a 64 bit unsigned value, increment by 8 // Get a 64 bit unsigned value, increment by 8
uint64_t get_uint64(); uint64_t get_uint64() { return this->get_uint(sizeof(uint64_t)); };
// Signed versions of the get functions // Signed versions of the get functions
uint8_t get_int8() { return (int8_t) this->get_uint8(); }; uint8_t get_int8() { return static_cast<int8_t>(this->get_uint8()); };
int16_t get_int16() { return (int16_t) this->get_uint16(); } int16_t get_int16() { return static_cast<int16_t>(this->get_uint(sizeof(int16_t))); }
uint32_t get_int24(); uint32_t get_int24();
int32_t get_int32() { return (int32_t) this->get_uint32(); } int32_t get_int32() { return static_cast<int32_t>(this->get_uint(sizeof(int32_t))); }
int64_t get_int64() { return (int64_t) this->get_uint64(); } int64_t get_int64() { return static_cast<int64_t>(this->get_uint(sizeof(int64_t))); }
// Get a float value, increment by 4 // Get a float value, increment by 4
float get_float(); float get_float();
// Get a double value, increment by 8 // Get a double value, increment by 8
double get_double(); double get_double();
// Get a bool value, increment by 1 // Get a bool value, increment by 1
bool get_bool() { return this->get_uint8() != 0; } 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 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_uint8(uint8_t value);
void put_uint16(uint16_t value); void put_uint16(uint16_t value) { this->put_uint(value, sizeof(uint16_t)); }
void put_uint24(uint32_t value); void put_uint24(uint32_t value) { this->put_uint(value, 3); }
void put_uint32(uint32_t value); void put_uint32(uint32_t value) { this->put_uint(value, sizeof(uint32_t)); }
void put_uint64(uint64_t value); void put_uint64(uint64_t value) { this->put_uint(value, sizeof(uint64_t)); }
// Signed versions of the put functions // Signed versions of the put functions
void put_int8(int8_t value) { this->put_uint8(value); } void put_int8(int8_t value) { this->put_uint8(static_cast<uint8_t>(value)); }
void put_int24(int32_t value) { this->put_uint24(value); } void put_int16(int32_t value) { this->put_uint(static_cast<uint16_t>(value), sizeof(uint16_t)); }
void put_int32(int32_t value) { this->put_uint32(value); } void put_int24(int32_t value) { this->put_uint(static_cast<uint32_t>(value), 3); }
void put_int64(int64_t value) { this->put_uint64(value); } 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 // Extra put functions
void put_float(float value); void put_float(float value);
void put_double(double value); void put_double(double value);
void put_bool(bool value) { this->put_uint8(value ? 1 : 0); } 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_capacity() const { return this->data_.size(); }
inline size_t get_position() const { return this->position_; } inline size_t get_position() const { return this->position_; }
@ -113,12 +128,12 @@ class ByteBuffer {
// set limit to current position, postition to zero. Used when swapping from write to read operations. // set limit to current position, postition to zero. Used when swapping from write to read operations.
void flip(); void flip();
// retrieve a pointer to the underlying data. // retrieve a pointer to the underlying data.
uint8_t *array() { return this->data_.data(); }; std::vector<uint8_t> get_data() { return this->data_; };
void rewind() { this->position_ = 0; } void rewind() { this->position_ = 0; }
void reset() { this->position_ = this->mark_; } void reset() { this->position_ = this->mark_; }
protected: protected:
ByteBuffer(std::vector<uint8_t> data) : data_(std::move(data)) { this->limit_ = this->get_capacity(); } ByteBuffer(std::vector<uint8_t> const &data) : data_(data), limit_(data.size()) {}
std::vector<uint8_t> data_; std::vector<uint8_t> data_;
Endian endianness_{LITTLE}; Endian endianness_{LITTLE};
size_t position_{0}; size_t position_{0};

View file

@ -75,6 +75,7 @@
#define USE_VALVE #define USE_VALVE
#define USE_WIFI #define USE_WIFI
#define USE_WIFI_AP #define USE_WIFI_AP
#define USE_WIREGUARD
// Arduino-specific feature flags // Arduino-specific feature flags
#ifdef USE_ARDUINO #ifdef USE_ARDUINO

View file

@ -106,6 +106,8 @@ def storage_should_clean(old: StorageJSON, new: StorageJSON) -> bool:
return True return True
if old.build_path != new.build_path: if old.build_path != new.build_path:
return True return True
if old.loaded_integrations != new.loaded_integrations:
return True
return False return False
@ -117,7 +119,9 @@ def update_storage_json():
return return
if storage_should_clean(old, new): if storage_should_clean(old, new):
_LOGGER.info("Core config or version changed, cleaning build files...") _LOGGER.info(
"Core config, version or integrations changed, cleaning build files..."
)
clean_build() clean_build()
new.save(path) new.save(path)

View file

@ -11,10 +11,6 @@ esphome:
message: Button was pressed message: Button was pressed
- homeassistant.tag_scanned: pulse - homeassistant.tag_scanned: pulse
wifi:
ssid: MySSID
password: password1
api: api:
port: 8000 port: 8000
password: pwd password: pwd

View file

@ -1 +1,5 @@
<<: !include common.yaml <<: !include common.yaml
wifi:
ssid: MySSID
password: password1

View file

@ -1 +1,5 @@
<<: !include common.yaml <<: !include common.yaml
wifi:
ssid: MySSID
password: password1

View file

@ -1 +1,5 @@
<<: !include common.yaml <<: !include common.yaml
wifi:
ssid: MySSID
password: password1

View file

@ -1 +1,5 @@
<<: !include common.yaml <<: !include common.yaml
wifi:
ssid: MySSID
password: password1

View file

@ -1 +1,5 @@
<<: !include common.yaml <<: !include common.yaml
wifi:
ssid: MySSID
password: password1

View file

@ -0,0 +1,3 @@
<<: !include common.yaml
network:

View file

@ -1 +1,5 @@
<<: !include common.yaml <<: !include common.yaml
wifi:
ssid: MySSID
password: password1

View file

@ -127,3 +127,11 @@ binary_sensor:
- platform: lvgl - platform: lvgl
name: LVGL checkbox name: LVGL checkbox
widget: checkbox_id widget: checkbox_id
wifi:
ssid: SSID
password: PASSWORD123
time:
platform: sntp
id: time_id

View file

@ -16,8 +16,6 @@ lvgl:
border_width: 0 border_width: 0
radius: 0 radius: 0
pad_all: 0 pad_all: 0
pad_row: 0
pad_column: 0
border_color: 0x0077b3 border_color: 0x0077b3
text_color: 0xFFFFFF text_color: 0xFFFFFF
width: 100% width: 100%
@ -55,6 +53,13 @@ lvgl:
pages: pages:
- id: page1 - id: page1
skip: true skip: true
layout:
type: flex
pad_row: 4
pad_column: 4px
flex_align_main: center
flex_align_cross: start
flex_align_track: end
widgets: widgets:
- animimg: - animimg:
height: 60 height: 60
@ -118,10 +123,8 @@ lvgl:
outline_width: 10px outline_width: 10px
pad_all: 10px pad_all: 10px
pad_bottom: 10px pad_bottom: 10px
pad_column: 10px
pad_left: 10px pad_left: 10px
pad_right: 10px pad_right: 10px
pad_row: 10px
pad_top: 10px pad_top: 10px
shadow_color: light_blue shadow_color: light_blue
shadow_ofs_x: 5 shadow_ofs_x: 5
@ -221,10 +224,47 @@ lvgl:
- label: - label:
text: Button text: Button
on_click: on_click:
lvgl.label.update: - lvgl.label.update:
id: hello_label id: hello_label
bg_color: 0x123456 bg_color: 0x123456
text: clicked text: clicked
- lvgl.label.update:
id: hello_label
text: !lambda return "hello world";
- lvgl.label.update:
id: hello_label
text: !lambda |-
ESP_LOGD("label", "multi-line lambda");
return "hello world";
- lvgl.label.update:
id: hello_label
text: !lambda 'return str_sprintf("Hello space");'
- lvgl.label.update:
id: hello_label
text:
format: "sprintf format %s"
args: ['x ? "checked" : "unchecked"']
- lvgl.label.update:
id: hello_label
text:
time_format: "%c"
- lvgl.label.update:
id: hello_label
text:
time_format: "%c"
time: time_id
- lvgl.label.update:
id: hello_label
text:
time_format: "%c"
time: !lambda return id(time_id).now();
- lvgl.label.update:
id: hello_label
text:
time_format: "%c"
time: !lambda |-
ESP_LOGD("label", "multi-line lambda");
return id(time_id).now();
on_value: on_value:
logger.log: logger.log:
format: "state now %d" format: "state now %d"
@ -339,6 +379,7 @@ lvgl:
format: "bar value %f" format: "bar value %f"
args: [x] args: [x]
- line: - line:
id: lv_line_id
align: center align: center
points: points:
- 5, 5 - 5, 5
@ -347,7 +388,10 @@ lvgl:
- 180, 60 - 180, 60
- 240, 10 - 240, 10
on_click: on_click:
lvgl.page.next: - lvgl.widget.update:
id: lv_line_id
line_color: 0xFFFF
- lvgl.page.next:
- switch: - switch:
align: right_mid align: right_mid
- checkbox: - checkbox:
@ -396,6 +440,8 @@ lvgl:
grid_row_align: end grid_row_align: end
grid_rows: [25px, fr(1), content] grid_rows: [25px, fr(1), content]
grid_columns: [40, fr(1), fr(1)] grid_columns: [40, fr(1), fr(1)]
pad_row: 6px
pad_column: 0
widgets: widgets:
- image: - image:
grid_cell_row_pos: 0 grid_cell_row_pos: 0

View file

@ -0,0 +1,4 @@
substitutions:
network_enable_ipv6: "false"
<<: !include common.yaml

View file

@ -220,6 +220,8 @@ switch:
name: inverter0_output_source_priority_solar name: inverter0_output_source_priority_solar
output_source_priority_battery: output_source_priority_battery:
name: inverter0_output_source_priority_battery name: inverter0_output_source_priority_battery
output_source_priority_hybrid:
name: inverter0_output_source_priority_hybrid
input_voltage_range: input_voltage_range:
name: inverter0_input_voltage_range name: inverter0_input_voltage_range
pv_ok_condition_for_parallel: pv_ok_condition_for_parallel:

View file

@ -220,6 +220,8 @@ switch:
name: inverter0_output_source_priority_solar name: inverter0_output_source_priority_solar
output_source_priority_battery: output_source_priority_battery:
name: inverter0_output_source_priority_battery name: inverter0_output_source_priority_battery
output_source_priority_hybrid:
name: inverter0_output_source_priority_hybrid
input_voltage_range: input_voltage_range:
name: inverter0_input_voltage_range name: inverter0_input_voltage_range
pv_ok_condition_for_parallel: pv_ok_condition_for_parallel:

View file

@ -220,6 +220,8 @@ switch:
name: inverter0_output_source_priority_solar name: inverter0_output_source_priority_solar
output_source_priority_battery: output_source_priority_battery:
name: inverter0_output_source_priority_battery name: inverter0_output_source_priority_battery
output_source_priority_hybrid:
name: inverter0_output_source_priority_hybrid
input_voltage_range: input_voltage_range:
name: inverter0_input_voltage_range name: inverter0_input_voltage_range
pv_ok_condition_for_parallel: pv_ok_condition_for_parallel:

View file

@ -220,6 +220,8 @@ switch:
name: inverter0_output_source_priority_solar name: inverter0_output_source_priority_solar
output_source_priority_battery: output_source_priority_battery:
name: inverter0_output_source_priority_battery name: inverter0_output_source_priority_battery
output_source_priority_hybrid:
name: inverter0_output_source_priority_hybrid
input_voltage_range: input_voltage_range:
name: inverter0_input_voltage_range name: inverter0_input_voltage_range
pv_ok_condition_for_parallel: pv_ok_condition_for_parallel:

View file

@ -220,6 +220,8 @@ switch:
name: inverter0_output_source_priority_solar name: inverter0_output_source_priority_solar
output_source_priority_battery: output_source_priority_battery:
name: inverter0_output_source_priority_battery name: inverter0_output_source_priority_battery
output_source_priority_hybrid:
name: inverter0_output_source_priority_hybrid
input_voltage_range: input_voltage_range:
name: inverter0_input_voltage_range name: inverter0_input_voltage_range
pv_ok_condition_for_parallel: pv_ok_condition_for_parallel:

View file

@ -220,6 +220,8 @@ switch:
name: inverter0_output_source_priority_solar name: inverter0_output_source_priority_solar
output_source_priority_battery: output_source_priority_battery:
name: inverter0_output_source_priority_battery name: inverter0_output_source_priority_battery
output_source_priority_hybrid:
name: inverter0_output_source_priority_hybrid
input_voltage_range: input_voltage_range:
name: inverter0_input_voltage_range name: inverter0_input_voltage_range
pv_ok_condition_for_parallel: pv_ok_condition_for_parallel: