From f1a3cb8ff44e2d9d9942eb37901ad99a462fe1d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Ko=C5=82odziejski?= Date: Sat, 21 Dec 2019 01:11:26 +0000 Subject: [PATCH] Add static find function --- src/find.ts | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/find.ts b/src/find.ts index 8d93bfb..0071b23 100644 --- a/src/find.ts +++ b/src/find.ts @@ -1,5 +1,6 @@ import {EventEmitter} from 'events'; import * as dgram from 'dgram'; +import debug0 from 'debug'; import Messenger from './lib/messenger'; class Find extends EventEmitter { @@ -20,6 +21,41 @@ class Find extends EventEmitter { this._listenerEncrypted.on('message', this._broadcastHandler.bind(this)); } + static async find(id: string, key: string): Promise { + const debug = (...args: any): void => { + debug0('@tuyapi/driver:find')({id, key}, 'find', ...args); + }; + + return new Promise((resolve, reject) => { + const find = new Find(); + + function stop(): void { + find.removeAllListeners(); + find.stop(); + } + + find.on('broadcast', data => { + const {ip} = data; + if (data.gwId === id) { + debug('ip found', {ip}); + + stop(); + resolve(ip); + } else { + debug('different device found', {data}); + } + }); + + find.on('error', error => { + debug('find error'); + stop(); + reject(error); + }); + + find.start(); + }); + } + start(): void { this._listener.bind(6666); this._listenerEncrypted.bind(6667);