bluetooth icon indicating copy to clipboard operation
bluetooth copied to clipboard

Question: How do I pair devices with security code?

Open Aukstkalnis opened this issue 1 year ago • 3 comments

Hello. I am trying to find out how to pair to a central device that requires a pairing key. I could not find any info in the examples. Should I use another library for this purpose? Or should I directly interact with bluetoochctl (a.k.a bluez)?

Use case: I am writhing application that connects to device, makes some configuration and disconnects. So, there will be a lot of devices and each has its own pairing code.

Aukstkalnis avatar May 27 '24 14:05 Aukstkalnis

Hey, I had a similar problem and made a fork with some additions to gap_linux.go and adapter_linux.go to connect and pair with my bluetooth LE devices. Basically what is needed is to register a "KeyboardOnly" agent which will allow us to programatically supply the pin code.

This is a cut down version, you need to scan and connect the device, then this code shows how to pair and trust the device

package main

import (
	"log"
	"github.com/robinlecouteur/go-bluetooth"
)

func main() {
	// Assuming you already have a connected device
	var device bluetooth.Device // your already connected device
	
	// Pair with PIN code
	if err := device.Pair("123456"); err != nil {
		log.Fatalf("Pairing failed: %v", err)
	}
	
	// Optional: Trust for future connections
	if err := device.TrustDevice(); err != nil {
		log.Printf("Trust failed: %v", err)
	}
	
	// Check status
	paired, _ := device.IsPaired()
	trusted, _ := device.IsTrusted()
	log.Printf("Paired: %t, Trusted: %t", paired, trusted)
}

The bluetoothctl equivelant would be like this:

bluetoothctl  # Enter bluetoothctl
agent off
agent KeyboardOnly #  This will make it prompt for pin on the command line
default-agent

scan on # Need to scan the device before connecting/pairing
connect FF:FF:FF:FF:FF:FF # connect with mac address of your device
pair FF:FF:FF:FF:FF:FF # pair with mac address of your device

# At this point you should be prompted for the pin code. I think running just connect will usually prompt for the code too, but if not, pair should do it
scan off # stop scanning 

paired-devices # Should return a list of paired devices
info FF:FF:FF:FF:FF:FF # Gives you details about the device

I also experimented with running that programatically using expect with bluetoothctl, so that's one way to do it as well.

Hopefully this helps others looking into this :)

robinlecouteur avatar Jun 18 '25 01:06 robinlecouteur

We don't support security features at this time. We really should add support for those some day though.

aykevl avatar Sep 24 '25 11:09 aykevl

OK. Thanks. I worked around this problem using bluetoochctl and go's exec routine.

Aukstkalnis avatar Sep 24 '25 23:09 Aukstkalnis