通过Python将蓝牙设备绑定到rfcomm

问题描述 投票:0回答:1

我能够使用 BlueZ API 搜索 Raspberry Pi 4 并将其与蓝牙 4.0 热敏打印机配对。

为了使用 python-escpos 库,我需要创建一个串行端口

/dev/rfcomm
,我可以使用
sudo rfcomm bind /dev/rfcomm0 XX:XX:XX:XX:XX:XX 1
来完成。

如何在 Python 中以编程方式完成此操作(无需使用

python-subprocess
)?

python bluetooth rfcomm
1个回答
0
投票

rfcomm
是 2017 年 BlueZ 项目弃用的工具之一。我建议您避免使用与此相关的功能。

python-escpos
库获取串行端口设备的位置,因此我建议使用Python pty库,它创建两个伪设备,即pts,模拟硬件串行端口设备。

您想要如何构建它取决于您的项目,但我做了一个简单的测试,其中我有一个脚本创建一个伪串行端口,如果收到数据,它会侦听并发送到 BLE 设备:

import os
import pty
from time import sleep

import pydbus

dev_addr = 'xx:xx:xx:xx:xx:xx'

ptmx_fd, pts_fd = pty.openpty()
pts_name = os.ttyname(pts_fd)
print(f"Printer port: {pts_name}")

bus = pydbus.SystemBus()

mngr = bus.get('org.bluez', '/')


def get_characteristic_path(dev_path, uuid):
    mng_objs = mngr.GetManagedObjects()
    for path in mng_objs:
        chr_uuid = mng_objs[path].get('org.bluez.GattCharacteristic1', {}).get('UUID')
        if path.startswith(dev_path) and chr_uuid == uuid.casefold():
            return path


class MyRemoteDevice:
    # CHAR_UUID = '0000ff02-0000-1000-8000-00805f9b34fb'  # Real printer
    CHAR_UUID = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E'  # my test device

    def __init__(self, mac_addr):
        device_path = f"/org/bluez/hci0/dev_{mac_addr.replace(':', '_')}"
        self.device = bus.get('org.bluez', device_path)

        # Placeholder for characteristic details
        self.characteristic = None

    def _get_gatt_details(self):
        char_path = get_characteristic_path(self.device._path,
                                            MyRemoteDevice.CHAR_UUID)
        self.characteristic = bus.get('org.bluez', char_path)

    def connect(self):
        self.device.Connect()
        # Check GATT services have been resolved before continuing
        while not self.device.ServicesResolved:
            sleep(0.25)
        self._get_gatt_details()

    def disconnect(self):
        self.device.Disconnect()

    def read(self):
        return self.characteristic.ReadValue({})

    def write(self, new_value):
        self.characteristic.WriteValue(new_value, {})


my_first_dev = MyRemoteDevice(dev_addr)

my_first_dev.connect()
try:
    while True:
        data = os.read(ptmx_fd, 1000)
        if data:
            print("data received:", data)
            my_first_dev.write(data)
except:
    pass
finally:
    my_first_dev.disconnect()

在 Python 提示符下,我使用 escpos 库将值发送到串行端口:

from escpos.printer import Serial
# 9600 Baud, 8N1, Flow Control Enabled
p = Serial(devfile='/dev/pts/3',
           baudrate=9600,
           bytesize=8,
           parity='N',
           stopbits=1,
           timeout=1.00,

p.text("Hello Printer#")
© www.soinside.com 2019 - 2024. All rights reserved.