Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Scan and pick first available hci device #369

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 49 additions & 5 deletions pkg/connector/ble/device_linux.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package ble

import (
"fmt"
"github.com/go-ble/ble"
"github.com/go-ble/ble/linux"
"github.com/go-ble/ble/linux/hci/cmd"
"log"
"time"
"os"
"path/filepath"
)

const bleTimeout = 20 * time.Second
Expand All @@ -20,9 +24,49 @@ var scanParams = cmd.LESetScanParameters{
}

func newDevice() (ble.Device, error) {
device, err := linux.NewDevice(ble.OptListenerTimeout(bleTimeout), ble.OptDialerTimeout(bleTimeout), ble.OptScanParams(scanParams))
if err != nil {
return nil, err
}
return device, nil
hciName, err := GetAvailableHCI()
if err != nil {
return nil, fmt.Errorf("failed to find available Bluetooth adapter: %w", err)
}

log.Printf("Using Bluetooth adapter: %s", hciName)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably use log.Debug


opts := []ble.Option{
ble.OptListenerTimeout(bleTimeout),
ble.OptDialerTimeout(bleTimeout),
ble.OptScanParams(scanParams),
ble.OptDeviceID(parseHCIIndex(hciName)), // Pass the detected HCI index
}

device, err := linux.NewDevice(opts...)
if err != nil {
return nil, err
}
return device, nil
}

// GetAvailableHCI returns the first available HCI device (e.g., hci0, hci1, etc.)
func GetAvailableHCI() (string, error) {
devices, err := filepath.Glob("/sys/class/bluetooth/hci*")
if err != nil {
return "", fmt.Errorf("failed to list HCI devices: %v", err)
}

for _, device := range devices {
if _, err := os.Stat(device); err == nil {
return filepath.Base(device), nil // Return first available HCI device (e.g., "hci0")
}
}

return "", fmt.Errorf("no available HCI devices found")
}

// Extract numeric index from "hciX" (e.g., "hci1" → 1)
func parseHCIIndex(hci string) int {
var index int
_, err := fmt.Sscanf(hci, "hci%d", &index)
if err != nil {
return 0 // Default to hci0 if parsing fails
}
return index
}