通过蓝牙串口与Python通信

时间:2016-04-18 14:14:54

标签: android python linux bluetooth

如何通过蓝牙和Python处理和接收串行数据?

我试图制作一个简单的Python服务器,通过蓝牙explained here访问数据。

我的server.py文件在发送文本" temp"时发送一个随机数:

#!/usr/bin/env python

import os
import glob
import time
import random

from bluetooth import *

def read_temp():
    return random.random()

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, "TestServer",
                   service_id = uuid,
                   service_classes = [ uuid, SERIAL_PORT_CLASS ],
                   profiles = [ SERIAL_PORT_PROFILE ], 
#                   protocols = [ OBEX_UUID ] 
                    )
while True:          
    print "Waiting for connection on RFCOMM channel %d" % port

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

    try:
        data = client_sock.recv(1024)
        if len(data) == 0: break
        print "received [%s]" % data

        if data == 'temp':
            data = str(read_temp())+'!'
            client_sock.send(data)
        else:
            data = 'WTF!' 
            client_sock.send(data)
        print "sending [%s]" % data

    except IOError:
        pass

    except KeyboardInterrupt:

        print "disconnected"

        client_sock.close()
        server_sock.close()
        print "all done"

        break

当我第一次运行时,我收到错误:

bluetooth.btcommon.BluetoothError: (2, 'No such file or directory')

可以通过启用兼容模式并通过编辑文件/lib/systemd/system/bluetooth.service并更改行来加载序列配置文件来修复Googled showed {/ 3>}

ExecStart=/usr/lib/bluetooth/bluetoothd

为:

ExecStart=/usr/lib/bluetooth/bluetoothd -C

然后运行sudo sdptool add SP

现在python server.py似乎没有错误地运行,我可以将运行它的机器与我的Android手机配对。但是,它似乎无法接收任何数据。

我尝试使用蓝牙终端仿真应用程序,如BlueTerm,BT Simple Terminal和Arduino BT,但是当我连接到服务器时输入文本并按回车键,{{1}没有响应}。它最初会报告一个"接受的连接......"收到并清空了字符串,但之后没有收到任何内容。

由于没有报告明确的错误,我不确定如何诊断问题。我如何确定问题是否存在于我的Python代码中?还是服务器上的蓝牙配置?还是我的Android手机?

2 个答案:

答案 0 :(得分:3)

正确的代码是:

#!/usr/bin/env python
"""
A simple test server that returns a random number when sent the text "temp" via Bluetooth serial.
"""

import os
import glob
import time
import random

from bluetooth import *

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, "TestServer",
                   service_id = uuid,
                   service_classes = [ uuid, SERIAL_PORT_CLASS ],
                   profiles = [ SERIAL_PORT_PROFILE ], 
#                   protocols = [ OBEX_UUID ] 
                    )

print "Waiting for connection on RFCOMM channel %d" % port
client_sock, client_info = server_sock.accept()
print "Accepted connection from ", client_info

while True:          

    try:
        req = client_sock.recv(1024)
        if len(req) == 0:
            break
        print "received [%s]" % req

        data = None
        if req in ('temp', '*temp'):
            data = str(random.random())+'!'
        else:
            pass

        if data:
            print "sending [%s]" % data
            client_sock.send(data)

    except IOError:
        pass

    except KeyboardInterrupt:

        print "disconnected"

        client_sock.close()
        server_sock.close()
        print "all done"

        break

答案 1 :(得分:0)

您还可以查看 bleak,参见 https://pypi.org/project/bleak/ Bleak 是 GATT 客户端软件,能够连接到充当 GATT 服务器的 BLE 设备。它旨在提供异步、跨平台的 Python API 来连接和通信,例如传感器