---
substitutions:
  devicename: "nodemcu-09"
  id_name: nodemcu_09
  Device_Location: "Garage InfraRed"
  update_interval: !secret d1-update_interval
  ipaddress: 10.0.0.19
  unique_id: "nodemcu-09"
  deep_sleep_interval: !secret deep_sleep_interval

logger:
  level: WARN

esp8266:
  board: nodemcuv2

wifi:
  ssid: !secret mogwai_wifi_name
  password: !secret mogwai_wifi_password
  <<: !include common/network.yaml

  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "$devicename Fallback Hotspot"
    password: !secret mogwai_ap_key

api:
  encryption:
    key: !secret mogwai_api_key

ota:
  platform: esphome
  password: !secret mogwai_ota_key

captive_portal:

esphome:
  name: $devicename
  friendly_name: "NodeMCU-09 - Garage PIR Sensor"

<<: !include common/nodemcu-led-onboard-both-mqtt.yaml

<<: !include common/time.yaml

<<: !include common/website.yaml

<<: !include common/wifi1.yaml

<<: !include common/uptime_formatted.yaml

switch:

  - <<: !include common/nodemcu-led-onboard1.yaml

  - <<: !include common/nodemcu-led-onboard2.yaml

  - <<: !include common/restart.yaml

  - platform: gpio
    id: led_blue
    name: "led_blue"
    pin:
      number: D7
      mode: OUTPUT
    restore_mode: ALWAYS_OFF
    on_turn_on:
      - mqtt.publish:
          topic: /sensors/nodemcu-09/ota_mode
          payload: "BLUE"

  - platform: gpio
    id: led_red
    name: "led_red"
    pin:
      number: D6
      mode: OUTPUT
    restore_mode: ALWAYS_OFF
    on_turn_on:
      - mqtt.publish:
          topic: /sensors/nodemcu-09/ota_mode
          payload: "RED"

  - platform: gpio
    id: led_green
    name: "led_green"
    pin:
      number: D5
      mode: OUTPUT
    restore_mode: ALWAYS_OFF
    on_turn_on:
      - mqtt.publish:
          topic: /sensors/nodemcu-09/ota_mode
          payload: "GREEN"

interval:

  - <<: !include common/version-interval.yaml

  - <<: !include common/whatami.yaml

<<: !include common/external-heapmon.yaml

sensor:

  - <<: !include common/wifi2.yaml

  - <<: !include common/uptime.yaml

  - platform: ultrasonic
    id: ultra2
    trigger_pin: 4
    echo_pin: 5
    name: "Ultrasonic Sensor"
    update_interval: 1s
    pulse_time: 5us
    filters:
      - delta: 0.10
      - filter_out: nan
      - lambda: 'return x * 100.0;'  # Converts reading to centimeters
    on_value_range:
      - below: 50  # If the distance is below 1 meter
        then:
          - switch.turn_on: led_red
          - switch.turn_off: led_blue
          - switch.turn_off: led_green
      - above: 100  # If the distance is above 1 meter
        then:
          - switch.turn_on: led_blue
          - switch.turn_off: led_red
          - switch.turn_off: led_green
      - above: 120  # Above 1.2 meters
        then:
          - switch.turn_on: led_green
          - switch.turn_off: led_blue
          - switch.turn_off: led_red

text_sensor:

  - <<: !include common/version.yaml