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);