#:########################################################################################:#
# TITLE: OFFICE MAIN LIGHTSWITCH
# zorruno.com layout v1.1 2026
#:########################################################################################:#
# REPO:
# https://home.fox.co.nz/gitea/zorruno/zorruno-homeassistant/src/branch/master/esphome/esp-officelights.yaml
#:########################################################################################:#
# VERSIONS:
# v3.0 2026-07-25 Refactored MQTT sync to use template HA switch actions; physical button and
#                 HA control now publish command topics to officeduallights; relay callbacks
#                 publish status only to prevent command ping-pong/chattering. 2-way sync with
#                 esp-officeduallights for offline HA-independent operation.
# v2.1 2026-02-25 Updated yaml to zorruno layout V1.1
# v2.0 2025-06-05 YAML Tidyups
# v1.0 2025-05-31 Initial Version
#:########################################################################################:#
# HARDWARE:
# - Zemismart KS-811 Triple push button (ESP8266)
# - Pinout/Schematic: https://community.home-assistant.io/t/zemismart-ks-811-working-with-esphome/
#:########################################################################################:#
# OPERATION NOTES:
# - Office 3-gang KS-811 (Triple) wall switch.
# - Button 1 (top) toggles Bunker Lights (both local Relay 1 physical bunker + remote dual light_1
#   Right Bunker via MQTT). Local Relay 1 is a physical load; remote is the Sonoff Dual R1.
# - Button 2 (middle) toggles Overhead Lights (remote dual light_2 via MQTT). Local Relay 2 is
#   a virtual mirror of the remote state only (no physical load connected).
# - Button 3 (bottom) is spare - no function assigned.
# - Home Assistant control of the exposed template switches also toggles the matching groups.
# - MQTT command topics request On/Off changes.
# - Relay state changes publish retained status only.
# - Relays never publish command topics directly. This prevents command ping-pong/chattering.
# - GPIO16 on ESP8266 does not support normal GPIO interrupts, so Button 1 uses polling mode.
#:########################################################################################:#
# MQTT COMMANDS:
# Bunker Lights (Button 1):
# - Command topic: ${mqtt_this_device_command_topic_bunker}
#   Payloads: ${mqtt_command_on}, ${mqtt_command_off}, or 1 to 3600 (timer seconds)
# - Status topic: ${mqtt_this_device_status_topic_bunker}
#   Payloads mirror the actual bunker relay state and are published retained.
#
# Overhead Lights (Button 2):
# - Command topic: ${mqtt_this_device_command_topic_overhead}
#   Payloads: ${mqtt_command_on}, ${mqtt_command_off}, or 1 to 3600 (timer seconds)
# - Status topic: ${mqtt_this_device_status_topic_overhead}
#   Payloads mirror the overhead virtual relay state and are published retained.
#
# This device subscribes to status topics from esp-officeduallights to mirror remote state.
# Timer values from esp-occupancyoffice are handled locally (countdown runs on this device).
# Physical button presses cancel any active timer before toggling.
#:########################################################################################:#
# OFFLINE NOTES:
# - a) Home Assistant offline (network and MQTT online):
#      - Local button control continues for both bunker and overhead lights.
#      - MQTT command/status operation continues for 2-way sync with esp-officeduallights.
#      - HA entities are unavailable until HA returns.
# - b) MQTT offline (or Home Assistant and MQTT offline):
#      - Local button control continues.
#      - Bunker lights still toggle locally (physical relay).
#      - Overhead lights cannot be toggled remotely (no MQTT transport).
#      - If Home Assistant is online and connected by native ESPHome API, HA control can still
#        change the local relays but remote MQTT sync is unavailable until MQTT returns.
# - c) Entire WiFi/network offline:
#      - Local wall-switch button control continues for both buttons.
#      - Bunker lights still toggle locally (physical relay).
#      - Overhead lights cannot be controlled (no network transport).
#      - Accurate time is not needed. SNTP is not used for this device.
#:########################################################################################:#

