根据蓝牙对请求运行功能

2024-05-23 23:15:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近一直在学习使用arduino的电路,并希望对我的Raspberry Pi应用程序进行一些更改

几年前,我用这个过时的教程创建了我的pi bluetooth接收器,目前它工作得很好(https://www.instructables.com/id/Turn-your-Raspberry-Pi-into-a-Portable-Bluetooth-A/),但这个过时的教程的一个缺点是,必须通过屏幕接受蓝牙连接(由于蓝牙扬声器没有屏幕,所以关闭了屏幕)

我的计划:使用按钮接受蓝牙连接,并使用闪烁的绿色LED指示连接请求

如何创建“侦听”蓝牙配对请求的脚本,并在侦听时相应地运行python代码?这样,我如何连接到蓝牙以接受配对请求

我不太熟悉Raspberry Pi脚本的位置,但我熟悉Python,知道如何连接到GPIO

谢谢:)


Tags: https脚本com应用程序屏幕wwwpi教程
2条回答

你试过使用this Python library吗?它列出了Raspberry Pi支持

此外,以下是有关侦听传入蓝牙连接的一些信息:

Bluetooth programming in Python follows the socket programming model. This is a concept that should be familiar to almost all network programmers, and makes the transition from Internet programming to Bluetooth programming much simpler. Example 3-2 and Example 3-3 show how to establish a connection using an RFCOMM socket, transfer some data, and disconnect.

import bluetooth

server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )

port = 1
server_sock.bind(("",port))
server_sock.listen(1)

client_sock,address = server_sock.accept()
print "Accepted connection from ",address

data = client_sock.recv(1024)
print "received [%s]" % data

client_sock.close()
server_sock.close()

An RFCOMM BluetoothSocket used to accept incoming connections must be attached to operating system resources with the bind method. bind takes in a tuple specifying the address of the local Bluetooth adapter to use and a port number to listen on. Usually, there is only one local Bluetooth adapter or it doesn't matter which one to use, so the empty string indicates that any local Bluetooth adapter is acceptable. Once a socket is bound, a call to listen puts the socket into listening mode and it is then ready to accept incoming connections.

...

Source

您正在搜索的称为蓝牙代理。您需要使用正式的linux蓝牙协议栈BlueZ。有描述代理APIlink的文档。它使用DBus进行通信。您需要调用以下步骤:

  1. 创建一个用python编写的bluetooth代理,并将其发布到特定的DBus对象路径。您的代理必须实现org.bluez.Agent1接口,如代理API文档中所述
  2. 然后,您需要通过从代理API调用RegisterAgent方法来注册此代理。在这里,您将提供代理所在的DBus路径,并且您还将在您的案例中提供功能“DisplayYesNo”(LED作为配对请求的显示器,按钮带有一些超时以实现是/否)
  3. 通过调用RequestDefaultAgent

  4. 现在,如果您尝试与设备配对,代理中的相应函数将被调用(我认为对于您的用例,它将是RequestAuthorization),如果您想要接受配对,您将从该函数返回,如果您想要拒绝配对,您必须在该函数中抛出DBus错误

作为您的起点,我建议您看看这个简单的python代理:https://github.com/pauloborges/bluez/blob/master/test/simple-agent 它实现了您需要的所有功能,因此只需根据您的需要进行更新即可

玩得开心:)

相关问题 更多 >