esphome:
  name: oil-tof # The unique name of your device. This is used for mDNS and in Home Assistant.
  area: Cottage # Assigns the device to the 'Cottage' area in Home Assistant.

substitutions:
  devicename: oil-tof # Defines a variable for the device name, making it easy to reuse.

# CONFIGURATION CHANGE FOR ESP32:
# To switch to ESP8266 from ESP32, replace the esp32 with the 'esp8266:' block
# esp8266:
#   board: nodemcuv2
#   type: arduino
esp32:
  board: esp32dev # Specifies the ESP32 development board. Common boards like `nodemcu-32s` or `esp32dev` work well.
  framework:
    type: arduino # The framework used to build the firmware. Arduino is the most common.

# Enable logging
logger: # Enables serial logging, which is essential for debugging.

# Enable Home Assistant API
api:
  encryption: 
    key: "FtKhT5Sf4cwe5bh/N0Kzy" # Enables the native API for communication with Home Assistant. The encryption key secures the communication.
#    password: NOT USED # This line is commented out, indicating the encryption key is used instead of a password.

ota:
  - platform: esphome # Enables Over-The-Air (OTA) updates. This allows you to upload new firmware wirelessly.
#   password: !secret ha_password  
    password: "" # Sets the OTA password. An empty password means no authentication is required for updates.

wifi:
  networks:
  - ssid: !secret wifi_ssid # Primary Wi-Fi network SSID, stored securely in secrets.yaml.
    password: !secret wifi_password # Primary Wi-Fi network password, stored securely.
  - ssid: !secret ee_ssid # Secondary Wi-Fi network SSID for fallback.
    password: !secret ee_password # Secondary Wi-Fi network password.

# Enable fallback hotspot (captive portal) in case wifi connection fails
  ap: {} # Enables an Access Point (AP) in case the device cannot connect to a configured Wi-Fi network.

captive_portal: # Enables a captive portal on the fallback AP, making it easier to reconfigure the device.
mdns:
  disabled: false # Enables mDNS (Multicast DNS), which allows the device to be discovered on your network by its hostname (e.g., `oil-tof.local`).

i2c:
  # CONFIGURATION CHANGE FOR ESP32:
  # The pin names for ESP32 are GPIO numbers, not D-pins like on the ESP8266.
  # The default pins for ESP32 are GPIO21 (SDA) and GPIO22 (SCL).
  # sda: D2 #GPI04 orange or green
  # scl: D1 #GPI05 yellow or blue
  sda: 21 # Pin for the I2C data line on the ESP32.
  scl: 22 # Pin for the I2C clock line on the ESP32.
  scan: true # Tells ESPHome to scan the I2C bus on startup and log any detected devices.

# sda (Optional, Pin): The pin for the data line of the IÂ²C bus. Defaults to the default of your board (usually GPIO21 for ESP32 and GPIO4 for ESP8266).
# scl (Optional, Pin): The pin for the clock line of the IÂ²C bus. Defaults to the default of your board (usually GPIO22 for ESP32 and GPIO5 for ESP8266).
# scan (Optional, boolean): If ESPHome should do a search of the IÂ²C address space on startup. Defaults to true.

