【发布时间】:2015-06-14 13:49:32
【问题描述】:
我有一个非常特殊的 Android 蓝牙问题:
我有一个设备(几乎没有文档),它充当蓝牙客户端并尝试连接(配对后)到使用 UUID“1234”进行侦听的蓝牙服务器。我已经使用 python 脚本预先测试过,该设备可以工作并且可以连接到服务器。脚本中的相关代码是:
import bluetooth
uuid = "1234"
pc = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
pc.bind(("", bluetooth.PORT_ANY))
pc.listen(1)
port = pc.getsockname()[1]
print 'Active RFCOMM port: ', port, '\r\n'
bluetooth.advertise_service( pc, "Server",
service_id = uuid,
service_classes = [ uuid, bluetooth.SERIAL_PORT_CLASS ],
profiles = [ bluetooth.SERIAL_PORT_PROFILE ]
)
print 'Waiting for connection...\r\n'
address = pc.accept()
print 'Accepting connection from: ', address, '\r\n'
我正在尝试使用 BluetoothServerSocket 在 Android 上创建类似的服务器。根据article,我已将 16 位 UUID(“1234”)转换为“00001234-0000-1000-8000-00805F9B34FB”。我已经使用 python 脚本测试了服务器是有效的,并且我可以使用指定的 UUID 连接到它。使用的代码非常标准,因为它可以在互联网上的许多示例中找到:
@Override
public void run() {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
Timber.i("Start Server");
try {
final BluetoothServerSocket bluetoothServer = adapter.listenUsingRfcommWithServiceRecord("Server", mUUID);
Timber.i("Server Started: " + mUUID.toString());
BluetoothSocket socket = bluetoothServer.accept();
Timber.i("Socket initiated: " + socket.getRemoteDevice().getName());
bluetoothServer.close();
} catch (IOException e) {
Timber.e("Error starting server: " + e.getMessage());
}
}
我已经尝试过listenUsingRfcommWithServiceRecord 和listenUsingInsecureRfcommWithServiceRecord。我已确保手机和设备已配对并且手机可被发现。我尝试过使用具有不同操作系统版本(2.3.7、4.0.3、4.4.2、5.1.0)的不同手机,因为我认为 Android 4.2 中蓝牙堆栈的变化是问题所在。似乎没有任何东西可以使设备连接到我的手机。我还可以提供设备尝试连接时捕获的 Nexus 5 的 hci 转储,但我无法确定问题所在。
任何帮助将不胜感激。
编辑:
这是用于验证Android蓝牙服务器的python代码:
import sys
import bluetooth
uuid = "1234"
service_matches = bluetooth.find_service( uuid = uuid )
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)
sock = bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((host, port))
sock.send("Test")
sock.close()
不用说它没有任何问题。
【问题讨论】:
-
请也发布您的客户端代码?