#:########################################################################################:#
# 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-officelights"
  friendly_name: "Office Main Lightswitch (3)"
  description_comment: "Office Main Lightswitch using a Zemismart KS-811 Triple Push Button. Bunker Lights (1), Overhead Lights (2), Spare (3) (Layout V1.1)"
  device_area: "Office"

  # Project Naming
  project_name: "Zemismart Technologies.KS-811 Triple"
  project_version: "v3.0"

  # Passwords & Secrets
  api_key: !secret esp-api_key
  ota_pass: !secret esp-ota_pass
  static_ip_address: !secret esp-officelights_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
  log_level: "INFO"
  update_interval: "60s"

  # Default relay restore mode
  # Options: RESTORE_DEFAULT_OFF, RESTORE_DEFAULT_ON, ALWAYS_ON, ALWAYS_OFF
  relay_restore_mode: "RESTORE_DEFAULT_OFF"

  # MQTT LOCAL Controls - Bunker Lights
  # Command topics: this device publishes here when Button 1 or HA toggles bunker.
  # Status topics:  this device publishes retained status here on relay state changes.
  #                 esp-officeduallights subscribes to mirror remote bunker state.
  mqtt_this_device_function_bunker: "office-main-lights-left"
  mqtt_this_device_command_topic_bunker: "${mqtt_command_main_topic}/${mqtt_this_device_function_bunker}"
  mqtt_this_device_status_topic_bunker: "${mqtt_status_main_topic}/${mqtt_this_device_function_bunker}"

  # MQTT LOCAL Controls - Overhead Lights
  # Command topics: this device publishes here when Button 2 or HA toggles overhead.
  # Status topics:  this device publishes retained status here on virtual relay state changes.
  #                 esp-officeduallights subscribes to mirror remote overhead state.
  mqtt_this_device_function_overhead: "office-main-lights-right"
  mqtt_this_device_command_topic_overhead: "${mqtt_command_main_topic}/${mqtt_this_device_function_overhead}"
  mqtt_this_device_status_topic_overhead: "${mqtt_status_main_topic}/${mqtt_this_device_function_overhead}"

  # MQTT Status/Command payloads
  mqtt_command_on: "On"
  mqtt_command_off: "Off"

  # MQTT Overhead Status - shared topic for overhead state sync
  # Both this device and esp-officeduallights publish and subscribe to this topic so
  # whichever device's timer finishes first keeps the other in sync.
  mqtt_shared_overhead_status_function: "office-overhead-status"
  mqtt_shared_overhead_status_topic: "${mqtt_status_main_topic}/${mqtt_shared_overhead_status_function}"

  # Switch/Relay/Button Naming
  switch_1_name: "Bunker Lights" # Physical relay (GPIO13) connected to bunker light load
  switch_2_name: "Overhead Lights" # Virtual mirror of esp-officeduallights overhead state
  switch_3_name: "Spare" # Virtual only, no function assigned

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

  #### 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}"
  area: "${device_area}"
  project:
    name: "${project_name}"
    version: "${project_version}"

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

#:########################################################################################:#
# LOGGING
# https://esphome.io/components/logger.html
#:########################################################################################:#
logger:
  level: "${log_level}"
  #baud_rate: 0
  id: logger_id

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

