adafruit / Adafruit_CircuitPython_MiniMQTT

MQTT Client Library for CircuitPython
Other
72 stars 50 forks source link

get_monotonic_time doesn't preserve resolution #209

Open kevin-tritz opened 3 months ago

kevin-tritz commented 3 months ago

The library tries to use monotonic_ns when available to preserve timing resolution. However, monotonic_ns only preserves resolution when kept as an int. When used in a floating operation, such as dividing by 1000000000 in get_monotonic_time, it experiences the same loss of precision as the original monotonic() function.

This results in timeout errors due to loss of precision when timeouts are low and uptime is long. I've seen false timeout errors for 10-20ms timeouts after a few hours, and false timeout errors for 0.1s timeouts after a few days.

I hacked in a fix using ticks_diff and ticks_ms from adafruit_ticks, and presumably you could also make the fix by taking the difference of nanosecond integers, and dividing that result.

so this doesn't work: time2_ns/1000000000 - time1_ns/1000000000 > timeout_s

but this should: (time2_ns - time1_ns)/1000000000 > timeout_s

I should note this is for the RP2040 chip in the W5500_EVB_PICO board.