# Loads default set of integrations. Do not remove.
default_config:

# Load frontend themes from the themes folder
frontend:
  themes: !include_dir_merge_named themes

# Text to speech
tts:
  - platform: google_translate

automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml

#Anleitung: https://book.cryd.de/books/projekte/page/hausverbrauch-strom-messen-incl-dummy-sensoren

utility_meter:
  daily_upload_volume:
    source: sensor.fritzbox_upload_volumen
    cycle: daily
  daily_download_volume:
    source: sensor.fritzbox_download_volumen
    cycle: daily
  taeglicher_stromverbrauch:
    source: sensor.stromzahler_energieverbrauch
    cycle: daily
  taegliche_einspeisung:
    source: sensor.stromzahler_energieeinspeisung
    cycle: daily

input_boolean:
  manual_trigger:
    name: Manual Trigger
    initial: off

influxdb:
  host: 127.0.0.1
  #host: a0d7b954-influxdb
  port: 8086
  database: homeassistant
  username: !secret influxdb_user
  password: !secret influxdb_pw
  max_retries: 3
  default_measurement: state

alexa:
  smart_home:
    endpoint: https://api.eu.amazonalexa.com/v3/events
    filter:
      include_entities:
        - light.living_room
        - switch.kitchen
    entity_config:
      light.living_room:
        name: "Wohnzimmer Licht"
      switch.kitchen:
        name: "Küchenschalter"