#:########################################################################################:#
# MQTT: Device-specific MQTT command triggers
# This extends the common MQTT package with local custom command/status topics.
#:########################################################################################:#
mqtt:
  # Republish current relay states whenever MQTT reconnects so retained status stays accurate
  # for subscribers that reconnect later.
  on_connect:
    - mqtt.publish:
        topic: "${mqtt_this_device_status_topic_bunker}"
        payload: !lambda |-
          return id(Relay_1).state ? "${mqtt_command_on}" : "${mqtt_command_off}";
        retain: true
    - mqtt.publish:
        topic: "${mqtt_this_device_status_topic_overhead}"
        payload: !lambda |-
          return id(Relay_2).state ? "${mqtt_command_on}" : "${mqtt_command_off}";
        retain: true
    - mqtt.publish:
        topic: "${mqtt_shared_overhead_status_topic}"
        payload: !lambda |-
          return id(Relay_2).state ? "${mqtt_command_on}" : "${mqtt_command_off}";
        retain: true

  on_message:
    # Mirror remote overhead command onto virtual Relay_2, but only if a real state change
    # is needed. Do not republish the command from here. Relay status is published by the
    # relay callback below.
    - topic: "${mqtt_this_device_command_topic_overhead}"
      payload: "${mqtt_command_on}"
      then:
        - script.stop: overhead_timer_script
        - if:
            condition:
              lambda: "return !id(Relay_2).state;"
            then:
              - switch.turn_on: Relay_2

    - topic: "${mqtt_this_device_command_topic_overhead}"
      payload: "${mqtt_command_off}"
      then:
        - script.stop: overhead_timer_script
        - if:
            condition:
              lambda: "return id(Relay_2).state;"
            then:
              - switch.turn_off: Relay_2

    - topic: "${mqtt_this_device_command_topic_overhead}"
      then:
        - lambda: |-
            if (x.empty()) {
              return;
            }

            bool numeric_payload = true;
            for (char c : x) {
              if (c < '0' || c > '9') {
                numeric_payload = false;
                break;
              }
            }

            if (!numeric_payload) {
              return;
            }

            const int timer_seconds = atoi(x.c_str());
            if (timer_seconds < 1 || timer_seconds > 3600) {
              return;
            }

            id(overhead_timer_script)->execute(timer_seconds * 1000);

    # Mirror shared overhead status from esp-officeduallights onto virtual Relay_2.
    # This handles the case where the dual lights' overhead timer finishes and turns off
    # the overhead — the main lightswitch mirrors the state so its virtual relay stays
    # in sync. State guards prevent ping-pong with the command topic handlers above.
    - topic: "${mqtt_shared_overhead_status_topic}"
      payload: "${mqtt_command_on}"
      then:
        - if:
            condition:
              lambda: "return !id(Relay_2).state;"
            then:
              - switch.turn_on: Relay_2

    - topic: "${mqtt_shared_overhead_status_topic}"
      payload: "${mqtt_command_off}"
      then:
        - if:
            condition:
              lambda: "return id(Relay_2).state;"
            then:
              - switch.turn_off: Relay_2

    # Mirror remote bunker command onto Relay_1, but only if a real state change is needed.
    # This handles commands from esp-officeduallights when its local button toggles the
    # physical bunker light and publishes status.
    - topic: "${mqtt_this_device_status_topic_bunker}"
      payload: "${mqtt_command_on}"
      then:
        - if:
            condition:
              lambda: "return !id(Relay_1).state;"
            then:
              - switch.turn_on: Relay_1

    - topic: "${mqtt_this_device_status_topic_bunker}"
      payload: "${mqtt_command_off}"
      then:
        - if:
            condition:
              lambda: "return id(Relay_1).state;"
            then:
              - switch.turn_off: Relay_1

    # Bunker command from occupancy sensor or other MQTT publishers. Handles On, Off,
    # and numeric timer values (1 to 3600 seconds).
    - topic: "${mqtt_this_device_command_topic_bunker}"
      payload: "${mqtt_command_on}"
      then:
        - script.stop: bunker_timer_script
        - if:
            condition:
              lambda: "return !id(Relay_1).state;"
            then:
              - switch.turn_on: Relay_1

    - topic: "${mqtt_this_device_command_topic_bunker}"
      payload: "${mqtt_command_off}"
      then:
        - script.stop: bunker_timer_script
        - if:
            condition:
              lambda: "return id(Relay_1).state;"
            then:
              - switch.turn_off: Relay_1

    - topic: "${mqtt_this_device_command_topic_bunker}"
      then:
        - lambda: |-
            if (x.empty()) {
              return;
            }

            bool numeric_payload = true;
            for (char c : x) {
              if (c < '0' || c > '9') {
                numeric_payload = false;
                break;
              }
            }

            if (!numeric_payload) {
              return;
            }

            const int timer_seconds = atoi(x.c_str());
            if (timer_seconds < 1 || timer_seconds > 3600) {
              return;
            }

            id(bunker_timer_script)->execute(timer_seconds * 1000);

