Skip to content

Commit 1def0b6

Browse files
committed
Update YouTube API Example with Connection Manager
1 parent fdf4cbf commit 1def0b6

File tree

1 file changed

+81
-84
lines changed

1 file changed

+81
-84
lines changed
Lines changed: 81 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -1,123 +1,120 @@
1-
# SPDX-FileCopyrightText: 2022 DJDevon3 for Adafruit Industries
1+
# SPDX-FileCopyrightText: 2024 DJDevon3
22
# SPDX-License-Identifier: MIT
3-
# Coded for Circuit Python 8.0
4-
"""DJDevon3 Adafruit Feather ESP32-S2 YouTube_API_Example"""
5-
import gc
6-
import json
3+
# Coded for Circuit Python 8.2.x
4+
"""YouTube API Subscriber Count Example"""
5+
# pylint: disable=import-error
6+
77
import os
8-
import ssl
98
import time
109

11-
import socketpool
10+
import adafruit_connection_manager
1211
import wifi
1312

1413
import adafruit_requests
1514

16-
# Ensure these are uncommented and in secrets.py or .env
17-
# "YT_username": "Your YouTube Username",
18-
# "YT_token" : "Your long API developer token",
19-
20-
# Initialize WiFi Pool (There can be only 1 pool & top of script)
21-
pool = socketpool.SocketPool(wifi.radio)
15+
# Initalize Wifi, Socket Pool, Request Session
16+
pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
17+
ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
18+
requests = adafruit_requests.Session(pool, ssl_context)
2219

23-
# Time between API refreshes
20+
# API Polling Rate
2421
# 900 = 15 mins, 1800 = 30 mins, 3600 = 1 hour
25-
sleep_time = 900
22+
SLEEP_TIME = 900
23+
24+
# Set debug to True for full JSON response.
25+
# WARNING: Will show credentials
26+
DEBUG = False
27+
28+
# Ensure these are uncommented and in settings.toml
29+
# YOUTUBE_USERNAME = "Your YouTube Username",
30+
# YOUTUBE_TOKEN = "Your long API developer token",
2631

2732
# Get WiFi details, ensure these are setup in settings.toml
2833
ssid = os.getenv("CIRCUITPY_WIFI_SSID")
2934
password = os.getenv("CIRCUITPY_WIFI_PASSWORD")
30-
yt_username = os.getenv("YT_username")
31-
yt_token = os.getenv("YT_token")
32-
33-
34-
if sleep_time < 60:
35-
sleep_time_conversion = "seconds"
36-
sleep_int = sleep_time
37-
elif 60 <= sleep_time < 3600:
38-
sleep_int = sleep_time / 60
39-
sleep_time_conversion = "minutes"
40-
elif 3600 <= sleep_time < 86400:
41-
sleep_int = sleep_time / 60 / 60
42-
sleep_time_conversion = "hours"
43-
else:
44-
sleep_int = sleep_time / 60 / 60 / 24
45-
sleep_time_conversion = "days"
35+
# Requires Steam Developer API key
36+
YT_USERNAME = os.getenv("YOUTUBE_USERNAME")
37+
YT_TOKEN = os.getenv("YOUTUBE_TOKEN")
38+
39+
40+
def time_calc(input_time):
41+
"""Converts seconds to minutes/hours/days"""
42+
if input_time < 60:
43+
return f"{input_time:.0f} seconds"
44+
if input_time < 3600:
45+
return f"{input_time / 60:.0f} minutes"
46+
if input_time < 86400:
47+
return f"{input_time / 60 / 60:.0f} hours"
48+
return f"{input_time / 60 / 60 / 24:.1f} days"
49+
4650

