/
cm160.go
73 lines (57 loc) · 1018 Bytes
/
cm160.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
package cm160
import (
"log"
"github.com/kylelemons/gousb/usb"
)
type CM160 struct {
device *usb.Device
}
type Record struct {
Volt int
Year int
Month int
Day int
Hour int
Minute int
Cost float32
Amps float32
IsLive bool
Watt float32
}
var ctx *usb.Context
func init() {
ctx = usb.NewContext()
}
const (
CM160_VENDOR = 0x0fde
CM160_PRODUCT = 0xca05
)
func isCM160(desc *usb.Descriptor) bool {
return desc.Vendor == usb.ID(CM160_VENDOR) &&
desc.Product == usb.ID(CM160_PRODUCT)
}
// Open initializes and returns a device
func Open() *CM160 {
devices, err := ctx.ListDevices(isCM160)
if err != nil {
log.Fatal(err)
}
if len(devices) == 0 {
return nil
}
for i, v := range devices {
if i != 0 {
v.Close()
}
}
d := devices[0]
d.SetConfig(1)
return &CM160{device: d}
}
// Register a callback to process each Record produced by the device
func (c *CM160) Register(cb func(*Record)) {
}
// Close the device
func (c *CM160) Close() {
c.device.Close()
}