# AIO Throttle: Publish Example for the ESP32-S3

import adafruit_connection_manager
import wifi
import adafruit_requests
from adafruit_io.adafruit_io import IO_HTTP

pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())
io = IO_HTTP(os.getenv("AIO_USERNAME"), os.getenv("AIO_KEY"), requests)

def publish_to_aio(value, feed):
    """Publish a value to an AIO feed, while monitoring checking the throttle
    transaction rate. A blocking method.
    :param union(int, float, str) value: The value to publish.
    :param str feed: The name of the AIO feed.
    """
    try:
        while io.get_remaining_throttle_limit() <= 10:
            time.sleep(1)  # Wait until throttle limit increases
        io.send_data(feed, value)
        print(f"SEND '{value}' -> {feed}")
    except Exception as aio_publish_error:
        print(f"FAIL: '{value}' -> {feed}")
        print(f"  {str(aio_publish_error)}")