#:########################################################################################:#
# TITLE: UNDERHOUSE LIGHTS
# zorruno.com layout v1.1 2026
#:########################################################################################:#
# REPO:
# https://home.fox.co.nz/gitea/zorruno/zorruno-homeassistant/src/branch/master/esphome/esp-underhouselights.yaml
#:########################################################################################:#
# VERSIONS:
# V1.2 2026-07-25 Standardized MQTT payloads: "ON"/"OFF" → "On"/"Off"
# V1.1 2026-02-25 Updated yaml to zorruno layout V1.1
# V1.0 2025-06-18 Initial Version
#:########################################################################################:#
# HARDWARE:
# Controlled by a Sonoff 4Ch R2
# Reference YAML: https://github.com/jvyoralek/homeassistant-config/blob/master/esphome/sonoff-4ch.yaml
#
# GPIO (Sonoff 4Ch R2):
# - Relays:  GPIO12, GPIO05, GPIO04, GPIO15
# - Buttons: GPIO00, GPIO09, GPIO10, GPIO14
# - Status LED: GPIO13
# - Extra "Remote Switch" inputs used here: GPIO03, GPIO02
#:########################################################################################:#
# OPERATION NOTES:
# - 4-channel relay controller for underhouse lighting circuits.
# - Local buttons toggle each relay (button1..button4).
# - Two extra GPIO inputs act as "remote switches" that toggle relay1 and relay2.
# - MQTT local command topics allow ON/OFF control per relay (see MQTT COMMANDS).
#:########################################################################################:#
# MQTT COMMANDS:
# Relay control (local MQTT):
# - ${mqtt_local_command_topic}/relay1/set  -> ON, OFF
# - ${mqtt_local_command_topic}/relay2/set  -> ON, OFF
# - ${mqtt_local_command_topic}/relay3/set  -> ON, OFF
# - ${mqtt_local_command_topic}/relay4/set  -> ON, OFF
#:########################################################################################:#
# OFFLINE NOTES:
# a) Home Assistant OFFLINE, but Network and MQTT ONLINE
#    - Device remains controllable via MQTT local command topics.
#    - Local buttons and remote switch inputs continue to toggle relays.
# b) MQTT OFFLINE (but WiFi/Network and HA API ONLINE)
#    - Device remains controllable via Home Assistant API.
#    - MQTT local commands will not work while MQTT is down.
#    - Local buttons and remote switch inputs continue to toggle relays.
# c) Entire WiFi/Network OFFLINE
#    - Local buttons and remote switch inputs continue to toggle relays.
#    - No HA API or MQTT control available.
#    - SNTP is not needed (no timeclocks used).
#:########################################################################################:#

#:########################################################################################:#
# 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-underhouselights"
  friendly_name: "Underhouse Lights"
  description_comment: "Underhouse Lights Control :: Sonoff 4Ch R2 (Layout V1.1)"
  device_area: "Underhouse" # Allows ESP device to be automatically linked to an 'Area' in Home Assistant.

  # Project Naming
  project_name: "Sonoff Technologies.Sonoff 4Ch R2" # Project Details
  project_version: "v1.2"  # 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-underhouselights_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: "ERROR" # NONE, ERROR, WARN, INFO, DEBUG (Default), VERBOSE, VERY_VERBOSE
  update_interval: "60s" # update time for general sensors etc

  # MQTT Controls
  mqtt_device_name: "underhouse-lights-control"
  mqtt_local_command_topic: "${mqtt_local_command_main_topic}/${mqtt_device_name}" # Topic we will use to command this locally without HA
  mqtt_local_status_topic: "${mqtt_local_status_main_topic}/${mqtt_device_name}" # Topic we will use to view status locally without HA

  # Switch Naming
  switch_1_name: "Underhouse Entrance Lights"
  button_1_name: "Button 1"
  relay_1_icon: "mdi:lightbulb"

  switch_2_name: "Underhouse Storage Lights"
  button_2_name: "Button 2"
  relay_2_icon: "mdi:lightbulb"

  switch_3_name: "Spare 3"
  button_3_name: "Button 3"
  relay_3_icon: "mdi:lightbulb"

  switch_4_name: "Spare 4"
  button_4_name: "Button 4"
  relay_4_icon: "mdi:lightbulb"

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