template:
  - sensor:
      - name: "Total Power3"
        unique_id: "total_power_sensor3"
        unit_of_measurement: "W"
        device_class: power
        state_class: measurement
        state: >
          {{ 
          states('sensor.shelly_em3_channel_a_power') | float(0) +
          states('sensor.shelly_em3_channel_b_power') | float(0) +
          states('sensor.shelly_em3_channel_c_power') | float(0)
          }}
      - name: "Prozent Nutzung"
        unique_id: "pv_prozent_nutzung"
        unit_of_measurement: "%"
        state: >
          {% set total_power = states('sensor.total_power_v2') | float(0) + states('sensor.solaranlage_power') | float(0) %}
          {% if total_power > 0 %}
            {{ (100 * states('sensor.solaranlage_power') | float(0) / total_power) | round(1) }}
          {% else %}
            0
          {% endif %}
      - name: "Total Energy Use1"
        unique_id: "total_energy_use1"
        device_class: energy
        state_class: total_increasing
        unit_of_measurement: "kWh"
        state: >
          {{
          states('sensor.shelly_em3_channel_a_energy') | float(0) +
          states('sensor.shelly_em3_channel_b_energy') | float(0) +
          states('sensor.shelly_em3_channel_c_energy') | float(0)
          }}
      - name: "Total Energy Returned1"
        unique_id: "total_energy_returned1"
        device_class: energy
        state_class: total_increasing
        unit_of_measurement: "kWh"
        state: >
          {{
          states('sensor.shelly_em3_channel_a_energy_returned') | float(0) +
          states('sensor.shelly_em3_channel_b_energy_returned') | float(0) +
          states('sensor.shelly_em3_channel_c_energy_returned') | float(0)
          }}
      - name: "Aktuelle Solarleistung1"
        unique_id: "aktuelle_solarleistung1"
        unit_of_measurement: "W"
        device_class: power
        state_class: measurement
        state: >
          {{
          max(0, states('sensor.esphome_web_39b3f0_charging_power_2') | float(0) -
          states('sensor.esphome_web_39b3f0_discharging_power_2') | float(0) +
          states('sensor.solaranlage_power') | float(0))
          }}
      - name: "Täglicher Stromverbrauch"
        unit_of_measurement: "kWh"
        state: >
          {% set aktueller_wert = states('sensor.stromzahler_energieverbrauch') | float %}
          {% set startwert = states('input_number.tagesstart_zaehlerstand') | float %}
          {{ (aktueller_wert - startwert) | round(2) }}
      - name: "Fritzbox Download Volumen"
        unit_of_measurement: "MB"
        state: >
          {% set rate_kbps = states('sensor.fritz_box_7530_download_durchsatz') | float %}
          {% set rate_kBps = rate_kbps / 8 %}  # Kilobits pro Sekunde in Kilobytes umrechnen
          {{ (rate_kBps * 60) / 1024 }}  # Datenvolumen pro Minute in Megabyte
      - name: "Fritzbox Upload Volumen"
        unit_of_measurement: "MB"
        state: >
          {% set rate_kbps = states('sensor.fritz_box_7530_upload_durchsatz') | float %}
          {% set rate_kBps = rate_kbps / 8 %}  # Kilobits pro Sekunde in Kilobytes umrechnen
          {{ (rate_kBps * 60) / 1024 }}  # Datenvolumen pro Minute in Megabyte
      - name: "Aktueller Strompreis"
        state: "{{ states('input_number.strompreis') }}"
        unit_of_measurement: "€/kWh"
        device_class: monetary
      - name: "Stromverbrauch Vortag"
        unique_id: "stromverbrauch_vortag"
        unit_of_measurement: "kWh"
        device_class: energy
        state: >
          {% set stats = state_attr('sensor.taeglicher_stromverbrauch', 'last_period') %}
          {{ stats | float(0) }}
      - name: "Einspeisung Vortag"
        unique_id: "einspeisung_vortag"
        unit_of_measurement: "kWh"
        device_class: energy
        state: >
          {% set stats = state_attr('sensor.taegliche_einspeisung', 'last_period') %}
          {{ stats | float(0) }}
      - name: "Generiert Vortag (Template)"
        unique_id: "generiert_vortag_template"
        unit_of_measurement: "kWh"
        device_class: energy
        state: >
          {% set stats = state_attr('sensor.komplett_solarlieferung', 'last_period') %}
          {{ stats | float(0) }}
      - name: "Nächste Müllabholung"
        state: >-
          {% set today = now().date().isoformat() %}
          {% for date in states.sensor.garbage.attributes.keys() | list | sort %}
            {% if date >= today %}
              {{ date }} - {{ states.sensor.garbage.attributes[date] }}
              {% break %}
            {% endif %}
          {% endfor %}
      - name: "Statistik Solarerzeugung Durchschnitt"
        state: "{{ now().year }}"
        attributes:
          data: >
            {{ states('sensor.gsheet_data') }}
      - name: "Solarertrag 2022"
        state: "OK"
        attributes:
          values: >
            {% set raw_data = state_attr('sensor.statistik_solarerzeugung_durchschnitt_mqtt', 'data')[1][1:] %}
            {{ raw_data | map('replace', ',', '.') | map('float') | list }}
      - name: "Solarertrag 2023"
        state: "OK"
        attributes:
          values: >
            {% set raw_data = state_attr('sensor.statistik_solarerzeugung_durchschnitt_mqtt', 'data')[2][1:] %}
            {{ raw_data | map('replace', ',', '.') | map('float') | list }}
      - name: "Solarertrag 2024"
        state: "OK"
        attributes:
          values: >
            {% set raw_data = state_attr('sensor.statistik_solarerzeugung_durchschnitt_mqtt', 'data')[3][1:] %}
            {{ raw_data | map('replace', ',', '.') | map('float') | list }}
      - name: "Solarertrag 2025"
        state: "OK"
        attributes:
          values: >
            {% set raw_data = state_attr('sensor.statistik_solarerzeugung_durchschnitt_mqtt', 'data')[4][1:] %}
            {{ raw_data | map('replace', ',', '.') | map('float') | list }}
      - name: "Solarertrag 2022 Werte"
        state: "{{ state_attr('sensor.solarertrag_2022', 'values')[-1] | float(0) }}"
        unit_of_measurement: "kWh" # Passen Sie die Einheit an
        state_class: measurement
        attributes:
          alle_werte: "{{ state_attr('sensor.solarertrag_2022', 'values') }}"

      - name: "Kühlschrank Letzte Aktivzeit"
        unique_id: kuehlschrank_letzte_aktivzeit
        unit_of_measurement: "min"
        state: >
          {% set aktiv_start = states.binary_sensor.kuehlschrank_laeuft.last_changed %}
          {% if is_state('binary_sensor.kuehlschrank_laeuft', 'on') %}
            {{ ((now() - aktiv_start).total_seconds() / 60) | round(1) }}
          {% else %}
            0
          {% endif %}

      - name: "Kühlschrank Letzte Pausezeit"
        unique_id: kuehlschrank_letzte_pausezeit
        unit_of_measurement: "min"
        state: >
          {% set pause_start = states.binary_sensor.kuehlschrank_laeuft.last_changed %}
          {% if is_state('binary_sensor.kuehlschrank_laeuft', 'off') %}
            {{ ((now() - pause_start).total_seconds() / 60) | round(1) }}
          {% else %}
            0
          {% endif %}
