switchdoclabs / RTC_SDL_DS3231

Raspberry Pi Python Library for the Real Time Clock DS3231
29 stars 29 forks source link

Possible bugs in SDL_DS3231.py #2

Open james-prior opened 7 years ago

james-prior commented 7 years ago

There might be bugs in SDL_DS3231.py.

SDL_DS3231.read_datetime() reads the date and time one byte at a time. Imagine the situation where it is just before something rolls over, such as just before midnight. For example, 2017-05-22 23:59:59. One reads the year, month, and date before midnight, then the clock rolls over to the next day then one reads the hours, minutes, and seconds. That is, one reads 2017-05-22 00:00:00, giving the illusion that time went backwards almost a day. Then one calls .read_datetime() again soon and gets 2017-05-23 00:00:00.

However, if one does a multibyte read from the chip, starting at address 0, and reads all the time/date stuff in one multibyte read, then one would get either 2017-05-22 23:59:59 or 2017-05-23 00:00:00, never some unholy mix. Unfortunately SDL_DS3231.py does not do that. Furthermore, the library it is based on, smbus, seems to come from https://pypi.python.org/pypi.smbus-cffi/0.5.1, which states in part:

Note of caution for Raspberry Pi users: when calling read_block_data ...
the underlying i2/smbus library/driver causes a kernel panic on the
Raspberry Pi.

SDL_DS3231.read_all() and SDL_DS3231.read_str() likely suffer the same fate as SDL_DS3231.read_datetime().

Ideally, one would rewrite the affected functions to use multi-byte reads and use an I2C library that supports multi-byte reads on Raspberry Pis.

A work around for continuing to use single byte reads, would be read the whole date and time until it got the same result twice in a row.