buttplug_server_device_config 11.0.0

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
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
// 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 buttplug_core::errors::ButtplugDeviceError;
use dashmap::DashMap;
use getset::Getters;
use std::{
  collections::HashMap,
  fmt::{self, Debug},
  sync::Arc,
  sync::RwLock,
};
use uuid::Uuid;

use crate::{
  BaseDeviceIdentifier,
  ButtplugDeviceConfigError,
  ProtocolCommunicationSpecifier,
  ServerDeviceDefinition,
  ServerDeviceDefinitionBuilder,
  SimulatedDeviceConfigEntry,
  UserDeviceIdentifier,
  device_config_file::{SimulatedDeviceArchetype, SimulatedDeviceFeatureSummary},
};

#[derive(Default, Clone)]
pub struct DeviceConfigurationManagerBuilder {
  base_communication_specifiers: HashMap<String, Vec<ProtocolCommunicationSpecifier>>,
  user_communication_specifiers: DashMap<String, Vec<ProtocolCommunicationSpecifier>>,
  base_device_definitions: HashMap<BaseDeviceIdentifier, Arc<ServerDeviceDefinition>>,
  user_device_definitions: DashMap<UserDeviceIdentifier, ServerDeviceDefinition>,
  simulated_devices: Vec<SimulatedDeviceConfigEntry>,
}

impl DeviceConfigurationManagerBuilder {
  pub fn communication_specifier(
    &mut self,
    protocol_name: &str,
    specifier: &[ProtocolCommunicationSpecifier],
  ) -> &mut Self {
    self
      .base_communication_specifiers
      .entry(protocol_name.to_owned())
      .or_default()
      .extend(specifier.iter().cloned());
    self
  }

  pub fn base_device_definition(
    &mut self,
    identifier: &BaseDeviceIdentifier,
    definition: Arc<ServerDeviceDefinition>,
  ) -> &mut Self {
    self
      .base_device_definitions
      .insert(identifier.clone(), definition);
    self
  }

  pub fn user_communication_specifier(
    &mut self,
    protocol_name: &str,
    specifier: &[ProtocolCommunicationSpecifier],
  ) -> &mut Self {
    self
      .user_communication_specifiers
      .entry(protocol_name.to_owned())
      .or_default()
      .extend(specifier.iter().cloned());
    self
  }

  pub fn user_device_definition(
    &mut self,
    identifier: &UserDeviceIdentifier,
    device_definition: &ServerDeviceDefinition,
  ) -> Result<&mut Self, ButtplugDeviceConfigError> {
    if self
      .base_device_definitions
      .iter()
      .any(|(_, x)| x.id() == device_definition.base_id().unwrap_or_default())
    {
      self
        .user_device_definitions
        .insert(identifier.clone(), device_definition.clone());
      Ok(self)
    } else {
      error!(
        "Cannot find protocol with base id {:?} for user id {}",
        device_definition.base_id(),
        device_definition.id()
      );
      Err(ButtplugDeviceConfigError::BaseIdNotFound(
        device_definition.id(),
      ))
    }
  }

  pub fn simulated_devices(&mut self, devices: Vec<SimulatedDeviceConfigEntry>) -> &mut Self {
    self.simulated_devices = devices;
    self
  }

  pub fn add_simulated_devices(&mut self, devices: Vec<SimulatedDeviceConfigEntry>) -> &mut Self {
    self.simulated_devices.extend(devices);
    self
  }

  pub fn finish(&mut self) -> Result<DeviceConfigurationManager, ButtplugDeviceError> {
    // Build and validate the protocol attributes tree.
    let mut attribute_tree_map = HashMap::new();

    // Add all the defaults first, they won't have parent attributes.
    for (ident, attr) in &self.base_device_definitions {
      attribute_tree_map.insert(ident.clone(), attr.clone());
    }

    let user_attribute_tree_map = DashMap::new();
    // Finally, add in user configurations, which will have an address.
    for kv in &self.user_device_definitions {
      user_attribute_tree_map.insert(kv.key().clone(), kv.value().clone());
    }

    // Validate simulated devices
    if !self.simulated_devices.is_empty() {
      let valid_archetypes: std::collections::HashSet<String> = self
        .base_communication_specifiers
        .get("simulated")
        .into_iter()
        .flat_map(|specifiers| specifiers.iter())
        .filter_map(|spec| {
          if let ProtocolCommunicationSpecifier::Simulated(sim) = spec {
            Some(sim.names().iter().cloned())
          } else {
            None
          }
        })
        .flatten()
        .collect();

      let mut seen_addresses = std::collections::HashSet::new();
      for device in &self.simulated_devices {
        if !valid_archetypes.contains(&device.identifier) {
          return Err(ButtplugDeviceError::DeviceConfigurationError(format!(
            "Invalid simulated device archetype '{}'. Valid archetypes: {:?}",
            device.identifier, valid_archetypes
          )));
        }
        if !seen_addresses.insert(&device.address) {
          return Err(ButtplugDeviceError::DeviceConfigurationError(format!(
            "Duplicate simulated device address '{}' for archetype '{}'",
            device.address, device.identifier
          )));
        }
      }
    }

    Ok(DeviceConfigurationManager {
      base_communication_specifiers: self.base_communication_specifiers.clone(),
      user_communication_specifiers: self.user_communication_specifiers.clone(),
      base_device_definitions: attribute_tree_map,
      user_device_definitions: user_attribute_tree_map,
      simulated_devices_store: RwLock::new(self.simulated_devices.clone()),
      //protocol_map,
    })
  }
}

