buttplug_server_device_config 12.0.1

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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
// 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 crate::ButtplugDeviceConfigError;

use buttplug_core::{
  message::{
    DeviceFeature,
    DeviceFeatureInput,
    DeviceFeatureInputProperties,
    DeviceFeatureOutput,
    DeviceFeatureOutputHwPositionWithDurationProperties,
    DeviceFeatureOutputValueProperties,
    InputCommandType,
    InputType,
    OutputType,
  },
  util::{
    range::RangeInclusive,
    small_vec_enum_map::{SmallVecEnumMap, VariantKey},
  },
};
use enumflags2::BitFlags;
use getset::{CopyGetters, Getters};
use serde::{Deserialize, Serialize};

use strum_macros::{Display, EnumDiscriminants, EnumIter, EnumString};
use uuid::Uuid;

/// Holds a combination of ranges. Base range is defined in the base device config, user range is
/// defined by the user later to be a sub-range of the base range. User range only stores in u32,
/// ranges with negatives (i.e. rotate with direction) are considered to be symettric around 0, we
/// let the system handle that conversion.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RangeWithLimit {
  pub base: RangeInclusive<i32>,
  #[serde(skip)]
  pub user: Option<RangeInclusive<u32>>,
}

impl From<RangeInclusive<i32>> for RangeWithLimit {
  fn from(value: RangeInclusive<i32>) -> Self {
    Self::new(value)
  }
}

impl RangeWithLimit {
  pub fn new(base: RangeInclusive<i32>) -> Self {
    Self { base, user: None }
  }

  pub fn new_with_user(base: RangeInclusive<i32>, user: Option<RangeInclusive<u32>>) -> Self {
    Self { base, user }
  }

  /// Returns the effective u32 range for calculations
  pub fn internal(&self) -> RangeInclusive<u32> {
    match self.user {
      Some(user_range) => user_range,
      None => RangeInclusive::new(0, self.base.end() as u32),
    }
  }

  pub fn step_limit(&self) -> RangeInclusive<i32> {
    if self.base.start() < 0 {
      RangeInclusive::new(-(self.step_count() as i32), self.step_count() as i32)
    } else {
      RangeInclusive::new(0, self.step_count() as i32)
    }
  }

  pub fn step_count(&self) -> u32 {
    if let Some(user) = &self.user {
      user.end() - user.start()
    } else {
      self.base.end() as u32
    }
  }

  pub fn try_new(
    base: RangeInclusive<i32>,
    user: Option<RangeInclusive<u32>>,
  ) -> Result<Self, ButtplugDeviceConfigError> {
    let truncated_base = RangeInclusive::new(0, base.end() as u32);
    if let Some(user) = user {
      if user.is_empty()
        || user.start() < truncated_base.start()
        || user.end() > truncated_base.end()
        || user.start() > truncated_base.end()
        || user.end() < truncated_base.start()
      {
        Err(ButtplugDeviceConfigError::InvalidUserRange)
      } else {
        Ok(Self {
          base,
          user: Some(user),
        })
      }
    } else if base.is_empty() {
      Err(ButtplugDeviceConfigError::BaseRangeRequired)
    } else {
      Ok(Self { base, user: None })
    }
  }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerDeviceFeatureOutputValueProperties {
  pub value: RangeWithLimit,
  #[serde(default)]
  pub disabled: bool,
}

impl ServerDeviceFeatureOutputValueProperties {
  pub fn new(value: RangeWithLimit, disabled: bool) -> Self {
    Self { value, disabled }
  }

  pub fn calculate_scaled_float(&self, value: f64) -> Result<i32, ButtplugDeviceConfigError> {
    if !(0.0..=1.0).contains(&value) {
      Err(ButtplugDeviceConfigError::InvalidFloatConversion(value))
    } else {
      let value = if value < 0.000001 { 0f64 } else { value };
      self.calculate_scaled_value((self.value.step_count() as f64 * value).ceil() as i32)
    }
  }

