# Filename: irrigation_unlimited_adjustment.yaml
#
# This file is a package and should be located in the config/packages
# folder. If you do not have a packages folder then create it and add
# the following to configuration.yaml
#
# homeassistant:
#  packages: !include_dir_named packages
#
# More information on packages can be found at https://www.home-assistant.io/docs/configuration/packages
#
# Set up some observation sensors.
# This uses the Home-Assistant-wundergroundpws https://github.com/cytech/Home-Assistant-wundergroundpws integration.
# Rain information (wupws_preciptotal) is a daily accumulation total. So we want to grab the
# data just before midnight to get the daily total. We shouldn't be too eager to look after midnight
# because the reset from WU may take a few minutes to come through, currently 10 min. Increase this
# if data is unreliable.
# Note: Requires the ha-average integration to be installed https://github.com/Limych/ha-average

sensor:
  - platform: average
    name: irrigation_unlimited_rain_0
    entities:
      - sensor.wupws_preciptotal
    precision: 1
    start: "{{ now().replace(hour=0).replace(minute=30).replace(second=0) }}"
    end: "{{ now() }}"
    scan_interval: 600

  - platform: average
    name: irrigation_unlimited_rain_1
    entities:
      - sensor.wupws_preciptotal
    precision: 1
    start: "{{ now().replace(hour=0).replace(minute=30).replace(second=0) - timedelta(days=1) }}"
    end: "{{ now().replace(hour=23).replace(minute=59).replace(second=0) - timedelta(days=1) }}"
    scan_interval: 600

  - platform: average
    name: irrigation_unlimited_rain_2
    entities:
      - sensor.wupws_preciptotal
    precision: 1
    start: "{{ now().replace(hour=0).replace(minute=30).replace(second=0) - timedelta(days=2) }}"
    end: "{{ now().replace(hour=23).replace(minute=59).replace(second=0) - timedelta(days=2) }}"
    scan_interval: 600

  - platform: average
    name: irrigation_unlimited_rain_3
    entities:
      - sensor.wupws_preciptotal
    precision: 1
    start: "{{ now().replace(hour=0).replace(minute=30).replace(second=0) - timedelta(days=3) }}"
    end: "{{ now().replace(hour=23).replace(minute=59).replace(second=0) - timedelta(days=3) }}"
    scan_interval: 600

  - platform: average
    name: irrigation_unlimited_rain_4
    entities:
      - sensor.wupws_preciptotal
    precision: 1
    start: "{{ now().replace(hour=0).replace(minute=30).replace(second=0) - timedelta(days=4) }}"
    end: "{{ now().replace(hour=23).replace(minute=59).replace(second=0) - timedelta(days=4) }}"
    scan_interval: 600

  - platform: average
    name: irrigation_unlimited_temperature_0
    entities:
      - sensor.wupws_temp
    precision: 1
    start: "{{ now().replace(hour=0).replace(minute=30).replace(second=0) }}"
    end: "{{ now() }}"
    scan_interval: 600

  - platform: average
    name: irrigation_unlimited_temperature_1
    entities:
      - sensor.wupws_temp
    precision: 1
    start: "{{ now().replace(hour=0).replace(minute=30).replace(second=0) - timedelta(days=1) }}"
    end: "{{ now().replace(hour=23).replace(minute=59).replace(second=0) - timedelta(days=1) }}"
    scan_interval: 600

  - platform: average
    name: irrigation_unlimited_temperature_2
    entities:
      - sensor.wupws_temp
    precision: 1
    start: "{{ now().replace(hour=0).replace(minute=30).replace(second=0) - timedelta(days=2) }}"
    end: "{{ now().replace(hour=23).replace(minute=59).replace(second=0) - timedelta(days=2) }}"
    scan_interval: 600

  - platform: average
    name: irrigation_unlimited_temperature_3
    entities:
      - sensor.wupws_temp
    precision: 1
    start: "{{ now().replace(hour=0).replace(minute=30).replace(second=0) - timedelta(days=3) }}"
    end: "{{ now().replace(hour=23).replace(minute=59).replace(second=0) - timedelta(days=3) }}"
    scan_interval: 600

  - platform: average
    name: irrigation_unlimited_temperature_4
    entities:
      - sensor.wupws_temp
    precision: 1
    start: "{{ now().replace(hour=0).replace(minute=30).replace(second=0) - timedelta(days=4) }}"
    end: "{{ now().replace(hour=23).replace(minute=59).replace(second=0) - timedelta(days=4) }}"
    scan_interval: 600

  - platform: average
    name: irrigation_unlimited_temperature_5_day_moving_average
    entities:
      - sensor.wupws_temp
    precision: 1
    start: "{{ now().replace(hour=0).replace(minute=30).replace(second=0) - timedelta(days=4) }}"
    end: "{{ now() }}"
    scan_interval: 600

  # Five day weighted rain total sensor.
  # Adjust the weight values (0.7, 0.3, 0.15, 0.05) to suit your needs (0.0 = ignore that day).
  - platform: template
    sensors:
      irrigation_unlimited_rain_weighted_total:
        friendly_name: "Irrigation Unlimited Rain Weighted Total"
        unit_of_measurement: "mm"
        icon_template: "mdi:umbrella"
        value_template: >
          {% set r0 = state_attr('sensor.irrigation_unlimited_rain_0','max_value') | float(-1) %}
          {% set r1 = state_attr('sensor.irrigation_unlimited_rain_1','max_value') | float(-1) %}
          {% set r2 = state_attr('sensor.irrigation_unlimited_rain_2','max_value') | float(-1) %}
          {% set r3 = state_attr('sensor.irrigation_unlimited_rain_3','max_value') | float(-1) %}
          {% set r4 = state_attr('sensor.irrigation_unlimited_rain_4','max_value') | float(-1) %}
          {% if r0 != -1 and r1 != -1 and r2 != -1 and r3 != - 1 and r4 != -1 %}
            {% set rain_total = r0 %}
            {% set rain_total = rain_total + r1 * 0.7 %}
            {% set rain_total = rain_total + r2 * 0.3 %}
            {% set rain_total = rain_total + r3 * 0.15 %}
            {% set rain_total = rain_total + r4 * 0.05 %}
            {{ rain_total | round(1) }}
          {% else %}
            {{ -1 }}
          {% endif %}
    scan_interval: 600

# Automation to adjust the run times for Irrigation Unlimited.
# It uses the 5 day weighted rain total and the moving 5 day average temperature sensors
# created above to generate a variation.
# Adjust rain_total_threshold, rain_rate_threshold and temperature_threshold variables to suit you needs.
automation:
  - id: 'IU1653340123453'
    alias: Irrigation Unlimited Adjustment
    trigger:
      # -------------------------------------------------------------------
      # Choose how you want to trigger this automation.
      # Comment out/delete/change as required.
      # -------------------------------------------------------------------
      # Run at a fixed time
      - platform: time
        at: "02:00"
      # Run when Home Assistant starts
      - platform: homeassistant
        event: start
      # Run when the sensors update. Don't use this option if any of your
      # schedules use the 'anchor: finish'. It will most likely cause the
      # system to skip. Use a fixed time.
      - platform: state
        entity_id:
          - sensor.irrigation_unlimited_rain_weighted_total
          - sensor.irrigation_unlimited_temperature_5_day_moving_average
          - sensor.wupws_preciprate
    condition:
      condition: and
      conditions:
        - "{{ states('sensor.irrigation_unlimited_rain_weighted_total') | float(-1) != -1 }}"
        - "{{ states('sensor.wupws_preciprate') | float(-1) != -1 }}"
        - "{{ states('sensor.irrigation_unlimited_temperature_5_day_moving_average') | float(-273) != -273 }}"
    action:
      service: irrigation_unlimited.adjust_time
      data:
        # -------------------------------------------------------------------
        # Please see documentation regarding the adjust_time service call.
        # Choose an option below. Comment out/delete/change as needed.
        # *** This will NOT work as is. ***
        # 1. Adjust a single zone. Change the zone as required
        # entity_id: binary_sensor.irrigation_unlimited_c1_z1
        # 2. Adjust a sequence. Change the sequence_id as required
        # entity_id: binary_sensor.irrigation_unlimited_c1_m
        # sequence_id: 1
        # -------------------------------------------------------------------
        percentage: >
          {# Threshold variables #}
          {% set rain_total_threshold = 3.5 %}
          {% set rain_rate_threshold = 1.0 %}
          {% set temperature_threshold = 20.0 %}

          {# Sensor data #}
          {% set rain_total = states('sensor.irrigation_unlimited_rain_weighted_total') | float(-1) %}
          {% set rain_rate = states('sensor.wupws_preciprate') | float(-1) %}
          {% set temperature_average = states('sensor.irrigation_unlimited_temperature_5_day_moving_average') | float(-273) %}

          {# Threshold variables #}
          {% set rain_multiplier = (1 - (rain_total / rain_total_threshold)) %}
          {% set temperature_multiplier = temperature_average / temperature_threshold %}

          {% set multiplier = 1.0 %}
          {% if rain_rate < rain_rate_threshold and rain_multiplier > 0 and rain_total < rain_total_threshold %}
            {% set multiplier = multiplier * temperature_multiplier %}
            {% set multiplier = multiplier * rain_multiplier %}
          {% else %}
            {% set multiplier = 0.0 %} {# It's raining or enough already #}
          {% endif %}

          {# Return multiplier as a percentage #}
          {{ (multiplier * 100) | round(0) }}