/// Correlates information about protocols and which devices they support.
///
/// The [DeviceConfigurationManager] handles stores information about which device protocols the
/// library supports, as well as which devices can use those protocols. When a
/// [DeviceCommunicationManager](crate::server::device::communication_manager) finds a device during scanning,
/// device information is given to the [DeviceConfigurationManager] to decide whether Buttplug
/// should try to connect to and communicate with the device.
///
/// Assuming the device is supported by the library, the [DeviceConfigurationManager] also stores
/// information about what commands can be sent to the device (Vibrate, Rotate, etc...), and the
/// parameters for those commands (number of power levels, stroke distances, etc...).
#[derive(Getters)]
#[getset(get = "pub(crate)")]
pub struct DeviceConfigurationManager {
  /// Communication specifiers from the base device config, mapped from protocol name to vector of
  /// specifiers. Should not change/update during a session.
  #[getset(get = "pub")]
  base_communication_specifiers: HashMap<String, Vec<ProtocolCommunicationSpecifier>>,
  /// Device definitions from the base device config. Should not change/update during a session.
  #[getset(get = "pub")]
  base_device_definitions: HashMap<BaseDeviceIdentifier, Arc<ServerDeviceDefinition>>,
  /// Communication specifiers provided by the user, mapped from protocol name to vector of
  /// specifiers. Loaded at session start, may change over life of session.
  #[getset(get = "pub")]
  user_communication_specifiers: DashMap<String, Vec<ProtocolCommunicationSpecifier>>,
  /// Device definitions from the user device config. Loaded at session start, may change over life
  /// of session.
  #[getset(get = "pub")]
  user_device_definitions: DashMap<UserDeviceIdentifier, ServerDeviceDefinition>,
  /// Simulated device configurations from the user config.
  simulated_devices_store: RwLock<Vec<SimulatedDeviceConfigEntry>>,
}

impl Debug for DeviceConfigurationManager {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("DeviceConfigurationManager").finish()
  }
}

impl Default for DeviceConfigurationManager {
  fn default() -> Self {
    // Unwrap allowed here because we assume our built in device config will
    // always work. System won't pass tests or possibly even build otherwise.
    DeviceConfigurationManagerBuilder::default()
      .finish()
      .expect("Default creation of a DCM should always work.")
  }
}

impl DeviceConfigurationManager {
  /// Construct a `DeviceConfigurationManager` directly from pre-built maps, bypassing the
  /// builder and its validation logic.
  ///
  /// **Use with caution**: the builder (`DeviceConfigurationManagerBuilder::finish`) performs
  /// validation and reconciliation steps that this constructor skips. Prefer the builder for
  /// any config loaded from JSON. This path exists for embedded or test contexts that assemble
  /// their own protocol/identifier maps and cannot or do not want to go through the JSON config
  /// pipeline. If you find yourself calling this in non-embedded production code, that is
  /// probably a sign the builder API needs extension rather than a bypass.
  pub fn new(
    base_communication_specifiers: HashMap<String, Vec<ProtocolCommunicationSpecifier>>,
    base_device_definitions: HashMap<BaseDeviceIdentifier, Arc<ServerDeviceDefinition>>,
  ) -> Self {
    Self {
      base_communication_specifiers,
      user_communication_specifiers: DashMap::new(),
      base_device_definitions,
      user_device_definitions: DashMap::new(),
      simulated_devices_store: RwLock::new(Vec::new()),
    }
  }

  pub fn simulated_devices(&self) -> Vec<SimulatedDeviceConfigEntry> {
    self
      .simulated_devices_store
      .read()
      .expect("Simulated device config lock should not be poisoned")
      .clone()
  }

  fn valid_simulated_archetypes(&self) -> std::collections::HashSet<String> {
    self
      .base_communication_specifiers
      .get("simulated")
      .into_iter()
      .flat_map(|specifiers| specifiers.iter())
      .filter_map(|spec| {
        if let ProtocolCommunicationSpecifier::Simulated(sim) = spec {
          Some(sim.names().iter().cloned())
        } else {
          None
        }
      })
      .flatten()
      .collect()
  }

