buttplug_server_device_config 10.0.2

Buttplug Intimate Hardware Control Library - Server Device Config Library
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
// Buttplug Rust Source Code File - See https://buttplug.io for more info.
//
// Copyright 2016-2026 Nonpolynomial Labs LLC. All rights reserved.
//
// Licensed under the BSD 3-Clause license. See LICENSE file in the project root
// for full license information.

use super::Endpoint;
use getset::{Getters, MutGetters, Setters};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use uuid::Uuid;

#[derive(Serialize, Deserialize, Debug, Clone, Getters, MutGetters, Setters, Eq)]
#[getset(get = "pub", set = "pub", get_mut = "pub(crate)")]
pub struct BluetoothLEManufacturerData {
  company: u16,
  data: Option<Vec<u8>>,
}

impl BluetoothLEManufacturerData {
  pub fn new(company: u16, data: &Option<Vec<u8>>) -> Self {
    Self {
      company,
      data: data.clone(),
    }
  }
}

impl PartialEq for BluetoothLEManufacturerData {
  fn eq(&self, other: &Self) -> bool {
    if self.company != *other.company() {
      return false;
    }

    // Only the deserialized device config can have none has a data value. If it does, that means
    // all we care about is the company value, at which point we can return true here.
    if self.data.is_none() || other.data.is_none() {
      return true;
    }

    let data = self.data().as_ref().expect("Already checked existence");
    let other_data = other.data().as_ref().expect("Already checked existence");

    if data.len() == other_data.len() {
      if *data == *other_data {
        return true;
      }
      return false;
    }

    // If our data lengths are different, see if one is a subsequence of the other.
    //
    // Since we don't have the information to know if either self or other is what was loaded from
    // the JSON file, we have to blindly guess for needle and haystack here based on length. This
    // means if manufacturer data comes back from a device shorter than the data the device config
    // expects, we could have a false match. This needs to be contexualized but that would require a
    // large device config system rewrite at the moment, so we'll just live with the bug for now.
    let needle = if data.len() < other_data.len() {
      data
    } else {
      other_data
    };
    let mut haystack = if data.len() > other_data.len() {
      data.as_slice()
    } else {
      other_data.as_slice()
    };
    while !haystack.is_empty() {
      if haystack.starts_with(needle) {
        return true;
      }
      haystack = &haystack[1..];
    }

    false
  }
}

/// Specifier for Bluetooth LE Devices
///
/// Used by protocols for identifying bluetooth devices via their advertisements, as well as
/// defining the services and characteristics they are expected to have.
#[derive(Serialize, Deserialize, Debug, Clone, Getters, MutGetters, Setters)]
#[getset(get = "pub", set = "pub", get_mut = "pub(crate)")]
pub struct BluetoothLESpecifier {
  /// Set of expected advertised names for this device.
  names: HashSet<String>,
  /// Array of possible manufacturer data values.
  #[serde(default)]
  manufacturer_data: Vec<BluetoothLEManufacturerData>,
  /// Set of expected advertised services for this device.
  #[serde(default)]
  advertised_services: HashSet<Uuid>,
  /// Services we expect the device may have. More services may be listed in a specifier than any
  /// one device may have, but we expect at least one to be matched by a device in order to consider
  /// the device part of the protocol that has this specifier.
  services: HashMap<Uuid, HashMap<Endpoint, Uuid>>,
}

impl PartialEq for BluetoothLESpecifier {
  fn eq(&self, other: &Self) -> bool {
    // If names or manufacturer data are found, use those automatically.
    if self.names.intersection(&other.names).count() > 0 {
      return true;
    }
    // Otherwise, try wildcarded names.
    for name in &self.names {
      for other_name in &other.names {
        let compare_name: &String;
        let mut wildcard: String;
        if name.ends_with('*') {
          wildcard = name.clone();
          compare_name = other_name;
        } else if other_name.ends_with('*') {
          wildcard = other_name.clone();
          compare_name = name;
        } else {
          continue;
        }
        // Remove asterisk from the end of the wildcard
        wildcard.pop();
        if compare_name.starts_with(&wildcard) {
          return true;
        }
      }
    }

    if !self.manufacturer_data.is_empty() && !other.manufacturer_data.is_empty() {
      for data in &self.manufacturer_data {
        if other.manufacturer_data.contains(data) {
          return true;
        }
      }
    }

    if self
      .advertised_services
      .intersection(&other.advertised_services)
      .count()
      > 0
    {
      return true;
    }

    false
  }
}