sensor:
  # 1) The main oil level sensor. It returns a negative Liters value for graphing.
  - platform: vl53l0x
    name: "oil_level_tof" # The name that will appear in Home Assistant.
    address: 0x29 # The I2C address of the VL53L0X sensor.
    id: myoilliters # An internal ID to reference this sensor in other parts of the YAML.
    internal: false # This sensor will be exposed to Home Assistant.
    update_interval: 40s # The frequency at which the sensor takes new readings.
    long_range: false # Configures the sensor for short-range measurements.
    accuracy_decimals: 0 # Rounds the sensor value to a whole number.
    unit_of_measurement: "L" # The unit for the sensor value (Liters).
    state_class: measurement # Indicates this is a single point-in-time measurement.
    device_class: volume # Hints to Home Assistant that this is a volume sensor.
    filters:
      - quantile: # A filter that helps smooth out noisy data by selecting a specific percentile of recent values.
          window_size: 6 # The number of readings to consider in a window.
          send_every: 3 # Sends a new value every 3 readings.
          send_first_at: 3 # Sends the first value after 3 readings.
          quantile: 0.95 # Selects the 95th percentile, useful for ignoring low-value outliers (noise).
      - lambda: |- # A custom filter that performs a calculation.
          # The `x` variable is the incoming sensor value (distance in meters from the VL53L0X).
          float distance_mm = x * 1000; # Converts the distance from meters to millimeters.
          # We need to return a negative value that represents the oil level.
          # The calculation `(distance_mm - 34)` gives us a value relative to the top of the tank.
          # Multiplying by `-1` makes the value negative, so it decreases as oil is consumed.
          # You will need to add a scaling factor to this part of the lambda to get the correct Liters value.
          # Example: `return -(distance_mm - 34) * (1000.0 / 1000.0);`
          return -(distance_mm - 34) ; # Currently, this returns a value in millimeters, converted to negative.

# 2) The raw kWh combination/kalman sensor. It's external and provides a positive value that can still fluctuate.
  - platform: combination
    type: kalman # Applies a Kalman filter, which is excellent for smoothing noisy, time-series data.
    name: "oil kw-raw" # The name of the sensor in Home Assistant.
    id: myoilkwh_raw # Internal ID for this sensor.
    internal: false # Exposed to Home Assistant.
    accuracy_decimals: 0 # Rounds to a whole number.
    unit_of_measurement: "kWh" # The unit of measurement (Kilowatt-hours).
    state_class: measurement # A single measurement, not a total.
    device_class: energy # Hints to Home Assistant that this is an energy sensor.
    process_std_dev: 0.001 # A parameter for the Kalman filter.
    sources:
       - source: myoilliters # The input for this filter is the negative Liters sensor from above.
         error: 1 # A parameter for the Kalman filter.
    filters:
      - lambda: return (-x) * 10; # A custom filter that converts the negative Liters (`x`) into a positive kWh value. The `-x` makes the negative value positive, and `* 10` is your conversion factor.
      
# 3) The final kWh copy sensor for the Energy Dashboard. It uses a `max` filter to prevent the value from ever dropping.
  - platform: copy
    source_id: myoilkwh_raw # The input is the raw kWh sensor from the previous step.
    name: "oil_kalkw" # The final name for the Energy Dashboard.
    id: myoilkwh # Internal ID.
    internal: false # Exposed to Home Assistant.
    accuracy_decimals: 0 # Rounds to a whole number.
    unit_of_measurement: "kWh" # The unit.
    state_class: total_increasing # This is a critical setting for the Home Assistant Energy Dashboard. It tells HA that this value should only ever increase.
    device_class: energy # The device class.
    filters:
      - max: # A filter that only allows the sensor to report a value if it is greater than or equal to the highest value seen in a recent window.
          window_size: 10 # Looks at the last 10 readings.
      - skip_initial: 5 # Skips the first 5 readings to allow the sensor to stabilize before reporting.


# Other components
  - platform: wifi_signal
    id: wifis
    update_interval: 600s  
    name: ${devicename} wifi # A sensor that reports the Wi-Fi signal strength.
  

output:
  - platform: gpio
    pin: GPIO2 # Defines an output on GPIO pin 2.
    id: oil_2gpio # Internal ID, useful for controlling this pin from Home Assistant.

    
switch:
  - platform: restart
    name: ${devicename} restart # A switch in Home Assistant to restart the device remotely.    


text_sensor:
  - platform: wifi_info
    ip_address:
      name: ${devicename} ip # A text sensor that reports the device's IP address.
    ssid:
      name: ${devicename} ssid # A text sensor that reports the connected Wi-Fi network's SSID.
    mac_address:
      name: ${devicename} mac # A text sensor that reports the device's MAC address.
    scan_results:
      name: ${devicename} scan # A text sensor that reports a list of nearby Wi-Fi networks.