  // We'll get a number from 0-x here. We'll need to calculate it with in the range we have. We'll
  // consider negative ranges symmetric.
  pub fn calculate_scaled_value(&self, value: i32) -> Result<i32, ButtplugDeviceConfigError> {
    let range = self.value.internal();
    let current_value = value.unsigned_abs();
    let mult = if value < 0 { -1 } else { 1 };
    if value != 0 && range.contains(range.start() + current_value) {
      Ok((range.start() + current_value) as i32 * mult)
    } else if value == 0 {
      Ok(0)
    } else {
      Err(ButtplugDeviceConfigError::InvalidOutputValue(
        value,
        format!("{:?}", range),
      ))
    }
  }
}

impl From<&ServerDeviceFeatureOutputValueProperties> for DeviceFeatureOutputValueProperties {
  fn from(val: &ServerDeviceFeatureOutputValueProperties) -> Self {
    DeviceFeatureOutputValueProperties::new(val.value.step_limit())
  }
}

#[derive(Debug, Clone, Getters, CopyGetters, Serialize, Deserialize)]
pub struct ServerDeviceFeatureOutputPositionProperties {
  pub value: RangeWithLimit,
  #[serde(default)]
  pub disabled: bool,
  #[serde(default)]
  pub reverse_position: bool,
}

impl ServerDeviceFeatureOutputPositionProperties {
  pub fn new(value: RangeWithLimit, disabled: bool, reverse_position: bool) -> Self {
    Self {
      value,
      disabled,
      reverse_position,
    }
  }

  pub fn calculate_scaled_float(&self, input: f64) -> Result<i32, ButtplugDeviceConfigError> {
    if !(0.0..=1.0).contains(&input) {
      Err(ButtplugDeviceConfigError::InvalidFloatConversion(input))
    } else {
      self
        .calculate_scaled_value((self.value.step_count() as f64 * input).ceil() as u32)
        .map(|x| x as i32)
    }
  }

  // We'll get a number from 0-x here. We'll need to calculate it with in the range we have.
  pub fn calculate_scaled_value(&self, input: u32) -> Result<u32, ButtplugDeviceConfigError> {
    let range = self.value.internal();
    if range.contains(range.start() + input) {
      if self.reverse_position {
        Ok(range.end() - input)
      } else {
        Ok(range.start() + input)
      }
    } else {
      Err(ButtplugDeviceConfigError::InvalidOutputValue(
        input as i32,
        format!("{:?}", range),
      ))
    }
  }
}

impl From<&ServerDeviceFeatureOutputPositionProperties> for DeviceFeatureOutputValueProperties {
  fn from(val: &ServerDeviceFeatureOutputPositionProperties) -> Self {
    DeviceFeatureOutputValueProperties::new(val.value.step_limit())
  }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerDeviceFeatureOutputHwPositionWithDurationProperties {
  pub value: RangeWithLimit,
  pub duration: RangeWithLimit,
  #[serde(default)]
  pub disabled: bool,
  #[serde(default)]
  pub reverse_position: bool,
}

impl ServerDeviceFeatureOutputHwPositionWithDurationProperties {
  pub fn new(
    value: RangeWithLimit,
    duration: RangeWithLimit,
    disabled: bool,
    reverse_position: bool,
  ) -> Self {
    Self {
      value,
      duration,
      disabled,
      reverse_position,
    }
  }

  pub fn calculate_scaled_float(&self, input: f64) -> Result<u32, ButtplugDeviceConfigError> {
    self.calculate_scaled_value((self.value.step_count() as f64 * input) as u32)
  }

