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
// Buttplug Rust Source Code File - See https://buttplug.io for more info.
//
// Copyright 2016-2019 Nonpolynomial Labs LLC. All rights reserved.
//
// Licensed under the BSD 3-Clause license. See LICENSE file in the project root
// for full license information.

//! Structs representing low level [Buttplug
//! Protocol](https://buttplug-spec.docs.buttplug.io) messages

use super::errors::*;
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};
use std::collections::HashMap;

/// Base trait for all Buttplug Protocol Message Structs. Handles management of
/// message ids, as well as implementing conveinence functions for converting
/// between message structs and [ButtplugMessageUnion] enums, serialization, etc...
pub trait ButtplugMessage: Send + Sync + Clone + Serialize + Deserialize<'static> {
    /// Returns the id number of the message
    fn get_id(&self) -> u32;
    /// Sets the id number of the message
    fn set_id(&mut self, id: u32);
    /// Returns the message as a [ButtplugMessageUnion] enum.
    fn as_union(self) -> ButtplugMessageUnion;
    /// Returns the message as a string in Buttplug JSON Protocol format.
    fn as_protocol_json(&self) -> String {
        "[".to_owned() + &serde_json::to_string(&self).unwrap() + "]"
    }
}

/// Represents the Buttplug Protocol Ok message, as documented in the [Buttplug
/// Protocol Spec](https://buttplug-spec.docs.buttplug.io/status.html#ok).
#[derive(Debug, PartialEq, Default, ButtplugMessage, Clone, Serialize, Deserialize)]
pub struct Ok {
    /// Message Id, used for matching message pairs in remote connection instances.
    #[serde(rename = "Id")]
    id: u32,
}

impl Ok {
    /// Creates a new Ok message with the given Id.
    pub fn new(id: u32) -> Self {
        Self { id }
    }
}

/// Error codes pertaining to error classes that can be represented in the
/// Buttplug [Error] message.
#[derive(Debug, Clone, Serialize_repr, Deserialize_repr, PartialEq)]
#[repr(u8)]
pub enum ErrorCode {
    ErrorUnknown = 0,
    ErrorHandshake,
    ErrorPing,
    ErrorMessage,
    ErrorDevice,
}

/// Represents the Buttplug Protocol Error message, as documented in the [Buttplug
/// Protocol Spec](https://buttplug-spec.docs.buttplug.io/status.html#error).
#[derive(Debug, ButtplugMessage, Clone, Serialize, Deserialize, PartialEq)]
pub struct Error {
    /// Message Id, used for matching message pairs in remote connection instances.
    #[serde(rename = "Id")]
    id: u32,
    /// Specifies the class of the error.
    #[serde(rename = "ErrorCode")]
    pub error_code: ErrorCode,
    /// Description of the error.
    #[serde(rename = "ErrorMessage")]
    pub error_message: String,
}

impl Error {
    /// Creates a new error object.
    pub fn new(error_code: ErrorCode, error_message: &str) -> Self {
        Self {
            id: 0,
            error_code,
            error_message: error_message.to_string(),
        }
    }
}

impl From<ButtplugError> for Error {
    /// Converts a [super::errors::ButtplugError] object into a Buttplug Protocol
    /// [Error] message.
    fn from(error: ButtplugError) -> Self {
        let code = match error {
            ButtplugError::ButtplugDeviceError(_) => ErrorCode::ErrorDevice,
            ButtplugError::ButtplugMessageError(_) => ErrorCode::ErrorMessage,
            ButtplugError::ButtplugPingError(_) => ErrorCode::ErrorPing,
            ButtplugError::ButtplugHandshakeError(_) => ErrorCode::ErrorHandshake,
            ButtplugError::ButtplugUnknownError(_) => ErrorCode::ErrorUnknown,
        };
        // Gross but was having problems with naming collisions on the error trait
        let msg = match error {
            ButtplugError::ButtplugDeviceError(_s) => _s.message,
            ButtplugError::ButtplugMessageError(_s) => _s.message,
            ButtplugError::ButtplugPingError(_s) => _s.message,
            ButtplugError::ButtplugHandshakeError(_s) => _s.message,
            ButtplugError::ButtplugUnknownError(_s) => _s.message,
        };
        Error::new(code, &msg)
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct MessageAttributes {
    #[serde(rename = "FeatureCount")]
    pub feature_count: Option<u32>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct DeviceMessageInfo {
    #[serde(rename = "DeviceIndex")]
    pub device_index: u32,
    #[serde(rename = "DeviceName")]
    pub device_name: String,
    #[serde(rename = "DeviceMessages")]
    pub device_messages: HashMap<String, MessageAttributes>,
}

#[derive(Default, ButtplugMessage, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct DeviceList {
    #[serde(rename = "Id")]
    id: u32,
    #[serde(rename = "Devices")]
    pub devices: Vec<DeviceMessageInfo>,
}

#[derive(Default, ButtplugMessage, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct DeviceAdded {
    #[serde(rename = "Id")]
    id: u32,
    #[serde(rename = "DeviceIndex")]
    pub device_index: u32,
    #[serde(rename = "DeviceName")]
    pub device_name: String,
    #[serde(rename = "DeviceMessages")]
    pub device_messages: HashMap<String, MessageAttributes>,
}

#[derive(Debug, Default, ButtplugMessage, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeviceRemoved {
    id: u32,
    pub device_index: u32,
}