impl BluetoothLESpecifier {
  pub fn new(
    names: HashSet<String>,
    manufacturer_data: Vec<BluetoothLEManufacturerData>,
    advertised_services: HashSet<Uuid>,
    services: HashMap<Uuid, HashMap<Endpoint, Uuid>>,
  ) -> Self {
    Self {
      names,
      manufacturer_data,
      advertised_services,
      services,
    }
  }

  /// Creates a specifier from a BLE device advertisement.
  pub fn new_from_device(
    name: &str,
    manufacturer_data: &HashMap<u16, Vec<u8>>,
    advertised_services: &[Uuid],
  ) -> BluetoothLESpecifier {
    let mut name_set = HashSet::new();
    name_set.insert(name.to_string());
    let mut data_vec = vec![];
    for (company, data) in manufacturer_data.iter() {
      data_vec.push(BluetoothLEManufacturerData::new(
        *company,
        &Some(data.clone()),
      ));
    }
    let service_set = HashSet::from_iter(advertised_services.iter().copied());
    BluetoothLESpecifier {
      names: name_set,
      manufacturer_data: data_vec,
      advertised_services: service_set,
      services: HashMap::new(),
    }
  }

  /// Merge with another BLE specifier, used when loading user configs that extend a protocol
  /// definition.
  pub fn merge(&mut self, other: BluetoothLESpecifier) {
    // Add any new names.
    self.names = self.names.union(&other.names).cloned().collect();
    // Add new services, overwrite matching services.
    self.advertised_services = self
      .advertised_services
      .union(&other.advertised_services)
      .cloned()
      .collect();
    self.services.extend(other.services);
  }
}

/// Specifier for [Lovense Connect
/// Service](crate::server::device::communication_manager::lovense_connect_service) devices
///
/// Network based services, has no attributes because the [Lovense Connect
/// Service](crate::server::device::communication_manager::lovense_connect_service) device communication manager
/// handles all device discovery and identification itself.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct LovenseConnectServiceSpecifier {
  // Needed for proper deserialization, but clippy will complain.
  #[allow(dead_code)]
  exists: bool,
}

impl Default for LovenseConnectServiceSpecifier {
  fn default() -> Self {
    Self { exists: true }
  }
}

impl PartialEq for LovenseConnectServiceSpecifier {
  fn eq(&self, _other: &Self) -> bool {
    true
  }
}

/// Specifier for [XInput](crate::server::device::communication_manager::xinput) devices
///
/// Network based services, has no attributes because the
/// [XInput](crate::server::device::communication_manager::xinput) device communication manager handles all device
/// discovery and identification itself.
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct XInputSpecifier {
  // Needed for deserialziation but unused.
  #[allow(dead_code)]
  exists: bool,
}

impl Default for XInputSpecifier {
  fn default() -> Self {
    Self { exists: true }
  }
}

impl PartialEq for XInputSpecifier {
  fn eq(&self, _other: &Self) -> bool {
    true
  }
}

#[derive(
  Serialize, Deserialize, Debug, PartialEq, Eq, Clone, Copy, Getters, Setters, MutGetters,
)]
pub struct VIDPIDPair {
  vendor_id: u16,
  product_id: u16,
}

/// Specifier for HID (USB, Bluetooth) devices
///
/// Handles devices managed by the operating system's HID manager.
#[derive(Serialize, Deserialize, Debug, Eq, Clone, Getters, Setters, MutGetters)]
#[getset(get = "pub", set = "pub", get_mut = "pub(crate)")]
pub struct VIDPIDSpecifier {
  pairs: Vec<VIDPIDPair>,
}

