### Basic Setup with get_rest_devices Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/README.md Initializes the API client, MQTT connection, and retrieves a list of connected devices. Useful for starting any interaction with the Hatch API. ```python from hatch_rest_api import get_rest_devices api, mqtt_conn, devices, expiration = await get_rest_devices( email="user@example.com", password="password" ) for device in devices: print(f"{device.device_name}: {device.is_online}") ``` -------------------------------- ### Full Example with Error Handling and Callbacks Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/bootstrap.md A comprehensive example showing `get_rest_devices` usage within a full application structure, including detailed error handling for authentication, base errors, and network issues, along with device callback registration. ```python import asyncio from hatch_rest_api import get_rest_devices, AuthError, BaseError from aiohttp import ClientError async def initialize_hatch(): try: api, mqtt_conn, devices, expiration = await get_rest_devices( email="user@example.com", password="password" ) # Device is ready for use for device in devices: device.register_callback(on_device_update) return api, mqtt_conn, devices except AuthError: print("Invalid login credentials") raise except BaseError as e: print(f"Failed to initialize Hatch: {e}") raise except ClientError as e: print(f"Network error: {e}") raise async def on_device_update(): print("Device state updated") async def main(): try: api, mqtt_conn, devices = await initialize_hatch() # Use devices here device = devices[0] device.set_volume(50) finally: # Always cleanup await api.cleanup_client_session() asyncio.run(main()) ``` -------------------------------- ### Example: Set Clock Brightness Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/device-classes.md Demonstrates setting both daytime and nighttime brightness for the clock. ```python await device.set_clock(daytime_brightness=100, nighttime_brightness=30) ``` -------------------------------- ### Old Python Package Installation and Upload Source: https://github.com/dahlb/hatch_rest_api/blob/main/RELEASE.md This snippet shows the traditional method for installing a Python package and uploading it to a repository. ```bash python setup.py install twine upload dist/* ``` -------------------------------- ### Example: Set Alarm Weekdays Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/device-classes.md Demonstrates how to set specific weekdays for an alarm. ```python await device.set_alarm_weekdays( alarm_id=1, weekdays=["monday", "tuesday", "wednesday", "thursday", "friday"] ) ``` -------------------------------- ### Basic Usage of get_rest_devices Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/bootstrap.md A fundamental example demonstrating how to call `get_rest_devices` with email and password, and then iterate through the discovered devices. ```python from hatch_rest_api import get_rest_devices try: api, mqtt_conn, devices, expiration = await get_rest_devices( email="user@example.com", password="password" ) print(f"Found {len(devices)} devices") print(f"AWS credentials expire at: {expiration}") for device in devices: print(f"- {device.device_name}: {device.__class__.__name__}") if hasattr(device, 'alarms'): print(f" Alarms: {len(device.alarms)}") finally: # Cleanup await api.cleanup_client_session() ``` -------------------------------- ### Get Favorite Routine Names Example Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/device-classes.md Demonstrates how to call the favorite_names method to get a list of favorite routine names. ```python names = device.favorite_names() # ["Naptime-123", "Bedtime-456"] ``` -------------------------------- ### RestBaby set_sound Examples Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/device-classes.md Demonstrates setting sounds using different input types: a SoundContent object, a sound ID, and a sound title. ```python # By sound object baby.set_sound(sounds[0]) # By sound ID baby.set_sound(10518) # By sound title baby.set_sound("Heartbeat") ``` -------------------------------- ### Complete Hatch API Initialization Example Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/configuration.md Demonstrates the full initialization process for the Hatch API, including setting up MQTT callbacks, handling authentication errors, and registering device update callbacks. ```python import asyncio import logging from hatch_rest_api import get_rest_devices, AuthError, BaseError # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) async def setup_hatch_devices(): """Initialize Hatch API and devices.""" # MQTT connection callbacks def on_interrupt(): logger.warning("MQTT connection interrupted") def on_resume(): logger.info("MQTT connection resumed") # Bootstrap try: api, mqtt_conn, devices, expiration = await get_rest_devices( email="user@example.com", password="password", on_connection_interrupted=on_interrupt, on_connection_resumed=on_resume, ) logger.info(f"Connected to {len(devices)} devices") logger.info(f"AWS credentials expire at: {expiration}") # Register state change callbacks on each device for device in devices: device.register_callback(lambda: on_device_update(device)) return api, mqtt_conn, devices except AuthError: logger.error("Invalid Hatch credentials") raise except BaseError as e: logger.error(f"Failed to initialize Hatch: {e}") raise except Exception as e: logger.error(f"Unexpected error: {e}") raise async def on_device_update(device): """Called when device state changes.""" logger.debug(f"Device {device.device_name} updated") async def main(): api = None try: api, mqtt_conn, devices = await setup_hatch_devices() # Use devices... for device in devices: print(f"{device.device_name}: online={device.is_online}") # Keep running (handle device updates) await asyncio.sleep(3600) except Exception as e: logger.error(f"Application error: {e}") return 1 finally: # Cleanup if api: await api.cleanup_client_session() logger.info("Shutdown complete") return 0 if __name__ == "__main__": exit_code = asyncio.run(main()) exit(exit_code) ``` -------------------------------- ### RestBaby set_sound_url Example Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/device-classes.md Shows how to use the set_sound_url method to play a sound from a custom MP3 URL. ```python baby.set_sound_url("https://example.com/sound.mp3") ``` -------------------------------- ### RIoTAudioTrack sound_url_map Example Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/constants.md Demonstrates how to retrieve the audio file URL for a specific RIoT device track using its value. ```python track = RIoTAudioTrack.Ocean url_map = RIoTAudioTrack.sound_url_map() url = url_map[track.value] ``` -------------------------------- ### Clock Flags Usage Example Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/constants.md Demonstrates how to use clock flag constants to check, set, or toggle the clock display status on a device. Requires importing the relevant flag. ```python from hatch_rest_api.const import RIOT_FLAGS_CLOCK_ON # Check if clock is on if device.flags & RIOT_FLAGS_CLOCK_ON: print("Clock is enabled") # Turn on clock (set bit) new_flags = device.flags | RIOT_FLAGS_CLOCK_ON # Turn off clock (toggle bit) new_flags = device.flags ^ RIOT_FLAGS_CLOCK_ON ``` -------------------------------- ### Type Hinting for Device Objects Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/configuration.md Utilize the `RestDevice` union type for flexible handling of different device capabilities. This example shows how to check for and use light-specific methods. ```python from hatch_rest_api import RestDevice def handle_device(device: RestDevice): if hasattr(device, 'set_color'): # Light-capable device.set_color(255, 0, 0, brightness=100) ``` -------------------------------- ### RestMini: Set Audio Track Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/device-classes.md Starts playing a specific audio track on a RestMini device. Pass RestMiniAudioTrack.NONE to stop playback. ```python from hatch_rest_api import RestMiniAudioTrack mini.set_audio_track(RestMiniAudioTrack.Heartbeat) ``` -------------------------------- ### Fetch Saved Routines Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/hatch.md Get a list of all saved routines for a particular device, using its MAC address and a valid authentication token. ```python routines = await hatch_api.routines(auth_token=token, mac="AA:BB:CC:DD:EE:FF") ``` -------------------------------- ### AuthError Usage Example Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/errors.md Demonstrates catching AuthError during login attempts, typically due to invalid credentials. This indicates a need to re-prompt the user for authentication. ```python from hatch_rest_api import AuthError try: token = await api.login(email="user@example.com", password="wrong") except AuthError: print("Invalid credentials") ``` -------------------------------- ### Scheduled Routine Alarm Usage Example Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/types.md Demonstrates how to retrieve scheduled alarms using `api.scheduled_routines()`, access alarm details, and update an alarm's enabled status using `device.set_alarm_enabled()`. Ensure necessary imports are included. ```python from hatch_rest_api.scheduled_routine import ( ScheduledRoutineAlarm, days_of_week_label, ) alarms = await api.scheduled_routines(auth_token=token, mac=mac, types=["alarm"]) alarm: ScheduledRoutineAlarm = alarms[0] print(f"Alarm: {alarm['name']} at {alarm['endTime']}") print(f"Days: {days_of_week_label(alarm['daysOfWeek'])}") # "Weekdays", "Weekends", etc. # Update alarm await device.set_alarm_enabled(alarm['id'], enabled=True) ``` -------------------------------- ### BaseError Usage Example Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/errors.md Demonstrates how to catch BaseError when interacting with the Hatch API. This is useful for handling generic API errors or unexpected response formats. ```python from hatch_rest_api import BaseError try: devices = await api.iot_devices(auth_token=token) except BaseError as e: print(f"Hatch API error: {e}") ``` -------------------------------- ### Get Rest Devices Return Value Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/bootstrap.md The structure of the tuple returned by `get_rest_devices`, detailing the API client, MQTT connection, device list, and credential expiration. ```python ( api: Hatch, mqtt_connection: MqttConnection, devices: list[RestDevice], expiration: str, ) ``` -------------------------------- ### Device Type Checking with isinstance Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/README.md Use `isinstance()` to determine the specific type of a device and access its unique features. This example demonstrates branching logic for different device types. ```python from hatch_rest_api import RestBaby, RestPlus for device in devices: if isinstance(device, RestBaby): # Full features device.set_sound("Heartbeat") elif isinstance(device, RestPlus): # Light + audio device.set_color(255, 0, 0, brightness=100) else: # Basic audio only device.set_volume(50) ``` -------------------------------- ### Handling Multiple aiohttp Client Errors Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/errors.md An example demonstrating how to catch various specific errors including AuthError, RateError, and the generic aiohttp.ClientError during API interactions. ```python from aiohttp import ClientError from hatch_rest_api import RateError, AuthError try: token = await api.login(email=email, password=password) except AuthError: print("Invalid credentials") except RateError: print("Rate limited, retry later") except ClientError as e: print(f"Network error: {e}") ``` -------------------------------- ### Correctly Await Async API Methods Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/README.md All public API methods are asynchronous and must be awaited. This example shows the correct usage within an async function. ```python # ✓ Correct token = await api.login(email, password) # ✗ Wrong token = api.login(email, password) # Use in async context async def main(): api, mqtt_conn, devices, _ = await get_rest_devices(...) ... asyncio.run(main()) ``` -------------------------------- ### Manual AWS IoT Configuration Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/configuration.md Manually configures AWS IoT connection using credentials obtained from the Hatch API. This is an advanced setup for direct AWS IoT interaction. ```python from awscrt import io, auth from awsiot.iotshadow import IotShadowClient from awsiot.mqtt_connection_builder import websockets_with_default_aws_signing # Get credentials from Hatch API aws_http = AwsHttp() aws_creds = await aws_http.aws_credentials( region=aws_token["region"], identityId=aws_token["identityId"], aws_token=aws_token["token"], ) # Create credentials provider credentials_provider = auth.AwsCredentialsProvider.new_static( aws_creds["Credentials"]["AccessKeyId"], aws_creds["Credentials"]["SecretKey"], session_token=aws_creds["Credentials"]["SessionToken"], ) # Setup connection event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) mqtt_connection = websockets_with_default_aws_signing( region=aws_token["region"], credentials_provider=credentials_provider, keep_alive_secs=30, client_bootstrap=client_bootstrap, endpoint=aws_token["endpoint"], client_id="hatch_rest_api/user/unique_id", ) mqtt_connection.connect().result() # Use with devices shadow_client = IotShadowClient(mqtt_connection) ``` -------------------------------- ### Get Rest Devices Function Signature Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/bootstrap.md The signature for the `get_rest_devices` function, outlining its parameters and their types. ```python async def get_rest_devices( email: str, password: str, client_session: ClientSession = None, on_connection_interrupted=None, on_connection_resumed=None, ) ``` -------------------------------- ### Initialize Hatch Client Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/configuration.md Create an instance of the Hatch client. You can use a default aioiohttp ClientSession or provide an existing one for connection pooling and lifecycle control. ```python from aiohttp import ClientSession from hatch_rest_api import Hatch # Create with default session api = Hatch() # Or provide existing session async with ClientSession() as session: api = Hatch(client_session=session) # Use api... await api.cleanup_client_session() ``` -------------------------------- ### Get Alarm by ID Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/device-classes.md Retrieves a specific alarm by its ID. Returns None if the alarm is not found. ```python def alarm_by_id(self, alarm_id: int | str) -> ScheduledRoutineAlarm | None ``` -------------------------------- ### Using SoundContent with API Data Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/types.md Demonstrates fetching sound content using the API and then casting the first item to the SoundContent type for device interaction. Requires authentication and product context. ```python from hatch_rest_api import SoundContent # Fetch sounds sounds = await api.content(auth_token=token, product="riot", content=["sound"]) # Use SoundContent to set sound sound: SoundContent = sounds["contentItems"][0] device.set_sound(sound) ``` -------------------------------- ### get_rest_devices Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/bootstrap.md Handles complete initialization: authentication, device discovery, AWS IoT connection, and device object creation. It automatically logs in, fetches devices and credentials, establishes an MQTT connection, and subscribes to shadow updates. ```APIDOC ## get_rest_devices ### Description High-level async function that handles complete initialization: authentication, device discovery, AWS IoT connection, and device object creation. It automatically logs in, fetches paired devices, retrieves AWS IoT credentials, configures MQTT connection, and subscribes to shadow updates. ### Method Asynchronous Function Call ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Function Signature ```python async def get_rest_devices( email: str, password: str, client_session: ClientSession = None, on_connection_interrupted=None, on_connection_resumed=None, ) ``` #### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | email | str | Yes | — | Hatch account email | | password | str | Yes | — | Hatch account password | | client_session | aiohttp.ClientSession | No | None | Existing aiohttp session, creates new if None | | on_connection_interrupted | callable | No | None | Callback when MQTT connection drops | | on_connection_resumed | callable | No | None | Callback when MQTT connection resumes | ### Returns **Tuple of four elements:** ```python ( api: Hatch, mqtt_connection: MqttConnection, devices: list[RestDevice], expiration: str, ) ``` | Element | Type | Description | |---------|------|-------------| | api | Hatch | Authenticated API client for REST operations | | mqtt_connection | MqttConnection | Connected MQTT client for device shadow updates | | devices | list[RestDevice] | List of initialized device objects | | expiration | str | AWS credential expiration timestamp | ### Device Discovery Automatically creates appropriate device class instances based on product type: - **restMini** → `RestMini` - **restPlus** → `RestPlus` - **riot** or **riotPlus** → `RestIot` - **restBaby** → `RestBaby` - **restoreIot** → `RestoreIot` (with alarm API configured) - **restoreV4** → `RestoreV4` (with alarm API configured) - **restoreV5** → `RestoreV5` (with alarm API configured) ### Automatic Setup The function automatically: 1. Logs in with provided credentials 2. Fetches all paired devices 3. Retrieves AWS IoT credentials 4. Fetches favorites and routines for each device 5. Fetches scheduled alarms (for alarm-capable devices) 6. Loads sound content libraries 7. Establishes MQTT connection 8. Subscribes to shadow updates 9. Configures alarm API on compatible devices ### Error Handling **Raises:** - `BaseError` - If no compatible devices found or initial login fails - `AuthError` - If credentials are invalid - `Exception` - If MQTT connection fails ### Usage Example ```python from hatch_rest_api import get_rest_devices try: api, mqtt_conn, devices, expiration = await get_rest_devices( email="user@example.com", password="password" ) print(f"Found {len(devices)} devices") print(f"AWS credentials expire at: {expiration}") for device in devices: print(f"- {device.device_name}: {device.__class__.__name__}") if hasattr(device, 'alarms'): print(f" Alarms: {len(device.alarms)}") finally: # Cleanup await api.cleanup_client_session() ``` ### Connection Callbacks Example ```python def on_interrupt(): print("MQTT connection interrupted") def on_resume(): print("MQTT connection resumed") api, mqtt_conn, devices, expiration = await get_rest_devices( email=email, password=password, on_connection_interrupted=on_interrupt, on_connection_resumed=on_resume, ) ``` ### Handling Rate Limits The function includes internal retry logic for rate-limited endpoints. If sounds fail to load due to rate limiting, the device proceeds with an empty sounds list. ```python # Inside get_rest_devices, sound loading includes: # try: # sounds = await api.content(...) # except RateError: # sounds = [] # Continue without sounds ``` ``` -------------------------------- ### Usage with Connection Callbacks Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/bootstrap.md Demonstrates how to provide callback functions for MQTT connection interruption and resumption when initializing devices with `get_rest_devices`. ```python def on_interrupt(): print("MQTT connection interrupted") def on_resume(): print("MQTT connection resumed") api, mqtt_conn, devices, expiration = await get_rest_devices( email=email, password=password, on_connection_interrupted=on_interrupt, on_connection_resumed=on_resume, ) ``` -------------------------------- ### Discover REST Devices Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/INDEX.md Initialize the API client and discover connected devices. This function sets up the MQTT connection and returns device information. ```python api, mqtt_conn, devices, expiration = await get_rest_devices(email, password) ``` -------------------------------- ### AWS Cognito Response Format Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/bootstrap.md Example of the expected response format when exchanging a Hatch API token for AWS IoT credentials. ```json { "Credentials": { "AccessKeyId": "...", "SecretKey": "...", "SessionToken": "...", }, "IdentityId": "...", "Expiration": "2024-12-31T12:00:00Z", } ``` -------------------------------- ### RateError Usage Example Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/errors.md Shows how to catch RateError when the API rate limit is exceeded. Note that Hatch.content() and Contentful.graphql_query() retry automatically. ```python from hatch_rest_api import RateError try: sounds = await api.content(auth_token=token, product="riot", content=["sound"]) except RateError: print("Too many requests. Wait before retrying.") ``` -------------------------------- ### Audio Track Constants and Usage Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/constants.md Demonstrates how to work with audio tracks, including retrieving all available tracks, creating a track from its ID, and setting or stopping audio playback on a device. ```python from hatch_rest_api import RestMiniAudioTrack, REST_MINI_AUDIO_TRACKS # Get all available tracks all_tracks = REST_MINI_AUDIO_TRACKS # Create track from value track = RestMiniAudioTrack(10124) # Heartbeat # Play on device device.set_audio_track(track) # Stop playing device.set_audio_track(RestMiniAudioTrack.NONE) ``` -------------------------------- ### RestIot Constructor Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/device-classes.md Initializes a RestIot device instance. Requires device details and an IoT shadow client. ```python def __init__( self, device_name: str, thing_name: str, mac: str, shadow_client: IotShadowClient, favorites: list | None = None, sounds: list[SoundContent | SimpleSoundContent] | None = None, ) ``` -------------------------------- ### Full Import Paths Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/INDEX.md Illustrates the required import paths for using the Hatch library and its components. ```python from hatch_rest_api import Hatch from hatch_rest_api.scheduled_routine import ScheduledRoutineAlarm ``` -------------------------------- ### Get Alarm Scheduled Routines Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/hatch.md Retrieves scheduled routines filtered by type 'alarm'. Requires an authentication token and device MAC address. ```python alarms = await hatch_api.scheduled_routines(auth_token=token, mac="AA:BB:BB:CC:DD:EE:FF", types=["alarm"]) ``` -------------------------------- ### Initialize Hatch API Client Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/hatch.md Instantiate the Hatch API client. You can either let it create a default aiohttp ClientSession or provide an existing one. ```python from aiohttp import ClientSession from hatch_rest_api import Hatch # Using default client session hatch_api = Hatch() # Using existing client session async with ClientSession() as session: hatch_api = Hatch(client_session=session) ``` -------------------------------- ### Bootstrap REST Devices Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/configuration.md Retrieve device information and establish MQTT connections. This function can accept callbacks for MQTT connection interruptions and resumptions. ```python from hatch_rest_api import get_rest_devices api, mqtt_conn, devices, expiration = await get_rest_devices( email="user@example.com", password="password", client_session=None, on_connection_interrupted=None, on_connection_resumed=None, ) ``` -------------------------------- ### Correct Async/Await Usage Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/INDEX.md Demonstrates the correct usage of async/await syntax for API calls. Ensure your functions are marked as async and use await when calling asynchronous methods. ```python # ✓ Correct result = await api.login(email, password) ``` ```python # ✗ Wrong result = api.login(email, password) ``` -------------------------------- ### Get AWS IoT Credentials Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/hatch.md Obtain AWS IoT credentials and endpoint information necessary for MQTT shadow communication. This requires a valid authentication token. ```python aws_creds = await hatch_api.token(auth_token=token) # Returns: {"region": "...", "endpoint": "...", "identityId": "...", "token": "..."} ``` -------------------------------- ### New Python Package Build and Upload Process Source: https://github.com/dahlb/hatch_rest_api/blob/main/RELEASE.md This snippet details the modern approach to building and uploading Python packages using the 'build' and 'twine' tools. ```bash python3 -m pip install --upgrade build python3 -m build python3 -m twine upload dist/* ``` -------------------------------- ### Color Constants and Usage Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/constants.md Shows how to set a custom color on a device using RGB values and brightness, and how to check if the light is currently on using the NO_COLOR_ID constant. ```python from hatch_rest_api.const import NO_COLOR_ID, CUSTOM_COLOR_ID from hatch_rest_api.util import convert_from_hex, convert_from_percentage # Set custom color device.set_color( red=255, green=100, blue=50, brightness=80 ) # Check if light is on if device.color_id != NO_COLOR_ID: print(f"Light is on, color_id={device.color_id}") ``` -------------------------------- ### Iterate and Control Light-Capable Devices Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/bootstrap.md Demonstrates iterating through a list of RestDevice objects and conditionally calling 'set_color' on light-capable devices. This allows for targeted control of device features. ```python from hatch_rest_api import RestDevice, get_rest_devices devices: list[RestDevice] = [...] # Assume devices is populated for device in devices: if hasattr(device, 'set_color'): # Light-capable devices device.set_color(255, 0, 0, brightness=100) ``` -------------------------------- ### Pack Dual Percentages (RestoreV5) Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/utilities.md Packs two percentages (0-100) into a single 32-bit integer. Used by RestoreV5 for storing brightness values. The nighttime percentage is packed into the upper 16 bits and the daytime percentage into the lower 16 bits. ```python from hatch_rest_api.restore_v5 import pack_dual_percentages # Set nighttime to 30%, daytime to 100% packed = pack_dual_percentages(30, 100) # Use in device update: {"clock": {"i": packed}} ``` -------------------------------- ### Rate Limit Handling for Sound Loading Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/bootstrap.md Illustrates the internal retry logic for rate-limited endpoints, specifically showing how sound loading handles `RateError` by defaulting to an empty sounds list. ```python # Inside get_rest_devices, sound loading includes: # try: # sounds = await api.content(...) # except RateError: # sounds = [] # Continue without sounds ``` -------------------------------- ### Weekday Bitmask Representation Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/types.md Illustrates the bitmask values used for the `daysOfWeek` field to represent specific days or combinations of days. For example, weekdays (Mon-Fri) are represented by the sum of their individual bit values. ```text sunday: 1 monday: 2 tuesday: 4 wednesday: 8 thursday: 16 friday: 32 saturday: 64 Example: weekdays (Mon-Fri) = 2|4|8|16|32 = 62 ``` -------------------------------- ### Connection Pooling with ClientSession Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/configuration.md Demonstrates how to reuse a single `ClientSession` across multiple API operations for performance tuning. This reduces overhead by maintaining a persistent connection. ```python async with ClientSession() as session: hatch_api = Hatch(client_session=session) token = await hatch_api.login(email, password) devices = await hatch_api.iot_devices(auth_token=token) # Connection reused across calls ``` -------------------------------- ### Unpack Dual Percentages (RestoreV5) Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/utilities.md Unpacks two percentages (nighttime, daytime) from a single 32-bit integer. Used by RestoreV5 to store brightness values. ```python from hatch_rest_api.restore_v5 import unpack_dual_percentages # Device reports packed clock brightness packed = 0x3FFF7FFF # Hypothetical value night, day = unpack_dual_percentages(packed) # night ≈ 50%, day ≈ 100% ``` -------------------------------- ### Safely Get JSON Value with Dot Notation Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/utilities.md Safely retrieves a value from a nested dictionary using a dot-separated key. It handles missing keys by returning None and can optionally cast the result to a specified type. Useful for parsing device state from JSON payloads. ```python from hatch_rest_api.util import safely_get_json_value state = { "deviceInfo": { "f": "1.2.3", # firmware version "b": 85, # battery }, "current": { "sound": { "v": 32767, # volume } } } firmware = safely_get_json_value(state, "deviceInfo.f") # Returns: "1.2.3" battery = safely_get_json_value(state, "deviceInfo.b", int) # Returns: 85 (cast to int) missing = safely_get_json_value(state, "nonexistent.path") # Returns: None (no KeyError) volume = safely_get_json_value(state, "current.sound.v") # Returns: 32767 ``` ```python def _update_local_state(self, state): if safely_get_json_value(state, "connected") is not None: self.is_online = safely_get_json_value(state, "connected", bool) if safely_get_json_value(state, "current.sound.v") is not None: self.volume = convert_to_percentage( safely_get_json_value(state, "current.sound.v", int) ) ``` -------------------------------- ### content Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/hatch.md Fetches sounds, colors, or windDown content available for a product. It includes automatic retry with exponential backoff for rate limiting. ```APIDOC ## content ### Description Fetches sounds, colors, or windDown content available for a product with exponential backoff retry on rate limit. ### Method POST ### Endpoint /content ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **auth_token** (str) - Required - Authentication token from login() - **product** (str) - Required - Product code, e.g. "riot", "restBaby" - **content** (list) - Required - Content types to fetch: ["sound"], ["color"], ["windDown"], or combinations - **max_retries** (int) - Optional - Max retry attempts on rate limit (429) - Default: 3 ### Request Example ```json { "auth_token": "your_auth_token", "product": "riot", "content": ["sound", "color"], "max_retries": 3 } ``` ### Response #### Success Response (200) - **contentItems** (list) - Payload with content items #### Response Example ```json { "contentItems": [ { "type": "sound", "name": "Lullaby", "url": "http://example.com/sound.mp3" } ] } ``` ### Error Handling - **RateError**: If rate limited after max_retries attempts. ``` -------------------------------- ### Alarm Scheduling Functions and Constants Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/constants.md Illustrates how to convert weekday names to a bitmask, display a bitmask as a human-readable label, and manually construct alarm bitmasks using WEEKDAY_BITS. ```python from hatch_rest_api.scheduled_routine import ( weekdays_to_days_of_week, days_of_week_label, WEEKDAY_BITS, ) # Convert weekday names to bitmask weekday_mask = weekdays_to_days_of_week( ["monday", "tuesday", "wednesday", "thursday", "friday"] ) # 62 # Convert bitmask to label label = days_of_week_label(weekday_mask) # "Weekdays" # Manual bitmask calculation alarm_mask = ( WEEKDAY_BITS["monday"] | WEEKDAY_BITS["wednesday"] | WEEKDAY_BITS["friday"] ) # 42 (MWF) ``` -------------------------------- ### Control Audio Playback Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/README.md Demonstrates setting audio volume and tracks for different device types. Use specific track enums or sound IDs/titles for playback. ```python # RestMini mini.set_volume(50) mini.set_audio_track(RestMiniAudioTrack.Heartbeat) # RestIot/RestBaby device.set_volume(60) device.set_audio_track(RIoTAudioTrack.Ocean) # RestBaby - by sound ID device.set_sound(10518) # Airplane sound # RestBaby - by title device.set_sound("Heartbeat") ``` -------------------------------- ### Fetch Data in Parallel with Asyncio Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/configuration.md Use asyncio to fetch favorites and routines for multiple devices concurrently. This is useful for optimizing data retrieval when dealing with many devices. ```python import asyncio async def setup(): api, mqtt_conn, devices, _ = await get_rest_devices(email, password) # Fetch favorites and routines in parallel tasks = [] for device in devices: if hasattr(device, 'mac'): tasks.append(api.favorites(auth_token=token, mac=device.mac)) tasks.append(api.routines(auth_token=token, mac=device.mac)) results = await asyncio.gather(*tasks) ``` -------------------------------- ### RestoreV5 Methods Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/device-classes.md Methods available for the RestoreV5 device class, extending RestoreIot with enhanced clock and sound control. ```APIDOC ## set_clock ### Description Sets dual clock brightness levels for daytime and nighttime. ### Method Not specified (assumed to be part of the class instance) ### Endpoint Not specified ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python await device.set_clock(daytime_brightness=100, nighttime_brightness=30) ``` ### Response None specified ``` ```APIDOC ## set_sound ### Description Sets the sound for the device, with options for duration and end time. ### Method Not specified (assumed to be part of the class instance) ### Endpoint Not specified ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python await device.set_sound(sound_or_id_or_title="Lullaby", duration=600, until="10:00 PM") ``` ### Response None specified ``` ```APIDOC ## turn_light_off ### Description Turns off the light while preserving audio state. ### Method Not specified (assumed to be part of the class instance) ### Endpoint Not specified ### Parameters None ### Request Example ```python await device.turn_light_off() ``` ### Response None specified ``` ```APIDOC ## set_color ### Description Sets light color and brightness. ### Method Not specified (assumed to be part of the class instance) ### Endpoint Not specified ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python await device.set_color(red=0, green=255, blue=0, brightness=50) ``` ### Response None specified ``` -------------------------------- ### MQTT Connection Callbacks for Device Bootstrap Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/configuration.md Define and use callback functions for handling MQTT connection interruptions and resumptions during device bootstrap. This is useful for updating UI status or managing command queues. ```python def on_mqtt_interrupt(): """Called when MQTT connection is lost.""" print("Device connection lost") def on_mqtt_resume(): """Called when MQTT reconnects.""" print("Device connection restored") api, mqtt_conn, devices, expiration = await get_rest_devices( email=email, password=password, on_connection_interrupted=on_mqtt_interrupt, on_connection_resumed=on_mqtt_resume, ) ``` -------------------------------- ### Configure Alarm API Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/scheduled-routines.md Sets up the API client for alarm operations. This is called automatically by get_rest_devices(). ```python device.configure_alarm_api( api=hatch_api, auth_token=token, alarms=initial_alarms ) ``` -------------------------------- ### iot_devices Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/hatch.md Fetches all IoT devices associated with the account, including RestMini, RestPlus, Riot, RestBaby, and Restore devices. ```APIDOC ## iot_devices ### Description Fetches all IoT devices associated with the account (RestMini, RestPlus, Riot, RestBaby, Restore devices). ### Method GET (assumed) ### Endpoint /iot/devices (assumed) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming 'token' is obtained from the login method devices = await hatch_api.iot_devices(auth_token=token) print(devices) ``` ### Response #### Success Response (200) - **(dict)** - Device payload containing list of all compatible devices #### Response Example ```json [ { "product": "RestMini", "name": "Baby Monitor", "macAddress": "AA:BB:CC:DD:EE:FF", "thingName": "device-12345" } ] ``` ``` -------------------------------- ### RestMini Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/device-classes.md Represents a lightweight device with audio playback control. It inherits from ShadowClientSubscriberMixin and uses AWS IoT Shadow for state management. ```APIDOC ## RestMini ### Description Lightweight device with audio playback control. Devices communicate with AWS IoT Shadow for state management. ### Constructor ```python def __init__( self, device_name: str, thing_name: str, mac: str, shadow_client: IotShadowClient, favorites: list | None = None, sounds: list | None = None, ) ``` #### Parameters * **device_name** (str) - Required - Display name of the device * **thing_name** (str) - Required - AWS IoT Thing name * **mac** (str) - Required - Device MAC address * **shadow_client** (IotShadowClient) - Required - AWS IoT Shadow client instance * **favorites** (list) - Optional - List of favorite routines * **sounds** (list) - Optional - List of available sounds ### Properties * **device_name** (str) - Display name of the device * **thing_name** (str) - AWS IoT Thing name * **mac** (str) - MAC address * **firmware_version** (str) - Current firmware version * **is_online** (bool) - Whether device is connected * **audio_track** (RestMiniAudioTrack) - Currently playing audio track * **volume** (int) - Current volume (0-100) * **current_playing** (str) - "none" or "remote" * **is_playing** (bool) - True if audio is currently playing * **document_version** (int) - AWS Shadow document version ### Methods #### set_volume Sets the volume for audio playback. * **percentage** (int) - Required - Volume level (0-100) **Example:** ```python mini.set_volume(50) # Set volume to 50% ``` #### set_audio_track Starts playing an audio track. * **audio_track** (RestMiniAudioTrack) - Required - Audio track to play (or NONE to stop) **Example:** ```python from hatch_rest_api import RestMiniAudioTrack mini.set_audio_track(RestMiniAudioTrack.Heartbeat) ``` ``` -------------------------------- ### pack_dual_percentages Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/utilities.md Packs two percentages into a single 32-bit integer. This is used internally by RestoreV5 for efficient storage of brightness values. ```APIDOC ## pack_dual_percentages ### Description Packs two percentage values (0-100) into a single 32-bit integer. ### Method Signature ```python def pack_dual_percentages( a_percentage: int, b_percentage: int, ) -> int ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Description | |-----------|------|-------------| | a_percentage | int | First percentage (0-100) | | b_percentage | int | Second percentage (0-100) | ### Returns `int` - A 32-bit integer representing the packed percentages. ### Example ```python from hatch_rest_api.restore_v5 import pack_dual_percentages packed = pack_dual_percentages(30, 100) # packed value can be used to set device clock brightness ``` ``` -------------------------------- ### Fetch Product Content Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/hatch.md Fetches sounds, colors, or windDown content for a given product. Supports automatic retries on rate limiting with a configurable maximum number of attempts. ```python async def content( self, auth_token: str, product: str, content: list, max_retries: int = 3, ) ``` ```python # Fetch sounds with automatic retry on rate limit sounds = await hatch_api.content( auth_token=token, product="riot", content=["sound"], max_retries=3 ) ``` -------------------------------- ### Set Light Color Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/device-classes.md Sets the light color, white level, and brightness. ```python def set_color( self, red: int, green: int, blue: int, white: int = 0, brightness: int = 0, ) ``` -------------------------------- ### Import Top-Level API Clients and Utilities Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/README.md Import necessary components for interacting with the Hatch REST API, including API clients, bootstrap functions, device classes, and error types. ```python from hatch_rest_api import ( # API clients Hatch, AwsHttp, Contentful, # Bootstrap get_rest_devices, RestDevice, # Union type # Device classes RestMini, RestPlus, RestIot, RestBaby, RestoreIot, RestoreV4, RestoreV5, # Errors BaseError, RateError, AuthError, # Audio tracks (enums with values) RestMiniAudioTrack, REST_MINI_AUDIO_TRACKS, RestPlusAudioTrack, REST_PLUS_AUDIO_TRACKS, RIoTAudioTrack, REST_IOT_AUDIO_TRACKS, RestBabyAudioTrack, REST_BABY_AUDIO_TRACKS, TimeToRiseTrack, TIME_TO_RISE_TRACKS, TimeForBedTrack, TIME_FOR_BED_TRACKS, ) ``` -------------------------------- ### Graceful Degradation for Optional Content Loading Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/errors.md This snippet demonstrates how to load optional content like sounds, handling RateError and other exceptions by proceeding with empty data. It's useful for features that are not critical to the application's core functionality. ```python async def load_sounds_optional(api, token, device): try: sounds = await api.content( auth_token=token, product="riot", content=["sound"], max_retries=3 ) device.sounds = sounds.get("contentItems", []) except RateError: # Content failed due to rate limit, proceed with empty sounds device.sounds = [] _LOGGER.warning("Sound content unavailable due to rate limiting") except Exception as e: # Other content errors device.sounds = [] _LOGGER.warning(f"Failed to load sounds: {e}") ``` -------------------------------- ### configure_alarm_api Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/scheduled-routines.md Sets up the API client for alarm operations. This method is typically called automatically by `get_rest_devices()` but can be called manually if needed. ```APIDOC ## configure_alarm_api ### Description Sets up the API client for alarm operations. Called automatically by `get_rest_devices()`. ### Method `configure_alarm_api` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | api | Hatch | Yes | — | Authenticated Hatch API client | | auth_token | str | Yes | — | Auth token for API calls | | alarms | list | No | None | Initial alarm list, loads if None | ### Example ```python device.configure_alarm_api( api=hatch_api, auth_token=token, alarms=initial_alarms ) ``` ``` -------------------------------- ### RestIot set_volume Method Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/device-classes.md Sets the volume level for the device. The percentage should be between 0 and 100. ```python def set_volume(self, percentage: int) ``` -------------------------------- ### Set Sound Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/device-classes.md Sets the sound for the device, which can be specified by a SoundContent object, ID, title, duration, or until when it should play. ```python def set_sound( self, sound_or_id_or_title: SoundContent | SimpleSoundContent | str | int | None, duration: int = 0, until: str = "indefinite", ) ``` -------------------------------- ### RestBaby set_sound_url Method Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/device-classes.md Sets a sound to play from a public URL. Supports WAV and MP3 formats. Defaults to a sample URL if none is provided. ```python def set_sound_url(self, sound_url: str = 'http://codeskulptor-demos.commondatastorage.googleapis.com/GalaxyInvaders/theme_01.mp3') ``` -------------------------------- ### Fetch IoT Devices Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/hatch.md Retrieve a list of all IoT devices associated with the authenticated account. This includes various Hatch device models. ```python devices = await hatch_api.iot_devices(auth_token=token) print(devices) # List of device objects with product, name, macAddress, thingName ``` -------------------------------- ### Listen to Device State Changes Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/README.md Registers a callback function to be executed whenever a device's state is updated. This is useful for real-time monitoring of device status. ```python def on_state_update(): print(f"Device updated: online={device.is_online}, playing={device.is_playing}") device.register_callback(on_state_update) ``` -------------------------------- ### Login to Hatch API Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/INDEX.md Obtain an authentication token by providing user credentials. This is the first step for most API interactions. ```python token = await api.login(email, password) ``` -------------------------------- ### List all alarms with their status, wake time, and days Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/api-reference/scheduled-routines.md Iterates through all retrieved alarms, displaying their enabled status, name, wake time, and a human-readable label for the days they are active. This provides a comprehensive overview of all configured alarms. ```python from hatch_rest_api.scheduled_routine import days_of_week_label alarms = await device.refresh_alarms() for alarm in alarms: days = days_of_week_label(alarm['daysOfWeek']) status = "✓" if alarm['enabled'] else "✗" print(f"{status} {alarm['name']}") print(f" Wake: {alarm['endTime']}") print(f" Days: {days}") print() ``` -------------------------------- ### REST_MINI_AUDIO_TRACKS List Constant Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/constants.md Provides a list of all available RestMini audio tracks. This is derived from the RestMiniAudioTrack enum. ```python REST_MINI_AUDIO_TRACKS = list(RestMiniAudioTrack) ``` -------------------------------- ### Import Scheduled Routine Utilities Source: https://github.com/dahlb/hatch_rest_api/blob/main/_autodocs/README.md Import specific utilities for managing scheduled routines, including alarm types, weekday conversions, and routine labels. ```python from hatch_rest_api.scheduled_routine import ( ScheduledRoutineAlarm, # TypedDict weekdays_to_days_of_week, days_of_week_to_weekdays, days_of_week_label, alarm_routines, ALARM_ROUTINE_TYPE, SCHEDULED_ROUTINE_ALARM_PRODUCTS, ) ```