#[derive(Debug, Default, ButtplugMessage, Clone, Serialize, Deserialize, PartialEq)]
pub struct StartScanning {
    #[serde(rename = "Id")]
    id: u32,
}

impl StartScanning {
    pub fn new() -> Self {
        Self { id: 1 }
    }
}

#[derive(Debug, Default, ButtplugMessage, Clone, Serialize, Deserialize, PartialEq)]
pub struct StopScanning {
    #[serde(rename = "Id")]
    id: u32,
}

#[derive(Debug, Default, ButtplugMessage, Clone, Serialize, Deserialize, PartialEq)]
pub struct ScanningFinished {
    #[serde(rename = "Id")]
    id: u32,
}

#[derive(Debug, Default, ButtplugMessage, Clone, Serialize, Deserialize, PartialEq)]
pub struct RequestDeviceList {
    #[serde(rename = "Id")]
    id: u32,
}

#[derive(Debug, Default, ButtplugMessage, Clone, Serialize, Deserialize, PartialEq)]
pub struct RequestServerInfo {
    #[serde(rename = "Id")]
    id: u32,
    #[serde(rename = "ClientName")]
    pub client_name: String,
    #[serde(rename = "MessageVersion")]
    pub message_version: u32,
}

impl RequestServerInfo {
    pub fn new(client_name: &str, message_version: u32) -> Self {
        Self {
            id: 1,
            client_name: client_name.to_string(),
            message_version,
        }
    }
}

#[derive(Debug, Default, ButtplugMessage, PartialEq, Clone, Serialize, Deserialize)]
pub struct ServerInfo {
    #[serde(rename = "Id")]
    id: u32,
    #[serde(rename = "MajorVersion")]
    pub major_version: u32,
    #[serde(rename = "MinorVersion")]
    pub minor_version: u32,
    #[serde(rename = "BuildVersion")]
    pub build_version: u32,
    #[serde(rename = "MessageVersion")]
    pub message_version: u32,
    #[serde(rename = "MaxPingTime")]
    pub max_ping_time: u32,
    #[serde(rename = "ServerName")]
    pub server_name: String,
}

impl ServerInfo {
    pub fn new(server_name: &str, message_version: u32, max_ping_time: u32) -> Self {
        Self {
            id: 0,
            major_version: 0,
            minor_version: 0,
            build_version: 0,
            message_version,
            max_ping_time,
            server_name: server_name.to_string(),
        }
    }
}

#[derive(Debug, Default, PartialEq, Clone, Serialize, Deserialize)]
pub struct VibrateSubcommand {
    #[serde(rename = "Index")]
    pub index: u32,
    #[serde(rename = "Speed")]
    pub speed: f64,
}

impl VibrateSubcommand {
    pub fn new(index: u32, speed: f64) -> Self {
        Self { index, speed }
    }
}

#[derive(Debug, Default, ButtplugMessage, PartialEq, Clone, Serialize, Deserialize)]
pub struct VibrateCmd {
    #[serde(rename = "Id")]
    pub id: u32,
    #[serde(rename = "DeviceIndex")]
    pub device_index: u32,
    #[serde(rename = "Speeds")]
    pub speeds: Vec<VibrateSubcommand>,
}

