在python 3中重新建立掉线的蓝牙连接
我已经使用内置套接字库在Python 3中编写了一个模拟蓝牙键盘(由RPi执行)的小程序。 尽管有一个特点,它仍可以正常工作
当真正的蓝牙键盘连接到设备时,设备和键盘都会以某种方式记住其他设备。 当键盘被关闭并重新启动时,它会自动重新连接到启动,而不必明确触发它。 (我试图再次连接到设备[没有绑定,听,接受],但它不工作)
那么,我该如何实现这样的行为呢? 启动脚本时,它应该在设备站点上没有手动连接请求的情况下进行连接。
编辑:由于它被要求,这里是连接过程(缩短)的代码:
import socket
import subprocess
import dbus
[...]
class btsSocket():
#define some constants
P_CTRL =17 #Service port - must match port configured in SDP record
P_INTR =19 #Service port - must match port configured in SDP record#Interrrupt port
def __init__(self, btAddress, btUuid, btServiceRecordUrl, btDeviceName, btDeviceClass):
self._init_bluez_profile(btUuid, btServiceRecordUrl) #set up a bluez profile to advertise device capabilities from a loaded service record
self._init_bt_device(btDeviceName, btDeviceClass) #configure the bluetooth hardware device
self._listen(btAddress)
#configure the bluetooth hardware device
def _init_bt_device(self, deviceName, deviceClass):
#set the device class to a keybord and set the name
subprocess.call(["hciconfig", "hcio", "class", deviceClass])
subprocess.call(["hciconfig", "hcio", "name", deviceName])
#make the device discoverable
subprocess.call(["hciconfig", "hcio", "piscan"])
#set up a bluez profile to advertise device capabilities from a loaded service record
def _init_bluez_profile(self, uuid, serviceRecordUrl):
[...]
#listen for incoming client connections
def _listen(self, address):
self.scontrol = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_L2CAP)
self.sinterrupt = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_L2CAP)
#bind these sockets to a port - port zero to select next available
self.scontrol.bind((address, self.P_CTRL))
self.sinterrupt.bind((address, self.P_INTR))
#Start listening on the server sockets
self.scontrol.listen(1) # Limit of 1 connection
self.sinterrupt.listen(1)
self.ccontrol, cinfo = self.scontrol.accept()
print ("Got a connection on the control channel from " + cinfo[0])
self.cinterrupt, cinfo = self.sinterrupt.accept()
print ("Got a connection on the interrupt channel from " + cinfo[0])
#send a string to the bluetooth host machine
def send_string(self, message):
self.cinterrupt.send(message)
创建此类的对象将Pi设置为聆听模式,直到用相应菜单中的设备(我想要连接到该设备)进行导航,搜索附近的蓝牙键盘(又名Pi)并单击它。 打开它时,真正的蓝牙键盘才会连接(如果它之前已正确连接)。
链接地址: http://www.djcxy.com/p/58321.html