Skip to content

Commit 208adf0

Browse files
authored
Merge pull request #128 from adafruit/anecdata-patch-2
UDP Client example (NTP)
2 parents 91f4eab + aca519f commit 208adf0

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

examples/esp32spi_udp_client.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# SPDX-FileCopyrightText: 2021 Adafruit Industries
2+
# SPDX-License-Identifier: MIT
3+
4+
import struct
5+
import time
6+
import board
7+
from digitalio import DigitalInOut
8+
from adafruit_esp32spi import adafruit_esp32spi
9+
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
10+
11+
# Get wifi details and more from a secrets.py file
12+
try:
13+
from secrets import secrets
14+
except ImportError:
15+
print("WiFi secrets are kept in secrets.py, please add them there!")
16+
raise
17+
18+
TIMEOUT = 5
19+
# edit host and port to match server
20+
HOST = "pool.ntp.org"
21+
PORT = 123
22+
NTP_TO_UNIX_EPOCH = 2208988800 # 1970-01-01 00:00:00
23+
24+
# PyPortal or similar; edit pins as needed
25+
spi = board.SPI()
26+
esp32_cs = DigitalInOut(board.ESP_CS)
27+
esp32_ready = DigitalInOut(board.ESP_BUSY)
28+
esp32_reset = DigitalInOut(board.ESP_RESET)
29+
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
30+
31+
# connect to wifi AP
32+
esp.connect(secrets)
33+
34+
# test for connectivity to server
35+
print("Server ping:", esp.ping(HOST), "ms")
36+
37+
# create the socket
38+
socket.set_interface(esp)
39+
socketaddr = socket.getaddrinfo(HOST, PORT)[0][4]
40+
s = socket.socket()
41+
42+
s.settimeout(TIMEOUT)
43+
44+
print("Sending")
45+
s.connect(socketaddr, conntype=esp.UDP_MODE)
46+
packet = bytearray(48)
47+
packet[0] = 0b00100011 # Not leap second, NTP version 4, Client mode
48+
s.send(packet, conntype=esp.UDP_MODE)
49+
50+
print("Receiving")
51+
packet = s.recv(48)
52+
seconds = struct.unpack_from("!I", packet, offset=len(packet) - 8)[0]
53+
print("Time:", time.localtime(seconds - NTP_TO_UNIX_EPOCH))

0 commit comments

Comments
 (0)