  pub fn add_simulated_device(
    &self,
    device: SimulatedDeviceConfigEntry,
  ) -> Result<(), ButtplugDeviceError> {
    let valid_archetypes = self.valid_simulated_archetypes();
    if !valid_archetypes.contains(&device.identifier) {
      return Err(ButtplugDeviceError::DeviceConfigurationError(format!(
        "Invalid simulated device archetype '{}'. Valid archetypes: {:?}",
        device.identifier, valid_archetypes
      )));
    }

    let mut simulated_devices = self
      .simulated_devices_store
      .write()
      .expect("Simulated device config lock should not be poisoned");
    if simulated_devices
      .iter()
      .any(|existing| existing.address == device.address)
    {
      return Err(ButtplugDeviceError::DeviceConfigurationError(format!(
        "Duplicate simulated device address '{}' for archetype '{}'",
        device.address, device.identifier
      )));
    }

    simulated_devices.push(device);
    Ok(())
  }

  pub fn remove_simulated_device(&self, address: &str) {
    let mut simulated_devices = self
      .simulated_devices_store
      .write()
      .expect("Simulated device config lock should not be poisoned");
    simulated_devices.retain(|device| device.address != address);
    self.user_device_definitions.retain(|identifier, _| {
      identifier.protocol() != "simulated" || identifier.address() != address
    });
  }

  pub fn add_user_communication_specifier(
    &self,
    protocol: &str,
    specifier: &ProtocolCommunicationSpecifier,
  ) -> Result<(), ButtplugDeviceError> {
    //self.protocol_map.contains_key(protocol);
    self
      .user_communication_specifiers
      .entry(protocol.to_owned())
      .or_default()
      .push(specifier.clone());
    Ok(())
  }

  pub fn remove_user_communication_specifier(
    &self,
    protocol: &str,
    specifier: &ProtocolCommunicationSpecifier,
  ) {
    if let Some(mut specifiers) = self.user_communication_specifiers.get_mut(protocol) {
      let specifier_vec = specifiers.value_mut();
      *specifier_vec = specifier_vec
        .iter()
        .filter(|s| *specifier != **s)
        .cloned()
        .collect();
    }
  }

  pub fn add_user_device_definition(
    &self,
    identifier: &UserDeviceIdentifier,
    definition: &ServerDeviceDefinition,
  ) {
    // TODO we should actually check validity of the definition we're adding here, i.e. does it have
    // a base id, is that ID in our base selections, etc...
    self
      .user_device_definitions
      .insert(identifier.clone(), definition.clone());
  }

  pub fn remove_user_device_definition(&self, identifier: &UserDeviceIdentifier) {
    self.user_device_definitions.remove(identifier);
  }

  pub fn address_allowed(&self, address: &str) -> bool {
    // Make sure the device isn't on the deny list
    if self
      .user_device_definitions
      .iter()
      .any(|kv| kv.key().address() == address && kv.value().deny())
    {
      // If device is outright denied, deny
      info!(
        "Device {} denied by configuration, not connecting.",
        address
      );
      false
    } else if self
      .user_device_definitions
      .iter()
      .any(|kv| kv.value().allow())
      && !self
        .user_device_definitions
        .iter()
        .any(|kv| kv.key().address() == address && kv.value().allow())
    {
      // If device is not on allow list and allow list isn't empty, deny
      info!(
        "Device {} not on allow list and allow list not empty, not connecting.",
        address
      );
      false
    } else {
      true
    }
  }

  fn device_index(&self, identifier: &UserDeviceIdentifier) -> u32 {
    // See if we have a reserved or reusable device index here.
    if let Some(config) = self.user_device_definitions.get(identifier) {
      let index = config.index();
      debug!("Found index {index} for device {identifier:?}");
      return index;
    }

    let current_indexes: Vec<u32> = self
      .user_device_definitions
      .iter()
      .map(|x| x.index())
      .collect();

    // Someone is gonna make a max device index in their config file just to fuck with me, therefore
    // we don't do "max + 1", we fill in holes (lol) in sequences. To whomever has 4 billion sex toys:
    // sorry your index finding for new devices is slow and takes 16GB of allocation every time we
    // want to search the index space.

    let mut index = 0;
    while current_indexes.contains(&index) {
      index += 1;
    }
    debug!("Generating and assigning index {index:?} for device {identifier:?}");
    index
  }

