Skip to content

Instantly share code, notes, and snippets.

@ryang14
Created May 12, 2020 22:39
Show Gist options
  • Save ryang14/019c44bf6e155ec160f663df74473fca to your computer and use it in GitHub Desktop.
Save ryang14/019c44bf6e155ec160f663df74473fca to your computer and use it in GitHub Desktop.
Code to use CircuitPython over WiFi. Very rough around the edges, but seems to work pretty well
import storage
import adafruit_requests as requests
import networkInit # Board specific network connection
try:
from secrets import secrets
connectionString = secrets["ota_connection_string"]
except (ImportError, KeyError):
print("Connection string is kept in secrets.py, please add it there!")
print("For example: 'ota_connection_string' : 'http://192.168.0.20:8000/',")
raise
try:
# Get the list of files to download
# Server must contain files.json
# Formated like: {"files": ["<file1>", "<file2>"]}
response = requests.get(connectionString + 'files.json')
if "content-length" not in response.headers or response.headers["content-length"] == 0:
raise RuntimeError("files.json not found on server")
fileList = response.json()["files"]
# Make sure the file system is writable, then download the files
storage.remount("/")
print("Downloading files")
for filename in fileList:
try:
response = requests.get(connectionString + filename)
if "content-length" not in response.headers or response.headers["content-length"] == 0:
raise RuntimeError("File not found")
text = response.text
with open(filename, "rw") as file:
file.write(text)
except:
print("File: " + filename + " failed to download")
continue
except (ValueError, RuntimeError) as e:
# Could not download files, continue to run program.py
print("Could not download files")
print(e)
pass
print("Running program.py")
__import__("program")
import board
import busio
import neopixel
from digitalio import DigitalInOut
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_esp32spi.adafruit_esp32spi_wifimanager as wifimanager
# 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
status_light = neopixel.NeoPixel(
board.D4, 1, brightness=0.2
)
esp32_cs = DigitalInOut(board.D10)
esp32_ready = DigitalInOut(board.D9)
esp32_reset = DigitalInOut(board.D6)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(
spi, esp32_cs, esp32_ready, esp32_reset
) # pylint: disable=line-too-long
if not esp.is_connected:
wifi = wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
wifi.connect()
from networkInit import esp # Board specific network connection
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
# Override socket.send to support UDP
class UDPSocket(socket.socket):
def send(self, data): # pylint: disable=no-self-use
"""Send some data to the socket"""
# socket_open is needed to start a new message
socket._the_interface.socket_open(self._socknum, bytearray(b"\xff\xff\xff\xff"), 1337, conn_mode=socket._the_interface.UDP_MODE)
socket._the_interface.socket_write(self._socknum, data, conn_mode=socket._the_interface.UDP_MODE)
# Setup the socket
socket.set_interface(esp)
sock = UDPSocket()
sock.connect((bytearray(b"\xff\xff\xff\xff"), 1337), conntype=esp.UDP_MODE)
def printUDP(arg):
try:
sock.send("{}".format(arg))
except:
pass # Ignore any failure to send
@askpatrickw
Copy link

This looks pretty cool ! One comment.
With the ESP32S2 Native Wifi merge the ESP32S2 Port has it own flow for managing WIFI connections (since its "native" and not via a co-processor).

Luckily its very easy. I doubt Adafruit has a guide out yet, but here's some sample code i've been using

import wifi

# 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


def wifi_join(ssid, password):
    for network in wifi.radio.start_scanning_networks():
        if network.ssid == ssid:
            wifi.radio.connect(ssid, password)
    wifi.radio.stop_scanning_networks()



wifi_join(secrets['ssid'], secrets['wifi_pass'])
print("ip: ", wifi.radio.ipv4_address)

@ryang14
Copy link
Author

ryang14 commented Sep 14, 2020

I already have an ESP32-S2 port, but I'm running into some subtle issues that I need to track down. I will update this when I get it working and make sure it still works with the ESP32 on SPI.

@askpatrickw
Copy link

You will need tannewt's updated requests library on the ESP32S2. It is not merged yet PR is here: adafruit/Adafruit_CircuitPython_Requests#31

@ryang14
Copy link
Author

ryang14 commented Sep 14, 2020

I'll try that. I'm currently using the one that was posted in discord.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment