API Reference
adafruit_esp32spi
CircuitPython driver library for using ESP32 as WiFi co-processor using SPI
Author(s): ladyada
Implementation Notes
Hardware:
Software and Dependencies:
Adafruit CircuitPython firmware for the supported boards: https://github.com/adafruit/circuitpython/releases
Adafruit’s Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
Note
As of version 11.0.0, it simpler to import this library and its submodules The examples in this documentation use the new import names. The old import names are still available, but are deprecated and may be removed in a future release.
Before version 11.0.0, the library was structured like this (not all components are shown):
adafruit_esp32spiadafruit_esp32spiESP32_SPIcontrol
adafruit_esp32spi_socketpoolSocketPool
adafruit_esp32spi_wifimanagerWiFiManager
# Old import scheme
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi.adafruit_esp32spi_socketpool import SocketPool
from adafruit_esp32spi.adafruit_esp32spi_wifimanager import WiFiManager
Now, the duplicated top-most name is not needed, and there are shorter names for the submodules.
adafruit_esp32spiESP32_SPIcontrolsocketpoolSocketPool
wifimanagerWiFiManager
# New import scheme
import adafruit_esp32spi
from adafruit_esp32spi.socketpool import SocketPool
from adafruit_esp32spi.wifimanager import WiFiManager
- class adafruit_esp32spi.Direction
Direction Enumeration
- class adafruit_esp32spi.ESP_SPIcontrol(spi, cs_dio, ready_dio, reset_dio, gpio0_dio=None, *, debug=False, debug_show_secrets=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_info
Network object containing BSSID, SSID, authmode, channel, country and RSSI when connected to an access point. None otherwise.
- property ap_listening
Returns if the ESP32 is in access point mode and is listening for connections
- connect(ssid, password=None, timeout=10)
Connect to an access point with given name and password.
Deprecated functionality: If the first argument (
ssid) is adict, assume it is a dictionary with entries for keys"ssid"and, optionally,"password". This mimics the previous signature forconnect(). This upward compatibility will be removed in a future release.
- 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
- property connected
Whether the ESP32 is connected to an access point
- 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:
- 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_remote_data(socket_num)
Get the IP address and port of the remote host
- 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 ipv4_address
IP address of the station when connected to an access point.
- property is_connected
Whether the ESP32 is connected to an access point
- property mac_address
A bytes containing the actual MAC address of the ESP32
- 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
- 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.
- set_analog_write(pin, analog_value)
Set the analog output value of pin, using PWM.
- set_certificate(client_certificate)
Sets client certificate. Must be called BEFORE a network connection is established.
- Parameters:
client_certificate (str) – 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.
- set_dns_config(dns1, dns2)
Tells the ESP32 to set DNS
- set_esp_debug(enabled)
Enable/disable debug mode on the ESP32. Debug messages will be written to the ESP32’s UART.
- set_hostname(hostname)
Tells the ESP32 to set hostname for DHCP.
- Parameters:
hostname (str) – The new host name.
- set_ip_config(ip_address, gateway, mask='255.255.255.0')
Tells the ESP32 to set ip, gateway and network mask b”ÿ”
- 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.
- Parameters:
private_key (str) – 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 bytes
- 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. Returns the number of bytes written
- 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_STOPPED, 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
- class adafruit_esp32spi.Network(esp_spi_control=None, raw_ssid=None, raw_bssid=None, raw_rssi=None, raw_channel=None, raw_country=None, raw_authmode=None)
A wifi network provided by a nearby access point.
- property authmode
String id of the authmode
derived from Nina code: https://github.com/adafruit/nina-fw/blob/master/arduino/libraries/WiFi/src/WiFi.cpp#L385
- property bssid
BSSID of the network (usually the AP’s MAC address)
- property channel
Channel number the network is operating on
- property country
String id of the country code
- property rssi
Signal strength of the network
- property ssid
String id of the network
- class adafruit_esp32spi.SPIDevice(spi: SPI, chip_select: DigitalInOut | None = None, *, cs_active_value: bool = False, baudrate: int = 100000, polarity: int = 0, phase: int = 0, extra_clocks: int = 0)
Represents a single SPI device and manages locking the bus and the device address.
- Parameters:
spi (SPI) – The SPI bus the device is on
chip_select (DigitalInOut) – The chip select pin object that implements the DigitalInOut API.
cs_active_value (bool) – Set to True if your device requires CS to be active high. Defaults to False.
baudrate (int) – The desired SCK clock rate in Hertz. The actual clock rate may be higher or lower due to the granularity of available clock settings (MCU dependent).
polarity (int) – The base state of the SCK clock pin (0 or 1).
phase (int) – The edge of the clock that data is captured. First (0) or second (1). Rising or falling depends on SCK clock polarity.
extra_clocks (int) – The minimum number of clock cycles to cycle the bus after CS is high. (Used for SD cards.)
Note
This class is NOT built into CircuitPython. See here for install instructions.
Example:
import busio import digitalio from board import * from adafruit_bus_device.spi_device import SPIDevice with busio.SPI(SCK, MOSI, MISO) as spi_bus: cs = digitalio.DigitalInOut(D10) device = SPIDevice(spi_bus, cs) bytes_read = bytearray(4) # The object assigned to spi in the with statements below # is the original spi_bus object. We are using the busio.SPI # operations busio.SPI.readinto() and busio.SPI.write(). with device as spi: spi.readinto(bytes_read) # A second transaction with device as spi: spi.write(bytes_read)
- adafruit_esp32spi.const(x)
Emulate making a constant
- class adafruit_esp32spi.socketpool.Socket(socket_pool: SocketPool, family: int = 2, type: int = 1, proto: int = 0, fileno: int | None = None, socknum: int | None = None)
A simplified implementation of the Python ‘socket’ class, for connecting through an interface to a remote device. Has properties specific to the implementation.
- Parameters:
socket_pool (SocketPool) – The underlying socket pool.
socknum (Optional[int]) – Allows wrapping a Socket instance around a socket number returned by the nina firmware. Used internally.
- accept()
Accept a connection on a listening socket of type SOCK_STREAM, creating a new socket of type SOCK_STREAM. Returns a tuple of (new_socket, remote_address)
- 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
- listen(backlog: int)
Set socket to listen for incoming connections. :param int backlog: length of backlog queue for waiting connections (ignored)
- recv(bufsize: int) bytes
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, nbytes: int = 0)
Read bytes from the connected remote address into a given buffer.
- send(data)
Send some data to the socket.
- sendto(data, address)
Connect and send some data to the socket.
- setblocking(flag: bool)
Set the blocking behaviour of this socket. :param bool flag: False means non-blocking, True means block indefinitely.
- setsockopt(*opts, **kwopts)
Dummy call for compatibility.
- settimeout(value)
Set the read timeout for sockets in seconds.
0means non-blocking.Nonemeans block indefinitely.
- class adafruit_esp32spi.socketpool.SocketPool(iface: ESP_SPIcontrol)
ESP32SPI SocketPool library
- 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
- socket(family=2, type=1, proto=0, fileno=None)
Create a new socket and return it
- adafruit_esp32spi.socketpool.const(x)
Emulate making a constant
- class adafruit_esp32spi.wifimanager.ESPSPI_WiFiManager(esp, secrets, status_pixel=None, attempts=2, connection_type=1, debug=False)
A legacy class to help manage the Wifi connection. Please update to using WiFiManager
- class adafruit_esp32spi.wifimanager.WiFiManager(esp, ssid, password=None, *, enterprise_ident=None, enterprise_user=None, 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:
- Returns:
The response from the request
- Return type:
Response
- get(url, **kw)
Pass the Get request to requests and update status LED
- Parameters:
- 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:
- 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
- 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:
- Returns:
The response from the request
- Return type:
Response
- put(url, **kw)
Pass the put request to requests and update status LED
- Parameters:
- 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.wifimanager.const(x)
Emulate making a constant
- adafruit_esp32spi.wifimanager.sleep(seconds)
Delay execution for a given number of seconds. The argument may be a floating-point number for subsecond precision.
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.
- Parameters:
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.
- 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.
- Parameters:
mode – Pin mode (IN, OUT, LOW, HIGH). Defaults to IN.
- value(val=None)
Sets ESP32 Pin GPIO output mode.
- Parameters:
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.