From 19a14e1d1b2360204267925b6070ca7ae37e7bfc Mon Sep 17 00:00:00 2001 From: root Date: Sun, 21 Dec 2025 20:55:54 +1300 Subject: [PATCH] various tidyups --- .ha_run.lock | 2 +- automations/main_sony_tv_automations.yaml | 14 - automations/two_way_light_switching.yaml | 69 -- esphome/common/include_more_diag_sensors.yaml | 72 ++ esphome/common/network_common.yaml | 1 + esphome/esp-athomv1temp1.yaml | 992 +++++++++++++++ esphome/esp-bedrm2ceilingfan.yaml | 4 +- esphome/esp-bedrm2fanswitch.yaml | 12 +- esphome/esp-bedrm3ceilingfan.yaml | 4 +- esphome/esp-bedrm3fanswitch.yaml | 4 +- esphome/esp-bedrm3lights.yaml | 4 +- esphome/esp-breakfastbarleds.yaml | 4 +- esphome/esp-centralstairs-bottom.yaml | 136 ++- esphome/esp-centralstairs-top.yaml | 144 ++- esphome/esp-downstairskitchleds.yaml | 4 +- esphome/esp-downstloungeentry.yaml | 4 +- esphome/esp-downstloungemain.yaml | 4 +- esphome/esp-garagebtproxy.yaml | 131 ++ esphome/esp-garagedbcontrols.yaml | 371 ++++++ esphome/esp-garageentrylights.yaml | 197 +++ esphome/esp-garageentrylights2.yaml | 197 +++ esphome/esp-garageextcornerlight.yaml | 240 ++++ esphome/esp-garagelights.yaml | 242 ++++ esphome/esp-loungebookshelfleds.yaml | 4 +- esphome/esp-loungecabinetleds2.yaml | 4 +- esphome/esp-loungepelmetleds2.yaml | 4 +- esphome/esp-maindishwasherspower.yaml | 170 +++ esphome/esp-midesklamp1s.yaml | 23 +- esphome/esp-officedeskrightgpo.yaml | 207 ++++ esphome/esp-officeduallights.yaml | 4 +- esphome/esp-officelights copy.yaml | 176 +++ esphome/esp-poollightpower copy.yaml.old | 1038 ++++++++++++++++ esphome/esp-poollightpower.yaml | 6 +- esphome/esp-poollightpower2.yaml | 1068 +++++++++++++++++ esphome/esp-rocktumbler.yaml | 187 +++ esphome/esp-underhouselights.yaml | 4 +- ...imate_master_bedroom_night_cycle.yaml.old} | 0 packages/energy_readings.yaml | 18 +- packages/internet_traffic.yaml | 38 +- packages/lounge_lighting_scenes.yaml | 6 +- packages/low_battery_device_quantity.yaml | 92 +- packages/main_sony_tv_automations.yaml | 42 + ...s_status.yaml => ms_teams_status.yaml.old} | 0 packages/multi_way_switching.yaml | 53 + packages/nspanel_keepawake.yaml | 50 +- .../{openbeken.yaml => openbeken.yaml.old} | 0 packages/pool_light_boost_switch.yaml | 10 +- ...nse_sense.yaml => presense_sense.yaml.old} | 0 packages/raspberry_pi_monitor.yaml | 188 ++- packages/simulation_lights.yaml | 9 +- packages/system_ha_uptime.yaml | 23 + packages/weather_additional.yaml | 19 +- packages/weewx.yaml | 131 +- scripts/cctv_detect.yaml | 8 - 54 files changed, 5932 insertions(+), 502 deletions(-) delete mode 100644 automations/main_sony_tv_automations.yaml delete mode 100644 automations/two_way_light_switching.yaml create mode 100644 esphome/esp-athomv1temp1.yaml create mode 100644 esphome/esp-garagebtproxy.yaml create mode 100644 esphome/esp-garagedbcontrols.yaml create mode 100644 esphome/esp-garageentrylights.yaml create mode 100644 esphome/esp-garageentrylights2.yaml create mode 100644 esphome/esp-garageextcornerlight.yaml create mode 100644 esphome/esp-garagelights.yaml create mode 100644 esphome/esp-maindishwasherspower.yaml create mode 100644 esphome/esp-officedeskrightgpo.yaml create mode 100644 esphome/esp-officelights copy.yaml create mode 100644 esphome/esp-poollightpower copy.yaml.old create mode 100644 esphome/esp-poollightpower2.yaml create mode 100644 esphome/esp-rocktumbler.yaml rename packages/{climate_master_bedroom_night_cycle.yaml => climate_master_bedroom_night_cycle.yaml.old} (100%) create mode 100644 packages/main_sony_tv_automations.yaml rename packages/{ms_teams_status.yaml => ms_teams_status.yaml.old} (100%) create mode 100644 packages/multi_way_switching.yaml rename packages/{openbeken.yaml => openbeken.yaml.old} (100%) rename packages/{presense_sense.yaml => presense_sense.yaml.old} (100%) create mode 100644 packages/system_ha_uptime.yaml delete mode 100644 scripts/cctv_detect.yaml diff --git a/.ha_run.lock b/.ha_run.lock index cf31149..763ba8d 100644 --- a/.ha_run.lock +++ b/.ha_run.lock @@ -1 +1 @@ -{"pid": 68, "version": 1, "ha_version": "2025.10.2", "start_ts": 1760251204.265106} \ No newline at end of file +{"pid": 68, "version": 1, "ha_version": "2025.12.4", "start_ts": 1766303118.5575826} \ No newline at end of file diff --git a/automations/main_sony_tv_automations.yaml b/automations/main_sony_tv_automations.yaml deleted file mode 100644 index f0559e5..0000000 --- a/automations/main_sony_tv_automations.yaml +++ /dev/null @@ -1,14 +0,0 @@ -- id: "1669966515993" - alias: Turn off Lounge TV - description: "" - trigger: - - platform: mqtt - topic: viewroad-commands/maintv/action - payload: "OFF" - condition: [] - action: - - type: turn_off - device_id: 4a9f71fc64e158f1c9286d6e43ce782e - entity_id: remote.lounge_tv - domain: remote - mode: single diff --git a/automations/two_way_light_switching.yaml b/automations/two_way_light_switching.yaml deleted file mode 100644 index 0d69c00..0000000 --- a/automations/two_way_light_switching.yaml +++ /dev/null @@ -1,69 +0,0 @@ -- id: "Two_Way_Lights_-_Garage_Corridor_-_1" - alias: "Two Way Lights - Garage Corridor - 1" - trigger: - - platform: state - entity_id: switch.garage_entry_switch_1 - action: - - choose: - - conditions: - - condition: state - entity_id: switch.garage_entry_switch_1 - state: "on" - sequence: - - service: switch.turn_on - entity_id: switch.esp_loungesouthleftswitch_relay_2_outside_light_1 - default: - - service: switch.turn_off - entity_id: switch.esp_loungesouthleftswitch_relay_2_outside_light_1 -- id: "Two_Way_Lights_-_Garage_Corridor_-_2" - alias: "Two Way Lights - Garage Corridor - 2" - trigger: - - platform: state - entity_id: switch.esp_loungesouthleftswitch_relay_2_outside_light_1 - action: - - choose: - - conditions: - - condition: state - entity_id: switch.esp_loungesouthleftswitch_relay_2_outside_light_1 - state: "on" - sequence: - - service: switch.turn_on - entity_id: switch.garage_entry_switch_1 - default: - - service: switch.turn_off - entity_id: switch.garage_entry_switch_1 - -- id: "Two_Way_Lights_-_Garage_Main_-_1" - alias: "Two Way Lights - Garage Main - 1" - trigger: - - platform: state - entity_id: switch.garage_entry_switch_3 - action: - - choose: - - conditions: - - condition: state - entity_id: switch.garage_entry_switch_3 - state: "on" - sequence: - - service: switch.turn_on - entity_id: switch.esp_loungesouthleftswitch_relay_2_outside_light_1 - default: - - service: switch.turn_off - entity_id: switch.tasmo_sbas_0407_garagelight -- id: "Two_Way_Lights_-_Garage_Main_-_2" - alias: "Two Way Lights - Garage Main - 2" - trigger: - - platform: state - entity_id: switch.tasmo_sbas_0407_garagelight - action: - - choose: - - conditions: - - condition: state - entity_id: switch.tasmo_sbas_0407_garagelight - state: "on" - sequence: - - service: switch.turn_on - entity_id: switch.garage_entry_switch_3 - default: - - service: switch.turn_off - entity_id: switch.garage_entry_switch_3 diff --git a/esphome/common/include_more_diag_sensors.yaml b/esphome/common/include_more_diag_sensors.yaml index 19f6a3c..7a9103a 100644 --- a/esphome/common/include_more_diag_sensors.yaml +++ b/esphome/common/include_more_diag_sensors.yaml @@ -54,4 +54,76 @@ text_sensor: # } # icon: mdi:clock-start +############################################################################### +# WIFI & MQTT CONNECT COUNTERS +# Replicates Tasmota-style "WiFi Connect Count" and "MQTT Connect Count" +# - Increments each time the connection succeeds. +# - Skips counting reconnects during the first 60s after boot (uptime filter). +# - Persists across reboots (restore_value: yes). +############################################################################### + +globals: + - id: wifi_connect_count + type: int + restore_value: yes + initial_value: '0' + + - id: mqtt_connect_count + type: int + restore_value: yes + initial_value: '0' + +# Uptime sensor to use for filtering +sensor: + - platform: uptime + id: uptime_seconds + update_interval: 10s + internal: true + + - platform: template + name: "WiFi Connect Count" + id: wifi_connect_sensor + icon: mdi:wifi + state_class: total_increasing + entity_category: diagnostic + #unit_of_measurement: "connections" + accuracy_decimals: 0 + lambda: |- + return id(wifi_connect_count); + + - platform: template + name: "MQTT Connect Count" + id: mqtt_connect_sensor + icon: mdi:cloud-outline + state_class: total_increasing + entity_category: diagnostic + #unit_of_measurement: "connections" + accuracy_decimals: 0 + lambda: |- + return id(mqtt_connect_count); + +wifi: + on_connect: + then: + - if: + condition: + lambda: 'return (id(uptime_seconds).state > 60);' # Only count if uptime > 60s + then: + - lambda: |- + id(wifi_connect_count)++; + ESP_LOGI("wifi", "WiFi reconnected, count=%d", id(wifi_connect_count)); + - component.update: wifi_connect_sensor + +mqtt: + on_connect: + then: + - if: + condition: + lambda: 'return (id(uptime_seconds).state > 60);' # Only count if uptime > 60s + then: + - lambda: |- + id(mqtt_connect_count)++; + ESP_LOGI("mqtt", "MQTT reconnected, count=%d", id(mqtt_connect_count)); + - component.update: mqtt_connect_sensor + diff --git a/esphome/common/network_common.yaml b/esphome/common/network_common.yaml index 5559823..8f3fef3 100644 --- a/esphome/common/network_common.yaml +++ b/esphome/common/network_common.yaml @@ -60,6 +60,7 @@ wifi: fast_connect: ${wifi_fast_connect} # Define dns domain / suffix to add to hostname domain: "${dns_domain}" + #min_auth_mode: WPA2 #captive_portal: # extra fallback mechanism for when connecting if the configured WiFi fails diff --git a/esphome/esp-athomv1temp1.yaml b/esphome/esp-athomv1temp1.yaml new file mode 100644 index 0000000..7daba38 --- /dev/null +++ b/esphome/esp-athomv1temp1.yaml @@ -0,0 +1,992 @@ +########################################################################################## +########################################################################################## +# +########################################################################################## +########################################################################################## + + +########################################################################################## +# 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-athomv1temp1" + friendly_name: "esp-athomv1temp1" + description_comment: "esp-athomv1temp1 :: Athom Smart Plug Power V1" + device_area: "Outside" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant. + + # Project Naming + project_name: "Athom Technology.Smart Plug V1" # Project Details + project_version: "v1.0" # Project V denotes release of yaml file, allowing checking of deployed vs latest version + + # Passwords + api_key: !secret esp-api_key # unfortunately you can't use substitutions inside secrets names + ota_pass: !secret esp-ota_pass # unfortunately you can't use substitutions inside secrets names + static_ip_address: !secret esp-athomv1temp1_ip + + # Device Settings + log_level: "NONE" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE + update_interval: "10s" # update time for for general sensors etc + + # Device Settings + relay_icon: "mdi:power-socket-au" + current_limit : "10" # Current Limit in Amps. AU Plug = 10. IL, BR, EU, UK, US Plug = 16. + mqtt_timer_topic: "viewroad-commands/esp-athomv1temp1" # Topics you will use to change stuff + boost_duration_default: "180" # Minutes to stay ON in BOOST mode before reverting to TIMER + morning_on_default: "450" # Default in minutes from midnight. Default 07:30 => 450 + morning_off_default: "450" # Default in minutes from midnight. Default 07:30 => 450 (same as ON as no need for morning schedule) + evening_on_default: "1140" # Default in minutes from midnight. Default 19:00 => 1140 + evening_off_default: "1350" # Default in minutes from midnight. Default 22:30 => 1350 => 1440 is midnight + + ############################################################################## + # POOL LIGHT MODE CONTROL (new) + ############################################################################## + max_modes: "16" # total number of modes in the cycle + mode_pulse_off: "400ms" # short OFF between quick pulses + mode_pulse_on: "400ms" # short ON after each quick pulse + mode_reset_off: "3s" # long OFF to force hardware reset to mode 1 + mode_reset_window_ms: "3000" # treat OFF>=this ms as a reset-to-1 when turning back ON + mode_prime_on: "800ms" # if relay is OFF when a color is selected, turn ON for this long before pulsing + # Ignored modes bitmask: bit (mode_index-1). For 4 and 5 ignored -> (1<<3)|(1<<4) = 24. + ignored_modes_mask: "8288" # Ignore 6(32), 7(64), 14(8192) :: 32 + 64 + 8192 = 8288 + +########################################################################################## +# PACKAGES: Included Common Packages +# https://esphome.io/components/packages.html +########################################################################################## +packages: + ################################################## + # MANDATORY packages (won't compile without them!) + ################################################## + + #### 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}" + + ################################################## + # OPTIONAL packages (comment if you don't want them) + ################################################## + + #### 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}" + + #### WEB PORTAL #### + #common_webportal: !include + # file: common/webportal_common.yaml + + #### MQTT #### + common_mqtt: !include + file: common/mqtt_common.yaml + vars: + local_device_name: "${device_name}" + + #### SNTP (Only use if you want/need accurate timeclocks) #### + common_sntp: !include + file: common/sntp_common.yaml + + #### DIAGNOSTICS Lite Sensors #### + common_lite_sensors: !include + file: common/sensors_common_lite.yaml + + #### DIAGNOSTICS General Sensors #### + common_general_sensors: !include + file: common/sensors_common.yaml + + #### DEBUGGING Sensors #### + # A count of various resets + #common_resetcount_debugging: !include + # file: common/resetcount_common.yaml + + # Device Specific included packages + common_athompowermonV1: !include + file: common/athompowermonv1_common.yaml + vars: + local_friendly_name: "${friendly_name}" + local_current_limit: "${current_limit}" + +########################################################################################## +# ESPHome +# https://esphome.io/components/esphome.html +########################################################################################## +esphome: + name: "${device_name}" + friendly_name: "${friendly_name}" + comment: "${description_comment}" #Appears on the esphome page in HA + area: "${device_area}" + name_add_mac_suffix: False + min_version: 2024.6.0 + project: + name: "${project_name}" + version: "${project_version}" + #platformio_options: + # build_unflags: + # - -std=gnu++20 + # - -std=gnu++2a + # build_flags: + # - -std=gnu++11 + # - -Os + # - -Wl,--gc-sections + # - -fno-exceptions + # - -fno-rtti + +########################################################################################## +# ESP Platform and Framework +# https://esphome.io/components/esp32.html +########################################################################################## +esp8266: + board: esp8285 + restore_from_flash: true # mainly for calculating cumulative energy, but not that important here + #framework: + # version: 2.7.4 + +preferences: + flash_write_interval: 10min + +mdns: + disabled: True # binary size saving + +########################################################################################## +# ESPHome Logging Enable +# https://esphome.io/components/logger.html +########################################################################################## +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) + #esp8266_store_log_strings_in_flash: false + #tx_buffer_size: 64 + +########################################################################################## +# Global Variables for use in automations etc +# https://esphome.io/guides/automations.html?highlight=globals#global-variables +########################################################################################## +globals: + + # Tracks the time (in seconds from midnight) at the previous boot + - id: last_boot_time_s + type: int + restore_value: true + initial_value: "0" + + # Counts how many consecutive boots have occurred (within X seconds) + - id: boot_count + type: int + restore_value: true + initial_value: "0" + + # Morning On time (minutes from midnight), + - id: morning_on + type: int + restore_value: true + initial_value: "${morning_on_default}" + + # Morning Off time (minutes from midnight), + - id: morning_off + type: int + restore_value: true + initial_value: "${morning_off_default}" + + # Evening On time (minutes from midnight), + - id: evening_on + type: int + restore_value: true + initial_value: "${evening_on_default}" + + # Evening Off time (minutes from midnight), + - id: evening_off + type: int + restore_value: true + initial_value: "${evening_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 = BOOST + #################################################### + - id: operation_mode + type: int + restore_value: true + initial_value: "2" + + #################################################### + # current_mins is set if SNTP is invalid. + # We assume user powers on the device at 12:00 noon + # => 12 * 60 = 720 minutes from midnight. + #################################################### + - id: current_mins + type: int + restore_value: true + initial_value: "720" # 720 is 12:00 Noon + + #################################################### + # boost_timer: counts minutes in BOOST mode + # After 'boost_duration' minutes, revert to TIMER. + #################################################### + - id: boost_timer + type: int + restore_value: true + initial_value: "0" + + ############################################################################## + # POOL LIGHT MODE CONTROL GLOBALS (new) + ############################################################################## + # Current assumed pool-light mode (0..max_modes). 0 means relay OFF. + - id: current_mode + type: int + restore_value: false + initial_value: "1" + + # Total modes in the cycle (edit in substitutions). + - id: max_modes + type: int + restore_value: false + initial_value: "${max_modes}" + + # Flag while we are actively pulsing to change modes (prevents scheduler interference). + - id: mode_changing + type: bool + restore_value: false + initial_value: "false" + + # Timestamp of last relay off (for delta measurement). + - id: last_off_ms + type: uint32_t + restore_value: false + initial_value: "0" + + # Millisecond threshold that separates "quick pulse" vs "reset to mode 1". + - id: reset_window_ms + type: int + restore_value: false + initial_value: "${mode_reset_window_ms}" + + # Desired target mode for the cycle script. + - id: desired_mode + type: int + restore_value: false + initial_value: "1" + + # Bitmask of ignored modes (1..max_modes). Example: ignore 4 & 5 -> 24. + - id: ignored_mask + type: int + restore_value: false + initial_value: "${ignored_modes_mask}" + + # Internal: whether a recheck is already scheduled for min OFF enforcement. + - id: recheck_pending + type: bool + restore_value: false + initial_value: "false" + +########################################################################################## +# Text Sensors +# https://esphome.io/components/text_sensor/index.html +########################################################################################## +text_sensor: + +############################ +# MQTT Subscriptions +############################ + #################################################### + # Subscribe to the Morning On time, format "HH:MM" + #################################################### + - platform: mqtt_subscribe + name: "Morning On Time Setting" + id: morning_on_topic + topic: "${mqtt_timer_topic}/morning-on" # Stored in the format HH:MM + internal: True + on_value: + then: + - lambda: |- + // Expect "HH:MM" => total length = 5, with ':' + if (x.size() == 5 && x[2] == ':') { + int hour = atoi(x.substr(0, 2).c_str()); // "HH" + int minute = atoi(x.substr(3, 2).c_str()); // "MM" + id(morning_on) = hour * 60 + minute; + ESP_LOGI("timer","Received new Morning On: %02d:%02d", hour, minute); + } else { + ESP_LOGW("timer","Invalid Morning On format: %s", x.c_str()); + } + #################################################### + # Morning Off time => "HH:MM" + #################################################### + - platform: mqtt_subscribe + name: "Morning Off Time Setting" + id: morning_off_topic + topic: "${mqtt_timer_topic}/morning-off" # Stored in the format HH:MM + internal: True # No need to show this in Home Assistant as there is a sensor that shows the set value + on_value: + then: + - lambda: |- + if (x.size() == 5 && x[2] == ':') { + int hour = atoi(x.substr(0, 2).c_str()); + int minute = atoi(x.substr(3, 2).c_str()); + id(morning_off) = hour * 60 + minute; + ESP_LOGI("timer","Received new Morning Off: %02d:%02d", hour, minute); + } else { + ESP_LOGW("timer","Invalid Morning Off format: %s", x.c_str()); + } + #################################################### + # Evening On time => "HH:MM" + #################################################### + - platform: mqtt_subscribe + name: "Evening On Time Setting" + id: evening_on_topic + topic: "${mqtt_timer_topic}/evening-on" # Stored in the format HH:MM + internal: True # No need to show this in Home Assistant as there is a sensor that shows the set value + on_value: + then: + - lambda: |- + if (x.size() == 5 && x[2] == ':') { + int hour = atoi(x.substr(0, 2).c_str()); + int minute = atoi(x.substr(3, 2).c_str()); + id(evening_on) = hour * 60 + minute; + ESP_LOGI("timer","Received new Evening On: %02d:%02d", hour, minute); + } else { + ESP_LOGW("timer","Invalid Evening On format: %s", x.c_str()); + } + #################################################### + # Evening Off time => "HH:MM" + #################################################### + - platform: mqtt_subscribe + name: "Evening Off Time Setting" + id: evening_off_topic + topic: "${mqtt_timer_topic}/evening-off" # Stored in the format HH:MM + internal: True # No need to show this in Home Assistant as there is a sensor that shows the set value + on_value: + then: + - lambda: |- + if (x.size() == 5 && x[2] == ':') { + int hour = atoi(x.substr(0, 2).c_str()); + int minute = atoi(x.substr(3, 2).c_str()); + id(evening_off) = hour * 60 + minute; + ESP_LOGI("timer","Received new Evening Off: %02d:%02d", hour, minute); + } else { + 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 0–1439 + 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(v); + } + + #################################################### + # Subscribe to operation mode: + # OFF, ON, TIMER, BOOST + #################################################### + # MQTT subscription: set mode, then immediately re-evaluate relay + - platform: mqtt_subscribe + id: timer_operation_mode_topic + topic: "${mqtt_timer_topic}/operation" + internal: True # No need to show this in Home Assistant as there is a sensor that shows the set value + on_value: + then: + - lambda: |- + if (strcasecmp(x.c_str(), "TIMER") == 0) { + id(operation_mode) = 2; + ESP_LOGI("timer","Operation mode set to TIMER"); + } else if (strcasecmp(x.c_str(), "ON") == 0) { + id(operation_mode) = 1; + ESP_LOGI("timer","Operation mode set to ON"); + } 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(), "BOOST") == 0) { + id(operation_mode) = 3; + id(boost_timer) = 0; + ESP_LOGI("timer","Operation mode set to BOOST"); + } else { + ESP_LOGW("timer","Invalid operation mode: %s", x.c_str()); + } + - script.execute: evaluate_relay_state + + ###################################################### + # Expose the current operation mode (OFF, ON, TIMER, BOOST) + ###################################################### + - platform: template + name: "Operation Mode State" + lambda: |- + // 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 {"BOOST"}; + default: return {"UNKNOWN"}; + } + update_interval: 5s + + ###################################################### + # Expose the "Morning On" time as a text (HH:MM) + ###################################################### + - platform: template + name: "Timeclock: Morning On Time" + lambda: |- + int hour = id(morning_on) / 60; + int minute = id(morning_on) % 60; + // Increase to 16 for safety + char buff[16]; + snprintf(buff, sizeof(buff), "%02d:%02d", hour, minute); + return { std::string(buff) }; + update_interval: "${update_interval}" + + ###################################################### + # Expose the "Morning Off" time as a text (HH:MM) + ###################################################### + - platform: template + name: "Timeclock: Morning Off Time" + lambda: |- + int hour = id(morning_off) / 60; + int minute = id(morning_off) % 60; + // Increase to 16 for safety + char buff[16]; + snprintf(buff, sizeof(buff), "%02d:%02d", hour, minute); + return { std::string(buff) }; + update_interval: "${update_interval}" + + ###################################################### + # Expose the "Evening On" time as a text (HH:MM) + ###################################################### + - platform: template + name: "Timeclock: Evening On Time" + lambda: |- + int hour = id(evening_on) / 60; + int minute = id(evening_on) % 60; + // Increase to 16 for safety + char buff[16]; + snprintf(buff, sizeof(buff), "%02d:%02d", hour, minute); + return { std::string(buff) }; + update_interval: "${update_interval}" + + ###################################################### + # Expose the "Evening Off" time as a text (HH:MM) + ###################################################### + - platform: template + name: "Timeclock: Evening Off Time" + lambda: |- + int hour = id(evening_off) / 60; + int minute = id(evening_off) % 60; + // Increase to 16 for safety + char buff[16]; + snprintf(buff, sizeof(buff), "%02d:%02d", hour, minute); + return { std::string(buff) }; + update_interval: "${update_interval}" + +########################################################################################## +# BINARY SENSORS +# https://esphome.io/components/binary_sensor/ +########################################################################################## +binary_sensor: + - platform: gpio + pin: + number: GPIO03 + mode: INPUT_PULLUP + inverted: true + name: "Power Button" + id: power_button + filters: + - delayed_on: 20ms + on_click: + - min_length: 20ms + max_length: 500ms + then: + - lambda: |- + if (id(relay).state) { + // Relay is ON: turn it OFF and set mode to 2 (TIMER) + id(relay).turn_off(); + id(operation_mode) = 2; + } else { + // Relay is OFF: turn it ON and set mode to 3 (BOOST) + id(relay).turn_on(); + id(operation_mode) = 3; + } + + - platform: template + name: "Relay Status" + lambda: |- + return id(relay).state; + +########################################################################################## +# Sensors +# https://esphome.io/components/text_sensor/index.html +########################################################################################## +sensor: + - platform: template + name: "Timeclock: Boost Duration" + id: boost_duration_time + unit_of_measurement: "mins" + accuracy_decimals: "0" + update_interval: "${update_interval}" + lambda: |- + return id(boost_duration); + + - platform: template + name: "Mins from Midnight" + id: mins_from_midnight + unit_of_measurement: "mins" + accuracy_decimals: "0" + update_interval: "${update_interval}" + internal: True # No need to show this in Home Assistant + 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; + + +################################################################################################# +# SWITCH COMPONENT +# https://esphome.io/components/switch/ +################################################################################################# +switch: + - platform: gpio + name: "Power Output" + pin: GPIO14 + id: relay + restore_mode: RESTORE_DEFAULT_OFF # Ensures the relay is restored (or off) at boot + #internal: true # Hides the switch from Home Assistant + icon: "${relay_icon}" + # POOL LIGHT MODE CONTROL: detect quick vs long off periods and keep current_mode in sync + on_turn_off: + - lambda: |- + id(last_off_ms) = millis(); + if (!id(mode_changing)) id(current_mode) = 0; // reflect OFF in select when off normally + on_turn_on: + - lambda: |- + if (id(mode_changing)) { + return; + } + uint32_t delta = millis() - id(last_off_ms); + if (delta >= (uint32_t)id(reset_window_ms)) { + id(current_mode) = 1; + } else { + id(current_mode)++; + if (id(current_mode) > id(max_modes)) id(current_mode) = 1; // keep internal index sane + } + +################################################################################################# +# BUTTON COMPONENT +# https://esphome.io/components/button/index.html +################################################################################################# +button: + - platform: template + name: "Boost now" + id: boost_button + icon: "mdi:play-circle-outline" + on_press: + # 1) reset BOOST timer and set mode + - lambda: |- + id(boost_timer) = 0; + id(operation_mode) = 3; + # 2) immediately re-evaluate relay state + - script.execute: evaluate_relay_state + - platform: template + name: "Default timer settings" + id: default_timer_settings_button + icon: "mdi:restore" + on_press: + - lambda: |- + // Restore all timing globals to their YAML defaults + id(morning_on) = ${morning_on_default}; + id(morning_off) = ${morning_off_default}; + id(evening_on) = ${evening_on_default}; + id(evening_off) = ${evening_off_default}; + id(boost_duration)= ${boost_duration_default}; + // Reset mode to TIMER and clear any running boost + id(operation_mode)= 2; + id(boost_timer) = 0; + ESP_LOGI("timer","Default timer settings applied"); + - script.execute: evaluate_relay_state + +################################################################################################# +# SELECT COMPONENT +# https://esphome.io/components/select/index.html +################################################################################################# +select: + - platform: template + name: "Operation Mode" + id: operation_mode_select + update_interval: 5s + options: + - "OFF" + - "ON" + - "TIMER" + - "BOOST" + + # show the current mode + 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"); + } + + # when changed in HA, set mode & re-evaluate + 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 { // BOOST + id(boost_timer) = 0; + id(operation_mode) = 3; + } + - script.execute: evaluate_relay_state + + ############################################################################## + # POOL LIGHT MODE SELECT (new) + # 0=OFF -> immediately turns relay OFF and sets Operation Mode = TIMER. + # Selecting a color (>=1) forces Operation Mode = ON. + # If target < current, do a long reset to mode 1, then pulse forward. + # Ignored modes are hidden here but still counted by pulses. + ############################################################################## + ############################################################################## + # POOL LIGHT MODE SELECT (updated display logic) + # 0=OFF -> immediately turns relay OFF and sets Operation Mode = TIMER. + # Selecting a color (>=1) forces Operation Mode = ON. + # If target < current, do a long reset to mode 1, then pulse forward. + # Ignored modes are hidden here but still counted by pulses. + ############################################################################## + - platform: template + name: "Pool Light Mode" + id: pool_light_mode_select + update_interval: 250ms + # Options include all 1..16 (no ignored modes currently) plus 0=OFF + options: + - "0= OFF" + - "1= Dark Blue" + - "2= Red" + - "3= Green" + - "4= Purple" + - "5= Aqua" + #- "6= Lime" + #- "7= Cool White" + - "8= Speed Up" + - "9= Transformer" + - "10= Blurple" + - "11= Redlime" + - "12= Greenqua" + - "13= Bluequa" + #- "14= Grelime" + - "15= Redurple" + - "16= RGB Mad" + + # Show OFF only when not in a color-change sequence. + # While changing, reflect the in-flight/current mode (never 0). + lambda: |- + auto label_for = [](int m) -> std::string { + switch (m) { + case 0: return "0= OFF"; + case 1: return "1= Dark Blue"; + case 2: return "2= Red"; + case 3: return "3= Green"; + case 4: return "4= Purple"; + case 5: return "5= Aqua"; + case 6: return "6= Lime"; + case 7: return "7= Cool White"; + case 8: return "8= Speed Up"; + case 9: return "9= Transformer"; + case 10: return "10= Blurple"; + case 11: return "11= Redlime"; + case 12: return "12= Greenqua"; + case 13: return "13= Bluequa"; + case 14: return "14= Grelime"; + case 15: return "15= Redurple"; + case 16: return "16= RGB Mad"; + default: return "1= Dark Blue"; + } + }; + auto is_ignored = [&](int m) -> bool { + if (m < 1 || m > id(max_modes)) return true; + int bit = 1 << (m - 1); + return (id(ignored_mask) & bit) != 0; + }; + + // While stepping (mode_changing), don't show OFF even if relay is briefly OFF. + if (id(mode_changing)) { + int cm = id(current_mode); + if (cm <= 0) cm = 1; // during long reset, assume Mode 1 is next + // Skip ignored modes for display if ever configured later + if (!is_ignored(cm)) return label_for(cm); + // find next non-ignored just for display robustness + for (int m = cm + 1; m <= id(max_modes); m++) if (!is_ignored(m)) return label_for(m); + for (int m = 1; m <= id(max_modes); m++) if (!is_ignored(m)) return label_for(m); + return label_for(1); + } + + // Normal (not changing): show OFF if relay is actually OFF, else show current mode + if (!id(relay).state) return std::string("0= OFF"); + + int cm = id(current_mode); + if (cm == 0) return std::string("0= OFF"); + if (!is_ignored(cm)) return label_for(cm); + for (int m = cm + 1; m <= id(max_modes); m++) if (!is_ignored(m)) return label_for(m); + for (int m = 1; m <= id(max_modes); m++) if (!is_ignored(m)) return label_for(m); + return label_for(1); + + set_action: + # First, set flags based on selection + - lambda: |- + int target = atoi(x.c_str()); + if (target < 0) target = 0; + if (target > id(max_modes)) target = id(max_modes); + + if (target == 0) { + // MODE 0: force everything OFF; UI goes back to TIMER control + id(mode_changing) = false; + id(recheck_pending) = false; + id(operation_mode) = 2; // TIMER + id(current_mode) = 0; // reflect OFF in dropdown + } else { + // defensive: ignore choosing an ignored mode (options already hide them) + int bit = 1 << (target - 1); + if ((id(ignored_mask) & bit) != 0) { + ESP_LOGW("mode","Selected target %d is ignored; ignoring request", target); + return; + } + // Color selection: force ON mode and start changer + id(operation_mode) = 1; + id(desired_mode) = target; + id(mode_changing) = true; + } + + # If OFF was selected, hard-stop any running scripts and cut power + - if: + condition: + lambda: 'return atoi(x.c_str()) == 0;' + then: + - script.stop: change_to_desired_mode + - script.stop: reset_to_mode1 + - script.stop: enforce_off_guard + - switch.turn_off: relay + else: + - script.execute: change_to_desired_mode + +################################################################################################# +# SCRIPT COMPONENT +# https://esphome.io/components/script.html +################################################################################################# +script: + # Core: evaluate and drive the relay (with enforced min OFF window) + - id: evaluate_relay_state + then: + - lambda: |- + if (id(mode_changing)) { + // do not fight the pulser + return; + } + // Determine target state + bool target_on = false; + int mode = id(operation_mode); + + if (mode == 3) { // BOOST + target_on = true; + } else if (mode == 0) { // OFF + target_on = false; + } else if (mode == 1) { // ON + target_on = true; + } else if (mode == 2) { // TIMER + bool should_on = false; + if (id(current_mins) >= id(morning_on) && id(current_mins) < id(morning_off)) + should_on = true; + if (id(current_mins) >= id(evening_on) && id(current_mins) < id(evening_off)) + should_on = true; + target_on = should_on; + } + + // Enforce minimum OFF time when turning ON normally (not during color pulses) + if (target_on) { + uint32_t delta = millis() - id(last_off_ms); + if (delta < (uint32_t) id(reset_window_ms)) { + // Still inside OFF window: wait; schedule a recheck if not already + if (!id(recheck_pending)) { + id(enforce_off_guard).execute(); + } + return; + } else { + id(relay).turn_on(); + return; + } + } else { + id(relay).turn_off(); + return; + } + + # Poll until OFF window elapsed, then re-evaluate (does not toggle the relay itself) + - id: enforce_off_guard + mode: restart + then: + - lambda: |- + id(recheck_pending) = true; + - while: + condition: + lambda: |- + if (id(mode_changing)) return false; // abort if color change starts + uint32_t delta = millis() - id(last_off_ms); + return delta < (uint32_t) id(reset_window_ms); + then: + - delay: 200ms + - lambda: |- + id(recheck_pending) = false; + - script.execute: evaluate_relay_state + + # Long reset to Mode 1 + - id: reset_to_mode1 + mode: restart + then: + - switch.turn_off: relay + - delay: ${mode_reset_off} + - switch.turn_on: relay + - delay: ${mode_pulse_on} + - lambda: |- + id(current_mode) = 1; + + # Change to desired_mode, robust from OFF and without wrap on lower targets + # Change to desired_mode, robust from OFF and without wrap on lower targets + - id: change_to_desired_mode + mode: restart + then: + # If relay is currently OFF, establish a known starting point + - if: + condition: + lambda: 'return !id(relay).state;' + then: + - lambda: |- + uint32_t delta = millis() - id(last_off_ms); + // If OFF < reset window, enforce a true reset first for predictable start + if (delta < (uint32_t) id(reset_window_ms)) { + id(reset_to_mode1).execute(); + } + - if: + condition: + lambda: 'return !id(relay).state;' + then: + - switch.turn_on: relay + - delay: ${mode_prime_on} + - lambda: |- + // If we turned ON after ≥ reset window, hardware is at Mode 1 + if ((millis() - id(last_off_ms)) >= (uint32_t) id(reset_window_ms)) { + id(current_mode) = 1; + } + + # If target is below current, do a long reset to Mode 1, then proceed + - if: + condition: + lambda: |- + return id(desired_mode) < id(current_mode); + then: + - script.execute: reset_to_mode1 + - script.wait: reset_to_mode1 + + # If already exactly at target, ensure ON and finish + - if: + condition: + lambda: 'return id(desired_mode) == id(current_mode);' + then: + - switch.turn_on: relay + - lambda: |- + id(mode_changing) = false; + + # Step forward until we reach desired (ignored modes still counted) + - while: + condition: + lambda: |- + // Allow immediate cancellation if OFF is selected mid-flight + return id(mode_changing) && (id(current_mode) < id(desired_mode)); + then: + - switch.turn_off: relay + - delay: ${mode_pulse_off} + - switch.turn_on: relay + - delay: ${mode_pulse_on} + - lambda: |- + id(current_mode)++; + + # End: make sure we leave the light ON and clear the guard + - switch.turn_on: relay + - lambda: |- + id(mode_changing) = false; + + +################################################################################################# +# INTERVAL COMPONENT +# https://esphome.io/components/interval.html +################################################################################################# +# Interval: bumps time (even if no SNTP), then calls the script to evaluate relay state +interval: + - interval: "1min" + then: + - lambda: |- + // — update current_mins via SNTP or fallback + if (!id(sntp_time).now().is_valid()) { + id(current_mins)++; + if (id(current_mins) >= 1440) id(current_mins) = 0; + } else { + auto now = id(sntp_time).now(); + id(current_mins) = now.hour * 60 + now.minute; + } + + // — if in BOOST, advance boost_timer and expire when done + if (id(operation_mode) == 3) { + id(boost_timer)++; + if (id(boost_timer) >= id(boost_duration)) { + id(operation_mode) = 2; + //id(mqtt_client).publish("${mqtt_timer_topic}/operation", "TIMER"); + } + } + - script.execute: evaluate_relay_state diff --git a/esphome/esp-bedrm2ceilingfan.yaml b/esphome/esp-bedrm2ceilingfan.yaml index c943ac7..9124a8f 100644 --- a/esphome/esp-bedrm2ceilingfan.yaml +++ b/esphome/esp-bedrm2ceilingfan.yaml @@ -38,8 +38,8 @@ substitutions: api_key: !secret esp-api_key ota_pass: !secret esp-ota_pass static_ip_address: !secret esp-bedrm2ceilingfan_ip # unfortunately you can't use substitutions inside secrets names - 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_main_topic: !secret mqtt_command_main_topic + mqtt_local_status_main_topic: !secret mqtt_status_main_topic # Device Settings log_level: "INFO" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE diff --git a/esphome/esp-bedrm2fanswitch.yaml b/esphome/esp-bedrm2fanswitch.yaml index 1e2beef..16e66b5 100644 --- a/esphome/esp-bedrm2fanswitch.yaml +++ b/esphome/esp-bedrm2fanswitch.yaml @@ -115,12 +115,12 @@ esphome: project: name: "${project_name}" version: "${project_version}" - platformio_options: - build_flags: - - "-Os" # optimize for size - - "-Wl,--gc-sections" # drop unused code/data - - "-fno-exceptions" # strip C++ exceptions - - "-fno-rtti" # strip C++ RTTI +# platformio_options: +# build_flags: +# - "-Os" # optimize for size +# - "-Wl,--gc-sections" # drop unused code/data +# - "-fno-exceptions" # strip C++ exceptions +# - "-fno-rtti" # strip C++ RTTI # on_boot: # priority: 200 # then: diff --git a/esphome/esp-bedrm3ceilingfan.yaml b/esphome/esp-bedrm3ceilingfan.yaml index 0d6e077..9837542 100644 --- a/esphome/esp-bedrm3ceilingfan.yaml +++ b/esphome/esp-bedrm3ceilingfan.yaml @@ -38,8 +38,8 @@ substitutions: api_key: !secret esp-api_key ota_pass: !secret esp-ota_pass static_ip_address: !secret esp-bedrm3ceilingfan_ip # unfortunately you can't use substitutions inside secrets names - 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_main_topic: !secret mqtt_command_main_topic + mqtt_local_status_main_topic: !secret mqtt_status_main_topic # Device Settings log_level: "INFO" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE diff --git a/esphome/esp-bedrm3fanswitch.yaml b/esphome/esp-bedrm3fanswitch.yaml index 1345475..6a3adc6 100644 --- a/esphome/esp-bedrm3fanswitch.yaml +++ b/esphome/esp-bedrm3fanswitch.yaml @@ -36,8 +36,8 @@ substitutions: api_key: !secret esp-api_key # unfortunately you can't use substitutions inside secrets names ota_pass: !secret esp-ota_pass # unfortunately you can't use substitutions inside secrets names static_ip_address: !secret esp-bedrm3fanswitch_ip - 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_main_topic: !secret mqtt_command_main_topic + mqtt_local_status_main_topic: !secret mqtt_status_main_topic # Device Settings #relay_icon: "mdi:heating-coil" diff --git a/esphome/esp-bedrm3lights.yaml b/esphome/esp-bedrm3lights.yaml index 4449d06..f7bfe6a 100644 --- a/esphome/esp-bedrm3lights.yaml +++ b/esphome/esp-bedrm3lights.yaml @@ -31,8 +31,8 @@ substitutions: api_key: !secret esp-api_key # unfortunately you can't use substitutions inside secrets names ota_pass: !secret esp-ota_pass # unfortunately you can't use substitutions inside secrets names static_ip_address: !secret esp-bedrm3lights_ip - 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_main_topic: !secret mqtt_command_main_topic + mqtt_local_status_main_topic: !secret mqtt_status_main_topic # Device Settings #relay_icon: "mdi:lightbulb-group" diff --git a/esphome/esp-breakfastbarleds.yaml b/esphome/esp-breakfastbarleds.yaml index a1078d3..7246c62 100644 --- a/esphome/esp-breakfastbarleds.yaml +++ b/esphome/esp-breakfastbarleds.yaml @@ -69,8 +69,8 @@ substitutions: # MQTT LOCAL Controls (This is just my local method of controlling via MQTT, I also use the built in method) mqtt_local_device_name: "lounge-breakfastbarleds" - 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_main_topic: !secret mqtt_command_main_topic + mqtt_local_status_main_topic: !secret mqtt_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" diff --git a/esphome/esp-centralstairs-bottom.yaml b/esphome/esp-centralstairs-bottom.yaml index 5de32e3..8542b66 100644 --- a/esphome/esp-centralstairs-bottom.yaml +++ b/esphome/esp-centralstairs-bottom.yaml @@ -18,50 +18,44 @@ # If NOT using a secrets file, just replace these with the passwords etc (in quotes) ########################################################################################## substitutions: - # Device Naming + # Device Custom Naming device_name: "esp-centralstairs-bottom" friendly_name: "Central Stair Lightswitch - Bottom (2)" description_comment: "Central Stair Lightswitch - Bottom, using Zemismart KS-811 Double Push Button. Main Stair Lights (1), Stair Footer Lights (2)" - device_area: "" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant. + device_area: "Lounge" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant. + static_ip_address: !secret esp-centralstairs-bottom_ip + mqtt_device_name_1: "stair-mainlights" + mqtt_device_name_2: "stair-footerlights" + + # I/O Naming + switch_1_name: "Main Stair Lights (Lower)" # Physical, but just the lower lights below the media cabinet + switch_2_name: "Stair Footer Lights" # virtual only, nothing connected to this output + #relay_1_name: "Garage Lights" + #button_1_name: "Power Button" + #relay_icon: "mdi:lightbulb-group" # Project Naming project_name: "Zemismart Technologies.KS-811 Double" # Project Details - project_version: "v3.7" # Project V denotes release of yaml file, allowing checking of deployed vs latest version + project_version: "v2.0" # Project V denotes release of yaml file, allowing checking of deployed vs latest version + + # MQTT Controls + mqtt_command_main_topic: !secret mqtt_command_main_topic + mqtt_status_main_topic: !secret mqtt_status_main_topic + mqtt_command_topic_1: "${mqtt_command_main_topic}/${mqtt_device_name_1}" + mqtt_status_topic_1: "${mqtt_status_main_topic}/${mqtt_device_name_1}" + mqtt_command_topic_2: "${mqtt_command_main_topic}/${mqtt_device_name_2}" + mqtt_status_topic_2: "${mqtt_status_main_topic}/${mqtt_device_name_2}" + mqtt_command_ON: "ON" + mqtt_command_OFF: "OFF" # Passwords & Secrets (unfortunately you can't use substitutions inside secrets names) api_key: !secret esp-api_key ota_pass: !secret esp-ota_pass - static_ip_address: !secret esp-centralstairs-bottom_ip - mqtt_command_main_topic: !secret mqtt_command_main_topic - mqtt_status_main_topic: !secret mqtt_status_main_topic - # Device Settings - #relay_icon: "mdi:lightbulb-group" - log_level: "INFO" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE + # General Settings + log_level: "ERROR" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE update_interval: "60s" # update time for for general sensors etc - # MQTT LOCAL Controls - mqtt_local_device_name: "stair-mainlights-lower" - mqtt_local_command_topic: "${mqtt_command_main_topic}/${mqtt_local_device_name}" # Topic we will use to command this locally without HA - mqtt_local_status_topic: "${mqtt_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" - - # MQTT REMOTE Controls - mqtt_remote_device1_name: "stair-footerlights" - mqtt_remote_device1_command_topic: "${mqtt_command_main_topic}/${mqtt_remote_device1_name}" - mqtt_remote_device1_status_topic: "${mqtt_status_main_topic}/${mqtt_remote_device1_name}" - #mqtt_remote_device2_name: "stair-mainlights-upper" - #mqtt_remote_device2_command_topic: "${mqtt_local_command_main_topic}/${mqtt_remote_device2_name}/relay3/set" - #mqtt_remote_device2_status_topic: "${mqtt_local_status_main_topic}/${mqtt_remote_device2_name}/relay3/state" - mqtt_remote_device_command_ON: "ON" - mqtt_remote_device_command_OFF: "OFF" - - # Switch Naming - switch_1_name: "Main Stair Lights (Lower)" # Physical, but just the lower lights below the media cabinet - switch_2_name: "Stair Footer Lights" # virtual only, nothing connected to this output - #switch_3_name: "Nil" - ######################################################################################### # PACKAGES: Included Common Packages # https://esphome.io/components/packages.html @@ -99,7 +93,7 @@ packages: #### 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_debug: !include common/include_debug_diag_sensors.yaml #diag_resetcount: !include common/include_resetcount_diag_sensors.yaml ######################################################################################### @@ -146,40 +140,64 @@ mqtt: on_connect: then: - if: + # Status of relay 1, which has an actual light connected condition: lambda: 'return id(Relay_1).state;' then: - mqtt.publish: - topic: "${mqtt_local_status_topic}" - payload: "${mqtt_local_device_command_ON}" + topic: "${mqtt_status_topic_1}" + payload: "${mqtt_command_ON}" qos: 0 retain: false else: - mqtt.publish: - topic: "${mqtt_local_status_topic}" - payload: "${mqtt_local_device_command_OFF}" + topic: "${mqtt_status_topic_1}" + payload: "${mqtt_command_OFF}" qos: 0 retain: false + on_message: - # Light control to turn on relay 1 - - topic: "${mqtt_local_command_topic}" - payload: "${mqtt_local_device_command_ON}" + # Relay 1: only turn ON if currently OFF + - topic: "${mqtt_command_topic_1}" + payload: "${mqtt_command_ON}" then: - - switch.turn_on: Relay_1 - # Light control to turn off relay 1 - - topic: "${mqtt_local_command_topic}" - payload: "${mqtt_local_device_command_OFF}" + - if: + condition: + not: + - switch.is_on: Relay_1 + then: + - switch.turn_on: Relay_1 + + # Relay 1: only turn OFF if currently ON + - topic: "${mqtt_command_topic_1}" + payload: "${mqtt_command_OFF}" then: - - switch.turn_off: Relay_1 - - topic: "${mqtt_remote_device1_status_topic}" - payload: "${mqtt_local_device_command_ON}" + - if: + condition: + - switch.is_on: Relay_1 + then: + - switch.turn_off: Relay_1 + + # Relay 2: only turn ON if currently OFF + - topic: "${mqtt_command_topic_2}" + payload: "${mqtt_command_ON}" then: - - switch.turn_on: Relay_2 - # Light control to turn off relay 2 - - topic: "${mqtt_remote_device1_status_topic}" - payload: "${mqtt_local_device_command_OFF}" + - if: + condition: + not: + - switch.is_on: Relay_2 + then: + - switch.turn_on: Relay_2 + + # Relay 2: only turn OFF if currently ON + - topic: "${mqtt_command_topic_2}" + payload: "${mqtt_command_OFF}" then: - - switch.turn_off: Relay_2 + - if: + condition: + - switch.is_on: Relay_2 + then: + - switch.turn_off: Relay_2 ######################################################################################### # STATUS LED @@ -223,13 +241,13 @@ binary_sensor: lambda: 'return id(Relay_2).state;' then: - mqtt.publish: - topic: "${mqtt_remote_device1_command_topic}" - payload: "${mqtt_remote_device_command_OFF}" + topic: "${mqtt_command_topic_2}" + payload: "${mqtt_command_OFF}" retain: false else: - mqtt.publish: - topic: "${mqtt_remote_device1_command_topic}" - payload: "${mqtt_remote_device_command_ON}" + topic: "${mqtt_command_topic_2}" + payload: "${mqtt_command_ON}" retain: false ######################################################################################### @@ -243,13 +261,13 @@ switch: id: Relay_1 on_turn_on: - mqtt.publish: - topic: "${mqtt_local_status_topic}" - payload: "${mqtt_local_device_command_ON}" + topic: "${mqtt_status_topic_1}" + payload: "${mqtt_command_ON}" retain: false on_turn_off: - mqtt.publish: - topic: "${mqtt_local_status_topic}" - payload: "${mqtt_local_device_command_OFF}" + topic: "${mqtt_status_topic_1}" + payload: "${mqtt_command_OFF}" retain: false - platform: gpio diff --git a/esphome/esp-centralstairs-top.yaml b/esphome/esp-centralstairs-top.yaml index d10962d..b72e744 100644 --- a/esphome/esp-centralstairs-top.yaml +++ b/esphome/esp-centralstairs-top.yaml @@ -18,49 +18,44 @@ # If NOT using a secrets file, just replace these with the passwords etc (in quotes) ########################################################################################## substitutions: - # Device Naming + # Device Custom Naming device_name: "esp-centralstairs-top" friendly_name: "Central Stair Lightswitch - Top (2)" description_comment: "Central Stair Lightswitch - Top, using Zemismart KS-811 Double Push Button. Main Stair Lights (1), Stair Footer Lights (2)" - device_area: "" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant. + device_area: "Lounge" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant. + static_ip_address: !secret esp-centralstairs-top_ip + mqtt_device_name_1: "stair-mainlights" + mqtt_device_name_2: "stair-footerlights" + + # I/O Naming + switch_1_name: "Main Stair Lights" # virtual only, nothing connected to this output + switch_2_name: "Stair Footer Lights" # Footer lights connected to this relay + #relay_1_name: "Garage Lights" + #button_1_name: "Power Button" + #relay_icon: "mdi:lightbulb-group" # Project Naming project_name: "Zemismart Technologies.KS-811 Double" # Project Details - project_version: "v3.7" # Project V denotes release of yaml file, allowing checking of deployed vs latest version + project_version: "v2.0" # Project V denotes release of yaml file, allowing checking of deployed vs latest version + + # MQTT Controls + mqtt_command_main_topic: !secret mqtt_command_main_topic + mqtt_status_main_topic: !secret mqtt_status_main_topic + mqtt_command_topic_1: "${mqtt_command_main_topic}/${mqtt_device_name_1}" + mqtt_status_topic_1: "${mqtt_status_main_topic}/${mqtt_device_name_1}" + mqtt_command_topic_2: "${mqtt_command_main_topic}/${mqtt_device_name_2}" + mqtt_status_topic_2: "${mqtt_status_main_topic}/${mqtt_device_name_2}" + mqtt_command_ON: "ON" + mqtt_command_OFF: "OFF" # Passwords & Secrets (unfortunately you can't use substitutions inside secrets names) api_key: !secret esp-api_key ota_pass: !secret esp-ota_pass - static_ip_address: !secret esp-centralstairs-top_ip - mqtt_command_main_topic: !secret mqtt_command_main_topic - mqtt_status_main_topic: !secret mqtt_status_main_topic - # Device Settings - #relay_icon: "mdi:lightbulb-group" - log_level: "INFO" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE + # General Settings + log_level: "ERROR" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE update_interval: "60s" # update time for for general sensors etc - # MQTT LOCAL Controls - mqtt_local_device_name: "stair-footerlights" - mqtt_local_command_topic: "${mqtt_command_main_topic}/${mqtt_local_device_name}" # Topic we will use to command this locally without HA - mqtt_local_status_topic: "${mqtt_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" - - # MQTT REMOTE Controls - mqtt_remote_device1_name: "stair-mainlights-lower" - mqtt_remote_device1_command_topic: "${mqtt_command_main_topic}/${mqtt_remote_device1_name}" - mqtt_remote_device1_status_topic: "${mqtt_status_main_topic}/${mqtt_remote_device1_name}" - #mqtt_remote_device2_name: "stair-mainlights-upper" - #mqtt_remote_device2_command_topic: "${mqtt_local_command_main_topic}/${mqtt_remote_device2_name}/relay3/set" - #mqtt_remote_device2_status_topic: "${mqtt_local_status_main_topic}/${mqtt_remote_device2_name}/relay3/state" - mqtt_remote_device_command_ON: "ON" - mqtt_remote_device_command_OFF: "OFF" - - # Switch Naming - switch_1_name: "Main Stair Lights" # virtual only, nothing connected to this output - switch_2_name: "Stair Footer Lights" - ######################################################################################### # PACKAGES: Included Common Packages # https://esphome.io/components/packages.html @@ -98,7 +93,7 @@ packages: #### 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_debug: !include common/include_debug_diag_sensors.yaml #diag_resetcount: !include common/include_resetcount_diag_sensors.yaml ######################################################################################### @@ -142,26 +137,67 @@ logger: # This adds device-specific MQTT command triggers to the common MQTT configuration. ########################################################################################## mqtt: + on_connect: + then: + - if: + # Status of relay 1, which has an actual light connected + condition: + lambda: 'return id(Relay_2).state;' + then: + - mqtt.publish: + topic: "${mqtt_status_topic_2}" + payload: "${mqtt_command_ON}" + qos: 0 + retain: false + else: + - mqtt.publish: + topic: "${mqtt_status_topic_2}" + payload: "${mqtt_command_OFF}" + qos: 0 + retain: false + on_message: - # Light control to turn on relay 2 - - topic: "${mqtt_local_command_topic}" - payload: "${mqtt_local_device_command_ON}" + # Relay 1: only turn ON if currently OFF + - topic: "${mqtt_command_topic_1}" + payload: "${mqtt_command_ON}" then: - - switch.turn_on: Relay_2 - # Light control to turn off relay 2 - - topic: "${mqtt_local_command_topic}" - payload: "${mqtt_local_device_command_OFF}" + - if: + condition: + not: + - switch.is_on: Relay_1 + then: + - switch.turn_on: Relay_1 + + # Relay 1: only turn OFF if currently ON + - topic: "${mqtt_command_topic_1}" + payload: "${mqtt_command_OFF}" then: - - switch.turn_off: Relay_2 - - topic: "${mqtt_remote_device1_status_topic}" - payload: "${mqtt_local_device_command_ON}" + - if: + condition: + - switch.is_on: Relay_1 + then: + - switch.turn_off: Relay_1 + + # Relay 2: only turn ON if currently OFF + - topic: "${mqtt_command_topic_2}" + payload: "${mqtt_command_ON}" then: - - switch.turn_on: Relay_1 - # Light control to turn off relay 2 - - topic: "${mqtt_remote_device1_status_topic}" - payload: "${mqtt_local_device_command_OFF}" + - if: + condition: + not: + - switch.is_on: Relay_2 + then: + - switch.turn_on: Relay_2 + + # Relay 2: only turn OFF if currently ON + - topic: "${mqtt_command_topic_2}" + payload: "${mqtt_command_OFF}" then: - - switch.turn_off: Relay_1 + - if: + condition: + - switch.is_on: Relay_2 + then: + - switch.turn_off: Relay_2 ######################################################################################### # STATUS LED @@ -193,13 +229,13 @@ binary_sensor: lambda: 'return id(Relay_1).state;' then: - mqtt.publish: - topic: "${mqtt_remote_device1_command_topic}" - payload: "${mqtt_remote_device_command_OFF}" + topic: "${mqtt_command_topic_1}" + payload: "${mqtt_command_OFF}" retain: false else: - mqtt.publish: - topic: "${mqtt_remote_device1_command_topic}" - payload: "${mqtt_remote_device_command_ON}" + topic: "${mqtt_command_topic_1}" + payload: "${mqtt_command_ON}" retain: false - platform: gpio @@ -231,13 +267,13 @@ switch: id: Relay_2 on_turn_on: - mqtt.publish: - topic: "${mqtt_local_status_topic}" - payload: "${mqtt_local_device_command_ON}" + topic: "${mqtt_status_topic_2}" + payload: "${mqtt_command_ON}" retain: false on_turn_off: - mqtt.publish: - topic: "${mqtt_local_status_topic}" - payload: "${mqtt_local_device_command_OFF}" + topic: "${mqtt_status_topic_2}" + payload: "${mqtt_command_OFF}" retain: false diff --git a/esphome/esp-downstairskitchleds.yaml b/esphome/esp-downstairskitchleds.yaml index 00e12ad..63320b2 100644 --- a/esphome/esp-downstairskitchleds.yaml +++ b/esphome/esp-downstairskitchleds.yaml @@ -80,8 +80,8 @@ substitutions: # 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_main_topic: !secret mqtt_command_main_topic + mqtt_local_status_main_topic: !secret mqtt_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" diff --git a/esphome/esp-downstloungeentry.yaml b/esphome/esp-downstloungeentry.yaml index a44b2b0..c88630f 100644 --- a/esphome/esp-downstloungeentry.yaml +++ b/esphome/esp-downstloungeentry.yaml @@ -31,8 +31,8 @@ substitutions: api_key: !secret esp-api_key # unfortunately you can't use substitutions inside secrets names ota_pass: !secret esp-ota_pass # unfortunately you can't use substitutions inside secrets names static_ip_address: !secret esp-downstloungeentry_ip - mqtt_command_main_topic: !secret mqtt_local_command_main_topic - mqtt_status_main_topic: !secret mqtt_local_status_main_topic + mqtt_command_main_topic: !secret mqtt_command_main_topic + mqtt_status_main_topic: !secret mqtt_status_main_topic # Device Settings log_level: "INFO" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE diff --git a/esphome/esp-downstloungemain.yaml b/esphome/esp-downstloungemain.yaml index e984a89..07f1d48 100644 --- a/esphome/esp-downstloungemain.yaml +++ b/esphome/esp-downstloungemain.yaml @@ -31,8 +31,8 @@ substitutions: api_key: !secret esp-api_key # unfortunately you can't use substitutions inside secrets names ota_pass: !secret esp-ota_pass # unfortunately you can't use substitutions inside secrets names static_ip_address: !secret esp-downstloungemain_ip - mqtt_command_main_topic: !secret mqtt_local_command_main_topic - mqtt_status_main_topic: !secret mqtt_local_status_main_topic + mqtt_command_main_topic: !secret mqtt_command_main_topic + mqtt_status_main_topic: !secret mqtt_status_main_topic # Device Settings log_level: "INFO" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE diff --git a/esphome/esp-garagebtproxy.yaml b/esphome/esp-garagebtproxy.yaml new file mode 100644 index 0000000..f028a2f --- /dev/null +++ b/esphome/esp-garagebtproxy.yaml @@ -0,0 +1,131 @@ +############################################# +############################################# +# ESP32 - Garage +# Bluetooth Proxy +############################################# +############################################# + +############################################# +# 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-garagebtproxy" + friendly_name: "Garage Entrance Bluetooth Proxy" + description_comment: "ESP32-WROOM garage entrance with BT Proxy" + device_area: "Garage" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant. + + # Project Naming + project_name: "Zemismart Technologies.KS-811-3 (Triple)" # Project Details + project_version: "v1" # Project V denotes release of yaml file, allowing checking of deployed vs latest version + + #entity_prefix: "Main Bathroom" # Simple device name where we want to prefix a sensor or switch, eg "Load" Current. + + # Passwords + api_key: !secret esp-api_key #unfortunately you can't use substitutions in secrets names + ota_pass: !secret esp-ota_pass #unfortunately you can't use substitutions in secrets names + static_ip_address: !secret esp-garagebtproxy_ip + #mqtt_local_command_main_topic: !secret mqtt_local_command_main_topic + #mqtt_local_status_main_topic: !secret mqtt_local_status_main_topic + + # Device Settings + #relay_icon: "mdi:heating-coil" + 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 + + ############################################# + # SPECIFIC PROJECT VARIABLE SUBSTITUTIONS + ############################################# + # + # + +########################################################################################## +# 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}" + + #### MQTT #### + common_mqtt: !include + file: common/mqtt_common.yaml + vars: + local_device_name: "${device_name}" + + #### 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 +# https://esphome.io/components/esphome.html +############################################# +esphome: + name: ${device_name} + friendly_name: ${friendly_name} + comment: ${description_comment} #appears on the esphome page in HA + min_version: 2024.6.0 # + area: ${device_area} + +############################################# +# ESP Platform and Framework +# https://esphome.io/components/esp32.html +############################################# +esp32: + board: esp32dev + framework: + #type: arduino + type: esp-idf #Suggested Use ESP-IDF Framework, or Plug Out the UART Cable Might Cause ESP32 Hang. + version: recommended #recommended, latest or dev + +############################################# +# ESPHome Logging Enable +# https://esphome.io/components/logger.html +############################################# +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) + #esp8266_store_log_strings_in_flash: false + #tx_buffer_size: 64 + +############################################# +# Bluetooth +# https://esphome.io/components/bluetooth_proxy.html +# https://esphome.io/components/esp32_ble_tracker.html +# Remember that this takes a LOT of processing. On the +# ESP32, enable the IDF framework, and disable the +# Web server component. Changing to the IDF framework +# needs to be via cable not OTA to change the +# partition setup. +############################################# +bluetooth_proxy: + active: true + +esp32_ble_tracker: + scan_parameters: + # We currently use the defaults to ensure Bluetooth + # can co-exist with WiFi In the future we may be able to + # enable the built-in coexistence logic in ESP-IDF + active: true + diff --git a/esphome/esp-garagedbcontrols.yaml b/esphome/esp-garagedbcontrols.yaml new file mode 100644 index 0000000..2de5021 --- /dev/null +++ b/esphome/esp-garagedbcontrols.yaml @@ -0,0 +1,371 @@ +############################################# +############################################# +# GARAGE DB CONTROLS +# Controlled by a Sonoff 4Ch R2 +# https://github.com/jvyoralek/homeassistant-config/blob/master/esphome/sonoff-4ch.yaml +# +# V1.0 2025-10-23 Initial Version +# +########################################################################################## +########################################################################################## + +########################################################################################## +# SPECIFIC DEVICE VARIABLE SUBSTITUTIONS +# If NOT using a secrets file, just replace these with the passwords etc (in quotes) +########################################################################################## +substitutions: + # Device Custom Naming + device_name: "esp-garagedbcontrols" + friendly_name: "Garage DB Control" + description_comment: "Garage DB Power, EV Power & Mesure, Lighting :: Sonoff 4ch R2" + device_area: "Garage" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant. + static_ip_address: !secret esp-garagedbcontrols_ip + #mqtt_device_name_1: "garage-dbcontrols" + + # I/O Naming + switch_1_name: "Small EV Charger" + button_1_name: "Button 1" + relay_1_icon: "mdi:power-socket-au" + switch_2_name: "Garage West Power" + button_2_name: "Button 2" + relay_2_icon: "mdi:power-socket-au" + switch_3_name: "Spare 3" + button_3_name: "Button 3" + relay_3_icon: "mdi:toggle-switch" + switch_4_name: "Spare 4" + button_4_name: "Button 4" + relay_4_icon: "mdi:toggle-switch" + + # Project Naming + project_name: "Sonoff Technologies.Sonoff 4Ch R2" # Project Details + project_version: "v1.0" # Project V denotes release of yaml file, allowing checking of deployed vs latest version + + # MQTT Controls + #mqtt_command_main_topic: !secret mqtt_command_main_topic + #mqtt_status_main_topic: !secret mqtt_status_main_topic + #mqtt_command_topic_1: "${mqtt_command_main_topic}/${mqtt_device_name_1}" + #mqtt_status_topic_1: "${mqtt_status_main_topic}/${mqtt_device_name_1}" + #mqtt_command_ON: "ON" + #mqtt_command_OFF: "OFF" + + # Passwords & Secrets (unfortunately you can't use substitutions inside secrets names) + api_key: !secret esp-api_key + ota_pass: !secret esp-ota_pass + + # General Settings + log_level: "ERROR" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE + update_interval: "60s" # update time for for general sensors etc + +########################################################################################## +# 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}" + + #### MQTT #### + common_mqtt: !include + file: common/mqtt_common.yaml + vars: + local_device_name: "${device_name}" + + #### 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 +# https://esphome.io/components/esphome.html +########################################################################################## +esphome: + name: "${device_name}" + friendly_name: "${friendly_name}" + comment: "${description_comment}" # Appears on the esphome page in HA + area: "${device_area}" + # On boot, initialise the window start so the first publish isn't huge + on_boot: + priority: -10 + then: + - lambda: |- + if (isfinite(id(ev_energy_total_kwh).state)) { + id(ev_last_total_kwh) = id(ev_energy_total_kwh).state; + } else { + id(ev_last_total_kwh) = 0.0f; + } + +########################################################################################## +# ESP Platform and Framework +# https://esphome.io/components/esp32.html +########################################################################################## +esp8266: + board: esp8285 + #board: esp01_1m + 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 + 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 + +########################################################################################## +# SWITCH COMPONENT +# https://esphome.io/components/switch/ +########################################################################################## +# Sonoff 4Ch R2 Relays are GPIO12,05,04,15 +############################################# +switch: + - platform: gpio + id: relay1 + name: "${switch_1_name}" + restore_mode: RESTORE_DEFAULT_OFF + pin: GPIO12 + icon: "${relay_1_icon}" + - platform: gpio + id: relay2 + name: "${switch_2_name}" + restore_mode: RESTORE_DEFAULT_ON + pin: GPIO5 + icon: "${relay_2_icon}" + - platform: gpio + id: relay3 + name: "${switch_3_name}" + restore_mode: RESTORE_DEFAULT_ON + pin: GPIO4 + icon: "${relay_3_icon}" + - platform: gpio + id: relay4 + name: "${switch_4_name}" + restore_mode: RESTORE_DEFAULT_OFF + pin: GPIO15 + icon: "${relay_4_icon}" + +########################################################################################## +# BINARY SENSORS +# https://esphome.io/components/binary_sensor/ +########################################################################################## +# Sonoff 4Ch R2 Buttons are GPIO00,09,10,14 +############################################# +binary_sensor: + - platform: gpio + id: button1 + name: "${button_1_name}" + pin: + number: GPIO0 + mode: INPUT_PULLUP + inverted: True + on_press: + - switch.toggle: relay1 + - platform: gpio + id: button2 + name: "${button_2_name}" + pin: + number: GPIO9 + mode: INPUT_PULLUP + inverted: True + on_press: + - switch.toggle: relay2 + - platform: gpio + id: button3 + name: "${button_3_name}" + pin: + number: GPIO10 + mode: INPUT_PULLUP + inverted: True + on_press: + - switch.toggle: relay3 + - platform: gpio + id: button4 + name: "${button_4_name}" + pin: + number: GPIO14 + mode: INPUT_PULLUP + inverted: True + on_press: + - switch.toggle: relay4 + +########################################################################################## +# STATUS LED +# https://esphome.io/components/status_led.html +########################################################################################## +status_led: + pin: + number: GPIO13 + inverted: yes + +########################################################################################## +# EV CHARGER ENERGY (PULSE INPUT ON GPIO2, 2.0 Wh PER PULSE) +# - Uses pulse_meter for stable pulse rate and total count +# - Derives instantaneous Power (W), 1h average Power, Today kWh, and lifetime kWh +########################################################################################## +sensor: + # Pulse rate -> Power Now (W) + - platform: pulse_meter + id: ev_pulse_pm + pin: + number: GPIO2 + mode: INPUT_PULLUP # GPIO2 must be HIGH at boot + inverted: false + name: "${switch_1_name} Power Now" + # pulse_meter reports pulses/min; each pulse = 2 Wh => W = pulses/min * 2 * 60 = x120 + unit_of_measurement: "W" + device_class: power + state_class: measurement + accuracy_decimals: 0 + internal_filter: 10ms # debounce pulses + timeout: 2min # set to 0 W if no pulses for 2 minutes + filters: + - multiply: 120.0 # convert pulses/min to Watts + + # Lifetime energy total (monotonic) + total: + id: ev_energy_total_kwh + name: "${switch_1_name} Energy Cumulative Total" + unit_of_measurement: "kWh" + device_class: energy + state_class: total_increasing + accuracy_decimals: 1 + filters: + - multiply: 0.002 # kWh per pulse (2.0 Wh = 0.002 kWh) + + # 1-hour sliding average of power (W) + - platform: template + id: ev_power_avg_1h + name: "${switch_1_name} Power (1h avg)" + unit_of_measurement: "W" + device_class: power + state_class: measurement + accuracy_decimals: 1 + update_interval: 10s + lambda: |- + return id(ev_pulse_pm).state; + filters: + - sliding_window_moving_average: + window_size: 360 # 10 s * 360 ≈ 1 hour + send_every: 6 # update HA once per minute + + # Today's energy (kWh), integrates "Power Now" and resets at local midnight + - platform: total_daily_energy + id: ev_energy_today_kwh + name: "${switch_1_name} Energy Today" + power_id: ev_pulse_pm + unit_of_measurement: "kWh" + device_class: energy + state_class: total + accuracy_decimals: 1 + filters: + - multiply: 0.001 # total_daily_energy outputs Wh; convert to kWh + +# Expose "Energy Yesterday" as a normal sensor + - platform: template + id: ev_energy_yesterday_sensor + name: "${switch_1_name} Energy Yesterday" + unit_of_measurement: "kWh" + device_class: energy + state_class: total + accuracy_decimals: 1 + update_interval: 30s + lambda: |- + return id(ev_energy_yesterday_kwh); + +########################################################################################## +# DHT SENSOR +# https://esphome.io/components/sensor/dht/ +########################################################################################## +#sensor: + - platform: dht + pin: GPIO3 + temperature: + name: "${friendly_name} Temperature" + humidity: + name: "${friendly_name} Humidity" + update_interval: 60s + +########################################################################################## +# Tasmota-like teleperiod publish of windowed Wh count every 60 s +########################################################################################## +# Store the last published total (kWh) +globals: + - id: ev_last_total_kwh + type: float + restore_value: true + initial_value: "0.0" + - id: ev_energy_yesterday_kwh + type: float + restore_value: true + initial_value: "0.0" + +# Teleperiod = 60s: publish JSON and advance the window +interval: + - interval: 60s + then: + - mqtt.publish: + topic: "stat/tasmo-s4chan-7594-garage-1/EnergyMeterCount" + qos: 0 + retain: false + payload: !lambda |- + // Current lifetime kWh from pulse_meter "total" + float current = id(ev_energy_total_kwh).state; + if (!isfinite(current)) current = id(ev_last_total_kwh); + + // Delta since last publish (kWh -> Wh) + float delta_kwh = current - id(ev_last_total_kwh); + if (delta_kwh < 0.0f || !isfinite(delta_kwh)) delta_kwh = 0.0f; + float delta_wh = delta_kwh * 1000.0f; + + // Advance the window (equivalent of "counter1 0") + id(ev_last_total_kwh) = current; + + // Build JSON payload + char buf[64]; + snprintf(buf, sizeof(buf), "{\"EVChargerWhCount\":%.3f}", delta_wh); + return std::string(buf); + +########################################################################################## +# YESTERDAY ENERGY (device-side snapshot of today's total at 23:59:59) +########################################################################################## +time: + - platform: sntp + id: ev_time_for_ev_snap + on_time: + - seconds: 59 + minutes: 59 + hours: 23 + then: + - lambda: |- + // Snapshot today's kWh just before midnight reset + if (isfinite(id(ev_energy_today_kwh).state)) { + id(ev_energy_yesterday_kwh) = id(ev_energy_today_kwh).state; + } + + diff --git a/esphome/esp-garageentrylights.yaml b/esphome/esp-garageentrylights.yaml new file mode 100644 index 0000000..d1ea735 --- /dev/null +++ b/esphome/esp-garageentrylights.yaml @@ -0,0 +1,197 @@ +############################################# +############################################# +# GARAGE ENTRY LIGHTSWITCH (OBK Converted, BK7231N) +# V1.0 2025-11-23 Initial +############################################# +# Zemismart KS-811 Triple push button +# pinout/schematic https://community.home-assistant.io/t/zemismart-ks-811-working-with-esphome/ +# +# NOTES +# - +# +############################################# +############################################# + +############################################# +# 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-garageentrylights" + friendly_name: "Garage Entry Lightswitch (3)" + description_comment: "BK7231N - Garage Entry Lightswitch using a Zemismart KS-811 Triple Push Button. Corridor Light (1), Patio Lights (2), Garage Lights (3)" + device_area: "Garage" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant. + + # Project Naming + project_name: "Zemismart Technologies.KS-811 Triple BK7231N" # Project Details + project_version: "v1.0" # Project V denotes release of yaml file, allowing checking of deployed vs latest version + + # Passwords + api_key: !secret esp-api_key # unfortunately you can't use substitutions inside secrets names + ota_pass: !secret esp-ota_pass # unfortunately you can't use substitutions inside secrets names + static_ip_address: !secret esp-garageentrylights_ip + + # Device Settings + 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 + + # Default relay restore mode + # Options: RESTORE_DEFAULT_OFF, RESTORE_DEFAULT_ON, ALWAYS_ON, ALWAYS_OFF + relay_restore_mode: "RESTORE_DEFAULT_OFF" + + # Switch Naming + switch_1_name: "Corridor Lights" # Only one light (Garage Side) actually connected to this relay + switch_2_name: "Patio Lights" # Output for pario string hanging lights + switch_3_name: "Garage Lights" # This is virtual only, no power connected to 3rd relay + +########################################################################################## +# 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}" + + #### MQTT #### + common_mqtt: !include + file: common/mqtt_common.yaml + vars: + local_device_name: "${device_name}" + + #### 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 +# https://esphome.io/components/esphome.html +############################################# +esphome: + name: "${device_name}" + friendly_name: "${friendly_name}" + comment: "${description_comment}" # Appears on the esphome page in HA + area: "${device_area}" + project: + name: "${project_name}" + version: "${project_version}" +# on_boot: +# priority: 200 +# then: +# - switch.turn_on: Relay_3 + +############################################# +# BUILD FOR BK CHIPSET +# bk72xx +# https://devices.esphome.io/board/bk72xx/ +############################################# +bk72xx: + board: generic-bk7231n-qfn32-tuya + +############################################# +# ESP Platform and Framework +# https://esphome.io/components/esp32.html +############################################# +#esp8266: +# board: esp01_1m +# early_pin_init: False # Initialise pins early to known values. Recommended false where switches are involved. Defaults to True. +# board_flash_mode: dout # Default is dout + +############################################# +# ESPHome Logging Enable +# https://esphome.io/components/logger.html +############################################# +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) + id: logger_id + +############################################# +# STATUS LED +# https://esphome.io/components/status_led.html +############################################# +status_led: + pin: + number: P22 #GPIO22 + inverted: true + +############################################# +# BINARY SENSORS +# https://esphome.io/components/binary_sensor/ +############################################# +binary_sensor: + - platform: gpio + pin: + number: P17 + mode: + input: true + pullup: true + inverted: true + name: "Button 1: ${switch_1_name}" + on_press: + - delay: 50ms + - switch.toggle: Relay_1 + + - platform: gpio + pin: + number: P26 + mode: + input: true + pullup: true + inverted: true + name: "Button 2: ${switch_2_name}" + on_press: + - delay: 50ms + - switch.toggle: Relay_2 + + - platform: gpio + pin: + number: P24 + mode: + input: true + pullup: true + inverted: true + name: "Button 3: ${switch_3_name}" + on_press: + - delay: 50ms + - switch.toggle: Relay_3 + +############################################# +# SWITCH COMPONENT +# https://esphome.io/components/switch/ +############################################# +switch: + - platform: gpio + name: "Relay 1: ${switch_1_name}" + pin: P14 #GPIO14 + id: Relay_1 + restore_mode: ${relay_restore_mode} + - platform: gpio + name: "Relay 2: ${switch_2_name}" + pin: P16 #GPIO16 + id: Relay_2 + restore_mode: ${relay_restore_mode} + - platform: gpio + name: "Relay 3: ${switch_3_name}" + pin: P15 #GPIO15 + id: Relay_3 + restore_mode: ${relay_restore_mode} \ No newline at end of file diff --git a/esphome/esp-garageentrylights2.yaml b/esphome/esp-garageentrylights2.yaml new file mode 100644 index 0000000..de0a55c --- /dev/null +++ b/esphome/esp-garageentrylights2.yaml @@ -0,0 +1,197 @@ +############################################# +############################################# +# GARAGE ENTRY LIGHTSWITCH 2 (OBK Converted, BK7231N) +# V1.0 2025-11-23 Initial +############################################# +# Zemismart KS-811 Triple push button +# pinout/schematic https://community.home-assistant.io/t/zemismart-ks-811-working-with-esphome/ +# +# NOTES +# - +# +############################################# +############################################# + +############################################# +# 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-garageentrylights2" + friendly_name: "Garage Entry Lightswitch (3) 2" + description_comment: "BK7231N - 2 Garage Entry Lightswitch using a Zemismart KS-811 Triple Push Button. Corridor Light (1), Patio Lights (2), Garage Lights (3)" + device_area: "Garage" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant. + + # Project Naming + project_name: "Zemismart Technologies.KS-811 Triple BK7231N" # Project Details + project_version: "v1.0" # Project V denotes release of yaml file, allowing checking of deployed vs latest version + + # Passwords + api_key: !secret esp-api_key # unfortunately you can't use substitutions inside secrets names + ota_pass: !secret esp-ota_pass # unfortunately you can't use substitutions inside secrets names + static_ip_address: !secret esp-garageentrylights2_ip + + # Device Settings + 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 + + # Default relay restore mode + # Options: RESTORE_DEFAULT_OFF, RESTORE_DEFAULT_ON, ALWAYS_ON, ALWAYS_OFF + relay_restore_mode: "RESTORE_DEFAULT_OFF" + + # Switch Naming + switch_1_name: "Corridor Lights" # Only one light (Garage Side) actually connected to this relay + switch_2_name: "Patio Lights" # Output for pario string hanging lights + switch_3_name: "Garage Lights" # This is virtual only, no power connected to 3rd relay + +########################################################################################## +# 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}" + + #### MQTT #### + common_mqtt: !include + file: common/mqtt_common.yaml + vars: + local_device_name: "${device_name}" + + #### 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 +# https://esphome.io/components/esphome.html +############################################# +esphome: + name: "${device_name}" + friendly_name: "${friendly_name}" + comment: "${description_comment}" # Appears on the esphome page in HA + area: "${device_area}" + project: + name: "${project_name}" + version: "${project_version}" +# on_boot: +# priority: 200 +# then: +# - switch.turn_on: Relay_3 + +############################################# +# BUILD FOR BK CHIPSET +# bk72xx +# https://devices.esphome.io/board/bk72xx/ +############################################# +bk72xx: + board: generic-bk7231n-qfn32-tuya + +############################################# +# ESP Platform and Framework +# https://esphome.io/components/esp32.html +############################################# +#esp8266: +# board: esp01_1m +# early_pin_init: False # Initialise pins early to known values. Recommended false where switches are involved. Defaults to True. +# board_flash_mode: dout # Default is dout + +############################################# +# ESPHome Logging Enable +# https://esphome.io/components/logger.html +############################################# +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) + id: logger_id + +############################################# +# STATUS LED +# https://esphome.io/components/status_led.html +############################################# +status_led: + pin: + number: P22 #GPIO22 + inverted: true + +############################################# +# BINARY SENSORS +# https://esphome.io/components/binary_sensor/ +############################################# +binary_sensor: + - platform: gpio + pin: + number: P17 + mode: + input: true + pullup: true + inverted: true + name: "Button 1: ${switch_1_name}" + on_press: + - delay: 50ms + - switch.toggle: Relay_1 + + - platform: gpio + pin: + number: P26 + mode: + input: true + pullup: true + inverted: true + name: "Button 2: ${switch_2_name}" + on_press: + - delay: 50ms + - switch.toggle: Relay_2 + + - platform: gpio + pin: + number: P24 + mode: + input: true + pullup: true + inverted: true + name: "Button 3: ${switch_3_name}" + on_press: + - delay: 50ms + - switch.toggle: Relay_3 + +############################################# +# SWITCH COMPONENT +# https://esphome.io/components/switch/ +############################################# +switch: + - platform: gpio + name: "Relay 1: ${switch_1_name}" + pin: P14 #GPIO14 + id: Relay_1 + restore_mode: ${relay_restore_mode} + - platform: gpio + name: "Relay 2: ${switch_2_name}" + pin: P16 #GPIO16 + id: Relay_2 + restore_mode: ${relay_restore_mode} + - platform: gpio + name: "Relay 3: ${switch_3_name}" + pin: P15 #GPIO15 + id: Relay_3 + restore_mode: ${relay_restore_mode} \ No newline at end of file diff --git a/esphome/esp-garageextcornerlight.yaml b/esphome/esp-garageextcornerlight.yaml new file mode 100644 index 0000000..f90950c --- /dev/null +++ b/esphome/esp-garageextcornerlight.yaml @@ -0,0 +1,240 @@ +############################################# +############################################# +# GARAGE LIGHTS +# Controlled by a Sonoff Basic R1 +# +# V2.0 2025-10-22 Latest layout with home MQTT code +# V1.0 2025-10-22 Initial Version +# +########################################################################################## +########################################################################################## + +########################################################################################## +# SPECIFIC DEVICE VARIABLE SUBSTITUTIONS +# If NOT using a secrets file, just replace these with the passwords etc (in quotes) +########################################################################################## +substitutions: + # Device Custom Naming + device_name: "esp-garageextcornerlight" + friendly_name: "Garage External Corner Light" + description_comment: "Garage External Corner Light :: Sonoff Basic" + device_area: "Garage" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant. + static_ip_address: !secret esp-garageextcornerlight_ip + mqtt_device_name: "garage-externalcorner-light" + + # Project Naming + project_name: "Sonoff Technologies.Sonoff Basic V1" # Project Details + project_version: "v2.0" # Project V denotes release of yaml file, allowing checking of deployed vs latest version + + # Passwords + api_key: !secret esp-api_key # unfortunately you can't use substitutions inside secrets names + ota_pass: !secret esp-ota_pass # unfortunately you can't use substitutions inside secrets names + mqtt_command_main_topic: !secret mqtt_command_main_topic + mqtt_status_main_topic: !secret mqtt_status_main_topic + + # Device Settings + relay_icon: "mdi:lightbulb" + log_level: "ERROR" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE + update_interval: "60s" # update time for for general sensors etc + + # Device Naming + relay_1_name: "Garage External Light" + button_1_name: "Power Button" + + # MQTT Controls + mqtt_command_topic: "${mqtt_command_main_topic}/${mqtt_device_name}" + mqtt_status_topic: "${mqtt_status_main_topic}/${mqtt_device_name}" + +########################################################################################## +# 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}" + + #### MQTT #### + common_mqtt: !include + file: common/mqtt_common.yaml + vars: + local_device_name: "${device_name}" + + #### 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 +# https://esphome.io/components/esphome.html +########################################################################################## +esphome: + name: "${device_name}" + friendly_name: "${friendly_name}" + comment: "${description_comment}" # Appears on the esphome page in HA + area: "${device_area}" +# platformio_options: +# build_flags: +# - "-Os" # optimize for size +# - "-Wl,--gc-sections" # drop unused code/data +# - "-fno-exceptions" # strip C++ exceptions +# - "-fno-rtti" # strip C++ RTTI + +########################################################################################## +# ESP Platform and Framework +# https://esphome.io/components/esp32.html +########################################################################################## +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 + 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 + +########################################################################################## +# SWITCH COMPONENT +# https://esphome.io/components/switch/ +########################################################################################## +# Sonoff Basic R1 Relay Switch is GPIO12 +############################################# +switch: + - platform: gpio + name: "${relay_1_name}" + pin: GPIO12 + id: relay1 + restore_mode: RESTORE_DEFAULT_OFF + icon: "${relay_icon}" + +########################################################################################## +# BINARY SENSORS +# https://esphome.io/components/binary_sensor/ +########################################################################################## +# Sonoff Basic R1 Button is GPIO03 +############################################# +binary_sensor: + + # Actual button input + - platform: gpio + pin: + number: GPIO03 + mode: INPUT_PULLUP + inverted: true + name: "${button_1_name}" + id: power_button + filters: + - delayed_on: 20ms + on_click: + - min_length: 20ms + max_length: 500ms + then: + - lambda: |- + if (id(relay1).state) { + // Relay is ON: turn it OFF + id(relay1).turn_off(); + } else { + // Relay is OFF: turn it ON + id(relay1).turn_on(); + } + + # Mimics actual relay status + - platform: template + name: "${relay_1_name} Status" + lambda: |- + return id(relay1).state; + on_press: + - mqtt.publish: + topic: "${mqtt_status_topic}" + payload: "ON" + on_release: + - mqtt.publish: + topic: "${mqtt_status_topic}" + payload: "OFF" + +########################################################################################## +# STATUS LED +# https://esphome.io/components/status_led.html +########################################################################################## +# Sonoff Basic R1 LED is GPIO13 +########################################################################################## +status_led: + pin: + number: GPIO13 + inverted: yes + +########################################################################################## +# MQTT COMMANDS +# This adds device-specific MQTT command triggers to the common MQTT configuration. +# Requires you to define: +# substitutions: +# mqtt_command_topic: "" +# mqtt_state_topic: "" +########################################################################################## +mqtt: + on_message: + # Relay 1 control (only act and publish if a change is needed) + - topic: "${mqtt_command_topic}" + payload: "ON" + then: + - if: + condition: + not: + switch.is_on: relay1 + then: + - switch.turn_on: relay1 + - mqtt.publish: + topic: "${mqtt_status_topic}" + payload: "ON" + #retain: true + + - topic: "${mqtt_command_topic}" + payload: "OFF" + then: + - if: + condition: + not: + switch.is_off: relay1 + then: + - switch.turn_off: relay1 + - mqtt.publish: + topic: "${mqtt_status_topic}" + payload: "OFF" + #retain: true + + # Announce current state whenever MQTT (re)connects + on_connect: + then: + - mqtt.publish: + topic: "${mqtt_status_topic}" + payload: !lambda 'return id(relay1).state ? "ON" : "OFF";' + #retain: true diff --git a/esphome/esp-garagelights.yaml b/esphome/esp-garagelights.yaml new file mode 100644 index 0000000..abea44d --- /dev/null +++ b/esphome/esp-garagelights.yaml @@ -0,0 +1,242 @@ +############################################# +############################################# +# GARAGE LIGHTS +# Controlled by a Sonoff Basic R1 +# +# V2.0 2025-10-22 Latest layout with home MQTT code +# V1.0 2025-10-22 Initial Version +# +########################################################################################## +########################################################################################## + +########################################################################################## +# SPECIFIC DEVICE VARIABLE SUBSTITUTIONS +# If NOT using a secrets file, just replace these with the passwords etc (in quotes) +########################################################################################## +substitutions: + # Device Custom Naming + device_name: "esp-garagelights" + friendly_name: "Garage Lights" + description_comment: "Garage Lights :: Sonoff Basic" + device_area: "Garage" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant. + static_ip_address: !secret esp-garagelights_ip + mqtt_device_name_1: "garage-lights" + + # I/O Naming + relay_1_name: "Garage Lights" + button_1_name: "Power Button" + relay_icon: "mdi:lightbulb-group" + + # Project Naming + project_name: "Sonoff Technologies.Sonoff Basic V1" # Project Details + project_version: "v2.0" # Project V denotes release of yaml file, allowing checking of deployed vs latest version + + # MQTT Controls + mqtt_command_main_topic: !secret mqtt_command_main_topic + mqtt_status_main_topic: !secret mqtt_status_main_topic + mqtt_command_topic_1: "${mqtt_command_main_topic}/${mqtt_device_name_1}" + mqtt_status_topic_1: "${mqtt_status_main_topic}/${mqtt_device_name_1}" + mqtt_command_ON: "ON" + mqtt_command_OFF: "OFF" + + # Passwords & Secrets (unfortunately you can't use substitutions inside secrets names) + api_key: !secret esp-api_key + ota_pass: !secret esp-ota_pass + + # General Settings + log_level: "ERROR" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE + update_interval: "60s" # update time for for general sensors etc + +########################################################################################## +# 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}" + + #### MQTT #### + common_mqtt: !include + file: common/mqtt_common.yaml + vars: + local_device_name: "${device_name}" + + #### 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 +# https://esphome.io/components/esphome.html +########################################################################################## +esphome: + name: "${device_name}" + friendly_name: "${friendly_name}" + comment: "${description_comment}" # Appears on the esphome page in HA + area: "${device_area}" +# platformio_options: +# build_flags: +# - "-Os" # optimize for size +# - "-Wl,--gc-sections" # drop unused code/data +# - "-fno-exceptions" # strip C++ exceptions +# - "-fno-rtti" # strip C++ RTTI + +########################################################################################## +# ESP Platform and Framework +# https://esphome.io/components/esp32.html +########################################################################################## +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 + 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 + +########################################################################################## +# SWITCH COMPONENT +# https://esphome.io/components/switch/ +########################################################################################## +# Sonoff Basic R1 Relay Switch is GPIO12 +############################################# +switch: + - platform: gpio + name: "${relay_1_name}" + pin: GPIO12 + id: relay1 + restore_mode: RESTORE_DEFAULT_OFF + icon: "${relay_icon}" + +########################################################################################## +# BINARY SENSORS +# https://esphome.io/components/binary_sensor/ +########################################################################################## +# Sonoff Basic R1 Button is GPIO03 +############################################# +binary_sensor: + + # Actual button input + - platform: gpio + pin: + number: GPIO03 + mode: INPUT_PULLUP + inverted: true + name: "${button_1_name}" + id: power_button + filters: + - delayed_on: 20ms + on_click: + - min_length: 20ms + max_length: 500ms + then: + - lambda: |- + if (id(relay1).state) { + // Relay is ON: turn it OFF + id(relay1).turn_off(); + } else { + // Relay is OFF: turn it ON + id(relay1).turn_on(); + } + + # Mimics actual relay status + - platform: template + name: "${relay_1_name} Status" + lambda: |- + return id(relay1).state; + on_press: + - mqtt.publish: + topic: "${mqtt_status_topic_1}" + payload: "${mqtt_command_ON}" + on_release: + - mqtt.publish: + topic: "${mqtt_status_topic_1}" + payload: "${mqtt_command_OFF}" + +########################################################################################## +# STATUS LED +# https://esphome.io/components/status_led.html +########################################################################################## +# Sonoff Basic R1 LED is GPIO13 +########################################################################################## +status_led: + pin: + number: GPIO13 + inverted: yes + +########################################################################################## +# MQTT COMMANDS +# This adds device-specific MQTT command triggers to the common MQTT configuration. +# Requires you to define: +# substitutions: +# mqtt_command_topic: "" +# mqtt_state_topic: "" +########################################################################################## +mqtt: + on_message: + # Relay 1 control (only act and publish if a change is needed) + - topic: "${mqtt_command_topic_1}" + payload: "${mqtt_command_ON}" + then: + - if: + condition: + not: + switch.is_on: relay1 + then: + - switch.turn_on: relay1 + - mqtt.publish: + topic: "${mqtt_status_topic_1}" + payload: "${mqtt_command_ON}" + #retain: true + + - topic: "${mqtt_command_topic_1}" + payload: "${mqtt_command_OFF}" + then: + - if: + condition: + not: + switch.is_off: relay1 + then: + - switch.turn_off: relay1 + - mqtt.publish: + topic: "${mqtt_status_topic_1}" + payload: "${mqtt_command_OFF}" + #retain: true + + # Announce current state whenever MQTT (re)connects + on_connect: + then: + - mqtt.publish: + topic: "${mqtt_status_topic_1}" + payload: !lambda 'return id(relay1).state ? "ON" : "OFF";' + #retain: true diff --git a/esphome/esp-loungebookshelfleds.yaml b/esphome/esp-loungebookshelfleds.yaml index 339bce7..ab8eabe 100644 --- a/esphome/esp-loungebookshelfleds.yaml +++ b/esphome/esp-loungebookshelfleds.yaml @@ -69,8 +69,8 @@ substitutions: # MQTT LOCAL Controls (This is just my local method of controlling via MQTT, I also use the built in method) mqtt_local_device_name: "lounge-bookshelfleds" - 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_main_topic: !secret mqtt_command_main_topic + mqtt_local_status_main_topic: !secret mqtt_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" diff --git a/esphome/esp-loungecabinetleds2.yaml b/esphome/esp-loungecabinetleds2.yaml index ffb8e5a..bc30eef 100644 --- a/esphome/esp-loungecabinetleds2.yaml +++ b/esphome/esp-loungecabinetleds2.yaml @@ -74,8 +74,8 @@ substitutions: # MQTT LOCAL Controls (This is just my local method of controlling via MQTT, I also use the built in method) mqtt_local_device_name: "lounge-cabinetleds" - 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_main_topic: !secret mqtt_command_main_topic + mqtt_local_status_main_topic: !secret mqtt_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" diff --git a/esphome/esp-loungepelmetleds2.yaml b/esphome/esp-loungepelmetleds2.yaml index c4be1b4..b0384c2 100644 --- a/esphome/esp-loungepelmetleds2.yaml +++ b/esphome/esp-loungepelmetleds2.yaml @@ -118,8 +118,8 @@ packages: #common_sntp: !include common/sntp_common.yaml 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_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 ########################################################################################## diff --git a/esphome/esp-maindishwasherspower.yaml b/esphome/esp-maindishwasherspower.yaml new file mode 100644 index 0000000..5f94ebc --- /dev/null +++ b/esphome/esp-maindishwasherspower.yaml @@ -0,0 +1,170 @@ +########################################################################################## +########################################################################################## +# MAIN DISHWASHER POWER +# Controlled by a Athom Smart Plug V1 +# package_import_url: github://athom-tech/athom-configs/athom-smart-plug.yaml +# +# V1.1 2025-06-12 package added for energy entities +# V1.0 2025-06-10 YAML Tidyups +# +########################################################################################## +########################################################################################## + +########################################################################################## +# 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-maindishwasherspower" + friendly_name: "Main Dishwashers Power" + description_comment: "Main Dishwashers Power Monitor :: Athom Smart Plug Power Monitor V1" + device_area: "Kitchen" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant. + + # Project Naming + project_name: "Athom Technology.Smart Plug V1" # Project Details + project_version: "v1.1" # Project V denotes release of yaml file, allowing checking of deployed vs latest version + + # Passwords + api_key: !secret esp-api_key # unfortunately you can't use substitutions inside secrets names + ota_pass: !secret esp-ota_pass # unfortunately you can't use substitutions inside secrets names + static_ip_address: !secret esp-maindishwasherspower_ip + + # Device Settings + 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 + + # Device Settings + relay_icon: "mdi:dishwasher" + current_limit : "10" # Current Limit in Amps. AU Plug = 10. IL, BR, EU, UK, US Plug = 16. + +########################################################################################## +# PACKAGES: Included Common Packages +# https://esphome.io/components/packages.html +########################################################################################## +packages: + 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}" + common_api: !include + file: common/api_common.yaml + vars: + local_api_key: "${api_key}" + #common_webportal: !include + # file: common/webportal_common.yaml + 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 + vars: + local_friendly_name: "${friendly_name}" + local_update_interval: "${update_interval}" + + # Device Specific included packages + common_athompowermonV1: !include + file: common/athompowermonv1_common.yaml + vars: + local_friendly_name: "${friendly_name}" + local_current_limit: "${current_limit}" + +########################################################################################## +# ESPHome +# https://esphome.io/components/esphome.html +########################################################################################## +esphome: + name: "${device_name}" + friendly_name: "${friendly_name}" + comment: "${description_comment}" # Appears on the esphome page in HA + area: "${device_area}" + name_add_mac_suffix: False + min_version: 2024.6.0 + project: + name: "${project_name}" + version: "${project_version}" + on_boot: + priority: 200 + then: + - switch.turn_on: "relay" + +########################################################################################## +# ESP Platform and Framework +# https://esphome.io/components/esp32.html +########################################################################################## +esp8266: + board: esp8285 + restore_from_flash: True # mainly for calculating cumulative energy, but not that important here + +preferences: + flash_write_interval: 5min + +mdns: + disabled: false + +#dashboard_import: +# package_import_url: github://athom-tech/esp32-configs/athom-smart-plug.yaml + +########################################################################################## +# ESPHome LOGGING +# https://esphome.io/components/logger.html +########################################################################################## +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) + #esp8266_store_log_strings_in_flash: false + #tx_buffer_size: 64 + +########################################################################################## +# STATUS LED +# https://esphome.io/components/status_led.html +########################################################################################## +status_led: + pin: + number: GPIO13 + inverted: True + +########################################################################################## +# BINARY SENSORS +# https://esphome.io/components/binary_sensor/ +########################################################################################## +binary_sensor: + - platform: gpio + pin: + number: 3 + mode: INPUT_PULLUP + inverted: true + name: "Power Button" + id: power_button + filters: + - delayed_on: 20ms + on_click: + - min_length: 20ms + max_length: 500ms + then: + - switch.toggle: + id: relay + + - platform: template + name: "Relay Status" + lambda: |- + return id(relay).state; + +################################################################################################# +# SWITCH COMPONENT +# https://esphome.io/components/switch/ +################################################################################################# +switch: + - platform: gpio + name: "Power Output" + pin: GPIO14 + id: relay + restore_mode: RESTORE_DEFAULT_ON # Ensures the relay is restored (or off) at boot + #internal: true # Hides the switch from Home Assistant + icon: "${relay_icon}" + diff --git a/esphome/esp-midesklamp1s.yaml b/esphome/esp-midesklamp1s.yaml index 9f6ead5..747a975 100644 --- a/esphome/esp-midesklamp1s.yaml +++ b/esphome/esp-midesklamp1s.yaml @@ -90,10 +90,13 @@ packages: ############################################# esphome: name: ${device_name} - friendly_name: ${friendly_name} # appears as main name on the esphome page in HA - comment: ${description_comment} # appears as comment on the esphome page in HA + friendly_name: ${friendly_name} + comment: ${description_comment} area: ${room} - #min_version: 2024.6.0 + #platformio_options: + # platform: espressif32@6.6.0 + # platform_packages: + # - framework-arduinoespressif32@2.0.17 ############################################# # ESP Platform and Framework @@ -102,15 +105,15 @@ esphome: esp32: board: esp32doit-devkit-v1 framework: - type: esp-idf # Suggest using the ESP-IDF Framework. Changing from 'arduino' to 'esp-idf' needs a cabled flash to correct partitions - version: recommended # recommended, latest or dev + type: arduino + version: recommended # these just for the esp32doit-devkit-v1 and Mi S Lamp - sdkconfig_options: - CONFIG_FREERTOS_UNICORE: y - advanced: - ignore_efuse_mac_crc: true - ignore_efuse_custom_mac: true + #sdkconfig_options: + # CONFIG_FREERTOS_UNICORE: y + #advanced: + # ignore_efuse_mac_crc: true + # ignore_efuse_custom_mac: true ############################################# # ESPHome Logging Enabl diff --git a/esphome/esp-officedeskrightgpo.yaml b/esphome/esp-officedeskrightgpo.yaml new file mode 100644 index 0000000..941c572 --- /dev/null +++ b/esphome/esp-officedeskrightgpo.yaml @@ -0,0 +1,207 @@ +############################################# +############################################# +# OFFICE GPO RIGHT CONTROL +# Controlled by a Sonoff Basic R1 +# +# V1.0 2025-06-14 Initial Version +# +########################################################################################## +########################################################################################## + +########################################################################################## +# 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-officedeskrightgpo" + friendly_name: "Office GPO Right" + description_comment: "Office (above desk) dial GPO and USB sockets power control :: Sonoff Basic" + device_area: "Office" # 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: "v1.0" # Project V denotes release of yaml file, allowing checking of deployed vs latest version + + # Passwords + api_key: !secret esp-api_key # unfortunately you can't use substitutions inside secrets names + ota_pass: !secret esp-ota_pass # unfortunately you can't use substitutions inside secrets names + static_ip_address: !secret esp-officedeskrightgpo_ip + mqtt_command_main_topic: !secret mqtt_command_main_topic + #mqtt_status_main_topic: !secret mqtt_status_main_topic + + # Device Settings + relay_icon: "mdi:generator-portable" + 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 + + # Device Naming + relay_1_name: "Office Right Hand GPO" + button_1_name: "Power Button" + + # MQTT Controls + mqtt_device_name: "office-deskright-gpo" + mqtt_main_topic: "${mqtt_command_main_topic}/${mqtt_device_name}" # Topic we will use to command stuff from external without HA + +########################################################################################## +# 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}" + + #### MQTT #### + common_mqtt: !include + file: common/mqtt_common.yaml + vars: + local_device_name: "${device_name}" + + #### 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 +# https://esphome.io/components/esphome.html +########################################################################################## +esphome: + name: "${device_name}" + friendly_name: "${friendly_name}" + comment: "${description_comment}" # Appears on the esphome page in HA + area: "${device_area}" +# platformio_options: +# build_flags: +# - "-Os" # optimize for size +# - "-Wl,--gc-sections" # drop unused code/data +# - "-fno-exceptions" # strip C++ exceptions +# - "-fno-rtti" # strip C++ RTTI + +########################################################################################## +# ESP Platform and Framework +# https://esphome.io/components/esp32.html +########################################################################################## +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 + 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 + +########################################################################################## +# SWITCH COMPONENT +# https://esphome.io/components/switch/ +########################################################################################## +# Sonoff Basic R1 Relay Switch is GPIO12 +############################################# +switch: + - platform: gpio + name: "${relay_1_name}" + pin: GPIO12 + id: relay1 + restore_mode: RESTORE_DEFAULT_ON + icon: "${relay_icon}" + +########################################################################################## +# BINARY SENSORS +# https://esphome.io/components/binary_sensor/ +########################################################################################## +# Sonoff Basic R1 Button is GPIO03 +############################################# +binary_sensor: + + - platform: gpio + pin: + number: GPIO03 + mode: INPUT_PULLUP + inverted: true + name: "${button_1_name}" + id: power_button + filters: + - delayed_on: 20ms + on_click: + - min_length: 20ms + max_length: 500ms + then: + - lambda: |- + if (id(relay1).state) { + // Relay is ON: turn it OFF + id(relay1).turn_off(); + } else { + // Relay is OFF: turn it ON + id(relay1).turn_on(); + } + + # Mimics actual relay status (but not controllable) + - platform: template + name: "${relay_1_name} Status" + lambda: |- + return id(relay1).state; + on_press: + - mqtt.publish: + topic: "${mqtt_topic}/relay1/state" + payload: "ON" + on_release: + - mqtt.publish: + topic: "${mqtt_topic}/relay1/state" + payload: "OFF" + +########################################################################################## +# STATUS LED +# https://esphome.io/components/status_led.html +########################################################################################## +# Sonoff Basic R1 LED is GPIO13 +############################################# +status_led: + pin: + number: GPIO13 + inverted: yes + +########################################################################################## +# MQTT COMMANDS +# This adds device-specific MQTT command triggers to the common MQTT configuration. +########################################################################################## +mqtt: + on_message: + # Relay 1 control + - topic: "${mqtt_main_topic}/relay1/set" + payload: "ON" + then: + - switch.turn_on: relay1 + - topic: "${mqtt_main_topic}/relay1/set" + payload: "OFF" + then: + - switch.turn_off: relay1 + diff --git a/esphome/esp-officeduallights.yaml b/esphome/esp-officeduallights.yaml index 0d70984..2d860a9 100644 --- a/esphome/esp-officeduallights.yaml +++ b/esphome/esp-officeduallights.yaml @@ -39,8 +39,8 @@ substitutions: api_key: !secret esp-api_key ota_pass: !secret esp-ota_pass static_ip_address: !secret esp-officeduallights_ip # unfortunately you can't use substitutions inside secrets names - 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_main_topic: !secret mqtt_command_main_topic + mqtt_local_status_main_topic: !secret mqtt_status_main_topic # Device Settings relay_icon: "mdi:lightbulb-group" diff --git a/esphome/esp-officelights copy.yaml b/esphome/esp-officelights copy.yaml new file mode 100644 index 0000000..c11f2db --- /dev/null +++ b/esphome/esp-officelights copy.yaml @@ -0,0 +1,176 @@ +############################################# +############################################# +# OFFICE MAIN LIGHTSWITCH +# V2.0 2025-06-05 YAML Tidyups +# V1.0 2025-05-31 Initial Version +############################################# +# Zemismart KS-811 Triple push button +# pinout/schematic https://community.home-assistant.io/t/zemismart-ks-811-working-with-esphome/ +# +# NOTES +# - +# +############################################# +############################################# + +############################################# +# 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-officelights" + friendly_name: "Office Main Lightswitch (3)" + description_comment: "Office Main Lightswitch using a Zemismart KS-811 Triple Push Button. Bunker Light A (1), Spare A (2), Spare B (3)" + device_area: "Office" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant. + + # Project Naming + project_name: "Zemismart Technologies.KS-811 Triple" # Project Details + project_version: "v2.0" # Project V denotes release of yaml file, allowing checking of deployed vs latest version + + # Passwords + api_key: !secret esp-api_key # unfortunately you can't use substitutions inside secrets names + ota_pass: !secret esp-ota_pass # unfortunately you can't use substitutions inside secrets names + static_ip_address: !secret esp-officelights_ip + + # Device Settings + 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 + + # Switch Naming + switch_1_name: "Nighttime Lights" # Only one light (Bunker Light) actually connected to this relay + switch_2_name: "Daytime Lights" # This is virtual only, no power connected to 2nd relay + switch_3_name: "Spare" # This is virtual only, no power connected to 3rd relay + +########################################################################################## +# 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}" + + #### MQTT #### + common_mqtt: !include + file: common/mqtt_common.yaml + vars: + local_device_name: "${device_name}" + + #### 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 +# https://esphome.io/components/esphome.html +############################################# +esphome: + name: "${device_name}" + friendly_name: "${friendly_name}" + comment: "${description_comment}" # Appears on the esphome page in HA + area: "${device_area}" + project: + name: "${project_name}" + version: "${project_version}" +# on_boot: +# priority: 200 +# then: +# - switch.turn_on: Relay_3 + +############################################# +# ESP Platform and Framework +# https://esphome.io/components/esp32.html +############################################# +esp8266: + board: esp01_1m + early_pin_init: False # Initialise pins early to known values. Recommended false where switches are involved. Defaults to True. + board_flash_mode: dout # Default is dout + +############################################# +# ESPHome Logging Enable +# https://esphome.io/components/logger.html +############################################# +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) + #esp8266_store_log_strings_in_flash: false + #tx_buffer_size: 64 + id: logger_id + +############################################# +# STATUS LED +# https://esphome.io/components/status_led.html +############################################# +status_led: + pin: + number: GPIO2 + inverted: yes + +############################################# +# BINARY SENSORS +# https://esphome.io/components/binary_sensor/ +############################################# +binary_sensor: + - platform: gpio + pin: + number: GPIO16 + mode: INPUT + inverted: True + name: "Button 1: ${switch_1_name}" + on_press: + - switch.toggle: Relay_1 + + - platform: gpio + pin: + number: GPIO05 + mode: INPUT + inverted: True + name: "Button 2: ${switch_2_name}" + on_press: + - switch.toggle: Relay_2 + + - platform: gpio + pin: + number: GPIO4 + mode: INPUT + inverted: True + name: "Button 3: ${switch_3_name}" + on_press: + - switch.toggle: Relay_3 + +############################################# +# SWITCH COMPONENT +# https://esphome.io/components/switch/ +############################################# +switch: + - platform: gpio + name: "Relay 1: ${switch_1_name}" + pin: GPIO13 + id: Relay_1 + - platform: gpio + name: "Relay 2: ${switch_2_name}" + pin: GPIO12 + id: Relay_2 + - platform: gpio + name: "Relay 3: ${switch_3_name}" + pin: GPIO14 + id: Relay_3 \ No newline at end of file diff --git a/esphome/esp-poollightpower copy.yaml.old b/esphome/esp-poollightpower copy.yaml.old new file mode 100644 index 0000000..c17588f --- /dev/null +++ b/esphome/esp-poollightpower copy.yaml.old @@ -0,0 +1,1038 @@ +########################################################################################## +########################################################################################## +# POOL LIGHT POWER AND TIMER +# Controlled by a Athom Smart Plug V1 +# +# dashboard_import: +# package_import_url: github://athom-tech/esp32-configs/athom-smart-plug.yaml +# +# V3.0 2025-09-02 Pool Light mode controller fixes; Mode select forces Operation=ON; +# added Mode 0=OFF; select shows OFF when relay off; enforce 7s min OFF window +# V2.4 2025-06-15 Changed back to an Athom V1 (esp8266) +# V2.3 2025-06-15 Changed to an Athom V3 (esp32) +# V2.2 2025-06-14 Fixes to offline time when sntp/network unavailable +# V2.1 2025-06-12 Added select and button to chose modes, added countdown & startup to boost +# V2.0 2025-06-05 YAML Tidyups +# +# INSTRUCTIONS +# - 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 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 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 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) +# +# operation_mode: +# 0 = OFF +# 1 = ON +# 2 = TIMER +# 3 = BOOST +# +########################################################################################## +########################################################################################## + + +########################################################################################## +# 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-poollightpower" + friendly_name: "Pool Light Power" + description_comment: "Pool Light Power :: Athom Smart Plug Power V1" + device_area: "Outside" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant. + + # Project Naming + project_name: "Athom Technology.Smart Plug V1" # Project Details + project_version: "v3.0" # Project V denotes release of yaml file, allowing checking of deployed vs latest version + + # Passwords + api_key: !secret esp-api_key # unfortunately you can't use substitutions inside secrets names + ota_pass: !secret esp-ota_pass # unfortunately you can't use substitutions inside secrets names + static_ip_address: !secret esp-poollightpower_ip + + # Device Settings + log_level: "NONE" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE + update_interval: "10s" # update time for for general sensors etc + + # Device Settings + relay_icon: "mdi:power-socket-au" + current_limit : "10" # Current Limit in Amps. AU Plug = 10. IL, BR, EU, UK, US Plug = 16. + mqtt_timer_topic: "viewroad-commands/poollight-timer" # Topics you will use to change stuff + boost_duration_default: "180" # Minutes to stay ON in BOOST mode before reverting to TIMER + morning_on_default: "450" # Default in minutes from midnight. Default 07:30 => 450 + morning_off_default: "450" # Default in minutes from midnight. Default 07:30 => 450 (same as ON as no need for morning schedule) + evening_on_default: "1140" # Default in minutes from midnight. Default 19:00 => 1140 + evening_off_default: "1350" # Default in minutes from midnight. Default 22:30 => 1350 => 1440 is midnight + + ############################################################################## + # POOL LIGHT MODE CONTROL (new) + ############################################################################## + max_modes: "16" # total number of modes in the cycle + mode_pulse_off: "400ms" # short OFF between quick pulses + mode_pulse_on: "400ms" # short ON after each quick pulse + mode_reset_off: "3s" # long OFF to force hardware reset to mode 1 + mode_reset_window_ms: "3000" # treat OFF>=this ms as a reset-to-1 when turning back ON + mode_prime_on: "800ms" # if relay is OFF when a color is selected, turn ON for this long before pulsing + # Ignored modes bitmask: bit (mode_index-1). For 4 and 5 ignored -> (1<<3)|(1<<4) = 24. + ignored_modes_mask: "8288" # Ignore 6(32), 7(64), 14(8192) :: 32 + 64 + 8192 = 8288 + +########################################################################################## +# PACKAGES: Included Common Packages +# https://esphome.io/components/packages.html +########################################################################################## +packages: + ################################################## + # MANDATORY packages (won't compile without them!) + ################################################## + + #### 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}" + + ################################################## + # OPTIONAL packages (comment if you don't want them) + ################################################## + + #### 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}" + + #### WEB PORTAL #### + #common_webportal: !include + # file: common/webportal_common.yaml + + #### MQTT #### + common_mqtt: !include + file: common/mqtt_common.yaml + vars: + local_device_name: "${device_name}" + + #### SNTP (Only use if you want/need accurate timeclocks) #### + common_sntp: !include + file: common/sntp_common.yaml + + #### DIAGNOSTICS Lite Sensors #### + common_lite_sensors: !include + file: common/sensors_common_lite.yaml + + #### DIAGNOSTICS General Sensors #### + common_general_sensors: !include + file: common/sensors_common.yaml + + #### DEBUGGING Sensors #### + # A count of various resets + #common_resetcount_debugging: !include + # file: common/resetcount_common.yaml + + # Device Specific included packages + common_athompowermonV1: !include + file: common/athompowermonv1_common.yaml + vars: + local_friendly_name: "${friendly_name}" + local_current_limit: "${current_limit}" + +########################################################################################## +# ESPHome +# https://esphome.io/components/esphome.html +########################################################################################## +esphome: + name: "${device_name}" + friendly_name: "${friendly_name}" + comment: "${description_comment}" #Appears on the esphome page in HA + area: "${device_area}" + name_add_mac_suffix: False + min_version: 2024.6.0 + project: + name: "${project_name}" + version: "${project_version}" + #platformio_options: + # build_unflags: + # - -std=gnu++20 + # - -std=gnu++2a + # build_flags: + # - -std=gnu++11 + # - -Os + # - -Wl,--gc-sections + # - -fno-exceptions + # - -fno-rtti + +########################################################################################## +# ESP Platform and Framework +# https://esphome.io/components/esp32.html +########################################################################################## +esp8266: + board: esp8285 + restore_from_flash: true # mainly for calculating cumulative energy, but not that important here + #framework: + # version: 2.7.4 + +preferences: + flash_write_interval: 10min + +mdns: + disabled: True # binary size saving + +########################################################################################## +# ESPHome Logging Enable +# https://esphome.io/components/logger.html +########################################################################################## +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) + #esp8266_store_log_strings_in_flash: false + #tx_buffer_size: 64 + +########################################################################################## +# Global Variables for use in automations etc +# https://esphome.io/guides/automations.html?highlight=globals#global-variables +########################################################################################## +globals: + + # Tracks the time (in seconds from midnight) at the previous boot + - id: last_boot_time_s + type: int + restore_value: true + initial_value: "0" + + # Counts how many consecutive boots have occurred (within X seconds) + - id: boot_count + type: int + restore_value: true + initial_value: "0" + + # Morning On time (minutes from midnight), + - id: morning_on + type: int + restore_value: true + initial_value: "${morning_on_default}" + + # Morning Off time (minutes from midnight), + - id: morning_off + type: int + restore_value: true + initial_value: "${morning_off_default}" + + # Evening On time (minutes from midnight), + - id: evening_on + type: int + restore_value: true + initial_value: "${evening_on_default}" + + # Evening Off time (minutes from midnight), + - id: evening_off + type: int + restore_value: true + initial_value: "${evening_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 = BOOST + #################################################### + - id: operation_mode + type: int + restore_value: true + initial_value: "2" + + #################################################### + # current_mins is set if SNTP is invalid. + # We assume user powers on the device at 12:00 noon + # => 12 * 60 = 720 minutes from midnight. + #################################################### + - id: current_mins + type: int + restore_value: true + initial_value: "720" # 720 is 12:00 Noon + + #################################################### + # boost_timer: counts minutes in BOOST mode + # After 'boost_duration' minutes, revert to TIMER. + #################################################### + - id: boost_timer + type: int + restore_value: true + initial_value: "0" + + ############################################################################## + # POOL LIGHT MODE CONTROL GLOBALS (new) + ############################################################################## + # Current assumed pool-light mode (0..max_modes). 0 means relay OFF. + - id: current_mode + type: int + restore_value: false + initial_value: "1" + + # Total modes in the cycle (edit in substitutions). + - id: max_modes + type: int + restore_value: false + initial_value: "${max_modes}" + + # Flag while we are actively pulsing to change modes (prevents scheduler interference). + - id: mode_changing + type: bool + restore_value: false + initial_value: "false" + + # Timestamp of last relay off (for delta measurement). + - id: last_off_ms + type: uint32_t + restore_value: false + initial_value: "0" + + # Millisecond threshold that separates "quick pulse" vs "reset to mode 1". + - id: reset_window_ms + type: int + restore_value: false + initial_value: "${mode_reset_window_ms}" + + # Desired target mode for the cycle script. + - id: desired_mode + type: int + restore_value: false + initial_value: "1" + + # Bitmask of ignored modes (1..max_modes). Example: ignore 4 & 5 -> 24. + - id: ignored_mask + type: int + restore_value: false + initial_value: "${ignored_modes_mask}" + + # Internal: whether a recheck is already scheduled for min OFF enforcement. + - id: recheck_pending + type: bool + restore_value: false + initial_value: "false" + +########################################################################################## +# Text Sensors +# https://esphome.io/components/text_sensor/index.html +########################################################################################## +text_sensor: + +############################ +# MQTT Subscriptions +############################ + #################################################### + # Subscribe to the Morning On time, format "HH:MM" + #################################################### + - platform: mqtt_subscribe + name: "Morning On Time Setting" + id: morning_on_topic + topic: "${mqtt_timer_topic}/morning-on" # Stored in the format HH:MM + internal: True + on_value: + then: + - lambda: |- + // Expect "HH:MM" => total length = 5, with ':' + if (x.size() == 5 && x[2] == ':') { + int hour = atoi(x.substr(0, 2).c_str()); // "HH" + int minute = atoi(x.substr(3, 2).c_str()); // "MM" + id(morning_on) = hour * 60 + minute; + ESP_LOGI("timer","Received new Morning On: %02d:%02d", hour, minute); + } else { + ESP_LOGW("timer","Invalid Morning On format: %s", x.c_str()); + } + #################################################### + # Morning Off time => "HH:MM" + #################################################### + - platform: mqtt_subscribe + name: "Morning Off Time Setting" + id: morning_off_topic + topic: "${mqtt_timer_topic}/morning-off" # Stored in the format HH:MM + internal: True # No need to show this in Home Assistant as there is a sensor that shows the set value + on_value: + then: + - lambda: |- + if (x.size() == 5 && x[2] == ':') { + int hour = atoi(x.substr(0, 2).c_str()); + int minute = atoi(x.substr(3, 2).c_str()); + id(morning_off) = hour * 60 + minute; + ESP_LOGI("timer","Received new Morning Off: %02d:%02d", hour, minute); + } else { + ESP_LOGW("timer","Invalid Morning Off format: %s", x.c_str()); + } + #################################################### + # Evening On time => "HH:MM" + #################################################### + - platform: mqtt_subscribe + name: "Evening On Time Setting" + id: evening_on_topic + topic: "${mqtt_timer_topic}/evening-on" # Stored in the format HH:MM + internal: True # No need to show this in Home Assistant as there is a sensor that shows the set value + on_value: + then: + - lambda: |- + if (x.size() == 5 && x[2] == ':') { + int hour = atoi(x.substr(0, 2).c_str()); + int minute = atoi(x.substr(3, 2).c_str()); + id(evening_on) = hour * 60 + minute; + ESP_LOGI("timer","Received new Evening On: %02d:%02d", hour, minute); + } else { + ESP_LOGW("timer","Invalid Evening On format: %s", x.c_str()); + } + #################################################### + # Evening Off time => "HH:MM" + #################################################### + - platform: mqtt_subscribe + name: "Evening Off Time Setting" + id: evening_off_topic + topic: "${mqtt_timer_topic}/evening-off" # Stored in the format HH:MM + internal: True # No need to show this in Home Assistant as there is a sensor that shows the set value + on_value: + then: + - lambda: |- + if (x.size() == 5 && x[2] == ':') { + int hour = atoi(x.substr(0, 2).c_str()); + int minute = atoi(x.substr(3, 2).c_str()); + id(evening_off) = hour * 60 + minute; + ESP_LOGI("timer","Received new Evening Off: %02d:%02d", hour, minute); + } else { + 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 0–1439 + 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(v); + } + + #################################################### + # Subscribe to operation mode: + # OFF, ON, TIMER, BOOST + #################################################### + # MQTT subscription: set mode, then immediately re-evaluate relay + - platform: mqtt_subscribe + id: timer_operation_mode_topic + topic: "${mqtt_timer_topic}/operation" + internal: True # No need to show this in Home Assistant as there is a sensor that shows the set value + on_value: + then: + - lambda: |- + if (strcasecmp(x.c_str(), "TIMER") == 0) { + id(operation_mode) = 2; + ESP_LOGI("timer","Operation mode set to TIMER"); + } else if (strcasecmp(x.c_str(), "ON") == 0) { + id(operation_mode) = 1; + ESP_LOGI("timer","Operation mode set to ON"); + } 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(), "BOOST") == 0) { + id(operation_mode) = 3; + id(boost_timer) = 0; + ESP_LOGI("timer","Operation mode set to BOOST"); + } else { + ESP_LOGW("timer","Invalid operation mode: %s", x.c_str()); + } + - script.execute: evaluate_relay_state + + ###################################################### + # Expose the current operation mode (OFF, ON, TIMER, BOOST) + ###################################################### + - platform: template + name: "Operation Mode State" + lambda: |- + // 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 {"BOOST"}; + default: return {"UNKNOWN"}; + } + update_interval: 5s + + ###################################################### + # Expose the "Morning On" time as a text (HH:MM) + ###################################################### + - platform: template + name: "Timeclock: Morning On Time" + lambda: |- + int hour = id(morning_on) / 60; + int minute = id(morning_on) % 60; + // Increase to 16 for safety + char buff[16]; + snprintf(buff, sizeof(buff), "%02d:%02d", hour, minute); + return { std::string(buff) }; + update_interval: "${update_interval}" + + ###################################################### + # Expose the "Morning Off" time as a text (HH:MM) + ###################################################### + - platform: template + name: "Timeclock: Morning Off Time" + lambda: |- + int hour = id(morning_off) / 60; + int minute = id(morning_off) % 60; + // Increase to 16 for safety + char buff[16]; + snprintf(buff, sizeof(buff), "%02d:%02d", hour, minute); + return { std::string(buff) }; + update_interval: "${update_interval}" + + ###################################################### + # Expose the "Evening On" time as a text (HH:MM) + ###################################################### + - platform: template + name: "Timeclock: Evening On Time" + lambda: |- + int hour = id(evening_on) / 60; + int minute = id(evening_on) % 60; + // Increase to 16 for safety + char buff[16]; + snprintf(buff, sizeof(buff), "%02d:%02d", hour, minute); + return { std::string(buff) }; + update_interval: "${update_interval}" + + ###################################################### + # Expose the "Evening Off" time as a text (HH:MM) + ###################################################### + - platform: template + name: "Timeclock: Evening Off Time" + lambda: |- + int hour = id(evening_off) / 60; + int minute = id(evening_off) % 60; + // Increase to 16 for safety + char buff[16]; + snprintf(buff, sizeof(buff), "%02d:%02d", hour, minute); + return { std::string(buff) }; + update_interval: "${update_interval}" + +########################################################################################## +# BINARY SENSORS +# https://esphome.io/components/binary_sensor/ +########################################################################################## +binary_sensor: + - platform: gpio + pin: + number: GPIO03 + mode: INPUT_PULLUP + inverted: true + name: "Power Button" + id: power_button + filters: + - delayed_on: 20ms + on_click: + - min_length: 20ms + max_length: 500ms + then: + - lambda: |- + if (id(relay).state) { + // Relay is ON: turn it OFF and set mode to 2 (TIMER) + id(relay).turn_off(); + id(operation_mode) = 2; + } else { + // Relay is OFF: turn it ON and set mode to 3 (BOOST) + id(relay).turn_on(); + id(operation_mode) = 3; + } + + - platform: template + name: "Relay Status" + lambda: |- + return id(relay).state; + +########################################################################################## +# Sensors +# https://esphome.io/components/text_sensor/index.html +########################################################################################## +sensor: + - platform: template + name: "Timeclock: Boost Duration" + id: boost_duration_time + unit_of_measurement: "mins" + accuracy_decimals: "0" + update_interval: "${update_interval}" + lambda: |- + return id(boost_duration); + + - platform: template + name: "Mins from Midnight" + id: mins_from_midnight + unit_of_measurement: "mins" + accuracy_decimals: "0" + update_interval: "${update_interval}" + internal: True # No need to show this in Home Assistant + 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; + + +################################################################################################# +# SWITCH COMPONENT +# https://esphome.io/components/switch/ +################################################################################################# +switch: + - platform: gpio + name: "Power Output" + pin: GPIO14 + id: relay + restore_mode: RESTORE_DEFAULT_OFF # Ensures the relay is restored (or off) at boot + #internal: true # Hides the switch from Home Assistant + icon: "${relay_icon}" + # POOL LIGHT MODE CONTROL: detect quick vs long off periods and keep current_mode in sync + on_turn_off: + - lambda: |- + id(last_off_ms) = millis(); + if (!id(mode_changing)) id(current_mode) = 0; // reflect OFF in select when off normally + on_turn_on: + - lambda: |- + if (id(mode_changing)) { + return; + } + uint32_t delta = millis() - id(last_off_ms); + if (delta >= (uint32_t)id(reset_window_ms)) { + id(current_mode) = 1; + } else { + id(current_mode)++; + if (id(current_mode) > id(max_modes)) id(current_mode) = 1; // keep internal index sane + } + +################################################################################################# +# BUTTON COMPONENT +# https://esphome.io/components/button/index.html +################################################################################################# +button: + - platform: template + name: "Boost now" + id: boost_button + icon: "mdi:play-circle-outline" + on_press: + # 1) reset BOOST timer and set mode + - lambda: |- + id(boost_timer) = 0; + id(operation_mode) = 3; + # 2) immediately re-evaluate relay state + - script.execute: evaluate_relay_state + - platform: template + name: "Default timer settings" + id: default_timer_settings_button + icon: "mdi:restore" + on_press: + - lambda: |- + // Restore all timing globals to their YAML defaults + id(morning_on) = ${morning_on_default}; + id(morning_off) = ${morning_off_default}; + id(evening_on) = ${evening_on_default}; + id(evening_off) = ${evening_off_default}; + id(boost_duration)= ${boost_duration_default}; + // Reset mode to TIMER and clear any running boost + id(operation_mode)= 2; + id(boost_timer) = 0; + ESP_LOGI("timer","Default timer settings applied"); + - script.execute: evaluate_relay_state + +################################################################################################# +# SELECT COMPONENT +# https://esphome.io/components/select/index.html +################################################################################################# +select: + - platform: template + name: "Operation Mode" + id: operation_mode_select + update_interval: 5s + options: + - "OFF" + - "ON" + - "TIMER" + - "BOOST" + + # show the current mode + 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"); + } + + # when changed in HA, set mode & re-evaluate + 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 { // BOOST + id(boost_timer) = 0; + id(operation_mode) = 3; + } + - script.execute: evaluate_relay_state + + ############################################################################## + # POOL LIGHT MODE SELECT (new) + # 0=OFF -> immediately turns relay OFF and sets Operation Mode = TIMER. + # Selecting a color (>=1) forces Operation Mode = ON. + # If target < current, do a long reset to mode 1, then pulse forward. + # Ignored modes are hidden here but still counted by pulses. + ############################################################################## + ############################################################################## + # POOL LIGHT MODE SELECT (updated display logic) + # 0=OFF -> immediately turns relay OFF and sets Operation Mode = TIMER. + # Selecting a color (>=1) forces Operation Mode = ON. + # If target < current, do a long reset to mode 1, then pulse forward. + # Ignored modes are hidden here but still counted by pulses. + ############################################################################## + - platform: template + name: "Pool Light Mode" + id: pool_light_mode_select + update_interval: 250ms + # Options include all 1..16 (no ignored modes currently) plus 0=OFF + options: + - "0= OFF" + - "1= Dark Blue" + - "2= Red" + - "3= Green" + - "4= Purple" + - "5= Aqua" + #- "6= Lime" + #- "7= Cool White" + - "8= Speed Up" + - "9= Transformer" + - "10= Blurple" + - "11= Redlime" + - "12= Greenqua" + - "13= Bluequa" + #- "14= Grelime" + - "15= Redurple" + - "16= RGB Mad" + + # Show OFF only when not in a color-change sequence. + # While changing, reflect the in-flight/current mode (never 0). + lambda: |- + auto label_for = [](int m) -> std::string { + switch (m) { + case 0: return "0= OFF"; + case 1: return "1= Dark Blue"; + case 2: return "2= Red"; + case 3: return "3= Green"; + case 4: return "4= Purple"; + case 5: return "5= Aqua"; + case 6: return "6= Lime"; + case 7: return "7= Cool White"; + case 8: return "8= Speed Up"; + case 9: return "9= Transformer"; + case 10: return "10= Blurple"; + case 11: return "11= Redlime"; + case 12: return "12= Greenqua"; + case 13: return "13= Bluequa"; + case 14: return "14= Grelime"; + case 15: return "15= Redurple"; + case 16: return "16= RGB Mad"; + default: return "1= Dark Blue"; + } + }; + auto is_ignored = [&](int m) -> bool { + if (m < 1 || m > id(max_modes)) return true; + int bit = 1 << (m - 1); + return (id(ignored_mask) & bit) != 0; + }; + + // While stepping (mode_changing), don't show OFF even if relay is briefly OFF. + if (id(mode_changing)) { + int cm = id(current_mode); + if (cm <= 0) cm = 1; // during long reset, assume Mode 1 is next + // Skip ignored modes for display if ever configured later + if (!is_ignored(cm)) return label_for(cm); + // find next non-ignored just for display robustness + for (int m = cm + 1; m <= id(max_modes); m++) if (!is_ignored(m)) return label_for(m); + for (int m = 1; m <= id(max_modes); m++) if (!is_ignored(m)) return label_for(m); + return label_for(1); + } + + // Normal (not changing): show OFF if relay is actually OFF, else show current mode + if (!id(relay).state) return std::string("0= OFF"); + + int cm = id(current_mode); + if (cm == 0) return std::string("0= OFF"); + if (!is_ignored(cm)) return label_for(cm); + for (int m = cm + 1; m <= id(max_modes); m++) if (!is_ignored(m)) return label_for(m); + for (int m = 1; m <= id(max_modes); m++) if (!is_ignored(m)) return label_for(m); + return label_for(1); + + set_action: + # First, set flags based on selection + - lambda: |- + int target = atoi(x.c_str()); + if (target < 0) target = 0; + if (target > id(max_modes)) target = id(max_modes); + + if (target == 0) { + // MODE 0: force everything OFF; UI goes back to TIMER control + id(mode_changing) = false; + id(recheck_pending) = false; + id(operation_mode) = 2; // TIMER + id(current_mode) = 0; // reflect OFF in dropdown + } else { + // defensive: ignore choosing an ignored mode (options already hide them) + int bit = 1 << (target - 1); + if ((id(ignored_mask) & bit) != 0) { + ESP_LOGW("mode","Selected target %d is ignored; ignoring request", target); + return; + } + // Color selection: force ON mode and start changer + id(operation_mode) = 1; + id(desired_mode) = target; + id(mode_changing) = true; + } + + # If OFF was selected, hard-stop any running scripts and cut power + - if: + condition: + lambda: 'return atoi(x.c_str()) == 0;' + then: + - script.stop: change_to_desired_mode + - script.stop: reset_to_mode1 + - script.stop: enforce_off_guard + - switch.turn_off: relay + else: + - script.execute: change_to_desired_mode + +################################################################################################# +# SCRIPT COMPONENT +# https://esphome.io/components/script.html +################################################################################################# +script: + # Core: evaluate and drive the relay (with enforced min OFF window) + - id: evaluate_relay_state + then: + - lambda: |- + if (id(mode_changing)) { + // do not fight the pulser + return; + } + // Determine target state + bool target_on = false; + int mode = id(operation_mode); + + if (mode == 3) { // BOOST + target_on = true; + } else if (mode == 0) { // OFF + target_on = false; + } else if (mode == 1) { // ON + target_on = true; + } else if (mode == 2) { // TIMER + bool should_on = false; + if (id(current_mins) >= id(morning_on) && id(current_mins) < id(morning_off)) + should_on = true; + if (id(current_mins) >= id(evening_on) && id(current_mins) < id(evening_off)) + should_on = true; + target_on = should_on; + } + + // Enforce minimum OFF time when turning ON normally (not during color pulses) + if (target_on) { + uint32_t delta = millis() - id(last_off_ms); + if (delta < (uint32_t) id(reset_window_ms)) { + // Still inside OFF window: wait; schedule a recheck if not already + if (!id(recheck_pending)) { + id(enforce_off_guard).execute(); + } + return; + } else { + id(relay).turn_on(); + return; + } + } else { + id(relay).turn_off(); + return; + } + + # Poll until OFF window elapsed, then re-evaluate (does not toggle the relay itself) + - id: enforce_off_guard + mode: restart + then: + - lambda: |- + id(recheck_pending) = true; + - while: + condition: + lambda: |- + if (id(mode_changing)) return false; // abort if color change starts + uint32_t delta = millis() - id(last_off_ms); + return delta < (uint32_t) id(reset_window_ms); + then: + - delay: 200ms + - lambda: |- + id(recheck_pending) = false; + - script.execute: evaluate_relay_state + + # Long reset to Mode 1 + - id: reset_to_mode1 + mode: restart + then: + - switch.turn_off: relay + - delay: ${mode_reset_off} + - switch.turn_on: relay + - delay: ${mode_pulse_on} + - lambda: |- + id(current_mode) = 1; + + # Change to desired_mode, robust from OFF and without wrap on lower targets + # Change to desired_mode, robust from OFF and without wrap on lower targets + - id: change_to_desired_mode + mode: restart + then: + # If relay is currently OFF, establish a known starting point + - if: + condition: + lambda: 'return !id(relay).state;' + then: + - lambda: |- + uint32_t delta = millis() - id(last_off_ms); + // If OFF < reset window, enforce a true reset first for predictable start + if (delta < (uint32_t) id(reset_window_ms)) { + id(reset_to_mode1).execute(); + } + - if: + condition: + lambda: 'return !id(relay).state;' + then: + - switch.turn_on: relay + - delay: ${mode_prime_on} + - lambda: |- + // If we turned ON after ≥ reset window, hardware is at Mode 1 + if ((millis() - id(last_off_ms)) >= (uint32_t) id(reset_window_ms)) { + id(current_mode) = 1; + } + + # If target is below current, do a long reset to Mode 1, then proceed + - if: + condition: + lambda: |- + return id(desired_mode) < id(current_mode); + then: + - script.execute: reset_to_mode1 + - script.wait: reset_to_mode1 + + # If already exactly at target, ensure ON and finish + - if: + condition: + lambda: 'return id(desired_mode) == id(current_mode);' + then: + - switch.turn_on: relay + - lambda: |- + id(mode_changing) = false; + + # Step forward until we reach desired (ignored modes still counted) + - while: + condition: + lambda: |- + // Allow immediate cancellation if OFF is selected mid-flight + return id(mode_changing) && (id(current_mode) < id(desired_mode)); + then: + - switch.turn_off: relay + - delay: ${mode_pulse_off} + - switch.turn_on: relay + - delay: ${mode_pulse_on} + - lambda: |- + id(current_mode)++; + + # End: make sure we leave the light ON and clear the guard + - switch.turn_on: relay + - lambda: |- + id(mode_changing) = false; + + +################################################################################################# +# INTERVAL COMPONENT +# https://esphome.io/components/interval.html +################################################################################################# +# Interval: bumps time (even if no SNTP), then calls the script to evaluate relay state +interval: + - interval: "1min" + then: + - lambda: |- + // — update current_mins via SNTP or fallback + if (!id(sntp_time).now().is_valid()) { + id(current_mins)++; + if (id(current_mins) >= 1440) id(current_mins) = 0; + } else { + auto now = id(sntp_time).now(); + id(current_mins) = now.hour * 60 + now.minute; + } + + // — if in BOOST, advance boost_timer and expire when done + if (id(operation_mode) == 3) { + id(boost_timer)++; + if (id(boost_timer) >= id(boost_duration)) { + id(operation_mode) = 2; + //id(mqtt_client).publish("${mqtt_timer_topic}/operation", "TIMER"); + } + } + - script.execute: evaluate_relay_state diff --git a/esphome/esp-poollightpower.yaml b/esphome/esp-poollightpower.yaml index c17588f..429c860 100644 --- a/esphome/esp-poollightpower.yaml +++ b/esphome/esp-poollightpower.yaml @@ -58,8 +58,8 @@ substitutions: # Device Naming device_name: "esp-poollightpower" - friendly_name: "Pool Light Power" - description_comment: "Pool Light Power :: Athom Smart Plug Power V1" + friendly_name: "Pool Light Power (temp)" + description_comment: "Pool Light Power (temp):: Athom Smart Plug Power V1" device_area: "Outside" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant. # Project Naming @@ -78,7 +78,7 @@ substitutions: # Device Settings relay_icon: "mdi:power-socket-au" current_limit : "10" # Current Limit in Amps. AU Plug = 10. IL, BR, EU, UK, US Plug = 16. - mqtt_timer_topic: "viewroad-commands/poollight-timer" # Topics you will use to change stuff + mqtt_timer_topic: "viewroad-commands/poollightold-timer" # Topics you will use to change stuff boost_duration_default: "180" # Minutes to stay ON in BOOST mode before reverting to TIMER morning_on_default: "450" # Default in minutes from midnight. Default 07:30 => 450 morning_off_default: "450" # Default in minutes from midnight. Default 07:30 => 450 (same as ON as no need for morning schedule) diff --git a/esphome/esp-poollightpower2.yaml b/esphome/esp-poollightpower2.yaml new file mode 100644 index 0000000..3941460 --- /dev/null +++ b/esphome/esp-poollightpower2.yaml @@ -0,0 +1,1068 @@ +########################################################################################## +########################################################################################## +# POOL LIGHT POWER AND TIMER 2 +# Controlled by a Athom Smart Plug V2 +# +# v4.0 2025-11-04 Changed to Athom V2 +# V3.0 2025-09-02 Pool Light mode controller fixes; Mode select forces Operation=ON; +# added Mode 0=OFF; select shows OFF when relay off; enforce 7s min OFF window +# V2.4 2025-06-15 Changed back to an Athom V1 (esp8266) +# V2.3 2025-06-15 Changed to an Athom V3 (esp32) +# V2.2 2025-06-14 Fixes to offline time when sntp/network unavailable +# V2.1 2025-06-12 Added select and button to chose modes, added countdown & startup to boost +# V2.0 2025-06-05 YAML Tidyups +# +# INSTRUCTIONS +# - 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 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 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 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) +# +# operation_mode: +# 0 = OFF +# 1 = ON +# 2 = TIMER +# 3 = BOOST +# +########################################################################################## +########################################################################################## + + +########################################################################################## +# 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-poollightpower2" + friendly_name: "Pool Light Power" + description_comment: "Pool Light Power :: Athom Smart Plug Power V2" + device_area: "Outside" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant. + + # Project Naming + project_name: "Athom Technology.Smart Plug V2" # Project Details + project_version: "v3.0" # Project V denotes release of yaml file, allowing checking of deployed vs latest version + + # Passwords + api_key: !secret esp-api_key # unfortunately you can't use substitutions inside secrets names + ota_pass: !secret esp-ota_pass # unfortunately you can't use substitutions inside secrets names + static_ip_address: !secret esp-poollightpower2_ip + + # Device Settings + log_level: "NONE" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE + update_interval: "10s" # update time for for general sensors etc + + # Device Settings + relay_icon: "mdi:power-socket-au" + current_limit : "10" # Current Limit in Amps. AU Plug = 10. IL, BR, EU, UK, US Plug = 16. + mqtt_timer_topic: "viewroad-commands/poollight-timer" # Topics you will use to change stuff + boost_duration_default: "180" # Minutes to stay ON in BOOST mode before reverting to TIMER + morning_on_default: "450" # Default in minutes from midnight. Default 07:30 => 450 + morning_off_default: "450" # Default in minutes from midnight. Default 07:30 => 450 (same as ON as no need for morning schedule) + evening_on_default: "1140" # Default in minutes from midnight. Default 19:00 => 1140 + evening_off_default: "1350" # Default in minutes from midnight. Default 22:30 => 1350 => 1440 is midnight + + ############################################################################## + # POOL LIGHT MODE CONTROL (new) + ############################################################################## + max_modes: "16" # total number of modes in the cycle + mode_pulse_off: "400ms" # short OFF between quick pulses + mode_pulse_on: "400ms" # short ON after each quick pulse + mode_reset_off: "3s" # long OFF to force hardware reset to mode 1 + mode_reset_window_ms: "3000" # treat OFF>=this ms as a reset-to-1 when turning back ON + mode_prime_on: "800ms" # if relay is OFF when a color is selected, turn ON for this long before pulsing + # Ignored modes bitmask: bit (mode_index-1). For 4 and 5 ignored -> (1<<3)|(1<<4) = 24. + ignored_modes_mask: "8288" # Ignore 6(32), 7(64), 14(8192) :: 32 + 64 + 8192 = 8288 + +########################################################################################## +# PACKAGES: Included Common Packages +# https://esphome.io/components/packages.html +########################################################################################## +packages: + ################################################## + # MANDATORY packages (won't compile without them!) + ################################################## + + #### 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}" + + ################################################## + # OPTIONAL packages (comment if you don't want them) + ################################################## + + #### 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}" + + #### WEB PORTAL #### + #common_webportal: !include + # file: common/webportal_common.yaml + + #### MQTT #### + common_mqtt: !include + file: common/mqtt_common.yaml + vars: + local_device_name: "${device_name}" + + #### SNTP (Only use if you want/need accurate timeclocks) #### + common_sntp: !include + file: common/sntp_common.yaml + + #### DIAGNOSTICS Lite Sensors #### + common_lite_sensors: !include + file: common/sensors_common_lite.yaml + + #### DIAGNOSTICS General Sensors #### + common_general_sensors: !include + file: common/sensors_common.yaml + + #### DEBUGGING Sensors #### + # A count of various resets + #common_resetcount_debugging: !include + # file: common/resetcount_common.yaml + + # Device Specific included packages + common_athompowermonV2: !include + file: common/athompowermonv2_common.yaml + vars: + local_friendly_name: "${friendly_name}" + #local_current_limit: "${current_limit}" + sensor_update_interval: "${update_interval}" # e.g. "10s" + hide_energy_sensor: "false" # or "true" if you want Energy hidden + relay_restore_mode: "RESTORE_DEFAULT_OFF" # matches what you already use + power_plug_type: "${relay_icon}" # e.g. "mdi:power-socket-au" + +########################################################################################## +# ESPHome +# https://esphome.io/components/esphome.html +########################################################################################## +esphome: + name: "${device_name}" + friendly_name: "${friendly_name}" + comment: "${description_comment}" #Appears on the esphome page in HA + area: "${device_area}" + name_add_mac_suffix: False + min_version: 2024.6.0 + project: + name: "${project_name}" + version: "${project_version}" + #platformio_options: + # build_unflags: + # - -std=gnu++20 + # - -std=gnu++2a + # build_flags: + # - -std=gnu++11 + # - -Os + # - -Wl,--gc-sections + # - -fno-exceptions + # - -fno-rtti + +########################################################################################## +# ESP Platform and Framework +# https://esphome.io/components/esp32.html +########################################################################################## +esp8266: + board: esp8285 + restore_from_flash: true # mainly for calculating cumulative energy, but not that important here + #framework: + # version: 2.7.4 + +preferences: + flash_write_interval: 10min + +mdns: + disabled: true # binary size saving + +########################################################################################## +# ESPHome Logging Enable +# https://esphome.io/components/logger.html +########################################################################################## +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) + #esp8266_store_log_strings_in_flash: false + #tx_buffer_size: 64 + +########################################################################################## +# Global Variables for use in automations etc +# https://esphome.io/guides/automations.html?highlight=globals#global-variables +########################################################################################## +globals: + + # Tracks the time (in seconds from midnight) at the previous boot + - id: last_boot_time_s + type: int + restore_value: true + initial_value: "0" + + # Counts how many consecutive boots have occurred (within X seconds) + - id: boot_count + type: int + restore_value: true + initial_value: "0" + + # Morning On time (minutes from midnight), + - id: morning_on + type: int + restore_value: true + initial_value: "${morning_on_default}" + + # Morning Off time (minutes from midnight), + - id: morning_off + type: int + restore_value: true + initial_value: "${morning_off_default}" + + # Evening On time (minutes from midnight), + - id: evening_on + type: int + restore_value: true + initial_value: "${evening_on_default}" + + # Evening Off time (minutes from midnight), + - id: evening_off + type: int + restore_value: true + initial_value: "${evening_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 = BOOST + #################################################### + - id: operation_mode + type: int + restore_value: true + initial_value: "2" + + #################################################### + # current_mins is set if SNTP is invalid. + # We assume user powers on the device at 12:00 noon + # => 12 * 60 = 720 minutes from midnight. + #################################################### + - id: current_mins + type: int + restore_value: true + initial_value: "720" # 720 is 12:00 Noon + + #################################################### + # boost_timer: counts minutes in BOOST mode + # After 'boost_duration' minutes, revert to TIMER. + #################################################### + - id: boost_timer + type: int + restore_value: true + initial_value: "0" + + ############################################################################## + # POOL LIGHT MODE CONTROL GLOBALS (new) + ############################################################################## + # Current assumed pool-light mode (0..max_modes). 0 means relay OFF. + - id: current_mode + type: int + restore_value: false + initial_value: "1" + + # Total modes in the cycle (edit in substitutions). + - id: max_modes + type: int + restore_value: false + initial_value: "${max_modes}" + + # Flag while we are actively pulsing to change modes (prevents scheduler interference). + - id: mode_changing + type: bool + restore_value: false + initial_value: "false" + + # Timestamp of last relay off (for delta measurement). + - id: last_off_ms + type: uint32_t + restore_value: false + initial_value: "0" + + # Millisecond threshold that separates "quick pulse" vs "reset to mode 1". + - id: reset_window_ms + type: int + restore_value: false + initial_value: "${mode_reset_window_ms}" + + # Desired target mode for the cycle script. + - id: desired_mode + type: int + restore_value: false + initial_value: "1" + + # Bitmask of ignored modes (1..max_modes). Example: ignore 4 & 5 -> 24. + - id: ignored_mask + type: int + restore_value: false + initial_value: "${ignored_modes_mask}" + + # Internal: whether a recheck is already scheduled for min OFF enforcement. + - id: recheck_pending + type: bool + restore_value: false + initial_value: "false" + +########################################################################################## +# Text Sensors +# https://esphome.io/components/text_sensor/index.html +########################################################################################## +text_sensor: + +############################ +# MQTT Subscriptions +############################ + #################################################### + # Subscribe to the Morning On time, format "HH:MM" + #################################################### + - platform: mqtt_subscribe + name: "Morning On Time Setting" + id: morning_on_topic + topic: "${mqtt_timer_topic}/morning-on" # Stored in the format HH:MM + internal: true + on_value: + then: + - lambda: |- + // Expect "HH:MM" => total length = 5, with ':' + if (x.size() == 5 && x[2] == ':') { + int hour = atoi(x.substr(0, 2).c_str()); // "HH" + int minute = atoi(x.substr(3, 2).c_str()); // "MM" + id(morning_on) = hour * 60 + minute; + ESP_LOGI("timer","Received new Morning On: %02d:%02d", hour, minute); + } else { + ESP_LOGW("timer","Invalid Morning On format: %s", x.c_str()); + } + #################################################### + # Morning Off time => "HH:MM" + #################################################### + - platform: mqtt_subscribe + name: "Morning Off Time Setting" + id: morning_off_topic + topic: "${mqtt_timer_topic}/morning-off" # Stored in the format HH:MM + internal: true # No need to show this in Home Assistant as there is a sensor that shows the set value + on_value: + then: + - lambda: |- + if (x.size() == 5 && x[2] == ':') { + int hour = atoi(x.substr(0, 2).c_str()); + int minute = atoi(x.substr(3, 2).c_str()); + id(morning_off) = hour * 60 + minute; + ESP_LOGI("timer","Received new Morning Off: %02d:%02d", hour, minute); + } else { + ESP_LOGW("timer","Invalid Morning Off format: %s", x.c_str()); + } + #################################################### + # Evening On time => "HH:MM" + #################################################### + - platform: mqtt_subscribe + name: "Evening On Time Setting" + id: evening_on_topic + topic: "${mqtt_timer_topic}/evening-on" # Stored in the format HH:MM + internal: true # No need to show this in Home Assistant as there is a sensor that shows the set value + on_value: + then: + - lambda: |- + if (x.size() == 5 && x[2] == ':') { + int hour = atoi(x.substr(0, 2).c_str()); + int minute = atoi(x.substr(3, 2).c_str()); + id(evening_on) = hour * 60 + minute; + ESP_LOGI("timer","Received new Evening On: %02d:%02d", hour, minute); + } else { + ESP_LOGW("timer","Invalid Evening On format: %s", x.c_str()); + } + #################################################### + # Evening Off time => "HH:MM" + #################################################### + - platform: mqtt_subscribe + name: "Evening Off Time Setting" + id: evening_off_topic + topic: "${mqtt_timer_topic}/evening-off" # Stored in the format HH:MM + internal: true # No need to show this in Home Assistant as there is a sensor that shows the set value + on_value: + then: + - lambda: |- + if (x.size() == 5 && x[2] == ':') { + int hour = atoi(x.substr(0, 2).c_str()); + int minute = atoi(x.substr(3, 2).c_str()); + id(evening_off) = hour * 60 + minute; + ESP_LOGI("timer","Received new Evening Off: %02d:%02d", hour, minute); + } else { + 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 0–1439 + 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(v); + } + + #################################################### + # Subscribe to operation mode: + # OFF, ON, TIMER, BOOST + #################################################### + # MQTT subscription: set mode, then immediately re-evaluate relay + - platform: mqtt_subscribe + id: timer_operation_mode_topic + topic: "${mqtt_timer_topic}/operation" + internal: true # No need to show this in Home Assistant as there is a sensor that shows the set value + on_value: + then: + - lambda: |- + if (strcasecmp(x.c_str(), "TIMER") == 0) { + id(operation_mode) = 2; + ESP_LOGI("timer","Operation mode set to TIMER"); + } else if (strcasecmp(x.c_str(), "ON") == 0) { + id(operation_mode) = 1; + ESP_LOGI("timer","Operation mode set to ON"); + } 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(), "BOOST") == 0) { + id(operation_mode) = 3; + id(boost_timer) = 0; + ESP_LOGI("timer","Operation mode set to BOOST"); + } else { + ESP_LOGW("timer","Invalid operation mode: %s", x.c_str()); + } + - script.execute: evaluate_relay_state + + ###################################################### + # Expose the current operation mode (OFF, ON, TIMER, BOOST) + ###################################################### + - platform: template + name: "Operation Mode State" + lambda: |- + // 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 {"BOOST"}; + default: return {"UNKNOWN"}; + } + update_interval: 5s + + ###################################################### + # Expose the "Morning On" time as a text (HH:MM) + ###################################################### + - platform: template + name: "Timeclock: Morning On Time" + lambda: |- + int hour = id(morning_on) / 60; + int minute = id(morning_on) % 60; + // Increase to 16 for safety + char buff[16]; + snprintf(buff, sizeof(buff), "%02d:%02d", hour, minute); + return { std::string(buff) }; + update_interval: "${update_interval}" + + ###################################################### + # Expose the "Morning Off" time as a text (HH:MM) + ###################################################### + - platform: template + name: "Timeclock: Morning Off Time" + lambda: |- + int hour = id(morning_off) / 60; + int minute = id(morning_off) % 60; + // Increase to 16 for safety + char buff[16]; + snprintf(buff, sizeof(buff), "%02d:%02d", hour, minute); + return { std::string(buff) }; + update_interval: "${update_interval}" + + ###################################################### + # Expose the "Evening On" time as a text (HH:MM) + ###################################################### + - platform: template + name: "Timeclock: Evening On Time" + lambda: |- + int hour = id(evening_on) / 60; + int minute = id(evening_on) % 60; + // Increase to 16 for safety + char buff[16]; + snprintf(buff, sizeof(buff), "%02d:%02d", hour, minute); + return { std::string(buff) }; + update_interval: "${update_interval}" + + ###################################################### + # Expose the "Evening Off" time as a text (HH:MM) + ###################################################### + - platform: template + name: "Timeclock: Evening Off Time" + lambda: |- + int hour = id(evening_off) / 60; + int minute = id(evening_off) % 60; + // Increase to 16 for safety + char buff[16]; + snprintf(buff, sizeof(buff), "%02d:%02d", hour, minute); + return { std::string(buff) }; + update_interval: "${update_interval}" + +########################################################################################## +# BINARY SENSORS +# https://esphome.io/components/binary_sensor/ +########################################################################################## +#binary_sensor: +# - platform: gpio +# pin: +# number: GPIO03 +# mode: INPUT_PULLUP +# inverted: true +# name: "Power Button" +# id: power_button +# filters: +# - delayed_on: 20ms +# on_click: +# - min_length: 20ms +# max_length: 500ms +# then: +# - lambda: |- +# if (id(relay).state) { +# // Relay is ON: turn it OFF and set mode to 2 (TIMER) +# id(relay).turn_off(); +# id(operation_mode) = 2; +# } else { +# // Relay is OFF: turn it ON and set mode to 3 (BOOST) +# id(relay).turn_on(); +# id(operation_mode) = 3; +# } + +binary_sensor: + - platform: template + id: relay_status + name: "Relay Status" + lambda: |- + return id(relay).state; + + # Mirror the package relay state and run your previous hooks + - platform: template + id: relay_shadow + internal: true + lambda: |- + return id(relay).state; + on_press: + - lambda: |- + // Mirrors your former switch.on_turn_on + if (id(mode_changing)) { + return; + } + uint32_t delta = millis() - id(last_off_ms); + if (delta >= (uint32_t) id(reset_window_ms)) { + id(current_mode) = 1; + } else { + id(current_mode)++; + if (id(current_mode) > id(max_modes)) id(current_mode) = 1; + } + on_release: + - lambda: |- + // Mirrors your former switch.on_turn_off + id(last_off_ms) = millis(); + if (!id(mode_changing)) id(current_mode) = 0; + + +########################################################################################## +# Sensors +# https://esphome.io/components/text_sensor/index.html +########################################################################################## +sensor: + - platform: template + name: "Timeclock: Boost Duration" + id: boost_duration_time + unit_of_measurement: "mins" + accuracy_decimals: "0" + update_interval: "${update_interval}" + lambda: |- + return id(boost_duration); + + - platform: template + name: "Mins from Midnight" + id: mins_from_midnight + unit_of_measurement: "mins" + accuracy_decimals: "0" + update_interval: "${update_interval}" + internal: true # No need to show this in Home Assistant + 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; + + +################################################################################################# +# SWITCH COMPONENT +# https://esphome.io/components/switch/ +################################################################################################# +#switch: +# - platform: gpio +# name: "Power Output" +# pin: GPIO14 +# id: relay +# restore_mode: RESTORE_DEFAULT_OFF # Ensures the relay is restored (or off) at boot +# #internal: true # Hides the switch from Home Assistant +# icon: "${relay_icon}" +# # POOL LIGHT MODE CONTROL: detect quick vs long off periods and keep current_mode in sync +# on_turn_off: +# - lambda: |- +# id(last_off_ms) = millis(); +# if (!id(mode_changing)) id(current_mode) = 0; // reflect OFF in select when off normally +# on_turn_on: +# - lambda: |- +# if (id(mode_changing)) { +# return; +# } +# uint32_t delta = millis() - id(last_off_ms); +# if (delta >= (uint32_t)id(reset_window_ms)) { +# id(current_mode) = 1; +# } else { +# id(current_mode)++; +# if (id(current_mode) > id(max_modes)) id(current_mode) = 1; // keep internal index sane +# } + +################################################################################################# +# BUTTON COMPONENT +# https://esphome.io/components/button/index.html +################################################################################################# +button: + - platform: template + name: "Boost now" + id: boost_button + icon: "mdi:play-circle-outline" + on_press: + # 1) reset BOOST timer and set mode + - lambda: |- + id(boost_timer) = 0; + id(operation_mode) = 3; + # 2) immediately re-evaluate relay state + - script.execute: evaluate_relay_state + - platform: template + name: "Default timer settings" + id: default_timer_settings_button + icon: "mdi:restore" + on_press: + - lambda: |- + // Restore all timing globals to their YAML defaults + id(morning_on) = ${morning_on_default}; + id(morning_off) = ${morning_off_default}; + id(evening_on) = ${evening_on_default}; + id(evening_off) = ${evening_off_default}; + id(boost_duration)= ${boost_duration_default}; + // Reset mode to TIMER and clear any running boost + id(operation_mode)= 2; + id(boost_timer) = 0; + ESP_LOGI("timer","Default timer settings applied"); + - script.execute: evaluate_relay_state + +################################################################################################# +# SELECT COMPONENT +# https://esphome.io/components/select/index.html +################################################################################################# +select: + - platform: template + name: "Operation Mode" + id: operation_mode_select + update_interval: 5s + options: + - "OFF" + - "ON" + - "TIMER" + - "BOOST" + + # show the current mode + 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"); + } + + # when changed in HA, set mode & re-evaluate + 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 { // BOOST + id(boost_timer) = 0; + id(operation_mode) = 3; + } + - script.execute: evaluate_relay_state + + ############################################################################## + # POOL LIGHT MODE SELECT (new) + # 0=OFF -> immediately turns relay OFF and sets Operation Mode = TIMER. + # Selecting a color (>=1) forces Operation Mode = ON. + # If target < current, do a long reset to mode 1, then pulse forward. + # Ignored modes are hidden here but still counted by pulses. + ############################################################################## + ############################################################################## + # POOL LIGHT MODE SELECT (updated display logic) + # 0=OFF -> immediately turns relay OFF and sets Operation Mode = TIMER. + # Selecting a color (>=1) forces Operation Mode = ON. + # If target < current, do a long reset to mode 1, then pulse forward. + # Ignored modes are hidden here but still counted by pulses. + ############################################################################## + - platform: template + name: "Pool Light Mode" + id: pool_light_mode_select + update_interval: 250ms + # Options include all 1..16 (no ignored modes currently) plus 0=OFF + options: + - "0= OFF" + - "1= Dark Blue" + - "2= Red" + - "3= Green" + - "4= Purple" + - "5= Aqua" + #- "6= Lime" + #- "7= Cool White" + - "8= Speed Up" + - "9= Transformer" + - "10= Blurple" + - "11= Redlime" + - "12= Greenqua" + - "13= Bluequa" + #- "14= Grelime" + - "15= Redurple" + - "16= RGB Mad" + + # Show OFF only when not in a color-change sequence. + # While changing, reflect the in-flight/current mode (never 0). + lambda: |- + auto label_for = [](int m) -> std::string { + switch (m) { + case 0: return "0= OFF"; + case 1: return "1= Dark Blue"; + case 2: return "2= Red"; + case 3: return "3= Green"; + case 4: return "4= Purple"; + case 5: return "5= Aqua"; + case 6: return "6= Lime"; + case 7: return "7= Cool White"; + case 8: return "8= Speed Up"; + case 9: return "9= Transformer"; + case 10: return "10= Blurple"; + case 11: return "11= Redlime"; + case 12: return "12= Greenqua"; + case 13: return "13= Bluequa"; + case 14: return "14= Grelime"; + case 15: return "15= Redurple"; + case 16: return "16= RGB Mad"; + default: return "1= Dark Blue"; + } + }; + auto is_ignored = [&](int m) -> bool { + if (m < 1 || m > id(max_modes)) return true; + int bit = 1 << (m - 1); + return (id(ignored_mask) & bit) != 0; + }; + + // While stepping (mode_changing), don't show OFF even if relay is briefly OFF. + if (id(mode_changing)) { + int cm = id(current_mode); + if (cm <= 0) cm = 1; // during long reset, assume Mode 1 is next + // Skip ignored modes for display if ever configured later + if (!is_ignored(cm)) return label_for(cm); + // find next non-ignored just for display robustness + for (int m = cm + 1; m <= id(max_modes); m++) if (!is_ignored(m)) return label_for(m); + for (int m = 1; m <= id(max_modes); m++) if (!is_ignored(m)) return label_for(m); + return label_for(1); + } + + // Normal (not changing): show OFF if relay is actually OFF, else show current mode + if (!id(relay).state) return std::string("0= OFF"); + + int cm = id(current_mode); + if (cm == 0) return std::string("0= OFF"); + if (!is_ignored(cm)) return label_for(cm); + for (int m = cm + 1; m <= id(max_modes); m++) if (!is_ignored(m)) return label_for(m); + for (int m = 1; m <= id(max_modes); m++) if (!is_ignored(m)) return label_for(m); + return label_for(1); + + set_action: + # First, set flags based on selection + - lambda: |- + int target = atoi(x.c_str()); + if (target < 0) target = 0; + if (target > id(max_modes)) target = id(max_modes); + + if (target == 0) { + // MODE 0: force everything OFF; UI goes back to TIMER control + id(mode_changing) = false; + id(recheck_pending) = false; + id(operation_mode) = 2; // TIMER + id(current_mode) = 0; // reflect OFF in dropdown + } else { + // defensive: ignore choosing an ignored mode (options already hide them) + int bit = 1 << (target - 1); + if ((id(ignored_mask) & bit) != 0) { + ESP_LOGW("mode","Selected target %d is ignored; ignoring request", target); + return; + } + // Color selection: force ON mode and start changer + id(operation_mode) = 1; + id(desired_mode) = target; + id(mode_changing) = true; + } + + # If OFF was selected, hard-stop any running scripts and cut power + - if: + condition: + lambda: 'return atoi(x.c_str()) == 0;' + then: + - script.stop: change_to_desired_mode + - script.stop: reset_to_mode1 + - script.stop: enforce_off_guard + - switch.turn_off: relay + else: + - script.execute: change_to_desired_mode + +################################################################################################# +# SCRIPT COMPONENT +# https://esphome.io/components/script.html +################################################################################################# +script: + # Core: evaluate and drive the relay (with enforced min OFF window) + - id: evaluate_relay_state + then: + - lambda: |- + if (id(mode_changing)) { + // do not fight the pulser + return; + } + // Determine target state + bool target_on = false; + int mode = id(operation_mode); + + if (mode == 3) { // BOOST + target_on = true; + } else if (mode == 0) { // OFF + target_on = false; + } else if (mode == 1) { // ON + target_on = true; + } else if (mode == 2) { // TIMER + bool should_on = false; + if (id(current_mins) >= id(morning_on) && id(current_mins) < id(morning_off)) + should_on = true; + if (id(current_mins) >= id(evening_on) && id(current_mins) < id(evening_off)) + should_on = true; + target_on = should_on; + } + + // Enforce minimum OFF time when turning ON normally (not during color pulses) + if (target_on) { + uint32_t delta = millis() - id(last_off_ms); + if (delta < (uint32_t) id(reset_window_ms)) { + // Still inside OFF window: wait; schedule a recheck if not already + if (!id(recheck_pending)) { + id(enforce_off_guard).execute(); + } + return; + } else { + id(relay).turn_on(); + return; + } + } else { + id(relay).turn_off(); + return; + } + + # Poll until OFF window elapsed, then re-evaluate (does not toggle the relay itself) + - id: enforce_off_guard + mode: restart + then: + - lambda: |- + id(recheck_pending) = true; + - while: + condition: + lambda: |- + if (id(mode_changing)) return false; // abort if color change starts + uint32_t delta = millis() - id(last_off_ms); + return delta < (uint32_t) id(reset_window_ms); + then: + - delay: 200ms + - lambda: |- + id(recheck_pending) = false; + - script.execute: evaluate_relay_state + + # Long reset to Mode 1 + - id: reset_to_mode1 + mode: restart + then: + - switch.turn_off: relay + - delay: ${mode_reset_off} + - switch.turn_on: relay + - delay: ${mode_pulse_on} + - lambda: |- + id(current_mode) = 1; + + # Change to desired_mode, robust from OFF and without wrap on lower targets + # Change to desired_mode, robust from OFF and without wrap on lower targets + - id: change_to_desired_mode + mode: restart + then: + # If relay is currently OFF, establish a known starting point + - if: + condition: + lambda: 'return !id(relay).state;' + then: + - lambda: |- + uint32_t delta = millis() - id(last_off_ms); + // If OFF < reset window, enforce a true reset first for predictable start + if (delta < (uint32_t) id(reset_window_ms)) { + id(reset_to_mode1).execute(); + } + - if: + condition: + lambda: 'return !id(relay).state;' + then: + - switch.turn_on: relay + - delay: ${mode_prime_on} + - lambda: |- + // If we turned ON after ≥ reset window, hardware is at Mode 1 + if ((millis() - id(last_off_ms)) >= (uint32_t) id(reset_window_ms)) { + id(current_mode) = 1; + } + + # If target is below current, do a long reset to Mode 1, then proceed + - if: + condition: + lambda: |- + return id(desired_mode) < id(current_mode); + then: + - script.execute: reset_to_mode1 + - script.wait: reset_to_mode1 + + # If already exactly at target, ensure ON and finish + - if: + condition: + lambda: 'return id(desired_mode) == id(current_mode);' + then: + - switch.turn_on: relay + - lambda: |- + id(mode_changing) = false; + + # Step forward until we reach desired (ignored modes still counted) + - while: + condition: + lambda: |- + // Allow immediate cancellation if OFF is selected mid-flight + return id(mode_changing) && (id(current_mode) < id(desired_mode)); + then: + - switch.turn_off: relay + - delay: ${mode_pulse_off} + - switch.turn_on: relay + - delay: ${mode_pulse_on} + - lambda: |- + id(current_mode)++; + + # End: make sure we leave the light ON and clear the guard + - switch.turn_on: relay + - lambda: |- + id(mode_changing) = false; + + +################################################################################################# +# INTERVAL COMPONENT +# https://esphome.io/components/interval.html +################################################################################################# +# Interval: bumps time (even if no SNTP), then calls the script to evaluate relay state +interval: + - interval: "1min" + then: + - lambda: |- + // — update current_mins via SNTP or fallback + if (!id(sntp_time).now().is_valid()) { + id(current_mins)++; + if (id(current_mins) >= 1440) id(current_mins) = 0; + } else { + auto now = id(sntp_time).now(); + id(current_mins) = now.hour * 60 + now.minute; + } + + // — if in BOOST, advance boost_timer and expire when done + if (id(operation_mode) == 3) { + id(boost_timer)++; + if (id(boost_timer) >= id(boost_duration)) { + id(operation_mode) = 2; + //id(mqtt_client).publish("${mqtt_timer_topic}/operation", "TIMER"); + } + } + - script.execute: evaluate_relay_state diff --git a/esphome/esp-rocktumbler.yaml b/esphome/esp-rocktumbler.yaml new file mode 100644 index 0000000..4983cdf --- /dev/null +++ b/esphome/esp-rocktumbler.yaml @@ -0,0 +1,187 @@ +########################################################################################## +########################################################################################## +# ROCK TUMBLER POWER MONITOR +# +# Controlled by a Athom Smart Plug V1 +# package_import_url: github://athom-tech/athom-configs/athom-smart-plug.yaml +# +# V1.3 2025-08-27 Changed to Athom V2 +# V1.2 2025-06-15 Changed to Athom V1 +# V1.1 2025-06-12 Tidyups and packages added +# +########################################################################################## +########################################################################################## + +########################################################################################## +# 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-rocktumbler" + friendly_name: "Rock Tumbler Power" + description_comment: "Rock Tumbler Power :: Athom Smart Plug Power V2" + device_area: "Laundry" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant. + + # Project Naming + project_name: "Athom Technology.Smart Plug V2" # Project Details + project_version: "v1.3" # Project V denotes release of yaml file, allowing checking of deployed vs latest version + + # Passwords (unfortunately you can't use substitutions inside secrets names) + api_key: !secret esp-api_key + ota_pass: !secret esp-ota_pass + static_ip_address: !secret esp-rocktumbler_ip + + # Device General Settings + log_level: "NONE" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE + update_interval: "60s" # update time for for general sensors etc + + # Device Specific Settings + # Athom Power Monitor Plug V2 + relay_icon: "mdi:power-socket-au" + current_limit: "10" # Current Limit in Amps. AU Plug = 10. IL, BR, EU, UK, US Plug = 16. + sensor_update_interval: "10s" + relay_restore_mode: RESTORE_DEFAULT_ON + hide_energy_sensor: "true" + +########################################################################################## +# PACKAGES: Included Common Packages +# https://esphome.io/components/packages.html +########################################################################################## +# Comment some of these out where not needed, eg MQTT, Web portal, SNTP, General Sensors +########################################################################################## +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}" + + #### MQTT #### + common_mqtt: !include + file: common/mqtt_common.yaml + vars: + local_device_name: "${device_name}" + + #### 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 + + # Device Specific included packages + # Athom Power Monitor Plug + common_athompowermonV2: !include + file: common/athompowermonv2_common.yaml + vars: + local_friendly_name: "${friendly_name}" + local_current_limit: "${current_limit}" + sensor_update_interval: "${sensor_update_interval}" + relay_restore_mode: "${relay_restore_mode}" + power_plug_type: "${relay_icon}" + hide_energy_sensor: "${hide_energy_sensor}" + +########################################################################################## +# ESPHome +# https://esphome.io/components/esphome.html +########################################################################################## +esphome: + name: "${device_name}" + friendly_name: "${friendly_name}" + comment: "${description_comment}" #Appears on the esphome page in HA + area: "${device_area}" + name_add_mac_suffix: false + min_version: 2024.6.0 + project: + name: "${project_name}" + version: "${project_version}" + on_boot: + - priority: 600 + then: + - select.set_index: + id: power_mode + index: !lambda |- + return id(restore_mode)-1; + - lambda: |- + switch(id(restore_mode)) + { + case 1:{ + id(relay).turn_off(); + break; + } + case 2:{ + id(relay).turn_on(); + break; + } + default:{ + break; + } + } + +########################################################################################## +# ESP Platform and Framework +# https://esphome.io/components/esp32.html +########################################################################################## +esp8266: + board: esp8285 + restore_from_flash: true # mainly for calculating cumulative energy, but not that important here + early_pin_init: true + +preferences: + flash_write_interval: 5min + +mdns: + disabled: false + +########################################################################################## +# ESPHome LOGGING +# https://esphome.io/components/logger.html +########################################################################################## +logger: + level: "${log_level}" + baud_rate: 0 #set to 0 for no logging via UART, needed if you are using it for other serial things (eg PZEM) + +########################################################################################## +# GLOBAL VARIABLES +# https://esphome.io/guides/automations.html?highlight=globals#global-variables +########################################################################################## +globals: + # 0 = Always_Off. 1 = Restore_Power_Off. 2 = Always_On. + - id: restore_mode + type: int + restore_value: yes + initial_value: "2" + +########################################################################################## +# SELECT COMPONENT +# https://esphome.io/components/select/index.html +########################################################################################## +select: + - platform: template + name: "Power On State" + id: "power_mode" + optimistic: true + icon: mdi:electric-switch + options: + - Always Off + - Always On + - Restore Previous State + on_value: + then: + - lambda: |- + id(restore_mode)=i+1; \ No newline at end of file diff --git a/esphome/esp-underhouselights.yaml b/esphome/esp-underhouselights.yaml index 863525a..c0bf0b7 100644 --- a/esphome/esp-underhouselights.yaml +++ b/esphome/esp-underhouselights.yaml @@ -28,8 +28,8 @@ substitutions: api_key: !secret esp-api_key # unfortunately you can't use substitutions inside secrets names ota_pass: !secret esp-ota_pass # unfortunately you can't use substitutions inside secrets names static_ip_address: !secret esp-underhouselights_ip - 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_main_topic: !secret mqtt_command_main_topic + mqtt_local_status_main_topic: !secret mqtt_status_main_topic # Device Settings log_level: "ERROR" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE diff --git a/packages/climate_master_bedroom_night_cycle.yaml b/packages/climate_master_bedroom_night_cycle.yaml.old similarity index 100% rename from packages/climate_master_bedroom_night_cycle.yaml rename to packages/climate_master_bedroom_night_cycle.yaml.old diff --git a/packages/energy_readings.yaml b/packages/energy_readings.yaml index b291716..af9db82 100644 --- a/packages/energy_readings.yaml +++ b/packages/energy_readings.yaml @@ -20,10 +20,16 @@ mqtt: unit_of_measurement: "kW" value_template: "{{ value_json.ENERGY.Power[2] }}" -sensor: - - platform: template - sensors: - electricity_power_total: - friendly_name: "Electricity Power Total" +template: + - sensor: + - name: "Electricity Power Total" + unique_id: electricity_power_total unit_of_measurement: "W" - value_template: "{{ states('sensor.tasmo_wemosd1_7280_powermon_1_energy_power_0') |float + states('sensor.tasmo_wemosd1_7280_powermon_1_energy_power_1') | float + states('sensor.tasmo_wemosd1_7280_powermon_1_energy_power_2') | float }}" + device_class: power + state_class: measurement + state: > + {{ + states('sensor.tasmo_wemosd1_7280_powermon_1_energy_power_0') | float(0) + + states('sensor.tasmo_wemosd1_7280_powermon_1_energy_power_1') | float(0) + + states('sensor.tasmo_wemosd1_7280_powermon_1_energy_power_2') | float(0) + }} diff --git a/packages/internet_traffic.yaml b/packages/internet_traffic.yaml index 34c5958..85927f1 100644 --- a/packages/internet_traffic.yaml +++ b/packages/internet_traffic.yaml @@ -1,19 +1,25 @@ -sensor: - - platform: template - sensors: - sensor_internet_downtraffic: - friendly_name: "Internet Download Traffic" +template: + - sensor: + - name: "Internet Download Traffic" + unique_id: internet_downtraffic unit_of_measurement: "kB/s" - value_template: "{{ state_attr('binary_sensor.edgeos_interface_pppoe0', 'KBytes/ps (Received)') }}" - - platform: template - sensors: - sensor_internet_uptraffic: - friendly_name: "Internet Upload Traffic" + state_class: measurement + state: > + {{ state_attr('binary_sensor.edgeos_interface_pppoe0', 'KBytes/ps (Received)') | float(0) }} + + - name: "Internet Upload Traffic" + unique_id: internet_uptraffic unit_of_measurement: "kB/s" - value_template: "{{ state_attr('binary_sensor.edgeos_interface_pppoe0', 'KBytes/ps (Sent)') }}" - - platform: template - sensors: - sensor_internet_totaltraffic: - friendly_name: "Internet Total Traffic" + state_class: measurement + state: > + {{ state_attr('binary_sensor.edgeos_interface_pppoe0', 'KBytes/ps (Sent)') | float(0) }} + + - name: "Internet Total Traffic" + unique_id: internet_totaltraffic unit_of_measurement: "kB/s" - value_template: "{{ state_attr('binary_sensor.edgeos_interface_pppoe0', 'KBytes/ps (Received)') |float + state_attr('binary_sensor.edgeos_interface_pppoe0', 'KBytes/ps (Sent)') | float }}" + state_class: measurement + state: > + {{ + (state_attr('binary_sensor.edgeos_interface_pppoe0', 'KBytes/ps (Received)') | float(0)) + + (state_attr('binary_sensor.edgeos_interface_pppoe0', 'KBytes/ps (Sent)') | float(0)) + }} diff --git a/packages/lounge_lighting_scenes.yaml b/packages/lounge_lighting_scenes.yaml index db384b5..b3499c3 100644 --- a/packages/lounge_lighting_scenes.yaml +++ b/packages/lounge_lighting_scenes.yaml @@ -114,9 +114,9 @@ script: light.esp_lounge6chdimmer_couch_spots_left: 20 light.esp_lounge6chdimmer_couch_spots_right: 20 #light.esp_lounge6chdimmer_dining_table_light: 100 - light.esp_lounge6chdimmer_lounge_downlights_centre: 20 - light.esp_lounge6chdimmer_lounge_downlights_south: 20 - light.esp_lounge6chdimmer_lounge_rafter_buttons: 20 + light.esp_lounge6chdimmer_lounge_downlights_centre: 10 + light.esp_lounge6chdimmer_lounge_downlights_south: 30 + light.esp_lounge6chdimmer_lounge_rafter_buttons: 0 light.esp_breakfastbarleds_breakfast_bar_leds: 40 light.esp_loungecabinetleds2_lounge_cabinet_leds: 40 light.esp_loungebookshelfleds_lounge_bookshelf_leds: 40 diff --git a/packages/low_battery_device_quantity.yaml b/packages/low_battery_device_quantity.yaml index 5be0504..500970f 100644 --- a/packages/low_battery_device_quantity.yaml +++ b/packages/low_battery_device_quantity.yaml @@ -1,20 +1,80 @@ -sensor: - - platform: template - sensors: - devices_with_low_battery: - friendly_name: "Devices with low battery" - unit_of_measurement: devices - value_template: >- - {{ states.sensor - | selectattr('attributes.device_class', 'eq', 'battery') - | map(attribute='state') - | reject('in', ['unknown', 'unavailable', 'Ok']) - | map('int', -1) | select('le', 97) - | list | count - }} - icon_template: >- - {% if is_state('sensor.devices_with_low_battery', '0') %} +template: + - sensor: + - name: "Devices with low battery" + unique_id: devices_with_low_battery_count + unit_of_measurement: "devices" + state: > + {% set ns = namespace(c=0) %} + {% for s in states.sensor %} + {% if s.attributes.device_class == 'battery' %} + {% set st = s.state %} + {% if st not in ['unknown', 'unavailable', 'Ok'] %} + {% if st | int(-1) != -1 and (st | int(0)) <= 97 %} + {% set ns.c = ns.c + 1 %} + {% endif %} + {% endif %} + {% endif %} + {% endfor %} + {{ ns.c }} + icon: > + {% if this.state | int(0) == 0 %} mdi:check-circle {% else %} mdi:battery-alert {% endif %} + + - name: "Devices with low battery list" + unique_id: devices_with_low_battery_list + icon: > + {% if states('sensor.devices_with_low_battery') | int(0) == 0 %} + mdi:check-circle + {% else %} + mdi:battery-alert + {% endif %} + state: > + {% set ns = namespace(names=[]) %} + {% for s in states.sensor %} + {% if s.attributes.device_class == 'battery' %} + {% set st = s.state %} + {% if st not in ['unknown', 'unavailable', 'Ok'] %} + {% if st | int(-1) != -1 and (st | int(0)) <= 97 %} + {% set ns.names = ns.names + [s.name ~ ' (' ~ (st | int(0)) ~ '%)'] %} + {% endif %} + {% endif %} + {% endif %} + {% endfor %} + {% if ns.names | length == 0 %} + None + {% else %} + {{ ns.names | join(', ') }} + {% endif %} + attributes: + count: "{{ states('sensor.devices_with_low_battery') | int(0) }}" + entities: > + {% set ns = namespace(e=[]) %} + {% for s in states.sensor %} + {% if s.attributes.device_class == 'battery' %} + {% set st = s.state %} + {% if st not in ['unknown', 'unavailable', 'Ok'] %} + {% if st | int(-1) != -1 and (st | int(0)) <= 97 %} + {% set ns.e = ns.e + [s.entity_id] %} + {% endif %} + {% endif %} + {% endif %} + {% endif %} + {% endfor %} + {{ ns.e }} + names: > + {% set ns = namespace(n=[]) %} + {% for s in states.sensor %} + {% if s.attributes.device_class == 'battery' %} + {% set st = s.state %} + {% if st not in ['unknown', 'unavailable', 'Ok'] %} + {% if st | int(-1) != -1 and (st | int(0)) <= 97 %} + {% set ns.n = ns.n + [s.name] %} + {% endif %} + {% endif %} + {% endif %} + {% endif %} + {% endfor %} + {{ ns.n }} diff --git a/packages/main_sony_tv_automations.yaml b/packages/main_sony_tv_automations.yaml new file mode 100644 index 0000000..1ca3acc --- /dev/null +++ b/packages/main_sony_tv_automations.yaml @@ -0,0 +1,42 @@ +automation: + - id: "1669966515993" + alias: Turn off Lounge TV + description: "" + trigger: + - platform: mqtt + topic: viewroad-commands/maintv/action + payload: "OFF" + condition: [] + action: + - type: turn_off + device_id: 4a9f71fc64e158f1c9286d6e43ce782e + entity_id: remote.lounge_tv + domain: remote + mode: single + + - id: tv_amp_follow_remote_state + alias: Lounge surround amp follows TV remote (5s debounce) + mode: restart + trigger: + - platform: state + entity_id: remote.lounge_tv + to: "on" + for: "00:00:05" + - platform: state + entity_id: remote.lounge_tv + to: "off" + for: "00:00:05" + action: + - choose: + - conditions: + - condition: state + entity_id: remote.lounge_tv + state: "on" + sequence: + - service: switch.turn_on + target: + entity_id: switch.tv_surround_amp_power_in_loft_x27pp + default: + - service: switch.turn_off + target: + entity_id: switch.tv_surround_amp_power_in_loft_x27pp diff --git a/packages/ms_teams_status.yaml b/packages/ms_teams_status.yaml.old similarity index 100% rename from packages/ms_teams_status.yaml rename to packages/ms_teams_status.yaml.old diff --git a/packages/multi_way_switching.yaml b/packages/multi_way_switching.yaml new file mode 100644 index 0000000..af151b2 --- /dev/null +++ b/packages/multi_way_switching.yaml @@ -0,0 +1,53 @@ +automation: + # Two lights and two switches for these corridor lights + - id: garage_entry_outside_2way_sync + alias: Garage Entry & Outside Light 2-Way Sync + initial_state: true + use_blueprint: + path: zorruno/two_three_way_sync.yaml + input: + members: + - switch.esp_garageentrylights_relay_1_corridor_lights + - switch.esp_loungesouthleftswitch_relay_2_outside_light_1 + sync_on_start: true + startup_delay: 5 + + # Internal Garage Lights (Light controller is sonoff basic in cupboard) + - id: garage_lights_2way_sync + alias: Garage Lights 2-Way Sync + initial_state: true + use_blueprint: + path: zorruno/two_three_way_sync.yaml + input: + members: + - switch.esp_garageentrylights_relay_3_garage_lights + - switch.esp_garagelights_garage_lights + sync_on_start: true + startup_delay: 5 + + # Stair Lights Top + - id: stair_lights_top_2way_sync + alias: Stair lights Top Lights 2-Way Sync + initial_state: true + use_blueprint: + path: zorruno/two_three_way_sync.yaml + input: + members: + - switch.esp_centralstairs_top_relay_1_main_stair_lights + - switch.esp_centralstairs_bottom_relay_1_main_stair_lights_lower + - switch.esp_loungemiddleswitch_relay_3_downlights_north + sync_on_start: true + startup_delay: 5 + + # Stair Lights Bottom + - id: stair_footer_lights_2way_sync + alias: Stair Footer Lights 2-Way Sync + initial_state: true + use_blueprint: + path: zorruno/two_three_way_sync.yaml + input: + members: + - switch.esp_centralstairs_top_relay_2_stair_footer_lights + - switch.esp_centralstairs_bottom_relay_2_stair_footer_lights + sync_on_start: true + startup_delay: 5 diff --git a/packages/nspanel_keepawake.yaml b/packages/nspanel_keepawake.yaml index cf6d5d0..a1a7d29 100644 --- a/packages/nspanel_keepawake.yaml +++ b/packages/nspanel_keepawake.yaml @@ -1,43 +1,21 @@ -#nspanel_keepawake: -# name: Entities to keep NSPanel Awake -# unique_id: Entities_to_keep_NSPanel_Awake -# # Keeps the bedroom NSPanel Bright if any of these are true -# If 'all' is set to true, they are 'ANDed' otherwise 'ORd' -#all: true -# entities: -# - binary_sensor.inverted_quiet_time_sensor -# - light.tasmo_arlecrgb_3522_bulb_3 -# - light.tasmo_ifan02_3793_bedrm1_1 -# - light.tasmo_ks811t_3647_bedrm1_1b - -#light: -# - platform: template -# sensors: -# inverted_quiet_time_sensor: -# value_template: >- -# {{ is_state('input_boolean.quiet_time', 'off') }} -# #device_class: None -# friendly_name: Quiet Time (Inverted) +template: + - light: + - name: "Inverted Quiet time as light" + unique_id: inverted_quiet_time_as_light + state: "{{ is_state('input_boolean.quiet_time', 'off') }}" + turn_on: + - service: light.turn_on + target: + entity_id: light.inverted_quiet_time_light + turn_off: + - service: light.turn_off + target: + entity_id: light.inverted_quiet_time_light light: - - platform: template - lights: - inverted_quiet_time_as_light: - friendly_name: "Inverted Quiet time as light" - unique_id: "inverted quiet time as light" - value_template: "{{ is_state('input_boolean.quiet_time', 'off') }}" - turn_on: - service: light.turn_on - target: - entity_id: light.inverted_quiet_time_light - turn_off: - service: light.turn_off - target: - entity_id: light.inverted_quiet_time_as_light - - platform: group name: "Entities to keep NSPanel Awake" - unique_id: "Entities to keep NSPanel Awake" + unique_id: "Entities to keep_nspanel_awake" entities: - light.inverted_quiet_time_as_light - light.tasmo_arlecrgb_3522_bulb_3 diff --git a/packages/openbeken.yaml b/packages/openbeken.yaml.old similarity index 100% rename from packages/openbeken.yaml rename to packages/openbeken.yaml.old diff --git a/packages/pool_light_boost_switch.yaml b/packages/pool_light_boost_switch.yaml index c9cebf5..af23aa6 100644 --- a/packages/pool_light_boost_switch.yaml +++ b/packages/pool_light_boost_switch.yaml @@ -22,7 +22,7 @@ automation: to: "on" condition: condition: state - entity_id: switch.esp_poollightpower_power_output + entity_id: switch.esp_poollightpower2_switch state: "off" action: - service: mqtt.publish @@ -37,7 +37,7 @@ automation: to: "off" condition: condition: state - entity_id: switch.esp_poollightpower_power_output + entity_id: switch.esp_poollightpower2_switch state: "on" action: - service: mqtt.publish @@ -68,12 +68,12 @@ automation: - alias: "Pool Lights → sync UI switch with real output (no MQTT)" trigger: platform: state - entity_id: switch.esp_poollightpower_power_output + entity_id: switch.esp_poollightpower2_switch action: - choose: - conditions: - condition: state - entity_id: switch.esp_poollightpower_power_output + entity_id: switch.esp_poollightpower2_switch state: "on" sequence: - service: input_boolean.turn_on @@ -84,7 +84,7 @@ automation: entity_id: input_boolean.timer_light_midnight_pending - conditions: - condition: state - entity_id: switch.esp_poollightpower_power_output + entity_id: switch.esp_poollightpower2_switch state: "off" sequence: - service: input_boolean.turn_off diff --git a/packages/presense_sense.yaml b/packages/presense_sense.yaml.old similarity index 100% rename from packages/presense_sense.yaml rename to packages/presense_sense.yaml.old diff --git a/packages/raspberry_pi_monitor.yaml b/packages/raspberry_pi_monitor.yaml index 1fdd51f..4236183 100644 --- a/packages/raspberry_pi_monitor.yaml +++ b/packages/raspberry_pi_monitor.yaml @@ -1,79 +1,131 @@ mqtt: sensor: - - state_topic: "viewroad-status/rpis/cctvquad1/cpu-temp" + - unique_id: cctvquad1_cpu_temp + state_topic: "viewroad-status/rpis/cctvquad1/cpu-temp" name: "CCTVQuad1 CPU Temperature" unit_of_measurement: "°C" + device_class: temperature + state_class: measurement + value_template: "{{ value | float(0) }}" icon: mdi:thermometer - - state_topic: "viewroad-status/rpis/cctvquad1/cpu-use" + + - unique_id: cctvquad1_cpu_use + state_topic: "viewroad-status/rpis/cctvquad1/cpu-use" name: "CCTVQuad1 CPU Use" unit_of_measurement: "%" + state_class: measurement + value_template: "{{ value | float(0) }}" icon: mdi:cpu-32-bit - - state_topic: "viewroad-status/rpis/cctvquad1/ram-use" + + - unique_id: cctvquad1_ram_use + state_topic: "viewroad-status/rpis/cctvquad1/ram-use" name: "CCTVQuad1 RAM Use" unit_of_measurement: "%" + state_class: measurement + value_template: "{{ value | float(0) }}" icon: mdi:raspberry-pi - - state_topic: "viewroad-status/rpis/cctvquad1/disk-use" + + - unique_id: cctvquad1_disk_use + state_topic: "viewroad-status/rpis/cctvquad1/disk-use" name: "CCTVQuad1 Disk Use" unit_of_measurement: "%" + state_class: measurement + value_template: "{{ value | float(0) }}" icon: mdi:harddisk - - state_topic: "viewroad-status/rpis/cctvquad1/uptime" + + - unique_id: cctvquad1_uptime + state_topic: "viewroad-status/rpis/cctvquad1/uptime" name: "CCTVQuad1 Uptime" icon: mdi:timer - - state_topic: "viewroad-status/rpis/cctvquad1/last-seen" + + - unique_id: cctvquad1_last_seen + state_topic: "viewroad-status/rpis/cctvquad1/last-seen" name: "CCTVQuad1 Last Seen" icon: mdi:calendar-clock - - state_topic: "viewroad-status/rpis/cctvquad1/ipv4-address" + + - unique_id: cctvquad1_ipv4_address + state_topic: "viewroad-status/rpis/cctvquad1/ipv4-address" name: "CCTVQuad1 IPv4 Address" icon: mdi:server-network - - state_topic: "viewroad-status/rpis/cctvquad2/cpu-temp" + + - unique_id: cctvquad2_cpu_temp + state_topic: "viewroad-status/rpis/cctvquad2/cpu-temp" name: "CCTVQuad2 CPU Temperature" unit_of_measurement: "°C" + device_class: temperature + state_class: measurement + value_template: "{{ value | float(0) }}" icon: mdi:thermometer - - state_topic: "viewroad-status/rpis/cctvquad2/cpu-use" + + - unique_id: cctvquad2_cpu_use + state_topic: "viewroad-status/rpis/cctvquad2/cpu-use" name: "CCTVQuad2 CPU Use" unit_of_measurement: "%" + state_class: measurement + value_template: "{{ value | float(0) }}" icon: mdi:cpu-32-bit - - state_topic: "viewroad-status/rpis/cctvquad2/ram-use" + + - unique_id: cctvquad2_ram_use + state_topic: "viewroad-status/rpis/cctvquad2/ram-use" name: "CCTVQuad2 RAM Use" unit_of_measurement: "%" + state_class: measurement + value_template: "{{ value | float(0) }}" icon: mdi:raspberry-pi - - state_topic: "viewroad-status/rpis/cctvquad2/disk-use" + + - unique_id: cctvquad2_disk_use + state_topic: "viewroad-status/rpis/cctvquad2/disk-use" name: "CCTVQuad2 Disk Use" unit_of_measurement: "%" + state_class: measurement + value_template: "{{ value | float(0) }}" icon: mdi:harddisk - - state_topic: "viewroad-status/rpis/cctvquad2/uptime" + + - unique_id: cctvquad2_uptime + state_topic: "viewroad-status/rpis/cctvquad2/uptime" name: "CCTVQuad2 Uptime" icon: mdi:timer - - state_topic: "viewroad-status/rpis/cctvquad2/last-seen" + + - unique_id: cctvquad2_last_seen + state_topic: "viewroad-status/rpis/cctvquad2/last-seen" name: "CCTVQuad2 Last Seen" icon: mdi:calendar-clock - - state_topic: "viewroad-status/rpis/cctvquad2/ipv4-address" + + - unique_id: cctvquad2_ipv4_address + state_topic: "viewroad-status/rpis/cctvquad2/ipv4-address" name: "CCTVQuad2 IPv4 Address" icon: mdi:server-network switch: - - name: "CCTVQuad1 Reboot" + - unique_id: cctvquad1_reboot + name: "CCTVQuad1 Reboot" state_topic: "viewroad-status/rpis/cctvquad1/reboot" command_topic: "viewroad-commands/rpis/cctvquad1/reboot/set" qos: 1 optimistic: false retain: false icon: mdi:refresh - - name: "CCTVQuad1 Shutdown" + + - unique_id: cctvquad1_shutdown + name: "CCTVQuad1 Shutdown" state_topic: "viewroad-status/rpis/cctvquad1/shutdown" command_topic: "viewroad-commands/rpis/cctvquad1/shutdown/set" qos: 1 optimistic: false retain: false icon: mdi:close-network - - name: "CCTVQuad2 Reboot" + + - unique_id: cctvquad2_reboot + name: "CCTVQuad2 Reboot" state_topic: "viewroad-status/rpis/cctvquad2/reboot" command_topic: "viewroad-commands/rpis/cctvquad2/reboot/set" qos: 1 optimistic: false retain: false icon: mdi:refresh - - name: "CCTVQuad2 Shutdown" + + - unique_id: cctvquad2_shutdown + name: "CCTVQuad2 Shutdown" state_topic: "viewroad-status/rpis/cctvquad2/shutdown" command_topic: "viewroad-commands/rpis/cctvquad2/shutdown/set" qos: 1 @@ -81,29 +133,25 @@ mqtt: retain: false icon: mdi:close-network -binary_sensor: - - platform: template - sensors: - pi_cctvquad1_on: - friendly_name: "CCTV Quad1 Available" - value_template: >- - {%- if states( 'sensor.cctvquad1_last_seen' ) != 'unknown' - and ( as_timestamp( now() ) - as_timestamp( states( 'sensor.cctvquad1_last_seen' ) ) ) <= 180 -%} - True - {%- else -%} - False - {%- endif %} - - platform: template - sensors: - pi_cctvquad2_on: - friendly_name: "CCTV Quad2 Available" - value_template: >- - {%- if states( 'sensor.cctvquad2_last_seen' ) != 'unknown' - and ( as_timestamp( now() ) - as_timestamp( states( 'sensor.cctvquad2_last_seen' ) ) ) <= 180 -%} - True - {%- else -%} - False - {%- endif %} +template: + - binary_sensor: + - name: "CCTV Quad1 Available" + unique_id: pi_cctvquad1_on + device_class: connectivity + state: > + {% set now_ts = as_timestamp(now()) %} + {% set last_ts = as_timestamp(states('sensor.cctvquad1_last_seen'), default=0) %} + {% set age = now_ts - last_ts %} + {{ last_ts > 0 and age >= 0 and age <= 180 }} + + - name: "CCTV Quad2 Available" + unique_id: pi_cctvquad2_on + device_class: connectivity + state: > + {% set now_ts = as_timestamp(now()) %} + {% set last_ts = as_timestamp(states('sensor.cctvquad2_last_seen'), default=0) %} + {% set age = now_ts - last_ts %} + {{ last_ts > 0 and age >= 0 and age <= 180 }} group: pi_cctvquad1_on: @@ -133,61 +181,3 @@ group: - sensor.cctvquad2_ram_use - sensor.cctvquad2_disk_use - sensor.cctvquad2_last_seen -#automation: -# - alias: "Home Assistant Start" -# trigger: -# platform: homeassistant -# event: start -# action: -# - service: group.set_visibility -# entity_id: -# - group.pi_cctvquad1_on -# data: -# visible: False -# - alias: "pi is on" -# trigger: -# platform: state -# entity_id: -# - binary_sensor.pi_cctvquad1_on -# from: "off" -# to: "on" -# action: -# - service: group.set_visibility -# data_template: -# entity_id: "group.pi_{{ trigger.entity_id | replace( 'binary_sensor.pi_', '' ) }}" -# visible: True -# - service: group.set_visibility -# data_template: -# entity_id: "group.pi_{{ trigger.entity_id | replace( 'binary_sensor.pi_', '' ) | replace( '_on', '' ) }}_off" -# visible: False -# - alias: "pi not seen" -# trigger: -# platform: state -# entity_id: -# - binary_sensor.pi_cctvquad1_on -# from: "on" -# to: "off" -# action: -# - service: group.set_visibility -# data_template: -# entity_id: "group.pi_{{ trigger.entity_id | replace( 'binary_sensor.pi_', '' ) | replace( '_on', '' ) }}_on" -# visible: False -# - service: group.set_visibility -# data_template: -# entity_id: "group.pi_{{ trigger.entity_id | replace( 'binary_sensor.pi_', '' ) | replace( '_on', '' ) }}_off" -# visible: True -#- service: notify.ios_PHONENAME -#data_template: -#title: "Pi Offline" -#message: "{{ trigger.entity_id | replace( 'binary_sensor.pi_', '' ) | replace( '_on', '' ) }}" -#- alias: 'pi disk use' -#trigger: -#platform: numeric_state -#entity_id: -#- sensor.cctvquad1_disk_use -#above: 90 -#action: -#- service: notify.ios_PHONENAME -#data_template: -#title: "Pi Disk Use > 90%" -#message: "{{ trigger.entity_id | replace( 'sensor.', '' ) | replace( '_disk_use', '' ) }}" diff --git a/packages/simulation_lights.yaml b/packages/simulation_lights.yaml index d37aee6..15decd2 100644 --- a/packages/simulation_lights.yaml +++ b/packages/simulation_lights.yaml @@ -10,6 +10,9 @@ group: - switch.esp_mainkitchenlights_relay_1_main_lights - switch.esp_mainkitchenlights_relay_2_benchtop_lights - switch.main_hallway_lightswitch_tasmo_ks811s_2940_hallway_1a - - switch.tasmo_ks811t_0702_lounge_3a - - switch.tasmo_ks811t_0702_lounge_3b - - switch.tasmo_ks811t_0702_lounge_3c + - light.esp_lounge6chdimmer_lounge_downlights_centre + - light.esp_lounge6chdimmer_lounge_downlights_south + - light.esp_lounge6chdimmer_lounge_rafter_buttons + - light.esp_loungepelmetleds2_lounge_pelmet_leds_a + - light.esp_lounge6chdimmer_couch_spots_left + - light.esp_lounge6chdimmer_couch_spots_right diff --git a/packages/system_ha_uptime.yaml b/packages/system_ha_uptime.yaml new file mode 100644 index 0000000..eb89275 --- /dev/null +++ b/packages/system_ha_uptime.yaml @@ -0,0 +1,23 @@ +############################################# +# HOME ASSISTANT SYSTEM UPTIME SENSORS +# V1.2 2025-11-26 +# - System Monitor removed from YAML (must be added via UI) +# - Template sensors only +############################################# + +############################################# +# TEMPLATE SENSORS (Home Assistant Core uptime) +############################################# +template: + - sensor: + - name: Home Assistant Core Uptime + unique_id: ha_core_uptime_seconds + icon: mdi:timer-outline + unit_of_measurement: seconds + state: > + {% set start = states('sensor.uptime') %} + {% if start in ['unknown', 'unavailable', 'none', ''] %} + unknown + {% else %} + {{ (as_timestamp(now()) - as_timestamp(start)) | int }} + {% endif %} diff --git a/packages/weather_additional.yaml b/packages/weather_additional.yaml index 39383fa..db46d20 100644 --- a/packages/weather_additional.yaml +++ b/packages/weather_additional.yaml @@ -1,8 +1,13 @@ -sensor: - - platform: template - sensors: - weewx_wind_bearing_template: - value_template: > +template: + - sensor: + - name: "Weewx Wind Bearing" + unique_id: weewx_wind_bearing_template + state: > {% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %} - {% set degree = states('sensor.weewx_wind_direction')|float %} - {{ direction[((degree+11.25)/22.5)|int] }} + {% set degree = states('sensor.weewx_wind_direction') | float(none) %} + {% if degree is not none %} + {% set d = (degree % 360) %} + {{ direction[((d + 11.25) / 22.5) | int] }} + {% else %} + unknown + {% endif %} diff --git a/packages/weewx.yaml b/packages/weewx.yaml index 42059fb..fed305c 100644 --- a/packages/weewx.yaml +++ b/packages/weewx.yaml @@ -3,136 +3,145 @@ mqtt: - unique_id: weewx_windSpeed_kph state_topic: "weewx/windSpeed_kph" name: "Weewx Wind Speed" - unit_of_measurement: "kph" - value_template: "{{ value | round(1) }}" + unit_of_measurement: "km/h" + state_class: measurement + value_template: "{{ value | float(0) | round(1) }}" icon: "mdi:weather-windy-variant" + - unique_id: weewx_windGust_kph state_topic: "weewx/windGust_kph" name: "Weewx Wind Gust" - unit_of_measurement: "kph" - value_template: "{{ value | round(1) }}" - icon: "mdi:outTemp_C" + unit_of_measurement: "km/h" + state_class: measurement + value_template: "{{ value | float(0) | round(1) }}" + icon: "mdi:weather-windy" + - unique_id: weewx_outTemp_C state_topic: "weewx/outTemp_C" name: "Weewx Outdoor Temperature" unit_of_measurement: "°C" - device_class: "temperature" - value_template: "{{ value | round(1) }}" + device_class: temperature + state_class: measurement + value_template: "{{ value | float(0) | round(1) }}" icon: "mdi:thermometer" + - unique_id: weewx_inTemp_C state_topic: "weewx/inTemp_C" name: "Weewx Indoor Temperature" unit_of_measurement: "°C" - device_class: "temperature" - value_template: "{{ value | round(1) }}" + device_class: temperature + state_class: measurement + value_template: "{{ value | float(0) | round(1) }}" icon: "mdi:thermometer" + - unique_id: weewx_humidex_C state_topic: "weewx/humidex_C" name: "Weewx Humidex" unit_of_measurement: "°C" - device_class: "temperature" - value_template: "{{ value | round(1) }}" + device_class: temperature + state_class: measurement + value_template: "{{ value | float(0) | round(1) }}" icon: "mdi:thermometer" + - unique_id: weewx_dewpoint_C state_topic: "weewx/dewpoint_C" name: "Weewx Dewpoint" unit_of_measurement: "°C" - device_class: "temperature" - value_template: "{{ value | round(1) }}" + device_class: temperature + state_class: measurement + value_template: "{{ value | float(0) | round(1) }}" icon: "mdi:thermometer" + - unique_id: weewx_heatindex_C state_topic: "weewx/heatindex_C" name: "Weewx Heat Index" unit_of_measurement: "°C" - device_class: "temperature" - value_template: "{{ value | round(1) }}" + device_class: temperature + state_class: measurement + value_template: "{{ value | float(0) | round(1) }}" icon: "mdi:thermometer" + - unique_id: weewx_windchill_C state_topic: "weewx/windchill_C" name: "Weewx Windchill" unit_of_measurement: "°C" - device_class: "temperature" - value_template: "{{ value | round(1) }}" + device_class: temperature + state_class: measurement + value_template: "{{ value | float(0) | round(1) }}" icon: "mdi:thermometer" + - unique_id: weewx_outHumidity state_topic: "weewx/outHumidity" name: "Weewx Outdoor Humidity" unit_of_measurement: "%" - value_template: "{{ value | round(1) }}" + device_class: humidity + state_class: measurement + value_template: "{{ value | float(0) | round(1) }}" icon: "mdi:water-percent" + - unique_id: weewx_inHumidity state_topic: "weewx/inHumidity" name: "Weewx Indoor Humidity" unit_of_measurement: "%" - value_template: "{{ value | round(1) }}" + device_class: humidity + state_class: measurement + value_template: "{{ value | float(0) | round(1) }}" icon: "mdi:water-percent" + - unique_id: weewx_barometer_mbar state_topic: "weewx/barometer_mbar" - name: "Weewx Air Pressure" - unit_of_measurement: "mbar" - value_template: "{{ value | round(3) }}" + name: "Weewx Barometer" + unit_of_measurement: "hPa" + device_class: pressure + state_class: measurement + value_template: "{{ value | float(0) | round(3) }}" icon: "mdi:gauge" + - unique_id: weewx_altimeter_mbar state_topic: "weewx/altimeter_mbar" - name: "Weewx Air Pressure" - unit_of_measurement: "mbar" - value_template: "{{ value | round(3) }}" + name: "Weewx Altimeter Pressure" + unit_of_measurement: "hPa" + device_class: pressure + state_class: measurement + value_template: "{{ value | float(0) | round(3) }}" icon: "mdi:gauge" + - unique_id: weewx_windDir state_topic: "weewx/windDir" name: "Weewx Wind Direction" - unit_of_measurement: "degrees" - value_template: "{{ value | round(1) }}" + unit_of_measurement: "deg" + state_class: measurement + value_template: "{{ value | float(0) | round(1) }}" icon: "mdi:compass" + - unique_id: weewx_windGustDir state_topic: "weewx/windGustDir" name: "Weewx Wind Gust Direction" - unit_of_measurement: "degrees" - value_template: "{{ value | round(1) }}" + unit_of_measurement: "deg" + state_class: measurement + value_template: "{{ value | float(0) | round(1) }}" icon: "mdi:compass" + - unique_id: weewx_rainRate_cm_per_hour state_topic: "weewx/rainRate_cm_per_hour" name: "Weewx Rain Rate" - unit_of_measurement: "cm/hour" - value_template: "{{ value | round(4) }}" + unit_of_measurement: "cm/h" + state_class: measurement + value_template: "{{ value | float(0) | round(4) }}" icon: "mdi:weather-rainy" + - unique_id: weewx_rain_cm state_topic: "weewx/rain_cm" name: "Weewx Rain Now" unit_of_measurement: "cm" - value_template: "{{ value | round(4) }}" + state_class: measurement + value_template: "{{ value | float(0) | round(4) }}" icon: "mdi:weather-rainy" + - unique_id: weewx_hourRain_cm state_topic: "weewx/hourRain_cm" name: "Weewx Hourly Rain" unit_of_measurement: "cm" - value_template: "{{ value | round(4) }}" + state_class: measurement + value_template: "{{ value | float(0) | round(4) }}" icon: "mdi:weather-rainy" - - unique_id: weewx_dayRain_cm - state_topic: "weewx/dayRain_cm" - name: "Weewx Daily Rain" - unit_of_measurement: "cm" - value_template: "{{ value | round(4) }}" - icon: "mdi:weather-rainy" - - unique_id: weewx_rain24_cm - state_topic: "weewx/rain24_cm" - name: "Weewx 24 Hour Rain" - unit_of_measurement: "cm" - value_template: "{{ value | round(4) }}" - icon: "mdi:weather-rainy" - - unique_id: weewx_rainTotal - state_topic: "weewx/rainTotal" - name: "Weewx Rain Total" - unit_of_measurement: "cm" - value_template: "{{ value | multiply(0.3937) | round(4) }}" - icon: "mdi:weather-rainy" - - unique_id: weewx_dateTime - state_topic: "weewx/dateTime" - name: "WeeWX Timestamp" - unit_of_measurement: "s" - value_template: "{{ value }}" - - unique_id: weewx_irxCheckPercent - state_topic: "weewx/rxCheckPercent" - name: "WeeWX Receive Quality" - unit_of_measurement: "%" - value_template: "{{ value }}" diff --git a/scripts/cctv_detect.yaml b/scripts/cctv_detect.yaml deleted file mode 100644 index 05e8c37..0000000 --- a/scripts/cctv_detect.yaml +++ /dev/null @@ -1,8 +0,0 @@ -#camdetecon: -# alias: booleanopen -# sequence: -# - service: input_boolean.turn_on -# entity_id: input_boolean.cameramotion -# - delay: 00:00:30 -# - service: input_boolean.turn_off -# entity_id: input_boolean.cameramotion