# AIO Throttle: Fetch Example for the PyPortal M4

import adafruit_pyportal

pyportal = adafruit_pyportal.PyPortal(status_neopixel=board.NEOPIXEL, default_bg="/pyportal_startup.bmp")

def get_last_value(feed_key):
    """Fetch the latest value of the AIO feed.
    :param str feed_key: The AIO feed key."""
    try:
        # print(f"throttle limit: {pyportal.network.io_client.get_remaining_throttle_limit()}")
        while pyportal.network.io_client.get_remaining_throttle_limit() <= 10:
            time.sleep(1)  # Wait until throttle limit increases
        last_value = pyportal.network.io_client.receive_data(feed_key)["value"]
        return last_value
    except (KeyError, IndexError) as e:
        print(f"Error fetching data from feed {feed_key}: {e}")