alienrgb 0.1.0

A library for Alienware RGB Controller device communication
Documentation
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
/*
 * Copyright (c) 2024 Matteo Franceschini
 * All rights reserved.
 *
 * Use of this source code is governed by BSD-3-Clause-Clear
 * license that can be found in the LICENSE file
 */

//! # Alienrgb
//!  A library for Alienware RGB Controller device communication.\
//! This crate was created using [these](https://gitlab.com/OpenRGBDevelopers/OpenRGB-Wiki/-/blob/442f5d0355f445e5ee0e189e5e33e4a139406573/Device-Documentation/Alienware-AlienFX.md) informations from OpenRGB Developer Wiki and the code from [there](https://gist.github.com/Cheaterman/accd912c6886f4055f45d0594b88553c).
//! ## Example
//! ```rust
//! let elc = Elc::new();
//! let zones: Vec<Zones> = (4..16).collect();
//! let dim_command = Commands::Dim(50, zones.clone());
//! let _ = elc.execute(dim_command);
//! ```

use rusb::{DeviceHandle, GlobalContext};
use std::time::Duration;

#[cfg(feature = "serde_support")]
use serde::{Deserialize, Serialize};

/// Represent the rgb controller\
/// If the device has a kernel driver it will be detached.\
/// It will be reattached when the drop occurs.
#[derive(Debug)]
pub struct Elc {
    handle: DeviceHandle<GlobalContext>,
    has_kernel_driver: bool,
}

impl Elc {
    #![allow(clippy::new_without_default)]
    /// Create a new rgb controller handler.
    pub fn new() -> Elc {
        let handle = rusb::open_device_with_vid_pid(0x187c, 0x0550).unwrap();
        let has_kernel_driver = handle.kernel_driver_active(0).unwrap_or(false);
        if has_kernel_driver {
            handle
                .detach_kernel_driver(0)
                .expect("Can't detach the kernel driver");
        }
        handle
            .claim_interface(0)
            .expect("Can't claim the interface");
        Elc {
            handle,
            has_kernel_driver,
        }
    }
    fn send_command(&mut self, data: &impl Command) -> Result<(), rusb::Error> {
        let request_type = rusb::request_type(
            rusb::Direction::Out,
            rusb::RequestType::Class,
            rusb::Recipient::Interface,
        );
        let header = [0x03].to_vec();
        let mut payload: Vec<u8> = header.into_iter().chain(data.build()).collect();
        payload.resize(33, 0x00);
        let result = self.handle.write_control(
            request_type,
            rusb::constants::LIBUSB_REQUEST_SET_CONFIGURATION,
            0x202,
            0,
            &payload,
            Duration::from_secs(1),
        );
        if let Ok(s) = result
            && s == 33
        {
            Ok(())
        } else if let Err(e) = result {
            Err(e)
        } else {
            Err(rusb::Error::Other)
        }
    }
    fn receive_data(&mut self) -> Vec<u8> {
        let mut buf = [0; 33].to_vec();
        let request_type = rusb::request_type(
            rusb::Direction::In,
            rusb::RequestType::Class,
            rusb::Recipient::Interface,
        );
        self.handle
            .read_control(
                request_type,
                rusb::constants::LIBUSB_REQUEST_CLEAR_FEATURE,
                0x101,
                0,
                &mut buf,
                Duration::from_secs(1),
            )
            .unwrap();
        buf
    }
    /// Execute a command.\
    /// Too many sequential command could crash the device. To reboot it, a power cycle is needed.\
    /// The controller may not reboot at the first power cycle.
    pub fn execute(&mut self, command: &impl Command) -> Result<Response, rusb::Error> {
        self.send_command(command)?;
        let data = self.receive_data();
        Ok(Response::from_data(command.response_type(), data))
    }
}

impl Drop for Elc {
    fn drop(&mut self) {
        if self.has_kernel_driver {
            self.handle
                .release_interface(0)
                .expect("Can't release the interface");
            self.handle
                .attach_kernel_driver(0)
                .expect("Can't attach the kernel driver")
        }
    }
}

