Skip to content

Commit 0f1b912

Browse files
authored
Merge pull request #178 from DJDevon3/DJDevon3-WifiAdvanced
update requests_wifi_advanced to 9.0 with Connection Manager
2 parents e433597 + 7c45cdd commit 0f1b912

File tree

2 files changed

+179
-25
lines changed

2 files changed

+179
-25
lines changed
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
# SPDX-FileCopyrightText: 2024 DJDevon3
2+
# SPDX-License-Identifier: MIT
3+
# Updated for Circuit Python 9.0
4+
# https://help.openai.com/en/articles/6825453-chatgpt-release-notes
5+
# https://chat.openai.com/share/32ef0c5f-ac92-4d36-9d1e-0f91e0c4c574
6+
""" WiFi Status Codes Example """
7+
8+
import os
9+
import time
10+
11+
import adafruit_connection_manager
12+
import wifi
13+
14+
import adafruit_requests
15+
16+
# Get WiFi details, ensure these are setup in settings.toml
17+
ssid = os.getenv("CIRCUITPY_WIFI_SSID")
18+
password = os.getenv("CIRCUITPY_WIFI_PASSWORD")
19+
20+
# Initalize Wifi, Socket Pool, Request Session
21+
pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
22+
ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
23+
requests = adafruit_requests.Session(pool, ssl_context)
24+
rssi = wifi.radio.ap_info.rssi
25+
26+
27+
def print_http_status(expected_code, actual_code, description):
28+
"""Returns HTTP status code and description"""
29+
if "100" <= actual_code <= "103":
30+
print(
31+
f" | ✅ Status Test Expected: {expected_code} Actual: {actual_code} - {description}"
32+
)
33+
elif "200" == actual_code:
34+
print(
35+
f" | 🆗 Status Test Expected: {expected_code} Actual: {actual_code} - {description}"
36+
)
37+
elif "201" <= actual_code <= "299":
38+
print(
39+
f" | ✅ Status Test Expected: {expected_code} Actual: {actual_code} - {description}"
40+
)
41+
elif "300" <= actual_code <= "600":
42+
print(
43+
f" | ❌ Status Test Expected: {expected_code} Actual: {actual_code} - {description}"
44+
)
45+
else:
46+
print(
47+
f" | Unknown Response Status Expected: {expected_code} "
48+
+ f"Actual: {actual_code} - {description}"
49+
)
50+
51+
52+
# All HTTP Status Codes
53+
http_status_codes = {
54+
"100": "Continue",
55+
"101": "Switching Protocols",
56+
"102": "Processing",
57+
"103": "Early Hints",
58+
"200": "OK",
59+
"201": "Created",
60+
"202": "Accepted",
61+
"203": "Non-Authoritative Information",
62+
"204": "No Content",
63+
"205": "Reset Content",
64+
"206": "Partial Content",
65+
"207": "Multi-Status",
66+
"208": "Already Reported",
67+
"226": "IM Used",
68+
"300": "Multiple Choices",
69+
"301": "Moved Permanently",
70+
"302": "Found",
71+
"303": "See Other",
72+
"304": "Not Modified",
73+
"305": "Use Proxy",
74+
"306": "Unused",
75+
"307": "Temporary Redirect",
76+
"308": "Permanent Redirect",
77+
"400": "Bad Request",
78+
"401": "Unauthorized",
79+
"402": "Payment Required",
80+
"403": "Forbidden",
81+
"404": "Not Found",
82+
"405": "Method Not Allowed",
83+
"406": "Not Acceptable",
84+
"407": "Proxy Authentication Required",
85+
"408": "Request Timeout",
86+
"409": "Conflict",
87+
"410": "Gone",
88+
"411": "Length Required",
89+
"412": "Precondition Failed",
90+
"413": "Payload Too Large",
91+
"414": "URI Too Long",
92+
"415": "Unsupported Media Type",
93+
"416": "Range Not Satisfiable",
94+
"417": "Expectation Failed",
95+
"418": "I'm a teapot",
96+
"421": "Misdirected Request",
97+
"422": "Unprocessable Entity",
98+
"423": "Locked",
99+
"424": "Failed Dependency",
100+
"425": "Too Early",
101+
"426": "Upgrade Required",
102+
"428": "Precondition Required",
103+
"429": "Too Many Requests",
104+
"431": "Request Header Fields Too Large",
105+
"451": "Unavailable For Legal Reasons",
106+
"500": "Internal Server Error",
107+
"501": "Not Implemented",
108+
"502": "Bad Gateway",
109+
"503": "Service Unavailable",
110+
"504": "Gateway Timeout",
111+
"505": "HTTP Version Not Supported",
112+
"506": "Variant Also Negotiates",
113+
"507": "Insufficient Storage",
114+
"508": "Loop Detected",
115+
"510": "Not Extended",
116+
"511": "Network Authentication Required",
117+
}
118+
119+
STATUS_TEST_URL = "https://httpbin.org/status/"
120+
121+
print(f"\nConnecting to {ssid}...")
122+
print(f"Signal Strength: {rssi}")
123+
try:
124+
# Connect to the Wi-Fi network
125+
wifi.radio.connect(ssid, password)
126+
except OSError as e:
127+
print(f"❌ OSError: {e}")
128+
print("✅ Wifi!")
129+
130+
131+
print(f" | Status Code Test: {STATUS_TEST_URL}")
132+
# Some return errors then confirm the error (that's a good thing)
133+
# Demonstrates not all errors have the same behavior
134+
# Some 300 level responses contain redirects that requests automatically follows
135+
# By default the response object will contain the status code from the final
136+
# response after all redirect, so it can differ from the expected status code.
137+
for current_code in sorted(http_status_codes.keys(), key=int):
138+
header_status_test_url = STATUS_TEST_URL + current_code
139+
with requests.get(header_status_test_url) as response:
140+
response_status_code = str(response.status_code)
141+
SORT_STATUS_DESC = http_status_codes.get(
142+
response_status_code, "Unknown Status Code"
143+
)
144+
print_http_status(current_code, response_status_code, SORT_STATUS_DESC)
145+
146+
# Rate limit ourselves a little to avoid strain on server
147+
time.sleep(0.5)
148+
print("Finished!")
Lines changed: 31 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
22
# SPDX-License-Identifier: MIT
3+
# Updated for Circuit Python 9.0
4+
5+
""" WiFi Advanced Example """
36

