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
use crate::core::{
  errors::{ButtplugDeviceError, ButtplugError},
  messages::{
    ButtplugDeviceCommandMessageUnion,
    ButtplugDeviceMessageType,
    LinearCmd,
    MessageAttributesMap,
    RotateCmd,
    RotationSubcommand,
    VibrateCmd,
    VibrateSubcommand,
  },
};

pub struct GenericCommandManager {
  sent_vibration: bool,
  sent_rotation: bool,
  _sent_linear: bool,
  vibrations: Vec<u32>,
  vibration_step_counts: Vec<u32>,
  rotations: Vec<(u32, bool)>,
  rotation_step_counts: Vec<u32>,
  _linears: Vec<(u32, u32)>,
  _linear_step_counts: Vec<u32>,
  stop_commands: Vec<ButtplugDeviceCommandMessageUnion>,
}

impl GenericCommandManager {
  pub fn new(attributes: &MessageAttributesMap) -> Self {
    let mut vibrations: Vec<u32> = vec![];
    let mut vibration_step_counts: Vec<u32> = vec![];
    let mut rotations: Vec<(u32, bool)> = vec![];
    let mut rotation_step_counts: Vec<u32> = vec![];
    let mut linears: Vec<(u32, u32)> = vec![];
    let mut linear_step_counts: Vec<u32> = vec![];

    let mut stop_commands = vec![];

    // TODO We should probably panic here if we don't have feature and step counts?
    if let Some(attr) = attributes.get(&ButtplugDeviceMessageType::VibrateCmd) {
      if let Some(count) = attr.feature_count {
        vibrations = vec![0; count as usize];
      }
      if let Some(step_counts) = &attr.step_count {
        vibration_step_counts = step_counts.clone();
      }

      let mut subcommands = vec![];
      for i in 0..vibrations.len() {
        subcommands.push(VibrateSubcommand::new(i as u32, 0.0).into());
      }
      stop_commands.push(VibrateCmd::new(0, subcommands).into());
    }
    if let Some(attr) = attributes.get(&ButtplugDeviceMessageType::RotateCmd) {
      if let Some(count) = attr.feature_count {
        rotations = vec![(0, true); count as usize];
      }
      if let Some(step_counts) = &attr.step_count {
        rotation_step_counts = step_counts.clone();
      }

      // TODO Can we assume clockwise is false here? We might send extra
      // messages on Lovense since it'll require both a speed and change
      // direction command, but is that really a big deal? We can just
      // have it ignore the direction difference on a 0.0 speed?
      let mut subcommands = vec![];
      for i in 0..rotations.len() {
        subcommands.push(RotationSubcommand::new(i as u32, 0.0, false));
      }
      stop_commands.push(RotateCmd::new(0, subcommands).into());
    }
    if let Some(attr) = attributes.get(&ButtplugDeviceMessageType::LinearCmd) {
      if let Some(count) = attr.feature_count {
        linears = vec![(0, 0); count as usize];
      }
      if let Some(step_counts) = &attr.step_count {
        linear_step_counts = step_counts.clone();
      }
    }

    Self {
      sent_vibration: false,
      sent_rotation: false,
      _sent_linear: false,
      vibrations,
      rotations,
      _linears: linears,
      vibration_step_counts,
      rotation_step_counts,
      _linear_step_counts: linear_step_counts,
      stop_commands,
    }
  }

