#:########################################################################################:#
# TITLE: MAIN BATHROOM FAN/HEAT COMBO SWITCH
# zorruno.com layout v1.1 2026
#:########################################################################################:#
# REPO:
# https://home.fox.co.nz/gitea/zorruno/zorruno-homeassistant/src/branch/master/esphome/esp-mainbathfancombo.yaml
#:########################################################################################:#
# VERSIONS:
# V1.6 2026-03-04 Updated yaml to zorruno layout V1.1; adjusted Button 2 click timing for towel rail MQTT reliability
# V1.5 2026-02-23 MQTT numeric timer only applies if fan already ON (does not turn fan ON)
# V1.4 2026-02-23 Add mm:ss countdown text sensor (eg 22:12) + per-second countdown engine
# V1.3 2026-02-23 Add 60-min cap timer + Remaining Minutes sensor (counts down)
# V1.2 2026-02-18 Stop delayed-off countdown when Relay_1 turns OFF
# V1.1 2025-08-26 Minor Changes (MQTT)
# V1.0 2025-06-01 Initial Version
#:########################################################################################:#
# HARDWARE:
# - Zemismart KS-811 Double Push Button
#   pinout/schematic https://community.home-assistant.io/t/zemismart-ks-811-working-with-esphome/
#:########################################################################################:#
# OPERATION NOTES:
# a) MQTT Local Usage
#    Send ON to ${mqtt_command_main_topic}/${mqtt_local_device_name} and it will turn the fan ON (60 min cap)
#    Send OFF to ${mqtt_command_main_topic}/${mqtt_local_device_name} and it will turn the fan OFF
#    Send a value from 1 to 60 to ${mqtt_command_main_topic}/${mqtt_local_device_name}
#      and it will ONLY start/restart the countdown IF the fan is already ON (in minutes)
# b) IR Heater Safety
#    It is designed so there should be no situation that the Heater can be on without the fan.
#    If the fan turns off, so will the IR Heater.
# c) Timing functions
#    By default, the fan will be on for 60mins max.  Other values can be sent via MQTT/HA
# d) Other device control
#    This device can turn on the heated towel rail via MQTT (doubleclick button 2)
#:########################################################################################:#
# OFFLINE NOTES:
# a) Home Assistant OFFLINE, but Network and MQTT ONLINE
#    - The fan can still be controlled with  ON, OFF and given a timer value, via MQTT.
#    - The Heated towel rail can also be switched on.
# b) HA/MQTT OFFLINE
#    With no automation controllers, fan and heater can be controlled on/off with the switches.
#    Auto timers cannot be changed, but the fam will be on for 60mins max.
# c) Internet/Wifi OFFLINE
#    No further changes, SNTP not required as timing functions do not rely on accurate clock.
#    - Accurate time is NOT needed (SNTP not required) for core operation (no time-of-day schedules)
#:########################################################################################:#


#:########################################################################################:#
# SUBSTITUTIONS: 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-mainbathfancombo"
  friendly_name: "Main Bathroom Fan-Heat Combo Switch (2)"
  description_comment: "Main Bathroom Fan/Heat Switch using a Zemismart KS-811 Double Push Button. Extract Fan (1), IR heater (2) (Layout V1.1)"
  device_area: "Main Bathroom" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant.

  # Project Naming
  project_name: "Zemismart Technologies.KS-811-2 (Double)" # Project Details
  project_version: "v1.6" # 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 inside secrets names
  ota_pass: !secret esp-ota_pass # unfortunately you can't use substitutions inside secrets names
  static_ip_address: !secret esp-mainbathfancombo_ip
  mqtt_command_main_topic: !secret mqtt_command_main_topic
  mqtt_status_main_topic: !secret mqtt_status_main_topic

  # If we are changing IP addresses, you must update the current IP address here, otherwise it remains
  # Don't forget to switch it back when changed.
  current_ip_address: ${static_ip_address}

  # 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

  # MQTT LOCAL Controls
  mqtt_local_device1_name: "masterbath-fan"
  mqtt_local_command1_topic: "${mqtt_command_main_topic}/${mqtt_local_device1_name}" # Topic we will use to command this locally without HA
  mqtt_local_status1_topic: "${mqtt_status_main_topic}/${mqtt_local_device1_name}" # Topic we will use to view status locally without HA

  # MQTT REMOTE Controls
  mqtt_remote_device1_name: "masterbath-towelrail"
  mqtt_remote_device1_command_topic: "${mqtt_command_main_topic}/${mqtt_remote_device1_name}/operation"
  mqtt_remote_device1_command1: "BOOST"


