-
Notifications
You must be signed in to change notification settings - Fork 1
/
stream-deck.ts
439 lines (389 loc) · 14.3 KB
/
stream-deck.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
import { emit, EventEmitter } from "./event-emitter";
import { checkRGBValue } from "./helpers";
import { HidAsync } from "./hid/hid-async";
import { IImageLibrary, IImageLibraryCreator, IImageRawOptions } from "./image-library";
/**
* Abstract base class which is a partial implementation and must be extended.
*
* To see which abstract properties and methods are required for a subclass
* check out the typings and look for the keyword `abstract`.
*/
export abstract class StreamDeck extends EventEmitter {
/**
* The pixel size of an icon written to the Stream Deck key.
*
* @readonly
*/
public abstract readonly iconSize: number;
/**
* The number of keys available for the Stream Deck.
*
* @readonly
*/
public abstract readonly buttonLength: number;
/**
* The number of columns of keys available for the Stream Deck.
*
* @readonly
*/
public abstract readonly buttonColumns: number;
/**
* The number of rows of keys available for the Stream Deck.
*
* @readonly
*/
public abstract readonly buttonRows: number;
/**
* The layout of the stream deck showing which position has a specific `keyIndex`.
*
* @readonly
*/
public abstract readonly buttonLayout: number[][];
/**
* The size of a page packet.
*
* @readonly
*/
protected abstract readonly pagePacketSize: number;
/**
* The connected device.
*/
protected device: HidAsync;
/**
* The current state of key presses.
*
* Limited to 32 buttons.
*/
protected keyState: number;
// tslint:disable-next-line:variable-name
protected _imageLibrary?: string | IImageLibraryCreator | PromiseLike<IImageLibraryCreator>;
/**
* The image library to use.
* If not already imported getting this property will trigger the import.
*
* @readonly
*/
public get imageLibrary() {
if (!this._imageLibrary) {
this._imageLibrary = import("./image-library").then((x) => x.default);
} else if (typeof this._imageLibrary === "string") {
this._imageLibrary = import(this._imageLibrary).then((x) => x.default || x);
}
return this._imageLibrary;
}
/**
* A sorted list containing the `keyIndex` of all buttons currently pressed.
*
* @readonly
*/
public get pressedKeys(): number[] {
const r: number[] = [];
for (let i = 0; i < this.buttonLength; i++) {
// tslint:disable-next-line:no-bitwise
if (this.keyState & (1 << i)) {
r.push(i);
}
}
return r;
}
/**
* A boolean showing if there currently are any pressed keys.
*
* @readonly
*/
public get hasPressedKeys(): boolean {
return this.keyState !== 0;
}
/**
* Connects to a HID device.
*
* @param {string} devicePath path to the HID device.
*/
public constructor(devicePath: string) {
super();
if (!devicePath) {
throw new Error("No Stream Decks are connected.");
} else {
this.device = new HidAsync(devicePath);
}
this.keyState = 0;
this.device.on("data", (data) => this.onDeviceData(data));
this.device.on("error", (err) => {
if (typeof err !== "object") {
err = new Error(err);
}
if (!this[emit]("error", err)) {
Promise.resolve().then(() => {
throw err;
});
}
});
}
/**
* Sets which image library should be used.
*
* If the parameter is a `string` the module or file will be imported when needed
* and expects `default` to be an `IImageLibraryCreator`.
* If no `default` is exported the functions defined in an `IImageLibraryCreator` must have been exported directly.
*
* @param {string | Promise<Object> | Object} library A name, path, or reference to an image library.
* @return {StreamDeck} this
*/
public setImageLibrary(library: string | IImageLibraryCreator | PromiseLike<IImageLibraryCreator>): this {
this._imageLibrary = library;
return this;
}
/**
* Checks a keyIndex is a valid key for a stream deck. An integer between 0 and `buttonLength - 1`.
*
* @param {number} keyIndex The keyIndex to check
*/
public checkValidKeyIndex(keyIndex: number): number {
// tslint:disable-next-line:no-bitwise
if (typeof keyIndex !== "number" || (keyIndex | 0) !== keyIndex) {
throw new TypeError("Expected keyIndex to be an integer");
}
if (keyIndex < 0 || keyIndex >= this.buttonLength) {
throw new TypeError("Expected a valid keyIndex 0 - " + (this.buttonLength - 1));
}
return keyIndex;
}
/**
* Loops through every available keyIndex.
*
* @param {Function} func The function to pass the keyIndex and the streamDeck instance to
* @returns {StreamDeck} this
*/
public forEachKey(func: (keyIndex: number, streamDeck: this) => any): this {
for (let i = 0; i < this.buttonLength; i++) {
func.call(this, i, this);
}
return this;
}
/**
* Get the `keyIndex` at a specific column and row.
*
* @param {number} x column number
* @param {number} y row number
* @returns {number} keyIndex
*/
public buttonIndexFromPosition(x: number, y: number): number | undefined {
if (this.buttonLayout[y] === undefined) {
return undefined;
}
return this.buttonLayout[y][x];
}
/**
* Writes a Buffer to the Stream Deck.
*
* @param {Uint8Array} buffer The buffer written to the Stream Deck
* @returns {Promise<number>} Resolves to the number of bytes written
*/
public write(buffer: Uint8Array): Promise<number> {
return this.device.write(buffer);
}
/**
* Writes a Buffer to the Stream Deck.
*
* @param {Uint8Array[]} buffers A list of buffers to be written to the Stream Deck
* @returns {Promise<number>} Resolves to the number of bytes written
*/
public writeMulti(buffers: Uint8Array[]): Promise<number> {
return this.device.writeMulti(buffers);
}
/**
* Sends a HID feature report to the Stream Deck.
*
* @param {Uint8Array} buffer The buffer send to the Stream Deck.
* @returns {Promise<number>} Resolves to the number of bytes written
*/
public sendFeatureReport(buffer: Uint8Array): Promise<number> {
return this.device.sendFeatureReport(buffer);
}
/**
* Closes this reference to the device.
*/
public close(): void {
this.device.close();
}
/**
* Fills the given key with a solid color.
*
* @param {number} keyIndex The key to fill 0 - 14
* @param {number} r The color's red value. 0 - 255
* @param {number?} g The color's green value. 0 - 255
* @param {number?} b The color's blue value. 0 -255
* @return {Promise<number>} Resolves to the number of bytes written.
*/
public fillColor(keyIndex: number, rgb: number): Promise<number>;
public fillColor(keyIndex: number, r: number, g: number, b: number): Promise<number>;
public fillColor(keyIndex: number, r: number, g?: number, b?: number): Promise<number> {
this.checkValidKeyIndex(keyIndex);
if (g === undefined || b === undefined) {
// tslint:disable-next-line:no-bitwise
b = r & 0x0000FF;
// tslint:disable-next-line:no-bitwise
g = (r & 0x00FF00) >> 8;
// tslint:disable-next-line:no-bitwise
r = (r & 0xFF0000) >> 16;
}
checkRGBValue(r);
checkRGBValue(g);
checkRGBValue(b);
const pixels = Buffer.alloc(this.iconSize * this.iconSize * 3, Buffer.from([b, g, r]));
return this.writeImagePage(keyIndex, pixels);
}
/**
* Fills the given key with an image in a Buffer.
*
* @param {number} keyIndex The key to fill 0 - 14
* @param {Uint8Array} imageBuffer
*/
public fillImage(keyIndex: number, imageBuffer: Uint8Array) {
this.checkValidKeyIndex(keyIndex);
const iconWidth = this.iconSize;
const iconHeight = this.iconSize;
const area = iconWidth * iconHeight;
const areadepth = area * 3;
if (imageBuffer.length !== areadepth) {
throw new RangeError(`Expected image buffer of length ${areadepth}, got length ${imageBuffer.length}`);
}
const pixels = Buffer.alloc(area * 3);
const l = iconWidth * 3;
for (let y = 0; y < iconHeight; y++) {
const start = y * l;
for (let i = 0; i < l; i += 3) {
const r = imageBuffer[i + start];
const g = imageBuffer[i + start + 1];
const b = imageBuffer[i + start + 2];
pixels[start + l - i - 1] = r && 0x80;
pixels[start + l - i - 2] = g;
pixels[start + l - i - 3] = b && 0x20;
}
}
return this.writeImagePage(keyIndex, pixels);
}
/**
* Fills the given key with an image from a file.
*
* @param {number} keyIndex The key to fill 0 - 14
* @param {string} filePath A file path to an image file
* @returns {Promise<number>} Resolves to the number of bytes that has been written
*/
public async fillImageFromFile(keyIndex: number, filePath: string): Promise<number> {
this.checkValidKeyIndex(keyIndex);
const imglib = await this.imageLibrary;
const imgins = await imglib.loadFile(filePath);
const buffer = await this.processImage(imgins);
return this.fillImage(keyIndex, buffer);
}
/**
* Fills the whole panel with an image in a Buffer.
* The image is scaled to fit, and then center-cropped (if necessary).
*
* @param {Uint8Array|string} imagePathOrBuffer
* @param {Object} [rawOptions] If supplying a buffer of raw pixels the size of the image must be specified.
* @param {Object} [rawOptions.channels] Number of channels per pixel.
* @param {Object} [rawOptions.height] Height of the raw pixel image.
* @param {Object} [rawOptions.width] Width of the raw pixel image.
*/
public async fillPanel(imagePathOrBuffer: Uint8Array | string): Promise<number>;
public async fillPanel(imagePathOrBuffer: Uint8Array, rawOptions: IImageRawOptions): Promise<number>;
public async fillPanel(imagePathOrBuffer: Uint8Array | string, rawOptions?: IImageRawOptions): Promise<number> {
const iconHeight = this.iconSize;
const iconWidth = this.iconSize;
const cols = this.buttonColumns;
const imglib = await this.imageLibrary;
const image0 = await (rawOptions
? imglib.createRaw(imagePathOrBuffer as Uint8Array, rawOptions)
: typeof imagePathOrBuffer === "string"
? imglib.loadFile(imagePathOrBuffer)
: imglib.loadFileData(imagePathOrBuffer)
);
const image1 = await image0.resize(cols * iconWidth, this.buttonRows * iconHeight);
const image = await image1.flatten(); // Eliminate alpha channel, if any.
const buttons = [];
for (let row = 0; row < this.buttonRows; row++) {
for (let column = 0; column < cols; column++) {
buttons.push({
index: (row * cols) + cols - column - 1,
x: column,
y: row,
});
}
}
const ret: Array<Promise<number>> = [];
for (const button of buttons) {
const part = await image.extract({
height: iconHeight,
left: button.x * iconWidth,
top: button.y * iconHeight,
width: iconWidth,
});
ret.push(this.fillImage(button.index, await part.toUint8Array()));
}
return Promise.all(ret).then((a) => a.reduce((x, y) => x + y, 0));
}
/**
* Clears the given key.
*
* @param {number} keyIndex The key to clear 0 - 14
*/
public clearKey(keyIndex: number) {
this.checkValidKeyIndex(keyIndex);
return this.fillColor(keyIndex, 0, 0, 0);
}
/**
* Clears all keys.
*
* returns {undefined}
*/
public clearAllKeys() {
return this.forEachKey(this.clearKey);
}
/**
* Sets the brightness of the keys on the Stream Deck
*
* @param {number} percentage The percentage brightness
*/
public setBrightness(percentage: number) {
if (percentage < 0 || percentage > 100) {
throw new RangeError("Expected brightness percentage to be between 0 and 100");
}
const brightnessCommandBuffer = Buffer.alloc(17);
brightnessCommandBuffer.set([0x05, 0x55, 0xaa, 0xd1, 0x01, percentage]);
return this.sendFeatureReport(brightnessCommandBuffer);
}
protected onDeviceData(data: Uint8Array) {
// The first byte is a report ID, the last byte appears to be padding.
// We strip these out for now.
data = data.slice(1, data.length - 1);
for (let i = 0; i < this.buttonLength; i++) {
// tslint:disable-next-line:no-bitwise
const bitidx = 1 << i;
const keyPressed = data[i] ? bitidx : 0;
// tslint:disable-next-line:no-bitwise
const stateChanged = keyPressed !== (this.keyState & bitidx);
if (stateChanged) {
// tslint:disable-next-line:no-bitwise
this.keyState ^= bitidx;
if (keyPressed) {
this[emit]("down", i);
} else {
this[emit]("up", i);
}
}
}
}
/**
* Process an image to be shown on the stream deck.
*
* @param {Object} image image to extract pixels from.
*/
protected async processImage(image: IImageLibrary): Promise<Uint8Array> {
const i0 = await image.flatten(); // Eliminate alpha channel, if any.
const i1 = await i0.resize(this.iconSize, this.iconSize);
return i1.toUint8Array();
}
protected abstract writeImagePage(keyIndex: number, pixels: Uint8Array): Promise<number>;
}