Using a timestamp with fractional second in ESPHome

I am trying to sniff the serial traffic on an OBD connection. I would like to add a timestamp to the individual messages passing back and forth using the %f formatting string in the C++/Lambda strftime() function. Like so:

strftime(my_string, sizeof(my_string), "%H:%M:%f", localtime(&currTime));

Is this even possible? I note that the Time Component does not list the %f formatting directive! Is this a deliberate exclusion? And if it is possible somehow, what is the time resolution of ESPHome. I think I have seen somewhere it is in the 8mSec range.

Looking at this problem from the Home Assistant end, it seems to me that although my OBD TX/RX overs are all captured in the SQLite DB, the last_updated_ts only has a resolution of 1 second. So a whole conversation (20/30 overs) are all recorded with the same time stamp. Is this correct or am I looking at my data the wrong way?

Regards, M.

1 Like

Not quite an answer but:

There’s some more hints on sub-seconds here:

Maybe you could leverage uptime as a timestamp of sorts? Or at least to add an indentifier?

Probably you’d want to update it manually as part of your lambda somehow rather than update the sensor hyper frequently.

There’s some info on loop time here:

Thank you for your suggestions. Very helpful.
Working at this problem all day and (besides going round in circles!), I don’t think a formal timestamp is needed. I only need to know the sequence in which the RX/TX messages arrive. To this end, I am wondering (with some caveats on atomicity) if I could use a global variable, add it to my RX/TX messages and increment before next use?
This is my current (non-working) yaml:

globals:
  - id: my_ts
    type: int
    initial_value: '0' 
text_sensor:

  - platform: custom
    # See: https://esphome.io/cookbook/lambda_magic.html
    # File is: /homeassistant/esphome/uart_read_line_sensor.h
    lambda: |-
      auto my_custom_sensor = new UartReadLineSensor(id(myUART23));
      App.register_component(my_custom_sensor);
      return {my_custom_sensor};
    text_sensors:
      - id: "odb_tx"
        name: "OBD TX"
        filters:
          - lambda: |-
              id(my_ts) = (id(my_ts) + 1);
              return x + my_ts; //I think my_ts needs to cast to a string?

How do I change the variable my_ts so that I can concatenate with text_sensor?

Regards, M.

I had a similar thought actually.

You should be able to increment a global like this.

Building a string might be something like this.

There should be examples on the forums for both of those if you dig and hit the right keywords. Good to see your full and final solution when you’ve cracked it.