  pub fn update_vibration(
    &mut self,
    msg: &VibrateCmd,
    match_all: bool,
  ) -> Result<Option<Vec<Option<u32>>>, ButtplugError> {
    // First, make sure this is a valid command, that contains at least one
    // subcommand.
    if msg.speeds.len() == 0 {
      return Err(
        ButtplugDeviceError::new(&format!("VibrateCmd has 0 commands, will not do anything."))
          .into(),
      );
    }

    // Now we convert from the generic 0.0-1.0 range to the StepCount
    // attribute given by the device config.

    // If we've already sent commands before, we should check against our
    // old values. Otherwise, we should always send whatever command we're
    // going to send.
    let mut changed_value = false;
    let mut result: Vec<Option<u32>> = vec![None; self.vibrations.len()];
    // If we're in a match all situation, set up the array with all prior
    // values before switching them out.
    if match_all {
      for i in 0..self.vibrations.len() {
        result[i] = Some(self.vibrations[i]);
      }
    }
    for speed_command in &msg.speeds {
      let index = speed_command.index as usize;
      // Since we're going to iterate here anyways, we do our index check
      // here instead of in a filter above.
      if index >= self.vibrations.len() {
        return Err(
          ButtplugDeviceError::new(&format!(
            "VibrateCmd has {} commands, device has {} vibrators.",
            msg.speeds.len(),
            self.vibrations.len()
          ))
          .into(),
        );
      }

      let speed = (speed_command.speed * self.vibration_step_counts[index] as f64) as u32;
      // If we've already sent commands, we don't want to send them again,
      // because some of our communication busses are REALLY slow. Make sure
      // these values get None in our return vector.
      if !self.sent_vibration || speed != self.vibrations[index] || match_all {
        // For some hardware, we always have to send all vibration
        // values, otherwise if we update one motor but not the other,
        // we'll stop the other motor completely if we send 0 to it.
        // That's what "match_all" is used for, so we always fall
        // through and set all of our values. However, in the case where
        // *no* motor speed changed, we don't want to send anything.
        // This is what changed_value checks.
        if speed != self.vibrations[index] || !self.sent_vibration {
          changed_value = true;
        }
        self.vibrations[index] = speed;
        result[index] = Some(speed);
      }
    }

    self.sent_vibration = true;

    // Return the command vector for the protocol to turn into proprietary commands
    if !changed_value {
      Ok(None)
    } else {
      Ok(Some(result))
    }
  }

  pub fn update_rotation(
    &mut self,
    msg: &RotateCmd,
  ) -> Result<Vec<Option<(u32, bool)>>, ButtplugError> {
    // First, make sure this is a valid command, that contains at least one
    // command.
    if msg.rotations.len() == 0 {
      return Err(
        ButtplugDeviceError::new(&format!("RotateCmd has 0 commands, will not do anything."))
          .into(),
      );
    }

    // Now we convert from the generic 0.0-1.0 range to the StepCount
    // attribute given by the device config.

    // If we've already sent commands before, we should check against our
    // old values. Otherwise, we should always send whatever command we're
    // going to send.
    let mut result: Vec<Option<(u32, bool)>> = vec![None; self.rotations.len()];
    for rotate_command in &msg.rotations {
      let index = rotate_command.index as usize;
      // Since we're going to iterate here anyways, we do our index check
      // here instead of in a filter above.
      if index >= self.rotations.len() {
        return Err(
          ButtplugDeviceError::new(&format!(
            "RotateCmd has {} commands, device has {} rotators.",
            msg.rotations.len(),
            self.rotations.len()
          ))
          .into(),
        );
      }
      let speed = (rotate_command.speed * self.rotation_step_counts[index] as f64) as u32;
      let clockwise = rotate_command.clockwise;
      // If we've already sent commands, we don't want to send them again,
      // because some of our communication busses are REALLY slow. Make sure
      // these values get None in our return vector.
      if !self.sent_rotation
        || speed != self.rotations[index].0
        || clockwise != self.rotations[index].1
      {
        self.rotations[index] = (speed, clockwise);
        result[index] = Some((speed, clockwise));
      }
    }

    self.sent_rotation = true;

    // Return the command vector for the protocol to turn into proprietary commands
    Ok(result)
  }

