Python Bluetooth how to send a file to a phone

情到浓时终转凉″ 提交于 2019-12-05 21:32:11

You're most of the way there...

As you know, you need something to talk to at the other end of your Bluetooth connection. You just need to replace your custom server with a well-known service (generally one of these options).

In my case, my phone supports the "OBEX Object Push" service, so I just need to connect to that and use a suitable client to talk the right protocol. Fortunately, the combination of PyOBEX and PyBluez does the trick here!

The following code (quickly patched together from PyOBEX and PyBluez samples) runs on my Windows 10, Python 2.7 installation and creates a simple text file on the phone.

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()

Looks like PyOBEX is a pretty minimal package, though, and isn't Python 3 compatible, so you may have a little porting to do if that's a requirement.

I haven't personally explored it but check out this blog -

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

The author uses the lightblue package as an API for the Obex protocol and send files over the connection. Now the lightblue package appears to be unmaintained. There are other packages like PyObex (which I could not import for whatever reason) which you could also explore as alternatives but lightblue seems to be the way to go.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!