From 437cd3a8a85650b9d0516d5f5c20dade46922367 Mon Sep 17 00:00:00 2001 From: doubleedesign Date: Sat, 2 Dec 2023 18:42:20 +1100 Subject: [PATCH] Add ability to get the group a light is in --- src/light.ts | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/light.ts b/src/light.ts index 434152e..b12c609 100644 --- a/src/light.ts +++ b/src/light.ts @@ -44,6 +44,7 @@ import { } from './errors/lightErrors'; import { ER_CLIENT_INVALID_ARGUMENT } from './errors/clientErrors'; import { SetTileState64Request, SetUserPositionRequest, StateDeviceChainResponse } from './packets/tiles/tiles'; +import { Group } from './packets/group/group'; export enum LightEvents { CONECTIVITY = 'connectivity', @@ -71,6 +72,7 @@ export class Light extends EventEmitter { private _client: Client; private _connectivity: boolean; private _label: string; + private _group: Group; private _power: boolean; private _color: ColorHSBK; @@ -791,6 +793,47 @@ export class Light extends EventEmitter { }); } + public getGroup(cache = false, timeout: number = DEFAULT_MSG_REPLY_TIMEOUT): Promise { + const ctx = this; + + return new Promise((resolve, reject) => { + if (!ctx.connectivity) { + return reject(new ServiceErrorBuilder(ER_LIGHT_OFFLINE).withContextualMessage(`Id: ${ctx.id}`).build()); + } + + if (cache === true) { + if (ctx._group) { + return resolve(ctx._group); + } + } + + const cmdReq = { target: this.id }; + const packetObj = createObject(packet.getGroup.type, cmdReq, ctx._client.source); + const sqnNumber = ctx._client.send(packetObj); + const timeoutHandle = setTimeout(() => { + reject(new ServiceErrorBuilder(ER_LIGHT_CMD_TIMEOUT).withContextualMessage(`Id: ${ctx.id}`).build()); + }, timeout); + + ctx._client.addMessageHandler( + packet.stateGroup.name, + (err: Error, data) => { + if (err) { + return reject(err); + } + + clearTimeout(timeoutHandle); + + return resolve({ + group: data.group, + label: data.label, + updatedAt: data.updatedAt + }); + }, + sqnNumber + ); + }); + } + public getTags(timeout: number = DEFAULT_MSG_REPLY_TIMEOUT) { const ctx = this;