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
mod generic_command_manager;

use super::device::DeviceImpl;
use crate::{
  core::{
    errors::ButtplugError,
    messages::{ButtplugDeviceCommandMessageUnion, ButtplugOutMessage, MessageAttributesMap},
  },
  device::configuration_manager::{DeviceProtocolConfiguration, ProtocolConstructor},
};
use async_trait::async_trait;
use std::collections::HashMap;

macro_rules! create_protocols(
    (
        $(
            ($protocol_config_name:tt, $protocol_module:tt, $protocol_name:tt)
        ),*
    ) => {
        paste::item! {
            $(
                mod $protocol_module;
                use $protocol_module::[<$protocol_name Creator>];
            )*

            pub fn create_protocol_creator_map() -> HashMap::<String, ProtocolConstructor> {
                // Do not try to use HashMap::new() here. We need the explicit typing,
                // otherwise we'll just get an anonymous closure type during insert that
                // won't match.
                let mut protocols = HashMap::<String, ProtocolConstructor>::new();

                $(
                    protocols.insert(
                        $protocol_config_name.to_owned(),
                        Box::new(|config: DeviceProtocolConfiguration| {
                            Box::new([<$protocol_name Creator>]::new(config))
                        }),
                    );
                )*
                protocols
            }
        }
    }
);

// IF YOU WANT TO ADD NEW PROTOCOLS TO THE SYSTEM, DO IT HERE.
//
// This takes a tuple per protocol:
//
// - the name of the protocol in the device configuration file
// - the name of the module
// - the base name of the protocol, as used in create_buttplug_protocol!
create_protocols!(
  ("aneros", aneros, Aneros),
  ("maxpro", maxpro, Maxpro),
  ("lovense", lovense, Lovense),
  ("picobong", picobong, Picobong),
  ("realov", realov, Realov),
  ("prettylove", prettylove, PrettyLove),
  ("svakom", svakom, Svakom),
  ("youcups", youcups, Youcups),
  ("youou", youou, Youou),
  ("lovehoney-desire", lovehoney_desire, LovehoneyDesire),
  ("vorze-sa", vorze_sa, VorzeSA),
  ("xinput", xinput, XInput)
);

#[async_trait]
pub trait ButtplugProtocolCreator: Sync + Send {
  async fn try_create_protocol(
    &self,
    device_impl: &Box<dyn DeviceImpl>,
  ) -> Result<Box<dyn ButtplugProtocol>, ButtplugError>;
}

#[async_trait]
pub trait ButtplugProtocol: Sync + Send {
  fn name(&self) -> &str;
  fn message_attributes(&self) -> MessageAttributesMap;
  fn box_clone(&self) -> Box<dyn ButtplugProtocol>;
  async fn parse_message(
    &mut self,
    device: &Box<dyn DeviceImpl>,
    message: &ButtplugDeviceCommandMessageUnion,
  ) -> Result<ButtplugOutMessage, ButtplugError>;
}

impl Clone for Box<dyn ButtplugProtocol> {
  fn clone(&self) -> Box<dyn ButtplugProtocol> {
    self.box_clone()
  }
}

// TODO These macros could use some compilation tests to make sure we're
// bringing in everything we need.

// Note: We have to use tt instead of ident here due to the async_trait macro.
// See https://github.com/dtolnay/async-trait/issues/46 for more info.
#[macro_export]
macro_rules! create_protocol_creator_impl (
    (
        true,
        $protocol_name:tt
    ) => {
        use async_trait::async_trait;
        use crate::{
            device::{
                protocol::{ButtplugProtocol, ButtplugProtocolCreator},
                configuration_manager::DeviceProtocolConfiguration,
            },
        };

        paste::item! {
            pub struct [<$protocol_name Creator>] {
                config: DeviceProtocolConfiguration,
            }

            impl [<$protocol_name Creator>] {
                pub fn new(config: DeviceProtocolConfiguration) -> Self {
                    Self { config }
                }
            }

            #[async_trait]
            impl ButtplugProtocolCreator for [<$protocol_name Creator>] {
                async fn try_create_protocol(
                    &self,
                    device_impl: &Box<dyn DeviceImpl>,
                ) -> Result<Box<dyn ButtplugProtocol>, ButtplugError> {
                    let (names, attrs) = self.config.get_attributes(device_impl.name()).unwrap();
                    let name = names.get("en-us").unwrap();
                    Ok(Box::new($protocol_name::new(name, attrs)))
                }
            }
        }
    };
    (
        false,
        $protocol_name:tt
    ) => {
    };
);

