esphome:
  name: mateuszs-tv
  friendly_name: Mateusz's TV

esp32:
  board: esp32dev
  framework:
    type: arduino

# Enable logging
logger:

# Enable Home Assistant API
api:
  encryption:
    key: "sn7OnWvf695dM1BAlpkhUFeFbBOyLCFwob+vOEiz6MY="

ota:
  platform: esphome
  password: !secret ota

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password

  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "Mateuszs-Tv Fallback Hotspot"
    password: "j781muxx0RXE"

captive_portal:

web_server:

# Define the TV state binary sensor (connected to GPIO34)
binary_sensor:
  - platform: gpio
    pin:
      number: 34
      mode: INPUT
    name: "Status"
    id: status
    device_class: power
    on_state:
      - lambda: |-
          if (id(override).state == false) {
            if (id(power_switch).state != x) {
              id(power_switch).publish_state(x);
            }
          }

text_sensor:
  - platform: homeassistant
    entity_id: remote.chromecast_hd
    id: tv_status
    on_value:
      - lambda: |-
            if (id(override).state == false) {
              if (x == "on" && !id(power_switch).state) {
                id(power_switch).turn_on();
              } else if (x == "off" && id(power_switch).state) {
                id(power_switch).turn_off();
              }
            }

# Define the switch to control TV power (Only toggled via Home Assistant)
switch:
  - platform: template
    name: "Switch"
    id: power_switch
    restore_mode: RESTORE_DEFAULT_OFF
    # turn_on_action:
    #   - output.turn_off: tv_relay  # Set P23 LOW
    #   - delay: 300ms
    #   - output.turn_on: tv_relay   # Set P23 HIGH
    optimistic: true
    turn_off_action:
      - lambda: |-
            if (millis() > 5000) {  // Check if 5 seconds have passed since startup
              id(tv_relay).turn_off();  // Set P23 LOW
              delay(1500);              // Delay for 1500ms
              id(tv_relay).turn_on();   // Set P23 HIGH
            }

  - platform: template
    name: "Override"
    id: override
    optimistic: true
    restore_mode: RESTORE_DEFAULT_OFF

# Define GPIO23 as the output (normally pull-up)
output:
  - platform: gpio
    id: tv_relay
    pin:
      number: 23
      mode: OUTPUT
      inverted: false  # Normal logic (LOW = active)
