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
use std::io::Error as IoError;
use std::time::Duration;
#[macro_use]
extern crate log;
extern crate hidapi;
use hidapi::{HidApi, HidDevice, HidError};
extern crate image;
use image::{DynamicImage, ImageBuffer, ImageError, Rgb};
pub mod images;
use crate::images::{apply_transform, encode_jpeg};
pub use crate::images::{Colour, ImageOptions};
pub mod info;
pub use info::*;
use imageproc::drawing::draw_text_mut;
use rusttype::{Font, Scale};
use std::str::FromStr;
use thiserror::Error;
pub struct StreamDeck {
kind: Kind,
device: HidDevice,
}
#[cfg(feature = "structopt")]
#[derive(structopt::StructOpt)]
pub struct Filter {
#[structopt(long, default_value="0fd9", parse(try_from_str=u16_parse_hex), env="USB_VID")]
pub vid: u16,
#[structopt(long, default_value="0063", parse(try_from_str=u16_parse_hex), env="USB_PID")]
pub pid: u16,
#[structopt(long, env = "USB_SERIAL")]
pub serial: Option<String>,
}
fn u16_parse_hex(s: &str) -> Result<u16, std::num::ParseIntError> {
u16::from_str_radix(s, 16)
}
#[derive(Debug, Error)]
pub enum Error {
#[error(transparent)]
Hid(#[from] HidError),
#[error(transparent)]
Io(#[from] IoError),
#[error(transparent)]
Image(#[from] ImageError),
#[error("invalid image size")]
InvalidImageSize,
#[error("invalid key index")]
InvalidKeyIndex,
#[error("unrecognised pid")]
UnrecognisedPID,
#[error("no data")]
NoData,
}
pub struct DeviceImage {
data: Vec<u8>,
}
pub mod pids {
pub const ORIGINAL: u16 = 0x0060;
pub const ORIGINAL_V2: u16 = 0x006d;
pub const MINI: u16 = 0x0063;
pub const XL: u16 = 0x006c;
pub const MK2: u16 = 0x0080;
}
impl StreamDeck {
pub fn connect(vid: u16, pid: u16, serial: Option<String>) -> Result<StreamDeck, Error> {
let api = HidApi::new()?;
StreamDeck::connect_with_hid(&api, vid, pid, serial)
}
pub fn connect_with_hid(
api: &HidApi,
vid: u16,
pid: u16,
serial: Option<String>,
) -> Result<StreamDeck, Error> {
let kind = match pid {
pids::ORIGINAL => Kind::Original,
pids::MINI => Kind::Mini,
pids::ORIGINAL_V2 => Kind::OriginalV2,
pids::XL => Kind::Xl,
pids::MK2 => Kind::Mk2,
_ => return Err(Error::UnrecognisedPID),
};
debug!("Device info: {:?}", kind);
let device = match &serial {
Some(s) => api.open_serial(vid, pid, s),
None => api.open(vid, pid),
}?;
Ok(StreamDeck { device, kind })
}
pub fn kind(&self) -> Kind {
self.kind
}
pub fn manufacturer(&mut self) -> Result<String, Error> {
let s = self.device.get_manufacturer_string()?;
Ok(s.unwrap())
}
pub fn product(&mut self) -> Result<String, Error> {
let s = self.device.get_product_string()?;
Ok(s.unwrap())
}
pub fn serial(&mut self) -> Result<String, Error> {
let s = self.device.get_serial_number_string()?;
Ok(s.unwrap())
}
pub fn version(&mut self) -> Result<String, Error> {
let mut buff = [0u8; 17];
buff[0] = if self.kind.is_v2() { 0x05 } else { 0x04 };
let _s = self.device.get_feature_report(&mut buff)?;
let offset = if self.kind.is_v2() { 6 } else { 5 };
Ok(std::str::from_utf8(&buff[offset..]).unwrap().to_string())
}
pub fn reset(&mut self) -> Result<(), Error> {
let mut cmd = [0u8; 17];
if self.kind.is_v2() {
cmd[..2].copy_from_slice(&[0x03, 0x02]);
} else {
cmd[..2].copy_from_slice(&[0x0b, 0x63]);
}
self.device.send_feature_report(&cmd)?;
Ok(())
}
pub fn set_brightness(&mut self, brightness: u8) -> Result<(), Error> {
let mut cmd = [0u8; 17];
let brightness = brightness.min(100);
if self.kind.is_v2() {
cmd[..3].copy_from_slice(&[0x03, 0x08, brightness]);
} else {
cmd[..6].copy_from_slice(&[0x05, 0x55, 0xaa, 0xd1, 0x01, brightness]);
}
self.device.send_feature_report(&cmd)?;
Ok(())
}
pub fn set_blocking(&mut self, blocking: bool) -> Result<(), Error> {
self.device.set_blocking_mode(blocking)?;
Ok(())
}
pub fn read_buttons(&mut self, timeout: Option<Duration>) -> Result<Vec<u8>, Error> {
let mut cmd = [0u8; 36];
let keys = self.kind.keys() as usize;
let offset = self.kind.key_data_offset();
match timeout {
Some(t) => self
.device
.read_timeout(&mut cmd[..keys + offset + 1], t.as_millis() as i32)?,
None => self.device.read(&mut cmd[..keys + offset + 1])?,
};
if cmd[0] == 0 {
return Err(Error::NoData);
}
let mut out = vec![0u8; keys];
match self.kind.key_direction() {
KeyDirection::RightToLeft => {
for (i, val) in out.iter_mut().enumerate() {
*val = cmd[offset + self.translate_key_index(i as u8)? as usize];
}
}
KeyDirection::LeftToRight => {
out[0..keys].copy_from_slice(&cmd[1 + offset..1 + offset + keys]);
}
}
Ok(out)
}
pub fn image_size(&self) -> (usize, usize) {
self.kind.image_size()
}
fn convert_image(&self, image: Vec<u8>) -> Result<DeviceImage, Error> {
if image.len() != self.kind.image_size_bytes() {
return Err(Error::InvalidImageSize);
}
let image = match self.kind.image_mode() {
ImageMode::Bmp => image,
ImageMode::Jpeg => {
let (w, h) = self.kind.image_size();
encode_jpeg(&image, w, h)?
}
};
Ok(DeviceImage{ data: image })
}
pub fn set_button_rgb(&mut self, key: u8, colour: &Colour) -> Result<(), Error> {
let mut image = vec![0u8; self.kind.image_size_bytes()];
let colour_order = self.kind.image_colour_order();
for i in 0..image.len() {
match i % 3 {
0 => {
image[i] = match colour_order {
ColourOrder::BGR => colour.b,
ColourOrder::RGB => colour.r,
}
}
1 => image[i] = colour.g,
2 => {
image[i] = match colour_order {
ColourOrder::BGR => colour.r,
ColourOrder::RGB => colour.b,
}
}
_ => unreachable!(),
};
}
self.write_button_image(key, &self.convert_image(image)?)?;
Ok(())
}
pub fn set_button_image(&mut self, key: u8, image: DynamicImage) -> Result<(), Error> {
let image = apply_transform(image, self.kind.image_rotation(), self.kind.image_mirror());
let image = match self.kind.image_colour_order() {
ColourOrder::BGR => image.into_bgra8().into_vec(),
ColourOrder::RGB => image.into_rgb8().into_vec(),
};
self.write_button_image(key, &self.convert_image(image)?)
}
pub fn set_button_text(
&mut self,
key: u8,
font: &Font,
pos: &TextPosition,
text: &str,
opts: &TextOptions,
) -> Result<(), Error> {
let (width, height) = self.kind.image_size();
let background = Rgb([opts.background.r, opts.background.g, opts.background.b]);
let colour = Rgb([opts.foreground.r, opts.foreground.g, opts.foreground.b]);
let mut image = ImageBuffer::from_pixel(width as u32, height as u32, background);
match pos {
TextPosition::Absolute { x, y } => {
let mut y = *y;
text.to_string().split("\n").for_each(|txt| {
draw_text_mut(&mut image, colour, *x, y, opts.scale, font, txt);
y += (opts.scale.y * opts.line_height).round() as u32;
});
}
}
self.set_button_image(key, DynamicImage::ImageRgb8(image))
}
pub fn set_button_file(
&mut self,
key: u8,
image: &str,
opts: &ImageOptions,
) -> Result<(), Error> {
self.write_button_image(key, &self.load_image(image, opts)?)
}
pub fn load_image(
&self,
image: &str,
opts: &ImageOptions,
) -> Result<DeviceImage, Error> {
let (x, y) = self.kind.image_size();
let rotate = self.kind.image_rotation();
let mirror = self.kind.image_mirror();
let image = images::load_image(
image,
x,
y,
rotate,
mirror,
opts,
self.kind.image_colour_order(),
)?;
self.convert_image(image)
}
fn translate_key_index(&self, key: u8) -> Result<u8, Error> {
if key >= self.kind.keys() {
return Err(Error::InvalidKeyIndex);
}
let mapped = match self.kind.key_direction() {
KeyDirection::LeftToRight => key,
KeyDirection::RightToLeft => {
let cols = self.kind.key_columns() as u8;
let col = key % cols;
let row = key / cols;
row * cols + cols - col
}
};
Ok(mapped)
}
pub fn write_button_image(&mut self, key: u8, image: &DeviceImage) -> Result<(), Error> {
let image = &image.data;
let key = self.translate_key_index(key)?;
let mut buf = vec![0u8; self.kind.image_report_len()];
let base = self.kind.image_base();
let hdrlen = self.kind.image_report_header_len();
match self.kind {
Kind::Original => {
self.write_image_header(&mut buf, key, 1, false, 0);
let start = hdrlen + base.len();
buf[hdrlen..start].copy_from_slice(base);
buf[start..start + 7749].copy_from_slice(&image[0..7749]);
self.device.write(&buf)?;
self.write_image_header(&mut buf, key, 2, true, 0);
buf[hdrlen..hdrlen + 7803].copy_from_slice(&image[7749..15552]);
self.device.write(&buf)?;
Ok(())
}
_ => {
let mut sequence = 0;
let mut offset = 0;
let maxdatalen = buf.len() - hdrlen;
while offset < image.len() {
let mut take = (image.len() - offset).min(maxdatalen);
let mut start = hdrlen;
if sequence == 0 && !base.is_empty() {
trace!("outputting base");
buf[start..start + base.len()].copy_from_slice(base);
take = (image.len() - offset).min(maxdatalen - base.len());
start += base.len();
}
let is_last = take == image.len() - offset;
self.write_image_header(&mut buf, key, sequence, is_last, take);
buf[start..start + take].copy_from_slice(&image[offset..offset + take]);
trace!(
"outputting image chunk [{}..{}[ in [{}..{}[, sequence {}{}",
offset,
offset + take,
start,
start + take,
sequence,
if is_last { " (last)" } else { "" },
);
self.device.write(&buf)?;
sequence += 1;
offset += take;
}
Ok(())
}
}
}
fn write_image_header(
&self,
buf: &mut [u8],
key: u8,
sequence: u16,
is_last: bool,
payload_len: usize,
) {
if self.kind.is_v2() {
buf[0] = 0x02;
buf[1] = 0x07;
buf[2] = key;
buf[3] = if is_last { 1 } else { 0 };
buf[4..6].copy_from_slice(&(payload_len as u16).to_le_bytes());
buf[6..8].copy_from_slice(&sequence.to_le_bytes());
} else {
buf[0] = 0x02;
buf[1] = 0x01;
buf[2..4].copy_from_slice(&sequence.to_le_bytes());
buf[4] = if is_last { 1 } else { 0 };
buf[5] = key;
}
}
}
pub enum TextPosition {
Absolute { x: u32, y: u32 },
}
pub struct TextOptions {
foreground: Colour,
background: Colour,
scale: Scale,
line_height: f32,
}
impl TextOptions {
pub fn new(foreground: Colour, background: Colour, scale: Scale, line_height: f32) -> Self {
TextOptions {
foreground,
background,
scale,
line_height,
}
}
}
impl Default for TextOptions {
fn default() -> Self {
TextOptions {
foreground: Colour::from_str("FFFFFF").unwrap(),
background: Colour::from_str("000000").unwrap(),
scale: Scale { x: 15.0, y: 15.0 },
line_height: 1.1,
}
}
}