← index #7137Issue #604
Related · high · value 4.315
QUERY · ISSUE

ntptime.py settime() does not cope with errors

openby peterhinchopened 2021-04-20updated 2022-07-31

This arose in the forum.

If an exception occurs in the time() function, msg is not updated so a value of -NTP_DELTA is returned. If this is the intended mechanism for reporting exceptions, settime() should check for this and avoid updating the RTC.

Or perhaps the finally clause in time() should re-raise the exception?

CANDIDATE · ISSUE

ntptime: Does not handle KoD (Kiss of Death) resonse.

openby peterhinchopened 2023-02-01updated 2023-06-01

A call to .time() can return a large negative number which results in a rather confusing exception in .settime(). This can occur if an application issues NTP requests too frequently: see this post. I suspect there may also be other circumstances in which an NTP query returns zero.

Another problem reported in discussions is that .time() frequently times out. Clearly the timeout must be short, but this implies that on many networks timeouts will be common.

There are a number of simple fixes. One is for .time() to return an error value in either of these cases which is tested by .settime(). The latter could return a bool indicating success or failure.

2 comments
massimosala · 2023-06-01

Hi Peter

I dislike the ntptime module, I think it is like "how to confuse a cat" !

Probably a lot of users get KoD because they don't realize that ntptime.time() isn't time.time() ...

I wrote my version, with more strict checking about the servers reponse.

Feel free to read and use it.
Ah, you have to remove the compatibility module and the gc_collect()
The compatibility is just to use this module also on windows / linux, defining const

Eventually I can donate it to mp ecosystem.

ntptime2.py.txt

massimosala · 2023-06-01

I see now I use a variable MICRO in settime()

Just replace the code with:

	try :
		from machine import RTC
		RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))
	except :
		print("Unsupported platform, no RTC")

and the printf() with print()

Ciao

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied