History_stats counts time in wrong state

I have created a helper called “body position” which tracks whether I am sitting, standing or laying down. Based on osha:s guidelines on prolonged sitting ( kProlonged (europa.eu)), I now want to get a notice related to their guideline “stand up for at least 10 min per 2 hours of sitting”.

So I created this sensor:

  - platform: history_stats
    name: Time standing since standing up
    entity_id: input_select.body_position
    state: "Standing"
    type: time
    start: "{{states.input_select.body_position.last_changed|as_timestamp}}"
    end: "{{now()}}"

But this does not work as expected. I want this sensor to count the time when I am standing but it reports 0 when standing. Instead it seems to count when another body position state is selected after Standing. So for example it starts to count when I sit down, which is completely not what I want.

(I will then create an automation that stores the timestamp as soon as the sensor above goes from 10+ minutes to 0. And a notification should be issued when body_position is “Sitting” and the current time is two hours passed the stored timestamp.)

You don’t need another sensor to trigger an automation to do this. Just use:

trigger:
  - platform: state
    entity_id: input_select.body_position
    to: "Standing"
    for:
      hours: 2
action:
  - service: etc...

Also please read this and format your post correctly next time: How to help us help you - or How to ask a good question

Thanks, but I still need a sensor. 10 minutes will be the required amount of standing, while 2 hours will be the accepted time without exercise. (If I sit for 1 hour, and stand up for 1 minute, the notification should be issued 59 minutes later. The one minute stand-up was not enough.) After the minimum 10 min standing, I also need to add a trigger to wait for state to change away from Standing. If not possible with history_stats, it seems like I will need two automations instead of one automation and one sensor.

# Automation 1 to set the start time for the 2-hour condition
trigger:
  - platform: state
    entity_id: input_select.body_position
    to: "Standing"
    for:
      minutes: 10
action:
  - wait_for_trigger:
      - platform: state
        entity_id:
          - input_select.body_position
        from: Standing
  - service: input_datetime.set_datetime
    metadata: {}
    data:
      timestamp: "{{now()|as_timestamp}}"
    target:
      entity_id: input_datetime.latest_10min_movement