esphome:
  name: smartmeter

esp8266:
  board: d1_mini

# Enable logging
logger:
  hardware_uart: UART0_SWAP

# Enable Home Assistant API
api:
  encryption:
    key: "nc/DDxg2mjIDat3SJd/7otH9KBA7te/egr9X8pGi1Io="

ota:
  password: "37b5b12ce4c3bc1184eb6872a85b48d6"

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

  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "Smartmeter Fallback Hotspot"
    password: "UzI1eDQxpFcP"

globals:
  - id: total_pulses
    type: int
    restore_value: false
    initial_value: '0'

captive_portal:
  
# SML Example configuration entry
uart:
  id: uart_bus
  rx_pin: GPIO3
  baud_rate: 9600
  data_bits: 8
  parity: NONE
  stop_bits: 1
  
# This is mainly here because the internal_filter of the pulse_counter on ESP8266
# can only be set to a maximum of 13us, which is way too low. The Reedswitch
# sometimes rapidly switches from ON to OFF, causing a lot of "ghost" pulses.
# The delayed_on filter will make sure that the sensor stayed ON for at least
# 100ms before increasing the counter.
binary_sensor:
  - platform: gpio
    id: internal_pulse_counter
    pin: GPIO16
    filters:
      - invert:
      - delayed_on: 100ms
    on_press:
      then:
        - lambda: id(total_pulses) += 1;

sml:
  id: mysml
  uart_id: uart_bus

sensor:
  - platform: sml
    name: "Total energy"
    sml_id: mysml
    server_id: "0a01445a4700039f12bd"
    obis_code: "1-0:1.8.0"
    unit_of_measurement: kWh
    accuracy_decimals: 1
    device_class: energy
    state_class: total_increasing
    filters:
      - multiply: 0.0001
      - heartbeat: 10s 
  
  - platform: sml
    name: "Power"
    sml_id: mysml
    server_id: "0a01445a4700039f12bd"
    obis_code: "1-0:16.7.0"
    unit_of_measurement: W
    accuracy_decimals: 1
    device_class: energy
    filters:
      - multiply: 0.01
      - heartbeat: 10s

  - platform: template
    name: "Gas used"
    device_class: gas
    unit_of_measurement: "m³"
    state_class: total_increasing
    icon: "mdi:fire"
    accuracy_decimals: 1
    lambda: |-
        return id(total_pulses) * 0.1;
  
text_sensor:
  - platform: sml
    name: "Total energy text"
    sml_id: mysml
    server_id: "0a01445a4700039f12bd"
    obis_code: "1-0:1.8.0"
    format: uint
    
  - platform: sml
    name: "Power text"
    sml_id: mysml
    server_id: "0a01445a4700039f12bd"
    obis_code: "1-0:16.7.0"
    format: uint
    
time:
  - platform: homeassistant
    on_time:
      - seconds: 0
        minutes: 0
        hours: 4
        days_of_week: MON-SUN
        then:
           - switch.toggle: restart_switch

switch:
  - platform: restart
    name: "Auto Restart"
    id: restart_switch