How to get second to last state of a sensor that holds strings?

Hi guys.

I am trying to write automation that sends notification to my phone and email when entity state changes. What I did not anticipate after I did that is, that during the day the device that the entity is associated with looses connection and reports “Disconnected” state. After a minute or even les it goes back to previous state, for instance, “Connected”.

Since this happens a lot I get spammed by my own code :slight_smile: What I was trying to do is to check state of the entity before current state. So, if currently it is reporting “Connected”, I would like to check if the state before this was “Disconnected” and in that case I would ignore the change.

I see the history for this sensor in the UI when clicking on it without any problems but I just can’t seem to write code to get its previous state in automation.

I’ve tried different aproaches with no success:

  • sensor that executes quers
- platform: sql
    - name: scond_to_last_state"
      query: >
        SELECT state
        FROM states
        WHERE entity_id = 'sensor.charger_status_description'
        ORDER BY state_id DESC
        LIMIT 1 OFFSET 1

This one always returned unknown.

Than i tried this:

- platform: history_stats
  name: previous_state
  entity_id: sensor.charger_status_description
  state: "all"
  type: time
  end: '{{ now() }}'
    hours: 1
- platform: template
      friendly_name: "Second-to-Last State"
      value_template: >-
          {% set history_data = state_attr('sensor.previous_state', 'history') %}
          {% if history_data is not none %}
            {% if history_data | length > 1 %}
              {% set second_to_last_state = history_data[-2].state %}
              {{ second_to_last_state }}
            {% else %}
            {% endif %}
          {% else %}
          {% endif %}

And this one always returned N/A…

One was interesting, but never worked:

- platform: template
     friendly_name: "Previous State"
     value_template: >-
      {% set history = states.history -%}
      {% set states = history[states('sensor.charger_status_description')] -%}
      {% set prev_state = states[:-1][-1] if states|length > 1 else None -%}
      {{ prev_state.state if prev_state is not none else 'N/A' }}

This next one was returning error but in the error I could see that it was reading previous states as the error contained such string:

[homeassistant.components.template.template_entity] TemplateError('TemplateError: Invalid entity ID 'history.Locked, device connected'')

Any other suggestions as to how I could get previous state recorded by my sensor?


Perhaps you can use in template for previous state trigger.from_state.state? Here is sample pf how it could be used for bandwith calculation from SNMP sensor:

  - alias: Monitor Traffic in 1
      platform: state
      entity_id: sensor.snmp_wan1_in
      - service: input_number.set_value
          entity_id: input_number.internet_traffic_delta_in1
          value: "{{ ((trigger.to_state.state | int - trigger.from_state.state | int) * 8 ) / ( as_timestamp(trigger.to_state.last_updated) - as_timestamp(trigger.from_state.last_updated) ) }}"
1 Like

Or if you just want to ignore if previous state is Disconnected you could use:

    - platform: state
      entity_id: sensor.charger_status_description
      not_from: "Disconnected"
1 Like

Thank you both. I tried what Mark suggested and it seems to be what I want and is cleaner :slight_smile: I still find it strange that it hard to, say, list all states in a sensor. But this will do nicely. Thanks again!