#:########################################################################################:#
# TITLE: BEDROOM 3 LIGHTSWITCH
# zorruno.com layout v1.1 2026
#:########################################################################################:#
# REPO:
# https://home.fox.co.nz/gitea/zorruno/zorruno-homeassistant/src/branch/master/esphome/esp-bedrm3lights.yaml
#:########################################################################################:#
# VERSIONS:
# V3.7 2026-07-25 Standardized MQTT payloads: "ON"/"OFF" → "On"/"Off"
# V3.6 2026-03-05 Updated yaml to zorruno layout V1.1
# V3.5 2025-07-24 YAML tidyups
#:########################################################################################:#
# HARDWARE:
# - Zemismart KS-811 Double push button (KS-811-2)
#   pinout/schematic: https://community.home-assistant.io/t/zemismart-ks-811-working-with-esphome/
#:########################################################################################:#
# OPERATION NOTES:
# - Virtual 2-button wall switch used to control Bedroom 3 ceiling fan light and to force "all off"
# - Button 1 toggles the iFan02 light (sends MQTT ON/OFF), using Relay 1 as the local state mirror
# - Button 2 forces "All Lights Off" (turns iFan02 light OFF and sets fan speed to 0), and turns Relay 2 OFF
# - Relay 1 and Relay 2 are used as local state indicators (no load connected)
# - A short cooldown is used on Button 1 to prevent repeated MQTT publishes
#:########################################################################################:#
# MQTT COMMANDS:
# Remote fan light command:
#   ${mqtt_remote_device_command_topic1}  ->  ON,OFF
# Remote fan speed command (used by All Off):
#   ${mqtt_remote_device_command_topic2}  ->  0
#
# Remote fan light status (subscribed to keep Relay 1 in sync):
#   ${mqtt_remote_status_topic1}          ->  ON,OFF
#:########################################################################################:#
# OFFLINE NOTES:
# a) Home Assistant OFFLINE, but Network and MQTT ONLINE
#    - Buttons still publish MQTT commands directly to the remote iFan02 (light and all-off actions)
#    - Relay 1 state mirror still updates from subscribed remote light status topic
# b) MQTT OFFLINE (but WiFi/Network and HA API ONLINE)
#    - Buttons cannot control the remote iFan02 (control path is MQTT)
#    - Relay 1 will not mirror the remote light status while MQTT is down
# c) Entire WiFi/Network OFFLINE
#    - No MQTT publish/subscribe and no HA API connectivity
#    - Buttons will not control the remote iFan02
#    - Local indicator relays remain in their last state until connectivity returns (or reboot)
#    - Accurate time is NOT needed (SNTP not required) for core operation
#:########################################################################################:#

#:########################################################################################:#
# 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-bedrm3lights"
  friendly_name: "Bedroom 3 Lightswitch (2)"
  description_comment: "Bedroom 3 Main Lightswitch using a Zemismart KS-811 Double Push Button. Main Lights (1-Virtual), All Lights Off (2-Virtual) (Layout V1.1)"
  device_area: "Bedroom 3" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant.

  # 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

  # Passwords and Secrets
  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_command_main_topic
  mqtt_local_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
  log_level: "INFO" # Define logging level: NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE
  update_interval: "60s" # update time for general sensors etc

  # MQTT LOCAL Controls
  mqtt_device_name: "bedroom3-lightswitch"

  # MQTT REMOTE Controls (Bedroom 3 iFan02)
  mqtt_remote_device_name: "bedroom3-ceilingfan"

  # Remote Light
  mqtt_remote_device_command_topic1: "${mqtt_local_command_main_topic}/${mqtt_remote_device_name}/light/set"
  mqtt_remote_status_topic1: "${mqtt_local_status_main_topic}/${mqtt_remote_device_name}/light/state"
  mqtt_remote_device_command_ON: "On"
  mqtt_remote_device_command_OFF: "Off"

  # Remote Fan Speed (used for All Off)
  mqtt_remote_device_command_topic2: "${mqtt_local_command_main_topic}/${mqtt_remote_device_name}/speed/set"
  mqtt_remote_device_command_0: "0"

  # Switch Naming
  switch_1_name: "Main Lights" # Nothing physically connected to this output (ifan02 light is the real load)
  switch_2_name: "All Lights Off" # Nothing physically connected to this output

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

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

