glenn20 / micropython

MicroPython - a lean and efficient Python implementation for microcontrollers and constrained systems
https://micropython.org
Other
39 stars 9 forks source link

Mostly unusable timestamp in `peers_table` #14

Closed AmirHmZz closed 1 year ago

AmirHmZz commented 1 year ago

According to docs :

time_ms is the time the message was received (in milliseconds since system boot - wraps every 12 days).

In my project I update esp32 time with server using a mechanism similar to ntptime.settime(). But it seems timestamps of peers_table will use the old time (which is time since boot). MicroPython doesn't provide any APIs to access mp_hal_ticks_ms() so these timestamp would be useless when we have no other time to compare. I have two questions:

  1. Why saving time in ms? as long as it is a uint32_t so it can keep time in seconds.
  2. Why timestamps should be measured since boot? What about make it identical and comparable with time.time() ?
glenn20 commented 1 year ago

Good questions :-).

I use milliseconds as I envisaged there may be use cases for tracking RSSI with sub-second granularity (eg. tracking device movement), though I seriously doubt RSSI signal clarity would be sufficent to enable that. I also had an interest in using this as a timestamp for messages from devices with ms precision (without caring about RSSI values).

I use time since boot as that is most easily accessible from the C layers (esp. in the ISR context).

I will look into this further - I believe I found a mechanism for converting the timestamp in the python layer, but will check.

glenn20 commented 1 year ago

@AmirHmZz I use

import time

...
rssi, timestamp_ms = e.peers_table[peer]
ms_since_message = time.ticks_diff(time.ticks_ms(), timestamp_ms)

to calculate how many milliseconds "ago" the message we received. You could convert to a unix timestamp (in seconds) with (untested code fragment):

...
rssi, timestamp_ticks_ms = e.peers_table[peer]
now_ticks_ms, now_time = time.ticks_ms(), time.time()  # See https://docs.micropython.org/en/latest/library/time.html
ms_since_message = time.ticks_diff(now_ticks, timestamp_ms)
timestamp_time = now_time - ms_since_message / 1000

After that, timestamp_time will hold the time.time() value (in seconds) of the message timestamp.

glenn20 commented 1 year ago

Or - more computationally efficient:

import time, network, espnow
...

ts_offset = time.time() - time.ticks_ms() / 1000  # Offset between seconds since boot and unix time

for peer, msg in e.irecv():
    rssi, ts_ticks_ms = e.peers_table[peer]
    ts_time = ts_offset + ts_ticks_ms / 1000
    # Process message
    ...