/// Every usable command should implement this trait
pub trait Command {
    fn build(&self) -> Vec<u8>;
    fn response_type(&self) -> ResponseType {
        ResponseType::Raw
    }
}

///All the (currently) available and implemented commands
#[derive(Debug)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub enum Commands {
    /// Gets information from the controller
    Query(QuerySub),
    /// Configure user and power animations. Expect animation subcommand and animation id
    Animation(AnimationSub, u16),
    /// Select zones to apply actions. Expect the loop flag and the zones to start the series for
    StartSeries(bool, Vec<Zone>),
    /// Apply the given actions to the zones selected by [Commands::StartSeries].\
    /// The amout of actions that can be concatenated to create an effect is unknown.
    AddActions(Vec<Action>),
    /// Control brightness of the specified zones
    /// The dim value should be between 0 (off) and 100 (full bright). Value outside this range are not tested.
    Dim(u8, Vec<Zone>),
    /// Control color of the specified zones
    Color(Rgb, Vec<Zone>),
    /// Erase the controller flash memory
    EraseFlash,
}

impl Command for Commands {
    fn build(&self) -> Vec<u8> {
        match self {
            Commands::Query(sub) => {
                let opcode = [0x20].to_vec();
                let sub = sub.build();
                opcode.into_iter().chain(sub).collect()
            }
            Commands::Animation(sub, animation_id) => {
                let opcode = if *animation_id >= 0x5b && *animation_id <= 0x60 {
                    [0x21].to_vec()
                } else {
                    [0x22].to_vec()
                };
                let sub = sub.build();
                let animation_id = animation_id.to_be_bytes().to_vec();
                opcode.into_iter().chain(sub).chain(animation_id).collect()
            }
            Commands::StartSeries(loop_flag, zones) => {
                let mut opcode = [0x23].to_vec().to_vec();
                let mut buf = vec![];
                buf.append(&mut opcode);
                let loop_flag = if *loop_flag { 1 } else { 0 };
                buf.push(loop_flag);
                let mut zones_len = (zones.len() as u16).to_be_bytes().to_vec();
                buf.append(&mut zones_len);
                for zone in zones {
                    buf.push(*zone);
                }
                buf
            }
            Commands::AddActions(actions) => {
                if actions.len() > 3 {
                    panic!("Can't add more than 3 actions at a time.");
                }
                let mut opcode = [0x24].to_vec();
                let mut buf = vec![];
                buf.append(&mut opcode);
                for action in actions {
                    buf.append(&mut action.build());
                }
                buf
            }
            Commands::Dim(level, zones) => {
                let mut opcode = [0x26].to_vec();
                let mut buf = vec![];
                buf.append(&mut opcode);
                buf.push(*level);
                let mut zones_len = (zones.len() as u16).to_be_bytes().to_vec();
                buf.append(&mut zones_len);
                for zone in zones {
                    buf.push(*zone);
                }
                buf
            }
            Commands::Color(color, zones) => {
                let mut opcode = [0x27].to_vec();
                let mut buf = vec![];
                buf.append(&mut opcode);
                buf.append(&mut color.build());
                let mut zones_len = (zones.len() as u16).to_be_bytes().to_vec();
                buf.append(&mut zones_len);
                for zone in zones {
                    buf.push(*zone);
                }
                buf
            }
            Commands::EraseFlash => {
                vec![0xFF]
            }
        }
    }
    fn response_type(&self) -> ResponseType {
        if let Self::Query(sub) = self {
            match sub {
                QuerySub::Version => ResponseType::Version,
                QuerySub::Status => ResponseType::Status,
                QuerySub::Platform => ResponseType::Platform,
                QuerySub::AnimationCount => ResponseType::AnimationCount,
            }
        } else {
            ResponseType::Raw
        }
    }
}

/// Query subcommands
#[derive(Debug)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub enum QuerySub {
    Version,
    Status,
    Platform,
    AnimationCount,
}

impl Command for QuerySub {
    fn build(&self) -> Vec<u8> {
        match self {
            QuerySub::Version => [0x00].to_vec(),
            QuerySub::Status => [0x01].to_vec(),
            QuerySub::Platform => [0x02].to_vec(),
            QuerySub::AnimationCount => [0x03].to_vec(),
        }
    }
}

