a bunch of esphome improvements

This commit is contained in:
root
2025-06-12 17:40:40 +12:00
parent dbd1342020
commit 362b8119b4
26 changed files with 4221 additions and 501 deletions

View File

@@ -3,58 +3,72 @@
# MASTER BATHROOM HEATED TOWEL RAIL
# Controlled by a Sonoff Basic
#
# V2.1 2025-06-12 Added select and button to chose modes, added countdown & startup to boost
# V2.0 2025-06-05 YAML Tidyups
# V1.1 2025-04-12 Fixes to timers and offline modes
# V1.0 2025-02-14 Initial Version
#
# INSTRUCTIONS
# - It allows a heated towel rail device to work in a standalone operation
# - On startup, it will turn on for (startup_duration) hours then go into timer mode (this allows you to just turn it on to get some heat immediately)
# - The timer has a morning and evening time (but no weekday/weekend setting)
# - Default values are 5am-7am and 9pm-Midnight (as this suits our use case)
# - It allows the device to work in a standalone timer style operation
# - The timer has a morning and evening time (but no weekday/weekend settings)
# - Default values are set, but changed values are remembered in flash
# - It uses SNTP for time setting (but obviously only if wifi & networking are working)
# - It will default to an internal timer if no wifi. To reset internal timer, reboot the device at 12pm (noon)
# - If on a network and there is a MQTT server, you can set the 4 on/off times via MQTT (See below commands)
# - You can set 4 modes ON/OFF/TIMER/STARTUP via MQTT. That way, you can set to STARTUP for a short boost
# - If on a network and there is a MQTT server, you can set the on/off times via MQTT (See below commands)
# - You can set 4 modes ON/OFF/TIMER/BOOST via MQTT. Setting BOOST gives you a oneshot operation
# - Any new timer times set via MQTT will be remembered though a reboot
# - On a reboot, the device will always turn on for the Startup Duration (STARTUP mode, default 2 hours)
# - TIMER mode will always be switched on after startup mode is complete
# - On startup, or a reboot, the device will always turn on for the BOOST Duration (BOOST mode, default 2 hours)
# - TIMER mode will always be switched on after BOOST mode is complete
# - Home Assistant entities are set so that BOOST mode can be pressed with a button and other modes selectable with a dropdown
# - If you need it ON continuously with no MQTT, toggle power ON/OFF 4 times within 30 seconds (with ~2 secs in between to allow it to boot)
#
# MQTT Commands
# Values will be set in place on the update_interval time, not immediately
# Use 00:00 in 24hr format for time setting. Note there is no weekday/weekend setting
# mqtt_timer_topic/morning-on/06:00 : Time towel rail will go on
# mqtt_timer_topic/morning-off/08:00 : Time towel rail will go off
# mqtt_timer_topic/evening-on/09:00 : Time towel rail will go on
# mqtt_timer_topic/evening-off/00:00 : Time towel rail will go off
# mqtt_timer_topic/operation/ON : Towel rail permanently on
# mqtt_timer_topic/operation/OFF : Towel rail permanently off
# mqtt_timer_topic/operation/TIMER : Towel rail will obey timer settings
# mqtt_timer_topic/operation/STARTUP : Turn on for (startup_duration) hours then TIMER (also on startup)
# Use 00:00 in 24hr format for time setting. (Note there is no weekday/weekend setting)
# mqtt_timer_topic/morning-on/06:00 : Time device will go on
# mqtt_timer_topic/morning-off/08:00 : Time device will go off
# mqtt_timer_topic/evening-on/09:00 : Time device will go on
# mqtt_timer_topic/evening-off/00:00 : Time device will go off
# mqtt_timer_topic/boost-time/0000 : Time in minutes device will temporarily go on for (1-1439)
# mqtt_timer_topic/operation/ON : Device permanently on
# mqtt_timer_topic/operation/OFF : Device permanently off
# mqtt_timer_topic/operation/TIMER : Device will obey timer settings
# mqtt_timer_topic/operation/BOOST : Turn on for (boost_duration) minutes then BOOST (also on startup)
#
#############################################
#############################################
##########################################################################################
##########################################################################################
#############################################
##########################################################################################
# SPECIFIC DEVICE VARIABLE SUBSTITUTIONS
# If NOT using a secrets file, just replace these with the passwords etc (in quotes)
#############################################
##########################################################################################
substitutions:
devicename: "esp-masterbathtowelrail"
# Device Naming
device_name: "esp-masterbathtowelrail"
friendly_name: "Master Bathroom Towelrail"
description_comment: "Sonoff Basic controlling ON/OFF/Timer for the Heated Towel Rail in the Master Bathroom"
device_area: "Main Bathroom" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant.
# Project Naming
project_name: "Sonoff Technologies.Sonoff Basic V1" # Project Details
project_version: "v2.1" # Project V denotes release of yaml file, allowing checking of deployed vs latest version
# Passwords
api_key: !secret esp-masterbathtowelrail_api_key # unfortunately you can't use substitutions inside secrets names
ota_pass: !secret esp-masterbathtowelrail_ota_pass # unfortunately you can't use substitutions inside secrets names
static_ip_address: !secret esp-masterbathtowelrail_ip
log_level: "INFO" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE
update_interval: "60s" # update time for for general sensors etc
room: "Main Bathroom" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant.
#############################################
# SPECIFIC PROJECT VARIABLE SUBSTITUTIONS
#############################################
# Device Settings
log_level: "INFO" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE
update_interval: "10s" # update time for for general sensors etc
# Timer Settings
mqtt_timer_topic: "viewroad-commands/masterbath-towelrail" # Topics you will use to change stuff
startup_duration: "120" # Minutes to stay ON in STARTUP mode before reverting to TIMER
boost_duration_default: "120" # Minutes to stay ON in BOOST mode before reverting to TIMER
morning_on_default: "300" # Default in minutes from midnight. Default 05:00 => 300
morning_off_default: "420" # Default in minutes from midnight. Default 07:00 => 420
evening_on_default: "1260" # Default in minutes from midnight. Default 21:00 => 1260
evening_off_default: "1440" # Default in minutes from midnight. Default 24:00 => 1440 => 1440 is midnight
#############################################
# Included Common Packages
@@ -64,12 +78,12 @@ packages:
common_wifi: !include
file: common/network_common.yaml
vars:
local_static_ip_address: ${static_ip_address}
local_ota_pass: ${ota_pass}
local_static_ip_address: "${static_ip_address}"
local_ota_pass: "${ota_pass}"
common_api: !include
file: common/api_common.yaml
vars:
local_api_key: ${api_key}
local_api_key: "${api_key}"
# common_webportal: !include
# file: common/webportal_common.yaml
common_mqtt: !include
@@ -79,18 +93,18 @@ packages:
common_general_sensors: !include
file: common/sensors_common.yaml
vars:
local_friendly_name: ${friendly_name}
local_update_interval: ${update_interval}
local_friendly_name: "${friendly_name}"
local_update_interval: "${update_interval}"
#############################################
# ESPHome
# https://esphome.io/components/esphome.html
#############################################
esphome:
name: ${devicename}
friendly_name: ${friendly_name}
comment: ${description_comment} # Appears on the esphome page in HA
area: "${room}"
name: "${device_name}"
friendly_name: "${friendly_name}"
comment: "${description_comment}" # Appears on the esphome page in HA
area: "${device_area}"
on_boot:
priority: 900 # High priority to run after globals are initialized
then:
@@ -127,9 +141,9 @@ esphome:
ESP_LOGI("power_cycle", "Detected 4 power cycles in 20s => Forcing ON mode");
} else {
// Otherwise do your normal startup logic:
id(operation_mode) = 3; // on_boot -> sets operation_mode = 3 (STARTUP)
id(startup_timer) = 0; // and reset startup_timer = 0 (for time sync if no sntp)
ESP_LOGI("power_cycle", "Boot count=%d => STARTUP mode", id(boot_count));
id(operation_mode) = 3; // on_boot -> sets operation_mode = 3 (BOOST)
id(boost_timer) = 0; // and reset boost_timer = 0 (for time sync if no sntp)
ESP_LOGI("power_cycle", "Boot count=%d => BOOST mode", id(boot_count));
}
#############################################
@@ -138,13 +152,20 @@ esphome:
#############################################
esp8266:
board: esp01_1m # The original sonoff basic
restore_from_flash: true # restore some values on reboot
preferences:
flash_write_interval: 5min
mdns:
disabled: false
#############################################
# ESPHome Logging Enable
# https://esphome.io/components/logger.html
#############################################
logger:
level: ${log_level} #INFO Level suggested, or DEBUG for testing
level: "${log_level}" #INFO Level suggested, or DEBUG for testing
#baud_rate: 0 #set to 0 for no logging via UART, needed if you are using it for other serial things (eg PZEM)
#esp8266_store_log_strings_in_flash: false
#tx_buffer_size: 64
@@ -168,39 +189,41 @@ globals:
initial_value: "0"
# Morning On time (minutes from midnight),
# default 05:00 => 300
- id: morning_on
type: int
restore_value: true
initial_value: "300"
initial_value: "${morning_on_default}"
# Morning Off time (minutes from midnight),
# default 07:00 => 420
- id: morning_off
type: int
restore_value: true
initial_value: "420"
initial_value: "${morning_off_default}"
# Evening On time (minutes from midnight),
# default 21:00 => 1260
- id: evening_on
type: int
restore_value: true
initial_value: "1260"
initial_value: "${morning_off_default}"
# Evening Off time (minutes from midnight),
# default 24:00 => 1440 => treat as midnight
- id: evening_off
type: int
restore_value: true
initial_value: "1440"
initial_value: "${morning_off_default}"
# Boost Duration (minutes),
- id: boost_duration
type: int
restore_value: true
initial_value: "${boost_duration_default}"
####################################################
# operation_mode:
# 0 = OFF
# 1 = ON
# 2 = TIMER
# 3 = STARTUP
# 3 = BOOST
####################################################
- id: operation_mode
type: int
@@ -219,16 +242,15 @@ globals:
initial_value: "720" # 720 is 12:00 Noon
####################################################
# startup_timer: counts minutes in STARTUP mode
# After 'startup_duration' minutes, revert to TIMER.
# boost_timer: counts minutes in BOOST mode
# After 'boost_duration' minutes, revert to TIMER.
# Not restored, so each boot starts fresh at 0.
####################################################
- id: startup_timer
- id: boost_timer
type: int
restore_value: false
initial_value: "0"
#############################################
# Text Sensors
# https://esphome.io/components/text_sensor/index.html
@@ -319,15 +341,37 @@ text_sensor:
ESP_LOGW("timer","Invalid Evening Off format: %s", x.c_str());
}
####################################################
# Boost duration => 1 - 1439
####################################################
- platform: mqtt_subscribe
name: "Boost Duration"
id: boost_time_topic
topic: "${mqtt_timer_topic}/boost-time" # Stored as an integer from 1-1439
internal: True # No need to show this in Home Assistant as there is a sensor that shows the set value
on_value:
then:
- lambda: |-
// parse as integer
char *endptr;
long v = strtol(x.c_str(), &endptr, 10);
// invalid if nothing parsed, trailing chars, or out of 01439
if (endptr == x.c_str() || *endptr != '\0' || v < 0 || v > 1439) {
ESP_LOGE("boost_time", "Invalid boost_time '%s'", x.c_str());
} else {
id(boost_duration) = static_cast<int>(v);
}
####################################################
# Subscribe to operation mode:
# OFF, ON, TIMER, STARTUP
# OFF, ON, TIMER, BOOST
# We do case-insensitive compare using strcasecmp
# (Requires <strings.h> typically included in ESPHome)
####################################################
- platform: mqtt_subscribe
name: "Operation Mode Setting"
id: timer_operation_mode_topic
topic: "${mqtt_timer_topic}/operation" # STARTUP,ON,OFF,TIMER
topic: "${mqtt_timer_topic}/operation" # BOOST,ON,OFF,TIMER
internal: True # No need to show this in Home Assistant as there is a sensor that shows the set value
on_value:
then:
@@ -346,29 +390,29 @@ text_sensor:
} else if (strcasecmp(x.c_str(), "OFF") == 0) {
id(operation_mode) = 0;
ESP_LOGI("timer","Operation mode set to OFF");
} else if (strcasecmp(x.c_str(), "STARTUP") == 0) {
} else if (strcasecmp(x.c_str(), "BOOST") == 0) {
id(operation_mode) = 3;
id(startup_timer) = 0; // Reset the startup timer to zero
ESP_LOGI("timer","Operation mode set to STARTUP");
id(boost_timer) = 0; // Reset the BOOST timer to zero
ESP_LOGI("timer","Operation mode set to BOOST");
} else {
ESP_LOGW("timer","Invalid operation mode: %s", x.c_str());
}
######################################################
# Expose the current operation mode (OFF, ON, TIMER, STARTUP)
# Expose the current operation mode (OFF, ON, TIMER, BOOST)
######################################################
- platform: template
name: "Operation Mode State"
lambda: |-
// 0=OFF, 1=ON, 2=TIMER, 3=STARTUP
// 0=OFF, 1=ON, 2=TIMER, 3=BOOST
switch (id(operation_mode)) {
case 0: return {"OFF"};
case 1: return {"ON"};
case 2: return {"TIMER"};
case 3: return {"STARTUP"};
case 3: return {"BOOST"};
default: return {"UNKNOWN"};
}
update_interval: ${update_interval}
update_interval: 5s
######################################################
# Expose the "Morning On" time as a text (HH:MM)
@@ -382,7 +426,7 @@ text_sensor:
char buff[16];
snprintf(buff, sizeof(buff), "%02d:%02d", hour, minute);
return { std::string(buff) };
update_interval: ${update_interval}
update_interval: "${update_interval}"
######################################################
# Expose the "Morning Off" time as a text (HH:MM)
@@ -397,7 +441,7 @@ text_sensor:
char buff[16];
snprintf(buff, sizeof(buff), "%02d:%02d", hour, minute);
return { std::string(buff) };
update_interval: ${update_interval}
update_interval: "${update_interval}"
######################################################
# Expose the "Evening On" time as a text (HH:MM)
@@ -412,7 +456,7 @@ text_sensor:
char buff[16];
snprintf(buff, sizeof(buff), "%02d:%02d", hour, minute);
return { std::string(buff) };
update_interval: ${update_interval}
update_interval: "${update_interval}"
######################################################
# Expose the "Evening Off" time as a text (HH:MM)
@@ -427,7 +471,17 @@ text_sensor:
char buff[16];
snprintf(buff, sizeof(buff), "%02d:%02d", hour, minute);
return { std::string(buff) };
update_interval: ${update_interval}
update_interval: "${update_interval}"
######################################################
# Expose the "Boost time" time as text (HH:MM)
######################################################
- platform: template
name: "Timeclock: Boost Time"
lambda: |-
// e.g. "120 Mins"
return std::to_string(id(boost_duration)) + " Mins";
update_interval: "${update_interval}"
#############################################
# Sensors
@@ -438,11 +492,37 @@ sensor:
name: "Mins from Midnight"
unit_of_measurement: "mins"
accuracy_decimals: 0
update_interval: ${update_interval}
update_interval: "${update_interval}"
internal: True
lambda: |-
return id(current_mins);
# A value in mins if a timer is running showing how many mins left
- platform: template
name: "Timer Minutes Remaining"
id: timer_minutes_remaining
unit_of_measurement: "Mins"
update_interval: 5s
accuracy_decimals: "0"
lambda: |-
// always zero if relay is off
if (!id(relay).state) {
return 0;
}
int rem = 0;
// only calculate for mode 2 (scheduled) or mode 3 (BOOST)
if (id(operation_mode) == 2) {
int a = id(morning_off) - id(current_mins);
int b = id(evening_off) - id(current_mins);
// if a is negative, use b; otherwise pick the smaller of a or b
rem = (a < 0) ? b : (a < b ? a : b);
}
else if (id(operation_mode) == 3) {
rem = id(boost_duration) - id(boost_timer);
}
// never return negative
return rem > 0 ? rem : 0;
####################################################
# Relay Switch (Sonoff Basic Relay on GPIO12)
####################################################
@@ -453,6 +533,62 @@ switch:
id: relay
restore_mode: RESTORE_DEFAULT_OFF
#################################################################################################
# BUTTON COMPONENT
# https://esphome.io/components/button/index.html
#################################################################################################
button:
- platform: template
name: "Boost now"
id: boost_button
icon: "mdi:play-circle-outline" # optional, pick any MaterialDesign icon you like
on_press:
then:
# 1) set the mode to BOOST (3)
- lambda: |-
id(boost_timer) = 0; // Reset the BOOST timer to zero
id(operation_mode) = 3; // Set to BOOST
ESP_LOGD("main", "operation_mode set to %d via BOOST button", id(operation_mode));
# 2) turn on the relay switch
- switch.turn_on:
id: relay
#################################################################################################
# SELECT COMPONENT
# https://esphome.io/components/select/index.html
#################################################################################################
select:
- platform: template
name: "Operation Mode"
id: operation_mode_select
update_interval: 5s # poll every 5 s for external changes
options:
- "OFF"
- "ON"
- "TIMER"
- "BOOST"
# Getter: maps your integer into one of the four strings
lambda: |-
switch (id(operation_mode)) {
case 1: return std::string("ON");
case 2: return std::string("TIMER");
case 3: return std::string("BOOST");
default: return std::string("OFF");
}
# set_action: called when you pick an option in HA
set_action:
- lambda: |-
if (x == "OFF") id(operation_mode) = 0;
else if (x == "ON") id(operation_mode) = 1;
else if (x == "TIMER") id(operation_mode) = 2;
else {
id(boost_timer) = 0; // Reset the BOOST timer to zero
id(operation_mode) = 3; /* BOOST */
}
ESP_LOGD("main", "operation_mode set to %d", id(operation_mode));
####################################################
# Check every minute to decide relay state
####################################################
@@ -482,26 +618,26 @@ interval:
// 0 = OFF
// 1 = ON
// 2 = TIMER
// 3 = STARTUP
// 3 = BOOST
int mode = id(operation_mode);
//////////////////////////////////////////////////
// STARTUP MODE: Relay ON for 'startup_duration'
// BOOST MODE: Relay ON for 'boost_duration'
// minutes, then automatically revert to TIMER.
//////////////////////////////////////////////////
if (mode == 3) {
id(startup_timer) = id(startup_timer) + 1 ; // works as long as update_interval in seconds
// Compare with the substitution startup_duration
if (id(startup_timer) < (int) ${startup_duration}) {
// Still within the STARTUP period => turn relay on
id(boost_timer) = id(boost_timer) + 1 ; // works as long as update_interval in seconds
// Compare with the substitution boost_duration
if (id(boost_timer) < id(boost_duration)) {
// Still within the BOOST period => turn relay on
id(relay).turn_on();
} else {
// After 'startup_duration' minutes => switch to TIMER
// After 'boost_duration' minutes => switch to TIMER
id(operation_mode) = 2;
id(mqtt_client).publish("${mqtt_timer_topic}/operation", "TIMER");
}
// Skip the rest of the logic
ESP_LOGI("startup_timer", "startup_timer=%d", id(startup_timer));
ESP_LOGI("boost_timer", "boost_timer=%d", id(boost_timer));
return;
}