adafruit_esp32spi

CircuitPython driver library for using ESP32 as WiFi co-processor using SPI

  • Author(s): ladyada

Implementation Notes

Hardware:

Software and Dependencies:

class adafruit_esp32spi.adafruit_esp32spi.ESP_SPIcontrol(spi, cs_pin, ready_pin, reset_pin, gpio0_pin=None, *, debug=False)

A class that will talk to an ESP32 module programmed with special firmware that lets it act as a fast an efficient WiFi co-processor

property MAC_address

A bytearray containing the MAC address of the ESP32

property MAC_address_actual

A bytearray containing the actual MAC address of the ESP32

property ap_listening

Returns if the ESP32 is in access point mode and is listening for connections

property bssid

The MAC-formatted service set ID of the access point we’re connected to

connect(secrets)

Connect to an access point using a secrets dictionary that contains a ‘ssid’ and ‘password’ entry

connect_AP(ssid, password, timeout_s=10)

Connect to an access point with given name and password. Will wait until specified timeout seconds and return on success or raise an exception on failure.

Parameters
  • ssid – the SSID to connect to

  • passphrase – the password of the access point

  • timeout_s – number of seconds until we time out and fail to create AP

create_AP(ssid, password, channel=1, timeout=10)

Create an access point with the given name, password, and channel. Will wait until specified timeout seconds and return on success or raise an exception on failure.

Parameters
  • ssid (str) – the SSID of the created Access Point. Must be less than 32 chars.

  • password (str) – the password of the created Access Point. Must be 8-63 chars.

  • channel (int) – channel of created Access Point (1 - 14).

  • timeout (int) – number of seconds until we time out and fail to create AP

disconnect()

Disconnect from the access point

property firmware_version

A string of the firmware version on the ESP32

get_host_by_name(hostname)

Convert a hostname to a packed 4-byte IP address. Returns a 4 bytearray

get_scan_networks()

The results of the latest SSID scan. Returns a list of dictionaries with ‘ssid’, ‘rssi’, ‘encryption’, bssid, and channel entries, one for each AP found

get_socket()

Request a socket from the ESP32, will allocate and return a number that can then be passed to the other socket commands

get_time()

The current unix timestamp

property ip_address

Our local IP address

property is_connected

Whether the ESP32 is connected to an access point

property network_data

A dictionary containing current connection details such as the ‘ip_addr’, ‘netmask’ and ‘gateway’

ping(dest, ttl=250)

Ping a destination IP address or hostname, with a max time-to-live (ttl). Returns a millisecond timing value

pretty_ip(ip)

Converts a bytearray IP address to a dotted-quad string for printing

reset()

Hard reset the ESP32 using the reset pin

property rssi

The receiving signal strength indicator for the access point we’re connected to

scan_networks()

Scan for visible access points, returns a list of access point details. Returns a list of dictionaries with ‘ssid’, ‘rssi’ and ‘encryption’ entries, one for each AP found

server_state(socket_num)

Get the state of the ESP32’s internal reference server socket number

set_analog_read(pin, atten=3)

Get the analog input value of pin. Returns an int between 0 and 65536.

Parameters
  • pin (int) – ESP32 GPIO pin to read from.

  • atten (int) – attenuation constant

set_analog_write(pin, analog_value)

Set the analog output value of pin, using PWM.

Parameters
  • pin (int) – ESP32 GPIO pin to write to.

  • value (float) – 0=off 1.0=full on

set_certificate(client_certificate)

Sets client certificate. Must be called BEFORE a network connection is established. :param str client_certificate: User-provided .PEM certificate up to 1300 bytes.

set_digital_read(pin)

Get the digital input value of pin. Returns the boolean value of the pin.

Parameters

pin (int) – ESP32 GPIO pin to read from.

set_digital_write(pin, value)

Set the digital output value of pin.

Parameters
  • pin (int) – ESP32 GPIO pin to write to.

  • value (bool) – Value for the pin.

set_esp_debug(enabled)

Enable/disable debug mode on the ESP32. Debug messages will be written to the ESP32’s UART.

set_pin_mode(pin, mode)

Set the io mode for a GPIO pin.

Parameters
  • pin (int) – ESP32 GPIO pin to set.

  • value – direction for pin, digitalio.Direction or integer (0=input, 1=output).

