use buttplug_core::errors::ButtplugDeviceError;
use dashmap::DashMap;
use getset::Getters;
use std::{
collections::HashMap,
fmt::{self, Debug},
sync::Arc,
sync::RwLock,
};
use uuid::Uuid;
use crate::{
BaseDeviceIdentifier,
ButtplugDeviceConfigError,
ProtocolCommunicationSpecifier,
ServerDeviceDefinition,
ServerDeviceDefinitionBuilder,
SimulatedDeviceConfigEntry,
UserDeviceIdentifier,
device_config_file::{SimulatedDeviceArchetype, SimulatedDeviceFeatureSummary},
};
#[derive(Default, Clone)]
pub struct DeviceConfigurationManagerBuilder {
base_communication_specifiers: HashMap<String, Vec<ProtocolCommunicationSpecifier>>,
user_communication_specifiers: DashMap<String, Vec<ProtocolCommunicationSpecifier>>,
base_device_definitions: HashMap<BaseDeviceIdentifier, Arc<ServerDeviceDefinition>>,
user_device_definitions: DashMap<UserDeviceIdentifier, ServerDeviceDefinition>,
simulated_devices: Vec<SimulatedDeviceConfigEntry>,
}
impl DeviceConfigurationManagerBuilder {
pub fn communication_specifier(
&mut self,
protocol_name: &str,
specifier: &[ProtocolCommunicationSpecifier],
) -> &mut Self {
self
.base_communication_specifiers
.entry(protocol_name.to_owned())
.or_default()
.extend(specifier.iter().cloned());
self
}
pub fn base_device_definition(
&mut self,
identifier: &BaseDeviceIdentifier,
definition: Arc<ServerDeviceDefinition>,
) -> &mut Self {
self
.base_device_definitions
.insert(identifier.clone(), definition);
self
}
pub fn user_communication_specifier(
&mut self,
protocol_name: &str,
specifier: &[ProtocolCommunicationSpecifier],
) -> &mut Self {
self
.user_communication_specifiers
.entry(protocol_name.to_owned())
.or_default()
.extend(specifier.iter().cloned());
self
}
pub fn user_device_definition(
&mut self,
identifier: &UserDeviceIdentifier,
device_definition: &ServerDeviceDefinition,
) -> Result<&mut Self, ButtplugDeviceConfigError> {
if self
.base_device_definitions
.iter()
.any(|(_, x)| x.id() == device_definition.base_id().unwrap_or_default())
{
self
.user_device_definitions
.insert(identifier.clone(), device_definition.clone());
Ok(self)
} else {
error!(
"Cannot find protocol with base id {:?} for user id {}",
device_definition.base_id(),
device_definition.id()
);
Err(ButtplugDeviceConfigError::BaseIdNotFound(
device_definition.id(),
))
}
}
pub fn simulated_devices(&mut self, devices: Vec<SimulatedDeviceConfigEntry>) -> &mut Self {
self.simulated_devices = devices;
self
}
pub fn add_simulated_devices(&mut self, devices: Vec<SimulatedDeviceConfigEntry>) -> &mut Self {
self.simulated_devices.extend(devices);
self
}
pub fn finish(&mut self) -> Result<DeviceConfigurationManager, ButtplugDeviceError> {
let mut attribute_tree_map = HashMap::new();
for (ident, attr) in &self.base_device_definitions {
attribute_tree_map.insert(ident.clone(), attr.clone());
}
let user_attribute_tree_map = DashMap::new();
for kv in &self.user_device_definitions {
user_attribute_tree_map.insert(kv.key().clone(), kv.value().clone());
}
if !self.simulated_devices.is_empty() {
let valid_archetypes: std::collections::HashSet<String> = self
.base_communication_specifiers
.get("simulated")
.into_iter()
.flat_map(|specifiers| specifiers.iter())
.filter_map(|spec| {
if let ProtocolCommunicationSpecifier::Simulated(sim) = spec {
Some(sim.names().iter().cloned())
} else {
None
}
})
.flatten()
.collect();
let mut seen_addresses = std::collections::HashSet::new();
for device in &self.simulated_devices {
if !valid_archetypes.contains(&device.identifier) {
return Err(ButtplugDeviceError::DeviceConfigurationError(format!(
"Invalid simulated device archetype '{}'. Valid archetypes: {:?}",
device.identifier, valid_archetypes
)));
}
if !seen_addresses.insert(&device.address) {
return Err(ButtplugDeviceError::DeviceConfigurationError(format!(
"Duplicate simulated device address '{}' for archetype '{}'",
device.address, device.identifier
)));
}
}
}
Ok(DeviceConfigurationManager {
base_communication_specifiers: self.base_communication_specifiers.clone(),
user_communication_specifiers: self.user_communication_specifiers.clone(),
base_device_definitions: attribute_tree_map,
user_device_definitions: user_attribute_tree_map,
simulated_devices_store: RwLock::new(self.simulated_devices.clone()),
})
}
}
#[derive(Getters)]
#[getset(get = "pub(crate)")]
pub struct DeviceConfigurationManager {
#[getset(get = "pub")]
base_communication_specifiers: HashMap<String, Vec<ProtocolCommunicationSpecifier>>,
#[getset(get = "pub")]
base_device_definitions: HashMap<BaseDeviceIdentifier, Arc<ServerDeviceDefinition>>,
#[getset(get = "pub")]
user_communication_specifiers: DashMap<String, Vec<ProtocolCommunicationSpecifier>>,
#[getset(get = "pub")]
user_device_definitions: DashMap<UserDeviceIdentifier, ServerDeviceDefinition>,
simulated_devices_store: RwLock<Vec<SimulatedDeviceConfigEntry>>,
}
impl Debug for DeviceConfigurationManager {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DeviceConfigurationManager").finish()
}
}
impl Default for DeviceConfigurationManager {
fn default() -> Self {
DeviceConfigurationManagerBuilder::default()
.finish()
.expect("Default creation of a DCM should always work.")
}
}
impl DeviceConfigurationManager {
pub fn new(
base_communication_specifiers: HashMap<String, Vec<ProtocolCommunicationSpecifier>>,
base_device_definitions: HashMap<BaseDeviceIdentifier, Arc<ServerDeviceDefinition>>,
) -> Self {
Self {
base_communication_specifiers,
user_communication_specifiers: DashMap::new(),
base_device_definitions,
user_device_definitions: DashMap::new(),
simulated_devices_store: RwLock::new(Vec::new()),
}
}
pub fn simulated_devices(&self) -> Vec<SimulatedDeviceConfigEntry> {
self
.simulated_devices_store
.read()
.expect("Simulated device config lock should not be poisoned")
.clone()
}
fn valid_simulated_archetypes(&self) -> std::collections::HashSet<String> {
self
.base_communication_specifiers
.get("simulated")
.into_iter()
.flat_map(|specifiers| specifiers.iter())
.filter_map(|spec| {
if let ProtocolCommunicationSpecifier::Simulated(sim) = spec {
Some(sim.names().iter().cloned())
} else {
None
}
})
.flatten()
.collect()
}
pub fn add_simulated_device(
&self,
device: SimulatedDeviceConfigEntry,
) -> Result<(), ButtplugDeviceError> {
let valid_archetypes = self.valid_simulated_archetypes();
if !valid_archetypes.contains(&device.identifier) {
return Err(ButtplugDeviceError::DeviceConfigurationError(format!(
"Invalid simulated device archetype '{}'. Valid archetypes: {:?}",
device.identifier, valid_archetypes
)));
}
let mut simulated_devices = self
.simulated_devices_store
.write()
.expect("Simulated device config lock should not be poisoned");
if simulated_devices
.iter()
.any(|existing| existing.address == device.address)
{
return Err(ButtplugDeviceError::DeviceConfigurationError(format!(
"Duplicate simulated device address '{}' for archetype '{}'",
device.address, device.identifier
)));
}
simulated_devices.push(device);
Ok(())
}
pub fn remove_simulated_device(&self, address: &str) {
let mut simulated_devices = self
.simulated_devices_store
.write()
.expect("Simulated device config lock should not be poisoned");
simulated_devices.retain(|device| device.address != address);
self.user_device_definitions.retain(|identifier, _| {
identifier.protocol() != "simulated" || identifier.address() != address
});
}
pub fn add_user_communication_specifier(
&self,
protocol: &str,
specifier: &ProtocolCommunicationSpecifier,
) -> Result<(), ButtplugDeviceError> {
self
.user_communication_specifiers
.entry(protocol.to_owned())
.or_default()
.push(specifier.clone());
Ok(())
}
pub fn remove_user_communication_specifier(
&self,
protocol: &str,
specifier: &ProtocolCommunicationSpecifier,
) {
if let Some(mut specifiers) = self.user_communication_specifiers.get_mut(protocol) {
let specifier_vec = specifiers.value_mut();
*specifier_vec = specifier_vec
.iter()
.filter(|s| *specifier != **s)
.cloned()
.collect();
}
}
pub fn add_user_device_definition(
&self,
identifier: &UserDeviceIdentifier,
definition: &ServerDeviceDefinition,
) {
self
.user_device_definitions
.insert(identifier.clone(), definition.clone());
}
pub fn remove_user_device_definition(&self, identifier: &UserDeviceIdentifier) {
self.user_device_definitions.remove(identifier);
}
pub fn address_allowed(&self, address: &str) -> bool {
if self
.user_device_definitions
.iter()
.any(|kv| kv.key().address() == address && kv.value().deny())
{
info!(
"Device {} denied by configuration, not connecting.",
address
);
false
} else if self
.user_device_definitions
.iter()
.any(|kv| kv.value().allow())
&& !self
.user_device_definitions
.iter()
.any(|kv| kv.key().address() == address && kv.value().allow())
{
info!(
"Device {} not on allow list and allow list not empty, not connecting.",
address
);
false
} else {
true
}
}
fn device_index(&self, identifier: &UserDeviceIdentifier) -> u32 {
if let Some(config) = self.user_device_definitions.get(identifier) {
let index = config.index();
debug!("Found index {index} for device {identifier:?}");
return index;
}
let current_indexes: Vec<u32> = self
.user_device_definitions
.iter()
.map(|x| x.index())
.collect();
let mut index = 0;
while current_indexes.contains(&index) {
index += 1;
}
debug!("Generating and assigning index {index:?} for device {identifier:?}");
index
}
pub fn device_definition_with_selection(
&self,
identifier: &UserDeviceIdentifier,
selection: &crate::DeviceDefinitionSelection,
) -> Result<ServerDeviceDefinition, ButtplugDeviceConfigError> {
if selection.protocol() != identifier.protocol() {
return Err(ButtplugDeviceConfigError::DeviceSelectionInvalid(format!(
"selection protocol '{}' does not match identifier protocol '{}'",
selection.protocol(),
identifier.protocol()
)));
}
let base_key = BaseDeviceIdentifier::new(selection.protocol(), selection.base_identifier());
let base_definition = self
.base_device_definitions
.get(&base_key)
.ok_or_else(|| {
ButtplugDeviceConfigError::DeviceSelectionInvalid(format!(
"base definition {:?} not found for protocol '{}'",
base_key,
selection.protocol()
))
})?
.clone();
if let Some(old_definition) = self
.user_device_definitions
.get(identifier)
.map(|x| x.clone())
{
let mut builder =
ServerDeviceDefinitionBuilder::from_base(&base_definition, old_definition.id(), false);
builder
.name(selection.canonical_name())
.display_name(old_definition.display_name())
.allow(old_definition.allow())
.deny(old_definition.deny())
.message_gap_ms(old_definition.message_gap_ms())
.index(old_definition.index());
for base_feature in base_definition.features().values() {
let feature = if let Some(old_feature) = old_definition
.features()
.values()
.find(|x| x.base_id == Some(base_feature.id()))
{
let mut feature =
crate::device_config_file::ConfigUserDeviceFeature::try_from(old_feature)?
.with_base_feature(base_feature)?;
if !old_feature.description.is_empty() {
feature.description = old_feature.description.clone();
}
feature
} else {
base_feature.as_new_user_feature()
};
builder.add_feature(&feature);
}
let rebuilt = builder.finish();
self
.user_device_definitions
.insert(identifier.clone(), rebuilt.clone());
Ok(rebuilt)
} else {
let mut builder =
ServerDeviceDefinitionBuilder::from_base(&base_definition, Uuid::new_v4(), true);
builder
.name(selection.canonical_name())
.index(self.device_index(identifier));
let definition = builder.finish();
self
.user_device_definitions
.insert(identifier.clone(), definition.clone());
Ok(definition)
}
}
pub fn device_definition(
&self,
identifier: &UserDeviceIdentifier,
) -> Option<ServerDeviceDefinition> {
let features = if let Some(definition) = self.user_device_definitions.get(identifier) {
debug!("User device config found for {:?}", identifier);
definition.clone()
} else if let Some(definition) = self.base_device_definitions.get(&BaseDeviceIdentifier::new(
identifier.protocol(),
identifier.identifier(),
)) {
debug!(
"Protocol + Identifier device config found for {:?}, creating new user device from configuration",
identifier
);
let mut builder = ServerDeviceDefinitionBuilder::from_base(definition, Uuid::new_v4(), true);
builder.index(self.device_index(identifier));
self.apply_simulated_display_name(&mut builder, identifier);
builder.finish()
} else if let Some(definition) = self
.base_device_definitions
.get(&BaseDeviceIdentifier::new(identifier.protocol(), &None))
{
debug!(
"Protocol device config found for {:?}, creating new user device from protocol defaults",
identifier
);
let mut builder = ServerDeviceDefinitionBuilder::from_base(definition, Uuid::new_v4(), true);
builder.index(self.device_index(identifier));
self.apply_simulated_display_name(&mut builder, identifier);
builder.finish()
} else {
return None;
};
if self.user_device_definitions.get(identifier).is_none() {
self
.user_device_definitions
.insert(identifier.clone(), features.clone());
}
Some(features)
}
fn apply_simulated_display_name(
&self,
builder: &mut ServerDeviceDefinitionBuilder,
identifier: &UserDeviceIdentifier,
) {
if let Some(entry) = self
.simulated_devices_store
.read()
.expect("Simulated device config lock should not be poisoned")
.iter()
.find(|d| d.address() == identifier.address())
{
builder.display_name(entry.display_name());
}
}
pub fn available_simulated_archetypes(&self) -> Vec<SimulatedDeviceArchetype> {
self
.base_device_definitions
.iter()
.filter(|(ident, _)| ident.protocol() == "simulated" && ident.identifier().is_some())
.map(|(ident, def)| {
let identifier = ident
.identifier()
.as_ref()
.expect("filtered for Some above")
.clone();
let output_features = def
.features()
.values()
.filter(|f| !f.output.is_empty())
.map(|f| {
let output_type = f
.output
.iter()
.next()
.map(|output| output.output_type().to_string())
.unwrap_or_default();
SimulatedDeviceFeatureSummary {
description: f.description.clone(),
output_type,
index: f.index(),
}
})
.collect();
SimulatedDeviceArchetype {
identifier,
display_name: def.name().clone(),
output_features,
}
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::load_protocol_configs;
#[test]
fn test_add_simulated_device_validates_archetype_and_address() {
let dcm = load_protocol_configs(&None, &None, false)
.expect("Should load base configs")
.finish()
.expect("Should build DCM");
let entry = SimulatedDeviceConfigEntry::new("simulated-1vibe", None);
let duplicate = entry.clone();
dcm
.add_simulated_device(entry)
.expect("Valid simulated archetype should add");
assert_eq!(dcm.simulated_devices().len(), 1);
let duplicate_result = dcm.add_simulated_device(duplicate);
assert!(duplicate_result.is_err());
let invalid_result = dcm.add_simulated_device(SimulatedDeviceConfigEntry::new(
"not-a-simulated-device",
None,
));
assert!(invalid_result.is_err());
}
#[test]
fn test_remove_simulated_device_removes_matching_user_definition() {
let dcm = load_protocol_configs(&None, &None, false)
.expect("Should load base configs")
.finish()
.expect("Should build DCM");
let entry = SimulatedDeviceConfigEntry::new("simulated-1vibe", None);
let address = entry.address.clone();
let identifier =
UserDeviceIdentifier::new(&address, "simulated", &Some(entry.identifier.clone()));
dcm
.add_simulated_device(entry)
.expect("Valid simulated archetype should add");
dcm
.device_definition(&identifier)
.expect("Simulated device definition should resolve");
assert!(dcm.user_device_definitions().contains_key(&identifier));
dcm.remove_simulated_device(&address);
assert!(dcm.simulated_devices().is_empty());
assert!(!dcm.user_device_definitions().contains_key(&identifier));
}
}