/// Animation subcommands
#[derive(Debug)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub enum AnimationSub {
    StartNew,
    FinishSave,
    FinishPlay,
    Remove,
    Play,
    SetDefault,
    SetStartup,
}

impl Command for AnimationSub {
    fn build(&self) -> Vec<u8> {
        match self {
            AnimationSub::StartNew => 0x01u16.to_be_bytes().to_vec(),
            AnimationSub::FinishSave => 0x02u16.to_be_bytes().to_vec(),
            AnimationSub::FinishPlay => 0x03u16.to_be_bytes().to_vec(),
            AnimationSub::Remove => 0x04u16.to_be_bytes().to_vec(),
            AnimationSub::Play => 0x05u16.to_be_bytes().to_vec(),
            AnimationSub::SetDefault => 0x06u16.to_be_bytes().to_vec(),
            AnimationSub::SetStartup => 0x07u16.to_be_bytes().to_vec(),
        }
    }
}

/// Available light effects.\
/// As stated in the documentation, it appears that all the effect available in the Alienware Center are a combination of these.
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub enum Effects {
    Color,
    Pulse,
    Morph,
}

impl Command for Effects {
    fn build(&self) -> Vec<u8> {
        match self {
            Effects::Color => [0x00].to_vec(),
            Effects::Pulse => [0x01].to_vec(),
            Effects::Morph => [0x02].to_vec(),
        }
    }
}

/// Represent a playable action
/// ## Notes
/// The Alienware Control Center application uses 2500ms as the longest duration value, and 1000ms as the shortest.\
/// From experimentation it looks like the controller will accept any value between those two.\
/// For tempo, the longest value ACC uses is 250ms, and the shortest is 64ms, with the controller accepting any value between those.
/// The values outside of these ranges are not tested. From [OpenRGB Developer Wiki](https://gitlab.com/OpenRGBDevelopers/OpenRGB-Wiki/-/blob/442f5d0355f445e5ee0e189e5e33e4a139406573/Device-Documentation/Alienware-AlienFX.md#command-0x24-add-action).
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct Action {
    effect: Effects,
    color: Rgb,
    duration: Duration,
    tempo: Duration,
}

impl Action {
    /// Create a new action
    pub fn new(effect: Effects, color: Rgb, duration: Duration, tempo: Duration) -> Self {
        Action {
            effect,
            color,
            duration,
            tempo,
        }
    }
}

impl Command for Action {
    fn build(&self) -> Vec<u8> {
        let mut effect = self.effect.build();
        let mut color = self.color.build();
        let duration = self.duration.as_millis() as u16;
        let mut duration = duration.to_be_bytes().to_vec();
        let tempo = self.tempo.as_millis() as u16;
        let mut tempo = tempo.to_be_bytes().to_vec();
        let mut buf = vec![];
        buf.append(&mut effect);
        buf.append(&mut duration);
        buf.append(&mut tempo);
        buf.append(&mut color);
        buf
    }
}

/// Color represented as its three components
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct Rgb {
    red: u8,
    green: u8,
    blue: u8,
}

impl Rgb {
    /// Create a new color from the given red, green and blue values
    pub fn new(red: u8, green: u8, blue: u8) -> Rgb {
        Rgb { red, green, blue }
    }
}

impl Command for Rgb {
    fn build(&self) -> Vec<u8> {
        vec![self.red, self.green, self.blue]
    }
}

/// Type representing a zone on the controller.
pub type Zone = u8;

/// Represetation of the different possible responses (without data)
#[derive(Debug)]
pub enum ResponseType {
    Raw,
    Version,
    Status,
    Platform,
    AnimationCount,
}

/// Represetation of the different possible responses (with data inside)
#[derive(Debug)]
pub enum Response {
    Raw(Vec<u8>),
    Version(VersionResponse),
    Status(StatusResponse),
    Platform(PlatformResponse),
    AnimationCount(AnimationCountResponse),
}