set_private_key(private_key)

Sets private key. Must be called BEFORE a network connection is established. :param str private_key: User-provided .PEM file up to 1700 bytes.

socket_available(socket_num)

Determine how many bytes are waiting to be read on the socket

socket_close(socket_num)

Close a socket using the ESP32’s internal reference number

socket_connect(socket_num, dest, port, conn_mode=0)

Open and verify we connected a socket to a destination IP address or hostname using the ESP32’s internal reference number. By default we use ‘conn_mode’ TCP_MODE but can also use UDP_MODE or TLS_MODE (dest must be hostname for TLS_MODE!)

socket_connected(socket_num)

Test if a socket is connected to the destination, returns boolean true/false

socket_open(socket_num, dest, port, conn_mode=0)

Open a socket to a destination IP address or hostname using the ESP32’s internal reference number. By default we use ‘conn_mode’ TCP_MODE but can also use UDP_MODE or TLS_MODE (dest must be hostname for TLS_MODE!)

socket_read(socket_num, size)

Read up to ‘size’ bytes from the socket number. Returns a bytearray

socket_status(socket_num)

Get the socket connection status, can be SOCKET_CLOSED, SOCKET_LISTEN, SOCKET_SYN_SENT, SOCKET_SYN_RCVD, SOCKET_ESTABLISHED, SOCKET_FIN_WAIT_1, SOCKET_FIN_WAIT_2, SOCKET_CLOSE_WAIT, SOCKET_CLOSING, SOCKET_LAST_ACK, or SOCKET_TIME_WAIT

socket_write(socket_num, buffer, conn_mode=0)

Write the bytearray buffer to a socket

property ssid

The name of the access point we’re connected to

start_scan_networks()

Begin a scan of visible access points. Follow up with a call to ‘get_scan_networks’ for response

start_server(port, socket_num, conn_mode=0, ip=None)

Opens a server on the specified port, using the ESP32’s internal reference number

property status

The status of the ESP32 WiFi core. Can be WL_NO_SHIELD or WL_NO_MODULE (not found), WL_IDLE_STATUS, WL_NO_SSID_AVAIL, WL_SCAN_COMPLETED, WL_CONNECTED, WL_CONNECT_FAILED, WL_CONNECTION_LOST, WL_DISCONNECTED, WL_AP_LISTENING, WL_AP_CONNECTED, WL_AP_FAILED

unpretty_ip(ip)

Converts a dotted-quad string to a bytearray IP address

wifi_set_entenable()

Enables WPA2 Enterprise mode

wifi_set_entidentity(ident)

Sets the WPA2 Enterprise anonymous identity

wifi_set_entpassword(password)

Sets the desired WPA2 Enterprise password

wifi_set_entusername(username)

Sets the desired WPA2 Enterprise username

wifi_set_network(ssid)

Tells the ESP32 to set the access point to the given ssid

wifi_set_passphrase(ssid, passphrase)

Sets the desired access point ssid and passphrase

adafruit_esp32spi_socket

A socket compatible interface thru the ESP SPI command set

  • Author(s): ladyada

adafruit_esp32spi.adafruit_esp32spi_socket.getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0)

Given a hostname and a port name, return a ‘socket.getaddrinfo’ compatible list of tuples. Honestly, we ignore anything but host & port

adafruit_esp32spi.adafruit_esp32spi_socket.set_interface(iface)

Helper to set the global internet interface

class adafruit_esp32spi.adafruit_esp32spi_socket.socket(family=2, type=0, proto=0, fileno=None, socknum=None)

A simplified implementation of the Python ‘socket’ class, for connecting through an interface to a remote device

available()

Returns how many bytes of data are available to be read (up to the MAX_PACKET length)

close()

Close the socket, after reading whatever remains

connect(address, conntype=None)

Connect the socket to the ‘address’ (which can be 32bit packed IP or a hostname string). ‘conntype’ is an extra that may indicate SSL or not, depending on the underlying interface

connected()

Whether or not we are connected to the socket

read(size=0)

Read up to ‘size’ bytes from the socket, this may be buffered internally! If ‘size’ isnt specified, return everything in the buffer. NOTE: This method is deprecated and will be removed.

readline(eol=b'\r\n')

Attempt to return as many bytes as we can up to but not including end-of-line character (default is ‘rn’)

