I’m using an A2DP sensor to see how long my commutes are (phone connected to car = sensor is ‘on’).
I would like to push a notification to my phone telling me how long I’ve driven at the moment the A2DP sensor turns to ‘off’.
To be able to do so I would need to know the duration of the previous state (which is ‘on’). Things coming to mind is starting/stopping a timer, using input fields to store the timestamps , perhaps a statistics sensor?
But perhaps there is an easier way to grab this data as HA is already recording it and the History graph card can show it?
There are a few ways, but the History Stats integration is what comes to mind first. You may need to also use a Template sensor to focus what the History stats sensor counts.
Another option is to use an automation to store the timestamp values in a helper or variable.
This discussion is old, but instead of creating a new thread I think its better to continue here. It is possible to have a condition based on the duration of the previous state when the state change of the entity is the trigger of the automation. In my automation I use the state change of a light entity to trigger the automation under the condition it has been switched from off to on and back to off within 0.3s. Effectively using the light switch as a type of pulse switch.
trigger:
- platform: state
entity_id:
- light.buitenlamp_voordeur
to: "off"
The condition template is true when the previous state has last less than 0.3s:
- condition: template
value_template: >-
{{(now()|as_timestamp(0)-trigger.from_state.last_changed|as_timestamp(0))<0.3}}
alias: Previous state last for less than 0.3seconds