impl VIDPIDSpecifier {
  pub fn new(vendor_id: u16, product_id: u16) -> Self {
    Self {
      pairs: vec![VIDPIDPair {
        vendor_id,
        product_id,
      }],
    }
  }
}

impl PartialEq for VIDPIDSpecifier {
  fn eq(&self, other: &Self) -> bool {
    for pair in &self.pairs {
      for other_pair in &other.pairs {
        if *pair == *other_pair {
          return true;
        }
      }
    }
    false
  }
}

/// Specifier for Serial devices
///
/// Handles serial port device identification (via port names) and configuration.
#[derive(Serialize, Deserialize, Debug, Clone, Default, Getters, Setters, MutGetters)]
#[getset(get = "pub", set = "pub", get_mut = "pub(crate)")]
pub struct SerialSpecifier {
  baud_rate: u32,
  data_bits: u8,
  stop_bits: u8,
  parity: char,
  port: String,
}

impl SerialSpecifier {
  pub fn new(port: &str, baud_rate: u32, data_bits: u8, stop_bits: u8, parity: char) -> Self {
    Self {
      port: port.to_owned(),
      baud_rate,
      data_bits,
      stop_bits,
      parity,
    }
  }

  /// Given a serial port name (the only identifier we have for this type of device), create a
  /// specifier instance.
  pub fn new_from_name(port: &str) -> Self {
    Self {
      port: port.to_owned(),
      ..Default::default()
    }
  }
}

impl PartialEq for SerialSpecifier {
  fn eq(&self, other: &Self) -> bool {
    if *self.port == *other.port {
      return true;
    }
    false
  }
}

/// Specifier for Websocket Device Manager devices
///
/// The websocket device manager is a network based manager, so we have no info other than possibly
/// a device name that is provided as part of the connection handshake.
#[derive(Serialize, Deserialize, Debug, Clone, Default, Getters, Setters, MutGetters)]
#[getset(get = "pub", set = "pub")]
pub struct WebsocketSpecifier {
  name: String,
}

impl PartialEq for WebsocketSpecifier {
  fn eq(&self, other: &Self) -> bool {
    if self.name == other.name {
      return true;
    }
    false
  }
}

impl WebsocketSpecifier {
  pub fn new(name: &str) -> WebsocketSpecifier {
    Self {
      name: name.to_owned(),
    }
  }
}

/// Enum that covers all types of communication specifiers.
///
/// Allows generalization of specifiers to handle checking for equality. Used for testing newly discovered
/// devices against the list of known devices for a protocol.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum ProtocolCommunicationSpecifier {
  #[serde(rename = "btle")]
  BluetoothLE(BluetoothLESpecifier),
  #[serde(rename = "hid")]
  HID(VIDPIDSpecifier),
  #[serde(rename = "usb")]
  USB(VIDPIDSpecifier),
  #[serde(rename = "serial")]
  Serial(SerialSpecifier),
  #[serde(rename = "xinput")]
  XInput(XInputSpecifier),
  #[serde(rename = "lovense_connect_service")]
  LovenseConnectService(LovenseConnectServiceSpecifier),
  #[serde(rename = "websocket")]
  Websocket(WebsocketSpecifier),
}

impl PartialEq for ProtocolCommunicationSpecifier {
  fn eq(&self, other: &ProtocolCommunicationSpecifier) -> bool {
    use ProtocolCommunicationSpecifier::*;
    match (self, other) {
      (USB(self_spec), USB(other_spec)) => self_spec == other_spec,
      (Serial(self_spec), Serial(other_spec)) => self_spec == other_spec,
      (BluetoothLE(self_spec), BluetoothLE(other_spec)) => self_spec == other_spec,
      (HID(self_spec), HID(other_spec)) => self_spec == other_spec,
      (XInput(self_spec), XInput(other_spec)) => self_spec == other_spec,
      (Websocket(self_spec), Websocket(other_spec)) => self_spec == other_spec,
      (LovenseConnectService(self_spec), LovenseConnectService(other_spec)) => {
        self_spec == other_spec
      }
      _ => false,
    }
  }
}

impl Eq for ProtocolCommunicationSpecifier {
}