|
1 |
| -# SPDX-FileCopyrightText: 2019 Brent Rubell for Adafruit Industries |
| 1 | +# SPDX-FileCopyrightText: 2022 Scott Shawcroft for Adafruit Industries |
2 | 2 | #
|
3 | 3 | # SPDX-License-Identifier: MIT
|
4 | 4 |
|
|
8 | 8 |
|
9 | 9 | Network Time Protocol (NTP) helper for CircuitPython
|
10 | 10 |
|
11 |
| - * Author(s): Brent Rubell |
| 11 | + * Author(s): Scott Shawcroft |
12 | 12 |
|
13 | 13 | Implementation Notes
|
14 | 14 | --------------------
|
|
19 | 19 | https://github.com/adafruit/circuitpython/releases
|
20 | 20 |
|
21 | 21 | """
|
| 22 | +import struct |
22 | 23 | import time
|
23 |
| -import rtc |
24 |
| - |
25 |
| -try: |
26 |
| - # Used only for typing |
27 |
| - import typing # pylint: disable=unused-import |
28 |
| - from adafruit_esp32spi.adafruit_esp32spi import ESP_SPIcontrol |
29 |
| -except ImportError: |
30 |
| - pass |
31 | 24 |
|
32 | 25 | __version__ = "0.0.0-auto.0"
|
33 | 26 | __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_NTP.git"
|
34 | 27 |
|
| 28 | +NTP_TO_UNIX_EPOCH = 2208988800 # 1970-01-01 00:00:00 |
| 29 | + |
35 | 30 |
|
36 | 31 | class NTP:
|
37 | 32 | """Network Time Protocol (NTP) helper module for CircuitPython.
|
38 |
| - This module does not handle daylight savings or local time. |
39 |
| -
|
40 |
| - :param adafruit_esp32spi esp: ESP32SPI object. |
41 |
| - :param bool debug: Set to True to output set_time() failures to console |
| 33 | + This module does not handle daylight savings or local time. It simply requests |
| 34 | + UTC from a NTP server. |
42 | 35 | """
|
43 | 36 |
|
44 |
| - def __init__(self, esp: ESP_SPIcontrol, debug: bool = False) -> None: |
45 |
| - # Verify ESP32SPI module |
46 |
| - if "ESP_SPIcontrol" in str(type(esp)): |
47 |
| - self._esp = esp |
48 |
| - else: |
49 |
| - raise TypeError("Provided object is not an ESP_SPIcontrol object.") |
50 |
| - self.valid_time = False |
51 |
| - self.debug = debug |
| 37 | + def __init__( |
| 38 | + self, |
| 39 | + socketpool, |
| 40 | + *, |
| 41 | + server: str = "0.adafruit.pool.ntp.org", |
| 42 | + port: int = 123, |
| 43 | + tz_offset: int = 0, |
| 44 | + ) -> None: |
| 45 | + """ |
| 46 | + :param object socketpool: A socket provider such as CPython's `socket` module. |
| 47 | + :param str server: The domain of the ntp server to query. |
| 48 | + :param int port: The port of the ntp server to query. |
| 49 | + :param float tz_offset: Timezone offset in hours from UTC. Only useful for timezone ignorant |
| 50 | + CircuitPython. CPython will determine timezone automatically and adjust (so don't use |
| 51 | + this.) For example, Pacific daylight savings time is -7. |
| 52 | + """ |
| 53 | + self._pool = socketpool |
| 54 | + self._server = server |
| 55 | + self._port = port |
| 56 | + self._packet = bytearray(48) |
| 57 | + self._tz_offset = tz_offset * 60 * 60 |
52 | 58 |
|
53 |
| - def set_time(self, tz_offset: int = 0) -> None: |
54 |
| - """Fetches and sets the microcontroller's current time |
55 |
| - in seconds since since Jan 1, 1970. |
| 59 | + # This is our estimated start time for the monotonic clock. We adjust it based on the ntp |
| 60 | + # responses. |
| 61 | + self._monotonic_start = 0 |
56 | 62 |
|
57 |
| - :param int tz_offset: The offset of the local timezone, |
58 |
| - in seconds west of UTC (negative in most of Western Europe, |
59 |
| - positive in the US, zero in the UK). |
60 |
| - """ |
| 63 | + self.next_sync = 0 |
| 64 | + |
| 65 | + @property |
| 66 | + def datetime(self) -> time.struct_time: |
| 67 | + """Current time from NTP server.""" |
| 68 | + if time.monotonic_ns() > self.next_sync: |
| 69 | + self._packet[0] = 0b00100011 # Not leap second, NTP version 4, Client mode |
| 70 | + for i in range(1, len(self._packet)): |
| 71 | + self._packet[i] = 0 |
| 72 | + with self._pool.socket(self._pool.AF_INET, self._pool.SOCK_DGRAM) as sock: |
| 73 | + sock.sendto(self._packet, (self._server, self._port)) |
| 74 | + sock.recvfrom_into(self._packet) |
| 75 | + # Get the time in the context to minimize the difference between it and receiving |
| 76 | + # the packet. |
| 77 | + destination = time.monotonic_ns() |
| 78 | + poll = struct.unpack_from("!B", self._packet, offset=2)[0] |
| 79 | + self.next_sync = destination + (2**poll) * 1_000_000_000 |
| 80 | + seconds = struct.unpack_from( |
| 81 | + "!I", self._packet, offset=len(self._packet) - 8 |
| 82 | + )[0] |
| 83 | + self._monotonic_start = ( |
| 84 | + seconds |
| 85 | + + self._tz_offset |
| 86 | + - NTP_TO_UNIX_EPOCH |
| 87 | + - (destination // 1_000_000_000) |
| 88 | + ) |
61 | 89 |
|
62 |
| - try: |
63 |
| - now = self._esp.get_time() |
64 |
| - now = time.localtime(now[0] + tz_offset) |
65 |
| - rtc.RTC().datetime = now |
66 |
| - self.valid_time = True |
67 |
| - except ValueError as error: |
68 |
| - if self.debug: |
69 |
| - print(str(error)) |
70 |
| - return |
| 90 | + return time.localtime( |
| 91 | + time.monotonic_ns() // 1_000_000_000 + self._monotonic_start |
| 92 | + ) |
0 commit comments