python3蓝牙通讯_与Python 3.3蓝牙服务器

Python3.3开始支持蓝牙套接字,但相关文档不足。尽管有介绍客户端实现的博客,但创建服务器和广告服务的资料匮乏。文章提到了pybluez库可以作为解决方案,尽管它自2009年以来未更新。pybluez依赖于BlueZ库来实现蓝牙功能,并提供了广告服务的代码示例。若不想使用pybluez,可能需要借助c-types自己实现缺失的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python 3.3 came with native support for bluetooth sockets. Unfortunately, it's not too well documented yet (there is only one mention of it in the documentation).

Googling it there is a blog post about implementing a client, but I couldn't find anything about creating a server.

More specifically, how to set the user-friendly name and advertise the service.

So, something like

import socket

serverSocket = socket.socket(socket.AF_BLUETOOTH,

socket.SOCK_STREAM,

socket.BTPROTO_RFCOMM)

serverSocket.setTimeout(1)

serverSocket.bind(("", 1))

serverSocket.listen(1)

something.advertise_service(something something)

Any ideas?

解决方案

Bad news:

Python doesn't appear to support what you want to do out of the box. (At least not in socketmodule.c).

Most of the python/bluetooth users I've seen use pybluez although it hasn't been updated since 2009.

Good news:

I went through their source (for Linux connections), and found the relevant bits for advertising services. Most of the code is essentially copy-pasted from the python 2.2 version of socketmodule.c.

pybluez does define some additional functionality for a socket object to implement all those bluetooth goodies. It doesn't get too low-level, and instead depends on BlueZ for that. From what I can tell, it basically takes python objects and creates the data structures expected by BlueZ and just calls that.

If you don't want to/can't use pybluez, you'll have to somehow implement this missing functionality. I think you may be able to do it with c-types. The relevant parts for advertising the service are in btmodule.c, lines 2562-2642.

There is a python-3 branch in the source for pybluez, although I don't know if it works or not.

If you do decide to use pybluez, an example taken from their source

server_sock=BluetoothSocket( RFCOMM )

server_sock.bind(("",PORT_ANY))

server_sock.listen(1)

port = server_sock.getsockname()[1]

uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"

advertise_service(server_sock, "SampleServer",

service_id = uuid,

service_classes = [ uuid, SERIAL_PORT_CLASS ],

profiles = [ SERIAL_PORT_PROFILE ],

)

As google code is closing, the code can also be found on github here.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值