47
import os
5-
import ssl
68

7-
import socketpool
9+
import adafruit_connection_manager
810
import wifi
911

1012
import adafruit_requests
@@ -13,36 +15,40 @@
1315
ssid = os.getenv("CIRCUITPY_WIFI_SSID")
1416
password = os.getenv("CIRCUITPY_WIFI_PASSWORD")
1517

16-
# Initialize WiFi Pool (There can be only 1 pool & top of script)
17-
radio = wifi.radio
18-
pool = socketpool.SocketPool(radio)
19-
20-
print("Connecting to AP...")
21-
while not wifi.radio.ipv4_address:
22-
try:
23-
wifi.radio.connect(ssid, password)
24-
except ConnectionError as e:
25-
print("could not connect to AP, retrying: ", e)
26-
print("Connected to", str(radio.ap_info.ssid, "utf-8"), "\tRSSI:", radio.ap_info.rssi)
27-
28-
# Initialize a requests session
29-
ssl_context = ssl.create_default_context()
18+
# Initalize Wifi, Socket Pool, Request Session
19+
pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
20+
ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
3021
requests = adafruit_requests.Session(pool, ssl_context)
22+
rssi = wifi.radio.ap_info.rssi
3123

24+
# URL for GET request
3225
JSON_GET_URL = "https://httpbin.org/get"
26+
# Define a custom header as a dict.
27+
headers = {"user-agent": "blinka/1.0.0"}
28+
29+
print(f"\nConnecting to {ssid}...")
30+
print(f"Signal Strength: {rssi}")
31+
try:
32+
# Connect to the Wi-Fi network
33+
wifi.radio.connect(ssid, password)
34+
except OSError as e:
35+
print(f"❌ OSError: {e}")
36+
print("✅ Wifi!")
3337

3438
# Define a custom header as a dict.
3539
headers = {"user-agent": "blinka/1.0.0"}
40+
print(f" | Fetching URL {JSON_GET_URL}")
3641

37-
print("Fetching JSON data from %s..." % JSON_GET_URL)
42+
# Use with statement for retreiving GET request data
3843
with requests.get(JSON_GET_URL, headers=headers) as response:
39-
print("-" * 60)
40-
4144
json_data = response.json()
4245
headers = json_data["headers"]
43-
print("Response's Custom User-Agent Header: {0}".format(headers["User-Agent"]))
44-
print("-" * 60)
45-
46-
# Read Response's HTTP status code
47-
print("Response HTTP Status Code: ", response.status_code)
48-
print("-" * 60)
46+
content_type = response.headers.get("content-type", "")
47+
date = response.headers.get("date", "")
48+
if response.status_code == 200:
49+
print(f" | 🆗 Status Code: {response.status_code}")
50+
else:
51+
print(f" | ❌ Status Code: {response.status_code}")
52+
print(f" | | Custom User-Agent Header: {headers['User-Agent']}")
53+
print(f" | | Content-Type: {content_type}")
54+
print(f" | | Response Timestamp: {date}")

0 commit comments

Comments
 (0)