generated from jamiekieranmartin/go-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bluetooth.go
81 lines (63 loc) · 1.29 KB
/
bluetooth.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package bluetooth
import (
"time"
"tinygo.org/x/bluetooth"
)
var adapter = bluetooth.DefaultAdapter
type Config struct {
Duration time.Duration
Debug bool
}
type Scanner struct {
config *Config
}
const (
DEFAULT_DURATION = 10 * time.Second
DEFAULT_DEBUG = false
)
func NewScanner(cfg ...*Config) *Scanner {
var config *Config
if len(cfg) > 0 && cfg[0] != nil {
config = cfg[0]
} else {
config = &Config{
Duration: DEFAULT_DURATION,
Debug: DEFAULT_DEBUG,
}
}
if config.Duration <= 0 {
config.Duration = DEFAULT_DURATION
}
return &Scanner{config}
}
func (s *Scanner) Start() chan Event {
if err := adapter.Enable(); err != nil {
panic(err)
}
duration := s.config.Duration
events := make(chan Event)
go func() {
defer close(events)
if err := adapter.Scan(func(adapter *bluetooth.Adapter, event bluetooth.ScanResult) {
events <- Event{
Address: event.Address.String(),
Name: event.LocalName(),
RSSI: event.RSSI,
CreatedAt: time.Now(),
}
}); err != nil {
panic(err)
}
}()
go func() {
time.Sleep(duration)
adapter.StopScan()
}()
return events
}
type Event struct {
Address string `json:"address"`
Name string `json:"name"`
RSSI int16 `json:"rssi"`
CreatedAt time.Time `json:"created_at"`
}