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
  queries:
    - 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() }}'
  duration:
    hours: 1
- platform: template
  sensors:
    second_to_last_state:
      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 %}
              N/A
            {% endif %}
          {% else %}
            N/A
          {% endif %}

And this one always returned N/A…

One was interesting, but never worked:

- platform: template
  sensors:
    previous_state:
     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?

Thanks.

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:

automation:
  - alias: Monitor Traffic in 1
    trigger:
      platform: state
      entity_id: sensor.snmp_wan1_in
    action:
      - service: input_number.set_value
        data_template:
          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:

automation:
  trigger:
    - 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!