UNPKG

homebridge-rinnai-touch-platform

Version:

Homebridge Plugin to control heating/cooling via a Rinnai Touch WiFi Module

104 lines 3.87 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TcpService = void 0; const net = require("net"); const events = require("events"); const UdpService_1 = require("./UdpService"); const Message_1 = require("../models/Message"); class TcpService extends events.EventEmitter { constructor(options = {}) { var _a, _b; super(); this.log = (_a = options.log) !== null && _a !== void 0 ? _a : console; this.hasStaticIpAddress = options.address !== undefined; this.address = options.address; this.timeout = (_b = options.timeout) !== null && _b !== void 0 ? _b : 5000; this.udp = new UdpService_1.UdpService({ log: this.log, timeout: this.timeout }); } async connect() { this.log.debug(this.constructor.name, 'connect'); if (!this.address) { this.address = await this.udp.getAddress(); } return new Promise((resolve, reject) => { try { if (this.socket) { resolve(); } this.socket = new net.Socket(); this.socket.on('data', (data) => { const message = new Message_1.Message(data); if (message.isValid) { this.emit('message', message); resolve(); } }); this.socket.once('error', (error) => { this.closeSocket(); this.emit('connection_error', error.message); reject(error); }); this.socket.once('ready', () => { var _a, _b; this.log.info(`TCP Connection: Open [${(_a = this.address) === null || _a === void 0 ? void 0 : _a.address}:${(_b = this.address) === null || _b === void 0 ? void 0 : _b.port}]`); }); this.socket.once('timeout', () => { this.closeSocket(); this.emit('connection_error', 'TCP Connection timed out'); reject(new Error('TCP Connection timed out')); }); if (!this.address) { reject(new Error('Cannot connect to module as address is undefined')); return; } this.socket.connect(this.address.port, this.address.address); this.socket.setTimeout(5000); } catch (error) { this.closeSocket(); reject(error); } }); } closeSocket() { this.log.debug(this.constructor.name, 'closeSocket'); if (!this.hasStaticIpAddress) { this.address = undefined; } if (this.socket) { this.socket.removeAllListeners(); this.socket.destroy(); this.socket = undefined; } } destroy() { this.log.debug(this.constructor.name, 'destroy'); if (this.socket) { this.closeSocket(); this.log.info('TCP Connection: Closed'); } } write(data) { this.log.debug(this.constructor.name, 'write', data); return new Promise((resolve, reject) => { try { if (!this.socket) { throw new Error('Cannot write data as socket is undefined'); } this.socket.write(data, (error) => { if (error) { reject(error); } else { resolve(); } }); } catch (error) { reject(error); } }); } } exports.TcpService = TcpService; //# sourceMappingURL=TcpService.js.map