forked from adafruit/Adafruit_CircuitPython_Requests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequests_wifi_simpletest.py
62 lines (50 loc) · 2.01 KB
/
requests_wifi_simpletest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
# Updated for Circuit Python 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!")