diff --git a/adafruit_esp32spi/adafruit_esp32spi.py b/adafruit_esp32spi/adafruit_esp32spi.py index a492888..76e6cc8 100644 --- a/adafruit_esp32spi/adafruit_esp32spi.py +++ b/adafruit_esp32spi/adafruit_esp32spi.py @@ -410,10 +410,10 @@ def is_connected(self): self.reset() return False - def connect(self, settings): - """Connect to an access point using a settings dictionary + def connect(self, secrets): + """Connect to an access point using a secrets dictionary that contains a 'ssid' and 'password' entry""" - self.connect_AP(settings['ssid'], settings['password']) + self.connect_AP(secrets['ssid'], secrets['password']) def connect_AP(self, ssid, password): # pylint: disable=invalid-name """Connect to an access point with given name and password. diff --git a/adafruit_esp32spi/adafruit_esp32spi_socket.py b/adafruit_esp32spi/adafruit_esp32spi_socket.py index b944774..aec0f6d 100644 --- a/adafruit_esp32spi/adafruit_esp32spi_socket.py +++ b/adafruit_esp32spi/adafruit_esp32spi_socket.py @@ -43,6 +43,8 @@ def set_interface(iface): SOCK_STREAM = const(1) AF_INET = const(2) +MAX_PACKET = const(4000) + # pylint: disable=too-many-arguments, unused-argument def getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0): """Given a hostname and a port name, return a 'socket.getaddrinfo' @@ -85,7 +87,7 @@ def readline(self): #print("Socket readline") while b'\r\n' not in self._buffer: # there's no line already in there, read some more - avail = min(_the_interface.socket_available(self._socknum), 4000) + avail = min(_the_interface.socket_available(self._socknum), MAX_PACKET) if avail: self._buffer += _the_interface.socket_read(self._socknum, avail) firstline, self._buffer = self._buffer.split(b'\r\n', 1) @@ -98,7 +100,7 @@ def read(self, size=0): #print("Socket read", size) if size == 0: # read as much as we can at the moment while True: - avail = min(_the_interface.socket_available(self._socknum), 4000) + avail = min(_the_interface.socket_available(self._socknum), MAX_PACKET) if avail: self._buffer += _the_interface.socket_read(self._socknum, avail) else: @@ -114,7 +116,7 @@ def read(self, size=0): received = [] while to_read > 0: #print("Bytes to read:", to_read) - avail = min(_the_interface.socket_available(self._socknum), 4000) + avail = min(_the_interface.socket_available(self._socknum), MAX_PACKET) if avail: stamp = time.monotonic() recv = _the_interface.socket_read(self._socknum, min(to_read, avail)) @@ -137,8 +139,7 @@ def read(self, size=0): return ret def settimeout(self, value): - """Set the receiving timeout, in seconds. If set to zero, we - fully block until data is ready""" + """Set the read timeout for sockets, if value is 0 it will block""" self._timeout = value def close(self): diff --git a/adafruit_esp32spi/adafruit_esp32spi_wifimanager.py b/adafruit_esp32spi/adafruit_esp32spi_wifimanager.py index cc65f92..5f20afa 100755 --- a/adafruit_esp32spi/adafruit_esp32spi_wifimanager.py +++ b/adafruit_esp32spi/adafruit_esp32spi_wifimanager.py @@ -39,10 +39,10 @@ class ESPSPI_WiFiManager: """ A class to help manage the Wifi connection """ - def __init__(self, esp, settings, status_neopixel=None, attempts=2): + def __init__(self, esp, secrets, status_neopixel=None, attempts=2): """ :param ESP_SPIcontrol esp: The ESP object we are using - :param dict settings: The WiFi and Adafruit IO Settings (See examples) + :param dict secrets: The WiFi and Adafruit IO secrets dict (See examples) :param int attempts: (Optional) Failed attempts before resetting the ESP32 (default=2) :param status_neopixel: (Optional) The neopixel pin - Usually board.NEOPIXEL (default=None) :type status_neopixel: Pin @@ -50,8 +50,8 @@ def __init__(self, esp, settings, status_neopixel=None, attempts=2): # Read the settings self._esp = esp self.debug = False - self.ssid = settings['ssid'] - self.password = settings['password'] + self.ssid = secrets['ssid'] + self.password = secrets['password'] self.attempts = attempts requests.set_interface(self._esp) if status_neopixel: diff --git a/examples/esp32spi_aio_post.py b/examples/esp32spi_aio_post.py index 2527369..205c743 100644 --- a/examples/esp32spi_aio_post.py +++ b/examples/esp32spi_aio_post.py @@ -8,11 +8,11 @@ print("ESP32 SPI webclient test") -# Get wifi details and more from a settings.py file +# Get wifi details and more from a secrets.py file try: - from esp32spi_settings import settings + from secrets import secrets except ImportError: - print("WiFi settings are kept in esp32spi_settings.py, please add them there!") + print("WiFi secrets are kept in secrets.py, please add them there!") raise esp32_cs = DigitalInOut(board.D9) @@ -20,9 +20,10 @@ esp32_reset = DigitalInOut(board.D5) spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) -wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, settings, board.NEOPIXEL) +wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, board.NEOPIXEL) counter = 0 + while True: try: print("Posting data...", end='') @@ -30,8 +31,9 @@ feed = 'test' payload = {'value':data} response = wifi.post( - "https://io.adafruit.com/api/v2/"+settings['aio_username']+"/feeds/"+feed+"/data", - json=payload,headers={bytes("X-AIO-KEY","utf-8"):bytes(settings['aio_key'],"utf-8")}) + "https://io.adafruit.com/api/v2/"+secrets['aio_username']+"/feeds/"+feed+"/data", + json=payload, + headers={bytes("X-AIO-KEY", "utf-8"):bytes(secrets['aio_key'], "utf-8")}) print(response.json()) response.close() counter = counter + 1 diff --git a/examples/esp32spi_cheerlights.py b/examples/esp32spi_cheerlights.py index b44060f..ce82707 100644 --- a/examples/esp32spi_cheerlights.py +++ b/examples/esp32spi_cheerlights.py @@ -9,11 +9,11 @@ import neopixel import adafruit_fancyled.adafruit_fancyled as fancy -# Get wifi details and more from a settings.py file +# Get wifi details and more from a secrets.py file try: - from esp32spi_settings import settings + from secrets import secrets except ImportError: - print("WiFi settings are kept in esp32spi_settings.py, please add them there!") + print("WiFi secrets are kept in secrets.py, please add them there!") raise print("ESP32 SPI webclient test") @@ -26,7 +26,7 @@ esp32_reset = DigitalInOut(board.D5) spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) -wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, settings, board.NEOPIXEL) +wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, board.NEOPIXEL) # neopixels pixels = neopixel.NeoPixel(board.A1, 16, brightness=0.3) @@ -40,7 +40,7 @@ print("Fetching json from", DATA_SOURCE) response = wifi.get(DATA_SOURCE) print(response.json()) - value=response.json() + value = response.json() for key in DATA_LOCATION: value = value[key] print(value) @@ -53,7 +53,7 @@ if not value: continue if last_value != value: - color = int(value[1:],16) + color = int(value[1:], 16) red = color >> 16 & 0xFF green = color >> 8 & 0xFF blue = color& 0xFF diff --git a/examples/esp32spi_localtime.py b/examples/esp32spi_localtime.py new file mode 100644 index 0000000..68eacd4 --- /dev/null +++ b/examples/esp32spi_localtime.py @@ -0,0 +1,57 @@ +import time +import board +import busio +from digitalio import DigitalInOut +from adafruit_esp32spi import adafruit_esp32spi +from adafruit_esp32spi import adafruit_esp32spi_wifimanager +import rtc + +# Get wifi details and more from a secrets.py file +try: + from secrets import secrets +except ImportError: + print("WiFi secrets are kept in secrets.py, please add them there!") + raise + +print("ESP32 local time") + +TIME_API = "http://worldtimeapi.org/api/ip" + +esp32_cs = DigitalInOut(board.ESP_CS) +esp32_ready = DigitalInOut(board.ESP_BUSY) +esp32_reset = DigitalInOut(board.ESP_RESET) +spi = busio.SPI(board.SCK, board.MOSI, board.MISO) +esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) +wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, board.NEOPIXEL) + +the_rtc = rtc.RTC() + +response = None +while True: + try: + print("Fetching json from", TIME_API) + response = wifi.get(TIME_API) + break + except (ValueError, RuntimeError) as e: + print("Failed to get data, retrying\n", e) + continue + +json = response.json() +current_time = json['datetime'] +the_date, the_time = current_time.split('T') +year, month, mday = [int(x) for x in the_date.split('-')] +the_time = the_time.split('.')[0] +hours, minutes, seconds = [int(x) for x in the_time.split(':')] + +# We can also fill in these extra nice things +year_day = json['day_of_year'] +week_day = json['day_of_week'] +is_dst = json['dst'] + +now = time.struct_time((year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst)) +print(now) +the_rtc.datetime = now + +while True: + print(time.localtime()) + time.sleep(1) diff --git a/examples/esp32spi_settings.py b/examples/esp32spi_secrets.py similarity index 96% rename from examples/esp32spi_settings.py rename to examples/esp32spi_secrets.py index 4b5013d..0f3a3fd 100644 --- a/examples/esp32spi_settings.py +++ b/examples/esp32spi_secrets.py @@ -1,7 +1,7 @@ # This file is where you keep secret settings, passwords, and tokens! # If you put them in the code you risk committing that info or sharing it -settings = { +secrets = { 'ssid' : 'yourssid', 'password' : 'yourpassword', 'timezone' : -5, # this is offset from UTC diff --git a/examples/esp32spi_simpletest.py b/examples/esp32spi_simpletest.py index b4b9a29..67d67c7 100644 --- a/examples/esp32spi_simpletest.py +++ b/examples/esp32spi_simpletest.py @@ -23,10 +23,12 @@ print("ESP32 found and in idle mode") print("Firmware vers.", esp.firmware_version) print("MAC addr:", [hex(i) for i in esp.MAC_address]) + for ap in esp.scan_networks(): print("\t%s\t\tRSSI: %d" % (str(ap['ssid'], 'utf-8'), ap['rssi'])) + print("Connecting to AP...") -esp.connect_AP(b'adafruit', b'ffffffff') +esp.connect_AP(b'MY_SSID_NAME', b'MY_SSID_PASSWORD') print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi) print("My IP address is", esp.pretty_ip(esp.ip_address)) print("IP lookup adafruit.com: %s" % esp.pretty_ip(esp.get_host_by_name("adafruit.com")))