/
PurpleAirApi.js
332 lines (298 loc) · 12.4 KB
/
PurpleAirApi.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
class PurpleAirApi {
static CALL_DELAY = 100; // URL call delay, hopefully to reduce throttling
static boundaries = this.generateBoundaries();
static gradient = this.generateGradient();
static getSensorData(sensor)
{
let url = `https://www.purpleair.com/json?show=${sensor.id}&key=${sensor.key}`;
let errorFunc = function(sensor) { sensor.raiseError("Can't load data"); }.bind(this, sensor);
let successFunc = sensor.consumeData.bind(sensor);
this.makeTheCall(url, errorFunc, successFunc);
}
static getSensorTimeline(sensor)
{
let channel = sensor.results.THINGSPEAK_PRIMARY_ID;
let api_key = sensor.results.THINGSPEAK_PRIMARY_ID_READ_KEY;
let field = 2;
// We'll be fetching data in multiple requests, as it seems
// it's tricky to get thingspeak to return all the data we want
// in one go.
// Also, we want higher resolutions for more recent data.
let rangesToFetch = [
// after resulution(minutes)
[ 6 * HOUR, 1], // last 6h at max resolution
[ 1 * WEEK, 10], // last week at 10m
[ 2 * WEEK, 60], // previous 3(+1) weeks at 1h
[ 3 * WEEK, 60],
[ 4 * WEEK, 60],
[ 26 * WEEK, 240], // previous 5(+1) months by 4 h
];
// Helper to format dates in a way thingspeak likes them
function dateString(ago) {
return moment(Date.now() - ago).format("YYYY-MM-DD HH:mm:ss")
}
let offset = - new Date().getTimezoneOffset() / 60;
let lastStart = null;
for (let r = 0; r < rangesToFetch.length; r++) {
let range = rangesToFetch[r];
let avg = range[1];
let start = range[0];
let startStr = dateString(start);
// We fetch until the data previously fetched
let endStr = lastStart ? dateString(lastStart + avg) : "";
lastStart = start;
let url = `https://api.thingspeak.com/channels/${channel}/fields/${field}.json?start=${startStr}&end=${endStr}&offset=${offset}&round=2&average=${avg}&api_key=${api_key}`
let errorFunc = function(sensor) { sensor.raiseError("Can't load timeline data"); }.bind(this, sensor);
let successFunc = sensor.consumeTimelineData.bind(sensor);
this.makeTheCall(url, errorFunc, successFunc);
}
}
static makeTheCall(url, errorFunc, successFunc)
{
let startTime = Date.now();
function onSuccess(data)
{
let dur = Date.now() - startTime;
log(`Request succeeded in ${dur} ms, calling ${successFunc}`)
successFunc(data);
}
function onError(data)
{
log(`Handling call error, data: ${JSON.stringify(data)}`)
if (data.readyState == 4 && data.responseJSON.code == 429) {
// Possible throttling
let msg = data.responseJSON.message;
// Handle "Rate limit exceeded. Try again in XXX milli seconds."
let m = msg.match(/.*Try again in (\d+) milli.*/);
if (m && !isNaN(m[1])) {
// Throttling detected
log(`Detected throttle of ${m[1]} ms`)
run_delayed(m[1], PurpleAirApi.makeTheCall.bind(this, url, errorFunc, successFunc));
return;
}
}
if (data.readyState == 0) {
// Some weird error, retry
log("Error response, retrying");
run_delayed(1000, PurpleAirApi.makeTheCall.bind(this, url, errorFunc, successFunc));
return;
}
// Can't recover
log(`ERROR: ${data}`);
errorFunc(data);
}
log(`Calling PurpleAir URL: ${url}`);
run_delayed(this.CALL_DELAY, () =>
$.ajax({
type: "GET",
url: url,
processData: false,
error: onError.bind(this),
success: onSuccess.bind(this)
}));
}
static generateBoundaries()
{
log("generateBoundaries(): start")
let comp = val => "0".concat(val.toString(16)).substr(-2,2);
function rgb(r, g, b) {
return "#" + comp(r) + comp(g) + comp(b);
}
function rgba(r, g, b, a) {
return "#" + comp(r) + comp(g) + comp(b) + comp(a);
}
let boundary_data = [
[ 0, [104,225,67], "Good"],
[ 50, [255,255,85], "Moderate"],
[ 100, [239,133,51], "Unhealthy for S.G."],
[ 150, [234,51,36], "Unhealthy"],
[ 200, [140,26,75], "Very Unhealthy"],
[ 300, [115,20,37], "Hazardous"],
[ 500, [65,0,25], "Here be monsters"],
[ 1000, [65,0,25], ""],
];
this.boundaries_max = 1000;
let boundaries = boundary_data.map(v => {
return {
low: v[0],
color: rgb(v[1][0], v[1][1], v[1][2]),
rgb: v[1],
label: v[2]
}
});
boundaries.forEach((v,i, a) => a[i].high = a[i + 1]?.low || 1000);
log("generateBoundaries(): end")
return boundaries;
}
static generateGradient()
{
function rgb(r, g, b) {
let comp = val => "0".concat(val.toString(16)).substr(-2,2);
return "#" + comp(r) + comp(g) + comp(b);
}
let gradient_colors = this.boundaries.map(v => {
return {
color: v.color,
pos: v.low / this.boundaries_max
}
});
return tinygradient(gradient_colors);
}
static aqiColor(aqi)
{
let gray = "#aaa";
if (isNaN(aqi)) {
return gray;
}
aqi = Math.min(aqi, this.boundaries_max)
return this.gradient.rgbAt(aqi / this.boundaries_max);
}
static findNeighbors(lat, lon, box_meters, callback_ok, callback_error)
{
let box = computeLatLonBox(lat, lon, box_meters);
let url = `https://www.purpleair.com/data.json?opt=1/mAQI/a0/cC0&fetch=true&` +
`nwlat=${box.nwlat}&selat=${box.selat}&nwlng=${box.nwlon}&selng=${box.selon}&fields=pm_0`;
this.makeTheCall(url, callback_error, callback_ok);
}
// Verbatim pasted from https://docs.google.com/document/d/15ijz94dXJ-YAZLi9iZ_RaBwrZ4KtYeCy08goGBwnbCU/edit
// Only changed "function" to "static"
static aqiFromPM(pm) {
if (isNaN(pm)) return null;
if (pm == undefined) return null;
if (pm < 0) return pm;
if (pm > 1000) return null;
/*
Good 0 - 50 0.0 - 15.0 0.0 – 12.0
Moderate 51 - 100 >15.0 - 40 12.1 – 35.4
Unhealthy for Sensitive Groups 101 – 150 >40 – 65 35.5 – 55.4
Unhealthy 151 – 200 > 65 – 150 55.5 – 150.4
Very Unhealthy 201 – 300 > 150 – 250 150.5 – 250.4
Hazardous 301 – 400 > 250 – 350 250.5 – 350.4
Hazardous 401 – 500 > 350 – 500 350.5 – 500
*/
if (pm > 350.5) {
return this.calcAQI(pm, 500, 401, 500, 350.5);
} else if (pm > 250.5) {
return this.calcAQI(pm, 400, 301, 350.4, 250.5);
} else if (pm > 150.5) {
return this.calcAQI(pm, 300, 201, 250.4, 150.5);
} else if (pm > 55.5) {
return this.calcAQI(pm, 200, 151, 150.4, 55.5);
} else if (pm > 35.5) {
return this.calcAQI(pm, 150, 101, 55.4, 35.5);
} else if (pm > 12.1) {
return this.calcAQI(pm, 100, 51, 35.4, 12.1);
} else if (pm >= 0) {
return this.calcAQI(pm, 50, 0, 12, 0);
} else {
return undefined;
}
}
static bplFromPM(pm) {
if (isNaN(pm)) return 0;
if (pm == undefined) return 0;
if (pm < 0) return 0;
/*
Good 0 - 50 0.0 - 15.0 0.0 – 12.0
Moderate 51 - 100 >15.0 - 40 12.1 – 35.4
Unhealthy for Sensitive Groups 101 – 150 >40 – 65 35.5 – 55.4
Unhealthy 151 – 200 > 65 – 150 55.5 – 150.4
Very Unhealthy 201 – 300 > 150 – 250 150.5 – 250.4
Hazardous 301 – 400 > 250 – 350 250.5 – 350.4
Hazardous 401 – 500 > 350 – 500 350.5 – 500
*/
if (pm > 350.5) {
return 401;
} else if (pm > 250.5) {
return 301;
} else if (pm > 150.5) {
return 201;
} else if (pm > 55.5) {
return 151;
} else if (pm > 35.5) {
return 101;
} else if (pm > 12.1) {
return 51;
} else if (pm >= 0) {
return 0;
} else {
return 0;
}
}
static bphFromPM(pm) {
//return 0;
if (isNaN(pm)) return 0;
if (pm == undefined) return 0;
if (pm < 0) return 0;
/*
Good 0 - 50 0.0 - 15.0 0.0 – 12.0
Moderate 51 - 100 >15.0 - 40 12.1 – 35.4
Unhealthy for Sensitive Groups 101 – 150 >40 – 65 35.5 – 55.4
Unhealthy 151 – 200 > 65 – 150 55.5 – 150.4
Very Unhealthy 201 – 300 > 150 – 250 150.5 – 250.4
Hazardous 301 – 400 > 250 – 350 250.5 – 350.4
Hazardous 401 – 500 > 350 – 500 350.5 – 500
*/
if (pm > 350.5) {
return 500;
} else if (pm > 250.5) {
return 500;
} else if (pm > 150.5) {
return 300;
} else if (pm > 55.5) {
return 200;
} else if (pm > 35.5) {
return 150;
} else if (pm > 12.1) {
return 100;
} else if (pm >= 0) {
return 50;
} else {
return 0;
}
}
static calcAQI(Cp, Ih, Il, BPh, BPl) {
var a = (Ih - Il);
var b = (BPh - BPl);
var c = (Cp - BPl);
return Math.round((a/b) * c + Il);
}
static getAQIDescription(aqi) {
if (aqi >= 401) {
return 'Hazardous';
} else if (aqi >= 301) {
return 'Hazardous';
} else if (aqi >= 201) {
return 'Very Unhealthy';
} else if (aqi >= 151) {
return 'Unhealthy';
} else if (aqi >= 101) {
return 'Unhealthy for Sensitive Groups';
} else if (aqi >= 51) {
return 'Moderate';
} else if (aqi >= 0) {
return 'Good';
} else {
return undefined;
}
}
static getAQIMessage(aqi) {
if (aqi >= 401) {
return '>401: Health alert: everyone may experience more serious health effects';
} else if (aqi >= 301) {
return '301-400: Health alert: everyone may experience more serious health effects';
} else if (aqi >= 201) {
return '201-300: Health warnings of emergency conditions. The entire population is more likely to be affected. ';
} else if (aqi >= 151) {
return '151-200: Everyone may begin to experience health effects; members of sensitive groups may experience more serious health effects.';
} else if (aqi >= 101) {
return '101-150: Members of sensitive groups may experience health effects. The general public is not likely to be affected.';
} else if (aqi >= 51) {
return '51-100: Air quality is acceptable; however, for some pollutants there may be a moderate health concern for a very small number of people who are unusually sensitive to air pollution.';
} else if (aqi >= 0) {
return '0-50: Air quality is considered satisfactory, and air pollution poses little or no risk';
} else {
return undefined;
}
}
}