File: agent.go

package info (click to toggle)
golang-github-muka-go-bluetooth 5.60-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 2,688 kB
  • sloc: makefile: 92; sh: 2
file content (76 lines) | stat: -rw-r--r-- 1,467 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package agent_example

import (
	"fmt"

	"github.com/godbus/dbus/v5"
	"github.com/muka/go-bluetooth/api"
	"github.com/muka/go-bluetooth/bluez/profile/adapter"
	"github.com/muka/go-bluetooth/bluez/profile/agent"
	log "github.com/sirupsen/logrus"
)

// ToDo: allow enabling "simple pairing" (sspmode set via hcitool)
func Run(deviceAddress, adapterID string) error {

	defer api.Exit()

	//Connect DBus System bus
	conn, err := dbus.SystemBus()
	if err != nil {
		return err
	}

	ag := agent.NewSimpleAgent()
	err = agent.ExposeAgent(conn, ag, agent.CapKeyboardDisplay, true)
	if err != nil {
		return fmt.Errorf("SimpleAgent: %s", err)
	}

	a, err := adapter.GetAdapter(adapterID)
	if err != nil {
		return err
	}

	devices, err := a.GetDevices()
	if err != nil {
		return fmt.Errorf("GetDevices: %s", err)
	}

	found := false
	for _, dev := range devices {

		if dev.Properties.Address != deviceAddress {
			continue
		}

		if dev.Properties.Paired {
			continue
		}

		found = true
		// log.Info(i, v.Path)
		log.Infof("Pairing with %s", dev.Properties.Address)

		err := dev.Pair()
		if err != nil {
			return fmt.Errorf("Pair failed: %s", err)
		}

		log.Info("Pair succeed, connecting...")
		agent.SetTrusted(adapterID, dev.Path())

		err = dev.Connect()
		if err != nil {
			return fmt.Errorf("Connect failed: %s", err)
		}

	}

	if !found {
		return fmt.Errorf("No device found that need to be paired on %s", adapterID)
	}

	log.Info("Working...")
	select {}
}