How to create two sensors for last changed for a lock sensor which have two values

I’ve tried to search but can’t find a working solution. I have a Yale Doorman lock. It has the states ‘locked’ and ‘unlocked’. I would like to create two sensors:
lock_time_locked - last time it was locked
lock_time_unlocked - last time it was unlocked

lock_time_locked:
        friendly_name: "Locked at"
        value_template: >
          {%- if states.lock.dorr.state == 'locked' -%}
            {{ as_timestamp(now()) }}
          {%- else -%}
            {{ states.sensor.lock_time_locked.state }}
          {%- endif -%}

I’ve tried to base it on the state change but I want to be able to save when it was locked even if it changes to unlocked. I get into an indefinit loop which just keeps updating and filling my DB. Can anyone please give me a direction how to achieve this?

I would also like to save the attribute “changed_by” somehow which disapeares when the door is locked again.

You’re half way there:

lock_time_locked:
  friendly_name: "Locked at"
  value_template: >
    {%- if states.lock.dorr.state == 'locked' -%}
      {{ as_timestamp(now()) }}
    {%- else -%}
      {{ states('sensor.lock_time_locked') }}
    {%- endif -%}

lock_time_unlocked:
  friendly_name: "Unlocked at"
  value_template: >
    {%- if states('lock.dorr') == 'unlocked' -%}
      {{ as_timestamp(now()) }}
    {%- else -%}
      {{ states('sensor.lock_time_unlocked') }}
    {%- endif -%}

I don’t understand this bit though:

Just tried what you created and that’s what I see as well. I watched the timestamp continuously update itself.

How about an automation, triggered by the lock’s state-changes, that writes the timestamp to an input-text?

If you want the automation to write to a sensor, you’ll have to used a small python_script to do that. Alternately, if you’re already using MQTT, you can publish the timestamp to the topic of an MQTT Sensor.


EDIT

I just tested the MQTT suggestion and it works.

Sensor

  - platform: mqtt
    name: Door Locked
    state_topic: sensor/door/locked

  - platform: mqtt
    name: Door Unlocked
    state_topic: sensor/door/unlocked

Automation

- alias: 'Record lock timestamp'
  trigger:
    platform: state
    entity_id: lock.door_lock
  action:
    service: mqtt.publish
    data_template:
      topic: "sensor/door/{{trigger.to_state.state}}"
      payload: "{{now().timestamp()}}"

Screenshot from 2020-09-16 11-31-29

Thank you both for your input!
Yes I get into this indefinate loop just updating. I was also thinking about an automation but didn’t know how to connect that to a sensor.
I was hoping there was a simpler way to store a value. I don’t use MQTT so far. Do you suggest me to go the python or the MQTT way. Which will be the easiest? Do you have an example of either?

Grand! You’re fast! I’ll try your example. Need to read upon mqtt it seems. I guess I need to enable that somehow or will only the above work for me?

Home Assistant doesn’t have a service to set a sensor’s state. To circumvent this limitation, someone create a python_script called set_state.py that allows you to set a state (or an attribute).

To use it, you will first have to install the python_script integration.

Yes, you must install an MQTT Broker and the MQTT integration (otherwise the example I provided will fail to work). If you are using Home Assistant OS or Home Assistant Supervised, the MQTT Broker is available as an Add-on. After it’s installed and configured, then you can install the MQTT integration.

Alternately, you can use the python_script solution which is simpler to install and configure.

I have Home Assistant installed on a Mac mini so the add-on won’t work but I think I’ll have a look at that anyway since the integration in the automations seems much cleaner and might have benefits in the future. Guess I can find a guide to a mqtt broker somewhere.

Hi Taras,
managed to install Mosquitto and think I got it to work. I did this with brew on mac os. This upgraded my python version from 3.7 to 3.8. When I try start homeassistant now with command “hass” i get the following error and my integration to IKEA tradfri does not longer work. Can you or someone help me out here. I guess it’s some kind of missing dependency but I can’t figure it out:

2020-09-17 00:30:10 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry 192.168.1.203 for tradfri
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/homeassistant/config_entries.py", line 222, in async_setup
    result = await component.async_setup_entry(  # type: ignore
  File "/usr/local/lib/python3.8/site-packages/homeassistant/components/tradfri/__init__.py", line 115, in async_setup_entry
    gateway_info = await api(gateway.get_gateway_info())
  File "/Users/Emil/.homeassistant/deps/lib/python/site-packages/pytradfri/api/aiocoap_api.py", line 155, in request
    result = await self._execute(api_commands)
  File "/Users/Emil/.homeassistant/deps/lib/python/site-packages/pytradfri/api/aiocoap_api.py", line 146, in _execute
    _, res = await self._get_response(msg)
  File "/Users/Emil/.homeassistant/deps/lib/python/site-packages/pytradfri/api/aiocoap_api.py", line 95, in _get_response
    r = await pr.response
  File "/Users/Emil/.homeassistant/deps/lib/python/site-packages/aiocoap/protocol.py", line 816, in _run_outer
    yield from cls._run(app_request, response, weak_observation, protocol, log, exchange_monitor_factory)
  File "/Users/Emil/.homeassistant/deps/lib/python/site-packages/aiocoap/protocol.py", line 865, in _run
    blockresponse = yield from blockrequest.response
  File "/Users/Emil/.homeassistant/deps/lib/python/site-packages/aiocoap/protocol.py", line 695, in _init_phase2
    yield from self.protocol.fill_remote(self.app_request)
  File "/Users/Emil/.homeassistant/deps/lib/python/site-packages/aiocoap/protocol.py", line 426, in fill_remote
    raise RuntimeError("No transport could route message")
RuntimeError: No transport could route message

That is so far off from the original question that it merits its own topic.

True. Thank you for your help. Will continue to try when I get HA to work again.
I’m kind of new to the concept of forums. Should I remove my last question which was out of topic or how does it work?

You can leave it here. The only reason I suggested you include it on another thread is because it’s more likely to be read and answered by someone (because this thread’s title has nothing to do with it).

Afterwards, you can return here and report if you were successful with my proposed solution.

Thanks @123 , I now managed to set up and configure MQTT on my mac, integrate it to Homeassistant and tried the automation and sensors you described. The automation triggers which I can see in the logs but the sensors does not update. Is there a good way I can debug what’s sent and what’s received if the sensor actutally receives. I guess I could have a second listerner somehow just to watch the message sent. I presume my problem is the sensor. They just show “unknown” all the time.

I understand that it should be possible from command line to listen to all messages by:

mosquitto_sub -h localhost -t '#' -u "username" -P "####"

Seems like my automation is triggering but does not see any messages.

The solution I posted was tested and confirmed to work. If your system is unable to receive payloads then you must confirm it is properly connected to the MQTT broker. Follow the instructions in this post to diagnose the connection:

After you have confirmed the connection is functional, double-check the spelling of all topics you have used.

Great! The integration worked fine, but the to listen within Home Assistant was great for debug. I listen to the topic # to see all and then I found the problem. For some reason it added a ‘/’ to the end, so after adding this to the sensor it worked like a charm.

state_topic: sensor/lock/time/locked/

It’s now time to actually make use of this, to send some notifications to my phone based on these sensors. Thanks again!

Glad to hear it works.

Please consider marking my post with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic has an accepted solution. It will also automatically place a link below your first post that leads to the solution post. All of this helps other users who may have a similar question to find answers.