  // We'll get a number from 0-x here. We'll need to calculate it with in the range we have.
  pub fn calculate_scaled_value(&self, input: u32) -> Result<u32, ButtplugDeviceConfigError> {
    let range = self.value.internal();
    if input > 0 && range.contains(range.start() + input) {
      if self.reverse_position {
        Ok(range.end() - input)
      } else {
        Ok(range.start() + input)
      }
    } else if input == 0 {
      Ok(0)
    } else {
      Err(ButtplugDeviceConfigError::InvalidOutputValue(
        input as i32,
        format!("{:?}", range),
      ))
    }
  }
}

impl From<&ServerDeviceFeatureOutputHwPositionWithDurationProperties>
  for DeviceFeatureOutputHwPositionWithDurationProperties
{
  fn from(val: &ServerDeviceFeatureOutputHwPositionWithDurationProperties) -> Self {
    DeviceFeatureOutputHwPositionWithDurationProperties::new(
      val.value.step_limit(),
      val.duration.step_limit(),
    )
  }
}

// ServerOutputType is auto-generated as the discriminant enum of ServerDeviceFeatureOutput.
// Adding or renaming a ServerDeviceFeatureOutput variant automatically updates ServerOutputType.
#[derive(Clone, Debug, Serialize, Deserialize, EnumDiscriminants)]
#[serde(rename_all = "snake_case")]
#[strum_discriminants(name(ServerOutputType))]
#[strum_discriminants(vis(pub(crate)))]
#[strum_discriminants(derive(Display, Hash, EnumIter, EnumString, Serialize, Deserialize))]
#[strum_discriminants(serde(rename_all = "snake_case"))]
pub enum ServerDeviceFeatureOutput {
  Vibrate(ServerDeviceFeatureOutputValueProperties),
  Rotate(ServerDeviceFeatureOutputValueProperties),
  Oscillate(ServerDeviceFeatureOutputValueProperties),
  Constrict(ServerDeviceFeatureOutputValueProperties),
  Temperature(ServerDeviceFeatureOutputValueProperties),
  Led(ServerDeviceFeatureOutputValueProperties),
  Spray(ServerDeviceFeatureOutputValueProperties),
  Position(ServerDeviceFeatureOutputPositionProperties),
  HwPositionWithDuration(ServerDeviceFeatureOutputHwPositionWithDurationProperties),
}

impl ServerDeviceFeatureOutput {
  pub fn output_type(&self) -> OutputType {
    OutputType::from(ServerOutputType::from(self))
  }

  pub fn is_disabled(&self) -> bool {
    match self {
      Self::Vibrate(p)
      | Self::Rotate(p)
      | Self::Oscillate(p)
      | Self::Constrict(p)
      | Self::Temperature(p)
      | Self::Led(p)
      | Self::Spray(p) => p.disabled,
      Self::Position(p) => p.disabled,
      Self::HwPositionWithDuration(p) => p.disabled,
    }
  }

  pub fn calculate_from_value(&self, value: i32) -> Result<i32, ButtplugDeviceConfigError> {
    match self {
      Self::Vibrate(p)
      | Self::Rotate(p)
      | Self::Oscillate(p)
      | Self::Constrict(p)
      | Self::Temperature(p)
      | Self::Led(p)
      | Self::Spray(p) => p.calculate_scaled_value(value),
      Self::Position(p) => p.calculate_scaled_value(value as u32).map(|x| x as i32),
      Self::HwPositionWithDuration(p) => p.calculate_scaled_value(value as u32).map(|x| x as i32),
    }
  }

  pub fn calculate_from_float(&self, value: f64) -> Result<i32, ButtplugDeviceConfigError> {
    match self {
      Self::Vibrate(p)
      | Self::Rotate(p)
      | Self::Oscillate(p)
      | Self::Constrict(p)
      | Self::Temperature(p)
      | Self::Led(p)
      | Self::Spray(p) => p.calculate_scaled_float(value),
      Self::Position(p) => p.calculate_scaled_float(value),
      Self::HwPositionWithDuration(p) => p.calculate_scaled_float(value).map(|x| x as i32),
    }
  }

