Skip to content

Commit d6006a3

Browse files
authored
Merge pull request #162 from DJDevon3/DJDevon3-DiscordActive
Update Discord Shields.io Example with Connection Manager
2 parents 9371463 + 84d0689 commit d6006a3

File tree

1 file changed

+53
-76
lines changed

1 file changed

+53
-76
lines changed
Lines changed: 53 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,13 @@
1-
# SPDX-FileCopyrightText: 2023 DJDevon3
1+
# SPDX-FileCopyrightText: 2024 DJDevon3
22
# SPDX-License-Identifier: MIT
3-
"""
4-
Coded for Circuit Python 8.2.3
5-
requests_adafruit_discord_active_online
6-
"""
7-
import gc
8-
import json
3+
# Coded for Circuit Python 8.2.x
4+
"""Discord Active Online Shields.IO Example"""
5+
# pylint: disable=import-error
6+
97
import os
10-
import ssl
118
import time
129

13-
import socketpool
10+
import adafruit_connection_manager
1411
import wifi
1512

1613
import adafruit_requests
@@ -19,95 +16,75 @@
1916
# JSON web scrape from SHIELDS.IO
2017
# Adafruit uses Shields.IO to see online users
2118

22-
# Initialize WiFi Pool (There can be only 1 pool & top of script)
23-
pool = socketpool.SocketPool(wifi.radio)
24-
25-
# Time in seconds between updates (polling)
26-
# 600 = 10 mins, 900 = 15 mins, 1800 = 30 mins, 3600 = 1 hour
27-
sleep_time = 900
28-
2919
# Get WiFi details, ensure these are setup in settings.toml
3020
ssid = os.getenv("CIRCUITPY_WIFI_SSID")
3121
password = os.getenv("CIRCUITPY_WIFI_PASSWORD")
3222

23+
# API Polling Rate
24+
# 900 = 15 mins, 1800 = 30 mins, 3600 = 1 hour
25+
SLEEP_TIME = 900
26+
27+
# Initalize Wifi, Socket Pool, Request Session
28+
pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
29+
ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
30+
requests = adafruit_requests.Session(pool, ssl_context)
31+
3332

34-
# Converts seconds to minutes/hours/days
3533
def time_calc(input_time):
34+
"""Converts seconds to minutes/hours/days"""
3635
if input_time < 60:
37-
sleep_int = input_time
38-
time_output = f"{sleep_int:.0f} seconds"
39-
elif 60 <= input_time < 3600:
40-
sleep_int = input_time / 60
41-
time_output = f"{sleep_int:.0f} minutes"
42-
elif 3600 <= input_time < 86400:
43-
sleep_int = input_time / 60 / 60
44-
time_output = f"{sleep_int:.0f} hours"
45-
else:
46-
sleep_int = input_time / 60 / 60 / 24
47-
time_output = f"{sleep_int:.1f} days"
48-
return time_output
36+
return f"{input_time:.0f} seconds"
37+
if input_time < 3600:
38+
return f"{input_time / 60:.0f} minutes"
39+
if input_time < 86400:
40+
return f"{input_time / 60 / 60:.0f} hours"
41+
return f"{input_time / 60 / 60 / 24:.1f} days"
4942

5043

5144
# Originally attempted to use SVG. Found JSON exists with same filename.
5245
# https://img.shields.io/discord/327254708534116352.svg
5346
ADA_DISCORD_JSON = "https://img.shields.io/discord/327254708534116352.json"
5447

55-
# Connect to Wi-Fi
56-
print("\n===============================")
57-
print("Connecting to WiFi...")
58-
requests = adafruit_requests.Session(pool, ssl.create_default_context())
59-
while not wifi.radio.ipv4_address:
60-
try:
61-
wifi.radio.connect(ssid, password)
62-
except ConnectionError as e:
63-
print("Connection Error:", e)
64-
print("Retrying in 10 seconds")
65-
time.sleep(10)
66-
gc.collect()
67-
print("Connected!\n")
68-
6948
while True:
49+
# Connect to Wi-Fi
50+
print("\nConnecting to WiFi...")
51+
while not wifi.radio.ipv4_address:
52+
try:
53+
wifi.radio.connect(ssid, password)
54+
except ConnectionError as e:
55+
print("❌ Connection Error:", e)
56+
print("Retrying in 10 seconds")
57+
print("✅ Wifi!")
7058
try:
71-
print(
72-
"\nAttempting to GET DISCORD SHIELD JSON!"
73-
) # --------------------------------
74-
# Print Request to Serial
75-
debug_request = True # Set true to see full request
76-
if debug_request:
77-
print("Full API GET URL: ", ADA_DISCORD_JSON)
78-
print("===============================")
59+
print(" | Attempting to GET Adafruit Discord JSON!")
60+
# Set debug to True for full JSON response.
61+
DEBUG_RESPONSE = True
62+
7963
try:
80-
ada_response = requests.get(ADA_DISCORD_JSON).json()
64+
shieldsio_response = requests.get(url=ADA_DISCORD_JSON)
65+
shieldsio_json = shieldsio_response.json()
8166
except ConnectionError as e:
82-
print("Connection Error:", e)
67+
print(f"Connection Error: {e}")
8368
print("Retrying in 10 seconds")
69+
print(" | ✅ Adafruit Discord JSON!")
70+
71+
if DEBUG_RESPONSE:
72+
print(" | | Full API GET URL: ", ADA_DISCORD_JSON)
73+
print(" | | JSON Dump: ", shieldsio_json)
8474

85-
# Print Full JSON to Serial
86-
full_ada_json_response = True # Change to true to see full response
87-
if full_ada_json_response:
88-
ada_dump_object = json.dumps(ada_response)
89-
print("JSON Dump: ", ada_dump_object)
90-
91-
# Print Debugging to Serial
92-
ada_debug = True # Set to True to print Serial data
93-
if ada_debug:
94-
ada_users = ada_response["value"]
95-
print("JSON Value: ", ada_users)
96-
online_string = " online"
97-
replace_with_nothing = ""
98-
string_replace_users = ada_users.replace(
99-
online_string, replace_with_nothing
100-
)
101-
print("Replaced Value: ", string_replace_users)
102-
print("Monotonic: ", time.monotonic())
75+
ada_users = shieldsio_json["value"]
76+
ONLINE_STRING = " online"
77+
REPLACE_WITH_NOTHING = ""
78+
active_users = ada_users.replace(ONLINE_STRING, REPLACE_WITH_NOTHING)
79+
print(f" | | Active Online Users: {active_users}")
10380

10481
print("\nFinished!")
105-
print("Next Update: ", time_calc(sleep_time))
82+
print(f"Board Uptime: {time.monotonic()}")
83+
print(f"Next Update: {time_calc(SLEEP_TIME)}")
10684
print("===============================")
107-
gc.collect()
10885

10986
except (ValueError, RuntimeError) as e:
110-
print("Failed to get data, retrying\n", e)
87+
print(f"Failed to get data, retrying\n {e}")
11188
time.sleep(60)
112-
continue
113-
time.sleep(sleep_time)
89+
break
90+
time.sleep(SLEEP_TIME)

0 commit comments

Comments
 (0)