UNPKG

daikin-controller

Version:

Control Daikin Air Conditioner devices using nodejs

66 lines (65 loc) 2.63 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DaikinDiscovery = void 0; const dgram_1 = require("dgram"); // Change this to true to output debugging logs to the console const debug = false; class DaikinDiscovery { constructor(waitForCount, callback) { this.listenAddress = '0.0.0.0'; this.listenPort = 30000; this.probePort = 30050; this.probeAddress = '255.255.255.255'; this.probeAttempts = 10; this.probeInterval = 500; this.probeData = Buffer.from('DAIKIN_UDP/common/basic_info'); this.probeTimeout = null; this.discoveredDevices = {}; this.callback = callback; // TODO: Which parameterrs are really needed // TODO: Also initialize DaicinAC instances? this.udpSocket = (0, dgram_1.createSocket)({ type: 'udp4', reuseAddr: true }); this.udpSocket.on('error', (err) => { this.log(`ERROR udpSocket: ${err}`); }); this.udpSocket.bind(this.listenPort, this.listenAddress, () => { this.udpSocket.addMembership('224.0.0.1'); this.udpSocket.setBroadcast(true); }); this.udpSocket.on('message', (message, remote) => { this.log(`${remote.address}:${remote.port} - ${message}`); // this.discoveredDevices[remote.address] = message.toString(); this.discoveredDevices[remote.address] = remote.address; if (Object.keys(this.discoveredDevices).length >= waitForCount) { this.finalizeDiscovery(); } }); this.udpSocket.on('listening', () => { this.sendProbes(this.probeAttempts); }); } sendProbes(attemptsLeft) { this.probeTimeout = null; if (attemptsLeft <= 0) { this.finalizeDiscovery(); return; } this.log(`Send UDP discovery package ${attemptsLeft}`); this.udpSocket.send(this.probeData, 0, this.probeData.length, this.probePort, this.probeAddress); this.probeTimeout = setTimeout(this.sendProbes.bind(this), this.probeInterval, --attemptsLeft); } finalizeDiscovery() { if (this.probeTimeout !== null) { clearTimeout(this.probeTimeout); this.probeTimeout = null; } this.udpSocket.close(); this.log(`Discovery finished with ${Object.keys(this.discoveredDevices).length} devices found`); this.callback(this.discoveredDevices); } log(message) { if (debug) console.log(message); } } exports.DaikinDiscovery = DaikinDiscovery;