-
Notifications
You must be signed in to change notification settings - Fork 1
/
communicator_linux.go
65 lines (56 loc) · 1.59 KB
/
communicator_linux.go
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
package bluetooth
import (
"fmt"
"golang.org/x/sys/unix"
)
// NOTE: https://github.com/golang/go/issues/52325
var _ Communicator = &bluetooth{}
type bluetooth struct {
log Log
FileDescriptor int
SocketAddr *unix.SockaddrRFCOMM
Addr string
}
func Connect(params Params) (Communicator, error) {
fd, err := unix.Socket(unix.AF_BLUETOOTH, unix.SOCK_STREAM, unix.BTPROTO_RFCOMM)
if err != nil {
return &bluetooth{
log: params.Log,
FileDescriptor: fd,
Addr: params.Address,
}, err
}
params.Log.Print("unix socket returned a file descriptor: ", fd)
socketAddr := &unix.SockaddrRFCOMM{Addr: addressToByteArray(params.Address), Channel: 6}
if err := unix.Connect(fd, socketAddr); err != nil {
return &bluetooth{
log: params.Log,
FileDescriptor: fd,
SocketAddr: socketAddr,
Addr: params.Address,
}, err
}
params.Log.Print("unix socket linked with an RFCOMM")
return &bluetooth{
log: params.Log,
FileDescriptor: fd,
SocketAddr: socketAddr,
Addr: params.Address,
}, nil
}
func (b *bluetooth) Read(dataLen int) (int, []byte, error) {
var data = make([]byte, dataLen)
n, err := unix.Read(b.FileDescriptor, data)
if err != nil {
return 0, nil, err
}
b.log.Print(fmt.Sprintf(">>>>>>>>>>>> protoComm.Read: %v", data[:n]))
return n, data, nil
}
func (b *bluetooth) Write(d []byte) (int, error) {
b.log.Print(fmt.Sprintf(">>>>>>>>>>>> protoComm.Write: %v", d))
return unix.Write(b.FileDescriptor, d)
}
func (b bluetooth) Close() error {
return unix.Close(b.FileDescriptor)
}