@isaac-platform/isaac-node-red
Version:
Set of Node-RED nodes to communicate with an ISAAC system
49 lines (48 loc) • 2.33 kB
JavaScript
const axios = require("axios"), utils = require("../../utils.js");
module.exports = (RED) => {
function IsaacConnectionNode(config) {
RED.nodes.createNode(this, config);
const node = this;
this.ipAddress = config.ipAddress, this.subsystemExternalId = config.subsystemExternalId, this.accessToken = config.accessToken;
const onHeartbeatCallbacks = [];
this.registerListener = (callback) => {
callback && typeof callback == "function" && onHeartbeatCallbacks.push(callback);
};
const sendHeartbeat = async () => {
const source = axios.CancelToken.source(), timeout = setTimeout(() => {
source.cancel("sendHeartbeats Canceled connection due to timeout, could not communicate with server.");
}, 5e3);
try {
const response = await axios.put(
`${utils.getApiUrl(config)}/subsystems/${this.subsystemExternalId}/heartbeat`,
void 0,
{
cancelToken: source.token
}
);
onHeartbeatCallbacks.forEach((callback) => {
callback(response.data);
}), clearTimeout(timeout);
} catch (e) {
clearTimeout(timeout);
let message = "";
try {
e && (typeof e == "string" ? message = e : typeof e == "object" && (e.message && typeof e.message == "string" && (message = e.message), e.response && typeof e.response == "object" && e.response.status && typeof e.response.status == "number" && !message.includes(e.response.status) && (message = `${e.response.status} ${message}`)));
} catch (err) {
console.error(err);
}
message = message.trim(), node.error(`ISAAC Communication Error${message ? `: ${message}` : ""}`);
}
};
let heartbeatInterval, checkInterval;
const startHeartbeatIfUsed = () => {
if (heartbeatInterval)
return;
utils.isConnectionUsed(node) && (clearInterval(checkInterval), sendHeartbeat(), heartbeatInterval = setInterval(sendHeartbeat, 5e3));
}, initialTimeout = setTimeout(startHeartbeatIfUsed, 2500);
checkInterval = setInterval(startHeartbeatIfUsed, 5e3), this.on("close", () => {
clearTimeout(initialTimeout), clearInterval(heartbeatInterval), clearInterval(checkInterval);
});
}
RED.nodes.registerType("isaac-connection", IsaacConnectionNode);
};