-
Notifications
You must be signed in to change notification settings - Fork 12
/
app.js
350 lines (303 loc) · 10.6 KB
/
app.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
(() => {
window.addEventListener("load", onStart);
let coord;
let closestSensor;
const FETCH_OPTIONS = {
headers: {
"X-API-Key": "BA110377-679A-11EE-A8AF-42010A80000A",
},
};
function onStart() {
document.getElementById("powerwash").onclick = clearStorage;
getLocation();
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/sw.js");
}
}
function getLocation() {
announceState("Finding you");
// If we don't have a location yet, then this is the first time we're trying
// and we should explain ourselves
if (coord === undefined) {
explainPermissionsRequest();
}
navigator.geolocation.getCurrentPosition(located, unsupported);
}
function located(position) {
coord = position.coords;
clearPermissionsRequest();
announceState("Finding nearby sensors");
loadSensorsFromCacheAndShowAQI();
}
function loadSensorsFromCacheAndShowAQI() {
try {
const cachedSensors = window.localStorage.getItem("sensors");
sensor_data = JSON.parse(cachedSensors);
if (sensor_data == null) {
throw "Sensor data not cached";
}
if (sensor_data.version !== 2) {
throw "Sensor data is the wrong version";
}
if (Date.now() > sensor_data.timestamp + 86400 * 1000) {
throw "Sensor data is more than a day old";
}
sensor = findClosestSensor(sensor_data.data);
if (sensor.distance > 10) {
throw "Nearest sensor is over 10km away";
}
updateWithSensor(sensor);
} catch (exception) {
console.log("Exception while reading cached sensor data");
console.log(exception);
clearStorage();
fetchSensorListAndShowAQI();
}
}
function clearStorage() {
window.localStorage.removeItem("sensors");
console.log("Cleared stored sensor list");
}
function fetchSensorListAndShowAQI() {
bounding_box = boundingBox(coord, 10); // 10km bounding box
const url = `https://api.purpleair.com/v1/sensors?fields=longitude,latitude&location_type=0&max_age=300&nwlng=${bounding_box.nw.longitude}&nwlat=${bounding_box.nw.latitude}&selng=${bounding_box.se.longitude}&selat=${bounding_box.se.latitude}`;
window
.fetch(url, FETCH_OPTIONS)
.then((response) => response.json())
.then((response) => {
if (response.code && response.code >= 400 && response.message) {
throw new Error(response.message);
}
return response;
})
.then(parsePurpleAirData)
.then(findClosestSensor)
.then(updateWithSensor)
.catch(purpleError);
}
function updateWithSensor(sensor) {
announceState("Getting sensor data");
const url = `https://api.purpleair.com/v1/sensors/${sensor.id}?fields=pm2.5_10minute_a,pm2.5_10minute_b,humidity`;
window
.fetch(url, FETCH_OPTIONS)
.then((response) => response.json())
.then(updateAQI)
.catch(purpleError);
}
function updateAQI(sensor) {
sensor = sensor.sensor;
announceState("Calculating AQI");
const humidity = sensor.humidity;
let pm25s = [];
if (sensor.stats_a["pm2.5_10minute"] !== 0.0) {
pm25s.push(sensor.stats_a["pm2.5_10minute"]);
}
if (sensor.stats_b["pm2.5_10minute"] !== 0.0) {
pm25s.push(sensor.stats_b["pm2.5_10minute"]);
}
const pm25 = pm25s.reduce((a, b) => a + b) / pm25s.length;
const aqi = epaAQIFromPMandHumidity(pm25, humidity);
const distance = Math.round(closestSensor.distance * 10) / 10;
const time = new Date().toLocaleTimeString();
const paLink = getPurpleAirLink();
const stateMsg = `and <a href="${paLink}">a sensor ${distance}km away</a> at ${time}`;
announce(aqi, "", stateMsg);
// We want to sent the body state after announcing the AQI
document.body.classList.add(getAQIClass(aqi), "aqi-result");
// When the animation ends, make sure the top tab/tray color matches the bg
let tc = document.head.querySelector('meta[name="theme-color"]');
if (tc) {
document.body.ontransitionend = function () {
tc.setAttribute(
"content",
window.getComputedStyle(document.body).backgroundColor
);
};
}
setTimeout(() => getLocation(), 300000);
}
function explainPermissionsRequest() {
document.body.classList.add("requesting-location");
}
function clearPermissionsRequest() {
document.body.classList.remove("requesting-location");
}
function announce(headMsg, descMsg = "", stateMsg = "") {
const head = document.getElementById("aqi");
const desc = document.getElementById("desc");
const state = document.getElementById("state");
// We want to clear the body state on any announce
document.body.classList.remove(...document.body.classList);
head.innerHTML = headMsg;
desc.innerHTML = descMsg;
state.innerHTML = stateMsg;
}
function announceError(errorMsg, descMsg = "") {
if (
closestSensor !== undefined &&
closestSensor !== null &&
closestSensor.id !== null
) {
const paLink = getPurpleAirLink();
callToAction = `<a href='#' onclick='location.reload()'>Reload?</a> Or <a href="${paLink}">try PurpleAir's map</a>.`;
} else {
callToAction =
"You might want to try <a href='https://www.purpleair.com/map?opt=1/i/mAQI/a0/cC1#1/25/-30'>PurpleAir's map</a>.";
}
announce(errorMsg, descMsg, callToAction);
}
function announceState(stateMsg) {
// If we have something in state already, it means we've previously loaded
// some content and don't want to blow away the top level AQI state until
// we have something interesting to report
const state = document.getElementById("state");
if (state.innerHTML !== "") {
state.innerHTML = stateMsg;
} else {
// If state is empty, we have not yet given the breather an AQI reading, so
// state is important enough to shove up top in the H1
announce(stateMsg);
}
}
function findClosestSensor(sensors) {
for (const sensor of sensors) {
const distance = distanceBetweenCoords(coord, sensor);
sensor.distance = distance;
}
sensors.sort((a, b) => a.distance - b.distance);
closestSensor = sensors[0];
return closestSensor;
}
function parsePurpleAirData(json) {
let sensors = [];
let fields = [];
fields["latitude"] = json.fields.findIndex((e) => e === "latitude");
fields["longitude"] = json.fields.findIndex((e) => e === "longitude");
fields["sensor_index"] = json.fields.findIndex((e) => e === "sensor_index");
for (const sensor of json.data) {
sensors.push({
id: sensor[fields["sensor_index"]],
latitude: sensor[fields["latitude"]],
longitude: sensor[fields["longitude"]],
});
}
window.localStorage.setItem(
"sensors",
JSON.stringify({ version: 2, timestamp: Date.now(), data: sensors })
);
return sensors;
}
// Adapted from https://stackoverflow.com/a/21623206 because I am a hack
function distanceBetweenCoords(coord1, coord2) {
const p = Math.PI / 180;
var a =
0.5 -
Math.cos((coord2.latitude - coord1.latitude) * p) / 2 +
(Math.cos(coord1.latitude * p) *
Math.cos(coord2.latitude * p) *
(1 - Math.cos((coord2.longitude - coord1.longitude) * p))) /
2;
// 12742 is the diameter of earth in km
return 12742 * Math.asin(Math.sqrt(a));
}
// Shoutout to ChatGPT
function boundingBox(coordinate, distance) {
const distanceInRadians = distance / 6371; // Earth's radius in kilometers
// Calculate bounding box coordinates
const latMin = coordinate.latitude - distanceInRadians * (180 / Math.PI);
const latMax = coordinate.latitude + distanceInRadians * (180 / Math.PI);
const lonMin =
coordinate.longitude -
(distanceInRadians * (180 / Math.PI)) /
Math.cos(coordinate.latitude * (Math.PI / 180));
const lonMax =
coordinate.longitude +
(distanceInRadians * (180 / Math.PI)) /
Math.cos(coordinate.latitude * (Math.PI / 180));
return {
nw: {
latitude: latMax,
longitude: lonMin,
},
se: {
latitude: latMin,
longitude: lonMax,
},
};
}
function getPurpleAirLink() {
return `https://www.purpleair.com/map?opt=1/i/mAQI/a0/cC5&select=${closestSensor.id}#14/${coord.latitude}/${coord.longitude}`;
}
// From https://www.epa.gov/sites/default/files/2021-05/documents/toolsresourceswebinar_purpleairsmoke_210519b.pdf final slide
function epaAQIFromPMandHumidity(pm, humidity) {
if (pm < 50) {
return aqiFromPM(0.52 * pm - 0.086 * humidity + 5.75);
} else if (pm < 229) {
return aqiFromPM(0.786 * pm - 0.086 * humidity + 5.75);
} else {
return aqiFromPM(
0.69 * pm + 8.84 * Math.pow(10, -4) * Math.pow(pm, 2) + 2.97
);
}
}
function aqiFromPM(pm) {
if (isNaN(pm)) return "-";
if (pm == undefined) return "-";
if (pm < 0) return 0;
if (pm > 1000) return "-";
if (pm > 350.5) {
return calcAQI(pm, 500, 401, 500, 350.5);
} else if (pm > 250.5) {
return calcAQI(pm, 400, 301, 350.4, 250.5);
} else if (pm > 150.5) {
return calcAQI(pm, 300, 201, 250.4, 150.5);
} else if (pm > 55.5) {
return calcAQI(pm, 200, 151, 150.4, 55.5);
} else if (pm > 35.5) {
return calcAQI(pm, 150, 101, 55.4, 35.5);
} else if (pm > 12.1) {
return calcAQI(pm, 100, 51, 35.4, 12.1);
} else if (pm >= 0) {
return calcAQI(pm, 50, 0, 12, 0);
} else {
return undefined;
}
}
function calcAQI(Cp, Ih, Il, BPh, BPl) {
// The AQI equation https://forum.airnowtech.org/t/the-aqi-equation/169
var a = Ih - Il;
var b = BPh - BPl;
var c = Cp - BPl;
return Math.round((a / b) * c + Il);
}
function getAQIClass(aqi) {
if (aqi >= 401) {
return "very-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;
}
}
function unsupported() {
clearPermissionsRequest();
announceError(
"Scooby-Doo, Where Are You!",
"We need your browser location to find the nearest PurpleAir sensor. This information never leaves your device. It's not sent to a server."
);
}
function purpleError(error) {
console.error("Purple Air Error: ", error);
announceError("idk how purple air evens, m8", error);
}
})();