#:########################################################################################:#
# SCRIPTS
# https://esphome.io/components/script.html
#:########################################################################################:#
script:
  # Local/HA requested ON for Bunker Lights. Change the local relay immediately, then publish
  # a non-retained command so esp-officeduallights follows.
  - id: office_bunker_on
    mode: restart
    then:
      - if:
          condition:
            lambda: "return !id(Relay_1).state;"
          then:
            - switch.turn_on: Relay_1
      - mqtt.publish:
          topic: "${mqtt_this_device_command_topic_bunker}"
          payload: "${mqtt_command_on}"
          retain: false

  # Local/HA requested OFF for Bunker Lights.
  - id: office_bunker_off
    mode: restart
    then:
      - if:
          condition:
            lambda: "return id(Relay_1).state;"
          then:
            - switch.turn_off: Relay_1
      - mqtt.publish:
          topic: "${mqtt_this_device_command_topic_bunker}"
          payload: "${mqtt_command_off}"
          retain: false

  # Physical Button 1 toggle logic for Bunker Lights. This is the only place that decides
  # ON vs OFF for the bunker.
  - id: office_bunker_toggle
    mode: restart
    then:
      - if:
          condition:
            lambda: "return id(Relay_1).state;"
          then:
            - script.execute: office_bunker_off
          else:
            - script.execute: office_bunker_on

  # Local/HA requested ON for Overhead Lights. Change the virtual mirror immediately, then
  # publish a non-retained command so esp-officeduallights follows.
  - id: office_overhead_on
    mode: restart
    then:
      - if:
          condition:
            lambda: "return !id(Relay_2).state;"
          then:
            - switch.turn_on: Relay_2
      - mqtt.publish:
          topic: "${mqtt_this_device_command_topic_overhead}"
          payload: "${mqtt_command_on}"
          retain: false

  # Local/HA requested OFF for Overhead Lights.
  - id: office_overhead_off
    mode: restart
    then:
      - if:
          condition:
            lambda: "return id(Relay_2).state;"
          then:
            - switch.turn_off: Relay_2
      - mqtt.publish:
          topic: "${mqtt_this_device_command_topic_overhead}"
          payload: "${mqtt_command_off}"
          retain: false

  # Physical Button 2 toggle logic for Overhead Lights.
  - id: office_overhead_toggle
    mode: restart
    then:
      - if:
          condition:
            lambda: "return id(Relay_2).state;"
          then:
            - script.execute: office_overhead_off
          else:
            - script.execute: office_overhead_on

  # Bunker timer script. Turns on immediately, waits for the duration, then turns off.
  # mode: restart means a new valid timer value restarts the timer from zero.
  - id: bunker_timer_script
    mode: restart
    parameters:
      timer_duration_ms: int
    then:
      - switch.turn_on: Relay_1
      - delay: !lambda "return timer_duration_ms;"
      - switch.turn_off: Relay_1

  # Overhead timer script. Turns on immediately, waits for the duration, then turns off.
  - id: overhead_timer_script
    mode: restart
    parameters:
      timer_duration_ms: int
    then:
      - switch.turn_on: Relay_2
      - delay: !lambda "return timer_duration_ms;"
      - switch.turn_off: Relay_2