#[macro_export]
macro_rules! create_buttplug_protocol (
    (
        $protocol_name:tt,
        $create_protocol_creator_impl:tt,
        (
            $(
                ( $member_name:tt: $member_type:ty = $member_initial_value:expr )
            ),*
        ),
        (
            $(
                ( $message_name:tt, $message_handler_body:block )
            ),+
        )
    ) => {
        use crate::{
            create_protocol_creator_impl,
            device::{
                Endpoint,
                device::{DeviceWriteCmd, DeviceImpl},
                protocol::generic_command_manager::GenericCommandManager,
            },
            core::{
                errors::{ButtplugError, ButtplugDeviceError},
                messages::{
                    self,
                    ButtplugMessage,
                    StopDeviceCmd,
                    MessageAttributesMap,
                    ButtplugOutMessage,
                    VibrateSubcommand,
                    ButtplugDeviceMessageType,
                    ButtplugDeviceCommandMessageUnion,
                    $(
                        $message_name
                    ),*
                },
            },
        };
        use async_std::sync::{Arc, Mutex};

        create_protocol_creator_impl!($create_protocol_creator_impl, $protocol_name);

        #[derive(Clone)]
        pub struct $protocol_name {
            name: String,
            attributes: MessageAttributesMap,
            manager: Arc<Mutex<GenericCommandManager>>,
            stop_commands: Vec<ButtplugDeviceCommandMessageUnion>,
            $(
                $member_name: $member_type
            ),*
        }

        paste::item! {
            impl $protocol_name {
                pub fn new(name: &str, attributes: MessageAttributesMap) -> Self {
                    let manager = GenericCommandManager::new(&attributes);

                    $protocol_name {
                        name: name.to_owned(),
                        attributes,
                        stop_commands: manager.get_stop_commands(),
                        manager: Arc::new(Mutex::new(manager)),
                        $(
                            $member_name: $member_initial_value
                        ),*
                    }
                }

                async fn handle_stop_device_cmd(
                    &mut self,
                    device: &Box<dyn DeviceImpl>,
                    stop_msg: &StopDeviceCmd,
                ) -> Result<ButtplugOutMessage, ButtplugError> {
                    // TODO This clone definitely shouldn't be needed but I'm tired. GOOD FIRST BUG.
                    let cmds = self.stop_commands.clone();
                    for msg in cmds {
                        self.parse_message(device, &msg).await?;
                    }
                    Ok(messages::Ok::new(stop_msg.get_id()).into())
                }

                $(
                    #[allow(non_snake_case)]
                    pub async fn [<$message_name _handler>](&mut self,
                        device: &Box<dyn DeviceImpl>,
                        msg: &$message_name,) -> Result<ButtplugOutMessage, ButtplugError>
                        $message_handler_body
                    )*
                }
            }
            paste::item! {
                #[async_trait]
                impl ButtplugProtocol for $protocol_name {
                    fn name(&self) -> &str {
                        &self.name
                    }

                    fn message_attributes(&self) -> MessageAttributesMap {
                        self.attributes.clone()
                    }

                    fn box_clone(&self) -> Box<dyn ButtplugProtocol> {
                        Box::new((*self).clone())
                    }

                    async fn parse_message(
                        &mut self,
                        device: &Box<dyn DeviceImpl>,
                        message: &ButtplugDeviceCommandMessageUnion,
                    ) -> Result<ButtplugOutMessage, ButtplugError> {
                        match message {
                            $(
                                ButtplugDeviceCommandMessageUnion::$message_name(msg) => {
                                    self.[<$message_name _handler>](device, msg).await
                                }
                            ),*,
                            ButtplugDeviceCommandMessageUnion::SingleMotorVibrateCmd(msg) => {
                                // Time for sadness! In order to handle conversion of
                                // SingleMotorVibrateCmd, we need to know how many
                                // vibrators a device has. We don't actually know that
                                // until we get to the protocol level, so we're stuck
                                // parsing this here. Since we can assume
                                // SingleMotorVibrateCmd will ALWAYS map to vibration,
                                // we can convert to VibrateCmd here and save ourselves
                                // having to handle it in every protocol, meaning spec
                                // v0 and v1 programs will still be forward compatible
                                // with vibrators.
                                let vibrator_count;
                                if let Some(attr) = self.attributes.get(&ButtplugDeviceMessageType::VibrateCmd) {
                                    if let Some(count) = attr.feature_count {
                                        vibrator_count = count as usize;
                                    } else {
                                        return Err(ButtplugDeviceError::new("$protocol_name needs to support VibrateCmd with a feature count to use SingleMotorVibrateCmd.").into());
                                    }
                                } else {
                                    return Err(ButtplugDeviceError::new("$protocol_name needs to support VibrateCmd to use SingleMotorVibrateCmd.").into());
                                }
                                let speed = msg.speed;
                                let mut cmds = vec!();
                                for i in 0..vibrator_count {
                                    cmds.push(VibrateSubcommand::new(i as u32, speed));
                                }
                                let mut vibrate_cmd = VibrateCmd::new(msg.device_index, cmds);
                                vibrate_cmd.set_id(msg.get_id());
                                self.parse_message(device, &vibrate_cmd.into()).await
                            },
                            ButtplugDeviceCommandMessageUnion::StopDeviceCmd(msg) => {
                                self.handle_stop_device_cmd(device, msg).await
                            },
                            _ => Err(ButtplugError::ButtplugDeviceError(
                                ButtplugDeviceError::new("$protocol_name does not accept this message type."),
                            )),
                        }
                    }
                }
            }
        }
    );