dirigera
Version:
A TypeScript client for IKEA's DIRIGERA smart home hub
51 lines (50 loc) • 1.85 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.discoverGatewayIP = void 0;
const mdns_server_1 = __importDefault(require("mdns-server"));
const name = '_ihsp._tcp.local.';
const discoverGatewayIP = async (timeoutMilliseconds = 10000) => {
const mdnsServer = (0, mdns_server_1.default)({
reuseAddr: true,
loopback: false,
noInit: true,
});
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
rejectWithError(new Error('Gateway discovery timed out. Try specifying the gateway IP address explicitly.'));
}, timeoutMilliseconds);
const resolveWithValue = (value) => {
clearTimeout(timeout);
mdnsServer.destroy();
resolve(value);
};
const rejectWithError = (error) => {
clearTimeout(timeout);
mdnsServer.destroy();
reject(error);
};
mdnsServer.on('response', (response) => {
const ipv4 = response?.answers?.find((a) => a.type === 'A')?.data;
if (ipv4) {
return resolveWithValue(ipv4);
}
const ipv6 = response?.answers?.find((a) => a.type === 'AAAA')?.data;
if (ipv6) {
return resolveWithValue(`[${ipv6}]`);
}
});
mdnsServer.on('ready', () => {
mdnsServer.query([
{ name, type: 'A' },
{ name, type: 'AAAA' },
{ name, type: 'PTR' },
]);
});
mdnsServer.on('error', rejectWithError);
mdnsServer.initServer();
});
};
exports.discoverGatewayIP = discoverGatewayIP;