pythonpython-3.xbluetoothraspberry-pihc-05

can't connect a socket to bluetooth paired device


I'm trying to connect my Raspberry Pi 3B to an Arduino that has an HC-05 bluetooth chip to send commands. I have successfully paired between the HC-05 and the Pi using

Device 98:7B:F3:57:76:34
    Name: BT05
    Alias: BT05
    Paired: yes
    Trusted: yes
    Blocked: no
    Connected: yes
    LegacyPairing: no
    UUID: Generic Access Profile    (00001800-0000-1000-8000-00805f9b34fb)
    UUID: Generic Attribute Profile (00001801-0000-1000-8000-00805f9b34fb)
    UUID: Device Information        (0000180a-0000-1000-8000-00805f9b34fb)
    UUID: Unknown                   (0000ffe0-0000-1000-8000-00805f9b34fb)
    Modalias: bluetooth:v000Dp0000d0110

Now I'm trying to use Python to send commands. My code is:

import bluetooth

bd_addr = "98:7B:F3:57:76:34"

def connect ():
    port = 1
    sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    print("Trying to pair to", bd_addr)
    sock.connect((bd_addr, port))
    a = "a"
    while a != 'quit':
        a = input("<<< ")
        sock.send(a)
    sock.close()

connect()

I get an exception while running the code, saying that the host is down, and I can't find the problem:

python3 tests/bt.py 
Trying to pair to 98:7B:F3:57:76:34
Traceback (most recent call last):
  File "<string>", line 3, in connect
_bluetooth.error: (112, 'Host is down')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "tests/bt.py", line 16, in <module>
    connect()
  File "tests/bt.py", line 9, in connect
    sock.connect((bd_addr, port))
  File "<string>", line 5, in connect
bluetooth.btcommon.BluetoothError: (112, 'Host is down')

I've tried replacing the HC-05 device and restarting the bluetooth service, and the Pi but I still can't seem to connect to Arduino, and I'm lost.

Thanks to all helpers


Solution

  • I fixed the issue by doing 2 things: First of all, only one out of my 5 HC-05 modules is OK, which made solving the other half of the issue very hard.

    The other solution came from this post. I changed the class section in

    /etc/bluetooth/main.conf
    

    to:

    Class = 0x400100
    

    And that's it. I don't even need to pair my device after a reboot (of the Arduino or the Pi). This code connects the Pi and the Arduino and sends all commands.