-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex-spaceapi.js
More file actions
77 lines (67 loc) · 2.62 KB
/
index-spaceapi.js
File metadata and controls
77 lines (67 loc) · 2.62 KB
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
const spaceapiUrl = '/spaceapi.json';
function escape(str) {
return str.replace(/[&<>"'/]/g, function (char) {
const escapeMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
};
return escapeMap[char] || char;
});
}
/* figures out what unit a time value should be displayed in, then returns the value in that unit and the name of that unit */
function secondsToValueInUnit(seconds) {
const absSeconds = Math.abs(seconds);
if (absSeconds < 3600) {
return [Math.round(seconds / 60), 'minutes'];
}
if (absSeconds < 86400) {
return [Math.round(seconds / 3600), 'hours'];
}
return [Math.round(seconds / 86400), 'days'];
}
// Main function :)
async function doSpaceapi(url, targetElementId) {
const targetElement = document.getElementById(targetElementId);
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`http: ${response.status} ${response.statusText}`);
}
let spaceapi;
try {
spaceapi = await response.json();
} catch (jsonError) {
throw new Error('bad json? ' + jsonError.message);
}
console.log(spaceapi);
const state = spaceapi["state"];
const sensors = spaceapi["sensors"];
var openHtml = '';
if (state && state.lastchange && typeof state.open !== 'undefined') {
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' })
const elapsed = secondsToValueInUnit(state.lastchange - (Date.now() / 1000.0));
const status = state.open ? '<a href="https://wiki.devhack.net/Entering_The_Space#Kinds_of_%22Open%22" target="_blank">doors open</a>!' : 'closed,';
openHtml = `space: ${status} as of ${rtf.format(elapsed[0], elapsed[1])} `;
}
var tempHtml = openHtml ? '<br>' : '';
if (sensors && sensors.temperature && sensors.temperature[0] && sensors.temperature[0].value) {
const temp = Math.round(sensors.temperature[0].value);
const unit = sensors.temperature[0].unit;
tempHtml = tempHtml + 'temp: ' + temp + unit + ' inside'
}
targetElement.innerHTML = '<p>' + openHtml + tempHtml + '</p>';
}
catch (error) {
console.error("Error fetching spaceapi:", error);
targetElement.innerHTML = '';
targetElement.appendChild(createError({
thing: "spaceapi",
message: error.toString()
}));
}
}
doSpaceapi(spaceapiUrl, 'spaceapi-body');