-
Notifications
You must be signed in to change notification settings - Fork 16
/
smartcollector.go
234 lines (207 loc) · 6.44 KB
/
smartcollector.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
// SmartThings sensor data to prometheus gateway
//
// This is a simple SmartThing to Prometheus collector. It uses the textfile collector
// capabilities of the prometheus node exporter to generate interesting data about sensors
// in your SmartThings location.
//
// Check the README.md for installation instructions.
//
// http://github.com/marcopaganini/smartcollector
// (C) 2016 by Marco Paganini <[email protected]>
package main
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"strconv"
"github.com/marcopaganini/gosmart"
"golang.org/x/net/context"
)
const (
// Prefix for the token file under the home directory.
tokenFilePrefix = ".smartcollector"
// Where your node exporter looks for textfile collector files. This is
// passed to node_exporter with the -collector.textfile.directory
// command-line argument.
textFileCollectorDir = "/run/textfile_collector"
// Time series textfile collector filename
textFileCollectorName = "smartcollector.prom"
)
var (
flagClient = flag.String("client", "", "OAuth Client ID")
flagSecret = flag.String("secret", "", "OAuth Secret")
flagTextFileCollectorDir = flag.String("textfile-dir", textFileCollectorDir, "Textfile Collector directory")
flagDryRun = flag.Bool("dry-run", false, "Just print the values (don't save to file)")
)
func main() {
flag.Parse()
// No date on log messages
log.SetFlags(0)
if *flagClient == "" {
log.Fatalf("Must specify Client ID (--client)")
}
tfile := tokenFilePrefix + "_" + *flagClient + ".json"
// Create the oauth2.config object and get a token
config := gosmart.NewOAuthConfig(*flagClient, *flagSecret)
token, err := gosmart.GetToken(tfile, config)
if err != nil {
log.Fatalf("Error fetching token: %v", err)
}
// Create a client with the token and fetch endpoints URI.
ctx := context.Background()
client := config.Client(ctx, token)
endpoint, err := gosmart.GetEndPointsURI(client, gosmart.EndPointsURI)
if err != nil {
log.Fatalf("Error reading endpoints URI: %v\n", err)
}
// Iterate over all devices and collect timeseries info.
devs, err := gosmart.GetDevices(client, endpoint)
if err != nil {
log.Fatalf("Error reading list of devices: %v\n", err)
}
ts := []string{}
for _, dev := range devs {
devinfo, err := gosmart.GetDeviceInfo(client, endpoint, dev.ID)
if err != nil {
log.Fatalf("Error reading device info: %v\n", err)
}
t, err := getTimeSeries(devinfo)
if err != nil {
log.Fatalf("Error processing sensor data: %v\n", err)
}
ts = append(ts, t...)
}
// Save timeseries (or just print if dry-run active)
if *flagDryRun {
for _, v := range ts {
fmt.Println(v)
}
} else {
f := filepath.Join(*flagTextFileCollectorDir, textFileCollectorName)
if err := saveTimeSeries(f, ts); err != nil {
log.Fatalf("Error saving timeseries: %v\n", err)
}
}
}
// saveTimeSeries saves the array of strings to a temporary file and renames
// the resulting file into a node exporter textfile collector file.
func saveTimeSeries(fname string, ts []string) error {
// Silly temp name. Uniqueness should be sufficient (famous last words...)
tempfile := fmt.Sprintf("%s-%d-%d", fname, os.Getpid(), os.Getppid())
// Create file and write every ts line into it, adding newline.
w, err := os.Create(tempfile)
if err != nil {
return err
}
defer w.Close()
for _, v := range ts {
w.Write([]byte(v + "\n"))
}
w.Close()
// Rename to real name
err = os.Rename(tempfile, fname)
if err != nil {
return err
}
return nil
}
// getTimeSeries returns a prometheus compatible timeseries from the device data.
func getTimeSeries(devinfo *gosmart.DeviceInfo) ([]string, error) {
var err error
var value float64
valOpenClosed := []string{"open", "closed"}
valInactiveActive := []string{"inactive", "active"}
valAbsentPresent := []string{"not present", "present"}
valOffOn := []string{"off", "on"}
ret := []string{}
for k, val := range devinfo.Attributes {
// Some sensors report nil as a value (instead of a blank string) so we
// convert nil to an empty string to avoid issues with type assertion.
if val == nil {
val = ""
}
switch k {
case "alarmState":
value, err = valueClear(val)
case "battery":
value, err = valueFloat(val)
case "carbonMonoxide":
value, err = valueClear(val)
case "contact":
value, err = valueOneOf(val, valOpenClosed)
case "energy":
value, err = valueFloat(val)
case "motion":
value, err = valueOneOf(val, valInactiveActive)
case "power":
value, err = valueFloat(val)
case "presence":
value, err = valueOneOf(val, valAbsentPresent)
case "smoke":
value, err = valueClear(val)
case "switch":
value, err = valueOneOf(val, valOffOn)
case "temperature":
value, err = valueFloat(val)
default:
// We only process keys we know about.
continue
}
if err != nil {
return nil, err
}
ret = append(ret, fmt.Sprintf("smartthings_sensors{id=\"%s\",name=\"%s\",attr=\"%v\"} %v", devinfo.ID, devinfo.DisplayName, k, value))
}
return ret, nil
}
// valueClear expects a string and returns 0 for "clear", 1 for anything else.
// TODO: Expand this to properly identify non-clear conditions and return error
// in case an unexpected value is found.
func valueClear(v interface{}) (float64, error) {
val, ok := v.(string)
if !ok {
return 0.0, fmt.Errorf("invalid non-string argument %v", v)
}
if val != "clear" {
return 0.0, nil
}
return 1.0, nil
}
// valueOneOf returns 0.0 if the value matches the first item
// in the array, 1.0 if it matches the second, and an error if
// nothing matches.
func valueOneOf(v interface{}, options []string) (float64, error) {
val, ok := v.(string)
if !ok {
return 0.0, fmt.Errorf("invalid non-string argument %v", v)
}
if val == options[0] {
return 0.0, nil
}
if val == options[1] {
return 1.0, nil
}
return 0.0, fmt.Errorf("invalid option %q. Expected %q or %q", val, options[0], options[1])
}
// valueFloat returns the float64 value of the value passed or
// error if the value cannot be converted. Accepts float64 and
// strings as valid arguments.
func valueFloat(v interface{}) (float64, error) {
switch val := v.(type) {
case string:
ret, err := strconv.ParseFloat(val, 64)
if err != nil {
return 0.0, fmt.Errorf("unable to convert %q to float: %v", val, v)
}
return ret, nil
case float64:
ret, ok := v.(float64)
if !ok {
return 0.0, fmt.Errorf("unable to convert \"%v\" to string", v)
}
return ret, nil
}
return 0.0, fmt.Errorf("invalid type for \"%v\": %T", v, v)
}