generated from homebridge/homebridge-plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathco2signal.ts
46 lines (37 loc) · 1.14 KB
/
co2signal.ts
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
import { Logger } from 'homebridge';
import * as http from 'https';
export class CO2SignalClient {
private readonly logger: Logger;
private readonly apiKey: string;
private readonly location: string;
constructor(logger: Logger, apiKey: string, location: string) {
this.logger = logger;
this.apiKey = apiKey;
this.location = location;
}
async getCO2Intensity(): Promise<number> {
this.logger.debug('Getting CO₂ intensity for', this.location);
return new Promise((resolve, reject) => {
let data = '';
http.get({
host: 'api.co2signal.com',
path: '/v1/latest?countryCode=' + this.location,
headers: { 'auth-token': this.apiKey },
}, (res) => {
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
if (res.statusCode !== 200) {
return reject(new Error('unexpected status code:' + res.statusCode));
}
const val = JSON.parse(data);
return resolve(val.data.carbonIntensity);
});
res.on('error', (err) => {
return reject(err);
});
});
});
}
}