#:########################################################################################:#
# BINARY SENSORS
# https://esphome.io/components/binary_sensor/
#:########################################################################################:#
binary_sensor:
  # Button 1 (GPIO16) - polling (GPIO16 has no interrupts)
  - platform: gpio
    pin:
      number: GPIO16
      mode: INPUT
      inverted: true
    use_interrupt: false
    name: "Button 1: ${switch_1_name}"
    filters:
      - delayed_on: 10ms
      - delayed_off: 10ms
    on_press:
      - script.execute: office_bunker_toggle

  # Button 2 (GPIO05)
  - platform: gpio
    pin:
      number: GPIO05
      mode: INPUT
      inverted: true
    name: "Button 2: ${switch_2_name}"
    filters:
      - delayed_on: 10ms
      - delayed_off: 10ms
    on_press:
      - script.execute: office_overhead_toggle

  # Button 3 (GPIO4) - Spare
  - platform: gpio
    pin:
      number: GPIO4
      mode: INPUT
      inverted: true
    name: "Button 3: ${switch_3_name}"

#:########################################################################################:#
# SWITCH
# https://esphome.io/components/switch/
#:########################################################################################:#
switch:
  # Exposed Home Assistant control for Bunker Lights. This controls the local relay and
  # publishes the matching command so esp-officeduallights follows.
  - platform: template
    name: "Relay 1: ${switch_1_name}"
    id: Relay_1_HA
    lambda: |-
      return id(Relay_1).state;
    turn_on_action:
      - script.execute: office_bunker_on
    turn_off_action:
      - script.execute: office_bunker_off

  # Exposed Home Assistant control for Overhead Lights. This publishes the matching command
  # so esp-officeduallights follows. Local Relay_2 is a virtual mirror of remote state.
  - platform: template
    name: "Relay 2: ${switch_2_name}"
    id: Relay_2_HA
    lambda: |-
      return id(Relay_2).state;
    turn_on_action:
      - script.execute: office_overhead_on
    turn_off_action:
      - script.execute: office_overhead_off

  # Physical Relay 1 (Bunker Lights). Kept internal so HA uses the template switch above.
  # Relay callbacks publish retained status only, not commands.
  - platform: gpio
    name: "Internal Relay 1: ${switch_1_name}"
    internal: true
    pin: GPIO13
    id: Relay_1
    restore_mode: ${relay_restore_mode}
    on_turn_on:
      - mqtt.publish:
          topic: "${mqtt_this_device_status_topic_bunker}"
          payload: "${mqtt_command_on}"
          retain: true
    on_turn_off:
      - mqtt.publish:
          topic: "${mqtt_this_device_status_topic_bunker}"
          payload: "${mqtt_command_off}"
          retain: true

  # Virtual Relay 2 (Overhead Lights mirror). No physical load connected. Mirrors the state
  # of esp-officeduallights overhead light via MQTT status subscription.
  - platform: gpio
    name: "Internal Relay 2: ${switch_2_name}"
    internal: true
    pin: GPIO12
    id: Relay_2
    restore_mode: ${relay_restore_mode}
    on_turn_on:
      - mqtt.publish:
          topic: "${mqtt_this_device_status_topic_overhead}"
          payload: "${mqtt_command_on}"
          retain: true
      - mqtt.publish:
          topic: "${mqtt_shared_overhead_status_topic}"
          payload: "${mqtt_command_on}"
          retain: true
    on_turn_off:
      - mqtt.publish:
          topic: "${mqtt_this_device_status_topic_overhead}"
          payload: "${mqtt_command_off}"
          retain: true
      - mqtt.publish:
          topic: "${mqtt_shared_overhead_status_topic}"
          payload: "${mqtt_command_off}"
          retain: true

  # Relay 3 (Spare) - no function assigned
  - platform: gpio
    name: "Relay 3: ${switch_3_name}"
    pin: GPIO14
    id: Relay_3
