-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPlugManager.cs
196 lines (182 loc) · 6.39 KB
/
PlugManager.cs
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
//using Buttplug;
using ButtplugManaged;
using System;
using System.IO;
using System.Threading.Tasks;
using UnityEngine;
namespace GoodVibes
{
public static class AsyncFAF
{
public static async void FireAndForget(this Task t, Action<string> logging)
{
try
{
await t;
}
catch (Exception e)
{
logging?.Invoke($"FAF Exception: {e.GetType()}; {e.Message}");
if (e.InnerException != null) logging?.Invoke($" Inner: {e.InnerException.GetType()}; {e.InnerException.Message}");
}
}
}
public class PlugManager
{
private ButtplugWebsocketConnectorOptions _connector;
//private int _retries;
internal float _currentPower = 0;
public ButtplugClient Client { get; private set; }
public string Address { get; init; }
public int Port { get; init; }
public int RetryAmount { get; init; }
public event Action<string> LogMessage;
private async void Log(string s)
{
for (int logAttempts = 0; logAttempts < 5;)
{
try
{
LogMessage?.Invoke(s);
return;
}
catch (IOException)
{
await Task.Delay(100);
logAttempts++;
}
}
}
private void SetupClient()
{
Client = new ButtplugClient("Plug Control");
_triedToInitialize = false;
Client.DeviceAdded += OnDeviceAdded;
Client.DeviceRemoved += OnDeviceRemoved;
Client.ServerDisconnect += ClientOnServerDisconnect;
Client.ErrorReceived += ClientOnErrorReceived;
Client.PingTimeout += ClientOnPingTimeout;
}
private void OnDeviceAdded(object sender, DeviceAddedEventArgs e)
{
Log($"Device Connected: {e.Device.Name}");
}
private void OnDeviceRemoved(object sender, DeviceRemovedEventArgs e)
{
Log($"Device Disconnected: {e.Device.Name}");
}
bool _tryingToReconnect = false;
private async void ClientOnServerDisconnect(object sender, EventArgs e)
{
if (_tryingToReconnect) return;
Log("Disconnected from server.");
_tryingToReconnect = true;
for (int _retries = 0; _retries < RetryAmount; _retries++)
{
Log($"Reconnecting... (Attempt {_retries + 1} of {RetryAmount})");
SetupClient();
bool success = await TryConnect();
if (success) return;
Log("Trying again in 5 seconds.");
await Task.Delay(TimeSpan.FromSeconds(5));
}
_tryingToReconnect = false;
Log("Could not reconnect to server.");
}
private void ClientOnErrorReceived(object sender, ButtplugExceptionEventArgs e)
{
Log($"Received an error: {e.Exception.Message}");
}
private void ClientOnPingTimeout(object sender, EventArgs e)
{
Log("Server ping timed out.");
}
private async Task UpdatePowerLevels()
{
Log($"Updating power level to {_currentPower*100}%");
if (Client == null)
{
Log($"Intiface Client is null - cannot update power. Try restarting the game.");
if (_triedToInitialize) SetupClient();
if (!await Initialize()) return;
}
if (!Client.Connected && Client.Devices.Length == 0 && false)
{
Log($"Intiface Client is disconnected - Is the server running?");
if (!await TryConnect())
{
Log($"Failed to connect. Resetting client to reinitialize");
SetupClient();
if (await Initialize()) Log("Reinitialized!");
else return;
}
else Log("Reconnected!");
}
else if (Client.Devices.Length == 0)
{
Log($"Intiface Client connected, but no devices are connected.");
}
foreach (var plug in Client?.Devices)
{
plug?.SendVibrateCmd(_currentPower);
}
}
private async Task<bool> TryScanning()
{
Log("Starting to scan for devices.");
try
{
await Client.StartScanningAsync();
_triedToInitialize = false;
}
catch (ButtplugException ex)
{
Log($"Failed to start scanning for devices: {ex.InnerException?.Message}");
return false;
}
return true;
}
private async Task<bool> TryConnect()
{
try
{
Log("Connecting to the server...");
await Client.ConnectAsync(_connector);
Log("Connected to server.");
_tryingToReconnect = false;
return await TryScanning();
}
catch (ButtplugConnectorException e)
{
Log($"Could not connect to the server: {e.InnerException?.Message}");
return false;
}
catch (ButtplugHandshakeException e)
{
Log($"There was an error performing the handshake with the server: {e.InnerException?.Message}");
return false;
}
}
internal bool _triedToInitialize = false;
public async Task<bool> Initialize()
{
if (_triedToInitialize) return false;
_triedToInitialize = true;
_connector = new ButtplugWebsocketConnectorOptions(new Uri($"ws://{Address}:{Port}/buttplug"));
SetupClient();
var success = await TryConnect();
if (!success)
{
Log("Could not connect to the server.");
return false;
}
return true;
}
public void SetPowerLevel(float level)
{
//if (level == _currentPower) return;
_currentPower = Mathf.Clamp01(level);
Task.Factory.StartNew(() => UpdatePowerLevels().FireAndForget(LogMessage));
}
}
}