MetalButtplug/Utils/ButtplugManager.cs

60 lines
2 KiB
C#
Raw Normal View History

using System;
2024-05-20 19:30:27 +00:00
using System.Linq;
using System.Threading.Tasks;
using Buttplug.Client;
using Buttplug.Client.Connectors.WebsocketConnector;
namespace MetalButtplug.Utils;
internal static class ButtplugManager {
static ButtplugClient client;
public async static void Init() {
ButtplugManager.client = new ButtplugClient("Metal: Hellsinger");
Plugin.Log.LogInfo("Attempting buttplug connection");
try {
var connector = new ButtplugWebsocketConnector(new Uri("ws://localhost:12345"));
await client.ConnectAsync(connector);
Plugin.Log.LogInfo("Connected to buttplug server!");
} catch(Exception ex) {
Plugin.Log.LogWarning($"Failed to connect: {ex.Message}\nDisabling buttplug integration - Is Intiface running?");
return;
}
client.DeviceAdded += OnDeviceAdd;
client.DeviceRemoved += OnDeviceRemove;
Plugin.Log.LogInfo($"Found devices:");
foreach (ButtplugClientDevice device in client.Devices) {
2024-05-20 19:30:27 +00:00
Plugin.Log.LogInfo($"- {device.Name}");
}
}
private static void OnDeviceAdd(object sender, DeviceAddedEventArgs e) {
2024-05-20 19:30:27 +00:00
Plugin.Log.LogInfo($"Device added: {e.Device.Name}");
}
private static void OnDeviceRemove(object sender, DeviceRemovedEventArgs e) {
2024-05-20 19:30:27 +00:00
Plugin.Log.LogInfo($"Device removed: {e.Device.Name}");
}
public async static void Vibrate(float strength, int duration) {
if (!client.Connected) return;
if (strength > 1) strength = 1;
if (strength <= 0) return; // No need to waste time if we're not going to vibrate anyway
Task[] tasks = client.Devices
.Where((device) => device.VibrateAttributes.Count > 0)
.Select(async (device) => {
await device.VibrateAsync(strength);
await Task.Delay(duration);
await device.Stop();
})
.ToArray();
await Task.WhenAll(tasks);
}
}