impl VibrateCmd {
    pub fn new(device_index: u32, speeds: Vec<VibrateSubcommand>) -> Self {
        Self {
            id: 1,
            device_index,
            speeds,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ButtplugMessageUnion {
    Ok(Ok),
    Error(Error),
    DeviceList(DeviceList),
    DeviceAdded(DeviceAdded),
    DeviceRemoved(DeviceRemoved),
    StartScanning(StartScanning),
    StopScanning(StopScanning),
    ScanningFinished(ScanningFinished),
    RequestDeviceList(RequestDeviceList),
    RequestServerInfo(RequestServerInfo),
    ServerInfo(ServerInfo),
    VibrateCmd(VibrateCmd),
}

impl ButtplugMessage for ButtplugMessageUnion {
    fn get_id(&self) -> u32 {
        match self {
            ButtplugMessageUnion::Ok(ref _msg) => _msg.id,
            ButtplugMessageUnion::Error(ref _msg) => _msg.id,
            ButtplugMessageUnion::DeviceList(ref _msg) => _msg.id,
            ButtplugMessageUnion::DeviceAdded(ref _msg) => _msg.id,
            ButtplugMessageUnion::DeviceRemoved(ref _msg) => _msg.id,
            ButtplugMessageUnion::StartScanning(ref _msg) => _msg.id,
            ButtplugMessageUnion::StopScanning(ref _msg) => _msg.id,
            ButtplugMessageUnion::ScanningFinished(ref _msg) => _msg.id,
            ButtplugMessageUnion::RequestDeviceList(ref _msg) => _msg.id,
            ButtplugMessageUnion::RequestServerInfo(ref _msg) => _msg.id,
            ButtplugMessageUnion::ServerInfo(ref _msg) => _msg.id,
            ButtplugMessageUnion::VibrateCmd(ref _msg) => _msg.id,
        }
    }

    fn set_id(&mut self, id: u32) {
        match self {
            ButtplugMessageUnion::Ok(ref mut _msg) => _msg.set_id(id),
            ButtplugMessageUnion::Error(ref mut _msg) => _msg.set_id(id),
            ButtplugMessageUnion::DeviceList(ref mut _msg) => _msg.set_id(id),
            ButtplugMessageUnion::DeviceAdded(ref mut _msg) => _msg.set_id(id),
            ButtplugMessageUnion::DeviceRemoved(ref mut _msg) => _msg.set_id(id),
            ButtplugMessageUnion::StartScanning(ref mut _msg) => _msg.set_id(id),
            ButtplugMessageUnion::StopScanning(ref mut _msg) => _msg.set_id(id),
            ButtplugMessageUnion::ScanningFinished(ref mut _msg) => _msg.set_id(id),
            ButtplugMessageUnion::RequestDeviceList(ref mut _msg) => _msg.set_id(id),
            ButtplugMessageUnion::RequestServerInfo(ref mut _msg) => _msg.set_id(id),
            ButtplugMessageUnion::ServerInfo(ref mut _msg) => _msg.set_id(id),
            ButtplugMessageUnion::VibrateCmd(ref mut _msg) => _msg.set_id(id),
        }
    }

    fn as_union(self) -> ButtplugMessageUnion {
        panic!("as_union shouldn't be called on union.");
    }
}

#[cfg(test)]
mod test {
    use super::{ButtplugMessageUnion, Error, ErrorCode, Ok};

    const OK_STR: &str = "{\"Ok\":{\"Id\":0}}";
    const ERROR_STR: &str =
        "{\"Error\":{\"Id\":0,\"ErrorCode\":1,\"ErrorMessage\":\"Test Error\"}}";

    #[test]
    fn test_ok_serialize() {
        let ok = ButtplugMessageUnion::Ok(Ok::new(0));
        let js = serde_json::to_string(&ok).unwrap();
        assert_eq!(OK_STR, js);
    }

    #[test]
    fn test_ok_deserialize() {
        let union: ButtplugMessageUnion = serde_json::from_str(&OK_STR).unwrap();
        assert_eq!(ButtplugMessageUnion::Ok(Ok::new(0)), union);
    }

    #[test]
    fn test_error_serialize() {
        let error =
            ButtplugMessageUnion::Error(Error::new(ErrorCode::ErrorHandshake, "Test Error"));
        let js = serde_json::to_string(&error).unwrap();
        assert_eq!(ERROR_STR, js);
    }

    #[test]
    fn test_error_deserialize() {
        let union: ButtplugMessageUnion = serde_json::from_str(&ERROR_STR).unwrap();
        assert_eq!(
            ButtplugMessageUnion::Error(Error::new(ErrorCode::ErrorHandshake, "Test Error")),
            union
        );
    }
}