【问题标题】:Android Bluetooth RFCOMM directly to Raspberry Pi without pairingAndroid 蓝牙 RFCOMM 直接连接树莓派,无需配对
【发布时间】:2017-07-09 08:58:46
【问题描述】:

我需要制作一个通过RFCOMM socketRaspberry Pi 通信的应用程序,无需配对。 在 Android 端,我有 RPi 的 MAC 地址,我正在尝试使用以下代码连接到服务器:

BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
BluetoothSocket mmSocket = null;

    try {
        mmSocket = device.createRfcommSocketToServiceRecord(UUID);
        mmSocket.connect();
        Log.d(TAG, "mmSocket returned");
    }
    ...

UUID 和服务器端的一样,我也试过用 createInsecureRfcommSocket 方法。

在 Raspberry Pi 方面,我使用了 rfcomm 服务器的 pybluez 示例(here is the example)

它曾经有效,但我不明白为什么有效或为什么不再有效,因为当我尝试从手机启动连接时,我在 Raspberry Pi 上收到了配对请求,但没有配对请求手机上,android上的socket对象已经连接成功了。

有谁知道我做错了什么,或者任何可能对我有帮助的想法,而且这样的事情甚至是可行的。 提前致谢。

【问题讨论】:

    标签: android bluetooth raspberry-pi rfcomm pybluez


    【解决方案1】:

    我发现了这个未回答的问题,并且我认为至少对于我的情况来说我有一个可行的解决方案。

    我需要做的就是调用这三个命令:

    sudo hciconfig hci0 piscan 
    sudo hciconfig hci0 sspmode 1
    sudo hciconfig hci0 class 0x400100
    

    前两行使 RPi 可被发现,from this answer,它还声称 RPi 应该自动配对。这对我不起作用。它仍然需要在两台设备上进行 PIN 确认,这对于无头 RPi 来说是不幸的。

    this answer 中的第三行至关重要,它允许将 RFCOMM 套接字连接到未配对的 RPi。 有可能改class会导致其他BT服务停止工作,不确定,我只需要RFCOMM。

    在此之后,以下示例适用于我的 RPI 4B 和我的 Win10 笔记本电脑:

    import socket
    from contextlib import closing
    
    # MAC address of RPi, can be obtained with `bluetoothctl list` on RPi.
    rpi_addr =  'e4:5f:01:7d:8A:A3' 
    # 1-32, some might be used already, e.g. 3 for me, in that case bind fails.
    channel = 15
    def server():
    
        print("Creating socket")
        with closing(socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, 
        socket.BTPROTO_RFCOMM)) as s:
            print("Binding socket")
            s.bind((rpi_addr ,channel))
            print("Listening socket")
            s.listen()
    
            s_sock, addr = s.accept()
            with closing(s_sock):
                print ("Accepted connection from "+str(addr))
    
                data = s_sock.send(b"Hello from RPi")
    
    def client():
    
        print("Creating socket")
        s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, 
        socket.BTPROTO_RFCOMM)
        print("Connecting socket")
        s.connect((rpi_addr,channel))
        print("Connected")
    
        data = s.recv(1024)
    
        print(f"Received {data}")
    

    【讨论】:

      猜你喜欢
      • 2013-04-09
      • 2015-10-25
      • 2012-06-22
      • 2016-04-08
      • 2021-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多