Compare commits

..
Author SHA1 Message Date
J. Nick Koston b94440ef46 Merge remote-tracking branch 'origin/dev' into HEAD 2026-11-14 08:39:21 -06:00
J. Nick Koston 5fe744a30e Merge branch 'dev' into time-cron-callback 2026-11-04 20:56:45 -06:00
J. Nick Koston 3a5a7ba6d3 [time] Expect the direct action call in the on_time codegen test 2026-11-04 20:54:06 -06:00
J. Nick Koston bc4cbe6c51 Merge remote-tracking branch 'origin/dev' into time-cron-callback
# Conflicts:
#	esphome/core/defines.h
2026-11-04 20:51:14 -06:00
J. Nick Koston 7123d83a30 Merge dev into time-cron-callback 2026-10-29 07:14:38 -10:00
J. Nick Koston 84fbf1a933 [time] Test that an every-second schedule generates no check 2026-10-28 22:01:19 -10:00
J. Nick Koston 29e98feabe [time] Validate the dict form of at: through the cron field validators 2026-10-28 21:34:03 -10:00
J. Nick Koston 7d972192fc [time] Check the on_time callback slot count per clock in the codegen tests 2026-10-28 17:53:39 -10:00
J. Nick Koston dc238ba271 [time] Normalise on_time list values in the validator and pass fields to the check builder 2026-10-28 17:53:00 -10:00
J. Nick Koston 1681f7790d [time] Keep the last on_time check as a 32-bit epoch and reuse ESPTime::from_epoch_local 2026-10-28 17:52:59 -10:00
J. Nick Koston 359e439b18 [time] Generate on_time checks as a value compare or a mask only 2026-10-28 17:33:39 -10:00
J. Nick Koston 19ee9db1cf Merge branch 'time-cron-tests' into time-cron-callback
# Conflicts:
#	tests/components/time/on_time.cpp
2026-10-28 16:59:51 -10:00
J. Nick Koston 57294a4499 Include the time headers before the final macro so it only reaches automation.h 2026-10-28 16:59:37 -10:00
J. Nick Koston 4ce89e21cc Merge branch 'time-cron-tests' into time-cron-callback 2026-10-28 16:37:58 -10:00
J. Nick Koston aeb099d8a1 [time] Pin the message each rejected on_time schedule fails with 2026-10-28 16:37:58 -10:00
J. Nick Koston e3563c3799 Note in the description why removing the codegen-only classes is not breaking 2026-10-28 16:36:24 -10:00
J. Nick Koston c0f0c61c54 [time] Generate numeric on_time checks for true/false list values 2026-10-28 16:16:30 -10:00
J. Nick Koston aebf8cf78f Merge branch 'time-cron-tests' into time-cron-callback
# Conflicts:
#	tests/components/time/on_time.cpp
2026-10-28 16:16:17 -10:00
J. Nick Koston 9d6a805343 [time] Name the on_time test fixture's protected methods with a trailing underscore 2026-10-28 16:15:55 -10:00
J. Nick Koston 9497ea0345 [time] Size the on_time callback list at compile time and build validators from the field table
Each clock holds a fixed array sized by the most on_time automations on any clock,
instead of a heap-allocated list. The schedule field table now carries the month and
weekday names, so the validators are built from named fields.
2026-10-28 15:49:38 -10:00
J. Nick Koston 13457001c3 Merge branch 'time-cron-tests' into time-cron-callback
# Conflicts:
#	tests/component_tests/time/test_on_time.py
2026-10-28 15:45:52 -10:00
J. Nick Koston 06bdedd3ff [time] Use CRON_KEYS in the on_time schedule test 2026-10-28 15:45:42 -10:00
J. Nick Koston 38b86769b3 Restore the test name the helper rename changed 2026-10-28 15:17:05 -10:00
J. Nick Koston ce4baa22c0 [time] Restore the start_on_time_checks name broken by the on_time_check rename 2026-10-28 15:15:57 -10:00
J. Nick Koston db8c32fe00 Merge branch 'time-cron-tests' into time-cron-callback
# Conflicts:
#	tests/components/time/on_time.cpp
2026-10-28 15:14:51 -10:00
J. Nick Koston 783cb8e449 [time] Size on_time masks by the field range and keep empty lists never matching 2026-10-28 15:14:34 -10:00
J. Nick Koston 23b82c7c22 [time] Run on_time tests in UTC and use the cron/at key constants 2026-10-28 15:13:36 -10:00
J. Nick Koston 330ac831fc [time] Trim per-clock on_time state and use masks for schedule lists
Clocks keep a lazy callback list and the last checked epoch instead of a full ESPTime, and
the once-a-second check is started from code generation only for clocks with on_time.
Schedule lists that are not a single value or run use a bit mask, avoiding a software
divide on ESP8266. One field table drives the keys, validator ranges and checks.
2026-10-28 14:16:13 -10:00
J. Nick Koston 98ba538a29 [time] Name on_time in the build test log message 2026-10-28 14:08:28 -10:00
J. Nick Koston 69621497b1 Merge branch 'time-cron-tests' into time-cron-callback 2026-10-28 14:08:28 -10:00
J. Nick Koston 93b7ca3bdd [time] Run on_time from one clock check with generated schedule checks
Each on_time was an 80 byte CronTrigger component with six bitsets filled at boot and its
own 1 s interval. The clock now owns the single interval and time jump handling, and each
on_time is a callback whose schedule check is generated at compile time.
2026-10-28 13:56:40 -10:00
J. Nick Koston a708742c5e [time] Add tests for on_time schedules and time jump handling 2026-10-28 13:30:32 -10:00
32 changed files with 794 additions and 454 deletions

No files matched your search