recv(bufsize=0)

Reads some bytes from the connected remote address. Will only return an empty string after the configured timeout.

Parameters

bufsize (int) – maximum number of bytes to receive

recv_into(buffer)

Read some bytes from the connected remote address into a given buffer

Parameters

buffer (bytearray) – The buffer to read into

send(data)

Send some data to the socket.

settimeout(value)

Set the read timeout for sockets, if value is 0 it will block

property socknum

The socket number

write(data)

Sends data to the socket. NOTE: This method is deprecated and will be removed.

adafruit_esp32spi_wifimanager

WiFi Manager for making ESP32 SPI as WiFi much easier

  • Author(s): Melissa LeBlanc-Williams, ladyada

class adafruit_esp32spi.adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_pixel=None, attempts=2, connection_type=1, debug=False)

A class to help manage the Wifi connection

connect()

Attempt to connect to WiFi using the current settings

connect_enterprise()

Attempt an enterprise style WiFi connection

connect_normal()

Attempt a regular style WiFi connection.

create_ap()

Attempt to initialize in Access Point (AP) mode. Uses SSID and optional passphrase from the current settings Other WiFi devices will be able to connect to the created Access Point

delete(url, **kw)

Pass the delete request to requests and update status LED

Parameters
  • url (str) – The URL to PUT data to

  • data (dict) – (Optional) Form data to submit

  • json (dict) – (Optional) JSON data to submit. (Data must be None)

  • header (dict) – (Optional) Header data to include

  • stream (bool) – (Optional) Whether to stream the Response

Returns

The response from the request

Return type

Response

get(url, **kw)

Pass the Get request to requests and update status LED

Parameters
  • url (str) – The URL to retrieve data from

  • data (dict) – (Optional) Form data to submit

  • json (dict) – (Optional) JSON data to submit. (Data must be None)

  • header (dict) – (Optional) Header data to include

  • stream (bool) – (Optional) Whether to stream the Response

Returns

The response from the request

Return type

Response

ip_address()

Returns a formatted local IP address, update status pixel.

patch(url, **kw)

Pass the patch request to requests and update status LED

Parameters
  • url (str) – The URL to PUT data to

  • data (dict) – (Optional) Form data to submit

  • json (dict) – (Optional) JSON data to submit. (Data must be None)

  • header (dict) – (Optional) Header data to include

  • stream (bool) – (Optional) Whether to stream the Response

Returns

The response from the request

Return type

Response

ping(host, ttl=250)

Pass the Ping request to the ESP32, update status LED, return response time

Parameters
  • host (str) – The hostname or IP address to ping

  • ttl (int) – (Optional) The Time To Live in milliseconds for the packet (default=250)

Returns

The response time in milliseconds

Return type

int

pixel_status(value)

Change Status Pixel if it was defined

Parameters

value (int or 3-value tuple) – The value to set the Board’s status LED to

post(url, **kw)

Pass the Post request to requests and update status LED

Parameters
  • url (str) – The URL to post data to

  • data (dict) – (Optional) Form data to submit

  • json (dict) – (Optional) JSON data to submit. (Data must be None)

  • header (dict) – (Optional) Header data to include

  • stream (bool) – (Optional) Whether to stream the Response

Returns

The response from the request

Return type

Response

put(url, **kw)

Pass the put request to requests and update status LED

Parameters
  • url (str) – The URL to PUT data to

  • data (dict) – (Optional) Form data to submit

  • json (dict) – (Optional) JSON data to submit. (Data must be None)

  • header (dict) – (Optional) Header data to include

  • stream (bool) – (Optional) Whether to stream the Response

Returns

The response from the request

Return type

Response

reset()

Perform a hard reset on the ESP32

signal_strength()

Returns receiving signal strength indicator in dBm

adafruit_esp32spi_wsgiserver

A simple WSGI (Web Server Gateway Interface) server that interfaces with the ESP32 over SPI. Opens a specified port on the ESP32 to listen for incoming HTTP Requests and Accepts an Application object that must be callable, which gets called whenever a new HTTP Request has been received.

The Application MUST accept 2 ordered parameters:
  1. environ object (incoming request data)

  2. start_response function. Must be called before the Application

    callable returns, in order to set the response status and headers.

The Application MUST return a single string in a list, which is the response data

