-
Notifications
You must be signed in to change notification settings - Fork 2
/
sensor.go
72 lines (64 loc) · 1.48 KB
/
sensor.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
package termux
import (
"bytes"
"context"
"encoding/json"
"strings"
"github.com/eternal-flame-AD/go-termux/internal/chanbuf"
)
// SensorList acquires a list of available sensors on the device
func SensorList() ([]string, error) {
buf := bytes.NewBuffer([]byte{})
if err := execAction("Sensor", nil, buf, "list"); err != nil {
return nil, err
}
res := buf.Bytes()
if err := checkErr(res); res != nil {
return nil, err
}
l := new(struct {
Sensors []string `json:"sensors"`
})
if err := json.Unmarshal(res, l); err != nil {
return nil, err
}
return l.Sensors, nil
}
// SensorWatchOpt represents the options to a Sensor call
type SensorWatchOpt struct {
Limit int
DelayMS int
SensorList []string
}
// Sensor starts a sensor watch in a given context and options
// returns raw data bytes encooded with JSON
func Sensor(ctx context.Context, opt SensorWatchOpt) (<-chan []byte, error) {
response := make(chan []byte)
param := map[string]interface{}{}
if opt.SensorList == nil {
param["all"] = true
} else {
param["sensors"] = strings.Join(opt.SensorList, ",")
}
if opt.DelayMS != 0 {
param["dalay"] = opt.DelayMS
}
if opt.Limit != 0 {
param["limit"] = opt.Limit
}
if err := execContext(ctx, nil, chanbuf.BufToChan{
C: response,
}, "Sensor", param, ""); err != nil {
return nil, err
}
go func() {
defer execAction("Sensor", nil, bytes.NewBuffer([]byte{}), "cleanup")
for {
select {
case <-ctx.Done():
return
}
}
}()
return response, nil
}