4751
# https://youtube.googleapis.com/youtube/v3/channels?part=statistics&forUsername=[YOUR_USERNAME]&key=[YOUR_API_KEY]
48-
YT_SOURCE = (
49-
"https://youtube.googleapis.com/youtube/v3/channels?"
50-
+ "part=statistics"
51-
+ "&forUsername="
52-
+ yt_username
52+
YOUTUBE_SOURCE = (
53+
"https://youtube.googleapis.com/youtube/v3/channels?part=statistics&forUsername="
54+
+ str(YT_USERNAME)
5355
+ "&key="
54-
+ yt_token
56+
+ str(YT_TOKEN)
5557
)
5658

57-
# Connect to Wi-Fi
58-
print("\n===============================")
59-
print("Connecting to WiFi...")
60-
requests = adafruit_requests.Session(pool, ssl.create_default_context())
61-
while not wifi.radio.ipv4_address:
62-
try:
63-
wifi.radio.connect(ssid, password)
64-
except ConnectionError as e:
65-
print("Connection Error:", e)
66-
print("Retrying in 10 seconds")
67-
time.sleep(10)
68-
gc.collect()
69-
print("Connected!\n")
70-
7159
while True:
60+
# Connect to Wi-Fi
61+
print("\nConnecting to WiFi...")
62+
while not wifi.radio.ipv4_address:
63+
try:
64+
wifi.radio.connect(ssid, password)
65+
except ConnectionError as e:
66+
print("❌ Connection Error:", e)
67+
print("Retrying in 10 seconds")
68+
print("✅ Wifi!")
7269
try:
73-
print("Attempting to GET YouTube Stats!") # ----------------------------------
74-
debug_request = False # Set true to see full request
75-
if debug_request:
76-
print("Full API GET URL: ", YT_SOURCE)
77-
print("===============================")
70+
print(" | Attempting to GET YouTube JSON...")
7871
try:
79-
response = requests.get(YT_SOURCE).json()
72+
youtube_response = requests.get(url=YOUTUBE_SOURCE)
73+
youtube_json = youtube_response.json()
8074
except ConnectionError as e:
8175
print("Connection Error:", e)
8276
print("Retrying in 10 seconds")
77+
print(" | ✅ YouTube JSON!")
78+
79+
if DEBUG:
80+
print(f" | Full API GET URL: {YOUTUBE_SOURCE}")
81+
print(f" | Full API Dump: {youtube_json}")
8382

84-
# Print Full JSON to Serial
85-
debug_response = False # Set true to see full response
86-
if debug_response:
87-
dump_object = json.dumps(response)
88-
print("JSON Dump: ", dump_object)
83+
# Key:Value RESPONSES
84+
if "pageInfo" in youtube_json:
85+
totalResults = youtube_json["pageInfo"]["totalResults"]
86+
print(f" | | Matching Results: {totalResults}")
8987

90-
# Print to Serial
91-
yt_debug_keys = True # Set to True to print Serial data
92-
if yt_debug_keys:
93-
print("Matching Results: ", response["pageInfo"]["totalResults"])
88+
if "items" in youtube_json:
89+
YT_request_kind = youtube_json["items"][0]["kind"]
90+
print(f" | | Request Kind: {YT_request_kind}")
9491

95-
YT_request_kind = response["items"][0]["kind"]
96-
print("Request Kind: ", YT_request_kind)
92+
YT_channel_id = youtube_json["items"][0]["id"]
93+
print(f" | | Channel ID: {YT_channel_id}")
9794

98-
YT_response_kind = response["kind"]
99-
print("Response Kind: ", YT_response_kind)
95+
YT_videoCount = youtube_json["items"][0]["statistics"]["videoCount"]
96+
print(f" | | Videos: {YT_videoCount}")
10097

101-
YT_channel_id = response["items"][0]["id"]
102-
print("Channel ID: ", YT_channel_id)
98+
YT_viewCount = youtube_json["items"][0]["statistics"]["viewCount"]
99+
print(f" | | Views: {YT_viewCount}")
103100

104-
YT_videoCount = response["items"][0]["statistics"]["videoCount"]
105-
print("Videos: ", YT_videoCount)
101+
YT_subsCount = youtube_json["items"][0]["statistics"]["subscriberCount"]
102+
print(f" | | Subscribers: {YT_subsCount}")
106103

107-
YT_viewCount = response["items"][0]["statistics"]["viewCount"]
108-
print("Views: ", YT_viewCount)
104+
if "kind" in youtube_json:
105+
YT_response_kind = youtube_json["kind"]
106+
print(f" | | Response Kind: {YT_response_kind}")
109107

110-
YT_subsCount = response["items"][0]["statistics"]["subscriberCount"]
111-
print("Subscribers: ", YT_subsCount)
112-
print("Monotonic: ", time.monotonic())
108+
youtube_response.close()
109+
print("✂️ Disconnected from YouTube API")
113110

114111
print("\nFinished!")
115-
print("Next Update in %s %s" % (int(sleep_int), sleep_time_conversion))
112+
print(f"Board Uptime: {time_calc(time.monotonic())}")
113+
print(f"Next Update: {time_calc(SLEEP_TIME)}")
116114
print("===============================")
117-
gc.collect()
118115

119116
except (ValueError, RuntimeError) as e:
120-
print("Failed to get data, retrying\n", e)
117+
print(f"Failed to get data, retrying\n {e}")
121118
time.sleep(60)
122-
continue
123-
time.sleep(sleep_time)
119+
break
120+
time.sleep(SLEEP_TIME)

0 commit comments

Comments
 (0)