-
Notifications
You must be signed in to change notification settings - Fork 5
/
btaddr_linux.go
56 lines (48 loc) · 944 Bytes
/
btaddr_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
package main
import (
"strconv"
"strings"
"syscall"
"log"
"golang.org/x/sys/unix"
)
type BTConn struct {
fd int
}
func str2ba(addr string) [6]byte {
a := strings.Split(addr, ":")
var b [6]byte
for i, tmp := range a {
u, _ := strconv.ParseUint(tmp, 16, 8)
b[len(b)-1-i] = byte(u)
}
return b
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func NewBT(id string) *BTConn {
mac := str2ba(id)
bt := &BTConn{fd: -1}
fd, err := unix.Socket(syscall.AF_BLUETOOTH, syscall.SOCK_STREAM, unix.BTPROTO_RFCOMM)
check(err)
bt.fd = fd
addr := &unix.SockaddrRFCOMM{Addr: mac, Channel: 1}
err = unix.Connect(bt.fd, addr)
check(err)
return bt
}
func (bt *BTConn) Read(buf []byte) (int, error) {
n, err := unix.Read(bt.fd, buf)
return n, err
}
func (bt *BTConn) Write(buf []byte) (int, error) {
n, err := unix.Write(bt.fd, buf)
return n, err
}
func (bt *BTConn) Close() error {
unix.Close(bt.fd)
return nil
}