Python蓝牙如何将文件发送到手机

在我目前的项目中,这是一个需要通过蓝牙从Windows电脑发送到Android设备的文件,除了标准状态,当然还有配对的蓝牙连接,没有任何东西在电话上。 我已经看了pybluez,它似乎很简单,发送文件之间的客户端和服务器体系结构(实际上它让我的笔记本电脑和桌面之间发送相当快),但我不能为我的生活find任何方式让python一旦连接build立,从计算机发送一个文件到android; 我的尝试一直在像这样从设备上抓取蓝牙MAC地址

nearby_devices = bluetooth.discover_devices( duration=8, lookup_names=True, flush_cache=True, lookup_class=False) 

然后再尝试像这样发送文件

 port = 1 for addr, name in nearby_devices: bd_addr = addr sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM ) sock.connect((bd_addr, port)) sock.send("download-app") sock.close() 

当然,通过pybluez文档给出的示例脚本,我可以在客户端和服务器之间无缝发送文件,但是我仍然无法将文件发送到选定的Android设备(即使我指定了它的地址并知道它在范围)

你大部分的方式在那里…

如您所知,您需要在蓝牙连接的另一端与之通话。 你只需要用一个众所周知的服务(通常是这些选项之一 )替换你的自定义服务器。

在我的情况下,我的手机支持“OBEX Object Push”服务,所以我只需要连接到这个服务,并使用合适的客户端来说出正确的协议。 幸运的是,PyBEX和PyBluez的组合在这里诀窍!

下面的代码(从PyOBEX和PyBluez样本快速修补)运行在我的Windows 10,Python 2.7安装,并在手机上创建一个简单的文本文件。

 from bluetooth import * from PyOBEX.client import Client import sys addr = sys.argv[1] print("Searching for OBEX service on %s" % addr) service_matches = find_service(name=b'OBEX Object Push\x00', address = addr ) if len(service_matches) == 0: print("Couldn't find the service.") sys.exit(0) first_match = service_matches[0] port = first_match["port"] name = first_match["name"] host = first_match["host"] print("Connecting to \"%s\" on %s" % (name, host)) client = Client(host, port) client.connect() client.put("test.txt", "Hello world\n") client.disconnect() 

看起来像PyOBEX是一个非常小的软件包,但不是Python 3兼容,所以如果这是一个需求,你可能有一点移植。

我没有亲自探讨过,但看看这个博客 –

http://recolog.blogspot.com/2013/07/transferring-files-via-bluetooth-using.html

作者使用lightblue包作为Obex协议的API并通过连接发送文件。 现在这个浅蓝色包似乎没有保留。 还有其他一些软件包,比如PyObex(我无法导入),你也可以作为替代品来探索,但是浅蓝色似乎是一种方法。