UNPKG

node-red-contrib-home-assistant-websocket

Version:
33 lines (32 loc) 1.18 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.startHeartbeat = startHeartbeat; const debug_1 = __importDefault(require("debug")); const debug = (0, debug_1.default)('home-assistant:ws:heartbeat'); const HEARTBEAT_TIMEOUT = 5000; const MIN_HEARTBEAT_INTERVAL = 10000; function startHeartbeat(client, interval, host) { let beatTimeoutId; const heartbeatIntervalId = setInterval(async () => { beatTimeoutId = setTimeout(() => { debug(`No pong received from ${host} attempting to reconnect`); client.reconnect(true); }, HEARTBEAT_TIMEOUT); debug(`Ping sent to ${host}`); try { await client.ping(); clearTimeout(beatTimeoutId); debug(`Pong received from ${host}`); } catch (e) { } }, // mininum of a 10 second heartbeat Math.max(MIN_HEARTBEAT_INTERVAL, interval * 1000)); return () => { clearInterval(heartbeatIntervalId); clearTimeout(beatTimeoutId); }; }