-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.js
95 lines (80 loc) · 2.08 KB
/
logger.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
import fetch from "node-fetch";
import fs from "fs";
import { reboot, takePicture } from "./utils.js";
import { getSensorValues } from "./sensors.js";
export const host = "xn--vrhna-sra2k.no";
function sleep(ms) {
return new Promise((r) => setTimeout(r, ms));
}
export async function logger() {
const sleepWon = "maybe";
const res = await Promise.race([
logToApi(),
(async function () {
await sleep(60_000 * 3);
return sleepWon;
})(),
]);
if (res === sleepWon) {
console.log("SLEEP WON");
reboot();
return;
}
return res;
}
async function logToApi() {
try {
await takePicture();
} catch (err) {
console.log("Could not take picture, continuing with old...");
}
try {
const imageBase64 = fs.readFileSync("./snapshot.jpg", {
encoding: "base64",
});
console.log("will send at " + new Date().toISOString());
console.log("--image with length", imageBase64.length);
console.log("--sensors", JSON.stringify(getSensorValues()));
console.log("--boxId", process.env.BOX_ID);
function send() {
return fetch(`https://${host}/api/graphql`, {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify({
query: `
mutation($input: AddSnapshotMutationInput!) {
snapshots {
add(input: $input) {
success
}
}
}
`,
variables: {
input: {
boxId: process.env.BOX_ID,
image: imageBase64,
...getSensorValues(),
},
},
}),
});
}
const response = await send();
if (!response.ok) {
throw new Error(`Snapshot FAILED`);
}
const json = await response.json();
if (json.errors) {
console.log(JSON.stringify(json.errors, null, 1));
throw new Error(`Snapshot FAILED`);
}
console.log(`Snapshot sent`);
} catch (e) {
console.log("logger error ⛔️");
console.log(e);
void reboot();
}
}