  pub fn device_definition(
    &self,
    identifier: &UserDeviceIdentifier,
  ) -> Option<ServerDeviceDefinition> {
    let features = if let Some(definition) = self.user_device_definitions.get(identifier) {
      debug!("User device config found for {:?}", identifier);
      definition.clone()
    } else if let Some(definition) = self.base_device_definitions.get(&BaseDeviceIdentifier::new(
      identifier.protocol(),
      identifier.identifier(),
    )) {
      debug!(
        "Protocol + Identifier device config found for {:?}, creating new user device from configuration",
        identifier
      );
      let mut builder = ServerDeviceDefinitionBuilder::from_base(definition, Uuid::new_v4(), true);
      builder.index(self.device_index(identifier));
      self.apply_simulated_display_name(&mut builder, identifier);
      builder.finish()
    } else if let Some(definition) = self
      .base_device_definitions
      .get(&BaseDeviceIdentifier::new(identifier.protocol(), &None))
    {
      debug!(
        "Protocol device config found for {:?}, creating new user device from protocol defaults",
        identifier
      );
      let mut builder = ServerDeviceDefinitionBuilder::from_base(definition, Uuid::new_v4(), true);
      builder.index(self.device_index(identifier));
      self.apply_simulated_display_name(&mut builder, identifier);
      builder.finish()
    } else {
      return None;
    };

    // If this is a new device, it needs to be added to the user device definition map.
    //
    // Device definitions are looked up before we fully initialize a device, mostly for algorithm
    // preparation. There is a very small chance we may save the device config then error out when
    // we connect to the device, but we'll assume we may connect successfully later.
    if self.user_device_definitions.get(identifier).is_none() {
      self
        .user_device_definitions
        .insert(identifier.clone(), features.clone());
    }

    Some(features)
  }

  fn apply_simulated_display_name(
    &self,
    builder: &mut ServerDeviceDefinitionBuilder,
    identifier: &UserDeviceIdentifier,
  ) {
    if let Some(entry) = self
      .simulated_devices_store
      .read()
      .expect("Simulated device config lock should not be poisoned")
      .iter()
      .find(|d| d.address() == identifier.address())
    {
      builder.display_name(entry.display_name());
    }
  }

  pub fn available_simulated_archetypes(&self) -> Vec<SimulatedDeviceArchetype> {
    self
      .base_device_definitions
      .iter()
      .filter(|(ident, _)| ident.protocol() == "simulated" && ident.identifier().is_some())
      .map(|(ident, def)| {
        let identifier = ident
          .identifier()
          .as_ref()
          .expect("filtered for Some above")
          .clone();
        let output_features = def
          .features()
          .values()
          .filter(|f| !f.output.is_empty())
          .map(|f| {
            let output_type = f
              .output
              .iter()
              .next()
              .map(|output| output.output_type().to_string())
              .unwrap_or_default();
            SimulatedDeviceFeatureSummary {
              description: f.description.clone(),
              output_type,
              index: f.index(),
            }
          })
          .collect();
        SimulatedDeviceArchetype {
          identifier,
          display_name: def.name().clone(),
          output_features,
        }
      })
      .collect()
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::load_protocol_configs;

  #[test]
  fn test_add_simulated_device_validates_archetype_and_address() {
    let dcm = load_protocol_configs(&None, &None, false)
      .expect("Should load base configs")
      .finish()
      .expect("Should build DCM");

    let entry = SimulatedDeviceConfigEntry::new("simulated-1vibe", None);
    let duplicate = entry.clone();

    dcm
      .add_simulated_device(entry)
      .expect("Valid simulated archetype should add");
    assert_eq!(dcm.simulated_devices().len(), 1);

    let duplicate_result = dcm.add_simulated_device(duplicate);
    assert!(duplicate_result.is_err());

    let invalid_result = dcm.add_simulated_device(SimulatedDeviceConfigEntry::new(
      "not-a-simulated-device",
      None,
    ));
    assert!(invalid_result.is_err());
  }

  #[test]
  fn test_remove_simulated_device_removes_matching_user_definition() {
    let dcm = load_protocol_configs(&None, &None, false)
      .expect("Should load base configs")
      .finish()
      .expect("Should build DCM");

    let entry = SimulatedDeviceConfigEntry::new("simulated-1vibe", None);
    let address = entry.address.clone();
    let identifier =
      UserDeviceIdentifier::new(&address, "simulated", &Some(entry.identifier.clone()));

    dcm
      .add_simulated_device(entry)
      .expect("Valid simulated archetype should add");
    dcm
      .device_definition(&identifier)
      .expect("Simulated device definition should resolve");
    assert!(dcm.user_device_definitions().contains_key(&identifier));

    dcm.remove_simulated_device(&address);

    assert!(dcm.simulated_devices().is_empty());
    assert!(!dcm.user_device_definitions().contains_key(&identifier));
  }
}