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
// Buttplug Rust Source Code File - See https://buttplug.io for more info.
//
// Copyright 2016-2022 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::server::device::configuration::ProtocolDeviceAttributes;
use crate::{
  core::{
    errors::ButtplugDeviceError,
    message::{self, ActuatorType, ButtplugDeviceMessage, ButtplugServerMessage, Endpoint},
  },
  server::device::{
    configuration::ProtocolAttributesType,
    hardware::{Hardware, HardwareCommand, HardwareReadCmd, HardwareWriteCmd},
    protocol::{
      generic_protocol_initializer_setup,
      ProtocolHandler,
      ProtocolIdentifier,
      ProtocolInitializer,
    },
    ServerDeviceIdentifier,
  },
};
use async_trait::async_trait;
use futures::future::{BoxFuture, FutureExt};
use std::sync::{
  atomic::{AtomicBool, Ordering},
  Arc,
};

generic_protocol_initializer_setup!(LovenseConnectService, "lovense-connect-service");

#[derive(Default)]
pub struct LovenseConnectServiceInitializer {}

#[async_trait]
impl ProtocolInitializer for LovenseConnectServiceInitializer {
  async fn initialize(
    &mut self,
    hardware: Arc<Hardware>,
    attributes: &ProtocolDeviceAttributes,
  ) -> Result<Arc<dyn ProtocolHandler>, ButtplugDeviceError> {
    let mut protocol = LovenseConnectService::new(hardware.address());

    if let Some(scalars) = attributes.message_attributes.scalar_cmd() {
      protocol.vibrator_count = scalars
        .clone()
        .iter()
        .filter(|x| [ActuatorType::Vibrate].contains(x.actuator_type()))
        .count();
      protocol.thusting_count = scalars
        .clone()
        .iter()
        .filter(|x| [ActuatorType::Oscillate].contains(x.actuator_type()))
        .count();

      // The Ridge and Gravity both oscillate, but the Ridge only oscillates but takes
      // the vibrate command... The Gravity has a vibe as well, and uses a Thrusting
      // command for that oscillator.
      if protocol.vibrator_count == 0 && protocol.thusting_count != 0 {
        protocol.vibrator_count = protocol.thusting_count;
        protocol.thusting_count = 0;
      }
    }

    Ok(Arc::new(protocol))
  }
}

#[derive(Default)]
pub struct LovenseConnectService {
  address: String,
  rotation_direction: Arc<AtomicBool>,
  vibrator_count: usize,
  thusting_count: usize,
}

impl LovenseConnectService {
  pub fn new(address: &str) -> Self {
    Self {
      address: address.to_owned(),
      ..Default::default()
    }
  }
}

