【问题标题】:Having trouble using raspberry pi bluetooth in python在 python 中使用树莓派蓝牙时遇到问题
【发布时间】:2018-03-10 20:25:09
【问题描述】:

首先,如果有人知道使用 python 在我的树莓派零 w 上编写蓝牙以打开发现、侦听配对请求、连接并保存配对设备等的好教程,那将是很棒的。我测试蓝牙发现的代码如下。

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')))

TraceBack 在下面

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

【问题讨论】:

  • 您使用的是哪种树莓派?它有蓝牙设备吗?您是否尝试过以 root 身份运行?
  • 树莓派零 w,是的,它有蓝牙。
  • 以 root 身份运行怎么样?这可能是这里的关键之一
  • 那我该怎么做呢?
  • 如果其他人知道我可以尝试解决此问题的任何其他内容。 pi zero w 带有蓝牙,但我必须安装蓝牙和 python-bluez 包。我不明白为什么会出现此错误

标签: python bluetooth raspberry-pi


【解决方案1】:

("错误访问蓝牙设备") 是线索。 是的 - 如前所述,您需要提升权限。 只需使用 sudo 运行脚本... 例如 - sudo python myscript.py 输入您的密码 它现在应该可以工作了..用于测试目的。 虽然接下来我会创建一个特权用户,并将该用户添加到具有设置 /bin/false 的根组中。 然后使用该用户运行所有脚本..

【讨论】:

    【解决方案2】:

    遇到了同样的问题,然后我编写了这个简单的脚本来使用 python3 包装 Bluetoothctl。在树莓派 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()
    

    【讨论】:

      猜你喜欢
      • 2017-03-30
      • 2013-04-09
      • 2016-12-07
      • 2018-06-16
      • 2016-01-18
      • 1970-01-01
      • 2015-08-09
      • 1970-01-01
      • 2021-04-03
      相关资源
      最近更新 更多