forked from ToddGreenfield/homebridge-airnow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
314 lines (292 loc) · 16.1 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
"use strict";
// AirNow (Air Quality Sensor) Accessory for HomeBridge
//
// Remember to add accessory to config.json. Example:
// "accessories": [
// {
// "accessory": "airnow", // required (all lowercase)
// "name": "AirNow", // required - For homebridge and logging
// "provider": "airnow", // Optional - Service Provider - defaults to airnow. Valid options are: airnow, aqicni, gamta.
//
// "airnow_api": "XXXXXX", // Optional - Required for AirNow.gov YOUR_API key from AirNowapi.org OR Aqicn (waqi)
// "zipcode": "90210", // Optional - Required for AirNow.gov - Zip code for area being checked
// "distance": "25", // Optional - Only used for AirNow.gov - Defaults to 25 miles from zip
//
// "aqicn_api": "XXXXXXX" // Optional - Required for Aqicn.org YOUR_API key from aqcin.org (Provided by api.waqi.info)
// "aqicn_city": "@245", // Optional - Only For Aqicn.org - Valid city @code from http://aqicn.org/city/all/ OR defaults to 'here' which will use Geolocation based on your IP.
//
// "gamta_station": "0002" // Optional - check Your nearest station ID http://stoteles.gamta.lt/ap3/
//
// "polling": "30" // Optional - defaults to OFF or 0. Time in minutes.
// }
// ],
//
//
var lowerCase = require('lower-case');
var request = require("request");
var striptags = require("striptags");
var Service, Characteristic;
var airQualityService;
module.exports = function (homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory("homebridge-airnow", "airnow", AirNowAccessory);
}
function AirNowAccessory(log, config) {
this.log = log;
this.name = config['name'];
this.provider = lowerCase(config['provider']) || "airnow";
this.zip = config['zipcode'];
this.distance = config['distance'] || '25';
this.airnow_api = config['airnow_api'];
this.aqicn_api = config['aqicn_api'];
this.aqicn_city = config['aqicn_city'] || 'here';
this.gamta_station = config['gamta_station'];
this.mpolling = config['polling'] || '0'; // Default is no polling.
this.polling = this.mpolling;
if (!this.provider) throw new Error("AirNow - You must provide a config value for 'provider'.");
if (this.provider == "airnow" && !this.zip) throw new Error("AirNow - You must provide a config value for 'zipcode' if using provider Airnow.com.");
if (this.provider == "airnow" && !this.airnow_api) throw new Error("AirNow - You must provide a config value for 'airnow_api' if using provider Airnow.gov.");
if (this.provider == "aqicn" && !this.aqicn_api) throw new Error("AirNow - You must provide a config value for 'aqicn_api' if using provider Aqicn.org.");
if (this.provider == "gamta" && !this.gamta_station) throw new Error("AirNow - You must provide a config value for 'gamta_station' if using provider stoteles.gamta.lt.");
if (this.polling > 0) {
var that = this;
this.polling *= 60000;
setTimeout(function() {
that.servicePolling();
}, this.polling);
};
if (this.provider == "gamta") {
this.log.info("AirNow using provider %s, station %s and Polling (minutes) is: %s", this.provider, this.gamta_station, (this.polling == '0') ? 'OFF' : this.mpolling);
} else {
this.log.info("AirNow using provider %s and Polling (minutes) is: %s", this.provider, (this.polling == '0') ? 'OFF' : this.mpolling);
}
}
AirNowAccessory.prototype = {
servicePolling: function(){
//this.log.debug('AirNow Polling...');
this.log.info('AirNow Polling...');
this.getObservation(function(p) {
var that = this;
that.airQualityService.setCharacteristic(Characteristic.AirQuality, p);
setTimeout(function() {
that.servicePolling();
}, that.polling);
}.bind(this));
},
getAirQuality: function(callback){
this.getObservation(function(a) {
callback(null, a);
});
},
getObservation: function (callback) {
var that = this;
var url, aqi;
aqi = 0;
if (this.provider == "airnow") {
url = "http://www.airnowapi.org/aq/observation/zipCode/current/?format=application/json&zipCode=" + this.zip +
"&distance=" + this.distance + "&API_KEY=" + this.airnow_api;
request({
url: url,
json: true
}, function (err, response, observations) {
if (!err && response.statusCode === 200){
if (typeof observations[0] === 'undefined'){
that.log.error("AirNow air quality Configuration Error - Invalid ZipCode for %s.", that.provider);
that.airQualityService.setCharacteristic(Characteristic.StatusFault,1);
} else if (typeof observations[0]["AQI"] === 'undefined') {
that.log.error("AirNow air quality Observation Error - %s for %s.", striptags(observations), that.provider);
that.airQualityService.setCharacteristic(Characteristic.StatusFault,1);
} else {
for (var key in observations) {
switch (observations[key]["ParameterName"]) {
case 'O3':
that.airQualityService.setCharacteristic(Characteristic.OzoneDensity,parseFloat(observations[key]["AQI"]));
break;
case 'PM2.5':
that.airQualityService.setCharacteristic(Characteristic.PM2_5Density,parseFloat(observations[key]["AQI"]));
break;
case 'PM10':
that.airQualityService.setCharacteristic(Characteristic.PM10Density,parseFloat(observations[key]["AQI"]));
break;
}
aqi = Math.max(aqi,parseFloat(observations[key]["AQI"])) // AirNow.gov defaults to MAX returned observation.
}
//that.log.debug("AirNow air quality AQI is: %s", aqi.toString());
that.log.info("AirNow air quality AQI is: %s", aqi.toString());
that.airQualityService.setCharacteristic(Characteristic.StatusFault,0);
}
} else {
that.log.error("AirNow air quality Network or Unknown Error from %s.", that.provider);
that.airQualityService.setCharacteristic(Characteristic.StatusFault,1);
}
callback(that.trans_aqi(aqi));
});
} else if (this.provider == "aqicn") {
url = "http://api.waqi.info/feed/" + this.aqicn_city + "/?token=" + this.aqicn_api;
request({
url: url,
json: true
}, function (err, response, observations) {
if (!err && response.statusCode === 200 && observations.status == "ok" && observations.data.idx != "-1"){
//that.log.debug("AirNow air quality AQI is: %s", observations.data.aqi);
that.log.info("AirNow air quality AQI is: %s", observations.data.aqi);
that.airQualityService.setCharacteristic(Characteristic.StatusFault,0);
(observations.data.iaqi.hasOwnProperty('o3')) ? that.airQualityService.setCharacteristic(Characteristic.OzoneDensity,parseFloat(observations.data.iaqi.o3.v)) : that.airQualityService.setCharacteristic(Characteristic.OzoneDensity,0);
(observations.data.iaqi.hasOwnProperty('no2')) ? that.airQualityService.setCharacteristic(Characteristic.NitrogenDioxideDensity,parseFloat(observations.data.iaqi.no2.v)) : that.airQualityService.setCharacteristic(Characteristic.NitrogenDioxideDensity,0);
(observations.data.iaqi.hasOwnProperty('so2')) ? that.airQualityService.setCharacteristic(Characteristic.SulphurDioxideDensity,parseFloat(observations.data.iaqi.so2.v)) : that.airQualityService.setCharacteristic(Characteristic.SulphurDioxideDensity,0);
(observations.data.iaqi.hasOwnProperty('pm25')) ? that.airQualityService.setCharacteristic(Characteristic.PM2_5Density,parseFloat(observations.data.iaqi.pm25.v)) : that.airQualityService.setCharacteristic(Characteristic.PM2_5Density,0);
(observations.data.iaqi.hasOwnProperty('pm10')) ? that.airQualityService.setCharacteristic(Characteristic.PM10Density,parseFloat(observations.data.iaqi.pm10.v)) : that.airQualityService.setCharacteristic(Characteristic.PM10Density,0);
(observations.data.iaqi.hasOwnProperty('co')) ? that.airQualityService.setCharacteristic(Characteristic.CarbonMonoxideLevel,parseFloat(observations.data.iaqi.co.v)) : that.airQualityService.setCharacteristic(Characteristic.CarbonMonoxideLevel,0);
// (observations.data.iaqi.hasOwnProperty('??')) ? that.airQualityService.setCharacteristic(Characteristic.VOCDensity,parseFloat(observations.data.iaqi.??.v)) : that.airQualityService.setCharacteristic(Characteristic.VOCDensity,0);
// (observations.data.iaqi.hasOwnProperty('??')) ? that.airQualityService.setCharacteristic(Characteristic.CarbonDioxideLevel,parseFloat(observations.data.iaqi.??.v)) : that.airQualityService.setCharacteristic(Characteristic.CarbonDioxideLevel,0);
aqi = parseFloat(observations.data.aqi);
} else if (!err && observations.status == "error") {
that.log.error("AirNow air quality Observation Error - %s from %s.", observations.data, that.provider);
} else if (!err && observations.status == "ok" && observations.data.idx == "-1") {
that.log.error("AirNow air quality Configuration Error - Invalid City Code from %s.", that.provider);
} else {
that.log.error("AirNow air quality Network or Unknown Error from %s.", that.provider);
that.airQualityService.setCharacteristic(Characteristic.StatusFault,1);
}
callback(that.trans_aqi(aqi));
});
} else if (this.provider == "gamta") {
url = "http://stoteles.gamta.lt/ap3/SS/index.php?action=updatemap";
request({
url: url,
json: true
}, function (err, response, observations) {
var co_ppm, stotele;
co_ppm=0;
stotele=that.gamta_station;
if (!err && response.statusCode === 200 && observations.error =="ok"){
that.log.debug ("AirNow API error: %s", observations.error);
switch ( observations.result[stotele].indeksas ) {
case '1':
aqi=40;
break;
case '2':
aqi=60;
break;
case '3':
aqi=110;
break;
case '4':
aqi=160;
break;
case '5':
aqi=210;
break;
}
for (var key in observations.result[stotele].kanalai) {
switch (observations.result[stotele].kanalai[key]["kanalas"]) {
case 'CO':
//convert mg/m3 to ppm X ppm =(Y mg/m3)(24.45)/(MW), where CO MW=28.01
//check units mg/m3 vs ug/m3
if ( observations.result[stotele].kanalai[key].matavimoVnt == 'mg/m3' ) {
co_ppm= parseFloat(observations.result[stotele].kanalai[key].koncentracija) * 24.45 / 28.01;
}
else if (observations.result[stotele].kanalai[key].matavimoVnt == 'uq/m3') {
co_ppm= parseFloat(observations.result[stotele].kanalai[key].koncentracija) * 24.45 / 28.01 * 1000;
}
that.log.info ("AirNow %s CarbonMonoxydeLevel: %d", stotele, co_ppm.toFixed(2));
that.airQualityService.setCharacteristic(Characteristic.CarbonMonoxideLevel,co_ppm);
break;
case 'O3':
// take only 1hr value
if (observations.result[stotele].kanalai[key].vidurkisVal == '1') {
that.airQualityService.setCharacteristic(Characteristic.OzoneDensity,parseFloat(observations.result[stotele].kanalai[key].koncentracija));
that.log.info ("AirNow %s OzoneDensity: %d", stotele, parseFloat(observations.result[stotele].kanalai[key].koncentracija).toFixed(2));
}
break;
case 'NO2':
that.airQualityService.setCharacteristic(Characteristic.NitrogenDioxideDensity,parseFloat(observations.result[stotele].kanalai[key].koncentracija));
that.log.info ("AirNow %s NitrogenDioxideDensity: %d", stotele, parseFloat(observations.result[stotele].kanalai[key].koncentracija).toFixed(2));
break;
case 'PM10':
that.airQualityService.setCharacteristic(Characteristic.PM10Density,parseFloat(observations.result[stotele].kanalai[key].koncentracija));
that.log.info ("AirNow %s PM10Density: %d", stotele, parseFloat(observations.result[stotele].kanalai[key].koncentracija).toFixed(2));
break;
case 'PM25':
that.airQualityService.setCharacteristic(Characteristic.PM2_5Density,parseFloat(observations.result[stotele].kanalai[key].koncentracija));
that.log.info ("AirNow %s PM2_5Density: %d", stotele, parseFloat(observations.result[stotele].kanalai[key].koncentracija).toFixed(2));
break;
case 'SO2':
// take only 1hr value
if (observations.result[stotele].kanalai[key].vidurkisVal == '1') {
that.airQualityService.setCharacteristic(Characteristic.SulphurDioxideDensity,parseFloat(observations.result[stotele].kanalai[key].koncentracija));
that.log.info ("AirNow %s SulphurDioxideDensity: %d", stotele, parseFloat(observations.result[stotele].kanalai[key].koncentracija).toFixed(2));
}
break;
}
}
} else if (!err && response.statusCode === 200 && observations.error !="ok") {
that.log.error("AirNow air quality Observation Error - %s from %s.", observations.error, that.provider);
} else {
that.log.error("AirNow air quality Network or Unknown Error from %s.", that.provider);
that.airQualityService.setCharacteristic(Characteristic.StatusFault,1);
}
callback(that.trans_aqi(aqi));
});
}
},
trans_aqi: function (aqi) {
/*
Map EPA AQI Categories to HomeKit AQI Categories as follows:
+----------------------------------+------------------------+
| EPA Category | HomeKit Category |
+----------------------------------+------------------------+
| ---- | Excellent (Don't use) |
| Good | Good |
| Moderate | Fair |
| Unhealthy for Sensitive Groups | Inferior |
| Unhealthy | Inferior |
| Very Unhealthy | Poor |
| Hazardous | Poor |
+----------------------------------+------------------------+
Note that Apple Home app will show the sensor 'on' for Inferior and above
*/
if (!aqi) {
return(0); // Error or unknown response
} else if (aqi <= 50) { // EPA "Good"
return(2); // Return HomeKit GOOD (Don't use HomeKit EXCELLENT category)
} else if (aqi >= 51 && aqi <= 100) { // EPA "Moderate"
return(3); // Return HomeKit FAIR
} else if (aqi >= 101 && aqi <= 150) { // EPA "Unhealthy for Sensitive Groups"
return(4); // Return HomeKit INFERIOR
} else if (aqi >= 151 && aqi <= 200) { // EPA "Unhealthy"
return(4); // Return HomeKit INFERIOR
} else if (aqi >= 201) { // EPA "Very Unhealthy" and "Hazardous"
return(5); // Return HomeKit POOR (HomeKit only goes to cat 5, so combine the last two EPA AQI categories.
} else {
return(0); // Error or unknown response.
}
},
identify: function (callback) {
this.log("Identify requested!");
callback(); // success
},
getServices: function () {
var services = []
var informationService = new Service.AccessoryInformation();
informationService
.setCharacteristic(Characteristic.Manufacturer, this.provider)
.setCharacteristic(Characteristic.Model, (this.provider == "aqicn") ? ((this.aqicn_city == "here") ? "GeoLocation" : this.aqicn_city) : (this.provider == 'gamta' ? this.gamta_station : "Zip:" + this.zip))
.setCharacteristic(Characteristic.SerialNumber, "Polling: " + this.mpolling);
services.push(informationService);
this.airQualityService = new Service.AirQualitySensor(this.name);
this.airQualityService
.getCharacteristic(Characteristic.AirQuality)
.on('get', this.getAirQuality.bind(this));
this.airQualityService.addCharacteristic(Characteristic.StatusFault); // Used if unable to connect to AQI services
this.airQualityService.addCharacteristic(Characteristic.OzoneDensity);
this.airQualityService.addCharacteristic(Characteristic.NitrogenDioxideDensity);
this.airQualityService.addCharacteristic(Characteristic.SulphurDioxideDensity);
this.airQualityService.addCharacteristic(Characteristic.PM2_5Density);
this.airQualityService.addCharacteristic(Characteristic.PM10Density);
this.airQualityService.addCharacteristic(Characteristic.CarbonMonoxideLevel);
services.push(this.airQualityService);
return services;
}
};