3

I need to make an application that communicates through an RFCOMM socket to a Raspberry Pi, without pairing. On the Android side, I have the MAC address of the RPi and I'm trying to connect to the server using this code:

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

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

UUID is the same as on the server-side, and i've also tried using the createInsecureRfcommSocket method.

On the Raspberry Pi side, I used the pybluez example of an rfcomm server(here is the example)

It once worked but I don't understand why it did or why it doesn't anymore, in the sense that when I tried to initiate the connection from the phone I got a pairing request on the Raspberry Pi without a pairing request on the phone, and the socket object on android had successfully connected.

Does anyone know what I am doing wrong, or any ideas that might help me, and is such a thing even feasible. Thanks in advance.

4

1 回答 1

0

我发现了这个悬而未决的问题,我认为至少对于我的情况我有一个可行的解决方案。

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

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

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

在这个答案中找到的第三行至关重要,它允许将 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}")
于 2022-01-13T10:33:31.250 回答