-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
288 lines (261 loc) · 9.5 KB
/
index.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
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
"use strict";
var Service, Characteristic;
var purpleAirService;
var request = require('request');
module.exports = function (homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory("homebridge-purpleair", "PurpleAir", PurpleAirAccessory);
};
/**
* PurpleAir Accessory
*/
function PurpleAirAccessory(log, config) {
this.log = log;
// Name and API key from PurpleAir
this.name = config['name'];
this.purpleID = config['purpleID'];
this.updateFreq = config['updateFreq'];
this.lastupdate = 0;
this.cache = undefined;
this.log.info("PurpleAir is working");
if (this.updateFreq == undefined) this.updateFreq = 300 // default 5 minutes
this.updateMsecs = this.updateFreq * 1000;
}
PurpleAirAccessory.prototype = {
/**
* Get all Air data from PurpleAir
*/
getPurpleAirData: function (callback) {
var self = this;
var aqi = 0;
var url = 'https://www.purpleair.com/json?show=' + this.purpleID;
// Make request only every updateFreq seconds (PurpleAir actual update frequency is around 40 seconds, but we really don't need that precision here}
var timenow = Date.now();
// this.log("getPurpleAirData called... lastupdate: %s, now: %s, freq: %s", this.lastupdate.toString(), timenow.toString(), this.updateMsecs.toString());
if (this.lastupdate === 0 || ((this.lastupdate + this.updateMsecs) < timenow) || this.cache === undefined) {
request({
url: url,
json: true,
}, function (err, response, data) {
// If no errors
if (!err && (response.statusCode === 200)) {
aqi = self.updateData(data, 'Fetch');
callback(null, self.transformAQI(aqi));
// If error
} else {
purpleAirService.setCharacteristic(Characteristic.StatusFault, 1);
self.log.error("PurpleAir Network or Unknown Error.");
callback(err);
};
});
// Return cached data
} else {
aqi = self.updateData(self.cache, 'Cache');
callback(null, self.transformAQI(aqi));
};
},
/**
* Update data
*/
updateData: function (data, type) {
var self = this;
purpleAirService.setCharacteristic(Characteristic.StatusFault, 0);
// PurpleAir outdoor sensors send data from two internal sensors, but indoor sensors only have one
// We have to verify exterior/interior, and if exterior, whether both sensors are working or only 1
var statsA; // = undefined;
var statsB;
var newest = 0;
var single = null;
if (data.results != undefined) {
if (data.results[0] != undefined) {
// stats[0] = undefined
if (data.results[0].Stats != undefined) statsA = JSON.parse(data.results[0].Stats);
if (data.results[0].DEVICE_LOCATIONTYPE != 'inside') {
// outside sensor, check for both sensors and find the one updated most recently
if (data.results[1] != undefined) {
//stats[1] = undefined
if (data.results[1].Stats != undefined) statsB = JSON.parse(data.results[1].Stats);
if (statsA.lastModified > statsB.lastModified) { // lastModified is epoch time in milliseconds
newest = statsA.lastModified;
} else {
newest = statsB.lastModified;
}
}
} else {
// indoor sensor - make sure the data is valid
// stats[1] = undefined;
if ((data.results[0].A_H != true) && (data.results[0].PM2_5Value != undefined) && (data.results[0].PM2_5Value != null)) {
single = 0;
newest = statsA.lastModified;
} else {
single = -1;
}
}
if (newest == this.lastupdate) { // no change
// nothing changed, return cached value?
if ((type != 'Cache') && (this.cache != undefined)) {
return self.updateData(this.cache, 'Cache');
} else {
return 0;
}
}
// Now, figure out which PM2_5Value we are using
if (single == null) {
if ((data.results[0].A_H == true) || (data.results[0].PM2_5Value == undefined) || (data.results[0].PM2_5Value == null)) {
// A is bad
if ((data.results[1].A_H == true) || (data.results[1].PM2_5Value == undefined) || (data.results[1].PM2_5Value == null)) {
// A bad, B bad
single = -1;
} else {
// A bad, B good
single = 1;
}
} else {
// Channel A is good
if ((data.results[1].A_H == true) || (data.results[1].PM2_5Value == undefined) || (data.results[1].PM2_5Value == null)) {
// A good, B bad
single = 0;
} else {
// A good, B good
single = 2;
}
}
}
var pm
var aqi
var aqiCode
if (single >= 0) {
if (single == 2) {
pm = Math.round( ((statsA.v + statsB.v)/2.0) * 100) / 100;
} else if (single == 0) {
pm = Math.round(statsA.v * 100) / 100;
} else {
pm = Math.round(statsB.v * 100) / 100;
}
aqi = Math.round(self.calculateAQI(pm));
} else {
// No valid data - return cached value?
if ((type != 'Cache') && (self.cache != undefined)) {
return self.updateData( self.cache, 'Cache');
} else {
return 0;
}
}
purpleAirService.setCharacteristic(Characteristic.PM2_5Density, pm.toString());
// purpleAirService.setCharacteristic(Characteristic.AirQualityIndex, aqi.toString());
// PM10 data isn't available via this PurpleAir API
// airService.setCharacteristic(Characteristic.PM10Density, data.pm10);
self.log.info("[%s] PurpleAir pm2_5 is %s, AQI is %s, Air Quality is %s.", type, pm.toString(), aqi.toString(), self.airQualityString(aqi));
self.cache = data;
if (type === 'Fetch') {
self.lastupdate = newest; // Use the newest sensors' time
}
return aqi;
}
}
// No valid data - return cached value?
if ((type != 'Cache') && (self.cache != undefined)) {
return self.updateData( self.cache, 'Cache');
} else {
return 0;
}
},
calculateAQI: function(pm) {
var aqi;
var self = this;
if (pm > 500) {
aqi = 500;
} else if (pm > 350.5) {
aqi = self.remap(pm, 350.5, 500.5, 400, 500);
} else if (pm > 250.5) {
aqi = self.remap(pm, 250.5, 350.5, 300, 400);
} else if (pm > 150.5) {
aqi = self.remap(pm, 150.5, 250.5, 200, 300);
} else if (pm > 55.5) {
aqi = self.remap(pm, 55.5, 150.5, 150, 200);
} else if (pm > 35.5) {
aqi = self.remap(pm, 35.5, 55.5, 100, 150);
} else if (pm > 12) {
aqi = self.remap(pm, 12, 35.5, 50, 100);
} else if (pm > 0) {
aqi = self.remap(pm, 0, 12, 0, 50);
} else { aqi = 0 }
return aqi;
},
/**
* Return Air Quality Index
* @param aqi
* @returns {number}
*/
transformAQI: function (aqi) {
// this.log("Transforming %s.", aqi.toString())
if (aqi == undefined) {
return (0); // Error or unknown response
} else if (aqi <= 50) {
return (1); // Return EXCELLENT
} else if (aqi <= 100) {
return (2); // Return GOOD
} else if (aqi <= 150) {
return (3); // Return FAIR
} else if (aqi <= 200) {
return (4); // Return INFERIOR
} else if (aqi > 200) {
return (5); // Return POOR (Homekit only goes to cat 5, so combined the last two AQI cats of Very Unhealty and Hazardous.
}
},
airQualityString: function(aqi) {
if (aqi == undefined) {
return ("Unknown"); // Error or unknown response
} else if (aqi <= 50) {
return ("Excellent"); // Return EXCELLENT
} else if (aqi <= 100) {
return ("Good"); // Return GOOD
} else if (aqi <= 150) {
return ("Fair"); // Return FAIR
} else if (aqi <= 200) {
return ("Inferior"); // Return INFERIOR
} else if (aqi > 200) {
return ("Poor"); // Return POOR (Homekit only goes to cat 5, so combined the last two AQI cats of Very Unhealty and Hazardous.
}
},
remap: function(value, fromLow, fromHigh, toLow, toHigh) {
var fromRange = fromHigh - fromLow;
var toRange = toHigh - toLow;
var scaleFactor = toRange / fromRange;
// Re-zero the value within the from range
var tmpValue = value - fromLow;
// Rescale the value to the to range
tmpValue *= scaleFactor;
// Re-zero back to the to range
return tmpValue + toLow;
},
identify: function (callback) {
this.log("Identify requested!");
callback(); // success
},
getServices: function () {
var services = [];
/**
* Informations
*/
var informationService = new Service.AccessoryInformation();
informationService
.setCharacteristic(Characteristic.Manufacturer, "PurpleAir")
.setCharacteristic(Characteristic.Model, "JSON_API")
.setCharacteristic(Characteristic.SerialNumber, this.purpleID);
services.push(informationService);
/**
* PurpleAirService
*/
purpleAirService = new Service.AirQualitySensor(this.name);
purpleAirService
.getCharacteristic(Characteristic.AirQuality)
.on('get', this.getPurpleAirData.bind(this));
purpleAirService.addCharacteristic(Characteristic.StatusFault);
purpleAirService.addCharacteristic(Characteristic.PM2_5Density);
// purpleAirService.addCharacteristic(Characteristic.AirQualityIndex);
services.push(purpleAirService);
return services;
}
};