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(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 (x == "on") {
            id(power_switch).turn_on();
          } else {
            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
    optimistic: true
    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
    turn_off_action:
      - output.turn_off: tv_relay  # Set P23 LOW
      - delay: 1500ms
      - output.turn_on: tv_relay   # Set P23 HIGH

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