  pub fn _update_linear(
    &mut self,
    _msg: &LinearCmd,
  ) -> Result<Option<Vec<(u32, u32)>>, ButtplugError> {
    // First, make sure this is a valid command, that doesn't contain an
    // index we can't reach.

    // If we've already sent commands before, we should check against our
    // old values. Otherwise, we should always send whatever command we're
    // going to send.

    // Now we convert from the generic 0.0-1.0 range to the StepCount
    // attribute given by the device config.

    // If we've already sent commands, we don't want to send them again,
    // because some of our communication busses are REALLY slow. Make sure
    // these values get None in our return vector.

    // Return the command vector for the protocol to turn into proprietary commands
    Ok(None)
  }

  pub fn get_stop_commands(&self) -> Vec<ButtplugDeviceCommandMessageUnion> {
    self.stop_commands.clone()
  }
}

#[cfg(test)]
mod test {

  use super::GenericCommandManager;
  use crate::core::messages::{
    ButtplugDeviceMessageType,
    MessageAttributes,
    MessageAttributesMap,
    RotateCmd,
    RotationSubcommand,
    VibrateCmd,
    VibrateSubcommand,
  };
  #[test]
  pub fn test_command_generator_vibration() {
    let mut attributes_map = MessageAttributesMap::new();

    let mut vibrate_attributes = MessageAttributes::default();
    vibrate_attributes.feature_count = Some(2);
    vibrate_attributes.step_count = Some(vec![20, 20]);
    attributes_map.insert(ButtplugDeviceMessageType::VibrateCmd, vibrate_attributes);
    let mut mgr = GenericCommandManager::new(&attributes_map);
    let vibrate_msg = VibrateCmd::new(
      0,
      vec![
        VibrateSubcommand::new(0, 0.5),
        VibrateSubcommand::new(1, 0.5),
      ],
    );
    assert_eq!(
      mgr.update_vibration(&vibrate_msg, false).unwrap(),
      Some(vec![Some(10), Some(10)])
    );
    assert_eq!(mgr.update_vibration(&vibrate_msg, false).unwrap(), None);
    let vibrate_msg_2 = VibrateCmd::new(
      0,
      vec![
        VibrateSubcommand::new(0, 0.5),
        VibrateSubcommand::new(1, 0.75),
      ],
    );
    assert_eq!(
      mgr.update_vibration(&vibrate_msg_2, false).unwrap(),
      Some(vec![None, Some(15)])
    );
    let vibrate_msg_invalid = VibrateCmd::new(0, vec![VibrateSubcommand::new(2, 0.5)]);
    assert!(mgr.update_vibration(&vibrate_msg_invalid, false).is_err());
  }

  #[test]
  pub fn test_command_generator_rotation() {
    let mut attributes_map = MessageAttributesMap::new();

    let mut rotate_attributes = MessageAttributes::default();
    rotate_attributes.feature_count = Some(2);
    rotate_attributes.step_count = Some(vec![20, 20]);
    attributes_map.insert(ButtplugDeviceMessageType::RotateCmd, rotate_attributes);
    let mut mgr = GenericCommandManager::new(&attributes_map);
    let rotate_msg = RotateCmd::new(
      0,
      vec![
        RotationSubcommand::new(0, 0.5, true),
        RotationSubcommand::new(1, 0.5, true),
      ],
    );
    assert_eq!(
      mgr.update_rotation(&rotate_msg).unwrap(),
      vec![Some((10, true)), Some((10, true))]
    );
    assert_eq!(mgr.update_rotation(&rotate_msg).unwrap(), vec![None, None]);
    let rotate_msg_2 = RotateCmd::new(
      0,
      vec![
        RotationSubcommand::new(0, 0.5, true),
        RotationSubcommand::new(1, 0.75, false),
      ],
    );
    assert_eq!(
      mgr.update_rotation(&rotate_msg_2).unwrap(),
      vec![None, Some((15, false))]
    );
    let rotate_msg_invalid = RotateCmd::new(0, vec![RotationSubcommand::new(2, 0.5, true)]);
    assert!(mgr.update_rotation(&rotate_msg_invalid).is_err());
  }

  // TODO Write test for vibration stop generator
}