Skip to content

Commit fcdd661

Browse files
committed
Send a heartbeat each minute
1 parent a9d3661 commit fcdd661

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ If debugging on Windows you may need these drivers http://www.ftdichip.com/Drive
2626
| -------------------- | ----------- |
2727
| `LOG_LEVEL` | `silly` |
2828
| `CLOUDFLARE_API_URL` | _none_ |
29+
| `CLOUDFLARE_HEARTBEAT_URL` | _none_ |
2930

3031
### Device Configuration Variables
3132

src/main.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ const responseParser = require("./parser");
55
const responseValidator = require("./validator");
66
const sleep = require("./sleep");
77
const cloudflare = require("./targets/cloudflare");
8+
const cloudflareHeartbeat = require("./targets/cloudflareHeartbeat");
89

910
logger.log("info", "Booted - connecting to Serial");
1011
/**
@@ -38,6 +39,8 @@ function serialWrite(message) {
3839
});
3940
}
4041

42+
setInterval(cloudflareHeartbeat, 60000); // Send a heartbeat to Cloudflare every minute
43+
4144
/**
4245
* Logic to query the serial device
4346
*/

src/targets/cloudflareHeartbeat.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
const logger = require("../logger");
2+
3+
// Function to send a heartbeat to Cloudflare to show the device is still alive
4+
const cloudflareHeartbeat = () => {
5+
const url = process.env.CLOUDFLARE_HEARTBEAT_URL;
6+
if (!url) return;
7+
8+
const controller = new AbortController();
9+
const timeout = setTimeout(() => controller.abort(), 1500);
10+
11+
fetch(url, { method: "HEAD", signal: controller.signal })
12+
.then((response) => {
13+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
14+
logger.verbose("http", "Sent heartbeat to cloudflare");
15+
})
16+
.catch((error) => {
17+
logger.log(
18+
"error",
19+
"Error from cloudflare when sending heartbeat",
20+
error.message
21+
);
22+
})
23+
.finally(() => clearTimeout(timeout));
24+
};
25+
26+
module.exports = cloudflareHeartbeat;

0 commit comments

Comments
 (0)