btsocket Library

0.3.0 · active · verified Thu Apr 16

btsocket is a Python library providing a high-level interface to the BlueZ Bluetooth Management API. It enables programmatic control over Bluetooth adapters and operations on Linux systems. The current version is `0.3.0`, with a release cadence that focuses on adding new BlueZ management commands and improving internal socket handling, typically with a few releases per year.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `BTSocket` object, connect to the BlueZ Management API, and then disconnect. It handles common `PermissionError` and `FileNotFoundError` exceptions that might occur if BlueZ is not properly set up or permissions are insufficient. Replace the `time.sleep(1)` with actual Bluetooth management commands for real-world usage.

import btsocket
import time

def main():
    """
    Demonstrates basic connection and disconnection using btsocket.
    Requires a functional BlueZ setup and appropriate permissions.
    """
    print("Initializing btsocket...")
    try:
        bt = btsocket.BTSocket()
        print(f"BTSocket initialized. Adapter index: {bt.idx}")

        print("Attempting to connect to Bluetooth Management API...")
        # This establishes a connection to the local BlueZ Management socket.
        # Depending on your system, you might need root privileges or to be
        # part of the 'bluetooth' group for certain operations.
        bt.connect()
        print("Successfully connected to Bluetooth Management API.")

        # In a real application, you would perform Bluetooth operations here.
        print("Connected for 1 second...")
        time.sleep(1)

        print("Disconnecting from Bluetooth Management API...")
        bt.disconnect()
        print("Disconnected.")

    except PermissionError as e:
        print(f"Error: Permission denied. {e}")
        print("Hint: Try running with 'sudo python your_script.py' or ensure your user is in the 'bluetooth' group and BlueZ is correctly configured.")
    except FileNotFoundError as e:
        print(f"Error: BlueZ management socket not found. {e}")
        print("Hint: Ensure BlueZ is installed and the 'bluetooth' service is running.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        print("Hint: Check if your Bluetooth adapter is enabled and BlueZ is functioning correctly.")

if __name__ == "__main__":
    main()

view raw JSON →