-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.js
More file actions
303 lines (268 loc) · 11 KB
/
app.js
File metadata and controls
303 lines (268 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
'use strict';
const Homey = require('homey');
const mqtt = require('mqtt');
const { EventEmitter } = require('events');
const gvCloud = require('./api/govee-api-v2');
class GoveeApp extends Homey.App {
/**
* onInit is called when the app is initialized.
*/
async onInit() {
this.log('Govee App has been initialized');
//Setup global jobs
this.mqttClient=null;
this.localApiClient=null;
this.cloudApi=null;
//Create an event emitter to send received mqtt to the devices
this.eventBus = new EventEmitter();
// Initialize cloud API for app-level flow cards
this.initCloudApi();
// Listen for API key changes to reinitialize cloud API
this.homey.settings.on('set', (key) => {
if (key === 'api_key') {
this.cloudApi = null; // Force reinit on next use
this.log('API key updated, cloud API will reinitialize on next use');
}
});
// Register Dreamview toggle action card
this._toggleDreamviewDevice = this.homey.flow.getActionCard('toggle-dreamview-device');
this._toggleDreamviewDevice.registerRunListener(async (args) => {
// args.state is the dropdown ID string directly (e.g., "on" or "off")
return this.toggleDreamviewDevice(args.device, args.state);
});
this._toggleDreamviewDevice.registerArgumentAutocompleteListener('device', async (query, args) => {
return this.getDreamviewDevices(query);
});
// Register BaseGroup toggle action card
this._toggleGroupDevice = this.homey.flow.getActionCard('toggle-group-device');
this._toggleGroupDevice.registerRunListener(async (args) => {
return this.toggleVirtualDevice(args.device, args.state);
});
this._toggleGroupDevice.registerArgumentAutocompleteListener('device', async (query, args) => {
return this.getVirtualDevicesBySkus(['BaseGroup'], query, 'Device Group');
});
// Register SameModeGroup toggle action card
this._toggleSamemodelGroup = this.homey.flow.getActionCard('toggle-samemodel-group');
this._toggleSamemodelGroup.registerRunListener(async (args) => {
return this.toggleVirtualDevice(args.device, args.state);
});
this._toggleSamemodelGroup.registerArgumentAutocompleteListener('device', async (query, args) => {
return this.getVirtualDevicesBySkus(['SameModeGroup'], query, 'Same-Model Group');
});
// Register Dreamview Scenes widget autocomplete for each scene slot (3 scenes per row)
const dreamviewWidget = this.homey.dashboards.getWidget('dreamview-scenes');
for (let i = 1; i <= 3; i++) {
dreamviewWidget.registerSettingAutocompleteListener(`scene${i}`, async (query) => {
return this.getDreamviewDevices(query);
});
}
// Register Govee Groups widget autocomplete for each group slot (3 groups per row)
const groupsWidget = this.homey.dashboards.getWidget('govee-groups');
for (let i = 1; i <= 3; i++) {
groupsWidget.registerSettingAutocompleteListener(`group${i}`, async (query) => {
return this.getVirtualDevicesBySkus(['BaseGroup', 'SameModeGroup'], query, 'Group');
});
}
// Handle uncaught errors from the govee-lan-control library
// This prevents the app from crashing due to library bugs or network issues
process.on('uncaughtException', (err) => {
// Handle UDP port already in use
if (err.code === 'EADDRINUSE' && err.message.includes('4002')) {
this.error('[GoveeApp] UDP port 4002 is already in use - local API disabled');
this.error('[GoveeApp] Another application (Home Assistant, another Govee app) may be using this port');
// Mark the local API client as failed if it exists
if (this.localApiClient) {
this.localApiClient.initError = err;
this.localApiClient.isReady = false;
}
return; // Don't re-throw, handle gracefully
}
// Handle govee-lan-control library bug: accessing state of undefined device
// This happens when the library receives a UDP message for an unknown device
if (err instanceof TypeError && err.message.includes("Cannot read properties of undefined (reading 'state')") &&
err.stack && err.stack.includes('govee-lan-control')) {
this.error('[GoveeApp] Govee LAN library received message for unknown device (ignoring)');
return; // Don't re-throw, this is a known library bug
}
// Handle JSON parsing errors from corrupted UDP messages in govee-lan-control
// This happens when the library receives garbled or partial network data
if (err instanceof SyntaxError && err.stack && err.stack.includes('govee-lan-control')) {
this.error('[GoveeApp] Govee LAN library received malformed data (ignoring):', err.message);
return; // Don't re-throw, network corruption is expected occasionally
}
// Handle other govee-lan-control errors gracefully
if (err.stack && err.stack.includes('govee-lan-control')) {
this.error('[GoveeApp] Govee LAN library error (ignoring):', err.message);
return; // Don't re-throw library errors
}
// Re-throw other uncaught exceptions
this.error('[GoveeApp] Uncaught exception:', err.message);
throw err;
});
}
async onUninit() {
//We need to disconnect our hosts
if (this.mqttClient != null) {
try {
this.mqttClient.end();
this.mqttClient.destroy();
} catch (err) {
this.error('Error cleaning up MQTT client:', err.message);
}
}
if (this.localApiClient != null) {
try {
this.localApiClient.destroy();
} catch (err) {
this.error('Error cleaning up Local API client:', err.message);
}
}
//Kill the eventbus, this prevents subscribed events from trying to fire while we are destroying hosts
this.eventBus.removeAllListeners();
this.log('Cleaned up open connections');
}
async setupMqttReceiver(){
//We only need to do this once for cloud devices
if(this.mqttClient!==null)
return;
const emqx_url = 'mqtt.openapi.govee.com';
const options = {
clean: true,
username: this.homey.settings.get('api_key'),
password: this.homey.settings.get('api_key'),
}
this.log('Connecting the mqtt broker for status updates');
const connectUrl = 'mqtts://' + emqx_url
const client = mqtt.connect(connectUrl, options)
client.on('connect', () => {
this.log('Connected to the mqtt broker.')
client.subscribe("GA/"+this.homey.settings.get('api_key'), (err) => {
if (!err) {
this.log('Subscribed to mqtt topic apiKey')
}
})
})
this.mqttClient=client;
this.mqttClient.on('message', (topic, message) => {
this.log(`Received message from topic ${topic}`)
const jsonString = message.toString();
const payload = JSON.parse(jsonString);
this.log(JSON.stringify(payload));
this.log('Message is for device ['+payload.device+']');
this.eventBus.emit('device_event_'+payload.device, payload);
})
}
/**
* Initialize the cloud API client for app-level flow cards
*/
initCloudApi() {
const apiKey = this.homey.settings.get('api_key');
if (apiKey) {
this.cloudApi = new gvCloud.GoveeClient({ api_key: apiKey });
this.log('Cloud API initialized for app-level flow cards');
}
}
/**
* Get virtual devices of specific SKU types for autocomplete
*/
async getVirtualDevicesBySkus(skus, query, description) {
const apiKey = this.homey.settings.get('api_key');
if (!apiKey) {
throw new Error('Cloud API key not configured. Please add your Govee API key in the app settings.');
}
if (!this.cloudApi) {
this.initCloudApi();
}
try {
const response = await this.cloudApi.deviceList();
return response.data
.filter(device => skus.includes(device.sku))
.filter(device => device.deviceName.toLowerCase().includes(query.toLowerCase()))
.map(device => ({
name: device.deviceName,
description,
id: device.device,
sku: device.sku
}));
} catch (error) {
this.error('Failed to fetch virtual devices:', error);
throw new Error('Failed to fetch devices from Govee cloud. Please check your API key.');
}
}
/**
* Activate or deactivate any virtual device (group, scene) via cloud API
*/
async toggleVirtualDevice(device, state) {
const apiKey = this.homey.settings.get('api_key');
if (!apiKey) {
throw new Error('Cloud API key not configured. Please add your Govee API key in the app settings.');
}
if (!this.cloudApi) {
this.initCloudApi();
}
const mode = state === 'on' ? 1 : 0;
const action = state === 'on' ? 'activated' : 'deactivated';
try {
await this.cloudApi.devicesTurn(mode, device.sku, device.id);
this.log(`Virtual device "${device.name}" ${action}`);
return true;
} catch (error) {
this.error('Failed to toggle virtual device:', error);
throw new Error(`Failed to ${state === 'on' ? 'activate' : 'deactivate'} device: ${error.message}`);
}
}
/**
* Get list of DreamViewScenic scenes from cloud API for autocomplete
*/
async getDreamviewDevices(query) {
const apiKey = this.homey.settings.get('api_key');
if (!apiKey) {
throw new Error('Cloud API key not configured. Please add your Govee API key in the app settings.');
}
if (!this.cloudApi) {
this.initCloudApi();
}
try {
const response = await this.cloudApi.deviceList();
// Filter for DreamViewScenic virtual device groups
const dreamviewScenes = response.data.filter(device => {
return device.sku === 'DreamViewScenic';
});
// Filter by query and map to autocomplete format
return dreamviewScenes
.filter(device => device.deviceName.toLowerCase().includes(query.toLowerCase()))
.map(device => ({
name: device.deviceName,
description: 'Dreamview Scene',
id: device.device,
sku: device.sku
}));
} catch (error) {
this.error('Failed to fetch Dreamview scenes:', error);
throw new Error('Failed to fetch Dreamview scenes from Govee cloud. Please check your API key.');
}
}
/**
* Activate or deactivate a Dreamview scene via cloud API
*/
async toggleDreamviewDevice(device, state) {
const apiKey = this.homey.settings.get('api_key');
if (!apiKey) {
throw new Error('Cloud API key not configured. Please add your Govee API key in the app settings.');
}
if (!this.cloudApi) {
this.initCloudApi();
}
const mode = state === 'on' ? 1 : 0;
const action = state === 'on' ? 'activated' : 'deactivated';
try {
await this.cloudApi.devicesTurn(mode, device.sku, device.id);
this.log(`Dreamview scene "${device.name}" ${action}`);
return true;
} catch (error) {
this.error('Failed to toggle Dreamview scene:', error);
throw new Error(`Failed to ${state === 'on' ? 'activate' : 'deactivate'} scene: ${error.message}`);
}
}
}
module.exports = GoveeApp;