From a31347dea88df7930761cd0dd8daf38fbdb42b86 Mon Sep 17 00:00:00 2001 From: Tama Gotchi <47679051+digital-pet@users.noreply.github.com> Date: Fri, 10 Dec 2021 11:41:02 -0500 Subject: [PATCH] Cleaned up some parts before beta --- AetherSenseRedux/Device.cs | 33 ++++++--- AetherSenseRedux/Pattern/PatternFactory.cs | 6 +- AetherSenseRedux/Plugin.cs | 81 ++++++++++++---------- AetherSenseRedux/Trigger/ChatTrigger.cs | 2 +- 4 files changed, 74 insertions(+), 48 deletions(-) diff --git a/AetherSenseRedux/Device.cs b/AetherSenseRedux/Device.cs index ab45305..7fc3d67 100644 --- a/AetherSenseRedux/Device.cs +++ b/AetherSenseRedux/Device.cs @@ -4,6 +4,7 @@ using System.Threading.Tasks; using AetherSenseRedux.Pattern; using Buttplug; +using Dalamud.Logging; namespace AetherSenseRedux { @@ -23,12 +24,17 @@ public Device(ButtplugClientDevice clientDevice) _active = true; } - public async Task Run() + public void Start() + { + Task.Run(MainLoop).ConfigureAwait(false); + } + + public async Task MainLoop() { while (_active) { - await OnTick(); - await Task.Delay(10); + OnTick(); + await Task.Yield(); } } @@ -37,11 +43,11 @@ public void Stop() _active = false; Patterns.Clear(); - var t = Task.Run(() => WriteAsync(0)); + var t = Task.Run(() => Write(0)); t.Wait(); } - private async Task OnTick() + private void OnTick() { List intensities = new List(); DateTime t = DateTime.UtcNow; @@ -71,10 +77,10 @@ private async Task OnTick() //TODO: Allow different merge modes besides average double intensity = (intensities.Any()) ? intensities.Average() : 0; - await WriteAsync(intensity); + Write(intensity); } - private async Task WriteAsync(double intensity) + private void Write(double intensity) { // clamp intensity before comparing to reduce unnecessary writes to device double clampedIntensity = Clamp(intensity, 0, 1); @@ -85,9 +91,20 @@ private async Task WriteAsync(double intensity) } _lastIntensity = clampedIntensity; + + // If we don't wait on this, bad things happen on Linux and disappointing things happen on Windows, especially with slow BLE adapters. + try + { + var t = ClientDevice.SendVibrateCmd(clampedIntensity); + t.Wait(); + } catch (Exception) + { + // Connecting to an intiface server on Linux will spam the log with bluez errors + // so we just ignore all exceptions from this statement. Good? Probably not. Necessary? Yes. + } - await ClientDevice.SendVibrateCmd(clampedIntensity); } + private static double Clamp(double value, double min, double max) { return (value < min) ? min : (value > max) ? max : value; diff --git a/AetherSenseRedux/Pattern/PatternFactory.cs b/AetherSenseRedux/Pattern/PatternFactory.cs index 2581595..af27174 100644 --- a/AetherSenseRedux/Pattern/PatternFactory.cs +++ b/AetherSenseRedux/Pattern/PatternFactory.cs @@ -8,9 +8,9 @@ namespace AetherSenseRedux.Pattern { internal class PatternFactory { - public static IPattern GetPatternFromString(string name, PatternConfig settings) + public static IPattern GetPatternFromObject(PatternConfig settings) { - switch (name) + switch (settings.Type) { case "Constant": return new ConstantPattern((ConstantPatternConfig)settings); @@ -21,7 +21,7 @@ public static IPattern GetPatternFromString(string name, PatternConfig settings) case "Square": return new SquarePattern((SquarePatternConfig)settings); default: - throw new ArgumentException(String.Format("Invalid pattern {0} specified",name)); + throw new ArgumentException(String.Format("Invalid pattern {0} specified", settings.Type)); } } diff --git a/AetherSenseRedux/Plugin.cs b/AetherSenseRedux/Plugin.cs index 138728c..7f3c3e5 100644 --- a/AetherSenseRedux/Plugin.cs +++ b/AetherSenseRedux/Plugin.cs @@ -22,6 +22,7 @@ namespace AetherSenseRedux public sealed class Plugin : IDalamudPlugin { public string Name => "AetherSense Redux"; + public bool Running = false; private const string commandName = "/asr"; @@ -32,7 +33,6 @@ public sealed class Plugin : IDalamudPlugin [PluginService] private ChatGui ChatGui { get; init; } = null!; private PluginUI PluginUi { get; init; } - private ButtplugClient Buttplug; private List DevicePool; @@ -84,6 +84,7 @@ public void Dispose() CommandManager.RemoveHandler(commandName); } + // EVENT HANDLERS private void OnDeviceAdded(object? sender, DeviceAddedEventArgs e) { @@ -93,7 +94,7 @@ private void OnDeviceAdded(object? sender, DeviceAddedEventArgs e) if (!Configuration.SeenDevices.Contains(newDevice.Name)){ Configuration.SeenDevices.Add(newDevice.Name); } - Task.Run(newDevice.Run).ConfigureAwait(false); + newDevice.Start(); } @@ -119,22 +120,36 @@ private void OnDeviceRemoved(object? sender, DeviceRemovedEventArgs e) } } } - foreach (Device device in toRemove) + foreach (Device device in toRemove) + { + lock (this.DevicePool) { - lock (this.DevicePool) - { - this.DevicePool.Remove(device); - } - + this.DevicePool.Remove(device); } + + } } - // Instead of constant async scanning, it may make sense to simply scan when a command is issued private void OnScanComplete(object? sender, EventArgs e) { Task.Run(DoScan).ConfigureAwait(false); } + private void OnChatReceived(XivChatType type, uint senderId, ref SeString sender, ref SeString message, ref bool isHandled) + { + ChatMessage chatMessage = new ChatMessage(type, senderId, ref sender, ref message, ref isHandled); + foreach (ChatTrigger t in ChatTriggerPool) + { + t.Queue(chatMessage); + } + if (Configuration.LogChat) + { + PluginLog.Debug(chatMessage.ToString()); + } + } + // END EVENT HANDLERS + + // SOME FUNCTIONS THAT DO THINGS public void DoPatternTest(dynamic patternConfig) { if (!Buttplug.Connected) @@ -146,27 +161,29 @@ public void DoPatternTest(dynamic patternConfig) { lock (device.Patterns) { - device.Patterns.Add(PatternFactory.GetPatternFromString(patternConfig.Type,patternConfig)); + device.Patterns.Add(PatternFactory.GetPatternFromObject(patternConfig)); } } } } - private void OnChatReceived(XivChatType type, uint senderId, ref SeString sender, ref SeString message, ref bool isHandled) + private async Task DoScan() { - ChatMessage chatMessage = new ChatMessage(type, senderId, ref sender, ref message, ref isHandled); - foreach (ChatTrigger t in ChatTriggerPool) + await Task.Delay(1000); + try { - t.Queue(chatMessage); + await Buttplug.StartScanningAsync(); } - if (Configuration.LogChat) + catch (Exception ex) { - PluginLog.Debug(chatMessage.ToString()); + PluginLog.Error(ex, "Asynchronous scanning failed."); } } + // END SOME FUNCTIONS THAT DO THINGS + + // START AND STOP FUNCTIONS private void InitButtplug() { - //TODO: connect to buttplug and start scanning for devices if (!Buttplug.Connected) { try @@ -202,10 +219,15 @@ private void DestroyButtplug() } catch (Exception ex) { - PluginLog.Error(ex, "Buttplug failed to connect"); + PluginLog.Error(ex, "Buttplug failed to disconnect, reinitalizing ButtplugClient."); + Buttplug = new ButtplugClient("AetherSense Redux"); + Buttplug.DeviceAdded += OnDeviceAdded; + Buttplug.DeviceRemoved += OnDeviceRemoved; + Buttplug.ScanningFinished += OnScanComplete; } PluginLog.Debug("Buttplug destroyed."); } + private void InitTriggers() { foreach (var d in Configuration.Triggers) @@ -229,6 +251,7 @@ private void InitTriggers() ChatGui.ChatMessage += OnChatReceived; PluginLog.Debug("Triggers created"); } + private void DestroyTriggers() { foreach (ChatTrigger t in ChatTriggerPool) @@ -240,6 +263,7 @@ private void DestroyTriggers() ChatTriggerPool.Clear(); PluginLog.Debug("Triggers destroyed."); } + public void Start() { Running = true; @@ -250,11 +274,6 @@ public void Start() public void Restart() { DestroyTriggers(); - - // while this works, a cleaner restart that doesn't drop the intiface connection may be in order - //Stop(); - //Start(); - InitTriggers(); } @@ -266,20 +285,9 @@ public void Stop() } + // END START AND STOP FUNCTIONS - private async Task DoScan() - { - await Task.Delay(1000); - try - { - await Buttplug.StartScanningAsync(); - } - catch (Exception ex) - { - PluginLog.Error(ex, "Asynchronous scanning failed."); - } - } - + // UI FUNCTIONS private void OnShowUI(string command, string args) { // in response to the slash command, just display our main ui @@ -295,5 +303,6 @@ private void DrawConfigUI() { PluginUi.SettingsVisible = true; } + // END UI FUNCTIONS } } diff --git a/AetherSenseRedux/Trigger/ChatTrigger.cs b/AetherSenseRedux/Trigger/ChatTrigger.cs index 75a6d16..3980332 100644 --- a/AetherSenseRedux/Trigger/ChatTrigger.cs +++ b/AetherSenseRedux/Trigger/ChatTrigger.cs @@ -82,7 +82,7 @@ private void OnTrigger() { lock (device.Patterns) { - device.Patterns.Add(PatternFactory.GetPatternFromString(Pattern, PatternSettings)); + device.Patterns.Add(PatternFactory.GetPatternFromObject(PatternSettings)); } }