-1
View File
@@ -26,7 +26,6 @@ esphome/components/ade7953_base/* @angelnu
esphome/components/ade7953_i2c/* @angelnu
esphome/components/ade7953_spi/* @angelnu
esphome/components/ads1118/* @solomondg1
esphome/components/ads1xxx/* @bdraco
esphome/components/ags10/* @mak-42
esphome/components/aic3204/* @kbx81
esphome/components/airthings_ble/* @jeromelaban
+3 -2
View File
@@ -3,7 +3,6 @@ from esphome.components import i2c
import esphome.config_validation as cv
from esphome.types import ConfigType
AUTO_LOAD = ["ads1xxx"]
DEPENDENCIES = ["i2c"]
DOMAIN = "ads1115"
MULTI_CONF = True
@@ -27,4 +26,6 @@ CONFIG_SCHEMA = (
async def to_code(config: ConfigType) -> None:
await i2c.new_i2c_component(config, config[CONF_CONTINUOUS_MODE])
var = await i2c.new_i2c_component(config)
cg.add(var.set_continuous_mode(config[CONF_CONTINUOUS_MODE]))
+163 -19
View File
@@ -1,19 +1,61 @@
#include "ads1115.h"
#include "esphome/components/ads1xxx/ads1xxx.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
namespace esphome::ads1115 {
ESPHOME_LOG_TAG(TAG, "ads1115");
static constexpr uint8_t REGISTER_CONVERSION = 0x00;
static constexpr uint8_t REGISTER_CONFIG = 0x01;
static constexpr uint16_t CONFIG_COMPARATOR_DISABLE = 0b11;
static const uint8_t ADS1115_REGISTER_CONVERSION = 0x00;
static const uint8_t ADS1115_REGISTER_CONFIG = 0x01;
void ADS1115Component::setup() {
const uint16_t config = ads1xxx::CONFIG_DATA_RATE | CONFIG_COMPARATOR_DISABLE |
(this->continuous_mode_ ? 0 : ads1xxx::CONFIG_SINGLE_SHOT);
if (!this->setup_check(this->write_byte_16(REGISTER_CONFIG, config)))
uint16_t value;
if (!this->setup_check(this->read_byte_16(ADS1115_REGISTER_CONVERSION, &value)))
return;
uint16_t config = 0;
// Clear single-shot bit
// 0b0xxxxxxxxxxxxxxx
config |= 0b0000000000000000;
// Setup multiplexer
// 0bx000xxxxxxxxxxxx
config |= ADS1115_MULTIPLEXER_P0_N1 << 12;
// Setup Gain
// 0bxxxx000xxxxxxxxx
config |= ADS1115_GAIN_6P144 << 9;
if (this->continuous_mode_) {
// Set continuous mode
// 0bxxxxxxx0xxxxxxxx
config |= 0b0000000000000000;
} else {
// Set singleshot mode
// 0bxxxxxxx1xxxxxxxx
config |= 0b0000000100000000;
}
// Set data rate - 860 samples per second
// 0bxxxxxxxx100xxxxx
config |= ADS1115_860SPS << 5;
// Set comparator mode - hysteresis
// 0bxxxxxxxxxxx0xxxx
config |= 0b0000000000000000;
// Set comparator polarity - active low
// 0bxxxxxxxxxxxx0xxx
config |= 0b0000000000000000;
// Set comparator latch enabled - false
// 0bxxxxxxxxxxxxx0xx
config |= 0b0000000000000000;
// Set comparator que mode - disabled
// 0bxxxxxxxxxxxxxx11
config |= 0b0000000000000011;
if (!this->setup_check(this->write_byte_16(ADS1115_REGISTER_CONFIG, config)))
return;
this->prev_config_ = config;
}
@@ -21,23 +63,92 @@ void ADS1115Component::dump_config() {
ESP_LOGCONFIG(TAG, "ADS1115:");
LOG_I2C_DEVICE(this);
}
float ADS1115Component::request_measurement(uint16_t config_bits, uint8_t conversion_delay_ms) {
const uint16_t config = CONFIG_COMPARATOR_DISABLE | config_bits |
(this->continuous_mode_ ? 0 : ads1xxx::CONFIG_SINGLE_SHOT | ads1xxx::CONFIG_START);
float ADS1115Component::request_measurement(ADS1115Multiplexer multiplexer, ADS1115Gain gain,
ADS1115Resolution resolution, ADS1115Samplerate samplerate) {
uint16_t config = this->prev_config_;
// Multiplexer
// 0bxBBBxxxxxxxxxxxx
config &= 0b1000111111111111;
config |= (multiplexer & 0b111) << 12;
// Gain
// 0bxxxxBBBxxxxxxxxx
config &= 0b1111000111111111;
config |= (gain & 0b111) << 9;
// Sample rate
// 0bxxxxxxxxBBBxxxxx
config &= 0b1111111100011111;
config |= (samplerate & 0b111) << 5;
if (!this->continuous_mode_) {
// Start conversion
config |= 0b1000000000000000;
}
if (!this->continuous_mode_ || this->prev_config_ != config) {
if (!this->status_comm_check(this->write_byte_16(REGISTER_CONFIG, config)))
if (!this->status_comm_check(this->write_byte_16(ADS1115_REGISTER_CONFIG, config)))
return NAN;
this->prev_config_ = config;
delay(conversion_delay_ms);
// In continuous mode the delay alone covers a conversion with the new settings
// Delay calculated as: ceil((1000/SPS)+.5)
if (resolution == ADS1015_12_BITS) {
switch (samplerate) {
case ADS1115_8SPS:
delay(9);
break;
case ADS1115_16SPS:
delay(5);
break;
case ADS1115_32SPS:
delay(3);
break;
case ADS1115_64SPS:
case ADS1115_128SPS:
delay(2);
break;
default:
delay(1);
break;
}
} else {
switch (samplerate) {
case ADS1115_8SPS:
delay(126); // NOLINT
break;
case ADS1115_16SPS:
delay(63); // NOLINT
break;
case ADS1115_32SPS:
delay(32);
break;
case ADS1115_64SPS:
delay(17);
break;
case ADS1115_128SPS:
delay(9);
break;
case ADS1115_250SPS:
delay(5);
break;
case ADS1115_475SPS:
delay(3);
break;
case ADS1115_860SPS:
delay(2);
break;
}
}
// in continuous mode, conversion will always be running, rely on the delay
// to ensure conversion is taking place with the correct settings
// can we use the rdy pin to trigger when a conversion is done?
if (!this->continuous_mode_) {
uint32_t start = millis();
uint16_t status;
while (this->read_byte_16(REGISTER_CONFIG, &status) && (status & ads1xxx::CONFIG_START) == 0) {
while (this->read_byte_16(ADS1115_REGISTER_CONFIG, &config) && (config >> 15) == 0) {
if (millis() - start > 100) {
this->status_comm_result(false, LOG_STR("Conversion timed out"));
ESP_LOGW(TAG, "Reading ADS1115 timed out");
this->status_set_warning();
return NAN;
}
yield();
@@ -45,10 +156,43 @@ float ADS1115Component::request_measurement(uint16_t config_bits, uint8_t conver
}
}
uint16_t raw;
if (!this->status_comm_result(this->read_byte_16(REGISTER_CONVERSION, &raw)))
uint16_t raw_conversion;
if (!this->status_comm_result(this->read_byte_16(ADS1115_REGISTER_CONVERSION, &raw_conversion)))
return NAN;
return ads1xxx::to_volts(static_cast<int16_t>(raw), config_bits);
if (resolution == ADS1015_12_BITS) {
// ADS1015 returns 12-bit value left-justified in 16 bits; shift right and sign-extend
raw_conversion = static_cast<uint16_t>(static_cast<int16_t>(raw_conversion) >> (16 - ADS1015_12_BITS));
}
auto signed_conversion = static_cast<int16_t>(raw_conversion);
float millivolts;
float divider = (resolution == ADS1115_16_BITS) ? 32768.0f : 2048.0f;
switch (gain) {
case ADS1115_GAIN_6P144:
millivolts = (signed_conversion * 6144) / divider;
break;
case ADS1115_GAIN_4P096:
millivolts = (signed_conversion * 4096) / divider;
break;
case ADS1115_GAIN_2P048:
millivolts = (signed_conversion * 2048) / divider;
break;
case ADS1115_GAIN_1P024:
millivolts = (signed_conversion * 1024) / divider;
break;
case ADS1115_GAIN_0P512:
millivolts = (signed_conversion * 512) / divider;
break;
case ADS1115_GAIN_0P256:
millivolts = (signed_conversion * 256) / divider;
break;
default:
millivolts = NAN;
}
return millivolts / 1e3f;
}
} // namespace esphome::ads1115
+44 -4
View File
@@ -3,20 +3,60 @@
#include "esphome/components/i2c/i2c.h"
#include "esphome/core/component.h"
#include <vector>
namespace esphome::ads1115 {
enum ADS1115Multiplexer {
ADS1115_MULTIPLEXER_P0_N1 = 0b000,
ADS1115_MULTIPLEXER_P0_N3 = 0b001,
ADS1115_MULTIPLEXER_P1_N3 = 0b010,
ADS1115_MULTIPLEXER_P2_N3 = 0b011,
ADS1115_MULTIPLEXER_P0_NG = 0b100,
ADS1115_MULTIPLEXER_P1_NG = 0b101,
ADS1115_MULTIPLEXER_P2_NG = 0b110,
ADS1115_MULTIPLEXER_P3_NG = 0b111,
};
enum ADS1115Gain {
ADS1115_GAIN_6P144 = 0b000,
ADS1115_GAIN_4P096 = 0b001,
ADS1115_GAIN_2P048 = 0b010,
ADS1115_GAIN_1P024 = 0b011,
ADS1115_GAIN_0P512 = 0b100,
ADS1115_GAIN_0P256 = 0b101,
};
enum ADS1115Resolution {
ADS1115_16_BITS = 16,
ADS1015_12_BITS = 12,
};
enum ADS1115Samplerate {
ADS1115_8SPS = 0b000,
ADS1115_16SPS = 0b001,
ADS1115_32SPS = 0b010,
ADS1115_64SPS = 0b011,
ADS1115_128SPS = 0b100,
ADS1115_250SPS = 0b101,
ADS1115_475SPS = 0b110,
ADS1115_860SPS = 0b111
};
class ADS1115Component final : public Component, public i2c::I2CDevice {
public:
explicit ADS1115Component(bool continuous_mode) : continuous_mode_(continuous_mode) {}
void setup() override;
void dump_config() override;
/// HARDWARE_LATE setup priority
void set_continuous_mode(bool continuous_mode) { continuous_mode_ = continuous_mode; }
/// Returns volts for `config_bits` (multiplexer, gain and data rate fields of the config register).
float request_measurement(uint16_t config_bits, uint8_t conversion_delay_ms);
/// Helper method to request a measurement from a sensor.
float request_measurement(ADS1115Multiplexer multiplexer, ADS1115Gain gain, ADS1115Resolution resolution,
ADS1115Samplerate samplerate);
protected:
uint16_t prev_config_{0};
const bool continuous_mode_;
bool continuous_mode_;
};
} // namespace esphome::ads1115
+50 -14
View File
@@ -1,10 +1,10 @@
import math
import esphome.codegen as cg
from esphome.components import sensor, voltage_sampler
from esphome.components.ads1xxx import MUX_GAIN_SCHEMA, mux_gain_bits
import esphome.config_validation as cv
from esphome.const import (
CONF_GAIN,
CONF_ID,
CONF_MULTIPLEXER,
CONF_RESOLUTION,
CONF_SAMPLE_RATE,
DEVICE_CLASS_VOLTAGE,
@@ -18,13 +18,45 @@ from .. import CONF_ADS1115_ID, ADS1115Component, ads1115_ns
AUTO_LOAD = ["voltage_sampler"]
DEPENDENCIES = ["ads1115"]
RESOLUTION = {"16_BITS": 16, "12_BITS": 12}
# Samples per second of each data rate code; the ADS1015 (12 bits) runs faster
DATA_RATES = {
16: (8, 16, 32, 64, 128, 250, 475, 860),
12: (128, 250, 490, 920, 1600, 2400, 3300, 3300),
ADS1115Multiplexer = ads1115_ns.enum("ADS1115Multiplexer")
MUX = {
"A0_A1": ADS1115Multiplexer.ADS1115_MULTIPLEXER_P0_N1,
"A0_A3": ADS1115Multiplexer.ADS1115_MULTIPLEXER_P0_N3,
"A1_A3": ADS1115Multiplexer.ADS1115_MULTIPLEXER_P1_N3,
"A2_A3": ADS1115Multiplexer.ADS1115_MULTIPLEXER_P2_N3,
"A0_GND": ADS1115Multiplexer.ADS1115_MULTIPLEXER_P0_NG,
"A1_GND": ADS1115Multiplexer.ADS1115_MULTIPLEXER_P1_NG,
"A2_GND": ADS1115Multiplexer.ADS1115_MULTIPLEXER_P2_NG,
"A3_GND": ADS1115Multiplexer.ADS1115_MULTIPLEXER_P3_NG,
}
ADS1115Gain = ads1115_ns.enum("ADS1115Gain")
GAIN = {
"6.144": ADS1115Gain.ADS1115_GAIN_6P144,
"4.096": ADS1115Gain.ADS1115_GAIN_4P096,
"2.048": ADS1115Gain.ADS1115_GAIN_2P048,
"1.024": ADS1115Gain.ADS1115_GAIN_1P024,
"0.512": ADS1115Gain.ADS1115_GAIN_0P512,
"0.256": ADS1115Gain.ADS1115_GAIN_0P256,
}
ADS1115Resolution = ads1115_ns.enum("ADS1115Resolution")
RESOLUTION = {
"16_BITS": ADS1115Resolution.ADS1115_16_BITS,
"12_BITS": ADS1115Resolution.ADS1015_12_BITS,
}
ADS1115Samplerate = ads1115_ns.enum("ADS1115Samplerate")
SAMPLERATE = {
"8": ADS1115Samplerate.ADS1115_8SPS,
"16": ADS1115Samplerate.ADS1115_16SPS,
"32": ADS1115Samplerate.ADS1115_32SPS,
"64": ADS1115Samplerate.ADS1115_64SPS,
"128": ADS1115Samplerate.ADS1115_128SPS,
"250": ADS1115Samplerate.ADS1115_250SPS,
"475": ADS1115Samplerate.ADS1115_475SPS,
"860": ADS1115Samplerate.ADS1115_860SPS,
}
SAMPLERATE = {str(sps): i for i, sps in enumerate(DATA_RATES[16])}
ADS1115Sensor = ads1115_ns.class_(
"ADS1115Sensor", sensor.Sensor, cg.PollingComponent, voltage_sampler.VoltageSampler
@@ -41,7 +73,8 @@ CONFIG_SCHEMA = (
.extend(
{
cv.GenerateID(CONF_ADS1115_ID): cv.use_id(ADS1115Component),
**MUX_GAIN_SCHEMA,
cv.Required(CONF_MULTIPLEXER): cv.enum(MUX, upper=True, space="_"),
cv.Required(CONF_GAIN): cv.enum(GAIN, string=True),
cv.Optional(CONF_RESOLUTION, default="16_BITS"): cv.enum(
RESOLUTION, upper=True, space="_"
),
@@ -55,9 +88,12 @@ CONFIG_SCHEMA = (
async def to_code(config: ConfigType) -> None:
rate = config[CONF_SAMPLE_RATE].enum_value
sps = DATA_RATES[config[CONF_RESOLUTION].enum_value][rate]
delay_ms = math.ceil(1000 / sps + 0.5)
var = await sensor.new_sensor(config, mux_gain_bits(config) | rate << 5, delay_ms)
var = cg.new_Pvariable(config[CONF_ID])
await sensor.register_sensor(var, config)
await cg.register_component(var, config)
await cg.register_parented(var, config[CONF_ADS1115_ID])
cg.add(var.set_multiplexer(config[CONF_MULTIPLEXER]))
cg.add(var.set_gain(config[CONF_GAIN]))
cg.add(var.set_resolution(config[CONF_RESOLUTION]))
cg.add(var.set_samplerate(config[CONF_SAMPLE_RATE]))
@@ -7,7 +7,7 @@ namespace esphome::ads1115 {
ESPHOME_LOG_TAG(TAG, "ads1115.sensor");
float ADS1115Sensor::sample() {
return this->parent_->request_measurement(this->config_bits_, this->conversion_delay_ms_);
return this->parent_->request_measurement(this->multiplexer_, this->gain_, this->resolution_, this->samplerate_);
}
void ADS1115Sensor::update() {
@@ -21,9 +21,11 @@ void ADS1115Sensor::update() {
void ADS1115Sensor::dump_config() {
LOG_SENSOR(" ", "ADS1115 Sensor", this);
ESP_LOGCONFIG(TAG,
" Config: 0x%04X\n"
" Conversion delay: %u ms",
this->config_bits_, this->conversion_delay_ms_);
" Multiplexer: %u\n"
" Gain: %u\n"
" Resolution: %u\n"
" Sample rate: %u",
this->multiplexer_, this->gain_, this->resolution_, this->samplerate_);
}
} // namespace esphome::ads1115
@@ -10,21 +10,26 @@
namespace esphome::ads1115 {
/// Internal holder class that is in instance of Sensor so that the hub can create individual sensors.
class ADS1115Sensor final : public sensor::Sensor,
public PollingComponent,
public voltage_sampler::VoltageSampler,
public Parented<ADS1115Component> {
public:
ADS1115Sensor(uint16_t config_bits, uint8_t conversion_delay_ms)
: config_bits_(config_bits), conversion_delay_ms_(conversion_delay_ms) {}
void update() override;
void set_multiplexer(ADS1115Multiplexer multiplexer) { this->multiplexer_ = multiplexer; }
void set_gain(ADS1115Gain gain) { this->gain_ = gain; }
void set_resolution(ADS1115Resolution resolution) { this->resolution_ = resolution; }
void set_samplerate(ADS1115Samplerate samplerate) { this->samplerate_ = samplerate; }
float sample() override;
void dump_config() override;
protected:
const uint16_t config_bits_;
const uint8_t conversion_delay_ms_;
ADS1115Multiplexer multiplexer_;
ADS1115Gain gain_;
ADS1115Resolution resolution_;
ADS1115Samplerate samplerate_;
};
} // namespace esphome::ads1115
-1
View File
@@ -4,7 +4,6 @@ import esphome.config_validation as cv
from esphome.types import ConfigType
CODEOWNERS = ["@solomondg1"]
AUTO_LOAD = ["ads1xxx"]
DEPENDENCIES = ["spi"]
DOMAIN = "ads1118"
MULTI_CONF = True
+96 -11
View File
@@ -1,25 +1,81 @@
#include "ads1118.h"
#include "esphome/components/ads1xxx/ads1xxx.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
namespace esphome::ads1118 {
ESPHOME_LOG_TAG(TAG, "ads1118");
// DOUT pull-up, NOP 01 (write the config), reserved bit set
static constexpr uint16_t CONFIG_BASE = ads1xxx::CONFIG_SINGLE_SHOT | ads1xxx::CONFIG_DATA_RATE | 0b1011;
static const uint8_t ADS1118_DATA_RATE_860_SPS = 0b111;
void ADS1118::setup() { this->spi_setup(); }
void ADS1118::setup() {
this->spi_setup();
this->config_ = 0;
// Setup multiplexer
// 0bx000xxxxxxxxxxxx
this->config_ |= ADS1118_MULTIPLEXER_P0_NG << 12;
// Setup Gain
// 0bxxxx000xxxxxxxxx
this->config_ |= ADS1118_GAIN_6P144 << 9;
// Set singleshot mode
// 0bxxxxxxx1xxxxxxxx
this->config_ |= 0b0000000100000000;
// Set data rate - 860 samples per second (we're in singleshot mode)
// 0bxxxxxxxx100xxxxx
this->config_ |= ADS1118_DATA_RATE_860_SPS << 5;
// Set temperature sensor mode - ADC
// 0bxxxxxxxxxxx0xxxx
this->config_ |= 0b0000000000000000;
// Set DOUT pull up - enable
// 0bxxxxxxxxxxxx0xxx
this->config_ |= 0b0000000000001000;
// NOP - must be 01
// 0bxxxxxxxxxxxxx01x
this->config_ |= 0b0000000000000010;
// Not used - can be 0 or 1, lets be positive
// 0bxxxxxxxxxxxxxxx1
this->config_ |= 0b0000000000000001;
}
void ADS1118::dump_config() {
ESP_LOGCONFIG(TAG, "ADS1118:");
LOG_PIN(" CS Pin:", this->cs_);
}
float ADS1118::request_measurement(uint16_t config_bits) {
float ADS1118::request_measurement(ADS1118Multiplexer multiplexer, ADS1118Gain gain, bool temperature_mode) {
uint16_t temp_config = this->config_;
// Multiplexer
// 0bxBBBxxxxxxxxxxxx
temp_config &= 0b1000111111111111;
temp_config |= (multiplexer & 0b111) << 12;
// Gain
// 0bxxxxBBBxxxxxxxxx
temp_config &= 0b1111000111111111;
temp_config |= (gain & 0b111) << 9;
if (temperature_mode) {
// Set temperature sensor mode
// 0bxxxxxxxxxxx1xxxx
temp_config |= 0b0000000000010000;
} else {
// Set ADC mode
// 0bxxxxxxxxxxx0xxxx
temp_config &= 0b1111111111101111;
}
// Start conversion
temp_config |= 0b1000000000000000;
this->enable();
this->write_byte16(CONFIG_BASE | ads1xxx::CONFIG_START | config_bits);
this->write_byte16(temp_config);
this->disable();
// about 1.2 ms with 860 samples per second
@@ -29,11 +85,40 @@ float ADS1118::request_measurement(uint16_t config_bits) {
uint8_t adc_first_byte = this->read_byte();
uint8_t adc_second_byte = this->read_byte();
this->disable();
auto raw = static_cast<int16_t>(encode_uint16(adc_first_byte, adc_second_byte));
uint16_t raw_conversion = encode_uint16(adc_first_byte, adc_second_byte);
if (config_bits & CONFIG_TEMPERATURE)
return (raw >> 2) * 0.03125f;
return ads1xxx::to_volts(raw, config_bits);
auto signed_conversion = static_cast<int16_t>(raw_conversion);
if (temperature_mode) {
return (signed_conversion >> 2) * 0.03125f;
} else {
float millivolts;
float divider = 32768.0f;
switch (gain) {
case ADS1118_GAIN_6P144:
millivolts = (signed_conversion * 6144) / divider;
break;
case ADS1118_GAIN_4P096:
millivolts = (signed_conversion * 4096) / divider;
break;
case ADS1118_GAIN_2P048:
millivolts = (signed_conversion * 2048) / divider;
break;
case ADS1118_GAIN_1P024:
millivolts = (signed_conversion * 1024) / divider;
break;
case ADS1118_GAIN_0P512:
millivolts = (signed_conversion * 512) / divider;
break;
case ADS1118_GAIN_0P256:
millivolts = (signed_conversion * 256) / divider;
break;
default:
millivolts = NAN;
}
return millivolts / 1e3f;
}
}
} // namespace esphome::ads1118
+26 -3
View File
@@ -2,19 +2,42 @@
#include "esphome/components/spi/spi.h"
#include "esphome/core/component.h"
#include "esphome/core/hal.h"
namespace esphome::ads1118 {
static constexpr uint16_t CONFIG_TEMPERATURE = 1 << 4;
enum ADS1118Multiplexer {
ADS1118_MULTIPLEXER_P0_N1 = 0b000,
ADS1118_MULTIPLEXER_P0_N3 = 0b001,
ADS1118_MULTIPLEXER_P1_N3 = 0b010,
ADS1118_MULTIPLEXER_P2_N3 = 0b011,
ADS1118_MULTIPLEXER_P0_NG = 0b100,
ADS1118_MULTIPLEXER_P1_NG = 0b101,
ADS1118_MULTIPLEXER_P2_NG = 0b110,
ADS1118_MULTIPLEXER_P3_NG = 0b111,
};
enum ADS1118Gain {
ADS1118_GAIN_6P144 = 0b000,
ADS1118_GAIN_4P096 = 0b001,
ADS1118_GAIN_2P048 = 0b010,
ADS1118_GAIN_1P024 = 0b011,
ADS1118_GAIN_0P512 = 0b100,
ADS1118_GAIN_0P256 = 0b101,
};
class ADS1118 final : public Component,
public spi::SPIDevice<spi::BIT_ORDER_MSB_FIRST, spi::CLOCK_POLARITY_LOW,
spi::CLOCK_PHASE_TRAILING, spi::DATA_RATE_1MHZ> {
public:
ADS1118() = default;
void setup() override;
void dump_config() override;
/// Returns volts, or degrees Celsius when `config_bits` has CONFIG_TEMPERATURE.
float request_measurement(uint16_t config_bits);
/// Helper method to request a measurement from a sensor.
float request_measurement(ADS1118Multiplexer multiplexer, ADS1118Gain gain, bool temperature_mode);
protected:
uint16_t config_{0};
};
} // namespace esphome::ads1118
+34 -8
View File
@@ -1,8 +1,9 @@
import esphome.codegen as cg
from esphome.components import sensor, voltage_sampler
from esphome.components.ads1xxx import MUX_GAIN_SCHEMA, mux_gain_bits
import esphome.config_validation as cv
from esphome.const import (
CONF_GAIN,
CONF_MULTIPLEXER,
CONF_TYPE,
DEVICE_CLASS_TEMPERATURE,
DEVICE_CLASS_VOLTAGE,
@@ -17,6 +18,29 @@ from .. import ADS1118, CONF_ADS1118_ID, ads1118_ns
AUTO_LOAD = ["voltage_sampler"]
DEPENDENCIES = ["ads1118"]
ADS1118Multiplexer = ads1118_ns.enum("ADS1118Multiplexer")
MUX = {
"A0_A1": ADS1118Multiplexer.ADS1118_MULTIPLEXER_P0_N1,
"A0_A3": ADS1118Multiplexer.ADS1118_MULTIPLEXER_P0_N3,
"A1_A3": ADS1118Multiplexer.ADS1118_MULTIPLEXER_P1_N3,
"A2_A3": ADS1118Multiplexer.ADS1118_MULTIPLEXER_P2_N3,
"A0_GND": ADS1118Multiplexer.ADS1118_MULTIPLEXER_P0_NG,
"A1_GND": ADS1118Multiplexer.ADS1118_MULTIPLEXER_P1_NG,
"A2_GND": ADS1118Multiplexer.ADS1118_MULTIPLEXER_P2_NG,
"A3_GND": ADS1118Multiplexer.ADS1118_MULTIPLEXER_P3_NG,
}
ADS1118Gain = ads1118_ns.enum("ADS1118Gain")
GAIN = {
"6.144": ADS1118Gain.ADS1118_GAIN_6P144,
"4.096": ADS1118Gain.ADS1118_GAIN_4P096,
"2.048": ADS1118Gain.ADS1118_GAIN_2P048,
"1.024": ADS1118Gain.ADS1118_GAIN_1P024,
"0.512": ADS1118Gain.ADS1118_GAIN_0P512,
"0.256": ADS1118Gain.ADS1118_GAIN_0P256,
}
ADS1118Sensor = ads1118_ns.class_(
"ADS1118Sensor",
cg.PollingComponent,
@@ -40,7 +64,8 @@ CONFIG_SCHEMA = cv.typed_schema(
.extend(
{
cv.GenerateID(CONF_ADS1118_ID): cv.use_id(ADS1118),
**MUX_GAIN_SCHEMA,
cv.Required(CONF_MULTIPLEXER): cv.enum(MUX, upper=True, space="_"),
cv.Required(CONF_GAIN): cv.enum(GAIN, string=True),
}
)
.extend(cv.polling_component_schema("60s")),
@@ -63,11 +88,12 @@ CONFIG_SCHEMA = cv.typed_schema(
async def to_code(config: ConfigType) -> None:
bits = (
mux_gain_bits(config)
if config[CONF_TYPE] == TYPE_ADC
else ads1118_ns.CONFIG_TEMPERATURE
)
var = await sensor.new_sensor(config, bits)
var = await sensor.new_sensor(config)
await cg.register_component(var, config)
await cg.register_parented(var, config[CONF_ADS1118_ID])
if config[CONF_TYPE] == TYPE_ADC:
cg.add(var.set_multiplexer(config[CONF_MULTIPLEXER]))
cg.add(var.set_gain(config[CONF_GAIN]))
if config[CONF_TYPE] == TYPE_TEMPERATURE:
cg.add(var.set_temperature_mode(True))
@@ -8,10 +8,15 @@ ESPHOME_LOG_TAG(TAG, "ads1118.sensor");
void ADS1118Sensor::dump_config() {
LOG_SENSOR(" ", "ADS1118 Sensor", this);
ESP_LOGCONFIG(TAG, " Config: 0x%04X", this->config_bits_);
ESP_LOGCONFIG(TAG,
" Multiplexer: %u\n"
" Gain: %u",
this->multiplexer_, this->gain_);
}
float ADS1118Sensor::sample() { return this->parent_->request_measurement(this->config_bits_); }
float ADS1118Sensor::sample() {
return this->parent_->request_measurement(this->multiplexer_, this->gain_, this->temperature_mode_);
}
void ADS1118Sensor::update() {
float v = this->sample();
@@ -15,15 +15,20 @@ class ADS1118Sensor final : public PollingComponent,
public voltage_sampler::VoltageSampler,
public Parented<ADS1118> {
public:
explicit ADS1118Sensor(uint16_t config_bits) : config_bits_(config_bits) {}
void update() override;
void set_multiplexer(ADS1118Multiplexer multiplexer) { this->multiplexer_ = multiplexer; }
void set_gain(ADS1118Gain gain) { this->gain_ = gain; }
void set_temperature_mode(bool temp) { this->temperature_mode_ = temp; }
float sample() override;
void dump_config() override;
protected:
const uint16_t config_bits_;
ADS1118Multiplexer multiplexer_{ADS1118_MULTIPLEXER_P0_NG};
ADS1118Gain gain_{ADS1118_GAIN_6P144};
bool temperature_mode_;
};
} // namespace esphome::ads1118
-27
View File
@@ -1,27 +0,0 @@
import esphome.config_validation as cv
from esphome.const import CONF_GAIN, CONF_MULTIPLEXER
from esphome.types import ConfigType
CODEOWNERS = ["@bdraco"]
DOMAIN = "ads1xxx"
_MUX = {
name: i
for i, name in enumerate(
("A0_A1", "A0_A3", "A1_A3", "A2_A3", "A0_GND", "A1_GND", "A2_GND", "A3_GND")
)
}
_GAIN = {
name: i
for i, name in enumerate(("6.144", "4.096", "2.048", "1.024", "0.512", "0.256"))
}
MUX_GAIN_SCHEMA = {
cv.Required(CONF_MULTIPLEXER): cv.enum(_MUX, upper=True, space="_"),
cv.Required(CONF_GAIN): cv.enum(_GAIN, string=True),
}
def mux_gain_bits(config: ConfigType) -> int:
"""Return the multiplexer and gain fields of the config register."""
return config[CONF_MULTIPLEXER].enum_value << 12 | config[CONF_GAIN].enum_value << 9
-19
View File
@@ -1,19 +0,0 @@
#pragma once
#include <cstdint>
namespace esphome::ads1xxx {
// Config register fields shared by the ADS101x, ADS111x and ADS1118
static constexpr uint16_t CONFIG_START = 1 << 15; // reads back as 1 once the conversion is done
static constexpr uint16_t CONFIG_DATA_RATE = 0x00E0; // all bits set is the fastest rate
static constexpr uint16_t CONFIG_SINGLE_SHOT = 1 << 8;
/// Volts for a conversion result taken with the gain field of `config`; 12-bit results are left-justified.
inline float to_volts(int16_t raw, uint16_t config) {
const uint8_t gain = (config >> 9) & 0b111;
// Volts per count: 6.144 V full scale for gain 0, else 8.192 V >> gain
return raw * (gain ? 0.00025f : 0.0001875f) / (1 << gain);
}
} // namespace esphome::ads1xxx
+90 -43
View File
@@ -1,7 +1,9 @@
from collections.abc import Callable
import errno
import functools
from importlib import resources
import logging
from typing import Any, NamedTuple
import tzlocal
@@ -25,7 +27,6 @@ from esphome.const import (
CONF_SECOND,
CONF_SECONDS,
CONF_TIMEZONE,
CONF_TRIGGER_ID,
KEY_CORE,
KEY_FRAMEWORK_VERSION,
PLATFORM_BK72XX,
@@ -38,6 +39,7 @@ from esphome.const import (
)
from esphome.core import CORE, CoroPriority, EsphomeError, coroutine_with_priority
from esphome.helpers import cpp_string_escape
from esphome.types import ConfigType
_LOGGER = logging.getLogger(__name__)
@@ -47,7 +49,7 @@ DOMAIN = "time"
time_ns = cg.esphome_ns.namespace("time")
RealTimeClock = time_ns.class_("RealTimeClock", cg.PollingComponent)
CronTrigger = time_ns.class_("CronTrigger", automation.Trigger.template(), cg.Component)
_request_on_time_slot = cg.slot_counter("TIME_ON_TIME_COUNT")
# C++ types for pre-parsed timezone struct generation
DSTRuleType_cpp = time_ns.enum("DSTRuleType", is_class=True)
@@ -221,7 +223,8 @@ def cron_expression_validator(name, min_value, max_value, special_mapping=None):
raise cv.Invalid(
f"{name} {v} is out of range (min={min_value} max={max_value})."
)
return sorted(value)
# YAML true/false pass as 1/0
return sorted({int(v) for v in value})
value = cv.string(value)
values = set()
for part in value.split(","):
@@ -231,12 +234,28 @@ def cron_expression_validator(name, min_value, max_value, special_mapping=None):
return validator
validate_cron_seconds = cron_expression_validator("seconds", 0, 60)
validate_cron_minutes = cron_expression_validator("minutes", 0, 59)
validate_cron_hours = cron_expression_validator("hours", 0, 23)
validate_cron_days_of_month = cron_expression_validator("days of month", 1, 31)
validate_cron_months = cron_expression_validator(
"months",
class CronField(NamedTuple):
"""An on_time schedule key, the ESPTime member it checks, its value range and value names."""
key: str
member: str
low: int
high: int
names: dict[str, int] | None = None
def validator(self) -> Callable[[Any], list[int]]:
return cron_expression_validator(
self.key.replace("_", " "), self.low, self.high, self.names
)
SECONDS_FIELD = CronField(CONF_SECONDS, "second", 0, 60)
MINUTES_FIELD = CronField(CONF_MINUTES, "minute", 0, 59)
HOURS_FIELD = CronField(CONF_HOURS, "hour", 0, 23)
DAYS_OF_MONTH_FIELD = CronField(CONF_DAYS_OF_MONTH, "day_of_month", 1, 31)
MONTHS_FIELD = CronField(
CONF_MONTHS,
"month",
1,
12,
{
@@ -254,20 +273,29 @@ validate_cron_months = cron_expression_validator(
"DEC": 12,
},
)
validate_cron_days_of_week = cron_expression_validator(
"days of week",
DAYS_OF_WEEK_FIELD = CronField(
CONF_DAYS_OF_WEEK,
"day_of_week",
1,
7,
{"SUN": 1, "MON": 2, "TUE": 3, "WED": 4, "THU": 5, "FRI": 6, "SAT": 7},
)
CRON_KEYS = [
CONF_SECONDS,
CONF_MINUTES,
CONF_HOURS,
CONF_DAYS_OF_MONTH,
CONF_MONTHS,
CONF_DAYS_OF_WEEK,
]
CRON_FIELDS = (
SECONDS_FIELD,
MINUTES_FIELD,
HOURS_FIELD,
DAYS_OF_MONTH_FIELD,
MONTHS_FIELD,
DAYS_OF_WEEK_FIELD,
)
CRON_KEYS = [field.key for field in CRON_FIELDS]
validate_cron_seconds = SECONDS_FIELD.validator()
validate_cron_minutes = MINUTES_FIELD.validator()
validate_cron_hours = HOURS_FIELD.validator()
validate_cron_days_of_month = DAYS_OF_MONTH_FIELD.validator()
validate_cron_months = MONTHS_FIELD.validator()
validate_cron_days_of_week = DAYS_OF_WEEK_FIELD.validator()
def validate_cron_raw(value):
@@ -291,9 +319,9 @@ def validate_cron_raw(value):
def validate_time_at(value):
value = cv.time_of_day(value)
return {
CONF_HOURS: [value[CONF_HOUR]],
CONF_MINUTES: [value[CONF_MINUTE]],
CONF_SECONDS: [value[CONF_SECOND]],
CONF_HOURS: validate_cron_hours([value[CONF_HOUR]]),
CONF_MINUTES: validate_cron_minutes([value[CONF_MINUTE]]),
CONF_SECONDS: validate_cron_seconds([value[CONF_SECOND]]),
CONF_DAYS_OF_MONTH: validate_cron_days_of_month("*"),
CONF_MONTHS: validate_cron_months("*"),
CONF_DAYS_OF_WEEK: validate_cron_days_of_week("*"),
@@ -322,6 +350,33 @@ def validate_cron_keys(value):
return cv.has_at_least_one_key(*CRON_KEYS)(value)
def cron_field_check(field: CronField, values: list[int]) -> str | None:
"""C++ check that valid ``x.<member>`` is one of the validated ``values``; None for the full range.
An empty list never matches, one value is compared, more use a mask as wide as the field's range.
"""
if values == list(range(field.low, field.high + 1)):
return None
if not values:
return "false"
member = f"x.{field.member}"
if len(values) == 1:
return f"{member} == {values[0]}"
mask = sum(1 << value for value in values)
suffix = "ULL" if field.high >= 32 else "U"
return f"(({mask:#x}{suffix} >> {member}) & 1)"
def on_time_check(conf: ConfigType) -> str | None:
checks = []
for field in CRON_FIELDS:
if (values := conf.get(field.key)) is None:
continue
if (check := cron_field_check(field, values)) is not None:
checks.append(check)
return " && ".join(checks) or None
def validate_tz(value: str) -> str:
value = cv.string_strict(value)
@@ -359,7 +414,6 @@ TIME_SCHEMA = cv.Schema(
),
cv.Optional(CONF_ON_TIME): automation.validate_automation(
{
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(CronTrigger),
cv.Optional(CONF_SECONDS): validate_cron_seconds,
cv.Optional(CONF_MINUTES): validate_cron_minutes,
cv.Optional(CONF_HOURS): validate_cron_hours,
@@ -438,23 +492,18 @@ async def setup_time_core_(time_var, config):
cg.add_define("USE_TIME_TRIGGERS")
for conf in on_time:
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], time_var)
seconds = conf.get(CONF_SECONDS, list(range(61)))
cg.add(trigger.add_seconds(seconds))
minutes = conf.get(CONF_MINUTES, list(range(60)))
cg.add(trigger.add_minutes(minutes))
hours = conf.get(CONF_HOURS, list(range(24)))
cg.add(trigger.add_hours(hours))
days_of_month = conf.get(CONF_DAYS_OF_MONTH, list(range(1, 32)))
cg.add(trigger.add_days_of_month(days_of_month))
months = conf.get(CONF_MONTHS, list(range(1, 13)))
cg.add(trigger.add_months(months))
days_of_week = conf.get(CONF_DAYS_OF_WEEK, list(range(1, 8)))
cg.add(trigger.add_days_of_week(days_of_week))
await cg.register_component(trigger, conf)
await automation.build_automation(trigger, [], conf)
_request_on_time_slot(str(time_var))
await automation.build_callback_automation(
time_var,
"add_on_time_callback",
[],
conf,
params=[(cg.ESPTime, "x")],
forward=[],
when=on_time_check(conf),
)
if on_time:
cg.add(time_var.start_on_time_checks())
for conf in config.get(CONF_ON_TIME_SYNC, []):
await automation.build_callback_automation(
@@ -492,11 +541,9 @@ automation.register_apply_condition(
# posix_tz.cpp is fully #ifdef'd on USE_TIME_TIMEZONE, set only when a
# timezone is configured or detected; automation.cpp holds the on_time
# trigger and is #ifdef'd on USE_TIME_TRIGGERS.
# timezone is configured or detected.
FILTER_SOURCE_FILES = filter_source_files_from_defines(
{
"posix_tz.cpp": "USE_TIME_TIMEZONE",
"automation.cpp": "USE_TIME_TRIGGERS",
}
)
-99
View File
@@ -1,99 +0,0 @@
#include "automation.h"
#ifdef USE_TIME_TRIGGERS
#include "esphome/core/log.h"
#include <cinttypes>
namespace esphome::time {
ESPHOME_LOG_TAG(TAG, "automation");
static const int MAX_TIMESTAMP_DRIFT = 900; // how far can the clock drift before we consider
// there has been a drastic time synchronization
void CronTrigger::add_second(uint8_t second) { this->seconds_[second] = true; }
void CronTrigger::add_minute(uint8_t minute) { this->minutes_[minute] = true; }
void CronTrigger::add_hour(uint8_t hour) { this->hours_[hour] = true; }
void CronTrigger::add_day_of_month(uint8_t day_of_month) { this->days_of_month_[day_of_month] = true; }
void CronTrigger::add_month(uint8_t month) { this->months_[month] = true; }
void CronTrigger::add_day_of_week(uint8_t day_of_week) { this->days_of_week_[day_of_week] = true; }
bool CronTrigger::matches(const ESPTime &time) {
return time.is_valid() && this->seconds_[time.second] && this->minutes_[time.minute] && this->hours_[time.hour] &&
this->days_of_month_[time.day_of_month] && this->months_[time.month] && this->days_of_week_[time.day_of_week];
}
void CronTrigger::setup() {
// Cron resolution is 1 second — check once per second instead of every loop iteration
this->set_interval(1000, [this]() { this->check_time_(); });
}
void CronTrigger::check_time_() {
ESPTime time = this->rtc_->now();
if (!time.is_valid())
return;
if (this->last_check_.has_value()) {
auto &last_check = *this->last_check_;
if (last_check > time && last_check.timestamp - time.timestamp > MAX_TIMESTAMP_DRIFT) {
// We went back in time (a lot), probably caused by time synchronization
ESP_LOGW(TAG, "Time has jumped back!");
} else if (last_check >= time) {
// already handled this one
return;
} else if (time > last_check && time.timestamp - last_check.timestamp > MAX_TIMESTAMP_DRIFT) {
// We went ahead in time (a lot), probably caused by time synchronization
ESP_LOGW(TAG, "Time has jumped ahead!");
this->last_check_ = time;
return;
}
while (true) {
last_check.increment_second();
if (last_check >= time)
break;
if (this->matches(last_check))
this->trigger();
}
}
this->last_check_ = time;
if (!time.fields_in_range()) {
ESP_LOGW(TAG, "Time is out of range!");
ESP_LOGD(TAG, "Second=%02u Minute=%02u Hour=%02u DayOfWeek=%u DayOfMonth=%u DayOfYear=%u Month=%u time=%" PRId64,
time.second, time.minute, time.hour, time.day_of_week, time.day_of_month, time.day_of_year, time.month,
(int64_t) time.timestamp);
}
if (this->matches(time))
this->trigger();
}
CronTrigger::CronTrigger(RealTimeClock *rtc) : rtc_(rtc) {}
void CronTrigger::add_seconds(const std::vector<uint8_t> &seconds) {
for (uint8_t it : seconds)
this->add_second(it);
}
void CronTrigger::add_minutes(const std::vector<uint8_t> &minutes) {
for (uint8_t it : minutes)
this->add_minute(it);
}
void CronTrigger::add_hours(const std::vector<uint8_t> &hours) {
for (uint8_t it : hours)
this->add_hour(it);
}
void CronTrigger::add_days_of_month(const std::vector<uint8_t> &days_of_month) {
for (uint8_t it : days_of_month)
this->add_day_of_month(it);
}
void CronTrigger::add_months(const std::vector<uint8_t> &months) {
for (uint8_t it : months)
this->add_month(it);
}
void CronTrigger::add_days_of_week(const std::vector<uint8_t> &days_of_week) {
for (uint8_t it : days_of_week)
this->add_day_of_week(it);
}
float CronTrigger::get_setup_priority() const { return setup_priority::HARDWARE; }
} // namespace esphome::time
#endif // USE_TIME_TRIGGERS
-48
View File
@@ -1,48 +0,0 @@
#pragma once
#include "esphome/core/defines.h"
#ifdef USE_TIME_TRIGGERS
#include "esphome/core/automation.h"
#include "esphome/core/component.h"
#include "esphome/core/time.h"
#include "real_time_clock.h"
#include <vector>
namespace esphome::time {
class CronTrigger final : public Trigger<>, public Component {
public:
explicit CronTrigger(RealTimeClock *rtc);
void add_second(uint8_t second);
void add_seconds(const std::vector<uint8_t> &seconds);
void add_minute(uint8_t minute);
void add_minutes(const std::vector<uint8_t> &minutes);
void add_hour(uint8_t hour);
void add_hours(const std::vector<uint8_t> &hours);
void add_day_of_month(uint8_t day_of_month);
void add_days_of_month(const std::vector<uint8_t> &days_of_month);
void add_month(uint8_t month);
void add_months(const std::vector<uint8_t> &months);
void add_day_of_week(uint8_t day_of_week);
void add_days_of_week(const std::vector<uint8_t> &days_of_week);
bool matches(const ESPTime &time);
void setup() override;
float get_setup_priority() const override;
protected:
void check_time_();
std::bitset<61> seconds_;
std::bitset<60> minutes_;
std::bitset<24> hours_;
std::bitset<32> days_of_month_;
std::bitset<13> months_;
std::bitset<8> days_of_week_;
RealTimeClock *rtc_;
optional<ESPTime> last_check_;
};
} // namespace esphome::time
#endif // USE_TIME_TRIGGERS
+41 -13
View File
@@ -1,5 +1,8 @@
#include "real_time_clock.h"
#include "esphome/core/log.h"
#ifdef USE_TIME_TRIGGERS
#include "esphome/core/application.h"
#endif
#ifdef USE_HOST
#include <sys/time.h>
#elif defined(USE_ZEPHYR)
@@ -23,19 +26,7 @@ ESPHOME_LOG_TAG(TAG, "time");
RealTimeClock::RealTimeClock() = default;
ESPTime __attribute__((noinline)) RealTimeClock::now() {
#ifdef USE_TIME_TIMEZONE
time_t epoch = this->timestamp_now();
struct tm local_tm;
if (epoch_to_local_tm(epoch, get_global_tz(), &local_tm)) {
return ESPTime::from_c_tm(&local_tm, epoch);
}
// Fallback to UTC if parsing failed
return ESPTime::from_epoch_utc(epoch);
#else
return ESPTime::from_epoch_local(this->timestamp_now());
#endif
}
ESPTime __attribute__((noinline)) RealTimeClock::now() { return ESPTime::from_epoch_local(this->timestamp_now()); }
void RealTimeClock::dump_config() {
#ifdef USE_TIME_TIMEZONE
@@ -108,4 +99,41 @@ void RealTimeClock::synchronize_epoch_(uint32_t epoch) {
this->time_sync_callback_.call();
}
#ifdef USE_TIME_TRIGGERS
// How far the clock may move between checks before it counts as a time sync instead of skipped seconds
static constexpr uint32_t MAX_TIMESTAMP_DRIFT = 900;
void RealTimeClock::start_on_time_checks() {
App.scheduler.set_interval(this, 1000, [this]() { this->check_time_(); });
}
void RealTimeClock::check_time_() {
ESPTime time = this->now();
if (!time.is_valid())
return;
const uint32_t epoch = static_cast<uint32_t>(time.timestamp);
const uint32_t last = this->last_check_;
if (last != 0) {
if (last > epoch && last - epoch > MAX_TIMESTAMP_DRIFT) {
ESP_LOGW(TAG, "Time has jumped back!");
} else if (last >= epoch) {
return;
} else if (epoch - last > MAX_TIMESTAMP_DRIFT) {
ESP_LOGW(TAG, "Time has jumped ahead!");
this->last_check_ = epoch;
return;
} else if (epoch - last > 1) {
for (ESPTime skipped = ESPTime::from_epoch_local(last + 1); skipped < time; skipped.increment_second()) {
if (skipped.is_valid())
this->time_callback_.call(skipped);
}
}
}
this->last_check_ = epoch;
this->time_callback_.call(time);
}
#endif
} // namespace esphome::time
+14 -1
View File
@@ -1,6 +1,5 @@
#pragma once
#include <bitset>
#include <cstdlib>
#include "esphome/core/automation.h"
#include "esphome/core/component.h"
@@ -35,6 +34,14 @@ class RealTimeClock : public PollingComponent {
this->time_sync_callback_.add(std::forward<F>(callback));
}
#ifdef USE_TIME_TRIGGERS
/// Called once per second with the local time, and once for each second skipped since the last call
/// (up to 15 minutes; a larger jump is treated as a time sync). Only called with a valid time.
template<typename F> void add_on_time_callback(F &&callback) { this->time_callback_.add(std::forward<F>(callback)); }
/// Start the once-a-second check; it keeps running even if this platform fails setup.
void start_on_time_checks();
#endif
void dump_config() override;
protected:
@@ -42,6 +49,12 @@ class RealTimeClock : public PollingComponent {
void synchronize_epoch_(uint32_t epoch);
LazyCallbackManager<void()> time_sync_callback_;
#ifdef USE_TIME_TRIGGERS
void check_time_();
StaticCallbackManager<TIME_ON_TIME_COUNT, void(const ESPTime &)> time_callback_;
uint32_t last_check_{0}; // epoch, 0 until the first valid time
#endif
};
/// How the weekday byte of a BCD calendar names the day, Sunday first.
+1
View File
@@ -369,6 +369,7 @@
#define USE_TEXT_SENSOR_FILTER_RESET
#define USE_TIME
#define USE_TIME_TRIGGERS
#define TIME_ON_TIME_COUNT 2
#define USE_TM1638_KEYS_PUBLISHER
#define USE_TMP102_BINARY_SENSOR
#define USE_TMP102_CONFIGURE
@@ -0,0 +1,34 @@
esphome:
name: test
esp32:
board: esp32dev
framework:
type: esp-idf
wifi:
ssid: "test_ssid"
password: "test_password"
logger:
api:
time:
- platform: sntp
id: sntp_time
timezone: UTC0
on_time:
- seconds: 0
then:
- logger.log: sntp_first
- seconds: 30
then:
- logger.log: sntp_second
- platform: homeassistant
id: ha_time
timezone: UTC0
on_time:
- seconds: 15
then:
- logger.log: ha_only
+129 -45
View File
@@ -6,17 +6,32 @@ from typing import Any
import pytest
from esphome.components.time import CRON_KEYS, TIME_SCHEMA
from esphome.components.time import (
CRON_KEYS,
DAYS_OF_MONTH_FIELD,
DAYS_OF_WEEK_FIELD,
HOURS_FIELD,
MINUTES_FIELD,
MONTHS_FIELD,
SECONDS_FIELD,
TIME_SCHEMA,
CronField,
cron_field_check,
on_time_check,
)
import esphome.config_validation as cv
from esphome.const import (
CONF_AT,
CONF_CRON,
CONF_DAYS_OF_MONTH,
CONF_DAYS_OF_WEEK,
CONF_HOUR,
CONF_HOURS,
CONF_MINUTE,
CONF_MINUTES,
CONF_MONTHS,
CONF_ON_TIME,
CONF_SECOND,
CONF_SECONDS,
CONF_THEN,
CONF_TIMEZONE,
@@ -138,63 +153,48 @@ def test_on_time_schedule_rejected(
TIME_SCHEMA({CONF_TIMEZONE: "UTC0", CONF_ON_TIME: [{**entry, CONF_THEN: []}]})
ALL_MINUTES = ", ".join(map(str, range(60)))
ALL_HOURS = ", ".join(map(str, range(24)))
ALL_DOM = ", ".join(map(str, range(1, 32)))
ALL_MONTHS_CPP = ", ".join(map(str, range(1, 13)))
def _cron_lines(
var: str,
seconds: str = "0",
minutes: str = ALL_MINUTES,
hours: str = ALL_HOURS,
days_of_month: str = ALL_DOM,
months: str = ALL_MONTHS_CPP,
days_of_week: str = "1, 2, 3, 4, 5, 6, 7",
) -> str:
def _on_time_lines(action: str, check: str) -> str:
return "\n".join(
[
f"new({var}) time::CronTrigger(sntp_time);",
f"{var}->add_seconds({{{seconds}}});",
f"{var}->add_minutes({{{minutes}}});",
f"{var}->add_hours({{{hours}}});",
f"{var}->add_days_of_month({{{days_of_month}}});",
f"{var}->add_months({{{months}}});",
f"{var}->add_days_of_week({{{days_of_week}}});",
"sntp_time->add_on_time_callback([](const std::remove_cvref_t<ESPTime> & x) -> void {",
f" if (!({check}))",
" return;",
f" esphome__{action}__fn();",
]
)
# One entry per on_time automation in config/on_time_fields.yaml, in order.
EXPECTED_ON_TIME_CODE = [
_cron_lines(
"time_crontrigger_id", minutes="0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55"
_on_time_lines(
"lambdaaction_id", "x.second == 0 && ((0x84210842108421ULL >> x.minute) & 1)"
),
_cron_lines(
"time_crontrigger_id_2", minutes="30", hours="7", days_of_week="2, 3, 4, 5, 6"
_on_time_lines(
"lambdaaction_id_2",
"x.second == 0 && x.minute == 30 && x.hour == 7"
" && ((0x7cU >> x.day_of_week) & 1)",
),
_cron_lines("time_crontrigger_id_3", minutes="30", hours="7"),
_cron_lines(
"time_crontrigger_id_4",
minutes="0",
hours="8, 9, 10, 11, 12, 13, 14, 15, 16, 17",
_on_time_lines(
"lambdaaction_id_3", "x.second == 0 && x.minute == 30 && x.hour == 7"
),
_cron_lines(
"time_crontrigger_id_5",
minutes="0",
hours="12",
days_of_month="1, 15",
months="1, 7",
_on_time_lines(
"lambdaaction_id_4",
"x.second == 0 && x.minute == 0 && ((0x3ff00U >> x.hour) & 1)",
),
_cron_lines(
"time_crontrigger_id_6",
minutes="0",
hours="0",
days_of_month="1, 8, 15, 22, 29",
_on_time_lines(
"lambdaaction_id_5",
"x.second == 0 && x.minute == 0 && x.hour == 12"
" && ((0x8002U >> x.day_of_month) & 1) && ((0x82U >> x.month) & 1)",
),
_on_time_lines(
"lambdaaction_id_6",
"x.second == 0 && x.minute == 0 && x.hour == 0"
" && ((0x20408102U >> x.day_of_month) & 1)",
),
_on_time_lines("lambdaaction_id_7", "((0x1000200040008001ULL >> x.second) & 1)"),
_on_time_lines(
"lambdaaction_id_8", "x.second == 0 && ((0x82U >> x.day_of_week) & 1)"
),
_cron_lines("time_crontrigger_id_7", seconds="0, 15, 30, 45, 60"),
_cron_lines("time_crontrigger_id_8", days_of_week="1, 7"),
]
@@ -209,3 +209,87 @@ def test_on_time_generated_code(
found = main_cpp.find(expected, position)
assert found != -1, f"missing or out of order:\n{expected}"
position = found + len(expected)
assert main_cpp.count("sntp_time->start_on_time_checks();") == 1
assert main_cpp.find("sntp_time->start_on_time_checks();", position) != -1
@pytest.mark.parametrize(
("field", "values", "check"),
[
(SECONDS_FIELD, list(range(61)), None),
(DAYS_OF_WEEK_FIELD, list(range(1, 8)), None),
(SECONDS_FIELD, [], "false"),
(MINUTES_FIELD, [30], "x.minute == 30"),
(DAYS_OF_MONTH_FIELD, [31], "x.day_of_month == 31"),
# a 0-60 field takes a 64-bit mask even when every listed value is below 32
(SECONDS_FIELD, [0, 1], "((0x3ULL >> x.second) & 1)"),
(MINUTES_FIELD, [0, 59], "((0x800000000000001ULL >> x.minute) & 1)"),
(HOURS_FIELD, [8, 17], "((0x20100U >> x.hour) & 1)"),
(DAYS_OF_MONTH_FIELD, [1, 31], "((0x80000002U >> x.day_of_month) & 1)"),
(MONTHS_FIELD, [1, 7], "((0x82U >> x.month) & 1)"),
(DAYS_OF_WEEK_FIELD, [2, 3, 4, 5, 6], "((0x7cU >> x.day_of_week) & 1)"),
],
)
def test_cron_field_check(
field: CronField, values: list[int], check: str | None
) -> None:
assert cron_field_check(field, values) == check
def test_empty_field_validates_and_generates(
set_core_config: SetCoreConfigCallable,
) -> None:
set_core_config(PlatformFramework.ESP32_IDF)
config = TIME_SCHEMA(
{CONF_TIMEZONE: "UTC0", CONF_ON_TIME: [{CONF_SECONDS: [], CONF_THEN: []}]}
)
assert on_time_check(config[CONF_ON_TIME][0]) == "false"
def test_list_values_are_deduplicated_ints(
set_core_config: SetCoreConfigCallable,
) -> None:
"""``true``/``false`` in a list have always meant 1/0; the check must be valid C++."""
set_core_config(PlatformFramework.ESP32_IDF)
config = TIME_SCHEMA(
{
CONF_TIMEZONE: "UTC0",
CONF_ON_TIME: [{CONF_SECONDS: [True, False, True], CONF_THEN: []}],
}
)
seconds = config[CONF_ON_TIME][0][CONF_SECONDS]
assert seconds == [0, 1]
assert all(type(value) is int for value in seconds)
def test_at_dict_values_are_ints(set_core_config: SetCoreConfigCallable) -> None:
"""The dict form of ``at`` takes the same path, so ``hour: true`` is checked as 1."""
set_core_config(PlatformFramework.ESP32_IDF)
config = TIME_SCHEMA(
{
CONF_TIMEZONE: "UTC0",
CONF_ON_TIME: [
{
CONF_AT: {CONF_HOUR: True, CONF_MINUTE: 0, CONF_SECOND: 0},
CONF_THEN: [],
}
],
}
)
assert on_time_check(config[CONF_ON_TIME][0]) == (
"x.second == 0 && x.minute == 0 && x.hour == 1"
)
def test_every_second_schedule_has_no_check(
set_core_config: SetCoreConfigCallable,
) -> None:
"""A schedule covering every field's full range fires every second, with no check."""
set_core_config(PlatformFramework.ESP32_IDF)
config = TIME_SCHEMA(
{
CONF_TIMEZONE: "UTC0",
CONF_ON_TIME: [{CONF_CRON: "* * * * * *", CONF_THEN: []}],
}
)
assert on_time_check(config[CONF_ON_TIME][0]) is None
+15 -7
View File
@@ -1,5 +1,5 @@
"""automation.cpp (CronTrigger) is only compiled when an on_time automation
exists, so the define must follow it; on_time_sync needs no class."""
"""The clock's once-a-second on_time check is only compiled when an on_time automation
exists, so the define must follow it; on_time_sync needs no check."""
from collections.abc import Callable
from pathlib import Path
@@ -8,21 +8,29 @@ import pytest
from esphome.core import CORE
from ..helpers import get_define_value
@pytest.mark.parametrize(
("fixture", "emits"),
("fixture", "emits", "slots"),
[
("no_triggers.yaml", False),
("on_time.yaml", True),
("on_time_sync.yaml", False),
("no_triggers.yaml", False, None),
("on_time.yaml", True, "1"),
("on_time_sync.yaml", False, None),
("on_time_fields.yaml", True, "8"),
# the callback list is per clock: its size is the largest count on one clock, not the total
("on_time_two_clocks.yaml", True, "2"),
],
)
def test_triggers_define_follows_automations(
fixture: str,
emits: bool,
slots: str | None,
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
generate_main(component_config_path(fixture))
main_cpp = generate_main(component_config_path(fixture))
defines = {define.name for define in CORE.defines}
assert ("USE_TIME_TRIGGERS" in defines) is emits
assert ("start_on_time_checks()" in main_cpp) is emits
assert get_define_value("TIME_ON_TIME_COUNT") == slots
+2 -15
View File
@@ -1,23 +1,10 @@
ads1115:
- id: ads1115_hub
i2c_id: i2c_bus
address: 0x48
- id: ads1015_hub
i2c_id: i2c_bus
address: 0x49
continuous_mode: true
i2c_id: i2c_bus
address: 0x48
sensor:
- platform: ads1115
ads1115_id: ads1115_hub
multiplexer: A0_A1
gain: 1.024
sample_rate: 128
id: ads1115_sensor
- platform: ads1115
ads1115_id: ads1015_hub
multiplexer: A3_GND
gain: 6.144
resolution: 12_BITS
sample_rate: 8
id: ads1015_sensor
+2 -1
View File
@@ -1,3 +1,4 @@
packages:
i2c: !include ../../test_build_components/common/i2c/esp32-idf.yaml
ads1115: !include common.yaml
<<: !include common.yaml
@@ -1,3 +1,4 @@
packages:
i2c: !include ../../test_build_components/common/i2c/esp8266-ard.yaml
ads1115: !include common.yaml
<<: !include common.yaml
@@ -1,3 +1,4 @@
packages:
i2c: !include ../../test_build_components/common/i2c/nrf52.yaml
ads1115: !include common.yaml
<<: !include common.yaml
@@ -1,3 +1,4 @@
packages:
i2c: !include ../../test_build_components/common/i2c/nrf52.yaml
ads1115: !include common.yaml
<<: !include common.yaml
@@ -1,3 +1,4 @@
packages:
i2c: !include ../../test_build_components/common/i2c/rp2040-ard.yaml
ads1115: !include common.yaml
<<: !include common.yaml
+1
View File
@@ -6,5 +6,6 @@ def override_manifest(manifest: ComponentManifestOverride) -> None:
async def to_code(config):
cg.add_define("USE_TIME_TIMEZONE")
cg.add_define("USE_TIME_TRIGGERS")
cg.add_define("TIME_ON_TIME_COUNT", 1)
manifest.to_code = to_code
+12 -57
View File
@@ -3,19 +3,7 @@
#include <gtest/gtest.h>
#include <bitset>
#include <vector>
#include "esphome/components/time/real_time_clock.h"
#include "esphome/core/automation.h"
#include "esphome/core/component.h"
#include "esphome/core/time.h"
// CronTrigger is final; drop that here so the test can reach check_time_() without the scheduler. Everything else
// is included above, so the macro only reaches this one header.
#define final
#include "esphome/components/time/automation.h"
#undef final
namespace esphome::time::testing {
@@ -24,81 +12,48 @@ static constexpr time_t MONDAY_235958 = 1767657598;
class FakeClock : public RealTimeClock {
public:
using RealTimeClock::check_time_;
time_t timestamp_now() override { return this->epoch; }
void update() override {}
time_t epoch{0};
};
class CountAction : public Action<> {
public:
explicit CountAction(int *count) : count_(count) {}
protected:
void play() override { (*this->count_)++; }
int *count_;
};
class TestCronTrigger : public CronTrigger {
public:
using CronTrigger::check_time_;
using CronTrigger::CronTrigger;
};
class OnTimeTest : public ::testing::Test {
protected:
void SetUp() override {
// Other tests leave their zone set; these times are UTC.
this->saved_tz_ = get_global_tz();
set_global_tz(ParsedTimezone{});
this->automation_.add_action(&this->count_);
}
void TearDown() override { set_global_tz(this->saved_tz_); }
void match_all_fields_except_seconds_() {
for (uint8_t i = 0; i < 60; i++)
this->trigger_.add_minute(i);
for (uint8_t i = 0; i < 24; i++)
this->trigger_.add_hour(i);
for (uint8_t i = 1; i <= 31; i++)
this->trigger_.add_day_of_month(i);
for (uint8_t i = 1; i <= 12; i++)
this->trigger_.add_month(i);
for (uint8_t i = 1; i <= 7; i++)
this->trigger_.add_day_of_week(i);
}
// Each stands in for the check code generation writes for an on_time automation.
void match_every_second_() {
this->match_all_fields_except_seconds_();
for (uint8_t i = 0; i <= 60; i++)
this->trigger_.add_second(i);
this->clock_.add_on_time_callback([this](const ESPTime &) { this->fires_++; });
}
void match_second_(uint8_t second) {
this->match_all_fields_except_seconds_();
this->trigger_.add_second(second);
this->clock_.add_on_time_callback([this, second](const ESPTime &time) {
if (time.second == second)
this->fires_++;
});
}
void match_midnight_on_(uint8_t day_of_week) {
this->trigger_.add_second(0);
this->trigger_.add_minute(0);
this->trigger_.add_hour(0);
for (uint8_t i = 1; i <= 31; i++)
this->trigger_.add_day_of_month(i);
for (uint8_t i = 1; i <= 12; i++)
this->trigger_.add_month(i);
this->trigger_.add_day_of_week(day_of_week);
this->clock_.add_on_time_callback([this, day_of_week](const ESPTime &time) {
if (time.second == 0 && time.minute == 0 && time.hour == 0 && time.day_of_week == day_of_week)
this->fires_++;
});
}
// One pass of the 1 s check with the clock at `epoch`; returns how many times on_time fired.
int tick_(time_t epoch) {
this->clock_.epoch = epoch;
this->fires_ = 0;
this->trigger_.check_time_();
this->clock_.check_time_();
return this->fires_;
}
ParsedTimezone saved_tz_{};
FakeClock clock_;
TestCronTrigger trigger_{&this->clock_};
Automation<> automation_{&this->trigger_};
int fires_{0};
CountAction count_{&this->fires_};
};
TEST_F(OnTimeTest, FiresOnlyOnMatchingSecond) {