|
1 | | -# SPDX-FileCopyrightText: 2022 DJDevon3 (Neradoc & Deshipu helped) for Adafruit Industries |
| 1 | +# SPDX-FileCopyrightText: 2024 DJDevon3 |
2 | 2 | # SPDX-License-Identifier: MIT |
3 | | -# Coded for Circuit Python 8.0 |
4 | | -"""DJDevon3 Adafruit Feather ESP32-S2 api_steam Example""" |
5 | | -import gc |
6 | | -import json |
| 3 | +# Coded for Circuit Python 8.2.x |
| 4 | +"""Steam API Get Owned Games Example""" |
| 5 | +# pylint: disable=import-error |
| 6 | + |
7 | 7 | import os |
8 | | -import ssl |
9 | 8 | import time |
10 | 9 |
|
11 | | -import socketpool |
| 10 | +import adafruit_connection_manager |
12 | 11 | import wifi |
13 | 12 |
|
14 | 13 | import adafruit_requests |
15 | 14 |
|
16 | 15 | # Steam API Docs: https://steamcommunity.com/dev |
17 | 16 | # Steam API Key: https://steamcommunity.com/dev/apikey |
18 | | -# Steam Usernumber: Visit https://steamcommunity.com |
19 | | -# click on your profile icon, your usernumber will be in the browser url. |
| 17 | +# Numerical Steam ID: Visit https://store.steampowered.com/account/ |
| 18 | +# Your account name will be in big bold letters. |
| 19 | +# Your numerical STEAM ID will be below in a very small font. |
20 | 20 |
|
21 | 21 | # Get WiFi details, ensure these are setup in settings.toml |
22 | 22 | ssid = os.getenv("CIRCUITPY_WIFI_SSID") |
23 | 23 | password = os.getenv("CIRCUITPY_WIFI_PASSWORD") |
24 | 24 | # Requires Steam Developer API key |
25 | | -steam_usernumber = os.getenv("steam_id") |
26 | | -steam_apikey = os.getenv("steam_api_key") |
27 | | - |
28 | | -# Initialize WiFi Pool (There can be only 1 pool & top of script) |
29 | | -pool = socketpool.SocketPool(wifi.radio) |
| 25 | +steam_usernumber = os.getenv("STEAM_ID") |
| 26 | +steam_apikey = os.getenv("STEAM_API_KEY") |
30 | 27 |
|
31 | | -# Time between API refreshes |
| 28 | +# API Polling Rate |
32 | 29 | # 900 = 15 mins, 1800 = 30 mins, 3600 = 1 hour |
33 | | -sleep_time = 900 |
| 30 | +SLEEP_TIME = 3600 |
| 31 | + |
| 32 | +# Set debug to True for full JSON response. |
| 33 | +# WARNING: Steam's full response will overload most microcontrollers |
| 34 | +# SET TO TRUE IF YOU FEEL BRAVE =) |
| 35 | +DEBUG = False |
| 36 | + |
| 37 | +# Initalize Wifi, Socket Pool, Request Session |
| 38 | +pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio) |
| 39 | +ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio) |
| 40 | +requests = adafruit_requests.Session(pool, ssl_context) |
34 | 41 |
|
35 | 42 | # Deconstruct URL (pylint hates long lines) |
36 | 43 | # http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/ |
37 | 44 | # ?key=XXXXXXXXXXXXXXXXXXXXX&include_played_free_games=1&steamid=XXXXXXXXXXXXXXXX&format=json |
38 | | -Steam_OwnedGames_URL = ( |
| 45 | +STEAM_SOURCE = ( |
39 | 46 | "http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?" |
40 | 47 | + "key=" |
41 | 48 | + steam_apikey |
|
45 | 52 | + "&format=json" |
46 | 53 | ) |
47 | 54 |
|
48 | | -if sleep_time < 60: |
49 | | - sleep_time_conversion = "seconds" |
50 | | - sleep_int = sleep_time |
51 | | -elif 60 <= sleep_time < 3600: |
52 | | - sleep_int = sleep_time / 60 |
53 | | - sleep_time_conversion = "minutes" |
54 | | -elif 3600 <= sleep_time < 86400: |
55 | | - sleep_int = sleep_time / 60 / 60 |
56 | | - sleep_time_conversion = "hours" |
57 | | -else: |
58 | | - sleep_int = sleep_time / 60 / 60 / 24 |
59 | | - sleep_time_conversion = "days" |
60 | | - |
61 | | -# Connect to Wi-Fi |
62 | | -print("\n===============================") |
63 | | -print("Connecting to WiFi...") |
64 | | -requests = adafruit_requests.Session(pool, ssl.create_default_context()) |
65 | | -while not wifi.radio.ipv4_address: |
66 | | - try: |
67 | | - wifi.radio.connect(ssid, password) |
68 | | - except ConnectionError as e: |
69 | | - print("Connection Error:", e) |
70 | | - print("Retrying in 10 seconds") |
71 | | - time.sleep(10) |
72 | | - gc.collect() |
73 | | -print("Connected!\n") |
| 55 | + |
| 56 | +def time_calc(input_time): |
| 57 | + """Converts seconds to minutes/hours/days""" |
| 58 | + if input_time < 60: |
| 59 | + return f"{input_time:.0f} seconds" |
| 60 | + if input_time < 3600: |
| 61 | + return f"{input_time / 60:.0f} minutes" |
| 62 | + if input_time < 86400: |
| 63 | + return f"{input_time / 60 / 60:.0f} hours" |
| 64 | + return f"{input_time / 60 / 60 / 24:.1f} days" |
| 65 | + |
| 66 | + |
| 67 | +def _format_datetime(datetime): |
| 68 | + """F-String formatted struct time conversion""" |
| 69 | + return ( |
| 70 | + f"{datetime.tm_mon:02}/" |
| 71 | + + f"{datetime.tm_mday:02}/" |
| 72 | + + f"{datetime.tm_year:02} " |
| 73 | + + f"{datetime.tm_hour:02}:" |
| 74 | + + f"{datetime.tm_min:02}:" |
| 75 | + + f"{datetime.tm_sec:02}" |
| 76 | + ) |
| 77 | + |
74 | 78 |
|
75 | 79 | while True: |
| 80 | + # Connect to Wi-Fi |
| 81 | + print("\nConnecting to WiFi...") |
| 82 | + while not wifi.radio.ipv4_address: |
| 83 | + try: |
| 84 | + wifi.radio.connect(ssid, password) |
| 85 | + except ConnectionError as e: |
| 86 | + print("❌ Connection Error:", e) |
| 87 | + print("Retrying in 10 seconds") |
| 88 | + print("✅ Wifi!") |
| 89 | + |
76 | 90 | try: |
77 | | - print("\nAttempting to GET STEAM Stats!") # -------------------------------- |
78 | | - # Print Request to Serial |
79 | | - debug_request = False # Set true to see full request |
80 | | - if debug_request: |
81 | | - print("Full API GET URL: ", Steam_OwnedGames_URL) |
82 | | - print("===============================") |
| 91 | + print(" | Attempting to GET Steam API JSON!") |
83 | 92 | try: |
84 | | - steam_response = requests.get(url=Steam_OwnedGames_URL).json() |
| 93 | + steam_response = requests.get(url=STEAM_SOURCE) |
| 94 | + steam_json = steam_response.json() |
85 | 95 | except ConnectionError as e: |
86 | 96 | print("Connection Error:", e) |
87 | 97 | print("Retrying in 10 seconds") |
88 | 98 |
|
89 | | - # Print Response to Serial |
90 | | - debug_response = False # Set true to see full response |
91 | | - if debug_response: |
92 | | - dump_object = json.dumps(steam_response) |
93 | | - print("JSON Dump: ", dump_object) |
94 | | - |
95 | | - # Print Keys to Serial |
96 | | - steam_debug_keys = True # Set True to print Serial data |
97 | | - if steam_debug_keys: |
98 | | - game_count = steam_response["response"]["game_count"] |
99 | | - print("Total Games: ", game_count) |
100 | | - total_minutes = 0 |
101 | | - |
102 | | - for game in steam_response["response"]["games"]: |
103 | | - total_minutes += game["playtime_forever"] |
104 | | - total_hours = total_minutes / 60 |
105 | | - total_days = total_minutes / 60 / 24 |
106 | | - print(f"Total Hours: {total_hours}") |
107 | | - print(f"Total Days: {total_days}") |
108 | | - |
109 | | - print("Monotonic: ", time.monotonic()) |
| 99 | + print(" | ✅ Steam JSON!") |
| 100 | + |
| 101 | + if DEBUG: |
| 102 | + print("Full API GET URL: ", STEAM_SOURCE) |
| 103 | + print(steam_json) |
| 104 | + |
| 105 | + game_count = steam_json["response"]["game_count"] |
| 106 | + print(f" | | Total Games: {game_count}") |
| 107 | + TOTAL_MINUTES = 0 |
| 108 | + |
| 109 | + for game in steam_json["response"]["games"]: |
| 110 | + TOTAL_MINUTES += game["playtime_forever"] |
| 111 | + total_hours = TOTAL_MINUTES / 60 |
| 112 | + total_days = TOTAL_MINUTES / 60 / 24 |
| 113 | + total_years = TOTAL_MINUTES / 60 / 24 / 365 |
| 114 | + print(f" | | Total Hours: {total_hours}") |
| 115 | + print(f" | | Total Days: {total_days}") |
| 116 | + print(f" | | Total Years: {total_years:.2f}") |
| 117 | + |
| 118 | + steam_response.close() |
| 119 | + print("✂️ Disconnected from Steam API") |
| 120 | + |
110 | 121 | print("\nFinished!") |
111 | | - print("Next Update in %s %s" % (int(sleep_int), sleep_time_conversion)) |
| 122 | + print(f"Board Uptime: {time_calc(time.monotonic())}") |
| 123 | + print(f"Next Update: {time_calc(SLEEP_TIME)}") |
112 | 124 | print("===============================") |
113 | | - gc.collect() |
114 | 125 |
|
115 | 126 | except (ValueError, RuntimeError) as e: |
116 | | - print("Failed to get data, retrying\n", e) |
| 127 | + print(f"Failed to get data, retrying\n {e}") |
117 | 128 | time.sleep(60) |
118 | | - continue |
119 | | - time.sleep(sleep_time) |
| 129 | + break |
| 130 | + time.sleep(SLEEP_TIME) |
0 commit comments