forked from jasonsnell/PurpleAir-AQI-Scriptable-Widget
-
Notifications
You must be signed in to change notification settings - Fork 0
/
purpleair-aqi.js
615 lines (525 loc) · 16.3 KB
/
purpleair-aqi.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
"use strict";
/**
* This widget is from <https://github.com/jasonsnell/PurpleAir-AQI-Scriptable-Widget>
* By Jason Snell, Rob Silverii, Adam Lickel, Alexander Ogilvie, and Brian Donovan.
* Based on code by Matt Silverlock.
*/
const API_URL = "https://www.purpleair.com";
/**
* Find a nearby PurpleAir sensor ID via https://fire.airnow.gov/
* Click a sensor near your location: the ID is the trailing integers
* https://www.purpleair.com/json has all sensors by location & ID.
* @type {number}
*/
const SENSOR_ID = args.widgetParameter;
/**
* Widget attributes: AQI level threshold, text label, gradient start and end colors, text color
*
* @typedef {object} LevelAttribute
* @property {number} threshold
* @property {string} label
* @property {string} startColor
* @property {string} endColor
* @property {string} textColor
* @property {string} darkStartColor
* @property {string} darkEndColor
* @property {string} darkTextColor
* @property {string} sfSymbol
*/
/**
* @typedef {object} SensorData
* @property {string} val
* @property {string} adj1
* @property {string} [adj2]
* @property {number} ts
* @property {string} hum
* @property {string} loc
* @property {string} lat
* @property {string} lon
*/
/**
* @typedef {object} LatLon
* @property {number} latitude
* @property {number} longitude
*/
/**
* Get JSON from a local file
*
* @param {string} fileName
* @returns {object}
*/
function getCachedData(fileName) {
const fileManager = FileManager.local();
const cacheDirectory = fileManager.joinPath(fileManager.libraryDirectory(), "jsnell-aqi");
const cacheFile = fileManager.joinPath(cacheDirectory, fileName);
if (!fileManager.fileExists(cacheFile)) {
return undefined;
}
const contents = fileManager.readString(cacheFile);
return JSON.parse(contents);
}
/**
* Wite JSON to a local file
*
* @param {string} fileName
* @param {object} data
*/
function cacheData(fileName, data) {
const fileManager = FileManager.local();
const cacheDirectory = fileManager.joinPath(fileManager.libraryDirectory(), "jsnell-aqi");
const cacheFile = fileManager.joinPath(cacheDirectory, fileName);
if (!fileManager.fileExists(cacheDirectory)) {
fileManager.createDirectory(cacheDirectory);
}
const contents = JSON.stringify(data);
fileManager.writeString(cacheFile, contents);
}
/**
* Get the closest PurpleAir sensorId to the given location
*
* @returns {Promise<number>}
*/
async function getSensorId() {
if (SENSOR_ID) return SENSOR_ID;
let fallbackSensorId = undefined;
try {
const cachedSensor = getCachedData("sensor.json");
if (cachedSensor) {
console.log({ cachedSensor });
const { id, updatedAt } = cachedSensor;
fallbackSensorId = id;
// If we've fetched the location within the last 15 minutes, just return it
if (Date.now() - updatedAt < 15 * 60 * 1000) {
return id;
}
}
/** @type {LatLon} */
const { latitude, longitude } = await Location.current();
const BOUND_OFFSET = 0.2;
const nwLat = latitude + BOUND_OFFSET;
const seLat = latitude - BOUND_OFFSET;
const nwLng = longitude - BOUND_OFFSET;
const seLng = longitude + BOUND_OFFSET;
const req = new Request(
`${API_URL}/json?exclude=true&nwlat=${nwLat}&selat=${seLat}&nwlng=${nwLng}&selng=${seLng}`
);
/** @type {{ code?: number; results?: Array<Object<string, number|string>>; }} */
const res = await req.loadJSON();
const { results } = res;
const sensorIdField = "ID";
const latField = "Lat";
const lonField = "Lon";
const locationField = "DEVICE_LOCATIONTYPE";
const ageField = "AGE";
const OUTDOOR = "outside";
let closestSensor;
let closestDistance = Infinity;
for (const location of results.filter((datum) => datum[locationField] === OUTDOOR && datum[ageField] < 60 * 4)) {
const distanceFromLocation = haversine(
{ latitude, longitude },
{ latitude: location[latField], longitude: location[lonField] }
);
if (distanceFromLocation < closestDistance) {
closestDistance = distanceFromLocation;
closestSensor = location;
}
}
const id = closestSensor[sensorIdField];
cacheData("sensor.json", { id, updatedAt: Date.now() });
return id;
} catch (error) {
console.log(`Could not fetch location: ${error}`);
return fallbackSensorId;
}
}
/**
* Returns the haversine distance between start and end.
*
* @param {LatLon} start
* @param {LatLon} end
* @returns {number}
*/
function haversine(start, end) {
const toRadians = (n) => (n * Math.PI) / 180;
const deltaLat = toRadians(end.latitude - start.latitude);
const deltaLon = toRadians(end.longitude - start.longitude);
const startLat = toRadians(start.latitude);
const endLat = toRadians(end.latitude);
const angle =
Math.sin(deltaLat / 2) ** 2 +
Math.sin(deltaLon / 2) ** 2 * Math.cos(startLat) * Math.cos(endLat);
return 2 * Math.atan2(Math.sqrt(angle), Math.sqrt(1 - angle));
}
/**
* Fetch content from PurpleAir
*
* @param {number} sensorId
* @returns {Promise<SensorData>}
*/
async function getSensorData(sensorId) {
const sensorCache = `sensor-${sensorId}-data.json`;
const req = new Request(`${API_URL}/json?show=${sensorId}`);
let json = await req.loadJSON();
try {
// Check that our results are what we expect
if (json && json.results && Array.isArray(json.results) && json.results.length > 1) {
console.log(`Sensor data looks good, will cache.`);
const sensorData = { json, updatedAt: Date.now() }
cacheData(sensorCache, sensorData);
} else {
const { json: cachedJson, updatedAt } = getCachedData(sensorCache);
if (Date.now() - updatedAt > 2 * 60 * 60 * 1000) {
// Bail if our data is > 2 hours old
throw `Our cache is too old: ${updatedAt }`;
}
console.log(`Using cached sensor data: ${updatedAt}`);
json = cachedJson;
}
return {
val: json.results[0].Stats,
adj1: json.results[0].pm2_5_cf_1,
adj2: json.results[1].pm2_5_cf_1,
ts: json.results[0].LastSeen,
hum: json.results[0].humidity,
loc: json.results[0].Label,
lat: json.results[0].Lat,
lon: json.results[0].Lon,
};
} catch (error) {
console.log(`Could not parse JSON: ${error}`);
throw 666;
}
}
/**
* Fetch reverse geocode
*
* @param {string} lat
* @param {string} lon
* @returns {Promise<GeospatialData>}
*/
async function getGeoData(lat, lon) {
const latitude = Number.parseFloat(lat);
const longitude = Number.parseFloat(lon);
const geo = await Location.reverseGeocode(latitude, longitude);
console.log({ geo: geo });
return {
neighborhood: geo[0].subLocality,
city: geo[0].locality,
state: geo[0].administrativeArea,
};
}
/**
* Fetch a renderable location
*
* @param {SensorData} data
* @returns {Promise<String>}
*/
async function getLocation(data) {
try {
if (args.widgetParameter) {
return data.loc;
}
const geoData = await getGeoData(data.lat, data.lon);
console.log({ geoData });
if (geoData.neighborhood && geoData.city) {
return `${geoData.neighborhood}, ${geoData.city}`;
} else {
return geoData.city || data.loc;
}
} catch (error) {
console.log(`Could not cleanup location: ${error}`);
return data.loc;
}
}
/** @type {Array<LevelAttribute>} sorted by threshold desc. */
const LEVEL_ATTRIBUTES = [
{
threshold: 300,
label: "Hazardous",
startColor: "76205d",
endColor: "521541",
textColor: "f0f0f0",
darkStartColor: "333333",
darkEndColor: "000000",
darkTextColor: "ce4ec5",
sfSymbol: "aqi.high",
},
{
threshold: 200,
label: "Very Unhealthy",
startColor: "9c2424",
endColor: "661414",
textColor: "f0f0f0",
darkStartColor: "333333",
darkEndColor: "000000",
darkTextColor: "f33939",
sfSymbol: "aqi.high",
},
{
threshold: 150,
label: "Unhealthy",
startColor: "da5340",
endColor: "bc2f26",
textColor: "eaeaea",
darkStartColor: "333333",
darkEndColor: "000000",
darkTextColor: "f16745",
sfSymbol: "aqi.high",
},
{
threshold: 100,
label: "Unhealthy for Sensitive Groups",
startColor: "f5ba2a",
endColor: "d3781c",
textColor: "1f1f1f",
darkStartColor: "333333",
darkEndColor: "000000",
darkTextColor: "f7a021",
sfSymbol: "aqi.medium",
},
{
threshold: 50,
label: "Moderate",
startColor: "f2e269",
endColor: "dfb743",
textColor: "1f1f1f",
darkStartColor: "333333",
darkEndColor: "000000",
darkTextColor: "f2e269",
sfSymbol: "aqi.low",
},
{
threshold: -20,
label: "Good",
startColor: "8fec74",
endColor: "77c853",
textColor: "1f1f1f",
darkStartColor: "333333",
darkEndColor: "000000",
darkTextColor: "6de46d",
sfSymbol: "aqi.low",
},
];
/**
* Get the EPA adjusted PPM
*
* @param {SensorData} sensorData
* @returns {number} EPA adjustment for wood smoke and PurpleAir from slide 8 of https://cfpub.epa.gov/si/si_public_record_report.cfm?dirEntryId=349513&Lab=CEMM&simplesearch=0&showcriteria=2&sortby=pubDate&timstype=&datebeginpublishedpresented=08/25/2018
*/
function computePM(sensorData) {
const adj1 = Number.parseInt(sensorData.adj1, 10);
const adj2 = Number.parseInt(sensorData.adj2, 10);
const hum = Number.parseInt(sensorData.hum, 10);
const dataAverage = isNaN(adj2) ? adj1 : (adj1 + adj2) / 2;
console.log(`PM2.5 number is ${dataAverage}.`)
if (dataAverage < 250) {
console.log(`Using EPA calculation.`)
return 0.52 * dataAverage - 0.085 * hum + 5.71;
} else {
console.log(`Using AQANDU calculation.`)
return .0778 * dataAverage + 2.65
}
}
/**
* Get AQI number from PPM reading
*
* @param {number} pm
* @returns {number|'-'}
*/
function aqiFromPM(pm) {
if (pm > 350.5) return calculateAQI(pm, 500.0, 401.0, 500.0, 350.5);
if (pm > 250.5) return calculateAQI(pm, 400.0, 301.0, 350.4, 250.5);
if (pm > 150.5) return calculateAQI(pm, 300.0, 201.0, 250.4, 150.5);
if (pm > 55.5) return calculateAQI(pm, 200.0, 151.0, 150.4, 55.5);
if (pm > 35.5) return calculateAQI(pm, 150.0, 101.0, 55.4, 35.5);
if (pm > 12.1) return calculateAQI(pm, 100.0, 51.0, 35.4, 12.1);
if (pm >= 0.0) return calculateAQI(pm, 50.0, 0.0, 12.0, 0.0);
return "-";
}
/**
* Calculate the AQI number
*
* @param {number} Cp
* @param {number} Ih
* @param {number} Il
* @param {number} BPh
* @param {number} BPl
* @returns {number}
*/
function calculateAQI(Cp, Ih, Il, BPh, BPl) {
const a = Ih - Il;
const b = BPh - BPl;
const c = Cp - BPl;
return Math.round((a / b) * c + Il);
}
/**
* Calculates the AQI level
* based on https://cfpub.epa.gov/airnow/index.cfm?action=aqibasics.aqi#unh
*
* @param {number|'-'} aqi
* @returns {LevelAttribute & { level: number }}
*/
function calculateLevel(aqi) {
const level = Number(aqi) || 0;
const {
label = "Weird",
startColor = "white",
endColor = "white",
textColor = "black",
darkStartColor = "009900",
darkEndColor = "007700",
darkTextColor = "000000",
threshold = -Infinity,
sfSymbol = "aqi.low",
} = LEVEL_ATTRIBUTES.find(({ threshold }) => level > threshold) || {};
return {
label,
startColor,
endColor,
textColor,
darkStartColor,
darkEndColor,
darkTextColor,
threshold,
level,
sfSymbol,
};
}
/**
* Get the AQI trend
*
* @param {{ v1: number; v3: number; }} stats
* @returns {string}
*/
function getAQITrend({ v1: partLive, v3: partTime }) {
const partDelta = partTime - partLive;
if (partDelta > 5) return "arrow.down";
if (partDelta < -5) return "arrow.up";
return "";
}
/**
* Constructs an SFSymbol from the given symbolName
*
* @param {string} symbolName
* @param {number} fontSize
* @returns {object} SFSymbol
*/
function createSymbol(symbolName, fontSize) {
const symbol = SFSymbol.named(symbolName);
symbol.applyFont(Font.systemFont(fontSize));
return symbol;
}
async function run() {
const listWidget = new ListWidget();
listWidget.useDefaultPadding();
try {
const sensorId = await getSensorId();
if (!sensorId) {
throw "Please specify a location for this widget.";
}
console.log(`Using sensor ID: ${sensorId}`);
const data = await getSensorData(sensorId);
const stats = JSON.parse(data.val);
console.log({ stats });
const aqiTrend = getAQITrend(stats);
console.log({ aqiTrend });
const epaPM = computePM(data);
console.log({ epaPM });
const aqi = aqiFromPM(epaPM);
const level = calculateLevel(aqi);
const aqiText = aqi.toString();
console.log({ aqi });
const sensorLocation = await getLocation(data)
console.log({ sensorLocation });
const startColor = Color.dynamic(new Color(level.startColor), new Color(level.darkStartColor));
const endColor = Color.dynamic(new Color(level.endColor), new Color(level.darkEndColor));
const textColor = Color.dynamic(new Color(level.textColor), new Color(level.darkTextColor));
// BACKGROUND
const gradient = new LinearGradient();
gradient.colors = [startColor, endColor];
gradient.locations = [0.0, 1];
console.log({ gradient });
listWidget.backgroundGradient = gradient;
// HEADER
const headStack = listWidget.addStack();
headStack.layoutHorizontally();
headStack.topAlignContent();
headStack.setPadding (0,0,0,0);
const textStack = headStack.addStack();
textStack.layoutVertically();
textStack.topAlignContent();
textStack.setPadding (0,0,0,0);
const header = textStack.addText('Air Quality'.toUpperCase());
header.textColor = textColor;
header.font = Font.regularSystemFont(11);
header.minimumScaleFactor = 1;
const wordLevel = textStack.addText(level.label);
wordLevel.textColor = textColor;
wordLevel.font = Font.semiboldSystemFont(25);
wordLevel.minimumScaleFactor = 0.3;
headStack.addSpacer();
const statusSymbol = createSymbol(level.sfSymbol, 20);
const statusImg = headStack.addImage(statusSymbol.image);
statusImg.resizable = false;
statusImg.tintColor = textColor;
listWidget.addSpacer(0);
// SCORE
const scoreStack = listWidget.addStack();
scoreStack.centerAlignContent()
const content = scoreStack.addText(aqiText);
content.textColor = textColor;
content.font = Font.semiboldSystemFont(30);
if (aqiTrend.length > 0) {
scoreStack.addSpacer(4);
const trendSymbol = createSymbol(aqiTrend, 15);
const trendImg = scoreStack.addImage(trendSymbol.image);
trendImg.resizable = false;
trendImg.tintColor = textColor;
}
listWidget.addSpacer();
// LOCATION
const locationText = listWidget.addText(sensorLocation);
locationText.textColor = textColor;
locationText.font = Font.regularSystemFont(14);
locationText.minimumScaleFactor = 0.5;
listWidget.addSpacer(2);
// UPDATED AT
const updatedAt = new Date(data.ts * 1000).toLocaleTimeString([], {
hour: "numeric",
minute: "2-digit",
});
const widgetText = listWidget.addText(`Updated ${updatedAt}`);
widgetText.textColor = textColor;
widgetText.font = Font.regularSystemFont(8);
widgetText.minimumScaleFactor = 0.5;
// TAP HANDLER
const purpleMapUrl = `https://www.purpleair.com/map?opt=1/i/mAQI/a10/cC5&select=${sensorId}#14/${data.lat}/${data.lon}`;
listWidget.url = purpleMapUrl;
} catch (error) {
if (error === 666) {
// Handle JSON parsing errors with a custom error layout
listWidget.background = new Color('999999');
const header = listWidget.addText('Error'.toUpperCase());
header.textColor = new Color('000000');
header.font = Font.regularSystemFont(11);
header.minimumScaleFactor = 0.50;
listWidget.addSpacer(15);
const wordLevel = listWidget.addText(`Couldn't connect to the server.`);
wordLevel.textColor = new Color ('000000');
wordLevel.font = Font.semiboldSystemFont(15);
wordLevel.minimumScaleFactor = 0.3;
} else {
console.log(`Could not render widget: ${error}`);
const errorWidgetText = listWidget.addText(`${error}`);
errorWidgetText.textColor = Color.red();
errorWidgetText.textOpacity = 30;
errorWidgetText.font = Font.regularSystemFont(10);
}
}
if (config.runsInApp) {
listWidget.presentSmall();
}
Script.setWidget(listWidget);
Script.complete();
}
await run();