dualsense-rs 0.4.0

Rust programmatic wrapper over HID messages sent and received by the PS5 DualSense controller.
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
use hidapi::{HidApi, HidDevice};
use std::{
    collections::HashMap,
    sync::{Arc, Mutex},
    thread::{self, sleep, JoinHandle},
    time::Duration,
};

use crate::properties::{
    dpad::DPad,
    property::{OutputProperty, Property},
    symbols::Symbols,
    valuetype::ValueType,
};

const VENDOR_ID: u16 = 1356;
const PRODUCT_ID: u16 = 3302;
const PACKET_SIZE: usize = 64;

type CBFunction = Box<dyn Fn(ValueType) + Send>;

/// Main struct used for interacting with the controller. Everything is thread safe to allow reading, writing,
/// setting callbacks after the `Self::run` method is called and to send data.
pub struct DualSense {
    device: Arc<Mutex<HidDevice>>,
    callbacks: Arc<Mutex<HashMap<Property, Vec<CBFunction>>>>,
    callback_cache: Arc<Mutex<HashMap<Property, ValueType>>>,
    output_cache: Arc<Mutex<HashMap<OutputProperty, u8>>>,
}

impl DualSense {
    pub fn new() -> Self {
        let api = HidApi::new().unwrap();
        let device = api.open(VENDOR_ID, PRODUCT_ID).unwrap();
        Self {
            device: Arc::new(Mutex::new(device)),
            callbacks: Arc::new(Mutex::new(HashMap::new())),
            callback_cache: Arc::new(Mutex::new(HashMap::new())),
            output_cache: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    /// Start listening to HID packets from the controller
    pub fn run(&mut self) -> JoinHandle<()> {
        let device = Arc::clone(&self.device);
        let callbacks = Arc::clone(&self.callbacks);
        let cache = Arc::clone(&self.callback_cache);
        let output_cache = Arc::clone(&self.output_cache);

        thread::spawn(move || loop {
            let mut buf = [0u8; PACKET_SIZE];
            let bytes_read = device.lock().unwrap().read(&mut buf);
            match bytes_read {
                Ok(PACKET_SIZE) => {}
                Ok(actual_size) => {
                    eprintln!("Packet size mismatch, ignoring values ({actual_size})");
                    continue;
                }
                Err(e) => {
                    eprintln!("Error on read, ignoring values {e}");
                    continue;
                }
            }

            Self::packet_received(&callbacks.lock().unwrap(), &mut cache.lock().unwrap(), &buf);
            Self::write(&device.lock().unwrap(), &output_cache.lock().unwrap());
            sleep(Duration::from_millis(50));
        })
    }

    pub fn set_light_red(&mut self, value: u8) {
        self.output_cache
            .lock()
            .unwrap()
            .insert(OutputProperty::Red, value);
    }

    pub fn set_light_green(&mut self, value: u8) {
        self.output_cache
            .lock()
            .unwrap()
            .insert(OutputProperty::Green, value);
    }

    pub fn set_light_blue(&mut self, value: u8) {
        self.output_cache
            .lock()
            .unwrap()
            .insert(OutputProperty::Blue, value);
    }
    /// Provide a callback to be called when the left stick's x coordinate changes
    /// left: 0x00, right: 0xFF
    pub fn on_left_pad_x_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(u8) + Send + Sync,
    {
        self.register_u8(Property::LeftPadX, cb);
    }

    /// Provide a callback to be called when the left stick's y coordinate changes
    /// up: 0x00, down: 0xFF
    pub fn on_left_pad_y_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(u8) + Send + Sync,
    {
        self.register_u8(Property::LeftPadY, cb);
    }

    /// Provide a callback to be called when the right stick's x coordinate changes
    pub fn on_right_pad_x_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(u8) + Send + Sync,
    {
        self.register_u8(Property::RightPadX, cb);
    }

    /// Provide a callback to be called when the right stick's y coordinate changes
    pub fn on_right_pad_y_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(u8) + Send + Sync,
    {
        self.register_u8(Property::RightPadY, cb);
    }

    /// Provide a callback to be called when the L1 button is pressed
    pub fn on_l1_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(bool) + Send + Sync,
    {
        self.register_bool(Property::L1, cb);
    }

    /// Provide a callback to be called when the R1 button is pressed
    pub fn on_r1_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(bool) + Send + Sync,
    {
        self.register_bool(Property::R1, cb);
    }

    /// Provide a callback to be called when the L2 button value changes
    pub fn on_l2_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(u8) + Send + Sync,
    {
        self.register_u8(Property::L2, cb);
    }

    /// Provide a callback to be called when the R2 button value changes
    pub fn on_r2_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(u8) + Send + Sync,
    {
        self.register_u8(Property::R2, cb);
    }

    /// Provide a callback to be called when the L3 button is pressed
    pub fn on_l3_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(bool) + Send + Sync,
    {
        self.register_bool(Property::L3, cb);
    }

    /// Provide a callback to be called when the R3 button is pressed
    pub fn on_r3_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(bool) + Send + Sync,
    {
        self.register_bool(Property::R3, cb);
    }

    /// Provide a callback to be called when the options button is pressed
    pub fn on_share_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(bool) + Send + Sync,
    {
        self.register_bool(Property::Share, cb);
    }

    /// Provide a callback to be called when the options button is pressed
    pub fn on_options_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(bool) + Send + Sync,
    {
        self.register_bool(Property::Options, cb);
    }

    /// Provide a callback to be called when any dpad button is pressed
    pub fn on_dpad_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(DPad) + Send + Sync,
    {
        self.register_dpad(Property::DPad, cb);
    }

    /// Provide a callback to be called when any symbol button is pressed
    pub fn on_symbols_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(Symbols) + Send + Sync,
    {
        self.register_symbols(Property::Symbols, cb);
    }

    /// Provide a callback to be called when the mute button is pressed
    pub fn on_mute_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(bool) + Send + Sync,
    {
        self.register_bool(Property::Mute, cb);
    }

    /// Provide a callback to be called when the touchpad is pressed
    pub fn on_touchpad_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(bool) + Send + Sync,
    {
        self.register_bool(Property::TouchPad, cb);
    }

    /// Provide a callback to be called when the playstation button is pressed
    pub fn on_playstation_pressed<F>(&mut self, cb: &'static F)
    where
        F: Fn(bool) + Send + Sync,
    {
        self.register_bool(Property::PlayStation, cb);
    }

    /// Provide a callback to be called when the gyroscope X axis is changed
    pub fn on_gyro_x_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(i16) + Send + Sync,
    {
        self.register_i16(Property::GyroscopeX, cb);
    }

    /// Provide a callback to be called when the gyroscope Y axis is changed
    pub fn on_gyro_y_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(i16) + Send + Sync,
    {
        self.register_i16(Property::GyroscopeY, cb);
    }

    /// Provide a callback to be called when the gyroscope Z axis is changed
    pub fn on_gyro_z_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(i16) + Send + Sync,
    {
        self.register_i16(Property::GyroscopeZ, cb);
    }

    /// Provide a callback to be called when the acceleration X axis is changed
    pub fn on_accel_x_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(i16) + Send + Sync,
    {
        self.register_i16(Property::AccelerationX, cb);
    }

    /// Provide a callback to be called when the acceleration Y axis is changed
    pub fn on_accel_y_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(i16) + Send + Sync,
    {
        self.register_i16(Property::AccelerationY, cb);
    }

    /// Provide a callback to be called when the acceleration Z axis is changed
    pub fn on_accel_z_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(i16) + Send + Sync,
    {
        self.register_i16(Property::AccelerationZ, cb);
    }

    /// Provide a callback to be called when the touchpad is touched
    pub fn on_touchpad1_pressed<F>(&mut self, cb: &'static F)
    where
        F: Fn(bool) + Send + Sync,
    {
        self.register_bool(Property::TouchPadFinger1Active, cb);
    }

    /// Provide a callback to be called when the touchpad is touched with the second finger
    pub fn on_touchpoint2_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(bool) + Send + Sync,
    {
        self.register_bool(Property::TouchPadFinger2Active, cb);
    }

    /// Provide a callback to be called when the touchpad ID changes
    pub fn on_touchpoint1_id_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(u8) + Send + Sync,
    {
        self.register_u8(Property::TouchPad1Id, cb);
    }
    /// Provide a callback to be called when the touchpad ID changes
    pub fn on_touchpoint2_id_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(u8) + Send + Sync,
    {
        self.register_u8(Property::TouchPad2Id, cb);
    }
    /// Provide a callback to be called when the touchpad input from the first finger
    /// on the X axis is changed
    pub fn on_touchpad1_x_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(u16) + Send + Sync,
    {
        self.register_u16(Property::TouchPad1X, cb);
    }

    /// Provide a callback to be called when the touchpad input from the first finger
    /// on the Y axis is changed
    pub fn on_touchpad1_y_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(u16) + Send + Sync,
    {
        self.register_u16(Property::TouchPad1Y, cb);
    }

    /// Provide a callback to be called when the touchpad input from the second finger
    /// on the X axis is changed
    pub fn on_touchpoint2_x_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(u16) + Send + Sync,
    {
        self.register_u16(Property::TouchPad2X, cb);
    }

    /// Provide a callback to be called when the touchpad input from the second finger
    /// on the Y axis is changed
    pub fn on_touchpoint2_y_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(u16) + Send + Sync,
    {
        self.register_u16(Property::TouchPad2Y, cb);
    }

    /// Provide a callback to be called when the left stick force trigger is active
    pub fn on_left_force_enabled<F>(&mut self, cb: &'static F)
    where
        F: Fn(bool) + Send + Sync,
    {
        self.register_bool(Property::L2FeedbackOn, cb);
    }

    /// Provide a callback to be called when the right stick force trigger is active
    pub fn on_right_force_enabled<F>(&mut self, cb: &'static F)
    where
        F: Fn(bool) + Send + Sync,
    {
        self.register_bool(Property::R2FeedbackOn, cb);
    }

    /// Provide a callback to be called when the left stick force amount changed
    pub fn on_left_force_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(u8) + Send + Sync,
    {
        self.register_u8(Property::L2FeedbackValue, cb);
    }

    /// Provide a callback to be called when the right stick force trigger is active
    pub fn on_right_force_changed<F>(&mut self, cb: &'static F)
    where
        F: Fn(u8) + Send + Sync,
    {
        self.register_u8(Property::R2FeedbackValue, cb);
    }

    fn register_u8<F>(&mut self, prop: Property, cb: &'static F)
    where
        F: Fn(u8) + Send + Sync,
    {
        self.callbacks
            .lock()
            .unwrap()
            .entry(prop)
            .or_default()
            .push(Box::new(move |x| cb(x.to_u8())));
    }

    fn register_u16<F>(&mut self, prop: Property, cb: &'static F)
    where
        F: Fn(u16) + Send + Sync,
    {
        self.callbacks
            .lock()
            .unwrap()
            .entry(prop)
            .or_default()
            .push(Box::new(move |x| cb(x.to_u16())));
    }

    fn register_i16<F>(&mut self, prop: Property, cb: &'static F)
    where
        F: Fn(i16) + Send + Sync,
    {
        self.callbacks
            .lock()
            .unwrap()
            .entry(prop)
            .or_default()
            .push(Box::new(move |x| cb(x.to_i16())));
    }

    fn register_dpad<F>(&mut self, prop: Property, cb: &'static F)
    where
        F: Fn(DPad) + Send + Sync,
    {
        self.callbacks
            .lock()
            .unwrap()
            .entry(prop)
            .or_default()
            .push(Box::new(move |x| cb(x.to_dpad())));
    }

    fn register_symbols<F>(&mut self, prop: Property, cb: &'static F)
    where
        F: Fn(Symbols) + Send + Sync,
    {
        self.callbacks
            .lock()
            .unwrap()
            .entry(prop)
            .or_default()
            .push(Box::new(move |x| cb(x.to_symbol())));
    }

    fn register_bool<F>(&mut self, prop: Property, cb: &'static F)
    where
        F: Fn(bool) + Send + Sync,
    {
        self.callbacks
            .lock()
            .unwrap()
            .entry(prop)
            .or_default()
            .push(Box::new(move |x| cb(x.to_bool())));
    }

    fn packet_received(
        callbacks: &HashMap<Property, Vec<CBFunction>>,
        cache: &mut HashMap<Property, ValueType>,
        data: &[u8; 64],
    ) {
        callbacks.iter().for_each(|(prop, cbs)| {
            let new_val = Self::extract_bytes(prop, data);
            let mut update = false;

            match cache.get_mut(prop) {
                Some(old_val) if old_val != &new_val => {
                    update = true;
                }
                None => {
                    update = true;
                }
                _ => {}
            }
            if update {
                cache.insert(*prop, new_val);
                cbs.iter().for_each(|cb| cb(new_val));
            }
        })
    }

    fn write(device: &HidDevice, output_cache: &HashMap<OutputProperty, u8>) {
        let mut data = [0_u8; 48];
        data[0] = 0x02;
        data[1] = 0xFF;
        data[2] = 0xF7;
        data[40] = 0x02;
        data[41] = 0x02;

        for (property, value) in output_cache.iter() {
            data[property.byte()] = *value;
        }
        device.write(&data).ok();
    }

    #[allow(dead_code)]
    fn debug_print_packet(data: &[u8; PACKET_SIZE]) {
        data.chunks(8).for_each(|w| {
            for b in w {
                print!("{:#04x} ", b)
            }
            println!();
        });
        println!()
    }

    fn extract_bytes(prop: &Property, data: &[u8; 64]) -> ValueType {
        if prop.offset().bits == (0..8) {
            prop.convert(&data.as_slice()[prop.offset().bytes])
        } else if prop.offset().bytes.count() == 1 {
            let mut out = 0u8;
            let byte = prop.offset().bytes.start;
            let val = data.as_slice()[byte];

            for i in prop.offset().bits {
                let offset = i - prop.offset().bits.start;
                let current_bit = (val & (1 << i)) >> i;
                out |= current_bit << offset;
            }
            prop.convert(&[out])
        } else {
            todo!()
        }
    }
}

impl Default for DualSense {
    fn default() -> Self {
        DualSense::new()
    }
}