Adding iotawatt problem

I couldn’t let this go so I’ve been fiddling with influxdb and creating sensors from my iotawatt export.

I’ve set up my iotawatt to publish to influxDB with the following tags:

device	$device	(uniquely identifies this device)
entity_id	$name	
unit	$units

Then I read latest value in HomeAssistant as a rest sensor:

sensor:
  - platform: rest
    name: IoTaWatt
    resource: 'http://192.168.1.2:8086/query?db=iotawatt&q=SELECT%20last(value)%20FROM%20Watts%20WHERE%20time%20>%20NOW()-10m%20GROUP%20BY%20entity_id'
    value_template: 'OK'
    json_attributes:
      - results

This creates a sensor with all the states in the results attribute. To check that everything worked go to http://hassio.local/developer-tools/template and paste:

{% for row in state_attr("sensor.iotawatt", "results")[0]["series"] -%}
{{ row["tags"]["entity_id"] }} {{ row["values"][0][1] | float }}
{% endfor -%}

In my setup it generates this:

Bathroom 231.41
Bedroom_1 0.0
Bedroom_2 0.01
Dishwasher 0.0
Fridge 23.23
Inverter 328.49
Kitchen 66.41
Living_room 138.22
Total 838.77
VVB 0.0
Washer 51.01

To generate yaml configuration paste the code below in the template editor:

 sensor:
  - platform: template
    sensors:
{%- for row in state_attr("sensor.iotawatt", "results")[0]["series"] %}
      iotawatt_input_{{ row['tags']['entity_id'].lower() }}:
        value_template: '
{{- '{% for row in state_attr("sensor.iotawatt", "results")[0]["series"] -%}' }} 
{{- '{{% if row["tags"]["entity_id"] == "{}" -%}}'.format(row['tags']['entity_id']) }}
{{- '{{ row["values"][0][1] | float }}{% endif -%}{% endfor -%}' }}'
        unit_of_measurement: W
        device_class: power
        friendly_name_template: '{{ row["tags"]["entity_id"].replace("_", " ") }}'
{%- endfor %}

In my setup I get this:

sensor:
  - platform: template
    sensors:
      iotawatt_input_bathroom:
        value_template: '{% for row in state_attr("sensor.iotawatt", "results")[0]["series"] -%}{% if row["tags"]["entity_id"] == "Bathroom" -%}{{ row["values"][0][1] | float }}{% endif -%}{% endfor -%}'
        unit_of_measurement: W
        device_class: power
        friendly_name: 'Bathroom'
      iotawatt_input_bedroom_1:
        value_template: '{% for row in state_attr("sensor.iotawatt", "results")[0]["series"] -%}{% if row["tags"]["entity_id"] == "Bedroom_1" -%}{{ row["values"][0][1] | float }}{% endif -%}{% endfor -%}'
        unit_of_measurement: W
        device_class: power
        friendly_name: 'Bedroom 1'

The for row in .. is there as I don’t trust InfluxDB to always return the same order.

Good luck! ::slight_smile: