pyatv Documentation

repository·master·Indexed 22 days ago

https://github.com/postlund/pyatv

An asyncio-based Python client library for interacting with Apple TV and AirPlay devices. It provides APIs for remote control, metadata retrieval, AirPlay streaming, app management, and virtual keyboard interaction. The library includes the atvremote CLI for device pairing and control, as well as support for the Companion protocol to manage installed apps and deep linking.

Tokens
53.9K
Snippets
199
Records
259
Agent score
78%

What's inside pyatv

  1. Overview of pyatv features and capabilities

    master

    pyatv is an asyncio Python library designed for interacting with Apple TV and AirPlay devices.

    Core Capabilities:

    • Device Discovery: Automatic discovery of devices using Zeroconf.
    • Device Information: Access to hardware models and operating system versions.
    • Media Control: Retrieve currently playing metadata, artwork, and receive push updates.
    • Remote Control: Send navigation, volume, and remote control commands.
    • Streaming: Basic support for streaming video and audio via AirPlay.
    • App Management: List installed apps, launch specific apps, and identify the currently playing app.
    • Power Management: Turn Apple TV devices on or off.
    • Device Support: Works with Apple TV (all generations), AirPort Express, HomePod, macOS Music app, and most AirPlay v1 receivers.
    • Persistence: Supports persistent storage of credentials and settings (e.g., to files or custom storage).
  2. Overview of atvscript

    master
    The atvscript command-line tool is designed for scripting and integration with existing software. It provides a subset of the functionality found in atvremote but is optimized for machine readability by producing output in easy-to-parse formats like JSON. One command response is always printed per line, making it ideal for streaming updates or processing logs.
  3. Overview of pyatv core features

    master

    Regardless of the specific protocol used, pyatv provides several core capabilities across all supported devices:

    • Automatic service discovery: Uses zeroconf/Bonjour to find devices on the network.
    • Device information: Retrieves device metadata (e.g., operating system and version) via service discovery.
    • Protocol setup: Automatically configures protocols based on the provided device configuration.
    • Connection monitoring: Provides callbacks when a connection is lost via device updates.
    • Storage API: A mechanism for storing settings and credentials (e.g., in a file or cloud service).
  4. What is the Companion Link protocol?

    master
    Companion Link is a protocol used for communication between Apple devices, notably used by the iOS 13+ remote widget in the Control Center and the Shortcuts app to launch apps. It is also believed to support Continuity and Handoff features. Service discovery uses Zeroconf with the service type _companion-link._tcp.local..
  5. What is the Media Remote Protocol (MRP)?

    master
    The Media Remote Protocol (MRP) is used by the Apple TV Remote App and the iOS Control Center widget (on versions prior to iOS 13). It is used to control devices like Apple TV 4 and tvOS. The protocol is based on Google's Protocol Buffers (protobuf). Service discovery is performed via Zeroconf using the service type _mediaremotetv._tcp.local.. Note that the communication port can change dynamically, typically starting from the ephemeral port range (e.g., 49152).
  6. Detecting Deep Sleep via Sleep Proxies

    master

    When an Apple TV is in deep sleep, a sleep proxy on the network announces its presence and can wake the device using Wake-On-LAN.

    pyatv can detect if a scan response originated from a sleep proxy. This state is indicated by the AppleTV.deep_sleep flag.

    Note: This is currently an experimental feature.

  7. How the pyatv Facade and Relayer system works

    master

    The pyatv library uses a Facade pattern to provide a unified interface to the user, even when multiple underlying protocols (like MRP, DMAP, AirPlay, etc.) are active.

    The Relayer Pattern

    Because a single device might support multiple protocols that implement the same interface (e.g., both MRP and Companion might support Power), pyatv uses Relayers to manage them:

    1. Priority-based selection: Each protocol has a priority. If multiple protocols implement a method, the one with the highest priority is used by default. The general priority order is: MRP > DMAP > Companion > AirPlay > RAOP.
    2. Implementation verification: A Relayer checks if a protocol actually provides an implementation for a specific method before attempting to call it. If the highest-priority protocol doesn't implement it, the Relayer falls back to the next one.
    3. Priority Overrides: The Facade can override the default priority list for specific interfaces or methods if a lower-priority protocol provides a better implementation (e.g., the Power interface often prefers Companion over MRP).

    The Facade

    The Facade implements the main interface.AppleTV and all its sub-interfaces (like Power, Audio, Apps, etc.). When you call a method on the Facade, it relays that call to the most appropriate protocol instance based on the rules above.

    class FacadeApps(Relayer, interface.Apps):
        def __init__(self):
            super().__init__(interface.Apps, DEFAULT_PRIORITIES)
    
        async def app_list(self) -> List[interface.App]:
            return await self.relay("app_list")()
    
        async def launch_app(self, bundle_id: str) -> None:
            await self.relay("launch_app")(bundle_id)
  8. How chickn pipelines, stages, and steps work

    master

    A chickn configuration defines a single pipeline via a chickn.yml file. The hierarchy is as follows:

    1. Pipeline: The top-level sequence of execution.
    2. Stages: Executed sequentially. One stage must finish before the next begins.
    3. Steps: Defined within a stage. All steps within a single stage are executed in parallel.

    Each step must have a unique name, which allows you to target specific steps from the command line.

    pipeline:
      stage1:
        - name: foobar
          run: ls /
      stage2:
        - name: hello
          run: echo helloe
        - name: world
          run: echo world
  9. Understand Feature States in pyatv

    master

    A feature on an Apple TV or AirPlay device can exist in one of four states. Understanding these states is crucial for deciding whether to attempt a command (like play() or pause()) or to skip it.

    StateMeaning
    FeatureState.UnknownThe device supports the feature, but its current availability cannot be determined (e.g., Pause is supported, but we don't know if anything is currently playing).
    FeatureState.UnsupportedThe device does not support this feature at all (e.g., Siri on an older Apple TV) or no configured protocols support it.
    FeatureState.UnavailableThe feature is supported by the device but cannot be used in the current context (e.g., Skip to next track while no media is playing).
    FeatureState.AvailableThe feature is supported and can be used immediately (e.g., Pause is available because media is playing).
  10. Uniquely identifying devices

    master

    To reliably connect to a specific device (especially in environments with DHCP where IP addresses change), you should use unique identifiers rather than names or IP addresses.

    pyatv extracts these identifiers from the services found during a scan. Common sources include:

    • MRP: Uses a UniqueIdentifier property.
    • AirPlay: Uses the deviceid (MAC address).

    You can use any of these identifiers when scanning to ensure you find the exact device you expect. For convenience, AppleTV.identifier provides a single property that picks one available identifier from the device.

  11. Configure the Event Channel encryption

    master

    The Event Channel is a TCP connection initiated by the sender to the port returned in the SETUP response. Encryption is required. The encryption keys are derived using the following parameters:

    DirectionSaltInfo
    OutputEvents-SaltEvents-Write-Encryption-Key
    InputEvents-SaltEvents-Read-Encryption-Key

    Note: Although the sender initiates the channel, it should treat the channel as originating from the receiver. Therefore, the sender must reverse the input and output keys during the SRP (Station-to-Station) process (use Output as Input and Input as Output).

  12. Understand the atvscript output format

    master

    All atvscript output is structured as a dictionary (e.g., JSON). Every response contains these pre-defined keys:

    KeyMeaning
    resultsuccess if the command worked, otherwise failure.
    datetimeISO8601 timestamp of the event.
    errorA string representing the error (e.g., device_not_found, unsupported_command). Only present if result is failure.
    exceptionThe exception message. Only present if result is failure.
    stacktraceThe stacktrace string. Only present if result is failure.

    Any additional keys in the dictionary are specific to the command being executed.