Skip to main content

Asynchronous Python SDK for Tonies API and MQTT WebSocket

Project description

Tonies API Client

A Python library for interacting with the Tonies API. This library provides an asynchronous client to manage your Tonies, Creative-Tonies, households, and more. It supports both standard data fetching via GraphQL/REST and real-time event monitoring via WebSocket/MQTT.

Features

  • Asynchronous Client: Built on httpx and websockets.
  • Authentication: Full OAuth2 flow via Keycloak.
  • Data Fetching (GraphQL):
    • User details
    • Households and Members
    • Tonieboxes
    • Creative-Tonies and Content-Tonies
    • Children profiles
  • Device Configuration (REST):
    • Volume limits (Speaker & Headphones)
    • LED & Lightring brightness
    • Toniebox name
    • Accelerometer & Tap gestures
    • Bedtime settings
  • Real-time Events (WebSocket):
    • Monitor connection state (online/offline)
    • Battery levels
    • Tonie placement detection
    • Headphone connection status
    • Bedtime configuration
  • Type Safety: Comprehensive Pydantic models for all data structures.

Installation

You can install the library directly from the source:

git clone https://github.com/Raphzer/tonies-api.git
cd tonies-api
pip install .

For development (editable mode):

pip install -e .

Usage

First, create a .env file in your project root with your Tonies credentials:

TONIE_USERNAME=your_email@example.com
TONIE_PASSWORD=your_password

Basic Data & Configuration

import asyncio
import os
from dotenv import load_dotenv
from tonies_api.client import TonieAPIClient

async def main():
    load_dotenv()
    username = os.getenv("TONIE_USERNAME")
    password = os.getenv("TONIE_PASSWORD")

    async with TonieAPIClient(username, password) as client:
        # Get Households
        households = await client.tonies.get_households()
        
        # Get Tonieboxes
        tonieboxes = await client.tonies.get_households_boxes()
        if tonieboxes:
            box = tonieboxes[0]
            print(f"Found box: {box.name} (Battery: {box.mac_address})")

            # Update Volume
            await client.tonies.set_max_volume(box.household_id, box.id, 75)
            print("Volume updated!")

if __name__ == "__main__":
    asyncio.run(main())

Real-time Events (WebSocket)

import asyncio
import os
from dotenv import load_dotenv
from tonies_api.client import TonieAPIClient

async def event_handler(topic, payload):
    print(f"Received event on {topic}: {payload}")

async def main():
    load_dotenv()
    async with TonieAPIClient(os.getenv("TONIE_USERNAME"), os.getenv("TONIE_PASSWORD")) as client:
        # Register callback
        client.ws.register_callback(event_handler)
        
        # Connect and subscribe
        await client.ws.connect()
        
        # get all box 
        boxes = await client.tonies.get_households_boxes()

        # subscribe to all compatible boxes (v2 gen)
        for box in boxes:
            await client.ws.subscribe_to_toniebox(box)

        # Keep alive
        await asyncio.sleep(60)

if __name__ == "__main__":
    asyncio.run(main())

API Reference

The TonieAPIClient provides access to TonieResources via client.tonies and TonieWebSocket via client.ws.

Data Methods (client.tonies)

  • get_user_details() -> User
  • get_households() -> List[Household]
  • get_households_boxes() -> List[Toniebox]
  • get_tonies() -> List[HouseholdWithTonies]
  • get_children(household_id: str) -> List[Child]
  • get_household_members(household_id: str) -> HouseholdMembersResponse
  • get_content_tonie_details(household_id: str, tonie_id: str) -> List[ContentTonieDetails]

Configuration Methods (client.tonies)

  • set_max_volume(household_id, toniebox_id, volume) -> Toniebox
  • set_max_headphone_volume(household_id, toniebox_id, volume) -> Toniebox
  • set_led_brightness(household_id, toniebox_id, level) -> Toniebox (level: 'on', 'off', 'dimmed')
  • set_toniebox_name(household_id, toniebox_id, name) -> Toniebox
  • set_accelerometer(household_id, toniebox_id, enabled) -> Toniebox
  • set_tap_direction(household_id, toniebox_id, direction) -> Toniebox ('left' or 'right')
  • set_lightring_brightness(household_id, toniebox_id, brightness) -> Toniebox
  • set_bedtime_max_volume(household_id, toniebox_id, volume) -> Toniebox
  • set_bedtime_headphone_max_volume(household_id, toniebox_id, volume) -> Toniebox
  • set_bedtime_lightring_brightness(household_id, toniebox_id, brightness) -> Toniebox

WebSocket Methods (client.ws)

  • connect(): Connects to the real-time server.
  • disconnect(): Closes the WebSocket connection.
  • subscribe_to_toniebox(toniebox): Subscribes to all events for a box.
  • subscribe(topics: List[str]): Manually subscribes to a list of MQTT topics.
  • register_callback(callback): Registers a function async def callback(topic, payload) to handle events.
  • send_toniebox_command(mac_address, command, payload): Sends a control command to the Toniebox (e.g., 'sleep', 'stl').
  • sleep_now(mac_address): Sends a command to immediately put the Toniebox to sleep.

Available MQTT Events

When you subscribe to a Toniebox using client.ws.subscribe_to_toniebox(mac_address), the client automatically subscribes to the wildcard topic external/toniebox/{mac_address}/#.

Common events you might receive include:

  • .../online-state: Updates when the box goes online or offline.
  • .../metrics/battery: Battery level updates.
  • .../metrics/headphones: Headphone connection status.
  • .../app-reply/bedtime-state: Current status of bedtime mode.
  • .../changed-properties: General property changes.
  • .../settings-applied: Confirmation that settings have been applied.
  • .../setup/status: Setup status updates.
  • .../playback/state: Current Tonie on the box.

License

This project is licensed under the Apache 2.0 License - see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tonies_api-0.1.2.tar.gz (21.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tonies_api-0.1.2-py3-none-any.whl (21.4 kB view details)

Uploaded Python 3

File details

Details for the file tonies_api-0.1.2.tar.gz.

File metadata

  • Download URL: tonies_api-0.1.2.tar.gz
  • Upload date:
  • Size: 21.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for tonies_api-0.1.2.tar.gz
Algorithm Hash digest
SHA256 22218f9bce068bde5e3cedbff1ace80ebc8a85b17dfd958d3e8235d485df417c
MD5 0bcd89bd2f227c04047f6aa89bb1fd5e
BLAKE2b-256 81a4dad032244c6d2b67c2d9c6a57d9c238c71bc557eeef6b087a662f3c34fcf

See more details on using hashes here.

File details

Details for the file tonies_api-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: tonies_api-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 21.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for tonies_api-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 74076e03450998c0500cca06c4423dc2715dc14a24f6cc3dde63cbe2f6e9b696
MD5 36545dc69ec141920bb645e32eeb1ddb
BLAKE2b-256 122199991cf571d7292c2b9225f9b4d294781b707e10be110d613e61a262b1ed

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page