sensor:
  - platform: average
    name: "Durchschnittsverbrauch"
    unique_id: "durchschnitt_verbrauch"
    duration: 60
    entities:
      - sensor.total_power_v2

  - platform: average
    name: "Durchschnittsertrag"
    unique_id: "durchschnitt_ertrag"
    duration: 180
    entities:
      - sensor.aktuelle_solarleistung1

  - platform: teamtracker
    league_id: "BUND"
    team_id: "MUC"
    name: "Bayern2"

  - platform: integration
    name: Upload Volume
    source: sensor.fritz_box_7530_upload_durchsatz
    unit_prefix: k
    round: 2
  - platform: integration
    name: Download Volume
    source: sensor.fritz_box_7530_download_durchsatz
    unit_prefix: k
    round: 2
  - platform: statistics
    name: "Generiert Vortag (Statistik)"
    entity_id: sensor.solaranlage_energy
    state_characteristic: change
    max_age:
      days: 1
  - platform: rest
    name: "Google Sheets Daten"
    resource: "https://script.google.com/macros/s/AKfycbz4sAiMvufOqL-gv5o7YfjaL4V0eWu9dGren_xg6pV35dE8bMyzaQckKp5WCs6ex5bbdA/exec"
    scan_interval: 600 # Aktualisiert alle 10 Minuten
    value_template: "{{ value_json[0] }}" # Falls erforderlich, kann dies angepasst werden
    json_attributes:
      - "Gesamtwerte"
      - "Genergiert"
      - "Einspeisung"
      - "Netzverbrauch"
      - "Solarverbrauch"
      - "Gesamtverbrauch"
      - "Durchschnittl. Nutzung"
      - "Autarkiegrad"
      - "Ersparnis in € / Tag"
      - "Ersparnis gesamt"
      - "Prozent Abgezahlt"
      - "Gesamnt abgezahlt"
  - platform: history_stats
    name: "Kühlschrank Aktivzeit"
    entity_id: binary_sensor.kuehlschrank_laeuft
    state: "on"
    type: time
    start: "{{ now() - timedelta(hours=24) }}"
    end: "{{ now() }}"

  - platform: history_stats
    name: "Kühlschrank Pausezeit"
    entity_id: binary_sensor.kuehlschrank_laeuft
    state: "off"
    type: time
    start: "{{ now() - timedelta(hours=24) }}"
    end: "{{ now() }}"
  - platform: statistics
    name: "Kühlschrank Durchschnitt Aktivzeit"
    entity_id: sensor.kuehlschrank_letzte_aktivzeit
    state_characteristic: mean
    max_age:
      hours: 24
    sampling_size: 10

  - platform: statistics
    name: "Kühlschrank Durchschnitt Pausezeit"
    entity_id: sensor.kuehlschrank_letzte_pausezeit
    state_characteristic: mean
    max_age:
      hours: 24
    sampling_size: 10
    
input_datetime:
  kuehlschrank_ende_aktiv:
    name: "Ende aktive Phase"
    has_time: true
  kuehlschrank_ende_pause:
    name: "Ende Pause Phase"
    has_time: true

waste_collection_schedule:
  sources:
    - name: awido_de
      args:
        customer: Erding
        city: Oberding
        street: "Gartenstraße"

binary_sensor:
  - platform: template
    sensors:
      kuehlschrank_laeuft:
        friendly_name: "Kühlschrank läuft"
        value_template: "{{ states('sensor.kuehlschrank_power')|float > 50 }}"

