-
Notifications
You must be signed in to change notification settings - Fork 0
/
adafruit-io-scriptable-widget.js
90 lines (67 loc) · 2.48 KB
/
adafruit-io-scriptable-widget.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
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: cyan; icon-glyph: magic;
// Sample Scriptable Widget to Display AdafruitIO Feed Data on an iOS home
// screen or lock screen widget. In this example a temperature value is
// displayed along with a message about how "fresh" the data is relative to
// the current time.
//
// Brad Black - 2023
//
// Substitute your Adafruit IO credentials and feed name here..
const AdafruitIOUser = "myAIOusername";
const AIOKEY = "myAIOKey";
const AIOFeedName = "feedname";
const widget = new ListWidget();
widget.backgroundColor = Color.black();
var problem = false;
// Construct our AIO API request
const req = new Request("https://io.adafruit.com/api/v2/" + AdafruitIOUser + "/feeds/" + AIOFeedName + "/data/last");
req.headers = { "X-AIO-Key": AIOKEY };
try {
console.log("start");
var res = await req.loadJSON();
} catch (err) {
console.log(err);
problem = true;
}
if (!problem) {
console.log(res.value);
let temp = res.value;
let createdAt = res.created_at;
console.log(createdAt);
// Calculate the time difference between the feed value and current time
var delayMessage = "";
var Date2 = new Date();
var Date1 = new Date(createdAt);
var timeDiff = Math.abs(Date2.getTime() - Date1.getTime());
var timeDiffInSecond = Math.ceil(timeDiff / 1000);
console.log(timeDiffInSecond);
if (timeDiffInSecond < 60) { delayMessage = "Just a moment ago"; } else {
if (timeDiffInSecond < 120) { delayMessage = "About a minute ago"; } else
if (timeDiffInSecond < 1200) { delayMessage = "About " + (timeDiffInSecond / 60).toFixed() + " minutes ago"; }
}
if (timeDiffInSecond >= 1200) delayMessage = "Problem Getting Data";
console.log(delayMessage);
let text = widget.addText(Number(temp).toFixed(1) + "°C");
text.font = Font.systemFont(32);
text.textColor = Color.yellow();
text.centerAlignText();
let timeText = widget.addText(delayMessage);
timeText.font = Font.systemFont(10);
timeText.textColor = Color.white();
timeText.centerAlignText();
timeText.bottomAlignContent;
} else {
let text = widget.addText("Offline?");
text.font = Font.systemFont(22);
text.textColor = Color.yellow();
text.centerAlignText();
}
// Attempt to refresh the widget every 10 minutes...
const now = Date.now();
widget.refreshAfterDate = new Date(now + (30 * 60 * 1000));
console.log(widget.refreshAfterDate);
Script.setWidget(widget);
Script.complete();
widget.presentMedium();