Skip to content

Commit ccc38de

Browse files
authored
Merge pull request #127 from adafruit/tyeth/issue126
Add Current User info methods
2 parents 99bd004 + 69b0501 commit ccc38de

File tree

3 files changed

+134
-1
lines changed

3 files changed

+134
-1
lines changed

Diff for: .pylintrc

+1-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ confidence=
5555
# no Warning level messages displayed, use"--disable=all --enable=classes
5656
# --disable=W"
5757
# disable=import-error,raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,deprecated-str-translate-call
58-
disable=raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,import-error,pointless-string-statement,unspecified-encoding
58+
disable=raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,import-error,pointless-string-statement,unspecified-encoding,too-many-public-methods
5959

6060
# Enable the message, report, category or checker with the given id(s). You can
6161
# either give multiple identifier separated by comma (,) or put this option

Diff for: adafruit_io/adafruit_io.py

+71
Original file line numberDiff line numberDiff line change
@@ -855,6 +855,77 @@ def receive_random_data(self, generator_id: int):
855855
path = self._compose_path("integrations/words/{0}".format(generator_id))
856856
return self._get(path)
857857

858+
def get_user_info(self):
859+
"""
860+
Get detailed account information for the current user.
861+
862+
See https://io.adafruit.com/api/docs/#get-user-info
863+
"""
864+
return self._get("https://io.adafruit.com/api/v2/user")
865+
866+
def get_user_rate_info(self):
867+
"""
868+
Get rate limit and usage information for the current user.
869+
870+
See https://io.adafruit.com/api/docs/#get-detailed-user-info
871+
872+
Example output:
873+
```
874+
{
875+
"data_rate_limit": 30,
876+
"active_data_rate": 0,
877+
"authentication_rate": 0,
878+
"subscribe_authorization_rate": 0,
879+
"publish_authorization_rate": 0,
880+
"hourly_ban_rate": 0,
881+
"mqtt_ban_error_message": null,
882+
"active_sms_rate": 0
883+
}
884+
```
885+
"""
886+
path = self._compose_path("throttle")
887+
return self._get(path)
888+
889+
def get_remaining_throttle_limit(self):
890+
"""
891+
Get the remaining data points allowed before hitting the throttle limit.
892+
This retrieves the user rate limit and deducts usage for the current user.
893+
894+
See https://io.adafruit.com/api/docs/#get-detailed-user-info
895+
"""
896+
user_rates = self.get_user_rate_info()
897+
if user_rates is None:
898+
raise ValueError(
899+
"Could not get user info, get_user_rate_info returned None."
900+
)
901+
return user_rates["data_rate_limit"] - user_rates["active_data_rate"]
902+
903+
def get_throttle_limit(self):
904+
"""
905+
Get user throttle limit a.k.a "data_rate_limit" for the current user.
906+
907+
See https://io.adafruit.com/api/docs/#get-detailed-user-info
908+
"""
909+
user_rates = self.get_user_rate_info()
910+
if user_rates is None:
911+
raise ValueError(
912+
"Could not get user info, get_user_rate_info returned None."
913+
)
914+
return user_rates["data_rate_limit"]
915+
916+
def get_current_usage(self):
917+
"""
918+
Get current rate usage a.k.a "active_data_rate" for the current user.
919+
920+
See https://io.adafruit.com/api/docs/#get-detailed-user-info
921+
"""
922+
user_rates = self.get_user_rate_info()
923+
if user_rates is None:
924+
raise ValueError(
925+
"Could not get user info, get_user_rate_info returned None."
926+
)
927+
return user_rates["active_data_rate"]
928+
858929
def receive_time(self, timezone: str = None):
859930
"""
860931
Returns a struct_time from the Adafruit IO Server based on the device's IP address.

Diff for: examples/adafruit_io_http/adafruit_io_user_info.py

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# SPDX-FileCopyrightText: 2024 Tyeth Gundry for Adafruit Industries
2+
# SPDX-License-Identifier: MIT
3+
4+
# retrieve user rate info via adafruit_circuitpython_adafruitio with native wifi networking
5+
import ssl
6+
import time # pylint: disable=unused-import
7+
import adafruit_requests
8+
import socketpool
9+
import wifi
10+
from adafruit_io.adafruit_io import IO_HTTP
11+
12+
# Add a secrets.py to your filesystem that has a dictionary called secrets with "ssid" and
13+
# "password" keys with your WiFi credentials. DO NOT share that file or commit it into Git or other
14+
# source control.
15+
16+
# pylint: disable=no-name-in-module,wrong-import-order
17+
try:
18+
from secrets import secrets
19+
except ImportError:
20+
print("WiFi secrets are kept in secrets.py, please add them there!")
21+
raise
22+
23+
# Set your Adafruit IO Username and Key in secrets.py
24+
# (visit io.adafruit.com if you need to create an account,
25+
# or if you need your Adafruit IO key.)
26+
aio_username = secrets["aio_username"]
27+
aio_key = secrets["aio_key"]
28+
29+
print("Connecting to %s" % secrets["ssid"])
30+
wifi.radio.connect(secrets["ssid"], secrets["password"])
31+
print("Connected to %s!" % secrets["ssid"])
32+
33+
34+
pool = socketpool.SocketPool(wifi.radio)
35+
requests = adafruit_requests.Session(pool, ssl.create_default_context())
36+
# Initialize an Adafruit IO HTTP API object
37+
io = IO_HTTP(aio_username, aio_key, requests)
38+
39+
print("===============\nUser Rate info:\n===============")
40+
print("\n".join([f"{k:<30}\t=\t{v}" for (k, v) in io.get_user_rate_info().items()]))
41+
42+
print(f"Throttle limit: {io.get_throttle_limit()}")
43+
print(f"Remaining throttle limit: {io.get_remaining_throttle_limit()}")
44+
45+
46+
# # Uncomment these lines to retrieve all user info as one big json object:
47+
# print("Waiting 5seconds before fetching full user info (a lot of JSON output)")
48+
# time.sleep(5)
49+
# try:
50+
# print("\n\nFull User info:")
51+
# print(io.get_user_info())
52+
# except MemoryError as me:
53+
# print(
54+
# "Board ran out of memory when processing all that user info json."
55+
# + "This is expected on most boards (ESP32-S3 should work)"
56+
# )
57+
# raise me
58+
# except Exception as e:
59+
# print("Unexpected error!")
60+
# raise e
61+
62+
print("\n\nDone!")

0 commit comments

Comments
 (0)