The wifi
Module
The wifi
module provides a simple interface between CircuitPython and the internet using WiFi. It is a built-in module on Espressif and Pico W boards.
Here are a couple of short examples from the guide Todbot's CircuitPython Tricks:
Scan Local WiFi Networks
import wifi networks = [] for network in wifi.radio.start_scanning_networks(): networks.append(network) wifi.radio.stop_scanning_networks() networks = sorted(networks, key=lambda net: net.rssi, reverse=True) for network in networks: print("ssid:",network.ssid, "rssi:",network.rssi)
Displaying Your Local IP Address
This short program uses the wifi
module to connect to the local network, using credentials you set up in a settings.toml file, and then gets the internet protocol (IP) address of your device and prints it out.
# settings.toml CIRCUITPY_WIFI_SSID = "PrettyFlyForAWiFi" CIRCUITPY_WIFI_PASSWORD = "mysecretpassword"
# code.py import os, wifi print("connecting...") wifi.radio.connect(ssid=os.getenv('CIRCUITPY_WIFI_SSID'), password=os.getenv('CIRCUITPY_WIFI_PASSWORD')) print("my IP addr:", wifi.radio.ipv4_address)
Using adafruit_connection_manager
The adafruit_connection_manager
library provides a simple way to get a socket pool or an SSL context (used for HTTPS requests). It supports using the wifi
module , the ESP32SPI library, and can also work on the desktop using CPython ("regular" Python).
Example:
import wifi import adafruit_connection_manager import adafruit_requests radio = wifi.radio # Add code to make sure your radio is connected pool = adafruit_connection_manager.get_radio_socketpool(radio) ssl_context = adafruit_connection_manager.get_radio_ssl_context(radio) requests = adafruit_requests.Session(pool, ssl_context) requests.get("http://wifitest.adafruit.com/testwifi/index.html") # Do something with response
The adafruit_requests
Library
The adafruit_requests
library provides functions similar to the CPython requests
module, used for HTTP(S) commands.
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT # Updated for CircuitPython 9.0 """WiFi Simpletest""" import os import adafruit_connection_manager import wifi import adafruit_requests # Get WiFi details, ensure these are setup in settings.toml ssid = os.getenv("CIRCUITPY_WIFI_SSID") password = os.getenv("CIRCUITPY_WIFI_PASSWORD") TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html" JSON_GET_URL = "https://httpbin.org/get" JSON_POST_URL = "https://httpbin.org/post" # Initalize Wifi, Socket Pool, Request Session pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio) ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio) requests = adafruit_requests.Session(pool, ssl_context) rssi = wifi.radio.ap_info.rssi print(f"\nConnecting to {ssid}...") print(f"Signal Strength: {rssi}") try: # Connect to the Wi-Fi network wifi.radio.connect(ssid, password) except OSError as e: print(f"❌ OSError: {e}") print("✅ Wifi!") print(f" | GET Text Test: {TEXT_URL}") with requests.get(TEXT_URL) as response: print(f" | ✅ GET Response: {response.text}") print("-" * 80) print(f" | GET Full Response Test: {JSON_GET_URL}") with requests.get(JSON_GET_URL) as response: print(f" | ✅ Unparsed Full JSON Response: {response.json()}") print("-" * 80) DATA = "This is an example of a JSON value" print(f" | ✅ JSON 'value' POST Test: {JSON_POST_URL} {DATA}") with requests.post(JSON_POST_URL, data=DATA) as response: json_resp = response.json() # Parse out the 'data' key from json_resp dict. print(f" | ✅ JSON 'value' Response: {json_resp['data']}") print("-" * 80) json_data = {"Date": "January 1, 1970"} print(f" | ✅ JSON 'key':'value' POST Test: {JSON_POST_URL} {json_data}") with requests.post(JSON_POST_URL, json=json_data) as response: json_resp = response.json() # Parse out the 'json' key from json_resp dict. print(f" | ✅ JSON 'key':'value' Response: {json_resp['json']}") print("-" * 80) print("Finished!")
Using MQTT
MQTT is a messaging protocol for communicating between two nodes on the internet. It is often used for Internet of Things (IoT) devices to pass data.
# Simple demo of MQTT client in CircuitPython with native WiFi (ESP32-S Series) # 9 Oct 2021 - @todbot / Tod Kurt # 31 July 2024 Anne Barela for Adafruit Industries # # This will connect to WiFi, then connect to an MQTT broker (shiftr.io was tested) # and then listen to one MQTT feed while periodically publishing to another MQTT feed. # # Your settings.toml file contains something like: # CIRCUITPY_WIFI_SSID = "myWiFiName" # CIRCUITPY_WIFI_PASSWORD = "mywifipassword" # mqtt_broker ="test.mosquitto.org" # mqtt_port = "1883" # unencrytped, use 8883 for TLS encrypted # mqtt_username = "" # mqtt_password = "" # import os import time import ssl, socketpool, wifi import adafruit_minimqtt.adafruit_minimqtt as MQTT my_mqtt_topic_hello = "me/feeds/hello" # the topic we send on my_mqtt_topic_light = "me/feeds/light" # the topic we receive on (could be the same) # Connect to WiFi print(f"Connecting to {os.getenv('CIRCUITPY_WIFI_SSID')}") wifi.radio.connect(os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD")) # Set up a MiniMQTT Client mqtt_client = MQTT.MQTT( broker=os.getenv("mqtt_broker"), port=os.getenv("mqtt_port"), username=os.getenv("mqtt_username"), password=os.getenv("mqtt_password"), socket_pool=socketpool.SocketPool(wifi.radio), ssl_context=ssl.create_default_context(), ) # Called when the client is connected successfully to the broker def connected(client, userdata, flags, rc): print("Connected to MQTT broker!") client.subscribe( my_mqtt_topic_light) # say I want to listen to this topic # Called when the client is disconnected def disconnected(client, userdata, rc): print("Disconnected from MQTT broker!") # Called when a topic the client is subscribed to has a new message def message(client, topic, message): print("New message on topic {0}: {1}".format(topic, message)) val = 0 try: val = int(message) # attempt to parse it as a number except ValueError: pass print("setting LED to color:",val) # led.fill(val) # if we had leds # Set the callback methods defined above mqtt_client.on_connect = connected mqtt_client.on_disconnect = disconnected mqtt_client.on_message = message print("Connecting to MQTT broker...") mqtt_client.connect() last_msg_send_time = 0 while True: print("waiting") mqtt_client.loop(timeout=1) # see if any messages to me if time.monotonic() - last_msg_send_time > 3.0: # send a message every 3 secs last_msg_send_time = time.monotonic() msg = "hi there! time is "+str(time.monotonic()) print("sending MQTT msg..", msg) mqtt_client.publish( my_mqtt_topic_hello, msg )
Further Reading
ReadTheDocs
Third Party Guides
- Connect to Multiple WiFi Networks with your Raspberry Pi Pico W
- CircuitPython WiFi Manager - opens an access point to allow the user to configure the device to configure the device to connect to available WiFi networks. When the device is configured, it then connects to the first available matching network and hands over the control to your code.
Text editor powered by tinymce.