#:########################################################################################:#
# 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}"
      local_current_ip_address: "${current_ip_address}"

  #### 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}"
  #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: -100
    then:
      # Avoid stale relay2_forced_relay1 across boots
      - if:
          condition:
            switch.is_on: Relay_2
          then:
            - lambda: |-
                id(relay2_forced_relay1) = !id(Relay_1).state;
            - if:
                condition:
                  switch.is_off: Relay_1
                then:
                  - switch.turn_on: Relay_1
          else:
            - lambda: |-
                id(relay2_forced_relay1) = false;


#:########################################################################################:#
# ESP PLATFORM AND FRAMEWORK:
# https://esphome.io/components/esp32.html
#:########################################################################################:#
esp8266:
  board: esp01_1m
  early_pin_init: false # Recommended false where switches are involved.
  board_flash_mode: dout # Default is dout


#:########################################################################################:#
# 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


#:########################################################################################:#
# GLOBAL VARIABLES:
# https://esphome.io/guides/automations.html?highlight=globals#global-variables
#:########################################################################################:#
globals:
  # Tracks if Relay_2 forced Relay_1 ON (so we can decide if Relay_1 should turn OFF when Relay_2 turns OFF)
  - id: relay2_forced_relay1
    type: bool
    restore_value: yes
    initial_value: "false"

  # 60-min cap / countdown state for Relay_1 (Fan)
  - id: relay1_timer_active
    type: bool
    restore_value: no
    initial_value: "false"

  - id: relay1_autooff_pending
    type: bool
    restore_value: no
    initial_value: "false"

  - id: relay1_remaining_min
    type: int
    restore_value: no
    initial_value: "0"

  # mm:ss countdown tracking
  - id: relay1_end_ms
    type: uint32_t
    restore_value: no
    initial_value: "0"

  - id: relay1_remaining_sec
    type: int
    restore_value: no
    initial_value: "0"


#:########################################################################################:#
# STATUS LED:
# https://esphome.io/components/status_led.html
#:########################################################################################:#
# Status LED for KS-811 is gpio2
status_led:
  pin:
    number: GPIO2
    inverted: yes


#:########################################################################################:#
# SENSORS:
#:########################################################################################:#
sensor:
  - platform: template
    name: "${entity_prefix} Fan Remaining Minutes"
    id: relay1_remaining_minutes
    unit_of_measurement: "min"
    accuracy_decimals: 0
    icon: mdi:timer-outline
    update_interval: 1s
    lambda: |-
      return (float) id(relay1_remaining_min);

text_sensor:
  - platform: template
    name: "${entity_prefix} Fan Countdown"
    id: relay1_countdown_text
    icon: mdi:timer-outline
    update_interval: 1s
    lambda: |-
      int sec = id(relay1_remaining_sec);
      if (sec < 0) sec = 0;
      int m = sec / 60;
      int s = sec % 60;
      char buf[12];
      snprintf(buf, sizeof(buf), "%d:%02d", m, s);
      return std::string(buf);