  /// Returns the value properties if this is one of the 7 simple value-type variants.
  pub fn as_value_properties(&self) -> Option<&ServerDeviceFeatureOutputValueProperties> {
    match self {
      Self::Vibrate(p)
      | Self::Rotate(p)
      | Self::Oscillate(p)
      | Self::Constrict(p)
      | Self::Temperature(p)
      | Self::Led(p)
      | Self::Spray(p) => Some(p),
      _ => None,
    }
  }
}

impl VariantKey for ServerDeviceFeatureOutput {
  type Key = OutputType;
  fn variant_key(&self) -> OutputType {
    self.output_type()
  }
}

macro_rules! impl_output_type_conversions {
  ($($variant:ident),+ $(,)?) => {
    impl From<ServerOutputType> for OutputType {
      fn from(val: ServerOutputType) -> Self {
        match val {
          $(ServerOutputType::$variant => OutputType::$variant,)+
        }
      }
    }

    impl From<OutputType> for ServerOutputType {
      fn from(val: OutputType) -> Self {
        match val {
          $(OutputType::$variant => ServerOutputType::$variant,)+
        }
      }
    }

    impl From<&ServerDeviceFeatureOutput> for DeviceFeatureOutput {
      fn from(val: &ServerDeviceFeatureOutput) -> Self {
        match val {
          $(ServerDeviceFeatureOutput::$variant(p) => DeviceFeatureOutput::$variant(p.into()),)+
        }
      }
    }
  };
}

impl_output_type_conversions![
  Vibrate,
  Rotate,
  Oscillate,
  Constrict,
  Temperature,
  Led,
  Spray,
  Position,
  HwPositionWithDuration,
];

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ServerDeviceFeatureInputProperties {
  pub value: Vec<RangeInclusive<i32>>,
  #[serde(with = "buttplug_core::util::serializers::bitflags_seq")]
  pub command: BitFlags<InputCommandType>,
}

impl ServerDeviceFeatureInputProperties {
  pub fn new(value: &[RangeInclusive<i32>], sensor_commands: &BitFlags<InputCommandType>) -> Self {
    Self {
      value: value.to_vec(),
      command: *sensor_commands,
    }
  }
}

impl From<&ServerDeviceFeatureInputProperties> for DeviceFeatureInputProperties {
  fn from(val: &ServerDeviceFeatureInputProperties) -> Self {
    DeviceFeatureInputProperties::new(&val.value, &val.command)
  }
}

// ServerInputType is auto-generated as the discriminant enum of ServerDeviceFeatureInput.
#[derive(Clone, Debug, Serialize, Deserialize, EnumDiscriminants)]
#[serde(rename_all = "snake_case")]
#[strum_discriminants(name(ServerInputType))]
#[strum_discriminants(vis(pub(crate)))]
#[strum_discriminants(derive(Display, Hash, EnumIter, EnumString, Serialize, Deserialize))]
#[strum_discriminants(serde(rename_all = "snake_case"))]
pub enum ServerDeviceFeatureInput {
  Battery(ServerDeviceFeatureInputProperties),
  Rssi(ServerDeviceFeatureInputProperties),
  Button(ServerDeviceFeatureInputProperties),
  Pressure(ServerDeviceFeatureInputProperties),
  Depth(ServerDeviceFeatureInputProperties),
  Position(ServerDeviceFeatureInputProperties),
}

impl ServerDeviceFeatureInput {
  pub fn input_type(&self) -> InputType {
    InputType::from(ServerInputType::from(self))
  }

  pub fn properties(&self) -> &ServerDeviceFeatureInputProperties {
    match self {
      Self::Battery(p)
      | Self::Rssi(p)
      | Self::Button(p)
      | Self::Pressure(p)
      | Self::Depth(p)
      | Self::Position(p) => p,
    }
  }

