esphome device updates

This commit is contained in:
root
2025-09-20 15:18:46 +12:00
parent a27b79fbd9
commit 1e1d0571d9
32 changed files with 3756 additions and 1188 deletions
+237 -150
View File
@@ -1,10 +1,9 @@
##########################################################################################
##########################################################################################
# Title: DOWNSTAIRS KITCHEN - OVER PANTRY LEDS
# Hardware: Sinilink MOSFET Board XY-WFMS (ESP8266) — sometimes listed as “XY-VFMS”
# https://devices.esphome.io/devices/Sinilink-XY-VFMS
# Repo: https://home.fox.co.nz/gitea/zorruno/zorruno-homeassistant/src/branch/master/esphome/esp-downstairskitchleds.yaml
#
# v2.0 - 2025-09-15 A bunch of fixes.
# v1.5 - 2025-09-04 Adopt ramped "Restore Brightness" (0→last non-zero), avoid boot blip (ALWAYS_OFF + high-priority on_boot),
# add flash-write coalescing (persist once at end of ramps), guards for edge cases, and flash_write_interval=5min
# v1.4 - 2025-08-22 Improved power loss/on actions
@@ -14,115 +13,131 @@
# v1.0 - 2025-08-17 First setup (and replacement of Tasmota)
#
# ------------------------------------------
# DEVICE GPIO (Sinilink XY-WFMS)
# ------------------------------------------
# GPIO02 Blue LED (used for ESPHome status)
# GPIO04 MOSFET output (0 V when switched) and Red LED
# GPIO12 Toggle button
# GPIO13 Green LED (used to display fading status)
#
# ------------------------------------------
# OPERATION (as of v1.5)
# OPERATION (as of v2.0)
# ------------------------------------------
# 1. General-purpose LED controller.
# 2. Designed for the Sinilink XY-WFMS board with a MOSFET output (claimed 5A, 5-36 V DC).
# 3. Global setting for MAX % output to extend LED life.
# 4. Minimum output setting; switches fully OFF at/below the minimum to avoid low-PWM flicker.
# 5. PWM frequency is set to 500 Hz by default. You can increase it, but higher values caused
# resets on this device. On ESP32 you can run much higher (~40 kHz).
# 6. Min/Max output settings are not exposed in Home Assistant/MQTT by default, but can be.
# 2. Designed for the Sinilink XY-WFMS board with a MOSFET output (claimed 5A, 5-36 V DC), but will suit similar mosfet boards.
# 3. (In SUBSTITUTIONS) setting for MAX % output to extend LED life (ie can ensure it is only ever 95%)
# 4. (In SUBSTITUTIONS) Minimum output setting; switches fully OFF at/below the minimum to avoid low-PWM flicker.
# 5. (In SUBSTITUTIONS) PWM frequency is set to 1kHz by default. You can increase it, but higher values caused
# resets on Sinilink device. On ESP32 you can run much higher (~40 kHz).
# 6. Min/Max output settings are not exposed in Home Assistant/MQTT by default, but could be.
# With a 1 MB flash, space is tight and only minimal optimisation has been done so far.
# 7. PACKAGES include common items: network settings, diagnostic entities, MQTT, and SNTP (optional).
# 8. Default behaviour:
# 7. (PACKAGES) include common items: network settings, diagnostic entities, MQTT, and SNTP (optional).
# 8. Default behaviours, for recovery from lost power or reset:
# - "Fade up to full": fade from floor to max on boot.
# - "Restore Brightness": fade from floor to the last non-zero brightness on boot (no on/off blip).
# - "Restore Brightness": fade from floor to the last non-zero brightness on boot (should be no on/off blip/flash).
# - "Remain Off": stays off on boot.
# 9. The green LED flashes while fading (different patterns for up/down). The red LED follows the
# output (it shares the MOSFET GPIO).
# output (it shares the MOSFET GPIO). (Obviously this depends on hardware)
# 10. Fade timing scales with the configured values (proportionally when starting mid-brightness).
# 11. Useful 3D-printed case: https://cults3d.com/en/3d-model/tool/snapfit-enclosure-for-esp8266-sinilink-xy-wfms-5v-36v-mosfet-switch-module
# 12. Exposed in Home Assistant/MQTT:
# - Startup action
# 11. Exposed in Home Assistant/MQTT:
# - Startup action (On,Off,Restore)
# - Fade Up / Fade Down / Fade Stop buttons
# - Fade Up/Down switch
# - Fade Up/Down toggle switch
# - Normal On/Off switch (quick ramp up/down)
# - Fade up/down times (0-60s)
# - Output % (pre-gamma) and PWM % (post-gamma)
# - Output Set (1-100, respects min/max)
# - Device diagnostics (from the included package)
# - Output Set (1-100, respects min/max). This also changes with other output so reflects value.
# - Many device diagnostics (from the included 'diagnostics' package)
# - Maximum 'on' time before automatic fade-down (1-48 h, 0 = no limit)
###########################################################################################
# Hardware: Sinilink MOSFET Board XY-WFMS (ESP8266) - sometimes listed as "XY-VFMS"
# https://devices.esphome.io/devices/Sinilink-XY-WFMS
# ------------------------------------------
# DEVICE GPIO (Sinilink XY-WFMS)
# ------------------------------------------
# GPIO02 Blue LED, active-low (used for ESPHome status)
# GPIO04 MOSFET output (0V when switched) and Red LED
# GPIO12 Toggle button
# GPIO13 Green LED (used to display fading status)
#
# 3D-printed case for Sinilink XY-WFMS
# https://cults3d.com/en/3d-model/tool/snapfit-enclosure-for-esp8266-sinilink-xy-wfms-5v-36v-mosfet-switch-module
#
##########################################################################################
##########################################################################################
##########################################################################################
# SPECIFIC DEVICE VARIABLE SUBSTITUTIONS
# If NOT using a secrets file, just replace these with the passwords etc (in quotes)
##########################################################################################
substitutions:
# Device Naming
device_name: "esp-downstairskitchleds"
device_name: "esp-downstairskitchleds" # yaml file should be device_name.yaml
friendly_name: "Downstairs Kitchen LEDs"
description_comment: "Downstairs Kitchen Over Pantry LEDs :: Sinilink XY-WFMS"
device_area: "Downstairs Kitchen" # Allows the ESP device to be automatically linked to an 'Area' in Home Assistant.
# Project Naming
project_name: "Sinilink.XY-WFMS" # Project details
project_version: "v1.5" # Project version denotes release of the YAML file, allowing checking of deployed vs latest version
# Passwords & Secrets
project_name: "Sinilink.XY-WFMS" # Project details. Manufacturer before the dot, device after the dot.
project_version: "v2.0" # Project version denotes release of the YAML file, allowing checking of deployed vs latest version
# Passwords & Secrets (Unfortunately, you can't use substitutions inside secret names)
api_key: !secret esp-api_key
ota_pass: !secret esp-ota_pass
static_ip_address: !secret esp-downstairskitchleds_ip # Unfortunately, you can't use substitutions inside secret names
mqtt_local_command_main_topic: !secret mqtt_local_command_main_topic
mqtt_local_status_main_topic: !secret mqtt_local_status_main_topic
static_ip_address: !secret esp-downstairskitchleds_ip # CHANGE THIS
# MQTT LOCAL Controls
mqtt_local_device_name: "downstairskitchen-pantryleds"
mqtt_local_command_main_topic: !secret mqtt_local_command_main_topic
mqtt_local_status_main_topic: !secret mqtt_local_status_main_topic
mqtt_local_command_topic: "${mqtt_local_command_main_topic}/${mqtt_local_device_name}" # Topic we will use to command this locally without HA
mqtt_local_status_topic: "${mqtt_local_status_main_topic}/${mqtt_local_device_name}" # Topic we will use to view status locally without HA
mqtt_local_device_command_ON: "ON"
mqtt_local_device_command_OFF: "OFF"
# Device Specific Settings
log_level: "NONE" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (default), VERBOSE, VERY_VERBOSE
update_interval: "20s" # Update time for general sensors, etc.
led_gamma: "1.2" # Gamma from 1.2-3 is sensible to normalise the LED fading vs PWM
minimum_led_output: "1" # % If at this value or below, we'll switch it completely off
maximum_led_output: "90" # % Maximum output; it is sometimes nice to limit the output for longevity or aesthetics
max_on_default_hours: "6" # The maximum time the LEDs will be on, in case they get left on. 0 = no automatic turn-off
log_level: "NONE" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (default), VERBOSE, VERY_VERBOSE
update_interval: "20s" # Update time for general sensors, etc.
led_gamma: "1.2" # Gamma from 1.2-3 is sensible to normalise the LED fading vs PWM
minimum_led_output: "1" # % If at this value or below, we'll switch it completely off
maximum_led_output: "90" # % Maximum output; it is sometimes nice to limit the output for longevity or aesthetics
max_on_default_hours: "24" # The maximum time the LEDs will be on, in case they get left on. 0 = no automatic turn-off
pwm_frequency: "1000hz" # PWM output Frequency. High enough to avoid audible/visible artifacts
# Device Specific GPIO (so we can easily update for other devices)
device_status_led: GPIO02
device_mosfet_out: GPIO04
device_usr_button: GPIO12
device_fading_led: GPIO13
##########################################################################################
# PACKAGES: Included Common Packages
# https://esphome.io/components/packages.html
##########################################################################################
packages:
#### WIFI, Network (Static/DHCP/IPV6 etc), Fallback AP, Safemode ####
common_wifi: !include
file: common/network_common.yaml
vars:
local_device_name: "${device_name}"
local_static_ip_address: "${static_ip_address}"
local_ota_pass: "${ota_pass}"
#### HOME ASSISTANT API (choose encryption or no encryption options) ####
common_api: !include
file: common/api_common.yaml
#file: common/api_common_noencryption.yaml
vars:
local_api_key: "${api_key}"
#common_webportal: !include
# file: common/webportal_common.yaml
#### MQTT ####
common_mqtt: !include
file: common/mqtt_common.yaml
vars:
local_device_name: "${device_name}"
#common_sntp: !include
# file: common/sntp_common.yaml
common_general_sensors: !include
file: common/sensors_common.yaml
#file: common/sensors_common_lite.yaml
vars:
local_friendly_name: "${friendly_name}"
local_update_interval: "${update_interval}"
#### WEB PORTAL ####
#common_webportal: !include common/webportal_common.yaml
#### SNTP (Only use if you want/need accurate timeclocks) ####
#common_sntp: !include common/sntp_common.yaml
#### DIAGNOSTICS Sensors ####
diag_basic: !include common/include_basic_diag_sensors.yaml
diag_more: !include common/include_more_diag_sensors.yaml
diag_debug: !include common/include_debug_diag_sensors.yaml
diag_resetcount: !include common/include_resetcount_diag_sensors.yaml
##########################################################################################
# ESPHome CORE CONFIGURATION
@@ -134,7 +149,8 @@ esphome:
comment: "${description_comment}"
area: "${device_area}"
on_boot:
priority: 600
# Run later so everything is initialised before we touch states.
priority: 200
then:
# Keep the HA dropdown in sync with the stored mode
- lambda: |-
@@ -152,34 +168,12 @@ esphome:
- lambda: 'id(ramp_switch_target_on) = true;'
- script.execute: ramp_on_script
# Mode 1: Restore Brightness using a scripted ramp 0 -> last non-zero brightness
# Mode 1: Restore Brightness (deferred to avoid races)
- if:
condition:
lambda: 'return id(restart_mode) == 1;'
then:
- lambda: |-
float target = id(last_nonzero_brightness_pct);
if (target < 0.0f) target = 0.0f;
if (target > 100.0f) target = 100.0f;
// Gently clamp to min/max caps to avoid an immediate post-on_state correction.
const float minp = (float) id(min_brightness_pct);
const float maxp = (float) id(max_brightness_pct);
if (target > 0.0f && target < minp) target = minp;
if (target > maxp) target = maxp;
id(restore_target_pct) = target; // set scripted target
id(ramp_switch_target_on) = (target > 0.0f);
- if:
condition:
lambda: 'return id(restore_target_pct) > 0.0f;'
then:
- script.stop: ramp_off_script
- script.execute: ramp_to_target_script
else:
- light.turn_off:
id: mosfet_leds
transition_length: 0s
- script.execute: deferred_restore_brightness
# Mode 2: Remain Off (no blip; stays off)
- if:
@@ -193,15 +187,19 @@ esphome:
id: mosfet_leds
transition_length: 0s
platformio_options:
build_unflags:
- -flto
build_flags:
- -fno-lto
- -Wl,--gc-sections
- -ffunction-sections
- -fdata-sections
- -DNDEBUG
# Boot complete: allow OFF handlers again
- lambda: 'id(booting) = false;'
# Only if you want to play with build flags...
# platformio_options:
# build_unflags:
# - -flto
# build_flags:
# - -fno-lto
# - -Wl,--gc-sections
# - -ffunction-sections
# - -fdata-sections
# - -DNDEBUG
##########################################################################################
# ESP PLATFORM AND FRAMEWORK
@@ -212,14 +210,11 @@ esp8266:
board: esp01_1m
restore_from_flash: true # restore some values on reboot
#preferences:
# flash_write_interval: 5min
mdns:
disabled: false # Disabling will make the build file smaller (and it is still available via static IP)
disabled: false # Disabling will make the build file smaller (and device is still available via static IP)
preferences:
flash_write_interval: 5min
flash_write_interval: 5sec # enough time to update values for reboots, but not enough to wear flash
##########################################################################################
# GLOBAL VARIABLES
@@ -240,7 +235,8 @@ globals:
- id: max_on_hours
type: int
restore_value: true
initial_value: '${max_on_default_hours}'
initial_value: "${max_on_default_hours}"
# Default Fading Up Time (Selectable and will be retained)
- id: ramp_up_ms # fade-in when turned ON
type: int
@@ -304,6 +300,16 @@ globals:
type: float
restore_value: false
initial_value: '0.0'
# guards OFF persistence during startup caused by restore_mode: ALWAYS_OFF
- id: booting
type: bool
restore_value: false
initial_value: 'true'
# true only while we are performing a ramp-down that briefly turns the light ON to hit the floor
- id: ramping_for_off
type: bool
restore_value: false
initial_value: 'false'
##########################################################################################
# LOGGER COMPONENT
@@ -314,6 +320,15 @@ logger:
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, Serial control)
#########################################################################################
# STATUS LED
# https://esphome.io/components/status_led.html
#########################################################################################
status_led:
pin:
number: ${device_status_led}
inverted: true
##########################################################################################
# MQTT COMMANDS
# This adds device-specific MQTT command triggers to the common MQTT configuration.
@@ -331,17 +346,6 @@ mqtt:
then:
- switch.turn_off: mosfet_ramp_switch
#########################################################################################
# STATUS LED
# https://esphome.io/components/status_led.html
#########################################################################################
# SINILINK: Status LED Blue LED on GPIO2, active-low
#########################################################################################
status_led:
pin:
number: GPIO2
inverted: true
##########################################################################################
# SWITCH COMPONENT
# https://esphome.io/components/switch/
@@ -400,15 +404,18 @@ button:
name: "${friendly_name} Fade Stop"
icon: mdi:pause
on_press:
# Stop any pending scripts (and their delayed turn_off)
# Stop any pending scripts (and their delayed actions)
- script.stop: ramp_on_script
- script.stop: ramp_off_script
- script.stop: led_flash_up
- script.stop: led_flash_down
- output.turn_off: green_led_out
# Cancel the light's transition by commanding the current level with 0 ms,
# but DO NOT change the ramp switch state/flag.
- lambda: |-
// We are no longer ramping (up or down)
id(ramping_for_off) = false;
id(is_ramping) = false;
// Freeze the light at its *current* level by overwriting the transition
const auto &cv = id(mosfet_leds).current_values;
if (cv.is_on()) {
auto call = id(mosfet_leds).make_call();
@@ -418,6 +425,14 @@ button:
call.perform();
}
// Persist the exact frozen level so "Restore Brightness" survives a reboot
if (cv.is_on()) {
float pct = cv.get_brightness() * 100.0f;
id(last_brightness_pct) = pct;
if (pct > 0.5f) id(last_nonzero_brightness_pct) = pct;
}
#########################################################################################
# SELECT COMPONENT
# https://esphome.io/components/select/index.html
@@ -452,7 +467,7 @@ binary_sensor:
id: btn_gpio12
name: "${friendly_name} Button"
pin:
number: GPIO12
number: ${device_usr_button}
mode:
input: true
pullup: true
@@ -465,14 +480,14 @@ binary_sensor:
condition:
lambda: 'return id(ramp_switch_target_on);'
then:
# Target is currently ON press should go OFF (start ramp-down)
# Target is currently ON -> press should go OFF (start ramp-down)
- lambda: |-
id(ramp_switch_target_on) = false;
id(mosfet_ramp_switch).publish_state(false); // reflect in HA immediately
- script.stop: ramp_on_script
- script.execute: ramp_off_script
else:
# Target is currently OFF press should go ON (start ramp-up)
# Target is currently OFF -> press should go ON (start ramp-up)
- lambda: |-
id(ramp_switch_target_on) = true;
id(mosfet_ramp_switch).publish_state(true); // reflect in HA immediately
@@ -497,17 +512,22 @@ sensor:
on_value:
then:
- lambda: |-
// Remember latest actual output (0..100) for "Restore Brightness"
id(last_brightness_pct) = x;
if (x > 0.5f) {
// Only persist when not ramping; always track a volatile copy
if (!id(is_ramping)) id(last_nonzero_brightness_pct) = x;
id(last_nonzero_tmp) = x;
const auto &cv_now = id(mosfet_leds).current_values;
// Only persist exact last brightness while actually ON,
// and not during the OFF ramp's brief floor-kick.
if (cv_now.is_on()) {
if (x > 0.5f) {
if (!id(is_ramping)) id(last_nonzero_brightness_pct) = x;
id(last_nonzero_tmp) = x;
}
} else {
if (x > 0.5f) id(last_nonzero_tmp) = x;
}
// If not suppressing sync, update the 0..100 slider only when its INT changes
if (!id(suppress_slider_sync)) {
float actual = x; // actual %
float actual = x;
float minp = (float) id(min_brightness_pct);
float maxp = (float) id(max_brightness_pct);
if (maxp <= minp) maxp = minp + 1.0f;
@@ -531,7 +551,7 @@ sensor:
lambda: |-
const auto &cv = id(mosfet_leds).current_values;
if (!cv.is_on()) return 0.0f;
const float lin = cv.get_brightness(); // 0..1 (linear brightness)
const float lin = cv.get_brightness(); // 0..1 linear brightness
const float gamma = atof("${led_gamma}"); // parse substitution string -> float
float pwm = powf(lin, gamma); // approx PWM duty after gamma
if (pwm < 0.0f) pwm = 0.0f;
@@ -548,12 +568,12 @@ sensor:
output:
- platform: esp8266_pwm
id: mosfet_pwm
pin: GPIO4
frequency: 1000 Hz # high frequency to avoid audible/visible artifacts
pin: ${device_mosfet_out}
frequency: ${pwm_frequency}
- platform: gpio
id: green_led_out # Green LED
pin:
number: GPIO13
number: ${device_fading_led}
inverted: false
##########################################################################################
@@ -565,29 +585,48 @@ light:
id: mosfet_leds
name: "${friendly_name}"
output: mosfet_pwm
restore_mode: ALWAYS_OFF
restore_mode: RESTORE_DEFAULT_OFF
default_transition_length: 2s
icon: mdi:led-strip-variant
gamma_correct: "${led_gamma}"
# ON: publish state, track intent, arm watchdog if configured
on_turn_on:
- mqtt.publish:
topic: "${mqtt_local_status_topic}/light/state"
payload: "${mqtt_local_device_command_ON}"
retain: true
- lambda: 'id(ramp_switch_target_on) = true;'
- lambda: |-
// Do not flip "intent to ON" when we're inside an OFF ramp's floor-kick
if (!id(ramping_for_off)) {
id(ramp_switch_target_on) = true;
}
- script.stop: max_on_watchdog
- if:
condition:
lambda: 'return id(max_on_hours) > 0;'
then:
- script.execute: max_on_watchdog
# OFF: publish state, track intent, clear watchdog, and persist OFF so Mode 1 will not restore
# Guarded by booting flag so the automatic OFF at boot from ALWAYS_OFF does not zero persistence.
on_turn_off:
- mqtt.publish:
topic: "${mqtt_local_status_topic}/light/state"
payload: "${mqtt_local_device_command_OFF}"
retain: true
- lambda: 'id(ramp_switch_target_on) = false;'
- script.stop: max_on_watchdog
- if:
condition:
lambda: 'return !id(booting);'
then:
- mqtt.publish:
topic: "${mqtt_local_status_topic}/light/state"
payload: "${mqtt_local_device_command_OFF}"
retain: true
- lambda: 'id(ramp_switch_target_on) = false;'
- script.stop: max_on_watchdog
- lambda: |-
id(last_brightness_pct) = 0.0f;
id(last_set_pos) = 0;
id(led_output_set_pct).publish_state(0);
# Cap brightness to max_brightness_pct without a visible step
on_state:
- lambda: |-
const float cap = id(max_brightness_pct) / 100.0f;
@@ -680,6 +719,8 @@ number:
- lambda: |-
id(ramp_switch_target_on) = false;
id(led_output_set_pct).publish_state(0);
id(last_brightness_pct) = 0.0f; // persist OFF immediately
id(last_set_pos) = 0;
- delay: 400ms
- lambda: 'id(suppress_slider_sync) = false;'
else:
@@ -703,7 +744,19 @@ number:
if (out_pct > maxp) out_pct = maxp;
return out_pct / 100.0f;
transition_length: 250ms
- lambda: 'id(ramp_switch_target_on) = true;'
- lambda: |-
id(ramp_switch_target_on) = true;
float pos = id(led_output_set_pct).state; // 1..100
float minp = (float) id(min_brightness_pct);
float maxp = (float) id(max_brightness_pct);
if (maxp <= minp) maxp = minp + 1.0f;
float out_pct = minp + (pos * (maxp - minp) / 100.0f);
if (out_pct > maxp) out_pct = maxp;
id(last_brightness_pct) = out_pct; // persist exact target now
if (out_pct > 0.5f) {
id(last_nonzero_brightness_pct) = out_pct;
id(last_nonzero_tmp) = out_pct;
}
- delay: 400ms
- lambda: 'id(suppress_slider_sync) = false;'
@@ -776,7 +829,7 @@ script:
- id: ramp_on_script
mode: restart
then:
- lambda: 'id(is_ramping) = true;' # mark ramping
- lambda: 'id(is_ramping) = true;'
- script.stop: ramp_off_script
- script.stop: led_flash_down
- script.execute: led_flash_up
@@ -800,13 +853,10 @@ script:
const auto &cv = id(mosfet_leds).current_values;
const float floor = id(min_brightness_pct) / 100.0f;
const float cap = id(max_brightness_pct) / 100.0f;
if (cap <= floor + 0.0005f) { id(last_ramp_ms) = 0; return (uint32_t) 0; } // guard degenerate case
if (cap <= floor + 0.0005f) { id(last_ramp_ms) = 0; return (uint32_t) 0; }
// IMPORTANT: when the light was OFF, treat current as 0 so we don't compute a 0ms jump to cap.
float curr = cv.is_on() ? cv.get_brightness() : 0.0f;
// If we're below the floor (i.e. coming from OFF), we just did the "floor kick" above.
// Use full ramp_up_ms for a smooth 0 -> cap ramp.
if (curr + 0.0005f < floor) {
id(last_ramp_ms) = id(ramp_up_ms);
return (uint32_t) id(last_ramp_ms);
@@ -822,18 +872,19 @@ script:
- script.stop: led_flash_up
- output.turn_off: green_led_out
- lambda: |-
id(is_ramping) = false; // ramp complete
id(is_ramping) = false;
const auto &cv = id(mosfet_leds).current_values;
if (cv.is_on()) {
float pct = cv.get_brightness() * 100.0f;
if (pct > 0.5f) id(last_nonzero_brightness_pct) = pct; // commit once
id(last_brightness_pct) = pct; // persist final level
if (pct > 0.5f) id(last_nonzero_brightness_pct) = pct;
}
# Script: ramp to a specific target (Restore Brightness path)
- id: ramp_to_target_script
mode: restart
then:
- lambda: 'id(is_ramping) = true;' # mark ramping
- lambda: 'id(is_ramping) = true;'
- script.stop: ramp_off_script
- script.stop: led_flash_down
- script.execute: led_flash_up
@@ -863,12 +914,9 @@ script:
float cap = id(restore_target_pct) / 100.0f;
const float maxp = id(max_brightness_pct) / 100.0f;
if (cap > maxp) cap = maxp;
if (cap <= floor + 0.0005f) { id(last_ramp_ms) = 0; return (uint32_t) 0; } // guard
if (cap <= floor + 0.0005f) { id(last_ramp_ms) = 0; return (uint32_t) 0; }
// Same OFF case handling: if off, treat curr as 0 so we don't collapse the ramp.
float curr = cv.is_on() ? cv.get_brightness() : 0.0f;
// Coming from OFF/below floor? We just did the "floor kick" above — use full ramp_up_ms.
if (curr + 0.0005f < floor) {
id(last_ramp_ms) = id(ramp_up_ms);
return (uint32_t) id(last_ramp_ms);
@@ -885,18 +933,21 @@ script:
- script.stop: led_flash_up
- output.turn_off: green_led_out
- lambda: |-
id(is_ramping) = false; // ramp complete
id(is_ramping) = false;
const auto &cv = id(mosfet_leds).current_values;
if (cv.is_on()) {
float pct = cv.get_brightness() * 100.0f;
if (pct > 0.5f) id(last_nonzero_brightness_pct) = pct; // commit once
id(last_brightness_pct) = pct; // persist final level
if (pct > 0.5f) id(last_nonzero_brightness_pct) = pct;
}
# Script: ramp down from current level to floor, then cleanly cut to OFF
- id: ramp_off_script
mode: restart
then:
- lambda: 'id(is_ramping) = true;' # mark ramping
- lambda: |-
id(is_ramping) = true;
id(ramping_for_off) = true;
- script.stop: ramp_on_script
- script.stop: led_flash_up
- script.execute: led_flash_down
@@ -909,7 +960,7 @@ script:
float curr = cv.get_brightness();
if (curr < floor) curr = floor;
const float denom = (1.0f - floor);
if (denom <= 0.0005f) { id(last_ramp_ms) = 0; return (uint32_t) 0; } // guard near-1.0 floor
if (denom <= 0.0005f) { id(last_ramp_ms) = 0; return (uint32_t) 0; }
float frac = (curr - floor) / denom;
if (frac < 0.0f) frac = 0.0f;
if (frac > 1.0f) frac = 1.0f;
@@ -923,11 +974,12 @@ script:
- script.stop: led_flash_down
- output.turn_off: green_led_out
- lambda: |-
id(is_ramping) = false; // ramp complete
auto call = id(mosfet_leds).make_call();
call.set_state(false);
call.set_brightness(id(max_brightness_pct) / 100.0f);
call.perform();
id(is_ramping) = false;
id(ramping_for_off) = false;
id(last_brightness_pct) = 0.0f; // persist OFF for restore path
id(last_set_pos) = 0;
id(led_output_set_pct).publish_state(0);
- id: max_on_watchdog
mode: restart
then:
@@ -945,3 +997,38 @@ script:
id(mosfet_ramp_switch).publish_state(false);
- script.stop: ramp_on_script
- script.execute: ramp_off_script
# Deferred restore to avoid early-boot races and ensure we apply the last saved level
- id: deferred_restore_brightness
mode: restart
then:
- delay: 5s # let preferences/globals load and light settle
- lambda: |-
// Use ONLY the exact last saved brightness.
float target = id(last_brightness_pct);
// Clamp into [min..max] only if we are restoring a non-zero target
float minp = (float) id(min_brightness_pct);
float maxp = (float) id(max_brightness_pct);
if (target > 0.0f && target < minp) target = minp;
if (target > maxp) target = maxp;
id(restore_target_pct) = target;
- if:
condition:
lambda: 'return id(restore_target_pct) > 0.5f;'
then:
- lambda: |-
id(ramp_switch_target_on) = true; // reflect our intent
id(suppress_slider_sync) = true;
- script.stop: ramp_off_script
- script.execute: ramp_to_target_script
- delay: !lambda 'return (uint32_t) id(last_ramp_ms);'
- lambda: 'id(suppress_slider_sync) = false;'
else:
# Exact last was 0 -> remain OFF
- lambda: 'id(ramp_switch_target_on) = false;'
- light.turn_off:
id: mosfet_leds
transition_length: 0s