ESP-IDF support and generic target platforms (#2303)

* Socket refactor and SSL

* esp-idf temp

* Fixes

* Echo component and noise

* Add noise API transport support

* Updates

* ESP-IDF

* Complete

* Fixes

* Fixes

* Versions update

* New i2c APIs

* Complete i2c refactor

* SPI migration

* Revert ESP Preferences migration, too complex for now

* OTA support

* Remove echo again

* Remove ssl again

* GPIOFlags updates

* Rename esphal and ICACHE_RAM_ATTR

* Make ESP32 arduino compilable again

* Fix GPIO flags

* Complete pin registry refactor and fixes

* Fixes to make test1 compile

* Remove sdkconfig file

* Ignore sdkconfig file

* Fixes in reviewing

* Make test2 compile

* Make test4 compile

* Make test5 compile

* Run clang-format

* Fix lint errors

* Use esp-idf APIs instead of btStart

* Another round of fixes

* Start implementing ESP8266

* Make test3 compile

* Guard esp8266 code

* Lint

* Reformat

* Fixes

* Fixes v2

* more fixes

* ESP-IDF tidy target

* Convert ARDUINO_ARCH_ESPxx

* Update WiFiSignalSensor

* Update time ifdefs

* OTA needs millis from hal

* RestartSwitch needs delay from hal

* ESP-IDF Uart

* Fix OTA blank password

* Allow setting sdkconfig

* Fix idf partitions and allow setting sdkconfig from yaml

* Re-add read/write compat APIs and fix esp8266 uart

* Fix esp8266 store log strings in flash

* Fix ESP32 arduino preferences not initialized

* Update ifdefs

* Change how sdkconfig change is detected

* Add checks to ci-custom and fix them

* Run clang-format

* Add esp-idf clang-tidy target and fix errors

* Fixes from clang-tidy idf round 2

* Fixes from compiling tests with esp-idf

* Run clang-format

* Switch test5.yaml to esp-idf

* Implement ESP8266 Preferences

* Lint

* Re-do PIO package version selection a bit

* Fix arduinoespressif32 package version

* Fix unit tests

* Lint

* Lint fixes

* Fix readv/writev not defined

* Fix graphing component

* Re-add all old options from core/config.py

Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
This commit is contained in:
Otto Winter 2021-09-20 11:47:51 +02:00 committed by GitHub
parent 1e8e471dec
commit ac0d921413
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
583 changed files with 9008 additions and 5420 deletions

View File

@ -46,7 +46,7 @@ jobs:
name: Run script/clang-format
- id: clang-tidy
name: Run script/clang-tidy for ESP8266
options: --environment esp8266-tidy --grep ARDUINO_ARCH_ESP8266
options: --environment esp8266-tidy --grep USE_ESP8266
pio_cache_key: tidyesp8266
- id: clang-tidy
name: Run script/clang-tidy for ESP32 1/4
@ -64,6 +64,10 @@ jobs:
name: Run script/clang-tidy for ESP32 4/4
options: --environment esp32-tidy --split-num 4 --split-at 4
pio_cache_key: tidyesp32
- id: clang-tidy
name: Run script/clang-tidy for ESP32 esp-idf
options: --environment esp32-idf-tidy --grep USE_ESP_IDF
pio_cache_key: tidyesp32-idf
steps:
- uses: actions/checkout@v2

2
.gitignore vendored
View File

@ -124,3 +124,5 @@ tests/.esphome/
/.temp-clang-tidy.cpp
/.temp/
.pio/
sdkconfig.*

View File

@ -44,9 +44,11 @@ esphome/components/dfplayer/* @glmnet
esphome/components/dht/* @OttoWinter
esphome/components/ds1307/* @badbadc0ffee
esphome/components/dsmr/* @glmnet @zuidwijk
esphome/components/esp32/* @esphome/core
esphome/components/esp32_ble/* @jesserockz
esphome/components/esp32_ble_server/* @jesserockz
esphome/components/esp32_improv/* @jesserockz
esphome/components/esp8266/* @esphome/core
esphome/components/exposure_notifications/* @OttoWinter
esphome/components/ezo/* @ssieb
esphome/components/fastled_base/* @OttoWinter
@ -81,6 +83,7 @@ esphome/components/mcp23x17_base/* @jesserockz
esphome/components/mcp23xxx_base/* @jesserockz
esphome/components/mcp2515/* @danielschramm @mvturnho
esphome/components/mcp9808/* @k7hpn
esphome/components/mdns/* @esphome/core
esphome/components/midea/* @dudanov
esphome/components/mitsubishi/* @RubyBailey
esphome/components/network/* @esphome/core

View File

@ -245,7 +245,7 @@ def upload_program(config, args, host):
ota_conf = config[CONF_OTA]
remote_port = ota_conf[CONF_PORT]
password = ota_conf[CONF_PASSWORD]
password = ota_conf.get(CONF_PASSWORD, "")
return espota2.run_ota(host, remote_port, password, CORE.firmware_bin)

View File

@ -30,6 +30,7 @@ from esphome.cpp_generator import ( # noqa
add_library,
add_build_flag,
add_define,
add_platformio_option,
get_variable,
get_variable_with_full_id,
process_lambda,
@ -78,4 +79,6 @@ from esphome.cpp_types import ( # noqa
JsonObjectConstRef,
Controller,
GPIOPin,
InternalGPIOPin,
gpio_Flags,
)

View File

@ -1,7 +1,7 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/esphal.h"
#include "esphome/core/hal.h"
#include "esphome/components/stepper/stepper.h"
namespace esphome {

View File

@ -1,10 +1,16 @@
#ifdef USE_ARDUINO
#include "ac_dimmer.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include <cmath>
#ifdef ARDUINO_ARCH_ESP8266
#ifdef USE_ESP8266
#include <core_esp8266_waveform.h>
#endif
#ifdef USE_ESP32_FRAMEWORK_ARDUINO
#include <esp32-hal-timer.h>
#endif
namespace esphome {
namespace ac_dimmer {
@ -25,7 +31,7 @@ static const uint32_t GATE_ENABLE_TIME = 50;
/// Function called from timer interrupt
/// Input is current time in microseconds (micros())
/// Returns when next "event" is expected in µs, or 0 if no such event known.
uint32_t ICACHE_RAM_ATTR HOT AcDimmerDataStore::timer_intr(uint32_t now) {
uint32_t IRAM_ATTR HOT AcDimmerDataStore::timer_intr(uint32_t now) {
// If no ZC signal received yet.
if (this->crossed_zero_at == 0)
return 0;
@ -37,13 +43,13 @@ uint32_t ICACHE_RAM_ATTR HOT AcDimmerDataStore::timer_intr(uint32_t now) {
if (this->enable_time_us != 0 && time_since_zc >= this->enable_time_us) {
this->enable_time_us = 0;
this->gate_pin->digital_write(true);
this->gate_pin.digital_write(true);
// Prevent too short pulses
this->disable_time_us = max(this->disable_time_us, time_since_zc + GATE_ENABLE_TIME);
this->disable_time_us = std::max(this->disable_time_us, time_since_zc + GATE_ENABLE_TIME);
}
if (this->disable_time_us != 0 && time_since_zc >= this->disable_time_us) {
this->disable_time_us = 0;
this->gate_pin->digital_write(false);
this->gate_pin.digital_write(false);
}
if (time_since_zc < this->enable_time_us)
@ -63,7 +69,7 @@ uint32_t ICACHE_RAM_ATTR HOT AcDimmerDataStore::timer_intr(uint32_t now) {
}
/// Run timer interrupt code and return in how many µs the next event is expected
uint32_t ICACHE_RAM_ATTR HOT timer_interrupt() {
uint32_t IRAM_ATTR HOT timer_interrupt() {
// run at least with 1kHz
uint32_t min_dt_us = 1000;
uint32_t now = micros();
@ -80,7 +86,7 @@ uint32_t ICACHE_RAM_ATTR HOT timer_interrupt() {
}
/// GPIO interrupt routine, called when ZC pin triggers
void ICACHE_RAM_ATTR HOT AcDimmerDataStore::gpio_intr() {
void IRAM_ATTR HOT AcDimmerDataStore::gpio_intr() {
uint32_t prev_crossed = this->crossed_zero_at;
// 50Hz mains frequency should give a half cycle of 10ms a 60Hz will give 8.33ms
@ -97,7 +103,7 @@ void ICACHE_RAM_ATTR HOT AcDimmerDataStore::gpio_intr() {
if (this->value == 65535) {
// fully on, enable output immediately
this->gate_pin->digital_write(true);
this->gate_pin.digital_write(true);
} else if (this->init_cycle) {
// send a full cycle
this->init_cycle = false;
@ -105,29 +111,29 @@ void ICACHE_RAM_ATTR HOT AcDimmerDataStore::gpio_intr() {
this->disable_time_us = cycle_time_us;
} else if (this->value == 0) {
// fully off, disable output immediately
this->gate_pin->digital_write(false);
this->gate_pin.digital_write(false);
} else {
if (this->method == DIM_METHOD_TRAILING) {
this->enable_time_us = 1; // cannot be 0
this->disable_time_us = max((uint32_t) 10, this->value * this->cycle_time_us / 65535);
this->disable_time_us = std::max((uint32_t) 10, this->value * this->cycle_time_us / 65535);
} else {
// calculate time until enable in µs: (1.0-value)*cycle_time, but with integer arithmetic
// also take into account min_power
auto min_us = this->cycle_time_us * this->min_power / 1000;
this->enable_time_us = max((uint32_t) 1, ((65535 - this->value) * (this->cycle_time_us - min_us)) / 65535);
this->enable_time_us = std::max((uint32_t) 1, ((65535 - this->value) * (this->cycle_time_us - min_us)) / 65535);
if (this->method == DIM_METHOD_LEADING_PULSE) {
// Minimum pulse time should be enough for the triac to trigger when it is close to the ZC zone
// this is for brightness near 99%
this->disable_time_us = max(this->enable_time_us + GATE_ENABLE_TIME, (uint32_t) cycle_time_us / 10);
this->disable_time_us = std::max(this->enable_time_us + GATE_ENABLE_TIME, (uint32_t) cycle_time_us / 10);
} else {
this->gate_pin->digital_write(false);
this->gate_pin.digital_write(false);
this->disable_time_us = this->cycle_time_us;
}
}
}
}
void ICACHE_RAM_ATTR HOT AcDimmerDataStore::s_gpio_intr(AcDimmerDataStore *store) {
void IRAM_ATTR HOT AcDimmerDataStore::s_gpio_intr(AcDimmerDataStore *store) {
// Attaching pin interrupts on the same pin will override the previous interrupt
// However, the user expects that multiple dimmers sharing the same ZC pin will work.
// We solve this in a bit of a hacky way: On each pin interrupt, we check all dimmers
@ -141,11 +147,11 @@ void ICACHE_RAM_ATTR HOT AcDimmerDataStore::s_gpio_intr(AcDimmerDataStore *store
}
}
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
// ESP32 implementation, uses basically the same code but needs to wrap
// timer_interrupt() function to auto-reschedule
static hw_timer_t *dimmer_timer = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
void ICACHE_RAM_ATTR HOT AcDimmerDataStore::s_timer_intr() { timer_interrupt(); }
void IRAM_ATTR HOT AcDimmerDataStore::s_timer_intr() { timer_interrupt(); }
#endif
void AcDimmer::setup() {
@ -174,15 +180,16 @@ void AcDimmer::setup() {
if (setup_zero_cross_pin) {
this->zero_cross_pin_->setup();
this->store_.zero_cross_pin = this->zero_cross_pin_->to_isr();
this->zero_cross_pin_->attach_interrupt(&AcDimmerDataStore::s_gpio_intr, &this->store_, FALLING);
this->zero_cross_pin_->attach_interrupt(&AcDimmerDataStore::s_gpio_intr, &this->store_,
gpio::INTERRUPT_FALLING_EDGE);
}
#ifdef ARDUINO_ARCH_ESP8266
#ifdef USE_ESP8266
// Uses ESP8266 waveform (soft PWM) class
// PWM and AcDimmer can even run at the same time this way
setTimer1Callback(&timer_interrupt);
#endif
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
// 80 Divider -> 1 count=1µs
dimmer_timer = timerBegin(0, 80, true);
timerAttachInterrupt(dimmer_timer, &AcDimmerDataStore::s_timer_intr, true);
@ -218,3 +225,5 @@ void AcDimmer::dump_config() {
} // namespace ac_dimmer
} // namespace esphome
#endif // USE_ARDUINO

View File

@ -1,7 +1,9 @@
#pragma once
#ifdef USE_ARDUINO
#include "esphome/core/component.h"
#include "esphome/core/esphal.h"
#include "esphome/core/hal.h"
#include "esphome/components/output/float_output.h"
namespace esphome {
@ -11,11 +13,11 @@ enum DimMethod { DIM_METHOD_LEADING_PULSE = 0, DIM_METHOD_LEADING, DIM_METHOD_TR
struct AcDimmerDataStore {
/// Zero-cross pin
ISRInternalGPIOPin *zero_cross_pin;
ISRInternalGPIOPin zero_cross_pin;
/// Zero-cross pin number - used to share ZC pin across multiple dimmers
uint8_t zero_cross_pin_number;
/// Output pin to write to
ISRInternalGPIOPin *gate_pin;
ISRInternalGPIOPin gate_pin;
/// Value of the dimmer - 0 to 65535.
uint16_t value;
/// Minimum power for activation
@ -37,7 +39,7 @@ struct AcDimmerDataStore {
void gpio_intr();
static void s_gpio_intr(AcDimmerDataStore *store);
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
static void s_timer_intr();
#endif
};
@ -47,16 +49,16 @@ class AcDimmer : public output::FloatOutput, public Component {
void setup() override;
void dump_config() override;
void set_gate_pin(GPIOPin *gate_pin) { gate_pin_ = gate_pin; }
void set_zero_cross_pin(GPIOPin *zero_cross_pin) { zero_cross_pin_ = zero_cross_pin; }
void set_gate_pin(InternalGPIOPin *gate_pin) { gate_pin_ = gate_pin; }
void set_zero_cross_pin(InternalGPIOPin *zero_cross_pin) { zero_cross_pin_ = zero_cross_pin; }
void set_init_with_half_cycle(bool init_with_half_cycle) { init_with_half_cycle_ = init_with_half_cycle; }
void set_method(DimMethod method) { method_ = method; }
protected:
void write_state(float state) override;
GPIOPin *gate_pin_;
GPIOPin *zero_cross_pin_;
InternalGPIOPin *gate_pin_;
InternalGPIOPin *zero_cross_pin_;
AcDimmerDataStore store_;
bool init_with_half_cycle_;
DimMethod method_;
@ -64,3 +66,5 @@ class AcDimmer : public output::FloatOutput, public Component {
} // namespace ac_dimmer
} // namespace esphome
#endif // USE_ARDUINO

View File

@ -19,17 +19,20 @@ DIM_METHODS = {
CONF_GATE_PIN = "gate_pin"
CONF_ZERO_CROSS_PIN = "zero_cross_pin"
CONF_INIT_WITH_HALF_CYCLE = "init_with_half_cycle"
CONFIG_SCHEMA = output.FLOAT_OUTPUT_SCHEMA.extend(
{
cv.Required(CONF_ID): cv.declare_id(AcDimmer),
cv.Required(CONF_GATE_PIN): pins.internal_gpio_output_pin_schema,
cv.Required(CONF_ZERO_CROSS_PIN): pins.internal_gpio_input_pin_schema,
cv.Optional(CONF_INIT_WITH_HALF_CYCLE, default=True): cv.boolean,
cv.Optional(CONF_METHOD, default="leading pulse"): cv.enum(
DIM_METHODS, upper=True, space="_"
),
}
).extend(cv.COMPONENT_SCHEMA)
CONFIG_SCHEMA = cv.All(
output.FLOAT_OUTPUT_SCHEMA.extend(
{
cv.Required(CONF_ID): cv.declare_id(AcDimmer),
cv.Required(CONF_GATE_PIN): pins.internal_gpio_output_pin_schema,
cv.Required(CONF_ZERO_CROSS_PIN): pins.internal_gpio_input_pin_schema,
cv.Optional(CONF_INIT_WITH_HALF_CYCLE, default=True): cv.boolean,
cv.Optional(CONF_METHOD, default="leading pulse"): cv.enum(
DIM_METHODS, upper=True, space="_"
),
}
).extend(cv.COMPONENT_SCHEMA),
cv.only_with_arduino,
)
async def to_code(config):

View File

@ -2,6 +2,7 @@
#include "esphome/core/log.h"
#ifdef USE_ADC_SENSOR_VCC
#include <Esp.h>
ADC_MODE(ADC_VCC)
#endif
@ -10,7 +11,7 @@ namespace adc {
static const char *const TAG = "adc";
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
void ADCSensor::set_attenuation(adc_atten_t attenuation) { this->attenuation_ = attenuation; }
inline adc1_channel_t gpio_to_adc1(uint8_t pin) {
@ -57,28 +58,28 @@ inline adc1_channel_t gpio_to_adc1(uint8_t pin) {
void ADCSensor::setup() {
ESP_LOGCONFIG(TAG, "Setting up ADC '%s'...", this->get_name().c_str());
#ifndef USE_ADC_SENSOR_VCC
GPIOPin(this->pin_, INPUT).setup();
pin_->setup();
#endif
#ifdef ARDUINO_ARCH_ESP32
adc1_config_channel_atten(gpio_to_adc1(pin_), attenuation_);
#ifdef USE_ESP32
adc1_config_channel_atten(gpio_to_adc1(pin_->get_pin()), attenuation_);
adc1_config_width(ADC_WIDTH_BIT_12);
#if !CONFIG_IDF_TARGET_ESP32C3 && !CONFIG_IDF_TARGET_ESP32H2
adc_gpio_init(ADC_UNIT_1, (adc_channel_t) gpio_to_adc1(pin_));
adc_gpio_init(ADC_UNIT_1, (adc_channel_t) gpio_to_adc1(pin_->get_pin()));
#endif
#endif
}
void ADCSensor::dump_config() {
LOG_SENSOR("", "ADC Sensor", this);
#ifdef ARDUINO_ARCH_ESP8266
#ifdef USE_ESP8266
#ifdef USE_ADC_SENSOR_VCC
ESP_LOGCONFIG(TAG, " Pin: VCC");
#else
ESP_LOGCONFIG(TAG, " Pin: %u", this->pin_);
LOG_PIN(" Pin: ", pin_);
#endif
#endif
#ifdef ARDUINO_ARCH_ESP32
ESP_LOGCONFIG(TAG, " Pin: %u", this->pin_);
#ifdef USE_ESP32
LOG_PIN(" Pin: ", pin_);
switch (this->attenuation_) {
case ADC_ATTEN_DB_0:
ESP_LOGCONFIG(TAG, " Attenuation: 0db (max 1.1V)");
@ -105,8 +106,8 @@ void ADCSensor::update() {
this->publish_state(value_v);
}
float ADCSensor::sample() {
#ifdef ARDUINO_ARCH_ESP32
int raw = adc1_get_raw(gpio_to_adc1(pin_));
#ifdef USE_ESP32
int raw = adc1_get_raw(gpio_to_adc1(pin_->get_pin()));
float value_v = raw / 4095.0f;
#if CONFIG_IDF_TARGET_ESP32
switch (this->attenuation_) {
@ -146,15 +147,15 @@ float ADCSensor::sample() {
return value_v;
#endif
#ifdef ARDUINO_ARCH_ESP8266
#ifdef USE_ESP8266
#ifdef USE_ADC_SENSOR_VCC
return ESP.getVcc() / 1024.0f; // NOLINT(readability-static-accessed-through-instance)
#else
return analogRead(this->pin_) / 1024.0f; // NOLINT
return analogRead(this->pin_->get_pin()) / 1024.0f; // NOLINT
#endif
#endif
}
#ifdef ARDUINO_ARCH_ESP8266
#ifdef USE_ESP8266
std::string ADCSensor::unique_id() { return get_mac_address() + "-adc"; }
#endif

View File

@ -1,12 +1,12 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/esphal.h"
#include "esphome/core/hal.h"
#include "esphome/core/defines.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/voltage_sampler/voltage_sampler.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
#include "driver/adc.h"
#endif
@ -15,7 +15,7 @@ namespace adc {
class ADCSensor : public sensor::Sensor, public PollingComponent, public voltage_sampler::VoltageSampler {
public:
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
/// Set the attenuation for this pin. Only available on the ESP32.
void set_attenuation(adc_atten_t attenuation);
#endif
@ -27,17 +27,17 @@ class ADCSensor : public sensor::Sensor, public PollingComponent, public voltage
void dump_config() override;
/// `HARDWARE_LATE` setup priority.
float get_setup_priority() const override;
void set_pin(uint8_t pin) { this->pin_ = pin; }
void set_pin(InternalGPIOPin *pin) { this->pin_ = pin; }
float sample() override;
#ifdef ARDUINO_ARCH_ESP8266
#ifdef USE_ESP8266
std::string unique_id() override;
#endif
protected:
uint8_t pin_;
InternalGPIOPin *pin_;
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
adc_atten_t attenuation_{ADC_ATTEN_DB_0};
#endif
};

View File

@ -5,11 +5,13 @@ from esphome.components import sensor, voltage_sampler
from esphome.const import (
CONF_ATTENUATION,
CONF_ID,
CONF_INPUT,
CONF_PIN,
DEVICE_CLASS_VOLTAGE,
STATE_CLASS_MEASUREMENT,
UNIT_VOLT,
)
from esphome.core import CORE
AUTO_LOAD = ["voltage_sampler"]
@ -23,10 +25,34 @@ ATTENUATION_MODES = {
def validate_adc_pin(value):
vcc = str(value).upper()
if vcc == "VCC":
return cv.only_on_esp8266(vcc)
return pins.analog_pin(value)
if str(value).upper() == "VCC":
return cv.only_on_esp8266("VCC")
if CORE.is_esp32:
from esphome.components.esp32 import is_esp32c3
value = pins.internal_gpio_input_pin_number(value)
if is_esp32c3():
if not (0 <= value <= 4): # ADC1
raise cv.Invalid("ESP32-C3: Only pins 0 though 4 support ADC.")
if not (32 <= value <= 39): # ADC1
raise cv.Invalid("ESP32: Only pins 32 though 39 support ADC.")
elif CORE.is_esp8266:
from esphome.components.esp8266.gpio import CONF_ANALOG
value = pins.internal_gpio_pin_number({CONF_ANALOG: True, CONF_INPUT: True})(
value
)
if value != 17: # A0
raise cv.Invalid("ESP8266: Only pin A0 (GPIO17) supports ADC.")
return pins.gpio_pin_schema(
{CONF_ANALOG: True, CONF_INPUT: True}, internal=True
)(value)
else:
raise NotImplementedError
return pins.internal_gpio_input_pin_schema(value)
adc_ns = cg.esphome_ns.namespace("adc")
@ -62,7 +88,8 @@ async def to_code(config):
if config[CONF_PIN] == "VCC":
cg.add_define("USE_ADC_SENSOR_VCC")
else:
cg.add(var.set_pin(config[CONF_PIN]))
pin = await cg.gpio_pin_expression(config[CONF_PIN])
cg.add(var.set_pin(pin))
if CONF_ATTENUATION in config:
cg.add(var.set_attenuation(config[CONF_ATTENUATION]))

View File

@ -8,9 +8,7 @@ static const char *const TAG = "ade7953";
void ADE7953::dump_config() {
ESP_LOGCONFIG(TAG, "ADE7953:");
if (this->has_irq_) {
ESP_LOGCONFIG(TAG, " IRQ Pin: GPIO%u", this->irq_pin_number_);
}
LOG_PIN(" IRQ Pin: ", irq_pin_);
LOG_I2C_DEVICE(this);
LOG_UPDATE_INTERVAL(this);
LOG_SENSOR(" ", "Voltage Sensor", this->voltage_sensor_);
@ -20,27 +18,28 @@ void ADE7953::dump_config() {
LOG_SENSOR(" ", "Active Power B Sensor", this->active_power_b_sensor_);
}
#define ADE_PUBLISH_(name, factor) \
if ((name) && this->name##_sensor_) { \
float value = *(name) / (factor); \
#define ADE_PUBLISH_(name, val, factor) \
if (err == i2c::ERROR_OK && this->name##_sensor_) { \
float value = (val) / (factor); \
this->name##_sensor_->publish_state(value); \
}
#define ADE_PUBLISH(name, factor) ADE_PUBLISH_(name, factor)
#define ADE_PUBLISH(name, val, factor) ADE_PUBLISH_(name, val, factor)
void ADE7953::update() {
if (!this->is_setup_)
return;
auto active_power_a = this->ade_read_<int32_t>(0x0312);
ADE_PUBLISH(active_power_a, 154.0f);
auto active_power_b = this->ade_read_<int32_t>(0x0313);
ADE_PUBLISH(active_power_b, 154.0f);
auto current_a = this->ade_read_<uint32_t>(0x031A);
ADE_PUBLISH(current_a, 100000.0f);
auto current_b = this->ade_read_<uint32_t>(0x031B);
ADE_PUBLISH(current_b, 100000.0f);
auto voltage = this->ade_read_<uint32_t>(0x031C);
ADE_PUBLISH(voltage, 26000.0f);
uint32_t val;
i2c::ErrorCode err = ade_read_32_(0x0312, &val);
ADE_PUBLISH(active_power_a, (int32_t) val, 154.0f);
err = ade_read_32_(0x0313, &val);
ADE_PUBLISH(active_power_b, (int32_t) val, 154.0f);
err = ade_read_32_(0x031A, &val);
ADE_PUBLISH(current_a, (uint32_t) val, 100000.0f);
err = ade_read_32_(0x031B, &val);
ADE_PUBLISH(current_b, (uint32_t) val, 100000.0f);
err = ade_read_32_(0x031C, &val);
ADE_PUBLISH(voltage, (uint32_t) val, 26000.0f);
// auto apparent_power_a = this->ade_read_<int32_t>(0x0310);
// auto apparent_power_b = this->ade_read_<int32_t>(0x0311);

View File

@ -1,7 +1,7 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/esphal.h"
#include "esphome/core/hal.h"
#include "esphome/components/i2c/i2c.h"
#include "esphome/components/sensor/sensor.h"
@ -10,10 +10,7 @@ namespace ade7953 {
class ADE7953 : public i2c::I2CDevice, public PollingComponent {
public:
void set_irq_pin(uint8_t irq_pin) {
has_irq_ = true;
irq_pin_number_ = irq_pin;
}
void set_irq_pin(InternalGPIOPin *irq_pin) { irq_pin_ = irq_pin; }
void set_voltage_sensor(sensor::Sensor *voltage_sensor) { voltage_sensor_ = voltage_sensor; }
void set_current_a_sensor(sensor::Sensor *current_a_sensor) { current_a_sensor_ = current_a_sensor; }
void set_current_b_sensor(sensor::Sensor *current_b_sensor) { current_b_sensor_ = current_b_sensor; }
@ -25,15 +22,13 @@ class ADE7953 : public i2c::I2CDevice, public PollingComponent {
}
void setup() override {
if (this->has_irq_) {
auto pin = GPIOPin(this->irq_pin_number_, INPUT);
this->irq_pin_ = &pin;
if (this->irq_pin_ != nullptr) {
this->irq_pin_->setup();
}
this->set_timeout(100, [this]() {
this->ade_write_<uint8_t>(0x0010, 0x04);
this->ade_write_<uint8_t>(0x00FE, 0xAD);
this->ade_write_<uint16_t>(0x0120, 0x0030);
this->ade_write_8_(0x0010, 0x04);
this->ade_write_8_(0x00FE, 0xAD);
this->ade_write_16_(0x0120, 0x0030);
this->is_setup_ = true;
});
}
@ -43,31 +38,51 @@ class ADE7953 : public i2c::I2CDevice, public PollingComponent {
void update() override;
protected:
template<typename T> bool ade_write_(uint16_t reg, T value) {
i2c::ErrorCode ade_write_8_(uint16_t reg, uint8_t value) {
std::vector<uint8_t> data;
data.push_back(reg >> 8);
data.push_back(reg >> 0);
for (int i = sizeof(T) - 1; i >= 0; i--)
data.push_back(value >> (i * 8));
return this->write_bytes_raw(data);
data.push_back(value);
return write(data.data(), data.size());
}
template<typename T> optional<T> ade_read_(uint16_t reg) {
uint8_t hi = reg >> 8;
uint8_t lo = reg >> 0;
if (!this->write_bytes_raw({hi, lo}))
return {};
auto ret = this->read_bytes_raw<sizeof(T)>();
if (!ret.has_value())
return {};
T result = 0;
for (int i = 0, j = sizeof(T) - 1; i < sizeof(T); i++, j--)
result |= T((*ret)[i]) << (j * 8);
return result;
i2c::ErrorCode ade_write_16_(uint16_t reg, uint16_t value) {
std::vector<uint8_t> data;
data.push_back(reg >> 8);
data.push_back(reg >> 0);
data.push_back(value >> 8);
data.push_back(value >> 0);
return write(data.data(), data.size());
}
i2c::ErrorCode ade_write_32_(uint16_t reg, uint32_t value) {
std::vector<uint8_t> data;
data.push_back(reg >> 8);
data.push_back(reg >> 0);
data.push_back(value >> 24);
data.push_back(value >> 16);
data.push_back(value >> 8);
data.push_back(value >> 0);
return write(data.data(), data.size());
}
i2c::ErrorCode ade_read_32_(uint16_t reg, uint32_t *value) {
uint8_t reg_data[2];
reg_data[0] = reg >> 8;
reg_data[1] = reg >> 0;
i2c::ErrorCode err = write(reg_data, 2);
if (err != i2c::ERROR_OK)
return err;
uint8_t recv[4];
err = read(recv, 4);
if (err != i2c::ERROR_OK)
return err;
*value = 0;
*value |= ((uint32_t) recv[0]) << 24;
*value |= ((uint32_t) recv[1]) << 24;
*value |= ((uint32_t) recv[2]) << 24;
*value |= ((uint32_t) recv[3]) << 24;
return i2c::ERROR_OK;
}
bool has_irq_ = false;
uint8_t irq_pin_number_;
GPIOPin *irq_pin_{nullptr};
InternalGPIOPin *irq_pin_ = nullptr;
bool is_setup_{false};
sensor::Sensor *voltage_sensor_{nullptr};
sensor::Sensor *current_a_sensor_{nullptr};

View File

@ -29,7 +29,7 @@ CONFIG_SCHEMA = (
cv.Schema(
{
cv.GenerateID(): cv.declare_id(ADE7953),
cv.Optional(CONF_IRQ_PIN): pins.input_pin,
cv.Optional(CONF_IRQ_PIN): pins.internal_gpio_input_pin_schema,
cv.Optional(CONF_VOLTAGE): sensor.sensor_schema(
unit_of_measurement=UNIT_VOLT,
accuracy_decimals=1,
@ -73,7 +73,8 @@ async def to_code(config):
await i2c.register_i2c_device(var, config)
if CONF_IRQ_PIN in config:
cg.add(var.set_irq_pin(config[CONF_IRQ_PIN]))
irq_pin = await cg.gpio_pin_expression(config[CONF_IRQ_PIN])
cg.add(var.set_irq_pin(irq_pin))
for key in [
CONF_VOLTAGE,

View File

@ -1,5 +1,6 @@
#include "ads1115.h"
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
namespace esphome {
namespace ads1115 {
@ -159,7 +160,7 @@ float ADS1115Component::request_measurement(ADS1115Sensor *sensor) {
float ADS1115Sensor::sample() { return this->parent_->request_measurement(this); }
void ADS1115Sensor::update() {
float v = this->parent_->request_measurement(this);
if (!isnan(v)) {
if (!std::isnan(v)) {
ESP_LOGD(TAG, "'%s': Got Voltage=%fV", this->get_name().c_str(), v);
this->publish_state(v);
}

View File

@ -14,6 +14,7 @@
#include "aht10.h"
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
namespace esphome {
namespace aht10 {
@ -33,8 +34,19 @@ void AHT10Component::setup() {
this->mark_failed();
return;
}
uint8_t data;
if (!this->read_byte(0, &data, AHT10_DEFAULT_DELAY)) {
uint8_t data = 0;
if (this->write(&data, 1) != i2c::ERROR_OK) {
ESP_LOGD(TAG, "Communication with AHT10 failed!");
this->mark_failed();
return;
}
delay(AHT10_DEFAULT_DELAY);
if (this->read(&data, 1) != i2c::ERROR_OK) {
ESP_LOGD(TAG, "Communication with AHT10 failed!");
this->mark_failed();
return;
}
if (this->read(&data, 1) != i2c::ERROR_OK) {
ESP_LOGD(TAG, "Communication with AHT10 failed!");
this->mark_failed();
return;
@ -55,15 +67,26 @@ void AHT10Component::update() {
return;
}
uint8_t data[6];
uint8_t delay = AHT10_DEFAULT_DELAY;
uint8_t delay_ms = AHT10_DEFAULT_DELAY;
if (this->humidity_sensor_ != nullptr)
delay = AHT10_HUMIDITY_DELAY;
delay_ms = AHT10_HUMIDITY_DELAY;
bool success = false;
for (int i = 0; i < AHT10_ATTEMPTS; ++i) {
ESP_LOGVV(TAG, "Attempt %u at %6ld", i, millis());
ESP_LOGVV(TAG, "Attempt %d at %6u", i, millis());
delay_microseconds_accurate(4);
if (!this->read_bytes(0, data, 6, delay)) {
uint8_t reg = 0;
if (this->write(&reg, 1) != i2c::ERROR_OK) {
ESP_LOGD(TAG, "Communication with AHT10 failed, waiting...");
} else if ((data[0] & 0x80) == 0x80) { // Bit[7] = 0b1, device is busy
continue;
}
delay(delay_ms);
if (this->read(data, 6) != i2c::ERROR_OK) {
ESP_LOGD(TAG, "Communication with AHT10 failed, waiting...");
continue;
}
if ((data[0] & 0x80) == 0x80) { // Bit[7] = 0b1, device is busy
ESP_LOGD(TAG, "AHT10 is busy, waiting...");
} else if (data[1] == 0x0 && data[2] == 0x0 && (data[3] >> 4) == 0x0) {
// Unrealistic humidity (0x0)
@ -80,11 +103,12 @@ void AHT10Component::update() {
}
} else {
// data is valid, we can break the loop
ESP_LOGVV(TAG, "Answer at %6ld", millis());
ESP_LOGVV(TAG, "Answer at %6u", millis());
success = true;
break;
}
}
if ((data[0] & 0x80) == 0x80) {
if (!success || (data[0] & 0x80) == 0x80) {
ESP_LOGE(TAG, "Measurements reading timed-out!");
this->status_set_warning();
return;
@ -105,7 +129,7 @@ void AHT10Component::update() {
this->temperature_sensor_->publish_state(temperature);
}
if (this->humidity_sensor_ != nullptr) {
if (isnan(humidity))
if (std::isnan(humidity))
ESP_LOGW(TAG, "Invalid humidity! Sensor reported 0%% Hum");
this->humidity_sensor_->publish_state(humidity);
}

View File

@ -1,7 +1,7 @@
#include "airthings_listener.h"
#include "esphome/core/log.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace airthings_ble {

View File

@ -1,10 +1,9 @@
#pragma once
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
#include "esphome/core/component.h"
#include "esphome/components/esp32_ble_tracker/esp32_ble_tracker.h"
#include <BLEDevice.h>
namespace esphome {
namespace airthings_ble {

View File

@ -1,6 +1,6 @@
#include "airthings_wave_plus.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32_FRAMEWORK_ARDUINO
namespace esphome {
namespace airthings_wave_plus {
@ -141,4 +141,4 @@ void AirthingsWavePlus::setup() {}
} // namespace airthings_wave_plus
} // namespace esphome
#endif // ARDUINO_ARCH_ESP32
#endif // USE_ESP32_FRAMEWORK_ARDUINO

View File

@ -1,6 +1,6 @@
#pragma once
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32_FRAMEWORK_ARDUINO
#include <algorithm>
#include <iterator>
@ -72,4 +72,4 @@ class AirthingsWavePlus : public PollingComponent, public ble_client::BLEClientN
} // namespace airthings_wave_plus
} // namespace esphome
#endif // ARDUINO_ARCH_ESP32
#endif // USE_ESP32_FRAMEWORK_ARDUINO

View File

@ -34,7 +34,7 @@ AirthingsWavePlus = airthings_wave_plus_ns.class_(
)
CONFIG_SCHEMA = (
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
cv.GenerateID(): cv.declare_id(AirthingsWavePlus),
@ -83,7 +83,9 @@ CONFIG_SCHEMA = (
}
)
.extend(cv.polling_component_schema("5mins"))
.extend(ble_client.BLE_CLIENT_SCHEMA)
.extend(ble_client.BLE_CLIENT_SCHEMA),
# Until BLEUUID reference removed
cv.only_with_arduino,
)

View File

@ -5,6 +5,7 @@
#include "am2320.h"
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
namespace esphome {
namespace am2320 {
@ -77,7 +78,7 @@ bool AM2320Component::read_bytes_(uint8_t a_register, uint8_t *data, uint8_t len
if (conversion > 0)
delay(conversion);
return this->parent_->raw_receive(this->address_, data, len);
return this->read(data, len) == i2c::ERROR_OK;
}
bool AM2320Component::read_data_(uint8_t *data) {

View File

@ -1,7 +1,8 @@
#include "am43.h"
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace am43 {

View File

@ -6,7 +6,7 @@
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/am43/am43_base.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
#include <esp_gattc_api.h>

View File

@ -1,7 +1,7 @@
#include "am43_cover.h"
#include "esphome/core/log.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace am43 {

View File

@ -6,7 +6,7 @@
#include "esphome/components/cover/cover.h"
#include "esphome/components/am43/am43_base.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
#include <esp_gattc_api.h>

View File

@ -1,7 +1,7 @@
#include "anova.h"
#include "esphome/core/log.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace anova {

View File

@ -6,7 +6,7 @@
#include "esphome/components/climate/climate.h"
#include "anova_base.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
#include <esp_gattc_api.h>

View File

@ -1,5 +1,6 @@
#include "apds9960.h"
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
namespace esphome {
namespace apds9960 {

View File

@ -1,7 +1,8 @@
#include "api_connection.h"
#include "esphome/core/log.h"
#include "esphome/core/util.h"
#include "esphome/components/network/util.h"
#include "esphome/core/version.h"
#include "esphome/core/hal.h"
#include <cerrno>
#ifdef USE_DEEP_SLEEP
@ -48,7 +49,7 @@ void APIConnection::loop() {
if (this->remove_)
return;
if (!network_is_connected()) {
if (!network::is_connected()) {
// when network is disconnected force disconnect immediately
// don't wait for timeout
this->on_fatal_error();

View File

@ -3,6 +3,7 @@
#include "esphome/core/log.h"
#include "esphome/core/helpers.h"
#include "proto.h"
#include <cstring>
namespace esphome {
namespace api {

View File

@ -2,6 +2,7 @@
// See scripts/api_protobuf/api_protobuf.py
#include "api_pb2.h"
#include "esphome/core/log.h"
#include <cstdio>
namespace esphome {
namespace api {

View File

@ -5,6 +5,8 @@
#include "esphome/core/log.h"
#include "esphome/core/util.h"
#include "esphome/core/version.h"
#include "esphome/core/hal.h"
#include "esphome/components/network/util.h"
#include <cerrno>
#ifdef USE_LOGGER
@ -130,7 +132,7 @@ void APIServer::loop() {
}
void APIServer::dump_config() {
ESP_LOGCONFIG(TAG, "API Server:");
ESP_LOGCONFIG(TAG, " Address: %s:%u", network_get_address().c_str(), this->port_);
ESP_LOGCONFIG(TAG, " Address: %s:%u", network::get_use_address().c_str(), this->port_);
}
bool APIServer::uses_password() const { return !this->password_.empty(); }
bool APIServer::check_password(const std::string &password) const {

View File

@ -246,6 +246,7 @@ class ProtoWriteBuffer {
class ProtoMessage {
public:
virtual ~ProtoMessage() = default;
virtual void encode(ProtoWriteBuffer buffer) const = 0;
void decode(const uint8_t *buffer, size_t length);
#ifdef HAS_PROTO_MESSAGE_DUMP

View File

@ -1,7 +1,7 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/esphal.h"
#include "esphome/core/hal.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/binary_sensor/binary_sensor.h"

View File

@ -25,8 +25,12 @@ void I2CAS3935Component::write_register(uint8_t reg, uint8_t mask, uint8_t bits,
uint8_t I2CAS3935Component::read_register(uint8_t reg) {
uint8_t value;
if (!this->read_byte(reg, &value, 2)) {
ESP_LOGW(TAG, "Read failed!");
if (write(&reg, 1) != i2c::ERROR_OK) {
ESP_LOGW(TAG, "Writing register failed!");
return 0;
}
if (read(&value, 1) != i2c::ERROR_OK) {
ESP_LOGW(TAG, "Reading register failed!");
return 0;
}
return value;

View File

@ -1,9 +1,15 @@
# Dummy integration to allow relying on AsyncTCP
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.core import CORE, coroutine_with_priority
CODEOWNERS = ["@OttoWinter"]
CONFIG_SCHEMA = cv.All(
cv.Schema({}),
cv.only_with_arduino,
)
@coroutine_with_priority(200.0)
async def to_code(config):

View File

@ -1,7 +1,7 @@
#include "atc_mithermometer.h"
#include "esphome/core/log.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace atc_mithermometer {

View File

@ -4,7 +4,7 @@
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/esp32_ble_tracker/esp32_ble_tracker.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace atc_mithermometer {

View File

@ -1,7 +1,7 @@
#include "b_parasite.h"
#include "esphome/core/log.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace b_parasite {
@ -79,4 +79,4 @@ bool BParasite::parse_device(const esp32_ble_tracker::ESPBTDevice &device) {
} // namespace b_parasite
} // namespace esphome
#endif // ARDUINO_ARCH_ESP32
#endif // USE_ESP32

View File

@ -4,7 +4,7 @@
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/esp32_ble_tracker/esp32_ble_tracker.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace b_parasite {
@ -37,4 +37,4 @@ class BParasite : public Component, public esp32_ble_tracker::ESPBTDeviceListene
} // namespace b_parasite
} // namespace esphome
#endif // ARDUINO_ARCH_ESP32
#endif // USE_ESP32

View File

@ -69,7 +69,8 @@ void BangBangClimate::compute_state_() {
this->switch_to_action_(climate::CLIMATE_ACTION_OFF);
return;
}
if (isnan(this->current_temperature) || isnan(this->target_temperature_low) || isnan(this->target_temperature_high)) {
if (std::isnan(this->current_temperature) || std::isnan(this->target_temperature_low) ||
std::isnan(this->target_temperature_high)) {
// if any control parameters are nan, go to OFF action (not IDLE!)
this->switch_to_action_(climate::CLIMATE_ACTION_OFF);
return;

View File

@ -71,10 +71,11 @@ void BH1750Sensor::update() {
float BH1750Sensor::get_setup_priority() const { return setup_priority::DATA; }
void BH1750Sensor::read_data_() {
uint16_t raw_value;
if (!this->parent_->raw_receive_16(this->address_, &raw_value, 1)) {
if (!this->read(reinterpret_cast<uint8_t *>(&raw_value), 2)) {
this->status_set_warning();
return;
}
raw_value = i2c::i2ctohs(raw_value);
float lx = float(raw_value) / 1.2f;
lx *= 69.0f / this->measurement_duration_;

View File

@ -4,6 +4,7 @@
#include "esphome/core/component.h"
#include "esphome/core/automation.h"
#include "esphome/core/hal.h"
#include "esphome/components/binary_sensor/binary_sensor.h"
namespace esphome {

View File

@ -3,7 +3,7 @@
#include "esphome/core/automation.h"
#include "esphome/components/ble_client/ble_client.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace ble_client {

View File

@ -4,7 +4,7 @@
#include "esphome/components/esp32_ble_tracker/esp32_ble_tracker.h"
#include "ble_client.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace ble_client {

View File

@ -4,7 +4,7 @@
#include "esphome/core/helpers.h"
#include "esphome/components/esp32_ble_tracker/esp32_ble_tracker.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
#include <string>
#include <array>

View File

@ -3,7 +3,7 @@
#include "esphome/core/automation.h"
#include "esphome/components/ble_client/sensor/ble_sensor.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace ble_client {

View File

@ -4,7 +4,7 @@
#include "esphome/core/helpers.h"
#include "esphome/components/esp32_ble_tracker/esp32_ble_tracker.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace ble_client {

View File

@ -5,7 +5,7 @@
#include "esphome/components/esp32_ble_tracker/esp32_ble_tracker.h"
#include "esphome/components/sensor/sensor.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
#include <esp_gattc_api.h>
namespace esphome {

View File

@ -2,7 +2,7 @@
#include "esphome/core/log.h"
#include "esphome/core/application.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace ble_client {

View File

@ -5,7 +5,7 @@
#include "esphome/components/esp32_ble_tracker/esp32_ble_tracker.h"
#include "esphome/components/switch/switch.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
#include <esp_gattc_api.h>
namespace esphome {

View File

@ -1,7 +1,7 @@
#include "ble_presence_device.h"
#include "esphome/core/log.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace ble_presence {

View File

@ -4,7 +4,7 @@
#include "esphome/components/esp32_ble_tracker/esp32_ble_tracker.h"
#include "esphome/components/binary_sensor/binary_sensor.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace ble_presence {

View File

@ -1,7 +1,7 @@
#include "ble_rssi_sensor.h"
#include "esphome/core/log.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace ble_rssi {

View File

@ -4,7 +4,7 @@
#include "esphome/components/esp32_ble_tracker/esp32_ble_tracker.h"
#include "esphome/components/sensor/sensor.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace ble_rssi {

View File

@ -1,7 +1,7 @@
#include "ble_scanner.h"
#include "esphome/core/log.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace ble_scanner {

View File

@ -7,7 +7,7 @@
#include "esphome/components/esp32_ble_tracker/esp32_ble_tracker.h"
#include "esphome/components/text_sensor/text_sensor.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
namespace esphome {
namespace ble_scanner {

View File

@ -186,7 +186,7 @@ void BME280Component::update() {
this->set_timeout("data", uint32_t(ceilf(meas_time)), [this]() {
int32_t t_fine = 0;
float temperature = this->read_temperature_(&t_fine);
if (isnan(temperature)) {
if (std::isnan(temperature)) {
ESP_LOGW(TAG, "Invalid temperature, cannot read pressure & humidity values.");
this->status_set_warning();
return;

View File

@ -1,5 +1,6 @@
#include "bme680.h"
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
namespace esphome {
namespace bme680 {

View File

@ -381,7 +381,7 @@ void BME680BSECComponent::delay_ms(uint32_t period) {
void BME680BSECComponent::load_state_() {
uint32_t hash = fnv1_hash("bme680_bsec_state_" + to_string(this->address_));
this->bsec_state_ = global_preferences.make_preference<uint8_t[BSEC_MAX_STATE_BLOB_SIZE]>(hash, true);
this->bsec_state_ = global_preferences->make_preference<uint8_t[BSEC_MAX_STATE_BLOB_SIZE]>(hash, true);
uint8_t state[BSEC_MAX_STATE_BLOB_SIZE];
if (this->bsec_state_.load(&state)) {

View File

@ -139,7 +139,7 @@ void BMP280Component::update() {
this->set_timeout("data", uint32_t(ceilf(meas_time)), [this]() {
int32_t t_fine = 0;
float temperature = this->read_temperature_(&t_fine);
if (isnan(temperature)) {
if (std::isnan(temperature)) {
ESP_LOGW(TAG, "Invalid temperature, cannot read pressure values.");
this->status_set_warning();
return;

View File

@ -12,14 +12,17 @@ CODEOWNERS = ["@OttoWinter"]
captive_portal_ns = cg.esphome_ns.namespace("captive_portal")
CaptivePortal = captive_portal_ns.class_("CaptivePortal", cg.Component)
CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(): cv.declare_id(CaptivePortal),
cv.GenerateID(CONF_WEB_SERVER_BASE_ID): cv.use_id(
web_server_base.WebServerBase
),
}
).extend(cv.COMPONENT_SCHEMA)
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
cv.GenerateID(): cv.declare_id(CaptivePortal),
cv.GenerateID(CONF_WEB_SERVER_BASE_ID): cv.use_id(
web_server_base.WebServerBase
),
}
).extend(cv.COMPONENT_SCHEMA),
cv.only_with_arduino,
)
@coroutine_with_priority(64.0)

View File

@ -1,3 +1,5 @@
#ifdef USE_ARDUINO
#include "captive_portal.h"
#include "esphome/core/log.h"
#include "esphome/core/application.h"
@ -78,14 +80,14 @@ void CaptivePortal::start() {
this->dns_server_ = make_unique<DNSServer>();
this->dns_server_->setErrorReplyCode(DNSReplyCode::NoError);
IPAddress ip = wifi::global_wifi_component->wifi_soft_ap_ip();
this->dns_server_->start(53, "*", ip);
network::IPAddress ip = wifi::global_wifi_component->wifi_soft_ap_ip();
this->dns_server_->start(53, "*", (uint32_t) ip);
this->base_->get_server()->onNotFound([this](AsyncWebServerRequest *req) {
bool not_found = false;
if (!this->active_) {
not_found = true;
} else if (req->host() == wifi::global_wifi_component->wifi_soft_ap_ip().toString()) {
} else if (req->host().c_str() == wifi::global_wifi_component->wifi_soft_ap_ip().str()) {
not_found = true;
}
@ -94,8 +96,8 @@ void CaptivePortal::start() {
return;
}
auto url = "http://" + wifi::global_wifi_component->wifi_soft_ap_ip().toString();
req->redirect(url);
auto url = "http://" + wifi::global_wifi_component->wifi_soft_ap_ip().str();
req->redirect(url.c_str());
});
this->initialized_ = true;
@ -151,3 +153,5 @@ CaptivePortal *global_captive_portal = nullptr; // NOLINT(cppcoreguidelines-avo
} // namespace captive_portal
} // namespace esphome
#endif // USE_ARDUINO

View File

@ -1,5 +1,7 @@
#pragma once
#ifdef USE_ARDUINO
#include <memory>
#include <DNSServer.h>
#include "esphome/core/component.h"
@ -73,3 +75,5 @@ extern CaptivePortal *global_captive_portal; // NOLINT(cppcoreguidelines-avoid-
} // namespace captive_portal
} // namespace esphome
#endif // USE_ARDUINO

View File

@ -1,5 +1,6 @@
#include "ccs811.h"
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
namespace esphome {
namespace ccs811 {
@ -124,12 +125,12 @@ void CCS811Component::send_env_data_() {
float humidity = NAN;
if (this->humidity_ != nullptr)
humidity = this->humidity_->state;
if (isnan(humidity) || humidity < 0 || humidity > 100)
if (std::isnan(humidity) || humidity < 0 || humidity > 100)
humidity = 50;
float temperature = NAN;
if (this->temperature_ != nullptr)
temperature = this->temperature_->state;
if (isnan(temperature) || temperature < -25 || temperature > 50)
if (std::isnan(temperature) || temperature < -25 || temperature > 50)
temperature = 25;
// temperature has a 25° offset to allow negative temperatures
temperature += 25;

View File

@ -95,7 +95,7 @@ void ClimateCall::validate_() {
ESP_LOGW(TAG, " Cannot set target temperature for climate device "
"with two-point target temperature!");
this->target_temperature_.reset();
} else if (isnan(target)) {
} else if (std::isnan(target)) {
ESP_LOGW(TAG, " Target temperature must not be NAN!");
this->target_temperature_.reset();
}
@ -107,11 +107,11 @@ void ClimateCall::validate_() {
this->target_temperature_high_.reset();
}
}
if (this->target_temperature_low_.has_value() && isnan(*this->target_temperature_low_)) {
if (this->target_temperature_low_.has_value() && std::isnan(*this->target_temperature_low_)) {
ESP_LOGW(TAG, " Target temperature low must not be NAN!");
this->target_temperature_low_.reset();
}
if (this->target_temperature_high_.has_value() && isnan(*this->target_temperature_high_)) {
if (this->target_temperature_high_.has_value() && std::isnan(*this->target_temperature_high_)) {
ESP_LOGW(TAG, " Target temperature low must not be NAN!");
this->target_temperature_high_.reset();
}
@ -318,17 +318,23 @@ void Climate::add_on_state_callback(std::function<void()> &&callback) {
static const uint32_t RESTORE_STATE_VERSION = 0x848EA6ADUL;
optional<ClimateDeviceRestoreState> Climate::restore_state_() {
this->rtc_ =
global_preferences.make_preference<ClimateDeviceRestoreState>(this->get_object_id_hash() ^ RESTORE_STATE_VERSION);
this->rtc_ = global_preferences->make_preference<ClimateDeviceRestoreState>(this->get_object_id_hash() ^
RESTORE_STATE_VERSION);
ClimateDeviceRestoreState recovered{};
if (!this->rtc_.load(&recovered))
return {};
return recovered;
}
void Climate::save_state_() {
#if defined(USE_ESP_IDF) && !defined(CLANG_TIDY)
#pragma GCC diagnostic ignored "-Wclass-memaccess"
#endif
ClimateDeviceRestoreState state{};
// initialize as zero to prevent random data on stack triggering erase
memset(&state, 0, sizeof(ClimateDeviceRestoreState));
#if USE_ESP_IDF && !defined(CLANG_TIDY)
#pragma GCC diagnostic pop
#endif
state.mode = this->mode;
auto traits = this->get_traits();

View File

@ -52,7 +52,7 @@ void ClimateIR::setup() {
this->swing_mode = climate::CLIMATE_SWING_OFF;
}
// Never send nan to HA
if (isnan(this->target_temperature))
if (std::isnan(this->target_temperature))
this->target_temperature = 24;
}

View File

@ -180,7 +180,7 @@ void Cover::publish_state(bool save) {
}
}
optional<CoverRestoreState> Cover::restore_state_() {
this->rtc_ = global_preferences.make_preference<CoverRestoreState>(this->get_object_id_hash());
this->rtc_ = global_preferences->make_preference<CoverRestoreState>(this->get_object_id_hash());
CoverRestoreState recovered{};
if (!this->rtc_.load(&recovered))
return {};

View File

@ -52,7 +52,7 @@ void CTClampSensor::loop() {
// Perform a single sample
float value = this->source_->sample();
if (isnan(value))
if (std::isnan(value))
return;
this->sample_sum_ += value;

View File

@ -1,7 +1,7 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/esphal.h"
#include "esphome/core/hal.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/voltage_sampler/voltage_sampler.h"

View File

@ -161,7 +161,7 @@ const std::string &DallasTemperatureSensor::get_address_name() {
return this->address_name_;
}
bool ICACHE_RAM_ATTR DallasTemperatureSensor::read_scratch_pad() {
bool IRAM_ATTR DallasTemperatureSensor::read_scratch_pad() {
ESPOneWire *wire = this->parent_->one_wire_;
if (!wire->reset()) {
return false;

View File

@ -12,11 +12,11 @@ const int ONE_WIRE_ROM_SEARCH = 0xF0;
ESPOneWire::ESPOneWire(GPIOPin *pin) : pin_(pin) {}
bool HOT ICACHE_RAM_ATTR ESPOneWire::reset() {
bool HOT IRAM_ATTR ESPOneWire::reset() {
uint8_t retries = 125;
// Wait for communication to clear
this->pin_->pin_mode(INPUT_PULLUP);
this->pin_->pin_mode(gpio::FLAG_INPUT | gpio::FLAG_PULLUP);
do {
if (--retries == 0)
return false;
@ -24,12 +24,12 @@ bool HOT ICACHE_RAM_ATTR ESPOneWire::reset() {
} while (!this->pin_->digital_read());
// Send 480µs LOW TX reset pulse
this->pin_->pin_mode(OUTPUT);
this->pin_->pin_mode(gpio::FLAG_OUTPUT);
this->pin_->digital_write(false);
delayMicroseconds(480);
// Switch into RX mode, letting the pin float
this->pin_->pin_mode(INPUT_PULLUP);
this->pin_->pin_mode(gpio::FLAG_INPUT | gpio::FLAG_PULLUP);
// after 15µs-60µs wait time, responder pulls low for 60µs-240µs
// let's have 70µs just in case
delayMicroseconds(70);
@ -39,9 +39,9 @@ bool HOT ICACHE_RAM_ATTR ESPOneWire::reset() {
return r;
}
void HOT ICACHE_RAM_ATTR ESPOneWire::write_bit(bool bit) {
void HOT IRAM_ATTR ESPOneWire::write_bit(bool bit) {
// Initiate write/read by pulling low.
this->pin_->pin_mode(OUTPUT);
this->pin_->pin_mode(gpio::FLAG_OUTPUT);
this->pin_->digital_write(false);
// bus sampled within 15µs and 60µs after pulling LOW.
@ -60,14 +60,14 @@ void HOT ICACHE_RAM_ATTR ESPOneWire::write_bit(bool bit) {
}
}
bool HOT ICACHE_RAM_ATTR ESPOneWire::read_bit() {
bool HOT IRAM_ATTR ESPOneWire::read_bit() {
// Initiate read slot by pulling LOW for at least 1µs
this->pin_->pin_mode(OUTPUT);
this->pin_->pin_mode(gpio::FLAG_OUTPUT);
this->pin_->digital_write(false);
delayMicroseconds(3);
// release bus, we have to sample within 15µs of pulling low
this->pin_->pin_mode(INPUT_PULLUP);
this->pin_->pin_mode(gpio::FLAG_INPUT | gpio::FLAG_PULLUP);
delayMicroseconds(10);
bool r = this->pin_->digital_read();
@ -76,43 +76,43 @@ bool HOT ICACHE_RAM_ATTR ESPOneWire::read_bit() {
return r;
}
void ICACHE_RAM_ATTR ESPOneWire::write8(uint8_t val) {
void IRAM_ATTR ESPOneWire::write8(uint8_t val) {
for (uint8_t i = 0; i < 8; i++) {
this->write_bit(bool((1u << i) & val));
}
}
void ICACHE_RAM_ATTR ESPOneWire::write64(uint64_t val) {
void IRAM_ATTR ESPOneWire::write64(uint64_t val) {
for (uint8_t i = 0; i < 64; i++) {
this->write_bit(bool((1ULL << i) & val));
}
}
uint8_t ICACHE_RAM_ATTR ESPOneWire::read8() {
uint8_t IRAM_ATTR ESPOneWire::read8() {
uint8_t ret = 0;
for (uint8_t i = 0; i < 8; i++) {
ret |= (uint8_t(this->read_bit()) << i);
}
return ret;
}
uint64_t ICACHE_RAM_ATTR ESPOneWire::read64() {
uint64_t IRAM_ATTR ESPOneWire::read64() {
uint64_t ret = 0;
for (uint8_t i = 0; i < 8; i++) {
ret |= (uint64_t(this->read_bit()) << i);
}
return ret;
}
void ICACHE_RAM_ATTR ESPOneWire::select(uint64_t address) {
void IRAM_ATTR ESPOneWire::select(uint64_t address) {
this->write8(ONE_WIRE_ROM_SELECT);
this->write64(address);
}
void ICACHE_RAM_ATTR ESPOneWire::reset_search() {
void IRAM_ATTR ESPOneWire::reset_search() {
this->last_discrepancy_ = 0;
this->last_device_flag_ = false;
this->last_family_discrepancy_ = 0;
this->rom_number_ = 0;
}
uint64_t HOT ICACHE_RAM_ATTR ESPOneWire::search() {
uint64_t HOT IRAM_ATTR ESPOneWire::search() {
if (this->last_device_flag_) {
return 0u;
}
@ -196,7 +196,7 @@ uint64_t HOT ICACHE_RAM_ATTR ESPOneWire::search() {
return this->rom_number_;
}
std::vector<uint64_t> ICACHE_RAM_ATTR ESPOneWire::search_vec() {
std::vector<uint64_t> IRAM_ATTR ESPOneWire::search_vec() {
std::vector<uint64_t> res;
this->reset_search();
@ -206,12 +206,12 @@ std::vector<uint64_t> ICACHE_RAM_ATTR ESPOneWire::search_vec() {
return res;
}
void ICACHE_RAM_ATTR ESPOneWire::skip() {
void IRAM_ATTR ESPOneWire::skip() {
this->write8(0xCC); // skip ROM
}
GPIOPin *ESPOneWire::get_pin() { return this->pin_; }
uint8_t ICACHE_RAM_ATTR *ESPOneWire::rom_number8_() { return reinterpret_cast<uint8_t *>(&this->rom_number_); }
uint8_t IRAM_ATTR *ESPOneWire::rom_number8_() { return reinterpret_cast<uint8_t *>(&this->rom_number_); }
} // namespace dallas
} // namespace esphome

View File

@ -1,7 +1,8 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/esphal.h"
#include "esphome/core/hal.h"
#include <vector>
namespace esphome {
namespace dallas {

View File

@ -4,8 +4,18 @@
#include "esphome/core/defines.h"
#include "esphome/core/version.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
#include <rom/rtc.h>
#include <esp_idf_version.h>
#endif
#ifdef USE_ARDUINO
#include <Esp.h>
#endif
#ifdef USE_ESP_IDF
#include <esp_heap_caps.h>
#include <esp_system.h>
#endif
namespace esphome {
@ -21,9 +31,14 @@ void DebugComponent::dump_config() {
#endif
ESP_LOGD(TAG, "ESPHome version %s", ESPHOME_VERSION);
#ifdef USE_ARDUINO
this->free_heap_ = ESP.getFreeHeap(); // NOLINT(readability-static-accessed-through-instance)
#elif defined(USE_ESP_IDF)
this->free_heap_ = heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
#endif
ESP_LOGD(TAG, "Free Heap Size: %u bytes", this->free_heap_);
#ifdef USE_ARDUINO
const char *flash_mode;
switch (ESP.getFlashChipMode()) { // NOLINT(readability-static-accessed-through-instance)
case FM_QIO:
@ -38,7 +53,7 @@ void DebugComponent::dump_config() {
case FM_DOUT:
flash_mode = "DOUT";
break;
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
case FM_FAST_READ:
flash_mode = "FAST_READ";
break;
@ -52,8 +67,9 @@ void DebugComponent::dump_config() {
// NOLINTNEXTLINE(readability-static-accessed-through-instance)
ESP_LOGD(TAG, "Flash Chip: Size=%ukB Speed=%uMHz Mode=%s", ESP.getFlashChipSize() / 1024,
ESP.getFlashChipSpeed() / 1000000, flash_mode);
#endif // USE_ARDUINO
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
esp_chip_info_t info;
esp_chip_info(&info);
const char *model;
@ -88,7 +104,9 @@ void DebugComponent::dump_config() {
ESP_LOGD(TAG, "ESP-IDF Version: %s", esp_get_idf_version());
std::string mac = uint64_to_string(ESP.getEfuseMac()); // NOLINT(readability-static-accessed-through-instance)
uint64_t chip_mac = 0LL;
esp_efuse_mac_get_default((uint8_t *) (&chip_mac));
std::string mac = uint64_to_string(chip_mac);
ESP_LOGD(TAG, "EFuse MAC: %s", mac.c_str());
const char *reset_reason;
@ -187,7 +205,7 @@ void DebugComponent::dump_config() {
ESP_LOGD(TAG, "Wakeup Reason: %s", wakeup_reason);
#endif
#if defined(ARDUINO_ARCH_ESP8266) && !defined(CLANG_TIDY)
#if defined(USE_ESP8266) && !defined(CLANG_TIDY)
ESP_LOGD(TAG, "Chip ID: 0x%08X", ESP.getChipId());
ESP_LOGD(TAG, "SDK Version: %s", ESP.getSdkVersion());
ESP_LOGD(TAG, "Core Version: %s", ESP.getCoreVersion().c_str());
@ -199,7 +217,11 @@ void DebugComponent::dump_config() {
#endif
}
void DebugComponent::loop() {
#ifdef USE_ARDUINO
uint32_t new_free_heap = ESP.getFreeHeap(); // NOLINT(readability-static-accessed-through-instance)
#elif defined(USE_ESP_IDF)
uint32_t new_free_heap = heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
#endif
if (new_free_heap < this->free_heap_ / 2) {
this->free_heap_ = new_free_heap;
ESP_LOGD(TAG, "Free Heap Size: %u bytes", this->free_heap_);

View File

@ -62,7 +62,7 @@ CONFIG_SCHEMA = cv.Schema(
cv.Schema(
{
cv.Required(CONF_PINS): cv.ensure_list(
pins.shorthand_input_pin, validate_pin_number
pins.internal_gpio_input_pin_schema, validate_pin_number
),
cv.Required(CONF_MODE): cv.enum(EXT1_WAKEUP_MODES, upper=True),
}

View File

@ -2,6 +2,10 @@
#include "esphome/core/log.h"
#include "esphome/core/application.h"
#ifdef USE_ESP8266
#include <Esp.h>
#endif
namespace esphome {
namespace deep_sleep {
@ -25,9 +29,9 @@ void DeepSleepComponent::dump_config() {
if (this->run_duration_.has_value()) {
ESP_LOGCONFIG(TAG, " Run Duration: %u ms", *this->run_duration_);
}
#ifdef ARDUINO_ARCH_ESP32
if (this->wakeup_pin_.has_value()) {
LOG_PIN(" Wakeup Pin: ", *this->wakeup_pin_);
#ifdef USE_ESP32
if (wakeup_pin_ != nullptr) {
LOG_PIN(" Wakeup Pin: ", this->wakeup_pin_);
}
#endif
}
@ -39,7 +43,7 @@ float DeepSleepComponent::get_loop_priority() const {
return -100.0f; // run after everything else is ready
}
void DeepSleepComponent::set_sleep_duration(uint32_t time_ms) { this->sleep_duration_ = uint64_t(time_ms) * 1000; }
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
void DeepSleepComponent::set_wakeup_pin_mode(WakeupPinMode wakeup_pin_mode) {
this->wakeup_pin_mode_ = wakeup_pin_mode;
}
@ -52,9 +56,9 @@ void DeepSleepComponent::begin_sleep(bool manual) {
this->next_enter_deep_sleep_ = true;
return;
}
#ifdef ARDUINO_ARCH_ESP32
if (this->wakeup_pin_mode_ == WAKEUP_PIN_MODE_KEEP_AWAKE && this->wakeup_pin_.has_value() &&
!this->sleep_duration_.has_value() && (*this->wakeup_pin_)->digital_read()) {
#ifdef USE_ESP32
if (this->wakeup_pin_mode_ == WAKEUP_PIN_MODE_KEEP_AWAKE && this->wakeup_pin_ != nullptr &&
!this->sleep_duration_.has_value() && this->wakeup_pin_->digital_read()) {
// Defer deep sleep until inactive
if (!this->next_enter_deep_sleep_) {
this->status_set_warning();
@ -69,14 +73,14 @@ void DeepSleepComponent::begin_sleep(bool manual) {
App.run_safe_shutdown_hooks();
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
if (this->sleep_duration_.has_value())
esp_sleep_enable_timer_wakeup(*this->sleep_duration_);
if (this->wakeup_pin_.has_value()) {
bool level = !(*this->wakeup_pin_)->is_inverted();
if (this->wakeup_pin_mode_ == WAKEUP_PIN_MODE_INVERT_WAKEUP && (*this->wakeup_pin_)->digital_read())
if (this->wakeup_pin_ != nullptr) {
bool level = this->wakeup_pin_->is_inverted();
if (this->wakeup_pin_mode_ == WAKEUP_PIN_MODE_INVERT_WAKEUP && this->wakeup_pin_->digital_read())
level = !level;
esp_sleep_enable_ext0_wakeup(gpio_num_t((*this->wakeup_pin_)->get_pin()), level);
esp_sleep_enable_ext0_wakeup(gpio_num_t(this->wakeup_pin_->get_pin()), level);
}
if (this->ext1_wakeup_.has_value()) {
esp_sleep_enable_ext1_wakeup(this->ext1_wakeup_->mask, this->ext1_wakeup_->wakeup_mode);
@ -90,7 +94,7 @@ void DeepSleepComponent::begin_sleep(bool manual) {
esp_deep_sleep_start();
#endif
#ifdef ARDUINO_ARCH_ESP8266
#ifdef USE_ESP8266
ESP.deepSleep(*this->sleep_duration_); // NOLINT(readability-static-accessed-through-instance)
#endif
}

View File

@ -3,12 +3,16 @@
#include "esphome/core/component.h"
#include "esphome/core/helpers.h"
#include "esphome/core/automation.h"
#include "esphome/core/esphal.h"
#include "esphome/core/hal.h"
#ifdef USE_ESP32
#include <esp_sleep.h>
#endif
namespace esphome {
namespace deep_sleep {
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
/** The values of this enum define what should be done if deep sleep is set up with a wakeup pin on the ESP32
* and the scenario occurs that the wakeup pin is already in the wakeup state.
@ -44,11 +48,11 @@ class DeepSleepComponent : public Component {
public:
/// Set the duration in ms the component should sleep once it's in deep sleep mode.
void set_sleep_duration(uint32_t time_ms);
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
/** Set the pin to wake up to on the ESP32 once it's in deep sleep mode.
* Use the inverted property to set the wakeup level.
*/
void set_wakeup_pin(GPIOPin *pin) { this->wakeup_pin_ = pin; }
void set_wakeup_pin(InternalGPIOPin *pin) { this->wakeup_pin_ = pin; }
void set_wakeup_pin_mode(WakeupPinMode wakeup_pin_mode);
@ -72,8 +76,8 @@ class DeepSleepComponent : public Component {
protected:
optional<uint64_t> sleep_duration_;
#ifdef ARDUINO_ARCH_ESP32
optional<GPIOPin *> wakeup_pin_;
#ifdef USE_ESP32
InternalGPIOPin *wakeup_pin_;
WakeupPinMode wakeup_pin_mode_{WAKEUP_PIN_MODE_IGNORE};
optional<Ext1Wakeup> ext1_wakeup_;
optional<bool> touch_wakeup_;

View File

@ -13,7 +13,7 @@ class DemoSensor : public sensor::Sensor, public PollingComponent {
float val = random_float();
bool increasing = this->get_state_class() == sensor::STATE_CLASS_TOTAL_INCREASING;
if (increasing) {
float base = isnan(this->state) ? 0.0f : this->state;
float base = std::isnan(this->state) ? 0.0f : this->state;
this->publish_state(base + val * 10);
} else {
if (val < 0.1)

View File

@ -71,7 +71,7 @@ void DHT::set_dht_model(DHTModel model) {
this->model_ = model;
this->is_auto_detect_ = model == DHT_MODEL_AUTO_DETECT;
}
bool HOT ICACHE_RAM_ATTR DHT::read_sensor_(float *temperature, float *humidity, bool report_errors) {
bool HOT IRAM_ATTR DHT::read_sensor_(float *temperature, float *humidity, bool report_errors) {
*humidity = NAN;
*temperature = NAN;
@ -83,7 +83,7 @@ bool HOT ICACHE_RAM_ATTR DHT::read_sensor_(float *temperature, float *humidity,
InterruptLock lock;
this->pin_->digital_write(false);
this->pin_->pin_mode(OUTPUT);
this->pin_->pin_mode(gpio::FLAG_OUTPUT);
this->pin_->digital_write(false);
if (this->model_ == DHT_MODEL_DHT11) {
@ -99,7 +99,7 @@ bool HOT ICACHE_RAM_ATTR DHT::read_sensor_(float *temperature, float *humidity,
} else {
delayMicroseconds(800);
}
this->pin_->pin_mode(INPUT_PULLUP);
this->pin_->pin_mode(gpio::FLAG_INPUT | gpio::FLAG_PULLUP);
// Host pull up 20-40us then DHT response 80us
// Start waiting for initial rising edge at the center when we

View File

@ -1,7 +1,7 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/esphal.h"
#include "esphome/core/hal.h"
#include "esphome/components/sensor/sensor.h"
namespace esphome {
@ -36,7 +36,7 @@ class DHT : public PollingComponent {
*/
void set_dht_model(DHTModel model);
void set_pin(GPIOPin *pin) { pin_ = pin; }
void set_pin(InternalGPIOPin *pin) { pin_ = pin; }
void set_model(DHTModel model) { model_ = model; }
void set_temperature_sensor(sensor::Sensor *temperature_sensor) { temperature_sensor_ = temperature_sensor; }
void set_humidity_sensor(sensor::Sensor *humidity_sensor) { humidity_sensor_ = humidity_sensor; }
@ -52,7 +52,7 @@ class DHT : public PollingComponent {
protected:
bool read_sensor_(float *temperature, float *humidity, bool report_errors);
GPIOPin *pin_;
InternalGPIOPin *pin_;
DHTModel model_{DHT_MODEL_AUTO_DETECT};
bool is_auto_detect_{false};
sensor::Sensor *temperature_sensor_{nullptr};

View File

@ -4,6 +4,7 @@
#include "esphome/core/application.h"
#include "esphome/core/color.h"
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
namespace esphome {
namespace display {
@ -372,7 +373,7 @@ bool Glyph::get_pixel(int x, int y) const {
return false;
const uint32_t width_8 = ((this->glyph_data_->width + 7u) / 8u) * 8u;
const uint32_t pos = x_data + y_data * width_8;
return pgm_read_byte(this->glyph_data_->data + (pos / 8u)) & (0x80 >> (pos % 8u));
return progmem_read_byte(this->glyph_data_->data + (pos / 8u)) & (0x80 >> (pos % 8u));
}
const char *Glyph::get_char() const { return this->glyph_data_->a_char; }
bool Glyph::compare_to(const char *str) const {
@ -464,22 +465,22 @@ bool Image::get_pixel(int x, int y) const {
return false;
const uint32_t width_8 = ((this->width_ + 7u) / 8u) * 8u;
const uint32_t pos = x + y * width_8;
return pgm_read_byte(this->data_start_ + (pos / 8u)) & (0x80 >> (pos % 8u));
return progmem_read_byte(this->data_start_ + (pos / 8u)) & (0x80 >> (pos % 8u));
}
Color Image::get_color_pixel(int x, int y) const {
if (x < 0 || x >= this->width_ || y < 0 || y >= this->height_)
return Color::BLACK;
const uint32_t pos = (x + y * this->width_) * 3;
const uint32_t color32 = (pgm_read_byte(this->data_start_ + pos + 2) << 0) |
(pgm_read_byte(this->data_start_ + pos + 1) << 8) |
(pgm_read_byte(this->data_start_ + pos + 0) << 16);
const uint32_t color32 = (progmem_read_byte(this->data_start_ + pos + 2) << 0) |
(progmem_read_byte(this->data_start_ + pos + 1) << 8) |
(progmem_read_byte(this->data_start_ + pos + 0) << 16);
return Color(color32);
}
Color Image::get_grayscale_pixel(int x, int y) const {
if (x < 0 || x >= this->width_ || y < 0 || y >= this->height_)
return Color::BLACK;
const uint32_t pos = (x + y * this->width_);
const uint8_t gray = pgm_read_byte(this->data_start_ + pos);
const uint8_t gray = progmem_read_byte(this->data_start_ + pos);
return Color(gray | gray << 8 | gray << 16 | gray << 24);
}
int Image::get_width() const { return this->width_; }
@ -496,7 +497,7 @@ bool Animation::get_pixel(int x, int y) const {
if (frame_index >= this->width_ * this->height_ * this->animation_frame_count_)
return false;
const uint32_t pos = x + y * width_8 + frame_index;
return pgm_read_byte(this->data_start_ + (pos / 8u)) & (0x80 >> (pos % 8u));
return progmem_read_byte(this->data_start_ + (pos / 8u)) & (0x80 >> (pos % 8u));
}
Color Animation::get_color_pixel(int x, int y) const {
if (x < 0 || x >= this->width_ || y < 0 || y >= this->height_)
@ -505,9 +506,9 @@ Color Animation::get_color_pixel(int x, int y) const {
if (frame_index >= this->width_ * this->height_ * this->animation_frame_count_)
return Color::BLACK;
const uint32_t pos = (x + y * this->width_ + frame_index) * 3;
const uint32_t color32 = (pgm_read_byte(this->data_start_ + pos + 2) << 0) |
(pgm_read_byte(this->data_start_ + pos + 1) << 8) |
(pgm_read_byte(this->data_start_ + pos + 0) << 16);
const uint32_t color32 = (progmem_read_byte(this->data_start_ + pos + 2) << 0) |
(progmem_read_byte(this->data_start_ + pos + 1) << 8) |
(progmem_read_byte(this->data_start_ + pos + 0) << 16);
return Color(color32);
}
Color Animation::get_grayscale_pixel(int x, int y) const {
@ -517,7 +518,7 @@ Color Animation::get_grayscale_pixel(int x, int y) const {
if (frame_index >= this->width_ * this->height_ * this->animation_frame_count_)
return Color::BLACK;
const uint32_t pos = (x + y * this->width_ + frame_index);
const uint8_t gray = pgm_read_byte(this->data_start_ + pos);
const uint8_t gray = progmem_read_byte(this->data_start_ + pos);
return Color(gray | gray << 8 | gray << 16 | gray << 24);
}
Animation::Animation(const uint8_t *data_start, int width, int height, uint32_t animation_frame_count, ImageType type)

View File

@ -4,6 +4,7 @@
#include "esphome/core/defines.h"
#include "esphome/core/automation.h"
#include "display_color_utils.h"
#include <cstdarg>
#ifdef USE_TIME
#include "esphome/components/time/real_time_clock.h"

View File

@ -39,14 +39,17 @@ def _validate_key(value):
return "".join(f"{part:02X}" for part in parts_int)
CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(): cv.declare_id(Dsmr),
cv.Optional(CONF_DECRYPTION_KEY): _validate_key,
cv.Optional(CONF_CRC_CHECK, default=True): cv.boolean,
cv.Optional(CONF_GAS_MBUS_ID, default=1): cv.int_,
}
).extend(uart.UART_DEVICE_SCHEMA)
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
cv.GenerateID(): cv.declare_id(Dsmr),
cv.Optional(CONF_DECRYPTION_KEY): _validate_key,
cv.Optional(CONF_CRC_CHECK, default=True): cv.boolean,
cv.Optional(CONF_GAS_MBUS_ID, default=1): cv.int_,
}
).extend(uart.UART_DEVICE_SCHEMA),
cv.only_with_arduino,
)
async def to_code(config):

View File

@ -1,3 +1,5 @@
#ifdef USE_ARDUINO
#include "dsmr.h"
#include "esphome/core/log.h"
@ -128,8 +130,9 @@ void Dsmr::receive_encrypted_() {
delay(4); // Wait for data
}
}
if (buffer_length > 0)
if (buffer_length > 0) {
ESP_LOGW(TAG, "Timeout while waiting for encrypted data or invalid data received.");
}
}
bool Dsmr::parse_telegram() {
@ -186,3 +189,5 @@ void Dsmr::set_decryption_key(const std::string &decryption_key) {
} // namespace dsmr
} // namespace esphome
#endif // USE_ARDUINO

View File

@ -1,5 +1,7 @@
#pragma once
#ifdef USE_ARDUINO
#include "esphome/core/component.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/text_sensor/text_sensor.h"
@ -103,3 +105,5 @@ class Dsmr : public Component, public uart::UARTDevice {
};
} // namespace dsmr
} // namespace esphome
#endif // USE_ARDUINO

View File

@ -15,7 +15,7 @@ void DutyCycleSensor::setup() {
this->last_update_ = micros();
this->store_.last_interrupt = micros();
this->pin_->attach_interrupt(DutyCycleSensorStore::gpio_intr, &this->store_, CHANGE);
this->pin_->attach_interrupt(DutyCycleSensorStore::gpio_intr, &this->store_, gpio::INTERRUPT_ANY_EDGE);
}
void DutyCycleSensor::dump_config() {
LOG_SENSOR("", "Duty Cycle Sensor", this);
@ -44,8 +44,8 @@ void DutyCycleSensor::update() {
float DutyCycleSensor::get_setup_priority() const { return setup_priority::DATA; }
void ICACHE_RAM_ATTR DutyCycleSensorStore::gpio_intr(DutyCycleSensorStore *arg) {
const bool new_level = arg->pin->digital_read();
void IRAM_ATTR DutyCycleSensorStore::gpio_intr(DutyCycleSensorStore *arg) {
const bool new_level = arg->pin.digital_read();
if (new_level == arg->last_level)
return;
arg->last_level = new_level;

View File

@ -1,7 +1,7 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/esphal.h"
#include "esphome/core/hal.h"
#include "esphome/components/sensor/sensor.h"
namespace esphome {
@ -12,14 +12,14 @@ struct DutyCycleSensorStore {
volatile uint32_t last_interrupt{0};
volatile uint32_t on_time{0};
volatile bool last_level{false};
ISRInternalGPIOPin *pin;
ISRInternalGPIOPin pin;
static void gpio_intr(DutyCycleSensorStore *arg);
};
class DutyCycleSensor : public sensor::Sensor, public PollingComponent {
public:
void set_pin(GPIOPin *pin) { pin_ = pin; }
void set_pin(InternalGPIOPin *pin) { pin_ = pin; }
void setup() override;
float get_setup_priority() const override;
@ -27,7 +27,7 @@ class DutyCycleSensor : public sensor::Sensor, public PollingComponent {
void update() override;
protected:
GPIOPin *pin_;
InternalGPIOPin *pin_;
DutyCycleSensorStore store_{};
uint32_t last_update_;

View File

@ -25,9 +25,7 @@ CONFIG_SCHEMA = (
.extend(
{
cv.GenerateID(): cv.declare_id(DutyCycleSensor),
cv.Required(CONF_PIN): cv.All(
pins.internal_gpio_input_pin_schema, pins.validate_has_interrupt
),
cv.Required(CONF_PIN): cv.All(pins.internal_gpio_input_pin_schema),
}
)
.extend(cv.polling_component_schema("60s"))

View File

@ -4,6 +4,8 @@ from esphome.components.light.types import AddressableLightEffect
from esphome.components.light.effects import register_addressable_effect
from esphome.const import CONF_ID, CONF_NAME, CONF_METHOD, CONF_CHANNELS
DEPENDENCIES = ["network"]
e131_ns = cg.esphome_ns.namespace("e131")
E131AddressableLightEffect = e131_ns.class_(
"E131AddressableLightEffect", AddressableLightEffect
@ -21,11 +23,16 @@ CHANNELS = {
CONF_UNIVERSE = "universe"
CONF_E131_ID = "e131_id"
CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(): cv.declare_id(E131Component),
cv.Optional(CONF_METHOD, default="MULTICAST"): cv.one_of(*METHODS, upper=True),
}
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
cv.GenerateID(): cv.declare_id(E131Component),
cv.Optional(CONF_METHOD, default="MULTICAST"): cv.one_of(
*METHODS, upper=True
),
}
),
cv.only_with_arduino,
)

View File

@ -1,12 +1,14 @@
#ifdef USE_ARDUINO
#include "e131.h"
#include "e131_addressable_light_effect.h"
#include "esphome/core/log.h"
#ifdef ARDUINO_ARCH_ESP32
#ifdef USE_ESP32
#include <WiFi.h>
#endif
#ifdef ARDUINO_ARCH_ESP8266
#ifdef USE_ESP8266
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#endif
@ -104,3 +106,5 @@ bool E131Component::process_(int universe, const E131Packet &packet) {
} // namespace e131
} // namespace esphome
#endif // USE_ARDUINO

View File

@ -1,5 +1,7 @@
#pragma once
#ifdef USE_ARDUINO
#include "esphome/core/component.h"
#include <memory>
@ -55,3 +57,5 @@ class E131Component : public esphome::Component {
} // namespace e131
} // namespace esphome
#endif // USE_ARDUINO

View File

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

View File

@ -1,5 +1,7 @@
#pragma once
#ifdef USE_ARDUINO
#include "esphome/core/component.h"
#include "esphome/components/light/addressable_light_effect.h"
@ -46,3 +48,5 @@ class E131AddressableLightEffect : public light::AddressableLightEffect {
} // namespace e131
} // namespace esphome
#endif // USE_ARDUINO

View File

@ -1,8 +1,14 @@
#ifdef USE_ARDUINO
#include "e131.h"
#include "esphome/core/log.h"
#include "esphome/core/util.h"
#include "esphome/components/network/ip_address.h"
#include <cstring>
#include <lwip/init.h>
#include <lwip/ip_addr.h>
#include <lwip/ip4_addr.h>
#include <lwip/igmp.h>
namespace esphome {
@ -63,8 +69,8 @@ bool E131Component::join_igmp_groups_() {
if (!universe.second)
continue;
ip4_addr_t multicast_addr = {
static_cast<uint32_t>(IPAddress(239, 255, ((universe.first >> 8) & 0xff), ((universe.first >> 0) & 0xff)))};
ip4_addr_t multicast_addr = {static_cast<uint32_t>(
network::IPAddress(239, 255, ((universe.first >> 8) & 0xff), ((universe.first >> 0) & 0xff)))};
auto err = igmp_joingroup(IP4_ADDR_ANY4, &multicast_addr);
@ -98,7 +104,7 @@ void E131Component::leave_(int universe) {
if (listen_method_ == E131_MULTICAST) {
ip4_addr_t multicast_addr = {
static_cast<uint32_t>(IPAddress(239, 255, ((universe >> 8) & 0xff), ((universe >> 0) & 0xff)))};
static_cast<uint32_t>(network::IPAddress(239, 255, ((universe >> 8) & 0xff), ((universe >> 0) & 0xff)))};
igmp_leavegroup(IP4_ADDR_ANY4, &multicast_addr);
}
@ -134,3 +140,5 @@ bool E131Component::packet_(const std::vector<uint8_t> &data, int &universe, E13
} // namespace e131
} // namespace esphome
#endif // USE_ARDUINO

View File

@ -1,5 +1,6 @@
#include "endstop_cover.h"
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
namespace esphome {
namespace endstop {

View File

@ -0,0 +1,379 @@
from dataclasses import dataclass
from typing import Union
from pathlib import Path
import logging
from esphome.helpers import write_file_if_changed
from esphome.const import (
CONF_BOARD,
CONF_FRAMEWORK,
CONF_TYPE,
CONF_VARIANT,
CONF_VERSION,
KEY_CORE,
KEY_FRAMEWORK_VERSION,
KEY_TARGET_FRAMEWORK,
KEY_TARGET_PLATFORM,
)
from esphome.core import CORE, HexInt
import esphome.config_validation as cv
import esphome.codegen as cg
from .const import (
KEY_BOARD,
KEY_ESP32,
KEY_SDKCONFIG_OPTIONS,
KEY_VARIANT,
VARIANT_ESP32C3,
VARIANTS,
)
# force import gpio to register pin schema
from .gpio import esp32_pin_to_code # noqa
_LOGGER = logging.getLogger(__name__)
CODEOWNERS = ["@esphome/core"]
def set_core_data(config):
CORE.data[KEY_ESP32] = {}
CORE.data[KEY_CORE][KEY_TARGET_PLATFORM] = "esp32"
conf = config[CONF_FRAMEWORK]
if conf[CONF_TYPE] == FRAMEWORK_ESP_IDF:
CORE.data[KEY_CORE][KEY_TARGET_FRAMEWORK] = "esp-idf"
CORE.data[KEY_ESP32][KEY_SDKCONFIG_OPTIONS] = {}
elif conf[CONF_TYPE] == FRAMEWORK_ARDUINO:
CORE.data[KEY_CORE][KEY_TARGET_FRAMEWORK] = "arduino"
CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION] = cv.Version.parse(
config[CONF_FRAMEWORK][CONF_VERSION_HINT]
)
CORE.data[KEY_ESP32][KEY_BOARD] = config[CONF_BOARD]
CORE.data[KEY_ESP32][KEY_VARIANT] = config[CONF_VARIANT]
return config
def get_esp32_variant():
return CORE.data[KEY_ESP32][KEY_VARIANT]
def is_esp32c3():
return get_esp32_variant() == VARIANT_ESP32C3
@dataclass
class RawSdkconfigValue:
"""An sdkconfig value that won't be auto-formatted"""
value: str
SdkconfigValueType = Union[bool, int, HexInt, str, RawSdkconfigValue]
def add_idf_sdkconfig_option(name: str, value: SdkconfigValueType):
"""Set an esp-idf sdkconfig value."""
if not CORE.using_esp_idf:
raise ValueError("Not an esp-idf project")
CORE.data[KEY_ESP32][KEY_SDKCONFIG_OPTIONS][name] = value
def _format_framework_arduino_version(ver: cv.Version) -> str:
# format the given arduino (https://github.com/espressif/arduino-esp32/releases) version to
# a PIO platformio/framework-arduinoespressif32 value
# List of package versions: https://api.registry.platformio.org/v3/packages/platformio/tool/framework-arduinoespressif32
if ver <= cv.Version(1, 0, 3):
return f"~2.{ver.major}{ver.minor:02d}{ver.patch:02d}.0"
return f"~3.{ver.major}{ver.minor:02d}{ver.patch:02d}.0"
# NOTE: Keep this in mind when updating the recommended version:
# * New framework historically have had some regressions, especially for WiFi.
# The new version needs to be thoroughly validated before changing the
# recommended version as otherwise a bunch of devices could be bricked
# * For all constants below, update platformio.ini (in this repo)
# and platformio.ini/platformio-lint.ini in the esphome-docker-base repository
# The default/recommended arduino framework version
# - https://github.com/espressif/arduino-esp32/releases
# - https://api.registry.platformio.org/v3/packages/platformio/tool/framework-arduinoespressif32
RECOMMENDED_ARDUINO_FRAMEWORK_VERSION = cv.Version(1, 0, 6)
# The platformio/espressif32 version to use for arduino frameworks
# - https://github.com/platformio/platform-espressif32/releases
# - https://api.registry.platformio.org/v3/packages/platformio/platform/espressif32
ARDUINO_PLATFORM_VERSION = cv.Version(3, 3, 2)
# The default/recommended esp-idf framework version
# - https://github.com/espressif/esp-idf/releases
# - https://api.registry.platformio.org/v3/packages/platformio/tool/framework-espidf
RECOMMENDED_ESP_IDF_FRAMEWORK_VERSION = cv.Version(4, 3, 0)
# The platformio/espressif32 version to use for esp-idf frameworks
# - https://github.com/platformio/platform-espressif32/releases
# - https://api.registry.platformio.org/v3/packages/platformio/platform/espressif32
ESP_IDF_PLATFORM_VERSION = cv.Version(3, 3, 2)
def _arduino_check_versions(value):
value = value.copy()
lookups = {
"dev": ("https://github.com/espressif/arduino-esp32.git", cv.Version(2, 0, 0)),
"latest": ("", cv.Version(1, 0, 3)),
"recommended": (
_format_framework_arduino_version(RECOMMENDED_ARDUINO_FRAMEWORK_VERSION),
RECOMMENDED_ARDUINO_FRAMEWORK_VERSION,
),
}
ver_value = value[CONF_VERSION]
default_ver_hint = None
if ver_value.lower() in lookups:
default_ver_hint = str(lookups[ver_value.lower()][1])
ver_value = lookups[ver_value.lower()][0]
else:
with cv.suppress_invalid():
ver = cv.Version.parse(cv.version_number(value))
if ver <= cv.Version(1, 0, 3):
ver_value = f"~2.{ver.major}{ver.minor:02d}{ver.patch:02d}.0"
else:
ver_value = f"~3.{ver.major}{ver.minor:02d}{ver.patch:02d}.0"
default_ver_hint = str(ver)
value[CONF_VERSION] = ver_value
if CONF_VERSION_HINT not in value and default_ver_hint is None:
raise cv.Invalid("Needs a version hint to understand the framework version")
ver_hint_s = value.get(CONF_VERSION_HINT, default_ver_hint)
value[CONF_VERSION_HINT] = ver_hint_s
plat_ver = value.get(CONF_PLATFORM_VERSION, ARDUINO_PLATFORM_VERSION)
value[CONF_PLATFORM_VERSION] = str(plat_ver)
if cv.Version.parse(ver_hint_s) != RECOMMENDED_ARDUINO_FRAMEWORK_VERSION:
_LOGGER.warning(
"The selected arduino framework version is not the recommended one"
)
_LOGGER.warning(
"If there are connectivity or build issues please remove the manual version"
)
return value
def _format_framework_espidf_version(ver: cv.Version) -> str:
# format the given arduino (https://github.com/espressif/esp-idf/releases) version to
# a PIO platformio/framework-espidf value
# List of package versions: https://api.registry.platformio.org/v3/packages/platformio/tool/framework-espidf
return f"~3.{ver.major}{ver.minor:02d}{ver.patch:02d}.0"
def _esp_idf_check_versions(value):
value = value.copy()
lookups = {
"dev": ("https://github.com/espressif/esp-idf.git", cv.Version(4, 3, 1)),
"latest": ("", cv.Version(4, 3, 0)),
"recommended": (
_format_framework_espidf_version(RECOMMENDED_ESP_IDF_FRAMEWORK_VERSION),
RECOMMENDED_ESP_IDF_FRAMEWORK_VERSION,
),
}
ver_value = value[CONF_VERSION]
default_ver_hint = None
if ver_value.lower() in lookups:
default_ver_hint = str(lookups[ver_value.lower()][1])
ver_value = lookups[ver_value.lower()][0]
else:
with cv.suppress_invalid():
ver = cv.Version.parse(cv.version_number(value))
ver_value = f"~3.{ver.major}{ver.minor:02d}{ver.patch:02d}.0"
default_ver_hint = str(ver)
value[CONF_VERSION] = ver_value
if CONF_VERSION_HINT not in value and default_ver_hint is None:
raise cv.Invalid("Needs a version hint to understand the framework version")
ver_hint_s = value.get(CONF_VERSION_HINT, default_ver_hint)
value[CONF_VERSION_HINT] = ver_hint_s
if cv.Version.parse(ver_hint_s) < cv.Version(4, 0, 0):
raise cv.Invalid("Only ESP-IDF 4.0+ is supported")
if cv.Version.parse(ver_hint_s) != RECOMMENDED_ESP_IDF_FRAMEWORK_VERSION:
_LOGGER.warning(
"The selected esp-idf framework version is not the recommended one"
)
_LOGGER.warning(
"If there are connectivity or build issues please remove the manual version"
)
plat_ver = value.get(CONF_PLATFORM_VERSION, ESP_IDF_PLATFORM_VERSION)
value[CONF_PLATFORM_VERSION] = str(plat_ver)
return value
CONF_VERSION_HINT = "version_hint"
CONF_PLATFORM_VERSION = "platform_version"
ARDUINO_FRAMEWORK_SCHEMA = cv.All(
cv.Schema(
{
cv.Optional(CONF_VERSION, default="recommended"): cv.string_strict,
cv.Optional(CONF_VERSION_HINT): cv.version_number,
cv.Optional(CONF_PLATFORM_VERSION): cv.string_strict,
}
),
_arduino_check_versions,
)
CONF_SDKCONFIG_OPTIONS = "sdkconfig_options"
ESP_IDF_FRAMEWORK_SCHEMA = cv.All(
cv.Schema(
{
cv.Optional(CONF_VERSION, default="recommended"): cv.string_strict,
cv.Optional(CONF_VERSION_HINT): cv.version_number,
cv.Optional(CONF_SDKCONFIG_OPTIONS, default={}): {
cv.string_strict: cv.string_strict
},
cv.Optional(CONF_PLATFORM_VERSION): cv.string_strict,
}
),
_esp_idf_check_versions,
)
FRAMEWORK_ESP_IDF = "esp-idf"
FRAMEWORK_ARDUINO = "arduino"
FRAMEWORK_SCHEMA = cv.typed_schema(
{
FRAMEWORK_ESP_IDF: ESP_IDF_FRAMEWORK_SCHEMA,
FRAMEWORK_ARDUINO: ARDUINO_FRAMEWORK_SCHEMA,
},
lower=True,
space="-",
default_type=FRAMEWORK_ARDUINO,
)
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
cv.Required(CONF_BOARD): cv.string_strict,
cv.Optional(CONF_VARIANT, default="ESP32"): cv.one_of(
*VARIANTS, upper=True
),
cv.Optional(CONF_FRAMEWORK, default={}): FRAMEWORK_SCHEMA,
}
),
set_core_data,
)
async def to_code(config):
cg.add_platformio_option("board", config[CONF_BOARD])
cg.add_build_flag("-DUSE_ESP32")
cg.add_define("ESPHOME_BOARD", config[CONF_BOARD])
cg.add_build_flag(f"-DUSE_ESP32_VARIANT_{config[CONF_VARIANT]}")
conf = config[CONF_FRAMEWORK]
if conf[CONF_TYPE] == FRAMEWORK_ESP_IDF:
cg.add_platformio_option(
"platform", f"espressif32 @ {conf[CONF_PLATFORM_VERSION]}"
)
cg.add_platformio_option("framework", "espidf")
cg.add_build_flag("-DUSE_ESP_IDF")
cg.add_build_flag("-DUSE_ESP32_FRAMEWORK_ESP_IDF")
cg.add_build_flag("-Wno-nonnull-compare")
cg.add_platformio_option(
"platform_packages",
[f"platformio/framework-espidf @ {conf[CONF_VERSION]}"],
)
add_idf_sdkconfig_option("CONFIG_PARTITION_TABLE_SINGLE_APP", False)
add_idf_sdkconfig_option("CONFIG_PARTITION_TABLE_CUSTOM", True)
add_idf_sdkconfig_option(
"CONFIG_PARTITION_TABLE_CUSTOM_FILENAME", "partitions.csv"
)
add_idf_sdkconfig_option("CONFIG_COMPILER_OPTIMIZATION_DEFAULT", False)
add_idf_sdkconfig_option("CONFIG_COMPILER_OPTIMIZATION_SIZE", True)
cg.add_platformio_option("board_build.partitions", "partitions.csv")
for name, value in conf[CONF_SDKCONFIG_OPTIONS].items():
add_idf_sdkconfig_option(name, RawSdkconfigValue(value))
elif conf[CONF_TYPE] == FRAMEWORK_ARDUINO:
cg.add_platformio_option(
"platform", f"espressif32 @ {conf[CONF_PLATFORM_VERSION]}"
)
cg.add_platformio_option("framework", "arduino")
cg.add_build_flag("-DUSE_ARDUINO")
cg.add_build_flag("-DUSE_ESP32_FRAMEWORK_ARDUINO")
cg.add_platformio_option(
"platform_packages",
[f"platformio/framework-arduinoespressif32 @ {conf[CONF_VERSION]}"],
)
cg.add_platformio_option("board_build.partitions", "partitions.csv")
ARDUINO_PARTITIONS_CSV = """\
nvs, data, nvs, 0x009000, 0x005000,
otadata, data, ota, 0x00e000, 0x002000,
app0, app, ota_0, 0x010000, 0x1C0000,
app1, app, ota_1, 0x1D0000, 0x1C0000,
eeprom, data, 0x99, 0x390000, 0x001000,
spiffs, data, spiffs, 0x391000, 0x00F000
"""
IDF_PARTITIONS_CSV = """\
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, , 0x4000,
otadata, data, ota, , 0x2000,
phy_init, data, phy, , 0x1000,
app0, app, ota_0, , 0x1C0000,
app1, app, ota_1, , 0x1C0000,
"""
def _format_sdkconfig_val(value: SdkconfigValueType) -> str:
if isinstance(value, bool):
return "y" if value else "n"
if isinstance(value, int):
return str(value)
if isinstance(value, str):
return f'"{value}"'
if isinstance(value, RawSdkconfigValue):
return value.value
raise ValueError
def _write_sdkconfig():
# sdkconfig.{name} stores the real sdkconfig (modified by esp-idf with default)
# sdkconfig.{name}.esphomeinternal stores what esphome last wrote
# we use the internal one to detect if there were any changes, and if so write them to the
# real sdkconfig
sdk_path = Path(CORE.relative_build_path(f"sdkconfig.{CORE.name}"))
internal_path = Path(
CORE.relative_build_path(f"sdkconfig.{CORE.name}.esphomeinternal")
)
want_opts = CORE.data[KEY_ESP32][KEY_SDKCONFIG_OPTIONS]
contents = (
"\n".join(
f"{name}={_format_sdkconfig_val(value)}"
for name, value in sorted(want_opts.items())
)
+ "\n"
)
if write_file_if_changed(internal_path, contents):
# internal changed, update real one
write_file_if_changed(sdk_path, contents)
# Called by writer.py
def copy_files():
if CORE.using_arduino:
write_file_if_changed(
CORE.relative_build_path("partitions.csv"),
ARDUINO_PARTITIONS_CSV,
)
if CORE.using_esp_idf:
_write_sdkconfig()
write_file_if_changed(
CORE.relative_build_path("partitions.csv"),
IDF_PARTITIONS_CSV,
)

View File

@ -1,212 +1,3 @@
ESP8266_BASE_PINS = {
"A0": 17,
"SS": 15,
"MOSI": 13,
"MISO": 12,
"SCK": 14,
"SDA": 4,
"SCL": 5,
"RX": 3,
"TX": 1,
}
ESP8266_BOARD_PINS = {
"d1": {
"D0": 3,
"D1": 1,
"D2": 16,
"D3": 5,
"D4": 4,
"D5": 14,
"D6": 12,
"D7": 13,
"D8": 0,
"D9": 2,
"D10": 15,
"D11": 13,
"D12": 14,
"D13": 14,
"D14": 4,
"D15": 5,
"LED": 2,
},
"d1_mini": {
"D0": 16,
"D1": 5,
"D2": 4,
"D3": 0,
"D4": 2,
"D5": 14,
"D6": 12,
"D7": 13,
"D8": 15,
"LED": 2,
},
"d1_mini_lite": "d1_mini",
"d1_mini_pro": "d1_mini",
"esp01": {},
"esp01_1m": {},
"esp07": {},
"esp12e": {},
"esp210": {},
"esp8285": {},
"esp_wroom_02": {},
"espduino": {"LED": 16},
"espectro": {"LED": 15, "BUTTON": 2},
"espino": {"LED": 2, "LED_RED": 2, "LED_GREEN": 4, "LED_BLUE": 5, "BUTTON": 0},
"espinotee": {"LED": 16},
"espmxdevkit": {},
"espresso_lite_v1": {"LED": 16},
"espresso_lite_v2": {"LED": 2},
"gen4iod": {},
"heltec_wifi_kit_8": "d1_mini",
"huzzah": {
"LED": 0,
"LED_RED": 0,
"LED_BLUE": 2,
"D4": 4,
"D5": 5,
"D12": 12,
"D13": 13,
"D14": 14,
"D15": 15,
"D16": 16,
},
"inventone": {},
"modwifi": {},
"nodemcu": {
"D0": 16,
"D1": 5,
"D2": 4,
"D3": 0,
"D4": 2,
"D5": 14,
"D6": 12,
"D7": 13,
"D8": 15,
"D9": 3,
"D10": 1,
"LED": 16,
},
"nodemcuv2": "nodemcu",
"oak": {
"P0": 2,
"P1": 5,
"P2": 0,
"P3": 3,
"P4": 1,
"P5": 4,
"P6": 15,
"P7": 13,
"P8": 12,
"P9": 14,
"P10": 16,
"P11": 17,
"LED": 5,
},
"phoenix_v1": {"LED": 16},
"phoenix_v2": {"LED": 2},
"sonoff_basic": {},
"sonoff_s20": {},
"sonoff_sv": {},
"sonoff_th": {},
"sparkfunBlynk": "thing",
"thing": {"LED": 5, "SDA": 2, "SCL": 14},
"thingdev": "thing",
"wifi_slot": {"LED": 2},
"wifiduino": {
"D0": 3,
"D1": 1,
"D2": 2,
"D3": 0,
"D4": 4,
"D5": 5,
"D6": 16,
"D7": 14,
"D8": 12,
"D9": 13,
"D10": 15,
"D11": 13,
"D12": 12,
"D13": 14,
},
"wifinfo": {
"LED": 12,
"D0": 16,
"D1": 5,
"D2": 4,
"D3": 0,
"D4": 2,
"D5": 14,
"D6": 12,
"D7": 13,
"D8": 15,
"D9": 3,
"D10": 1,
},
"wio_link": {"LED": 2, "GROVE": 15, "D0": 14, "D1": 12, "D2": 13, "BUTTON": 0},
"wio_node": {"LED": 2, "GROVE": 15, "D0": 3, "D1": 5, "BUTTON": 0},
"xinabox_cw01": {"SDA": 2, "SCL": 14, "LED": 5, "LED_RED": 12, "LED_GREEN": 13},
}
FLASH_SIZE_1_MB = 2 ** 20
FLASH_SIZE_512_KB = FLASH_SIZE_1_MB // 2
FLASH_SIZE_2_MB = 2 * FLASH_SIZE_1_MB
FLASH_SIZE_4_MB = 4 * FLASH_SIZE_1_MB
FLASH_SIZE_16_MB = 16 * FLASH_SIZE_1_MB
ESP8266_FLASH_SIZES = {
"d1": FLASH_SIZE_4_MB,
"d1_mini": FLASH_SIZE_4_MB,
"d1_mini_lite": FLASH_SIZE_1_MB,
"d1_mini_pro": FLASH_SIZE_16_MB,
"esp01": FLASH_SIZE_512_KB,
"esp01_1m": FLASH_SIZE_1_MB,
"esp07": FLASH_SIZE_4_MB,
"esp12e": FLASH_SIZE_4_MB,
"esp210": FLASH_SIZE_4_MB,
"esp8285": FLASH_SIZE_1_MB,
"esp_wroom_02": FLASH_SIZE_2_MB,
"espduino": FLASH_SIZE_4_MB,
"espectro": FLASH_SIZE_4_MB,
"espino": FLASH_SIZE_4_MB,
"espinotee": FLASH_SIZE_4_MB,
"espmxdevkit": FLASH_SIZE_1_MB,
"espresso_lite_v1": FLASH_SIZE_4_MB,
"espresso_lite_v2": FLASH_SIZE_4_MB,
"gen4iod": FLASH_SIZE_512_KB,
"heltec_wifi_kit_8": FLASH_SIZE_4_MB,
"huzzah": FLASH_SIZE_4_MB,
"inventone": FLASH_SIZE_4_MB,
"modwifi": FLASH_SIZE_2_MB,
"nodemcu": FLASH_SIZE_4_MB,
"nodemcuv2": FLASH_SIZE_4_MB,
"oak": FLASH_SIZE_4_MB,
"phoenix_v1": FLASH_SIZE_4_MB,
"phoenix_v2": FLASH_SIZE_4_MB,
"sonoff_basic": FLASH_SIZE_1_MB,
"sonoff_s20": FLASH_SIZE_1_MB,
"sonoff_sv": FLASH_SIZE_1_MB,
"sonoff_th": FLASH_SIZE_1_MB,
"sparkfunBlynk": FLASH_SIZE_4_MB,
"thing": FLASH_SIZE_512_KB,
"thingdev": FLASH_SIZE_512_KB,
"wifi_slot": FLASH_SIZE_1_MB,
"wifiduino": FLASH_SIZE_4_MB,
"wifinfo": FLASH_SIZE_1_MB,
"wio_link": FLASH_SIZE_4_MB,
"wio_node": FLASH_SIZE_4_MB,
"xinabox_cw01": FLASH_SIZE_4_MB,
}
ESP8266_LD_SCRIPTS = {
FLASH_SIZE_512_KB: ("eagle.flash.512k0.ld", "eagle.flash.512k.ld"),
FLASH_SIZE_1_MB: ("eagle.flash.1m0.ld", "eagle.flash.1m.ld"),
FLASH_SIZE_2_MB: ("eagle.flash.2m.ld", "eagle.flash.2m.ld"),
FLASH_SIZE_4_MB: ("eagle.flash.4m.ld", "eagle.flash.4m.ld"),
FLASH_SIZE_16_MB: ("eagle.flash.16m.ld", "eagle.flash.16m14m.ld"),
}
ESP32_BASE_PINS = {
"TX": 1,
"RX": 3,
@ -1134,19 +925,3 @@ ESP32_BOARD_PINS = {
},
"xinabox_cw02": {"LED": 27},
}
ESP32_C3_BASE_PINS = {
"TX": 21,
"RX": 20,
"ADC1_0": 0,
"ADC1_1": 1,
"ADC1_2": 2,
"ADC1_3": 3,
"ADC1_4": 4,
"ADC2_0": 5,
}
ESP32_C3_BOARD_PINS = {
"esp32-c3-devkitm-1": {"LED": 8},
"esp32-c3-devkitc-02": "esp32-c3-devkitm-1",
}

View File

@ -0,0 +1,21 @@
import esphome.codegen as cg
KEY_ESP32 = "esp32"
KEY_BOARD = "board"
KEY_VARIANT = "variant"
KEY_SDKCONFIG_OPTIONS = "sdkconfig_options"
VARIANT_ESP32 = "ESP32"
VARIANT_ESP32S2 = "ESP32S2"
VARIANT_ESP32S3 = "ESP32S3"
VARIANT_ESP32C3 = "ESP32C3"
VARIANT_ESP32H2 = "ESP32H2"
VARIANTS = [
VARIANT_ESP32,
VARIANT_ESP32S2,
VARIANT_ESP32S3,
VARIANT_ESP32C3,
VARIANT_ESP32H2,
]
esp32_ns = cg.esphome_ns.namespace("esp32")

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