Debian Codegraph @

linux/device.go

raw symbols SCIP
1 package linux
2
3 import (
4 "errors"
5 "log"
6 "sync"
7 "syscall"
8 "unsafe"
9
10 "github.com/paypal/gatt/linux/gioctl"
11 "github.com/paypal/gatt/linux/socket"
12 )
13
14 type device struct {
15 fd int
16 dev int
17 name string
18 rmu *sync.Mutex
19 wmu *sync.Mutex
20 }
21
22 func newDevice(n int, chk bool) (*device, error) {
23 fd, err := socket.Socket(socket.AF_BLUETOOTH, syscall.SOCK_RAW, socket.BTPROTO_HCI)
24 if err != nil {
25 return nil, err
26 }
27 if n != -1 {
28 return newSocket(fd, n, chk)
29 }
30
31 req := devListRequest{devNum: hciMaxDevices}
32 if err := gioctl.Ioctl(uintptr(fd), hciGetDeviceList, uintptr(unsafe.Pointer(&req))); err != nil {
33 return nil, err
34 }
35 for i := 0; i < int(req.devNum); i++ {
36 d, err := newSocket(fd, i, chk)
37 if err == nil {
38 log.Printf("dev: %s opened", d.name)
39 return d, err
40 }
41 }
42 return nil, errors.New("no supported devices available")
43 }
44
45 func newSocket(fd, n int, chk bool) (*device, error) {
46 i := hciDevInfo{id: uint16(n)}
47 if err := gioctl.Ioctl(uintptr(fd), hciGetDeviceInfo, uintptr(unsafe.Pointer(&i))); err != nil {
48 return nil, err
49 }
50 name := string(i.name[:])
51 // Check the feature list returned feature list.
52 if chk && i.features[4]&0x40 == 0 {
53 err := errors.New("does not support LE")
54 log.Printf("dev: %s %s", name, err)
55 return nil, err
56 }
57 log.Printf("dev: %s up", name)
58 if err := gioctl.Ioctl(uintptr(fd), hciUpDevice, uintptr(n)); err != nil {
59 if err != syscall.EALREADY {
60 return nil, err
61 }
62 log.Printf("dev: %s reset", name)
63 if err := gioctl.Ioctl(uintptr(fd), hciResetDevice, uintptr(n)); err != nil {
64 return nil, err
65 }
66 }
67 log.Printf("dev: %s down", name)
68 if err := gioctl.Ioctl(uintptr(fd), hciDownDevice, uintptr(n)); err != nil {
69 return nil, err
70 }
71
72 // Attempt to use the linux 3.14 feature, if this fails with EINVAL fall back to raw access
73 // on older kernels.
74 sa := socket.SockaddrHCI{Dev: n, Channel: socket.HCI_CHANNEL_USER}
75 if err := socket.Bind(fd, &sa); err != nil {
76 if err != syscall.EINVAL {
77 return nil, err
78 }
79 log.Printf("dev: %s can't bind to hci user channel, err: %s.", name, err)
80 sa := socket.SockaddrHCI{Dev: n, Channel: socket.HCI_CHANNEL_RAW}
81 if err := socket.Bind(fd, &sa); err != nil {
82 log.Printf("dev: %s can't bind to hci raw channel, err: %s.", name, err)
83 return nil, err
84 }
85 }
86 return &device{
87 fd: fd,
88 dev: n,
89 name: name,
90 rmu: &sync.Mutex{},
91 wmu: &sync.Mutex{},
92 }, nil
93 }
94
95 func (d device) Read(b []byte) (int, error) {
96 d.rmu.Lock()
97 defer d.rmu.Unlock()
98 return syscall.Read(d.fd, b)
99 }
100
101 func (d device) Write(b []byte) (int, error) {
102 d.wmu.Lock()
103 defer d.wmu.Unlock()
104 return syscall.Write(d.fd, b)
105 }
106
107 func (d device) Close() error {
108 return syscall.Close(d.fd)
109 }