#:########################################################################################:#
# MQTT: Device-specific MQTT command triggers
# This adds device-specific MQTT command triggers to the common MQTT configuration.
#:########################################################################################:#
mqtt:
  on_message:
    # Fan control: ON / OFF / 1..60 minutes (timer only if fan already ON)
    - topic: "${mqtt_local_command1_topic}"
      then:
        - lambda: |-
            std::string p = x;

            // Trim leading/trailing whitespace
            while (!p.empty() && (p.back() == '\n' || p.back() == '\r' || p.back() == ' ' || p.back() == '\t')) p.pop_back();
            size_t s = p.find_first_not_of(" \t\r\n");
            if (s == std::string::npos) return;
            p = p.substr(s);

            // Uppercase
            for (size_t i = 0; i < p.size(); i++) {
              if (p[i] >= 'a' && p[i] <= 'z') p[i] = (char)(p[i] - 'a' + 'A');
            }

            if (p == "ON") {
              // ON always turns fan ON (if needed) and starts/restarts 60 min cap timer
              id(relay_1_delayed_off).execute(60, true);
              return;
            }

            if (p == "OFF") {
              if (id(Relay_1).state) id(Relay_1).turn_off();
              return;
            }

            // Parse 1..60 minutes
            char *endptr = nullptr;
            long v = strtol(p.c_str(), &endptr, 10);

            if (endptr != nullptr) {
              while (*endptr == ' ' || *endptr == '\t' || *endptr == '\r' || *endptr == '\n') endptr++;
            }

            if (endptr != nullptr && *endptr == '\0' && v >= 1 && v <= 60) {
              // Minor change: ONLY start/restart countdown if fan already ON (do not turn it ON)
              if (id(Relay_1).state) {
                id(relay_1_delayed_off).execute((int) v, false);
                ESP_LOGI("mqtt", "Relay_1 timer restarted: %ld minute(s).", v);
              } else {
                ESP_LOGI("mqtt", "Ignoring timer value %ld because Relay_1 is OFF.", v);
              }
            } else {
              ESP_LOGW("mqtt", "Ignoring payload '%s' on %s", p.c_str(), "${mqtt_local_command1_topic}");
            }


#:########################################################################################:#
# SCRIPTS:
#:########################################################################################:#
script:
  # Starts/restarts mm:ss countdown, and optionally turns fan ON (used for MQTT ON / auto-start)
  - id: relay_1_delayed_off
    mode: restart
    parameters:
      off_delay_min: int
      ensure_on: bool
    then:
      - lambda: |-
          int m = off_delay_min;
          if (m < 1) m = 1;
          if (m > 60) m = 60;

          uint32_t dur_ms = (uint32_t) m * 60UL * 1000UL;
          id(relay1_end_ms) = millis() + dur_ms;

          id(relay1_remaining_sec) = m * 60;
          id(relay1_remaining_min) = m;

          id(relay1_timer_active) = true;
          id(relay1_autooff_pending) = false;

      # Optionally ensure fan is ON
      - if:
          condition:
            lambda: |-
              return ensure_on;
          then:
            - if:
                condition:
                  switch.is_off: Relay_1
                then:
                  - switch.turn_on: Relay_1


#:########################################################################################:#
# BINARY SENSORS:
# https://esphome.io/components/binary_sensor/
#:########################################################################################:#
# Buttons for KS-811-2 are GPIO16, GPIO05
binary_sensor:
  - platform: gpio
    pin:
      number: GPIO16
      mode: INPUT
      inverted: true
    use_interrupt: false # GPIO16 pin doesn't support interrupts so use polling. Only suppresses a warning.
    name: "Button 1: Extract Fan"
    on_press:
      - switch.toggle: Relay_1

  - platform: gpio
    pin:
      number: GPIO05
      mode: INPUT
      inverted: true
    name: "Button 2: IR Heater"
    filters:
      - delayed_on: 20ms
      - delayed_off: 20ms

    on_multi_click:
      # Double click: quick and deliberate
      - timing:
          - ON for at most 350ms
          - OFF for at most 350ms
          - ON for at most 350ms
          - OFF for at least 120ms
        then:
          - mqtt.publish:
              topic: "${mqtt_remote_device1_command_topic}"
              payload: "${mqtt_remote_device1_command1}"

      # Single click: normal press, short settle time so it still feels responsive
      - timing:
          - ON for at most 500ms
          - OFF for at least 350ms
        then:
          - switch.toggle: Relay_2


