Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion micropython/net/ntptime/manifest.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
metadata(description="NTP client.", version="0.2.2")
metadata(description="NTP client.", version="0.3.0")

module("ntptime.py", opt=3)
14 changes: 11 additions & 3 deletions micropython/net/ntptime/ntptime.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@
timeout = 1


class NTPError(OSError):
"""The NTP server returned an error or an invalid response."""


class UnsupportedEpochError(Exception):
"""The platform epoch is neither 1970 nor 2000."""


def time():
NTP_QUERY = bytearray(48)
NTP_QUERY[0] = 0x23
Expand All @@ -20,10 +28,10 @@ def time():
finally:
s.close()
if len(msg) < 48:
raise OSError(-1)
raise NTPError(-1)
val = struct.unpack("!I", msg[40:44])[0]
if not (msg[1] and val):
raise OSError(-1)
raise NTPError(-1)

# 2024-01-01 00:00:00 converted to an NTP timestamp
MIN_NTP_TIMESTAMP = 3913056000
Expand Down Expand Up @@ -58,7 +66,7 @@ def time():
# (date(1970, 1, 1) - date(1900, 1, 1)).days * 24*60*60
NTP_DELTA = 2208988800
else:
raise Exception("Unsupported epoch: {}".format(EPOCH_YEAR))
raise UnsupportedEpochError("Unsupported epoch: {}".format(EPOCH_YEAR))

return val - NTP_DELTA

Expand Down
32 changes: 32 additions & 0 deletions micropython/net/ntptime/test_ntptime.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,39 @@ def test_time_zero_ts_raises():
ntptime.socket = orig


def test_time_short_raises_ntp_error():
orig = _patch(b"short")
try:
try:
ntptime.time()
assert False, "expected NTPError"
except ntptime.NTPError as e:
assert isinstance(e, OSError)
assert e.args == (-1,)
finally:
ntptime.socket = orig


def test_unsupported_epoch_raises():
orig_socket = _patch(ntp_msg())
orig_gmtime = ntptime.gmtime
ntptime.gmtime = lambda t: (2010, 1, 1, 0, 0, 0, 0, 0)
try:
try:
ntptime.time()
assert False, "expected UnsupportedEpochError"
except ntptime.UnsupportedEpochError as e:
assert isinstance(e, Exception)
assert not isinstance(e, OSError)
assert "Unsupported epoch: 2010" in str(e)
finally:
ntptime.gmtime = orig_gmtime
ntptime.socket = orig_socket


test_time_ok()
test_time_short_raises()
test_time_kod_stratum_raises()
test_time_zero_ts_raises()
test_time_short_raises_ntp_error()
test_unsupported_epoch_raises()
Loading