mqtt:
  sensor:
    - name: "Balkonkraftwerk Leistung AC"
      state_topic: "inverter/hm600/ch0/P_AC"
      device_class: power
      unit_of_measurement: W
      state_class: measurement
      unique_id: "BalkonkraftwerkLeistungAC"
    - name: "Balkonkraftwerk Module 1 Leistung"
      state_topic: "inverter/hm600/ch1/P_DC"
      device_class: power
      unit_of_measurement: W
      state_class: measurement
      unique_id: "BalkonkraftwerkModule13Leistung"
    - name: "Balkonkraftwerk Module 2 Leistung"
      state_topic: "inverter/hm600/ch2/P_DC"
      device_class: power
      unit_of_measurement: W
      state_class: measurement
      unique_id: "BalkonkraftwerkModule24Leistung"
    - name: "Balkonkraftwerk Temperatur"
      state_topic: "inverter/hm600/ch0/Temp"
      device_class: temperature
      unit_of_measurement: °C
      state_class: measurement
      unique_id: "BalkonkraftwerkTemperatur"
    - name: "Balkonkraftwerk Arbeit Tag"
      state_topic: "inverter/hm600/ch0/YieldDay"
      device_class: energy
      unit_of_measurement: Wh
      state_class: total_increasing
      unique_id: "BalkonkraftwerkArbeitTag"
    - name: "Balkonkraftwerk Arbeit Gesamt"
      state_topic: "inverter/hm600/ch0/YieldTotal"
      device_class: energy
      unit_of_measurement: kWh
      state_class: total_increasing
      unique_id: "BalkonkraftwerkArbeitGesamt"
    - name: "version"
      state_topic: "inverter/version"
      unique_id: "version_dtu"
    - name: "Limit"
      state_topic: "inverter/hm600/ch0/active_PowerLimit"
      unique_id: "set_powerlimit"
    - name: "Energy Akkuentladung current"
      device_class: power
      unit_of_measurement: "W"
      state_topic: "esphome-web-39b3f0/sensor/esphome-web-39b3f0_discharging_power"
      unique_id: "energy_akkuentladung"
    - name: "Energy Akkuentladung total"
      device_class: energy
      unit_of_measurement: "kWh"
      state_topic: "esphome-web-39b3f0/sensor/esphome-web-39b3f0_discharging_power"
    - name: "Effizienz HM600"
      unit_of_measurement: "%"
      state_topic: "inverter/hm600/ch0/Efficiency"
      unique_id: "effizienz_hm600"
    - name: "HM600 Spannung"
      unit_of_measurement: "V"
      state_topic: "inverter/hm600/ch1/U_DC"
    - name: "Waschmaschine Leistung"
      state_topic: "shellyplus1pm-84cca8771670/status/switch:0"
      value_template: "{{ value_json.apower }}"
      unit_of_measurement: "W"
      device_class: power
    - name: "Waschmaschine Energieverbrauch"
      state_topic: "shellyplus1pm-84cca8771670/status/switch:0"
      value_template: "{{ value_json.aenergy.total }}"
      unit_of_measurement: "kWh"
      device_class: energy
    - name: "Statistik Solarerzeugung Durchschnitt mqtt"
      state_topic: "homeassistant/sensor/gsheet_data"
      value_template: "{{ value_json.state }}"
      json_attributes_topic: "homeassistant/sensor/gsheet_data"
      json_attributes_template: "{{ value_json.attributes | tojson }}"

logger:
  default: warning
  logs:
    custom_components.awtrix: warning
    homeassistant.components.sensor: warning

# Nächste Abholung Restmüll

#      - name: "Restmüll"
#        state: '{{value.types|join(", ")}}{% if value.daysTo == 0 %} Heute{% elif value.daysTo == 1 %} Morgen{% else %} in {{value.daysTo}} Tagen{% endif %}'
#        attributes:
#          value_template: '{{value.types|join(", ")}}'
#        unique_id: "restmuell"
#        unit_of_measurement: "days"
#        device_class: "timestamp"
#        value_template: '{{(states.sensor.waste_collection_schedule.attributes.next_date)|as_timestamp | timestamp_local}}'

# Nächste Abholung Biotonne

#      - name: "Biotonne"
#        state: '{{value.types|join(", ")}}{% if value.daysTo == 0 %} Heute{% elif value.daysTo == 1 %} Morgen{% else %} in {{value.daysTo}} Tagen{% endif %}'
#        attributes:
#          value_template: '{{value.types|join(", ")}}'
#        unique_id: "biotonne"
#        unit_of_measurement: "days"
#        device_class: "timestamp"
#        value_template: '{{(states.sensor.waste_collection_schedule.attributes.next_date)|as_timestamp | timestamp_local}}'