#:########################################################################################:#
# SWITCH COMPONENT:
# https://esphome.io/components/switch/
#:########################################################################################:#
# Relays for KS-811-2 are GPIO13, GPIO12
switch:
  - platform: gpio
    name: "Relay 1: Extract Fan"
    pin: GPIO13
    id: Relay_1

    on_turn_on:
      then:
        # Any direct ON of Relay_1 starts a 60 minute cap timer, EXCEPT:
        # - When a timer/script has already started (prevents MQTT "5" being overwritten to 60)
        # - When Relay_2 forced Relay_1 ON
        - if:
            condition:
              lambda: |-
                if (id(relay1_timer_active)) return false;
                if (id(Relay_2).state && id(relay2_forced_relay1)) return false;
                return true;
            then:
              - script.execute:
                  id: relay_1_delayed_off
                  off_delay_min: 60
                  ensure_on: false

    on_turn_off:
      then:
        # Clear timer state
        - lambda: |-
            id(relay1_timer_active) = false;
            id(relay1_remaining_min) = 0;
            id(relay1_remaining_sec) = 0;
            id(relay1_end_ms) = 0;
            id(relay1_autooff_pending) = false;

        # Stop any pending delayed-off countdown if Relay_1 is turned OFF (by any means)
        - script.stop: relay_1_delayed_off

        # Rule 3: If Relay_1 is turned OFF while Relay_2 is ON, turn OFF Relay_2 too
        - if:
            condition:
              switch.is_on: Relay_2
            then:
              - switch.turn_off: Relay_2

  - platform: gpio
    name: "Relay 2: IR Heater"
    pin: GPIO12
    id: Relay_2

    on_turn_on:
      then:
        # Rule 2: Relay_2 implies Relay_1 must be ON
        # Also capture whether Relay_2 had to force Relay_1 ON (Rule 4/5 memory)
        - lambda: |-
            id(relay2_forced_relay1) = !id(Relay_1).state;
        - switch.turn_on: Relay_1

    on_turn_off:
      then:
        # Rule 4/5:
        # - If Relay_1 was ON before Relay_2, keep Relay_1 ON
        # - If Relay_2 was ON before Relay_1 (forced), then turn Relay_1 OFF now
        - if:
            condition:
              lambda: |-
                return id(relay2_forced_relay1);
            then:
              - switch.turn_off: Relay_1

        # If a fan timer finished while heater was ON, auto-off fan now (when heater turns OFF)
        - if:
            condition:
              lambda: |-
                return id(relay1_autooff_pending);
            then:
              - lambda: |-
                  id(relay1_autooff_pending) = false;
              - if:
                  condition:
                    switch.is_on: Relay_1
                  then:
                    - switch.turn_off: Relay_1


#:########################################################################################:#
# INTERVAL COMPONENT:
# https://esphome.io/components/interval/
#:########################################################################################:#
# Assurance: if Relay_2 (Heater) is ever on, check that Relay_1 (Fan) is on also
interval:
  - interval: 1s
    then:
      # Countdown engine (mm:ss)
      - lambda: |-
          if (id(relay1_timer_active) && id(Relay_1).state) {
            int32_t diff = (int32_t) (id(relay1_end_ms) - millis());

            if (diff <= 0) {
              id(relay1_remaining_sec) = 0;
              id(relay1_remaining_min) = 0;
              id(relay1_timer_active) = false;

              // If heater is ON, keep fan running but remember to turn it off when heater turns off
              if (id(Relay_2).state) {
                id(relay1_autooff_pending) = true;
              } else {
                id(Relay_1).turn_off();
              }
            } else {
              // Ceil to avoid showing 0:00 early
              int sec = (diff + 999) / 1000;
              id(relay1_remaining_sec) = sec;

              // Minutes sensor uses ceil minutes (stays 1 until it hits 0:00)
              id(relay1_remaining_min) = (sec + 59) / 60;
            }
          }

      # Safety: if Relay_2 (Heater) is ever on, check that Relay_1 (Fan) is on also
      - if:
          condition:
            and:
              - switch.is_on: Relay_2
              - switch.is_off: Relay_1
          then:
            - switch.turn_off: Relay_2