MQTT Sensor : how to define last_reset_value_template

Yes, I understand that particular approach works for the simple reason that it complies with the intended purpose of last_reset_topic.

My comment was targeted at the other approach you appear to have attempted in the past where you hard-coded the Unix Epoch into last_reset_value_template. The assumption is you did that to avoid having to explicitly publish that value. However, it fails because the template is not evaluated until a payload (any payload) is received via last_reset_topic.

correct. I did try that, because Frenck insisted ‘it’ should work. He didnt however say we need the last_rest_topic first…
Ive asked in Discord #devs_energy now, so hope we can get confirmation our conclusion is in fact correct :wink:

It sort of does:

Defines a template to extract the last_reset.

It’s also more specific than the description for plain old value_template

Defines a template to extract the value

That’s why I was puzzled by the lack of the last_reset_topic option in the first post. The combination of topic and corresponding value_template is fairly common (json_attributes_topic and json_attributes_template) so seeing last_reset_value_template used alone seemed anomalous to me.

with that knowledge Frencks answer makes sense now. At the time of that post, some of us were in the effort trying to make that stand alone template work, not thinking past our own mind lock…

Seems correct. I noticed how zigbee2mqtt sends it’s discovery messages :

{
  "availability": [
    {
      "topic": "zigbee2mqtt/bridge/state"
    }
  ],
  "device": {
    "identifiers": [
      "zigbee2mqtt_0x04cf8cdf3c77ea45"
    ],
    "manufacturer": "Xiaomi",
    "model": "Mi power plug ZigBee EU (ZNCZ04LM)",
    "name": "mi_outlet",
    "sw_version": "Zigbee2MQTT 1.21.0"
  },
  "device_class": "energy",
  "json_attributes_topic": "zigbee2mqtt/mi_outlet",
  "last_reset_topic": "zigbee2mqtt/mi_outlet",
  "last_reset_value_template": "1970-01-01T00:00:00+00:00",
  "name": "mi_outlet_energy",
  "state_class": "measurement",
  "state_topic": "zigbee2mqtt/mi_outlet",
  "unique_id": "0x04cf8cdf3c77ea45_energy_zigbee2mqtt",
  "unit_of_measurement": "kWh",
  "value_template": "{{ value_json.energy }}"
}

Clever!

It uses the same topic for state_topic, json_attributes_topic, and last_reset_topic.

Because state_topic will regularly receive payloads, it will cause last_reset_value_template to be evaluated the moment a payload is received via the shared topic.

The actual content of the payload is irrelevant for last_reset_value_template because it doesn’t use it and is hard-coded with the Unix Epoch.

Applying this simple principle to Marius’ example, we get this:

  - platform: mqtt
    state_topic: 'macaddress/energy-solar-sdm630-modbus/f339a2fb/import'
    name: ZP Import
    unit_of_measurement: kWh
    value_template: >
        {{value|round(2)}}
    last_reset_topic: 'macaddress/energy-solar-sdm630-modbus/f339a2fb/import'
    last_reset_value_template: '1970-01-01T00:00:00+00:00'
    device_class: energy
    state_class: measurement

Your MQTT Sensor becomes this:

  - platform: mqtt
    name: "Mains Consumed Energy"
    state_topic: "electricity1/tele/RESULT"
    value_template: >- 
      {% set message = value_json.SerialReceived %}
      {% set payload = message[6:14] %}
      {% set payload_len = (payload | length) %}
      {% set result = namespace(value='') %}
      
      {% for i in range(0, payload_len + 1) | reverse -%}
        {%- if i is divisibleby 2 -%}
          {%- set result.value = result.value + payload[i:i+2] -%}
        {%- endif -%}
      {%- endfor -%}
      
      {{ (result.value|float) / 100 }}
    unit_of_measurement: 'kWh'
    unique_id: "mains_consumed_energy"    
    device_class: energy
    state_class: measurement
    last_reset_topic: 'electricity1/tele/RESULT'
    last_reset_value_template: '1970-01-01T00:00:00+00:00'

EDIT

Correction. Removed superfluous trailing parentheses in first example.

2 Likes

Yes, no more customization !

My ZMAI90’s like this

  - platform: mqtt
    name: "Mains Consumed Energy"
    state_topic: "electricity1/tele/RESULT"
    value_template: >- 
      {% set message = value_json.SerialReceived %}
      {% set payload = message[6:14] %}
      {% set payload_len = (payload | length) %}
      {% set result = namespace(value='') %}
      
      {% for i in range(0, payload_len + 1) | reverse -%}
        {%- if i is divisibleby 2 -%}
          {%- set result.value = result.value + payload[i:i+2] -%}
        {%- endif -%}
      {%- endfor -%}
      
      {{ (result.value|float) / 100 }}
    unit_of_measurement: 'kWh'
    unique_id: "mains_consumed_energy"    
    device_class: energy
    state_class: measurement
    last_reset_topic: 'electricity1/tele/RESULT'
    last_reset_value_template: '1970-01-01T00:00:00+00:00'