##sensor:
#  - platform: average
#    name: 'Durchschnittsverbrauch'
#    unique_id: 'durchschnitt_verbrauch'
#    duration: 60
#    entities:
#      - sensor.total_power
#  - platform: average
#    name: 'Durchschnittsertrag'
#    unique_id: 'durchschnitt_ertrag'
#    duration: 180
#    entities:
#      - sensor.aktuelle_solarleistung
#  - platform: teamtracker
#    league_id: "BUND"
#    team_id: "MUC"
#    name: "Bayern2"
#
#  - platform: template
#    name: "Total Power"
#    unique_id: "Total_Energy"
#    device_class: power
#    state_class: total
#    unit_of_measurement: "W"
#    value_template: >
#      {{
#      states('sensor.shelly_em3_channel_a_power')| float(0) +
#      states('sensor.shelly_em3_channel_b_power')| float(0) +
#      states('sensor.shelly_em3_channel_c_power')| float(0)
#      }}
#
#  - platform: template
#    name: "Total Energy Use1"
#    unique_id: "Total_Energy_Use1"
#    device_class: energy
#    state_class: total
#    unit_of_measurement: "kWh"
#    value_template: >
#      {{
#      states('sensor.shelly_em3_channel_a_energy')| float(0) +
#      states('sensor.shelly_em3_channel_b_energy')| float(0) +
#      states('sensor.shelly_em3_channel_c_energy')| float(0)
#      }}
#
#  - name: "Total Energy Returned1"
#    unique_id: "Total_Energy_Returned1"
#    device_class: energy
#    state_class: total
#    unit_of_measurement: "kWh"
#    value_template: >
#      {{
#      states('sensor.shelly_em3_channel_a_energy_returned')| float(0) +
#      states('sensor.shelly_em3_channel_b_energy_returned')| float(0) +
#      states('sensor.shelly_em3_channel_c_energy_returned')| float(0)
#      }}
#
#  - name: "PV Einspeisung"
#    unique_id: "pv_einspeisung"
#    unit_of_measurement: "W"
#    device_class: power
#    value_template: "{{ states('sensor.total_power')|float if states('sensor.total_power') | int < 1 else 0 }}"
#
#  - name: "PV Einspeisung negiert"
#    unique_id: "pv_einspeisung_negiert"
#    unit_of_measurement: "W"
#    device_class: power
#    value_template: "{{ states('sensor.pv_einspeisung')|float * -1 }}"
#
#  - name: "Wirkungsgrad"
#    unique_id: "wirkungsgrad_battery"
#    unit_of_measurement: "%"
#    device_class: power
#    value_template: >
#      {{(100 * states('sensor.solaranlage_power')| float(0) / states('sensor.esphome_web_39b3f0_discharging_power')| float(0)) | round(1) }}
#
#  - name: "Prozent_Nutzung"
#    unique_id: "pv_prozent_nutzung"
#    unit_of_measurement: "%"
#    device_class: power
#    value_template: >
#      {{
#      (100 * states('sensor.solaranlage_power')| float(0) / (states('sensor.solaranlage_power')| float(0) + states('sensor.total_power_v2')| float(0))) | round(1)
#      }}
#
#  - name: "Aktuelle_Solarleistung"
#    unique_id: "aktuelle-solarleistung"
#    unit_of_measurement: "W"
#    device_class: power
#    value_template: >
#      {{
#      max(0, states('sensor.esphome_web_39b3f0_charging_power_2')| float(0) -
#      states('sensor.esphome_web_39b3f0_discharging_power_2')| float(0) +
#      states('sensor.solaranlage_power')|float(0) +
#      }}
#
# //states('sensor.akku_power')|float(0)) removed from aktuelle solarleistung
#
#  - name: "Summierter Ertrag"
#    unique_id: "summierter_ertrag"
#    unit_of_measurement: "W"
#    device_class: power
#    value_template: >
#      {{
#      states('sensor.akku_power')| float(0) +
#      states('sensor.solaranlage_power')|float(0)
#      }}
#
#  - name: "Total Power"
#    unique_id: "Total_Energy"
#    device_class: power
#    state_class: total
#    unit_of_measurement: "W"
#    value_template: >
#      {{
#      states('sensor.shelly_em3_channel_a_power')| float(0) +
#      states('sensor.shelly_em3_channel_b_power')| float(0) +
#      states('sensor.shelly_em3_channel_c_power')| float(0)
#      }}
#
#  - name: "Total Energy Use"
#    unique_id: "Total_Energy_Use"
#    device_class: energy
#    state_class: total
#    unit_of_measurement: "kWh"
#    value_template: >
#      {{
#      states('sensor.shelly_em3_channel_a_energy')| float(0) +
#      states('sensor.shelly_em3_channel_b_energy')| float(0) +
#      states('sensor.shelly_em3_channel_c_energy')| float(0)
#      }}
#
#  - name: "Total Energy Returned"
#    unique_id: "Total_Energy_Returned"
#    device_class: energy
#    state_class: total
#    unit_of_measurement: "kWh"
#    value_template: >
#      {{
#      states('sensor.shelly_em3_channel_a_energy_returned')| float(0) +
#      states('sensor.shelly_em3_channel_b_energy_returned')| float(0) +
#      states('sensor.shelly_em3_channel_c_energy_returned')| float(0)
#      }}
#
#  - name: "PV Einspeisung"
#    unique_id: "pv_einspeisung"
#    unit_of_measurement: "W"
#    device_class: power
#    value_template: "{{ states('sensor.total_power')|float if states('sensor.total_power') | int < 1 else 0 }}"
#
#  - name: "PV Einspeisung negiert"
#    unique_id: "pv_einspeisung_negiert"
#    unit_of_measurement: "W"
#    device_class: power
#    value_template: "{{ states('sensor.pv_einspeisung')|float * -1 }}"
#
#  - name: "Wirkungsgrad"
#    unique_id: "wirkungsgrad_battery"
#    unit_of_measurement: "%"
#    device_class: power
#    value_template: >
#      {{(100 * states('sensor.solaranlage_power')| float(0) / states('sensor.esphome_web_39b3f0_discharging_power')| float(0)) | round(1) }}###
#
#  - name: "Prozent_Nutzung"
#    unique_id: "pv_prozent_nutzung"
#    unit_of_measurement: "%"
#    device_class: power
#    value_template: >
#      {{
#      (100 * states('sensor.solaranlage_power')| float(0) / (states('sensor.solaranlage_power')| float(0) + states('sensor.total_power')| float(0))) | round(1)
#      }}
#
#  - name: "Aktuelle_Solarleistung"
#    unique_id: "aktuelle-solarleistung"
#    unit_of_measurement: "W"
#    device_class: power
#    value_template: >
#      {{
#      max(0, states('sensor.esphome_web_39b3f0_charging_power_2')| float(0) -
#      states('sensor.esphome_web_39b3f0_discharging_power_2')| float(0) +
#      states('sensor.solaranlage_power')|float(0) +
#      states('sensor.akku_power')|float(0))
#      }}
#
#  - name: "Summierter Ertrag"
#    unique_id: "summierter_ertrag"
#    unit_of_measurement: "W"
#    device_class: power
#    value_template: >
#      {{
#      states('sensor.akku_power')| float(0) +
#      states('sensor.solaranlage_power')|float(0)
#      }}

# https://community.home-assistant.io/t/hoymiles-dtu-microinverters-pv/253674/21

# statistics
#- platform: statistics
#  entity_id: sensor.total_power_av
#  sampling_size: 20

#powercalc:

#sensor:
#   - platform: powercalc
#     entity_id: light.esslicht
#     fixed:
#      states_power:
#       off: 0.4
#       on: 22

# platform: template
#   daily_solar_percent:
#    value_template: "{{ ( 100 * states('sensor.total_power')|float / states('sensor.solaranlage_power')|float )|round(1) }}"
#    unit_of_measurement: '%'
#    friendly_name: Daily Solar Percentage

# ssl Configuration
# http:
#  ssl_certificate: /ssl/fullchain.pem
#  ssl_key: /ssl/privkey.pem

http:
  use_x_forwarded_for: true
  trusted_proxies:
    - 127.0.0.1
    - 192.168.178.6
    - 172.16.0.0/12
    - ::1
  #ssl_certificate: "/ssl/fullchain.pem"
  #ssl_key: "/ssl/privkey.pem"
homeassistant:
  external_url: "https://floke-ha.duckdns.org"