impl Response {
    fn from_data(response_type: ResponseType, data: Vec<u8>) -> Response {
        match response_type {
            ResponseType::Raw => Response::Raw(data),
            ResponseType::Version => Response::Version(VersionResponse::from(data)),
            ResponseType::Status => Response::Status(StatusResponse::from(data)),
            ResponseType::Platform => Response::Platform(PlatformResponse::from(data)),
            ResponseType::AnimationCount => {
                Response::AnimationCount(AnimationCountResponse::from(data))
            }
        }
    }
}

/// The version of the controller software
#[derive(Debug)]
pub struct VersionResponse {
    pub major: u8,
    pub minor: u8,
    pub revision: u8,
}

impl From<Vec<u8>> for VersionResponse {
    fn from(value: Vec<u8>) -> Self {
        let value: Vec<u8> = value.into_iter().skip(3).collect();
        VersionResponse {
            major: value[0],
            minor: value[1],
            revision: value[2],
        }
    }
}

/// Status of the controller
#[derive(Debug)]
pub enum StatusResponse {
    OK,
    Err,
    Unknown(u8),
}

impl From<Vec<u8>> for StatusResponse {
    fn from(value: Vec<u8>) -> Self {
        let value: Vec<u8> = value.into_iter().skip(3).collect();
        let value = value[0];
        match value {
            0x00 => StatusResponse::OK,
            0x01 => StatusResponse::Err,
            v => StatusResponse::Unknown(v),
        }
    }
}

/// Represent platform id and zone count
#[derive(Debug)]
pub struct PlatformResponse {
    pub platform_id: u16,
    pub zone_count: u8,
}

impl From<Vec<u8>> for PlatformResponse {
    fn from(value: Vec<u8>) -> Self {
        let value: Vec<u8> = value.into_iter().skip(3).collect();
        let platform_id = [value[0], value[1]];
        let platform_id = u16::from_be_bytes(platform_id);
        let zone_count = value[2];
        PlatformResponse {
            platform_id,
            zone_count,
        }
    }
}

/// Represent the count of possible animation and the last played animation id
#[derive(Debug)]
pub struct AnimationCountResponse {
    pub animation_count: u16,
    pub last_animation_id: u16,
}

impl From<Vec<u8>> for AnimationCountResponse {
    fn from(value: Vec<u8>) -> Self {
        let value: Vec<u8> = value.into_iter().skip(3).collect();
        let animation_count = [value[0], value[1]];
        let animation_count = u16::from_be_bytes(animation_count);
        let last_animation_id = [value[0], value[1]];
        let last_animation_id = u16::from_be_bytes(last_animation_id);
        AnimationCountResponse {
            animation_count,
            last_animation_id,
        }
    }
}

/// Animations id, except for the power ones.\
/// Used to determine when to play an animation.
#[derive(Debug)]
pub enum AnimationId {
    Bootup,
    Keyboard,
    Ephimeral,
}

impl AnimationId {
    /// Get the animation code
    pub const fn build_animation(&self) -> u16 {
        match self {
            AnimationId::Bootup => 0x0008,
            AnimationId::Keyboard => 0x0061,
            AnimationId::Ephimeral => 0xFFFF,
        }
    }
}

/// Power animations id.\
/// Used to determine in what power situation play the animation.
#[derive(Debug)]
pub enum PowerAnimationId {
    AcSleep,
    AcCharged,
    AcCharging,
    BatterySleep,
    BatteryOn,
    BatteryCritical,
}

impl PowerAnimationId {
    /// Get the animation code
    pub const fn build_animation(&self) -> u16 {
        match self {
            PowerAnimationId::AcSleep => 0x005B,
            PowerAnimationId::AcCharged => 0x005C,
            PowerAnimationId::AcCharging => 0x005D,
            PowerAnimationId::BatterySleep => 0x005E,
            PowerAnimationId::BatteryOn => 0x005F,
            PowerAnimationId::BatteryCritical => 0x0060,
        }
    }
}
/// Useful struct for serialization/deserialization of instruction files\
/// Available only with `serde_support` enabled
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
#[cfg(feature = "serde_support")]
pub struct Config {
    pub commands: Vec<Commands>,
}

#[cfg(feature = "serde_support")]
impl Config {
    pub fn new(commands: Vec<Commands>) -> Self {
        Self { commands }
    }
}