#:########################################################################################:#
# ESP PLATFORM AND FRAMEWORK:
# https://esphome.io/components/esp8266/
#:########################################################################################:#
esp8266:
  board: esp01_1m
  restore_from_flash: true

preferences:
  flash_write_interval: 5min

mdns:
  disabled: false

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

#:########################################################################################:#
# SWITCH COMPONENT:
# https://esphome.io/components/switch/
# Sonoff 4Ch R2 Relays are GPIO12, GPIO05, GPIO04, GPIO15
#:########################################################################################:#
switch:
  - platform: gpio
    id: relay1
    name: "${switch_1_name}"
    pin: GPIO12
    icon: "${relay_1_icon}"

  - platform: gpio
    id: relay2
    name: "${switch_2_name}"
    pin: GPIO5
    icon: "${relay_2_icon}"

  - platform: gpio
    id: relay3
    name: "${switch_3_name}"
    pin: GPIO4
    icon: "${relay_3_icon}"

  - platform: gpio
    id: relay4
    name: "${switch_4_name}"
    pin: GPIO15
    icon: "${relay_4_icon}"

#:########################################################################################:#
# BINARY SENSORS:
# https://esphome.io/components/binary_sensor/
# Sonoff 4Ch R2 Buttons are GPIO00, GPIO09, GPIO10, GPIO14
#:########################################################################################:#
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

  # Extra remote switch input -> toggles relay 1
  - platform: gpio
    pin:
      number: GPIO3
      mode: INPUT_PULLUP
      inverted: true
    name: "${switch_1_name} Remote Switch"
    id: light_button_1
    filters:
      - delayed_on: 20ms
    on_click:
      - min_length: 20ms
        max_length: 500ms
        then:
          - lambda: |-
              if (id(relay1).state) {
                id(relay1).turn_off();
              } else {
                id(relay1).turn_on();
              }

  # Extra remote switch input -> toggles relay 2
  - platform: gpio
    pin:
      number: GPIO2
      mode: INPUT_PULLUP
      inverted: true
    name: "${switch_2_name} Remote Switch"
    id: light_button_2
    filters:
      - delayed_on: 20ms
    on_click:
      - min_length: 20ms
        max_length: 500ms
        then:
          - lambda: |-
              if (id(relay2).state) {
                id(relay2).turn_off();
              } else {
                id(relay2).turn_on();
              }

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

#:########################################################################################:#
# MQTT:
# This adds device-specific MQTT command triggers to the common MQTT configuration.
#:########################################################################################:#
mqtt:
  on_message:
    # Relay 1 control
    - topic: "${mqtt_local_command_topic}/relay1/set"
      payload: "On"
      then:
        - switch.turn_on: relay1
    - topic: "${mqtt_local_command_topic}/relay1/set"
      payload: "Off"
      then:
        - switch.turn_off: relay1

    # Relay 2 control
    - topic: "${mqtt_local_command_topic}/relay2/set"
      payload: "On"
      then:
        - switch.turn_on: relay2
    - topic: "${mqtt_local_command_topic}/relay2/set"
      payload: "Off"
      then:
        - switch.turn_off: relay2

    # Relay 3 control
    - topic: "${mqtt_local_command_topic}/relay3/set"
      payload: "On"
      then:
        - switch.turn_on: relay3
    - topic: "${mqtt_local_command_topic}/relay3/set"
      payload: "Off"
      then:
        - switch.turn_off: relay3

    # Relay 4 control
    - topic: "${mqtt_local_command_topic}/relay4/set"
      payload: "On"
      then:
        - switch.turn_on: relay4
    - topic: "${mqtt_local_command_topic}/relay4/set"
      payload: "Off"
      then:
        - switch.turn_off: relay4