  pub fn can_subscribe(&self) -> bool {
    self
      .properties()
      .command
      .contains(InputCommandType::Subscribe)
  }
}

impl VariantKey for ServerDeviceFeatureInput {
  type Key = InputType;
  fn variant_key(&self) -> InputType {
    self.input_type()
  }
}

macro_rules! impl_input_type_conversions {
  ($($variant:ident),+ $(,)?) => {
    impl From<ServerInputType> for InputType {
      fn from(val: ServerInputType) -> Self {
        match val {
          $(ServerInputType::$variant => InputType::$variant,)+
        }
      }
    }

    impl From<InputType> for ServerInputType {
      fn from(val: InputType) -> Self {
        match val {
          $(InputType::$variant => ServerInputType::$variant,)+
        }
      }
    }

    impl From<&ServerDeviceFeatureInput> for DeviceFeatureInput {
      fn from(val: &ServerDeviceFeatureInput) -> Self {
        match val {
          $(ServerDeviceFeatureInput::$variant(p) => DeviceFeatureInput::$variant(p.into()),)+
        }
      }
    }
  };
}

impl_input_type_conversions![Battery, Rssi, Button, Pressure, Depth, Position,];

#[derive(Clone, Debug, Getters, CopyGetters, Serialize, Deserialize)]
#[serde(default)]
pub struct ServerDeviceFeature {
  #[getset(get_copy = "pub")]
  #[serde(default)]
  index: u32,
  #[serde(default)]
  pub description: String,
  #[serde(skip)]
  #[getset(get_copy = "pub")]
  id: Uuid,
  #[serde(default)]
  pub base_id: Option<Uuid>,
  #[serde(default)]
  pub alt_protocol_index: Option<u32>,
  #[serde(default)]
  pub output: SmallVecEnumMap<ServerDeviceFeatureOutput, 1>,
  #[serde(default)]
  pub input: SmallVecEnumMap<ServerDeviceFeatureInput, 1>,
}

impl PartialEq for ServerDeviceFeature {
  fn eq(&self, other: &Self) -> bool {
    self.id == other.id
  }
}

impl Eq for ServerDeviceFeature {
}

impl Default for ServerDeviceFeature {
  fn default() -> Self {
    Self {
      index: 0,
      description: String::new(),
      id: Uuid::new_v4(),
      base_id: None,
      alt_protocol_index: None,
      output: SmallVecEnumMap::default(),
      input: SmallVecEnumMap::default(),
    }
  }
}

impl ServerDeviceFeature {
  pub fn new(
    index: u32,
    description: String,
    id: Uuid,
    base_id: Option<Uuid>,
    alt_protocol_index: Option<u32>,
    output: SmallVecEnumMap<ServerDeviceFeatureOutput, 1>,
    input: SmallVecEnumMap<ServerDeviceFeatureInput, 1>,
  ) -> Self {
    Self {
      index,
      description,
      id,
      base_id,
      alt_protocol_index,
      output,
      input,
    }
  }

  // --- Output helpers ---

  pub fn has_output(&self) -> bool {
    !self.output.is_empty()
  }

  pub fn contains_output(&self, t: OutputType) -> bool {
    self.output.contains_key(&t)
  }

  pub fn get_output(&self, t: OutputType) -> Option<&ServerDeviceFeatureOutput> {
    self.output.find_by_key(&t)
  }

  // --- Input helpers ---

  pub fn has_input(&self) -> bool {
    !self.input.is_empty()
  }

  pub fn contains_input(&self, t: InputType) -> bool {
    self.input.contains_key(&t)
  }

  pub fn get_input(&self, t: InputType) -> Option<&ServerDeviceFeatureInput> {
    self.input.find_by_key(&t)
  }

  pub fn can_subscribe(&self) -> bool {
    self.input.iter().any(|i| i.can_subscribe())
  }

  // --- Lifecycle ---

  pub fn as_new_user_feature(&self) -> Self {
    let mut new_feature = self.clone();
    new_feature.base_id = Some(self.id);
    new_feature.id = Uuid::new_v4();
    new_feature
  }

  pub fn as_device_feature(&self) -> Result<DeviceFeature, ButtplugDeviceConfigError> {
    let output: SmallVecEnumMap<DeviceFeatureOutput, 1> = self
      .output
      .iter()
      .filter(|o| !o.is_disabled())
      .map(|o| o.into())
      .collect();
    let input: SmallVecEnumMap<DeviceFeatureInput, 1> =
      self.input.iter().map(|i| i.into()).collect();
    Ok(DeviceFeature::new(
      self.index,
      &self.description,
      &output,
      &input,
    ))
  }
}