-
Notifications
You must be signed in to change notification settings - Fork 3
/
scanner.go
92 lines (84 loc) · 2.09 KB
/
scanner.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
82
83
84
85
86
87
88
89
90
91
92
package beacon
import (
"fmt"
"sync"
"time"
)
// Scanner scans for beacons with a given ble interface (i.e., BlueZ, BLE112, CoreBluetooth)
type Scanner struct {
device ScanDevice
parsers []*Parser
beaconChannel chan Slice
done chan bool
beacons Slice
}
// ScanData represents a possible beacon advertisement that can be parsed into a beacon
type ScanData struct {
Bytes []byte
Device string
AddressType uint8
AdvType uint8
Channel uint8
RSSI int8
Raw *[]byte
}
// A ScanDevice will return ScanData on a channel. Currently the only implementation is
// BLE112Device.
type ScanDevice interface {
Scan(data chan ScanData, done chan bool)
}
// NewScanner initializes a new Scanner which will scan using the given ScanDevice and
// look for beacons given the list of beacon Parsers.
func NewScanner(d ScanDevice, p []*Parser) *Scanner {
var s Scanner
s.device = d
s.parsers = p
return &s
}
// Scan will scan for beacons and return a list of beacons that it detects on the interval
// given in cycleTime. It will stop scanning when it receives something on the done channel.
func (s *Scanner) Scan(cycleTime time.Duration, output chan Slice, done chan bool) {
data := make(chan ScanData)
doneOut := make(chan bool)
var wg sync.WaitGroup
wg.Add(1)
go func() {
timer := time.NewTimer(cycleTime)
s.beacons = s.beacons[:0] // clear beacons slice
loop:
for {
select {
case scan, more := <-data:
if !more {
break loop
}
s.processScan(scan)
case <-done:
doneOut <- true
case <-timer.C:
output <- s.beacons
s.beacons = s.beacons[:0] // clear beacons slice
timer = time.NewTimer(cycleTime)
}
}
fmt.Printf("boom\n")
timer.Stop()
wg.Done()
}()
s.device.Scan(data, doneOut)
wg.Wait()
}
func (s *Scanner) processScan(scan ScanData) {
beacon := Parse(scan.Bytes, s.parsers)
if beacon == nil {
return
}
beacon.Device = scan.Device
found := s.beacons.Find(beacon)
if found != nil {
found.AddRSSI(scan.RSSI)
} else {
beacon.AddRSSI(scan.RSSI)
s.beacons = append(s.beacons, beacon)
}
}