and my global consumption like this :

template:
  - sensor:
      - name: "House electricity energy"
        unit_of_measurement: 'kWh'
        state: >
          {{ (states("sensor.mains_consumed_energy") | float + states("sensor.upstairs_consumed_energy") | float) + (states("sensor.extra_consumed_energy") | float)  | round(2) }}       
        device_class: energy
        state_class: measurement      
        attributes:         
           last_reset: '1970-01-01T00:00:00+00:00'

1 Like

handt thought about that, mostly because I havent rebuilt my ‘legacy’ template sensors to the new template: integration yet. probably could have used

attribute_templates:
  last_reset: '1970-01-01T00:00:00+00:00'

but just didnt think of that. also because state_class: measurement isn’t supported on those legacy template sensors.

however, and this is HUGE news, with 2021.8.2 we can now use the template: in packages, and that is enough reason to spend the rest of my holidays rebuilding the template sensors in my config :wink:

so, good new all around!

I’m very new to MQTT and frankly almost all of this has gone entirely over my head…

I’m installing a Shelly EM tomorrow and was hoping to use it with MQTT (this was my plan before 2021.8 so it’s a really well timed update for me)!

Not a damn clue how to set it all up… why are there two sensors and more importantly are they both template sensors or what? I get the MQTT sensor but what the heck is the bit that Taras named ZP Import?

I only once find ZP Import on this page, and it is an example from marius using yaml anchors. You can ignore it.

The important message from this whole topic is: if you want to use your mqtt sensor in the energy tab, it needs at least 4 extra items :

    device_class: energy
    state_class: measurement
    last_reset_topic: 'electricity1/tele/RESULT'
    last_reset_value_template: '1970-01-01T00:00:00+00:00'

device_class, state_class, last_reset_value_template: always as shown
last_reset_topic: set it to your state topic

2 Likes

Like francisp explained, that’s in the example posted by Mariusthvdb. When I posted a revised version of his example, I purposely excluded the YAML anchor to simplify it and avoid confusion. :slightly_smiling_face:

A YAML anchor let’s you duplicate a section of YAML elsewhere simply by referring to it by name. I provided an example for someone else in this thread.

1 Like

Tanks but for me it needs to be without a uppercase letter

sensor.*_energy:

I also have my power and engery readings via mqtt. But I couldn’t add these lines using VSCode as an editor. Well, I could! But it complaints.

    state_class: measurement
    last_reset_topic: 'electricity1/tele/RESULT'
    last_reset_value_template: '1970-01-01T00:00:00+00:00'

Because it keeps complaining that “Property state_class is not allowed”. Same complaints for the other two lines of YAML.

Does anyone know a solution for this annoyance?

The complaint comes from VS Code Config Helper. It works with VS Code to identify potential errors in your YAML code. It probably hasn’t been updated yet so it falsely identifies those two options as being “not allowed”.

The next update will probably correct it.

I know this is an older thread but I am really struggling with getting this to work.

I have a ZooZ z-wave power strip. The MQTT topic for power monitoring returns this json:

{
    "value_id": "6-50-1-0",
    "node_id": 6,
    "class_id": 50,
    "type": "decimal",
    "genre": "user",
    "instance": 1,
    "index": 0,
    "label": "Instance 1: Electric - kWh",
    "units": "kWh",
    "help": "",
    "read_only": true,
    "write_only": false,
    "min": 0,
    "max": 0,
    "is_polled": false,
    "value": 111.02,
    "lastUpdate": 1651274701101
}

I believe the ‘lastUpdate’ element is what should be used for the last_reset_value_template:

Here’s what my Yaml Looks like:

 ### Power Monitoring ###
  - platform: mqtt
    name: Office_Power_Strip_Total_kwh
    state_topic: "zwave2mqtt/6/50/1/0"
    value_template: "{{value_json.value}}"
    last_reset_topic: "zwave2mqtt/6/50/1/0"
    last_reset_value_template: "{{value_json.lastUpdate}}"
    unit_of_measurement: "kWh"
    device_class: energy
    state_class: measurement

But for the life of me, I cannot get this last reset value to populate.

Does anyone have any ideas on what i’m doing wrong?

That does not seem a date.

Its an epoch / unix timestamp.

try this:

 last_reset_value_template: "{{value_json.lastUpdate | int | timestamp_custom('%d.%m.%Y %H:%M'}}"

still nothing… (Had to put a close “)” on that to make it work)… I’ve even tried hardcoding the date in the right format but never got HA to recognize it.

I know this topic is old and you may know why this happened now but for anyone arriving here as I did I believe it’s because of the state_class being set to measurement in your case.

I used the state_class: total and the value I put in to last_reset_value_template is then populated.