Requires update_poll being called in the applications main event loop.

For more details about Python WSGI see: https://www.python.org/dev/peps/pep-0333/

  • Author(s): Matt Costi

class adafruit_esp32spi.adafruit_esp32spi_wsgiserver.WSGIServer(port=80, debug=False, application=None)

A simple server that implements the WSGI interface

client_available()

returns a client socket connection if available. Otherwise, returns None :return: the client :rtype: Socket

finish_response(result)

Called after the application callbile returns result data to respond with. Creates the HTTP Response payload from the response_headers and results data, and sends it back to client.

Parameters

result (string) – the data string to send back in the response to the client.

start()

starts the server and begins listening for incoming connections. Call update_poll in the main loop for the application callable to be invoked on receiving an incoming request.

update_poll()

Call this method inside your main event loop to get the server check for new incoming client requests. When a request comes in, the application callable will be invoked.

adafruit_esp32spi.adafruit_esp32spi_wsgiserver.parse_headers(client)

Parses the header portion of an HTTP request from the socket. Expects first line of HTTP request to have been read already.

adafruit_esp32spi.adafruit_esp32spi_wsgiserver.set_interface(iface)

Helper to set the global internet interface

digitalio

DigitalIO for ESP32 over SPI.

  • Author(s): Brent Rubell, based on Adafruit_Blinka digitalio implementation and bcm283x Pin implementation.

https://github.com/adafruit/Adafruit_Blinka/blob/master/src/adafruit_blinka/microcontroller/bcm283x/pin.py https://github.com/adafruit/Adafruit_Blinka/blob/master/src/digitalio.py

class adafruit_esp32spi.digitalio.DigitalInOut(esp, pin)

Implementation of DigitalIO module for ESP32SPI.

Parameters
  • esp (ESP_SPIcontrol) – The ESP object we are using.

  • pin (int) – Valid ESP32 GPIO Pin, predefined in ESP32_GPIO_PINS.

deinit()

De-initializes the pin object.

property direction

Returns the pin’s direction.

property drive_mode

Returns pin drive mode.

switch_to_input(pull=None)

Sets the pull and then switch to read in digital values. :param Pull pull: Pull configuration for the input.

switch_to_output(value=False, drive_mode=<adafruit_esp32spi.digitalio.DriveMode object>)

Set the drive mode and value and then switch to writing out digital values. :param bool value: Default mode to set upon switching. :param DriveMode drive_mode: Drive mode for the output.

property value

Returns the digital logic level value of the pin.

class adafruit_esp32spi.digitalio.Direction

DriveMode Enum.

class adafruit_esp32spi.digitalio.DriveMode

DriveMode Enum.

class adafruit_esp32spi.digitalio.Pin(esp_pin, esp)

Implementation of CircuitPython API Pin Handling for ESP32SPI.

Parameters
  • esp_pin (int) – Valid ESP32 GPIO Pin, predefined in ESP32_GPIO_PINS.

  • esp (ESP_SPIcontrol) – The ESP object we are using.

NOTE: This class does not currently implement reading digital pins or the use of internal pull-up resistors.

init(mode=0)

Initalizes a pre-defined pin. :param mode: Pin mode (IN, OUT, LOW, HIGH). Defaults to IN.

value(val=None)

Sets ESP32 Pin GPIO output mode. :param val: Pin output level (LOW, HIGH)

PWMOut

PWMOut CircuitPython API for ESP32SPI.

  • Author(s): Brent Rubell

class adafruit_esp32spi.PWMOut.PWMOut(esp, pwm_pin, *, frequency=500, duty_cycle=0, variable_frequency=False)

Implementation of CircuitPython PWMOut for ESP32SPI.

Parameters
  • esp_pin (int) – Valid ESP32 GPIO Pin, predefined in ESP32_GPIO_PINS.

  • esp (ESP_SPIcontrol) – The ESP object we are using.

  • duty_cycle (int) – The fraction of each pulse which is high, 16-bit.

  • frequency (int) – The target frequency in Hertz (32-bit).

  • variable_frequency (bool) – True if the frequency will change over time.

deinit()

De-initalize the PWMOut object.

property duty_cycle

Returns the PWMOut object’s duty cycle as a ratio from 0.0 to 1.0.

property frequency

Returns the PWMOut object’s frequency value.