# Template sensors Energy
- platform: template
  sensors:
    power_import:
      unique_id: shelly_power_import
      friendly_name: "Energy from grid"
      unit_of_measurement: 'W'
      device_class: power
      value_template: >-
        {% if states('sensor.shellypro3em_9867_phase_a_active_power') | is_number and
              states('sensor.shellypro3em_9867_phase_b_active_power') | is_number and
              states('sensor.shellypro3em_9867_phase_c_active_power') | is_number %}

          {% set phase_a = states('sensor.shellypro3em_9867_phase_a_active_power') | float(0) %}
          {% set phase_b = states('sensor.shellypro3em_9867_phase_b_active_power') | float(0) %}
          {% set phase_c = states('sensor.shellypro3em_9867_phase_c_active_power') | float(0) %}

          {% set import_a = phase_a if phase_a > 0 else 0 %}
          {% set import_b = phase_b if phase_b > 0 else 0 %}
          {% set import_c = phase_c if phase_c > 0 else 0 %}

          {{ (import_a + import_b + import_c) | round(2) }}
        {% else %}
          0
        {% endif %}
      availability_template: "{{ [states('sensor.shellypro3em_9867_phase_a_active_power'), states('sensor.shellypro3em_9867_phase_b_active_power'), states('sensor.shellypro3em_9867_phase_c_active_power')] | map('is_number') | min }}"

    power_export:
      unique_id: shelly_power_export
      friendly_name: "Energy to grid"
      unit_of_measurement: 'W'
      device_class: power
      value_template: >-
        {% if states('sensor.shellypro3em_9867_phase_a_active_power') | is_number and
              states('sensor.shellypro3em_9867_phase_b_active_power') | is_number and
              states('sensor.shellypro3em_9867_phase_c_active_power') | is_number %}

          {% set phase_a = states('sensor.shellypro3em_9867_phase_a_active_power') | float(0) %}
          {% set phase_b = states('sensor.shellypro3em_9867_phase_b_active_power') | float(0) %}
          {% set phase_c = states('sensor.shellypro3em_9867_phase_c_active_power') | float(0) %}

          {% set export_a = phase_a if phase_a < 0 else 0 %}
          {% set export_b = phase_b if phase_b < 0 else 0 %}
          {% set export_c = phase_c if phase_c < 0 else 0 %}

          {{ (export_a + export_b + export_c) | abs | round(2) }}

        {% else %}
          0
        {% endif %}
      availability_template: "{{ [states('sensor.shellypro3em_9867_phase_a_active_power'), states('sensor.shellypro3em_9867_phase_b_active_power'), states('sensor.shellypro3em_9867_phase_c_active_power')] | map('is_number') | min }}"

# Integration of sensors for energy
- platform: integration
  unique_id: energy_import_sum
  source: sensor.power_import
  name: "Total Energy from grid"
  unit_prefix: k
  round: 2
  method: left

- platform: integration
  unique_id: energy_export_sum
  source: sensor.power_export
  name: "Total Energy to grid"
  unit_prefix: k
  round: 2
  method: left
