/
data-source.go
76 lines (68 loc) · 1.35 KB
/
data-source.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
package main
import (
"encoding/json"
ohaus "github.com/kf8a/ohaus"
"log"
)
type dataSource struct {
connections map[*connection]bool
register chan *connection
unregister chan *connection
port string
}
func newDataSource() *dataSource {
return &dataSource{
connections: make(map[*connection]bool),
register: make(chan *connection),
unregister: make(chan *connection),
port: "/dev/ttyUSB0",
}
}
// the one place where we talk to the insturment
func (q *dataSource) readData(cs chan string, test bool) {
var data ohaus.Datum
c := make(chan ohaus.Datum)
scale := ohaus.Scale{PortName: q.port}
if test {
go scale.TestReader(c)
} else {
go scale.Reader(c)
}
for {
data = <-c
result, err := json.Marshal(data)
if err != nil {
log.Fatal(err)
}
cs <- string(result)
}
}
func (q *dataSource) read(test bool) {
cs := make(chan string)
go q.readData(cs, test)
for {
select {
case c := <-q.register:
q.connections[c] = true
case c := <-q.unregister:
if q.connections[c] {
log.Println("closing")
q.connections[c] = false
delete(q.connections, c)
close(c.send)
log.Println(q)
}
default:
data := <-cs
log.Println(q)
for c := range q.connections {
select {
case c.send <- []byte(data):
default:
delete(q.connections, c)
close(c.send)
}
}
}
}
}