-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.ts
709 lines (598 loc) · 22.8 KB
/
client.ts
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
import { WLEDClientOptions, WLEDClientState, WLEDClientInfo, WLEDClientEffects, WLEDClientPalettes, WLEDClientUpdatableState, WLEDClientUpdatableSegment, WLEDClientPlaylist, WLEDClientContext, WLEDClientLiveLEDs, WLEDClientNightlightState, WLEDClientSendOptions, WLEDClientPresets, WLEDClientPreset, WLEDClientCurrentStatePreset, WLEDClientDeviceOptions, WLEDClientLive, WLEDClientSendSegmentOptions, WLEDClientConfig, WLEDClientUpdatableConfig, WLEDClientLightCapabilities } from './types.client';
import { DEFAULT_OPTIONS, WLEDLiveDataOverride, WLEDNightlightMode, DEFAULT_CLIENT_CONTEXT } from './constants'
import { WLEDJSONAPI } from './apis/json'
import { WLEDWebsocketAPI } from './apis/websocket'
import { wledToClientState, wledToClientInfo, clientToWLEDState, wledToClientPresets, wledToClientDeviceOptions, wledToClientConfig, clientToWLEDConfig, wledToClientLightCapabilities } from './adapters';
import { RGBWColor, RGBColor, RequireAtLeastOne, BuildStateFn } from './types'
import { IsomorphicEventEmitter } from './utils.emitter'
import { isBuildStateFunction, sleep } from './utils'
import { WLEDContext, WLEDPresets, WLEDPalettesData, WLEDConfig } from './types.wled';
/**
* Client interface for WLED devices.
*/
export class WLEDClient extends IsomorphicEventEmitter {
/** Device's current state. */
public readonly state:WLEDClientState
/** Information about the device. */
public readonly info:WLEDClientInfo
/** List of effects available for this device. */
public readonly effects:WLEDClientEffects
/** List of color palettes available for this device. */
public readonly palettes:WLEDClientPalettes
/** List of presets save on this device. */
public readonly presets:WLEDClientPresets
/** */
public readonly config:WLEDClientConfig
/** Options that are set on the device. */
public readonly deviceOptions:WLEDClientDeviceOptions
/** Lighting capabilities of the device. */
public readonly lightCapabilities:WLEDClientLightCapabilities
/** Live streaming data sources currently sending data. */
public readonly live:WLEDClientLive
/** Promise that is resolved when a successful connection has been made and the state has been retrieved. */
private isReady:Promise<boolean>
private options:WLEDClientOptions
/** The ready state of the WebSocket instance. */
get wsReadyState() { return this.WSAPI.websocket.readyState }
private JSONAPI:WLEDJSONAPI
private WSAPI:WLEDWebsocketAPI
/**
* @param {string} host - The IP or hostname of the device.
*/
constructor(host:string)
/**
* @param {Partial<WLEDClientOptions>} options - Client options object.
*/
constructor(options:Partial<WLEDClientOptions>)
/** Create a new WLED Client. */
constructor(host_or_options:string|Partial<WLEDClientOptions> = {}) {
super()
let options:Partial<WLEDClientOptions>
if (typeof host_or_options == 'string') options = { host: host_or_options } // If `host_or_options` is a string, then it is the device's host
else options = host_or_options // Otherwise `host_or_options` is an options object
const resolved_options = Object.assign(DEFAULT_OPTIONS, options) // Build final options by assigning passed options over the default options
this.options = resolved_options // Store options
Object.assign(this, DEFAULT_CLIENT_CONTEXT) // Initialize the default context
this.WSAPI = new WLEDWebsocketAPI(resolved_options) // Initialize the WS API
this.WSAPI.on('error', (event) => this.emit('error', event)) // Relay error events
this.WSAPI.on('close', (event) => this.emit('close', event)) // Relay close events
this.WSAPI.on('open', (event) => this.emit('open', event)) // Relay open events
this.WSAPI.on('live:leds', (event) => this.emit<[WLEDClientLiveLEDs]>('live:leds', event)) // Relay live LEDs event
this.WSAPI.on('update:context', this.setContext.bind(this)) // Listen for updates on the WebSocket
this.JSONAPI = new WLEDJSONAPI(resolved_options) // Initialize the JSON API
this.JSONAPI.on('error', (event) => this.emit('error', event)) // Relay error events
if (resolved_options.immediate) this.init()
}
async init() {
if (this.isReady) return this.isReady
let initializing = this.options.websocket ? [this.refreshContext(this.options.init), this.WSAPI.connect()] : [this.refreshContext(this.options.init)]
let isReady = Promise.allSettled(initializing)
this.isReady = isReady.then(([json_result, ws_result]) => {
if ((ws_result && ws_result.status == 'rejected') && json_result.status == 'rejected') {
this.emit('error', json_result.reason)
return Promise.reject(json_result.reason)
}
if (json_result.status == 'fulfilled') {
this.emit('success', { transport: 'http' })
this.emit('success:http')
}
if (ws_result && ws_result.status == 'fulfilled') {
this.emit('success', { transport: 'ws' })
this.emit('success:ws')
}
this.emit('ready')
return true
})
}
/** Get the latest context from the device. */
async refreshContext(options:{presets?:boolean, config?:boolean} = {}) {
const {presets: get_presets = true, config: get_config = true} = options
const [context, presets, config] = await Promise.all([
this.JSONAPI.getAll(),
get_presets ? this.JSONAPI.getPresets() : Promise.resolve({}),
get_config ? this.JSONAPI.getConfig() : Promise.resolve({})
])
this.setContext({ ...context, presets, config })
}
/** Get the latest state from the device. */
async refreshState() {
const state = await this.JSONAPI.getState()
this.setContext({ state })
}
/** Get the latest info from the device. */
async refreshInfo() {
const info = await this.JSONAPI.getInfo()
this.setContext({ info })
}
/** Get the latest effects from the device. */
async refreshEffects() {
const effects = await this.JSONAPI.getEffects()
this.setContext({ effects })
}
/** Get the latest palettes from the device. */
async refreshPalettes() {
const palettes = await this.JSONAPI.getPalettes()
this.setContext({ palettes })
}
/** Get the latest presets from the device. */
async refreshPresets() {
const presets = await this.JSONAPI.getPresets()
this.setContext({ presets })
}
/** Get the latest config from the device. */
async refreshConfig() {
const config = await this.JSONAPI.getConfig()
this.setContext({ config })
}
private setContext({ state, info, effects, palettes, presets, config }:Partial<WLEDContext>&{presets?:WLEDPresets, config?:WLEDConfig}) {
let client_state = state ? wledToClientState(state) : this.state
let client_info = info ? wledToClientInfo(info) : this.info
let client_effects = effects ? effects : this.effects
let client_palettes = palettes ? palettes : this.palettes
let client_presets = presets ? wledToClientPresets(presets) : this.presets
let client_config = config ? wledToClientConfig(config) : this.config
let context:WLEDClientContext = {
state: client_state,
info: client_info,
effects: client_effects,
palettes: client_palettes,
presets: client_presets,
deviceOptions: info ? wledToClientDeviceOptions(info.opt) : this.deviceOptions,
lightCapabilities: info ? wledToClientLightCapabilities(info.leds.lc) : this.lightCapabilities,
live: this.live,
config: client_config
}
Object.assign(this, { ...context })
this.emit<[WLEDClientContext]>('update:context', context)
if (state) this.emit<[WLEDClientState]>('update:state', client_state)
if (info) this.emit<[WLEDClientInfo]>('update:info', client_info)
if (effects) this.emit<[WLEDClientEffects]>('update:effects', client_effects)
if (palettes) this.emit<[WLEDClientPalettes]>('update:palettes', client_palettes)
if (presets) this.emit<[WLEDClientPresets]>('update:presets', client_presets)
if (config) this.emit<[WLEDClientConfig]>('update:config', client_config)
}
/**
* Make an update to the state object with multiple values.
* @param {WLEDClientUpdatableState} state Partial state object of values to update
*/
async updateState(state:WLEDClientUpdatableState, options?:WLEDClientSendOptions) {
let use_method:'ws'|'json'|undefined
let timeout:number|undefined
if (options) { // Handle options passed for this call only
const { transition, noSync, method, timeout: o_timeout } = options
if (transition) state.temporaryTransition = transition
if (noSync) state.udpSync = { ...(state.udpSync || {}), noSync }
if (method) use_method = method
if (timeout) timeout = o_timeout
}
const wled_state = clientToWLEDState(state) // Transform the client state object into the WLED API state object
if ((!use_method || use_method != 'json') && this.WSAPI.available) {
try {
this.emit('loading')
await this.WSAPI.updateState(wled_state)
this.emit('success', { transport: 'ws' })
this.emit('success:ws')
return
} catch(e) {
this.emit('error', e)
}
}
if (!use_method || use_method != 'ws') {
try {
this.emit('loading')
let new_context = await this.JSONAPI.updateState({ ...wled_state, v: true }, { timeout }) as WLEDContext
this.emit('success', { transport: 'http' })
this.emit('success:http')
return this.setContext(new_context)
} catch(e) {
this.emit('error', e)
}
}
throw new Error('No transport available to handle state update.')
}
/**
* Make an update to the config object with multiple values.
* @param {WLEDClientUpdatableConfig} config Partial config object of values to update
*/
async updateConfig(config:WLEDClientUpdatableConfig) {
const wled_config = clientToWLEDConfig(config)
const { success } = await this.JSONAPI.updateConfig(wled_config)
if (success) this.refreshContext()
return success
}
/**
* Constructs a state update request that applies new state to all segments passed, or to the main state object if no segments are passed.
* @param state The state to update, or a function that is called optionally per-segment and returns the state to update
* @param segmentId One or more segment IDs
*/
buildStateWithSegments(state:(WLEDClientUpdatableState|WLEDClientUpdatableSegment)|BuildStateFn, segmentId?:number|number[]) {
let new_state:WLEDClientUpdatableState|WLEDClientUpdatableSegment
if (segmentId !== undefined) new_state = { segments: (Array.isArray(segmentId) ? segmentId : [segmentId]).map(id => ({ id, ...(isBuildStateFunction(state) ? state(this.getSegment(id)) : state) })) }
else new_state = isBuildStateFunction(state) ? state() : state
return new_state
}
/** Connect to the device's WebSocket API. */
connect() {
return this.WSAPI.connect()
}
/** Disconnect from the device's WebSocket API. */
disconnect() {
return this.WSAPI.disconnect()
}
/** Start a live stream of LED values from the device via the WebSocket API. Listen to the `update:leds` event (e.g. `wled.addEventListener('update:leds', cb)`). */
async startLEDStream() {
await this.WSAPI.startLEDStream()
this.live.leds = true
this.emit('update:live', this.live)
}
/** Stop the live stream of LED values from the device. */
async stopLEDStream() {
await this.WSAPI.stopLEDStream()
this.live.leds = false
this.emit('update:live', this.live)
}
/** Start the live stream if it is stopped, or stop the live stream if it is started */
toggleLEDStream() {
if (this.live.leds) return this.stopLEDStream()
return this.startLEDStream()
}
//
// Device Power
/** Hard reboot the device. */
reboot() {
return this.updateState({ reboot: true })
}
/** Set the device or segment power state to on. */
turnOn({ segmentId, ...options}:WLEDClientSendOptions&WLEDClientSendSegmentOptions={}) {
return this.updateState(this.buildStateWithSegments({ on: true }, segmentId), options)
}
/** Set the device or segment power state to off. */
turnOff({ segmentId, ...options}:WLEDClientSendOptions&WLEDClientSendSegmentOptions={}) {
return this.updateState(this.buildStateWithSegments({ on: false }, segmentId), options)
}
/** Change the device or segment power state to the opposite of what it currently is. */
toggle({ segmentId, ...options}:WLEDClientSendOptions&WLEDClientSendSegmentOptions={}) {
return this.updateState(this.buildStateWithSegments((segment) => {
return { on: segment ? !segment.on : !this.state.on }
}, segmentId), options)
}
//
// LED Brightness and Color
/**
* Set the device's master brightness.
* @param value Any integer between 0 and 255
*/
setBrightness(value:number, { segmentId, ...options}:WLEDClientSendOptions&WLEDClientSendSegmentOptions={}) {
return this.updateState(this.buildStateWithSegments({ brightness: value }, segmentId), options)
}
/**
* Set the primary color of the device's main segment.
* @param {RGBColor|RGBWColor} color RGB or RGBW color array
* @alias setPrimaryColor
*/
setColor(color:RGBColor|RGBWColor, options?:WLEDClientSendOptions&WLEDClientSendSegmentOptions) { return this.setPrimaryColor(color, options) }
/**
* Set the primary color of the device's main segment.
* @param {RGBColor|RGBWColor} color RGB or RGBW color array
*/
setPrimaryColor(color:RGBColor|RGBWColor, { segmentId, ...options}:WLEDClientSendOptions&WLEDClientSendSegmentOptions={}) {
return this.updateState(this.buildStateWithSegments({ colors: [color] }, segmentId||0), options)
}
/**
* Set the secondary color of the device's main segment.
* @param {RGBColor|RGBWColor} color RGB or RGBW color array
*/
setSecondaryColor(color:RGBColor|RGBWColor, { segmentId, ...options}:WLEDClientSendOptions&WLEDClientSendSegmentOptions={}) {
return this.updateState(this.buildStateWithSegments({ colors: [undefined, color] }, segmentId||0), options)
}
/**
* Set the tertiary color of the device's main segment.
* @param {RGBColor|RGBWColor} color RGB or RGBW color array
*/
setTertiaryColor(color:RGBColor|RGBWColor, { segmentId, ...options}:WLEDClientSendOptions&WLEDClientSendSegmentOptions={}) {
return this.updateState(this.buildStateWithSegments({ colors: [undefined, undefined, color] }, segmentId||0), options)
}
/**
* Set the correlated color temperature of the device's main segment.
* @param {number} kelvin The desired temperature in Kevlin
*/
setCCT(kelvin:number, { segmentId, ...options}:WLEDClientSendOptions&WLEDClientSendSegmentOptions={}) {
return this.updateState(this.buildStateWithSegments({ cct: kelvin }, segmentId||0), options)
}
/**
* Set the palette applied to the device's main segment.
* @param {number} paletteId ID of the desired palette, as found in `palettes`
*/
setPalette(paletteId:number, { segmentId, ...options}:WLEDClientSendOptions&WLEDClientSendSegmentOptions={}) {
return this.updateState(this.buildStateWithSegments({ paletteId }, segmentId||0), options)
}
private paletteDataCache:WLEDPalettesData
async getPalettesData(page?:number) {
let palettes_data:WLEDPalettesData = {}
if (page) {
const { p } = await this.JSONAPI.getPalettesDataPage(page) // If we want a specific page, just forward the request
Object.assign(palettes_data, p)
} else if(this.paletteDataCache) {
palettes_data = this.paletteDataCache // Return cached result
} else {
let max_page = 1 // Initialize with 1, will be updated after each request using the `m` property
page = 0
while (page <= max_page || page > 100) { // Just in case, hard cap at 100 page iterations
let result = await this.JSONAPI.getPalettesDataPage(page)
if (result != null) {
let { m, p } = result
Object.assign(palettes_data, p)
max_page = m
page++
} else {
await sleep(100) // If we're getting a NULL response, the device might be overloaded. Give the device some time to rest before trying again.
}
}
this.paletteDataCache = palettes_data // Cache the result in memory to optimize future calls
}
return palettes_data
}
//
// Effects
/**
* Set the effect applied to the device's main segment.
* @param {number} effectId ID of the desired effect, as found in `effects`
*/
setEffect(effectId:number, { segmentId, ...options}:WLEDClientSendOptions&WLEDClientSendSegmentOptions={}) {
return this.updateState(this.buildStateWithSegments({ effectId }, segmentId||0), options)
}
setEffectSpeed(value:number, { segmentId, ...options}:WLEDClientSendOptions&WLEDClientSendSegmentOptions={}) {
return this.updateState(this.buildStateWithSegments({ effectSpeed: value }, segmentId||0), options)
}
setEffectIntensity(value:number, { segmentId, ...options}:WLEDClientSendOptions&WLEDClientSendSegmentOptions={}) {
return this.updateState(this.buildStateWithSegments({ effectIntensity: value }, segmentId||0), options)
}
/**
* Duration of the crossfade between different colors/brightness levels.
* @param {number} value Time in 100ms intervals (eg. 4 is 400ms), 0 to 255
*/
setTransitionTime(value:number) {
return this.updateState({
transitionTime: value
})
}
//
// Segments
/**
* Set which segment should be considered the main one.
* @param {number} id ID of the main segment
*/
setMainSegmentId(id:number) {
return this.updateState({
mainSegmentId: id
})
}
/**
* Get a segment by its `id`.
* @param {number} id ID of the desired segment
*/
getSegment(id:number) {
return this.state.segments[id]
}
/**
* Create a new segment and adds it to the segment array.
* @param {WLEDClientUpdatableSegment} data Every updatable parameter on the segment object except `id`
*/
createSegment(data:Omit<WLEDClientUpdatableSegment, 'id'>) {
return this.updateState({
segments: [
...this.state.segments,
data
]
})
}
/**
* Update a specific segment by `id`.
* @param {number} id ID of the segment to be updated
* @param {WLEDClientUpdatableSegment} data Every updatable parameter on the segment object except `id`
*/
updateSegment(id:number, data:Omit<WLEDClientUpdatableSegment, 'id'>, options?:WLEDClientSendOptions) {
return this.updateState({
segments: [
{ id, ...data }
]
}, options)
}
/**
* Delete a specific segment by `id`.
* @param {number} id ID of the segment to be removed
*/
deleteSegment(id:number) {
return this.updateState({
segments: [
{ id, stop: 0 }
]
})
}
/**
* Set the entire segment array.
* @param {WLEDClientUpdatableSegment[]} segments Array of segment objects to replace the current array of segment objects
*/
async setSegments(segments:Omit<WLEDClientUpdatableSegment, 'id'>[]) {
await this.clearSegments()
return this.updateState({ segments })
}
/** Clear the segment array completely. */
clearSegments() {
return this.updateState({
segments: this.state.segments.map(() => ({ stop: 0 }))
})
}
//
// Playlist
/**
* Set a playlist for the device.
* @param {WLEDClientPlaylist} playlist A playlist object
*/
setPlaylist(playlist:WLEDClientPlaylist) {
return this.updateState({ playlist })
}
//
// Nightlight
/** Methods relating to the nightlight feature. */
nightlight = (() => {
const wled = this
return {
/**
* State object of the nightlight feature
* @alias WLEDClient.state.nightlight
*/
get state() { return wled.state.nightlight },
/**
* Activate the nightlight. Depending on the set mode, the device will fade towards the target brightness over the set duration.
* @param {number|WLEDClientNightlightState} with_state Optional. Duration if number is passed, otherwise nightlight state object containing other properties to set while activating the nightlight
*/
enable(with_state:number|Omit<Partial<WLEDClientNightlightState>, 'on'> = {}) {
if (typeof with_state == 'number') with_state = { duration: with_state }
this.state.remaining = this.state.duration
return wled.updateState({
nightlight: {
on: true,
...with_state
}
})
},
/** Deactivate the nightlight. */
disable() {
return wled.updateState({
nightlight: {
on: false
}
})
},
/** Change the nightlight state to the opposite of what it currently is. */
toggle() {
return wled.updateState({
nightlight: {
on: !wled.state.nightlight.on
}
})
},
/**
* Set the length of time the nightlight feature will remain active for.
* @param {number} value Time in minutes, 1 to 255
*/
setDuration(value:number) {
return wled.updateState({
nightlight: {
duration: value
}
})
},
/**
* Set the target brightness of the nightlight feature.
* @param {number} value 0 to 255
*/
setTargetBrightness(value:number) {
return wled.updateState({
nightlight: {
targetBrightness: value
}
})
},
/**
* Set the mode the nightlight will operate by.
* @param {WLEDNightlightMode} mode
*/
setMode(mode:WLEDNightlightMode) {
return wled.updateState({
nightlight: {
mode
}
})
}
}
})()
//
// Live Data
/**
* Ignore any live data if the device is currently being used to display the live data.
* @param {boolean} until_reboot If `false` or `undefined`, the live data will be ignored until the live data stream ends. If `true` the device will ignore live data until it reboots.
*/
ignoreLiveData(until_reboot?:boolean) {
let liveDataOverride:WLEDLiveDataOverride = until_reboot ? WLEDLiveDataOverride.UNTIL_REBOOT : WLEDLiveDataOverride.UNTIL_END
return this.updateState({ liveDataOverride })
}
/** Allow live data to be displayed by the device. */
allowLiveData() {
return this.updateState({
liveDataOverride: WLEDLiveDataOverride.OFF
})
}
//
// UDP Sync
enableUDPSync(options?:RequireAtLeastOne<WLEDClientState['udpSync']>) {
if (!options) {
options = { send:true }
if (this.info.syncToggleReceive) options.receive = true
}
return this.updateState({
udpSync: options as WLEDClientState['udpSync']
})
}
disableUDPSync() {
let udpSync:WLEDClientState['udpSync'] = { send: false }
if (this.info.syncToggleReceive) udpSync.receive = false
return this.updateState({ udpSync })
}
//
// Presets
/**
* Get a preset by its ID.
* @param {number} id ID of the desired preset
*/
getPreset(id:number) {
return this.presets[id]
}
/**
* Activate a new preset.
* @param {number} id ID of the desired preset
*/
setPreset(id:number) {
return this.updateState({
presetId: id
})
}
/**
* Save a preset using the device's current state.
* @param {number} id
* @param {WLEDClientCurrentStatePreset} preset
*/
async saveStateAsPreset(id:number, preset:WLEDClientCurrentStatePreset) {
preset = Object.assign({ includeBrightness: true, segmentBounds: true }, preset)
await this.updateState({
savePresetId: id,
...preset,
time: new Date().getTime()
}, { method: 'json' })
// To Do: Build and add new preset object
}
/**
* Save a preset.
* @param {number} id
* @param {WLEDClientPreset} preset
*/
async savePreset(id:number, preset:WLEDClientPreset) {
await this.updateState({
savePresetId: id,
overwriteState: true,
...preset
}, { method: 'json' })
this.presets[id] = preset
}
/**
* Delete a preset by its ID.
* @param {number} id ID of the preset to delete
*/
async deletePreset(id:number) {
await this.updateState({
deletePresetId: id
})
delete this.presets[id]
}
}