impl ProtocolHandler for LovenseConnectService {
  fn handle_scalar_cmd(
    &self,
    cmds: &[Option<(ActuatorType, u32)>],
  ) -> Result<Vec<HardwareCommand>, ButtplugDeviceError> {
    let mut hardware_cmds = vec![];

    // Handle vibration commands, these will be by far the most common. Fucking machine oscillation
    // uses lovense vibrate commands internally too, so we can include them here.
    let vibrate_cmds: Vec<&(ActuatorType, u32)> = cmds
      .iter()
      .filter(|x| {
        if let Some(val) = x {
          if self.thusting_count == 0 {
            [ActuatorType::Vibrate, ActuatorType::Oscillate].contains(&val.0)
          } else {
            [ActuatorType::Vibrate].contains(&val.0)
          }
        } else {
          false
        }
      })
      .map(|x| x.as_ref().expect("Already verified is some"))
      .collect();

    if !vibrate_cmds.is_empty() {
      // Lovense is the same situation as the Lovehoney Desire, where commands
      // are different if we're addressing all motors or seperate motors.
      // Difference here being that there's Lovense variants with different
      // numbers of motors.
      //
      // Neat way of checking if everything is the same via
      // https://sts10.github.io/2019/06/06/is-all-equal-function.html.
      //
      // Just make sure we're not matching on None, 'cause if that's the case
      // we ain't got shit to do.
      if self.vibrator_count == vibrate_cmds.len()
        && (self.vibrator_count == 1 || vibrate_cmds.windows(2).all(|w| w[0].1 == w[1].1))
      {
        let lovense_cmd = format!("Vibrate?v={}&t={}", vibrate_cmds[0].1, self.address)
          .as_bytes()
          .to_vec();
        hardware_cmds.push(HardwareWriteCmd::new(Endpoint::Tx, lovense_cmd, false).into());
      } else {
        for (i, cmd) in cmds.iter().enumerate() {
          if let Some((actuator, speed)) = cmd {
            if self.thusting_count == 0
              && ![ActuatorType::Vibrate, ActuatorType::Oscillate].contains(actuator)
            {
              continue;
            }
            if self.thusting_count != 0 && ![ActuatorType::Vibrate].contains(actuator) {
              continue;
            }
            let lovense_cmd = format!("Vibrate{}?v={}&t={}", i + 1, speed, self.address)
              .as_bytes()
              .to_vec();
            hardware_cmds.push(HardwareWriteCmd::new(Endpoint::Tx, lovense_cmd, false).into());
          }
        }
      }
    }

    // Handle constriction commands.
    let thrusting_cmds: Vec<&(ActuatorType, u32)> = cmds
      .iter()
      .filter(|x| {
        if let Some(val) = x {
          [ActuatorType::Oscillate].contains(&val.0)
        } else {
          false
        }
      })
      .map(|x| x.as_ref().expect("Already verified is some"))
      .collect();
    if self.thusting_count != 0 && !thrusting_cmds.is_empty() {
      let lovense_cmd = format!("Thrusting?v={}&t={}", thrusting_cmds[0].1, self.address)
        .as_bytes()
        .to_vec();

      hardware_cmds.push(HardwareWriteCmd::new(Endpoint::Tx, lovense_cmd, false).into());
    }

    // Handle constriction commands.
    let constrict_cmds: Vec<&(ActuatorType, u32)> = cmds
      .iter()
      .filter(|x| {
        if let Some(val) = x {
          val.0 == ActuatorType::Constrict
        } else {
          false
        }
      })
      .map(|x| x.as_ref().expect("Already verified is some"))
      .collect();

    if !constrict_cmds.is_empty() {
      // Only the max has a constriction system, and there's only one, so just parse the first command.
      /* ~ Sutekh
       * - Implemented constriction.
       * - Kept things consistent with the lovense handle_scalar_cmd() method.
       * - Using AirAuto method.
       * - Changed step count in device config file to 3.
       */
      let lovense_cmd = format!("AirAuto?v={}&t={}", constrict_cmds[0].1, self.address)
        .as_bytes()
        .to_vec();

      hardware_cmds.push(HardwareWriteCmd::new(Endpoint::Tx, lovense_cmd, false).into());
    }

    // Handle "rotation" commands: Currently just applicable as the Flexer's Fingering command
    let rotation_cmds: Vec<&(ActuatorType, u32)> = cmds
      .iter()
      .filter(|x| {
        if let Some(val) = x {
          val.0 == ActuatorType::Rotate
        } else {
          false
        }
      })
      .map(|x| x.as_ref().expect("Already verified is some"))
      .collect();

    if !rotation_cmds.is_empty() {
      let lovense_cmd = format!("Fingering?v={}&t={}", rotation_cmds[0].1, self.address)
        .as_bytes()
        .to_vec();

      hardware_cmds.push(HardwareWriteCmd::new(Endpoint::Tx, lovense_cmd, false).into());
    }

    Ok(hardware_cmds)

    /* Note from Sutekh:
     * I removed the code below to keep the handle_scalar_cmd methods for lovense toys somewhat consistent.
     * The patch above is almost the same as the "Lovense" ProtocolHandler implementation.
     * I have changed the commands to the Lovense Connect API format.
     * During my testing of the Lovense Connect app's API it seems that even though Constriction has a step range of 0-5. It only responds to values 1-3.
     */

    /*
        // Lovense is the same situation as the Lovehoney Desire, where commands
        // are different if we're addressing all motors or seperate motors.
        // Difference here being that there's Lovense variants with different
    @@ -77,26 +220,27 @@
        // Just make sure we're not matching on None, 'cause if that's the case
        // we ain't got shit to do.
        let mut msg_vec = vec![];
        if cmds[0].is_some() && (cmds.len() == 1 || cmds.windows(2).all(|w| w[0] == w[1])) {
          let lovense_cmd = format!(
            "Vibrate?v={}&t={}",
            cmds[0].expect("Already checked existence").1,
            self.address
          )
          .as_bytes()
          .to_vec();
          msg_vec.push(HardwareWriteCmd::new(Endpoint::Tx, lovense_cmd, false).into());
        } else {
          for (i, cmd) in cmds.iter().enumerate() {
            if let Some((_, speed)) = cmd {
              let lovense_cmd = format!("Vibrate{}?v={}&t={}", i + 1, speed, self.address)
                .as_bytes()
                .to_vec();
              msg_vec.push(HardwareWriteCmd::new(Endpoint::Tx, lovense_cmd, false).into());
            }
          }
        }
        Ok(msg_vec)
        */
  }

  fn handle_rotate_cmd(
    &self,
    cmds: &[Option<(u32, bool)>],
  ) -> Result<Vec<HardwareCommand>, ButtplugDeviceError> {
    let mut hardware_cmds = vec![];
    if let Some(Some((speed, clockwise))) = cmds.get(0) {
      let lovense_cmd = format!("/Rotate?v={}&t={}", speed, self.address)
        .as_bytes()
        .to_vec();
      hardware_cmds.push(HardwareWriteCmd::new(Endpoint::Tx, lovense_cmd, false).into());
      let dir = self.rotation_direction.load(Ordering::SeqCst);
      // TODO Should we store speed and direction as an option for rotation caching? This is weird.
      if dir != *clockwise {
        self.rotation_direction.store(*clockwise, Ordering::SeqCst);
        hardware_cmds
          .push(HardwareWriteCmd::new(Endpoint::Tx, b"RotateChange?".to_vec(), false).into());
      }
    }
    Ok(hardware_cmds)
  }

  fn handle_battery_level_cmd(
    &self,
    device: Arc<Hardware>,
    msg: message::SensorReadCmd,
  ) -> BoxFuture<Result<ButtplugServerMessage, ButtplugDeviceError>> {
    async move {
      // This is a dummy read. We just store the battery level in the device
      // implementation and it's the only thing read will return.
      let reading = device
        .read_value(&HardwareReadCmd::new(Endpoint::Rx, 0, 0))
        .await?;
      debug!("Battery level: {}", reading.data()[0]);
      Ok(
        message::SensorReading::new(
          msg.device_index(),
          *msg.sensor_index(),
          *msg.sensor_type(),
          vec![reading.data()[0] as i32],
        )
        .into(),
      )
    }
    .boxed()
  }
}