Skip to content

Commit 36b69cc

Browse files
authored
Merge pull request #12 from ladyada/master
change settings to secrets, add a localtime example, internally set 4K as max socket packet size
2 parents 08c1726 + a0a711e commit 36b69cc

8 files changed

+88
-26
lines changed

adafruit_esp32spi/adafruit_esp32spi.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -410,10 +410,10 @@ def is_connected(self):
410410
self.reset()
411411
return False
412412

413-
def connect(self, settings):
414-
"""Connect to an access point using a settings dictionary
413+
def connect(self, secrets):
414+
"""Connect to an access point using a secrets dictionary
415415
that contains a 'ssid' and 'password' entry"""
416-
self.connect_AP(settings['ssid'], settings['password'])
416+
self.connect_AP(secrets['ssid'], secrets['password'])
417417

418418
def connect_AP(self, ssid, password): # pylint: disable=invalid-name
419419
"""Connect to an access point with given name and password.

adafruit_esp32spi/adafruit_esp32spi_socket.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ def set_interface(iface):
4343
SOCK_STREAM = const(1)
4444
AF_INET = const(2)
4545

46+
MAX_PACKET = const(4000)
47+
4648
# pylint: disable=too-many-arguments, unused-argument
4749
def getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0):
4850
"""Given a hostname and a port name, return a 'socket.getaddrinfo'
@@ -85,7 +87,7 @@ def readline(self):
8587
#print("Socket readline")
8688
while b'\r\n' not in self._buffer:
8789
# there's no line already in there, read some more
88-
avail = min(_the_interface.socket_available(self._socknum), 4000)
90+
avail = min(_the_interface.socket_available(self._socknum), MAX_PACKET)
8991
if avail:
9092
self._buffer += _the_interface.socket_read(self._socknum, avail)
9193
firstline, self._buffer = self._buffer.split(b'\r\n', 1)
@@ -98,7 +100,7 @@ def read(self, size=0):
98100
#print("Socket read", size)
99101
if size == 0: # read as much as we can at the moment
100102
while True:
101-
avail = min(_the_interface.socket_available(self._socknum), 4000)
103+
avail = min(_the_interface.socket_available(self._socknum), MAX_PACKET)
102104
if avail:
103105
self._buffer += _the_interface.socket_read(self._socknum, avail)
104106
else:
@@ -114,7 +116,7 @@ def read(self, size=0):
114116
received = []
115117
while to_read > 0:
116118
#print("Bytes to read:", to_read)
117-
avail = min(_the_interface.socket_available(self._socknum), 4000)
119+
avail = min(_the_interface.socket_available(self._socknum), MAX_PACKET)
118120
if avail:
119121
stamp = time.monotonic()
120122
recv = _the_interface.socket_read(self._socknum, min(to_read, avail))
@@ -137,8 +139,7 @@ def read(self, size=0):
137139
return ret
138140

139141
def settimeout(self, value):
140-
"""Set the receiving timeout, in seconds. If set to zero, we
141-
fully block until data is ready"""
142+
"""Set the read timeout for sockets, if value is 0 it will block"""
142143
self._timeout = value
143144

144145
def close(self):

adafruit_esp32spi/adafruit_esp32spi_wifimanager.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,19 +39,19 @@ class ESPSPI_WiFiManager:
3939
"""
4040
A class to help manage the Wifi connection
4141
"""
42-
def __init__(self, esp, settings, status_neopixel=None, attempts=2):
42+
def __init__(self, esp, secrets, status_neopixel=None, attempts=2):
4343
"""
4444
:param ESP_SPIcontrol esp: The ESP object we are using
45-
:param dict settings: The WiFi and Adafruit IO Settings (See examples)
45+
:param dict secrets: The WiFi and Adafruit IO secrets dict (See examples)
4646
:param int attempts: (Optional) Failed attempts before resetting the ESP32 (default=2)
4747
:param status_neopixel: (Optional) The neopixel pin - Usually board.NEOPIXEL (default=None)
4848
:type status_neopixel: Pin
4949
"""
5050
# Read the settings
5151
self._esp = esp
5252
self.debug = False
53-
self.ssid = settings['ssid']
54-
self.password = settings['password']
53+
self.ssid = secrets['ssid']
54+
self.password = secrets['password']
5555
self.attempts = attempts
5656
requests.set_interface(self._esp)
5757
if status_neopixel:

examples/esp32spi_aio_post.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,30 +8,32 @@
88

99
print("ESP32 SPI webclient test")
1010

11-
# Get wifi details and more from a settings.py file
11+
# Get wifi details and more from a secrets.py file
1212
try:
13-
from esp32spi_settings import settings
13+
from secrets import secrets
1414
except ImportError:
15-
print("WiFi settings are kept in esp32spi_settings.py, please add them there!")
15+
print("WiFi secrets are kept in secrets.py, please add them there!")
1616
raise
1717

1818
esp32_cs = DigitalInOut(board.D9)
1919
esp32_ready = DigitalInOut(board.D10)
2020
esp32_reset = DigitalInOut(board.D5)
2121
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
2222
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
23-
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, settings, board.NEOPIXEL)
23+
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, board.NEOPIXEL)
2424

2525
counter = 0
26+
2627
while True:
2728
try:
2829
print("Posting data...", end='')
2930
data = counter
3031
feed = 'test'
3132
payload = {'value':data}
3233
response = wifi.post(
33-
"https://io.adafruit.com/api/v2/"+settings['aio_username']+"/feeds/"+feed+"/data",
34-
json=payload,headers={bytes("X-AIO-KEY","utf-8"):bytes(settings['aio_key'],"utf-8")})
34+
"https://io.adafruit.com/api/v2/"+secrets['aio_username']+"/feeds/"+feed+"/data",
35+
json=payload,
36+
headers={bytes("X-AIO-KEY", "utf-8"):bytes(secrets['aio_key'], "utf-8")})
3537
print(response.json())
3638
response.close()
3739
counter = counter + 1

examples/esp32spi_cheerlights.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,11 @@
99
import neopixel
1010
import adafruit_fancyled.adafruit_fancyled as fancy
1111

12-
# Get wifi details and more from a settings.py file
12+
# Get wifi details and more from a secrets.py file
1313
try:
14-
from esp32spi_settings import settings
14+
from secrets import secrets
1515
except ImportError:
16-
print("WiFi settings are kept in esp32spi_settings.py, please add them there!")
16+
print("WiFi secrets are kept in secrets.py, please add them there!")
1717
raise
1818

1919
print("ESP32 SPI webclient test")
@@ -26,7 +26,7 @@
2626
esp32_reset = DigitalInOut(board.D5)
2727
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
2828
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
29-
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, settings, board.NEOPIXEL)
29+
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, board.NEOPIXEL)
3030

3131
# neopixels
3232
pixels = neopixel.NeoPixel(board.A1, 16, brightness=0.3)
@@ -40,7 +40,7 @@
4040
print("Fetching json from", DATA_SOURCE)
4141
response = wifi.get(DATA_SOURCE)
4242
print(response.json())
43-
value=response.json()
43+
value = response.json()
4444
for key in DATA_LOCATION:
4545
value = value[key]
4646
print(value)
@@ -53,7 +53,7 @@
5353
if not value:
5454
continue
5555
if last_value != value:
56-
color = int(value[1:],16)
56+
color = int(value[1:], 16)
5757
red = color >> 16 & 0xFF
5858
green = color >> 8 & 0xFF
5959
blue = color& 0xFF

examples/esp32spi_localtime.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import time
2+
import board
3+
import busio
4+
from digitalio import DigitalInOut
5+
from adafruit_esp32spi import adafruit_esp32spi
6+
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
7+
import rtc
8+
9+
# Get wifi details and more from a secrets.py file
10+
try:
11+
from secrets import secrets
12+
except ImportError:
13+
print("WiFi secrets are kept in secrets.py, please add them there!")
14+
raise
15+
16+
print("ESP32 local time")
17+
18+
TIME_API = "http://worldtimeapi.org/api/ip"
19+
20+
esp32_cs = DigitalInOut(board.ESP_CS)
21+
esp32_ready = DigitalInOut(board.ESP_BUSY)
22+
esp32_reset = DigitalInOut(board.ESP_RESET)
23+
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
24+
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
25+
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, board.NEOPIXEL)
26+
27+
the_rtc = rtc.RTC()
28+
29+
response = None
30+
while True:
31+
try:
32+
print("Fetching json from", TIME_API)
33+
response = wifi.get(TIME_API)
34+
break
35+
except (ValueError, RuntimeError) as e:
36+
print("Failed to get data, retrying\n", e)
37+
continue
38+
39+
json = response.json()
40+
current_time = json['datetime']
41+
the_date, the_time = current_time.split('T')
42+
year, month, mday = [int(x) for x in the_date.split('-')]
43+
the_time = the_time.split('.')[0]
44+
hours, minutes, seconds = [int(x) for x in the_time.split(':')]
45+
46+
# We can also fill in these extra nice things
47+
year_day = json['day_of_year']
48+
week_day = json['day_of_week']
49+
is_dst = json['dst']
50+
51+
now = time.struct_time((year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst))
52+
print(now)
53+
the_rtc.datetime = now
54+
55+
while True:
56+
print(time.localtime())
57+
time.sleep(1)

examples/esp32spi_settings.py renamed to examples/esp32spi_secrets.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# This file is where you keep secret settings, passwords, and tokens!
22
# If you put them in the code you risk committing that info or sharing it
33

4-
settings = {
4+
secrets = {
55
'ssid' : 'yourssid',
66
'password' : 'yourpassword',
77
'timezone' : -5, # this is offset from UTC

examples/esp32spi_simpletest.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,12 @@
2323
print("ESP32 found and in idle mode")
2424
print("Firmware vers.", esp.firmware_version)
2525
print("MAC addr:", [hex(i) for i in esp.MAC_address])
26+
2627
for ap in esp.scan_networks():
2728
print("\t%s\t\tRSSI: %d" % (str(ap['ssid'], 'utf-8'), ap['rssi']))
29+
2830
print("Connecting to AP...")
29-
esp.connect_AP(b'adafruit', b'ffffffff')
31+
esp.connect_AP(b'MY_SSID_NAME', b'MY_SSID_PASSWORD')
3032
print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi)
3133
print("My IP address is", esp.pretty_ip(esp.ip_address))
3234
print("IP lookup adafruit.com: %s" % esp.pretty_ip(esp.get_host_by_name("adafruit.com")))

0 commit comments

Comments
 (0)