8000 net/ntptime/ntptime.py: Allow overriding default NTP host and timeout. · micropython/micropython-lib@bcff017 · GitHub
[go: up one dir, main page]

Skip to content

Commit bcff017

Browse files
committed
net/ntptime/ntptime.py: Allow overriding default NTP host and timeout.
* The default 1 second timeout is sometimes not enough depending on the host and network latencies. This patch adds keyword args to `time()` and `settime()` to allow overriding the default NTP host and timeout.
1 parent 0c5880d commit bcff017

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

micropython/net/ntptime/ntptime.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,19 @@
88
import ustruct as struct
99
except:
1010
import struct
11+
from micropython import const
1112

12-
# The NTP host can be configured at runtime by doing: ntptime.host = 'myhost.org'
13-
host = "pool.ntp.org"
13+
_DEFAULT_HOST = "pool.ntp.org"
14+
_DEFAULT_TIMEOUT = const(1.0)
1415

1516

16-
def time():
17+
def time(timeout=_DEFAULT_TIMEOUT, host=_DEFAULT_HOST):
1718
NTP_QUERY = bytearray(48)
1819
NTP_QUERY[0] = 0x1B
1920
addr = socket.getaddrinfo(host, 123)[0][-1]
2021
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
2122
try:
22-
s.settimeout(1)
23+
s.settimeout(timeout)
2324
res = s.sendto(NTP_QUERY, addr)
2425
msg = s.recv(48)
2526
finally:
@@ -40,8 +41,8 @@ def time():
4041

4142

4243
# There's currently no timezone support in MicroPython, and the RTC is set in UTC time.
43-
def settime():
44-
t = time()
44+
def settime(timeout=_DEFAULT_TIMEOUT, host=_DEFAULT_HOST):
45+
t = time(timeout, host)
4546
import machine
4647

4748
tm = utime.gmtime(t)

0 commit comments

Comments
 (0)
0