-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathreporter.js
93 lines (82 loc) · 2.23 KB
/
reporter.js
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
const Influx = require('influx');
const os = require('os');
const hostname = process.env.HOSTNAME || os.hostname();
const db = process.env.INFLUX_DB || 'miners_db';
const { Client } = require('tplink-smarthome-api');
const client = new Client();
const influx = new Influx.InfluxDB({
host: process.env.INFLUX_HOST || 'localhost',
database: db,
schema: [
{
measurement: 'power_consumption',
fields: {
current: Influx.FieldType.FLOAT,
voltage: Influx.FieldType.FLOAT,
total: Influx.FieldType.FLOAT,
power: Influx.FieldType.FLOAT,
},
tags: [
'host'
]
}
]
});
class Reporter {
export(res) {
influx.writePoints([
{
measurement: 'power_consumption',
tags: {host: hostname},
fields: res,
}
])
}
getDevice () {
return client.getDevice({host: process.env.DEVICE_IP_ADDR})
.then(device => {
this.device = device;
return device;
})
}
constructor() {
this.timer = process.env.TIMER || 5000;
this.device = null;
}
query() {
return this.device.emeter.getRealtime()
}
format(raw) {
delete raw.err_code;
return raw
}
log(res) {
if (!process.env.DEBUG) return res;
console.log(res);
return res
}
checkDatabase() {
return influx.getDatabaseNames()
.then(names => {
if (!names.includes(db)) {
return influx.createDatabase(db);
}
})
.catch(err => {
console.error(`Error creating Influx database!`);
})
}
run() {
this.checkDatabase()
.then(_ => this.getDevice())
.then(_ => {
setInterval(_ => {
this.query()
.then(res => this.format(res))
.then(res => this.log(res))
.then(res => this.export(res))
}, this.timer)
});
}
}
module.exports = Reporter;