#:########################################################################################:#
# LOGGING: ESPHome Logging Enable
# https://esphome.io/components/logger.html
#:########################################################################################:#
logger:
  level: "${log_level}" # INFO suggested, or DEBUG for testing
  #baud_rate: 0 # set to 0 for no logging via UART, needed if using UART for other serial devices
  #esp8266_store_log_strings_in_flash: false
  #tx_buffer_size: 64

#:########################################################################################:#
# GLOBAL VARIABLES:
# https://esphome.io/guides/automations.html#global-variables
#:########################################################################################:#
globals:
  - id: btn1_last_ms
    type: uint32_t
    restore_value: false
    initial_value: "0"

#:########################################################################################:#
# STATUS LED:
# https://esphome.io/components/status_led.html
#:########################################################################################:#
status_led:
  pin:
    number: GPIO2
    inverted: true

#:########################################################################################:#
# BINARY SENSORS:
# https://esphome.io/components/binary_sensor/
# Buttons for KS-811-2 are GPIO16, GPIO5
#:########################################################################################:#
binary_sensor:
  - platform: gpio
    id: button_1
    pin:
      number: GPIO16
      mode:
        input: true
        pullup: false # set to true if you need an internal pull-up
      inverted: true
    use_interrupt: false # GPIO16 does not support interrupts so use polling (suppresses warning).
    name: "Button 1: ${switch_1_name}"
    filters:
      - delayed_on: 30ms
      - delayed_off: 30ms
    on_press:
      # Cooldown: 250ms between publishes
      - if:
          condition:
            lambda: |-
              return (millis() - id(btn1_last_ms)) > 250;
          then:
            - lambda: |-
                id(btn1_last_ms) = millis();
            - if:
                condition:
                  switch.is_on: Relay_1
                then:
                  - mqtt.publish:
                      topic: "${mqtt_remote_device_command_topic1}"
                      payload: "${mqtt_remote_device_command_OFF}"
                      qos: 0
                      retain: false
                else:
                  - mqtt.publish:
                      topic: "${mqtt_remote_device_command_topic1}"
                      payload: "${mqtt_remote_device_command_ON}"
                      qos: 0
                      retain: false

  - platform: gpio
    id: button_2
    pin:
      number: GPIO05
      mode: INPUT
      inverted: true
    name: "Button 2: ${switch_2_name}"
    on_press:
      - switch.turn_off: Relay_2
      - mqtt.publish:
          topic: "${mqtt_remote_device_command_topic1}"
          payload: "${mqtt_remote_device_command_OFF}"
          qos: 0
          retain: false
      - mqtt.publish:
          topic: "${mqtt_remote_device_command_topic2}"
          payload: "${mqtt_remote_device_command_0}"
          qos: 0
          retain: false

#:########################################################################################:#
# SWITCH COMPONENT:
# https://esphome.io/components/switch/
# Relays for KS-811-2 are GPIO13, GPIO12 (no load connected; used as indicators)
#:########################################################################################:#
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

#:########################################################################################:#
# MQTT:
# This adds device-specific MQTT command triggers to the common MQTT configuration.
#:########################################################################################:#
mqtt:
  on_message:
    # Mirror remote light state onto Relay 1 indicator
    - topic: "${mqtt_remote_status_topic1}"
      payload: "${mqtt_remote_device_command_ON}"
      then:
        - switch.turn_on: Relay_1

    - topic: "${mqtt_remote_status_topic1}"
      payload: "${mqtt_remote_device_command_OFF}"
      then:
        - switch.turn_off: Relay_1
