简体   繁体   中英

Having trouble using raspberry pi bluetooth in python

First off if anybody knows of a good tutorial for coding bluetooth on my raspberry pi zero w with python to turn on discovery, listen for a pair request, connect and save the paired device, and more, that would be awesome. My code for testing bluetooth discovery is below.

import bluetooth

print("performing inquiry...")

nearby_devices = bluetooth.discover_devices(
        duration=8, lookup_names=True, flush_cache=True)

print("found %d devices" % len(nearby_devices))

for addr, name in nearby_devices:
    try:
        print("  %s - %s" % (addr, name))
    except UnicodeEncodeError:
        print("  %s - %s" % (addr, name.encode('utf-8', 'replace')))

The TraceBack is below

Traceback (most recent call last):
  File "bluetoothConnect.py", line 6, in <module>
    duration=8, lookup_names=True, flush_cache=True)
  File "/usr/lib/python2.7/dist-packages/bluetooth/bluez.py", line 17, in discover_devices
    sock = _gethcisock ()
  File "/usr/lib/python2.7/dist-packages/bluetooth/bluez.py", line 226, in _gethcisock
    raise BluetoothError ("error accessing bluetooth device")
bluetooth.btcommon.BluetoothError: error accessing bluetooth device

("error accessing bluetooth device") is the clue. Yes - as earlier mentioned you need elevated privileges. Simply run the script with sudo... eg - sudo python myscript.py enter your password It should now work..for testing purposes. Though going forward I would create a privileged user and add that user to the root group with the setting /bin/false. Then use that user to run all your scripts..

Had the same issue and then I wrote this simple script to wrap Bluetoothctl using python3. Tested on Raspberry pi 4.

import subprocess
import time


def scan(scan_timeout=20):
    """ scan
        Scan for devices
        Parameters
        ----------
        scan_timeout : int
            Timeout to run the scan
        Returns
        ----------
        devices : dict
            set of discovered devices as MAC:Name pairs
    """
    p = subprocess.Popen(["bluetoothctl", "scan", "on"])
    time.sleep(scan_timeout)
    p.terminate()
    return __devices()


def __devices():
    """ devices
        List discovered devices
        Returns
        ----------
        devices : dict
            set of discovered devices as MAC:Name pairs
    """
    devices_s = subprocess.check_output("bluetoothctl devices", shell=True).decode().split("\n")[:-1]
    devices = {}
    for each in devices_s:
        devices[each[7:24]] = each[25:]
    return devices


def info():
    """ Info
        Returns
        ----------
        info : str
            information about the device connected currently if any
    """
    return subprocess.check_output("bluetoothctl info", shell=True).decode()


def pair(mac_address):
    """ pair
        Pair with a device
        Parameters
        ----------
        mac_address : str
           mac address of the device tha you need to pair
    """
    subprocess.check_output("bluetoothctl pair {}".format(mac_address), shell=True)


def remove(mac_address):
    """ remove
        Remove a connected(paired) device
        Parameters
        ----------
        mac_address : str
           mac address of the device tha you need to remove
    """
    subprocess.check_output("bluetoothctl remove {}".format(mac_address), shell=True)


def connect(mac_address):
    """ connect
        Connect to a device
        Parameters
        ----------
        mac_address : str
           mac address of the device tha you need to connect
    """
    subprocess.check_output("bluetoothctl connect {}".format(mac_address), shell=True)


def disconnect():
    """ disconnect
        Disconnects for currently connected device
    """
    subprocess.check_output("bluetoothctl disconnect", shell=True)


def paired_devices():
    """ paired_devices
            Return a list of paired devices
    """
    return subprocess.check_output("bluetoothctl paired-devices", shell=True).decode()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM