Skip to content

Commit

Permalink
Cleaned up some parts before beta
Browse files Browse the repository at this point in the history
  • Loading branch information
digital-pet committed Dec 10, 2021
1 parent 99c0c37 commit a31347d
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 48 deletions.
33 changes: 25 additions & 8 deletions AetherSenseRedux/Device.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Threading.Tasks;
using AetherSenseRedux.Pattern;
using Buttplug;
using Dalamud.Logging;

namespace AetherSenseRedux
{
Expand All @@ -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();
}
}

Expand All @@ -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<double> intensities = new List<double>();
DateTime t = DateTime.UtcNow;
Expand Down Expand Up @@ -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);
Expand All @@ -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;
Expand Down
6 changes: 3 additions & 3 deletions AetherSenseRedux/Pattern/PatternFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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));
}
}

Expand Down
81 changes: 45 additions & 36 deletions AetherSenseRedux/Plugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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<Device> DevicePool;
Expand Down Expand Up @@ -84,6 +84,7 @@ public void Dispose()
CommandManager.RemoveHandler(commandName);
}

// EVENT HANDLERS
private void OnDeviceAdded(object? sender, DeviceAddedEventArgs e)
{

Expand All @@ -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();

}

Expand All @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -229,6 +251,7 @@ private void InitTriggers()
ChatGui.ChatMessage += OnChatReceived;
PluginLog.Debug("Triggers created");
}

private void DestroyTriggers()
{
foreach (ChatTrigger t in ChatTriggerPool)
Expand All @@ -240,6 +263,7 @@ private void DestroyTriggers()
ChatTriggerPool.Clear();
PluginLog.Debug("Triggers destroyed.");
}

public void Start()
{
Running = true;
Expand All @@ -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();
}

Expand All @@ -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
Expand All @@ -295,5 +303,6 @@ private void DrawConfigUI()
{
PluginUi.SettingsVisible = true;
}
// END UI FUNCTIONS
}
}
2 changes: 1 addition & 1 deletion AetherSenseRedux/Trigger/ChatTrigger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ private void OnTrigger()
{
lock (device.Patterns)
{
device.Patterns.Add(PatternFactory.GetPatternFromString(Pattern, PatternSettings));
device.Patterns.Add(PatternFactory.GetPatternFromObject(PatternSettings));
}
}

Expand Down

0 comments on commit a31347d

Please sign in to comment.