-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
502 lines (447 loc) · 20.6 KB
/
Program.cs
File metadata and controls
502 lines (447 loc) · 20.6 KB
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
using Buttplug.Client;
using Buttplug.Core;
using Buttplug.Core.Messages;
using Buttplug.Client.Connectors.WebsocketConnector;
using LanguageExt;
using static LanguageExt.Prelude;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
namespace skybutt
{
internal class Program
{
private static async Task WaitForKey()
{
Console.WriteLine("Press any key to continue.");
while (!Console.KeyAvailable)
{
await Task.Delay(1);
}
Console.ReadKey(true);
}
private static async Task RunExample(string logFile)
{
// Now that we've seen all of the different parts of Buttplug, let's
// put them together in a small program.
//
// This program will:
// - Create an embedded (or possibly websocket) connector
// - Scan, this time using real Managers, so we'll see devices
// (assuming you have them hooked up)
// - List the connected devices for the user
// - Let the user select a device, and trigger some sort of event on
// that device (vibration, thrusting, etc...).
// As usual, we start off with our connector setup. We really don't
// need access to the connector this time, so we can just pass the
// created connector directly to the client.
//var client = new ButtplugClient("skybutt client",
// new ButtplugEmbeddedConnector("skybutt server"));
// If you want to use a websocket client and talk to a websocket
// server instead, uncomment the following line and comment the one
// above out. Note you will need to turn off TLS/SSL on the server.
var client = new ButtplugClient("skybutt client", new
ButtplugWebsocketConnector(new Uri("ws://localhost:12345/buttplug")));
await client.ConnectAsync();
// At this point, if you want to see everything that's happening,
// uncomment this block to turn on logging. Warning, it might be
// pretty spammy.
// void HandleLogMessage(object aObj, LogEventArgs aArgs) {
// Console.WriteLine($"LOG: {aArgs.Message.LogMessage}"); }
// client.Log += HandleLogMessage; await client.RequestLogAsync(ButtplugLogLevel.Debug);
// Now we scan for devices. Since we didn't add any Subtype Managers
// yet, this will go out and find them for us. They'll be reported in
// the logs as they are found.
//
// We'll scan for devices, and print any time we find one.
void HandleDeviceAdded(object aObj, DeviceAddedEventArgs aArgs)
{
Console.WriteLine($"Device connected: {aArgs.Device.Name}");
}
client.DeviceAdded += HandleDeviceAdded;
void HandleDeviceRemoved(object aObj, DeviceRemovedEventArgs aArgs)
{
Console.WriteLine($"Device connected: {aArgs.Device.Name}");
}
client.DeviceRemoved += HandleDeviceRemoved;
// The structure here is gonna get a little weird now, because I'm
// using method scoped functions. We'll be defining our scanning
// function first, then running it just to find any devices up front.
// Then we'll define our command sender. Finally, with all of that
// done, we'll end up in our main menu
// Here's the scanning part. Pretty simple, just scan until the user
// hits a button. Any time a new device is found, print it so the
// user knows we found it.
async Task ScanForDevices()
{
Console.WriteLine("Scanning for devices until key is pressed.");
Console.WriteLine("Found devices will be printed to console.");
await client.StartScanningAsync();
await WaitForKey();
// Stop scanning now, 'cause we don't want new devices popping up anymore.
await client.StopScanningAsync();
}
// Scan for devices before we get to the main menu.
await ScanForDevices();
// Now we define the device control menus. After we've scanned for
// devices, the user can use this menu to select a device, then
// select an action for that device to take.
async Task ControlDevice()
{
// Controlling a device has 2 steps: selecting the device to
// control, and choosing which command to send. We'll just list
// the devices the client has available, then search the device
// message capabilities once that's done to figure out what we
// can send. Note that this is using the Device Index, which is
// assigned by the device manager and may not be sequential
// (which is why we can't just use an array index).
// Of course, if we don't have any devices yet, that's not gonna work.
if (!client.Devices.Any())
{
Console.WriteLine("No devices available. Please scan for a device.");
return;
}
var options = new List<uint>();
foreach (var dev in client.Devices)
{
Console.WriteLine($"{dev.Index}. {dev.Name}");
options.Add(dev.Index);
}
uint vaginalDeviceChoice;
if (options.Length() == 1)
{
vaginalDeviceChoice = client.Devices.Head().Index;
} else
{
Console.WriteLine("Choose vaginal device: ");
if (!uint.TryParse(Console.ReadLine(), out vaginalDeviceChoice) ||
!options.Contains(vaginalDeviceChoice))
{
Console.WriteLine("Invalid choice");
return;
}
}
uint analDeviceChoice;
if (options.Length() == 1)
{
analDeviceChoice = client.Devices.Head().Index;
} else
{
Console.WriteLine("Choose anal device: ");
if (!uint.TryParse(Console.ReadLine(), out analDeviceChoice) ||
!options.Contains(analDeviceChoice))
{
Console.WriteLine("Invalid choice");
return;
}
}
var vaginalDevice = client.Devices.First(dev => dev.Index == vaginalDeviceChoice);
foreach (var m in vaginalDevice.AllowedMessages)
{
Console.WriteLine($"Device message: {m.Key} -> {m.Value}");
}
var analDevice = client.Devices.First(dev => dev.Index == analDeviceChoice);
foreach (var m in analDevice.AllowedMessages)
{
Console.WriteLine($"Device message: {m.Key} -> {m.Value}");
}
Console.WriteLine("Watching Controller Rumble log file");
await WatchLogFileAsync(logFile, client, vaginalDevice, analDevice);
}
async Task ControlDeviceRandom()
{
// Controlling a device has 2 steps: selecting the device to
// control, and choosing which command to send. We'll just list
// the devices the client has available, then search the device
// message capabilities once that's done to figure out what we
// can send. Note that this is using the Device Index, which is
// assigned by the device manager and may not be sequential
// (which is why we can't just use an array index).
// Of course, if we don't have any devices yet, that's not gonna work.
if (!client.Devices.Any())
{
Console.WriteLine("No devices available. Please scan for a device.");
return;
}
var options = new List<uint>();
foreach (var dev in client.Devices)
{
Console.WriteLine($"{dev.Index}. {dev.Name}");
options.Add(dev.Index);
}
uint deviceChoice;
if (options.Length() == 1)
{
deviceChoice = client.Devices.Head().Index;
} else
{
Console.WriteLine("Choose a device: ");
if (!uint.TryParse(Console.ReadLine(), out deviceChoice) ||
!options.Contains(deviceChoice))
{
Console.WriteLine("Invalid choice");
return;
}
}
var device = client.Devices.First(dev => dev.Index == deviceChoice);
await RunRandom(client, device);
}
// And finally, we arrive at the main menu. We give the user the
// choice to scan for more devices (in case they forgot to turn them
// on earlier or whatever), run a command on a device, or just quit.
while (true)
{
Console.WriteLine("1. Scan For More Devices\n2. Run Skyrim vibrator\n3. Randomly vibrate\n4. Quit\nChoose an option: ");
if (!uint.TryParse(Console.ReadLine(), out var choice) ||
(choice == 0 || choice > 4))
{
Console.WriteLine("Invalid choice, try again.");
continue;
}
switch (choice)
{
case 1:
await ScanForDevices();
continue;
case 2:
await ControlDevice();
continue;
case 3:
await ControlDeviceRandom();
continue;
case 4:
return;
default:
// Due to the check above, we'll never hit this, but eh.
continue;
}
}
}
static async Task RunRandom(ButtplugClient client, ButtplugClientDevice device)
{
var rnd = new Random();
while (true)
{
var delay = rnd.NextDouble() * 0.5 + rnd.NextDouble() * rnd.NextDouble() * 10.0;
try
{
if (IsVorze(device))
{
await device.SendVorzeA10CycloneCmd(Convert.ToUInt32(rnd.Next(101)), rnd.Next(2) == 0 ? true : false);
} else
{
bool shouldStop = rnd.NextDouble() < 0.35;
double strength = shouldStop ? 0 : rnd.NextDouble();
await device.SendVibrateCmd(strength);
}
}
catch (ButtplugDeviceException e)
{
Console.WriteLine($"Device error: {e}");
device = await AttemptReconnect(client, device);
}
catch (Exception e)
{
Console.WriteLine("Unknown exception, attempting reconnect anyway. Exception: " + e);
device = await AttemptReconnect(client, device);
}
await Task.Delay(TimeSpan.FromSeconds(delay));
}
}
static async Task<ButtplugClientDevice> AttemptReconnect(ButtplugClient client, ButtplugClientDevice device)
{
Console.WriteLine("Attempting to reconnect device" + device.Name);
await client.StartScanningAsync();
return await _AttemptReconnect(client, device);
}
static async Task<ButtplugClientDevice> _AttemptReconnect(ButtplugClient client, ButtplugClientDevice device)
{
await Task.Delay(500);
var deviceOption = client.Devices.Find(d => d.Name.Equals(device.Name));
return await deviceOption.Match((ButtplugClientDevice d) =>
{
client.StopScanningAsync();
return Task.FromResult(d);
}, async () =>
{
return await _AttemptReconnect(client, device);
});
}
static async Task WatchLogFileAsync(string filename, ButtplugClient client, ButtplugClientDevice vaginalDevice, ButtplugClientDevice analDevice)
{
var wh = new AutoResetEvent(false);
var fsw = new FileSystemWatcher(".");
fsw.Filter = filename;
fsw.EnableRaisingEvents = true;
fsw.Changed += (s, e) => wh.Set();
var fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
fs.Seek(0, SeekOrigin.End);
// Watch the file
VibrateStatus currentSetting = VibrateStatus.Stopped();
using (var sr = new StreamReader(fs))
{
while (true)
{
// Reset position for new file
if (fs.Position > fs.Length)
fs.Seek(0, SeekOrigin.Begin);
string s = sr.ReadLine();
if (s != null)
{
bool isAnal = s.Contains("JNAnal");
bool isVaginal = s.Contains("JNVaginal");
if (isAnal || isVaginal)
{
var deviceToSendTo = isAnal ? analDevice : vaginalDevice;
Either<Exception, VibrateCommand> vlOrE = ParseVibrateLine(s);
Console.WriteLine("[RumbleLog] " + vlOrE);
await vlOrE.Match(async vl =>
{
try
{
if (vl is VibrateStart)
{
currentSetting = await HandleVibrateStart(deviceToSendTo, vl as VibrateStart, currentSetting);
}
else if (vl is VibrateStop)
{
await HandleVibrateStop(deviceToSendTo);
currentSetting = VibrateStatus.Stopped();
}
}
catch (ButtplugDeviceException e)
{
Console.WriteLine(e);
Console.WriteLine("Device disconnected.");
deviceToSendTo = await AttemptReconnect(client, deviceToSendTo);
}
catch (Exception e)
{
Console.WriteLine("Unknown exception, attempting reconnect anyway. Exception: " + e);
deviceToSendTo = await AttemptReconnect(client, deviceToSendTo);
}
}, async e => Console.WriteLine(e));
}
}
else
{
wh.WaitOne(10);
}
}
}
// TODO end loop
//wh.Close();
}
private static async Task<VibrateStatus> HandleVibrateStart(ButtplugClientDevice device, VibrateStart vs, VibrateStatus status)
{
if (IsVorze(device))
{
var newDirection = random(2) == 0 ? true : false;
await device.SendVorzeA10CycloneCmd(Convert.ToUInt32(vs.strength * 100), newDirection);
return await vs.time.MatchAsync(async time =>
{
await Task.Delay(time);
await device.SendVorzeA10CycloneCmd(StrengthToVorzeRotation(status.strength), status.direction);
return status;
}, () => new VibrateStatus(vs.strength, newDirection));
}
else
{
await device.SendVibrateCmd(vs.strength);
// TODO handle intervals
return await vs.time.MatchAsync(async time =>
{
await Task.Delay(time);
await device.SendVibrateCmd(status.strength);
return status;
}, () => new VibrateStatus(vs.strength, false));
}
}
private static bool IsVorze(ButtplugClientDevice device)
{
return device.AllowedMessages.ContainsKey(typeof(VorzeA10CycloneCmd));
}
private static UInt32 StrengthToVorzeRotation(double strength)
{
return Convert.ToUInt32(Math.Pow(strength, 2) * 80);
}
private static async Task HandleVibrateStop(ButtplugClientDevice device)
{
await device.StopDeviceCmd();
}
static Either<Exception, VibrateCommand> ParseVibrateLine(string s)
{
Arr<string> parts = new Arr<string>(s.ToLower().Split(' '));
if (parts.Contains("start"))
{
Map<string, string> dict = new Map<string, string>(parts.Filter(s_ => s_.Contains("=")).Map(p =>
{
string[] pp = p.Split('=');
return (pp.First(), pp.Last());
}));
try
{
return Right<VibrateCommand>(new VibrateStart(
dict["type"], dict.Find("time").Map(Double.Parse), dict.Find("interval").Map(Double.Parse), Double.Parse(dict["strength"])));
}
catch (Exception e)
{
return Left(e);
}
}
else if (parts.Contains("stop"))
return Right<VibrateCommand>(new VibrateStop());
else
return Right<VibrateCommand>(new VibrateNone());
}
class VibrateStatus
{
public double strength;
public bool direction;
public VibrateStatus(double strength, bool direction)
{
this.strength = strength;
this.direction = direction;
}
public static VibrateStatus Stopped()
{
return new VibrateStatus(0, true);
}
}
interface VibrateCommand {}
class VibrateStart : VibrateCommand
{
private const double StrengthFactor = 100;
public string type;
public Option<TimeSpan> time;
public Option<TimeSpan> interval;
public double strength;
public VibrateStart(string type, Option<double> time, Option<double> interval, double strength)
{
this.type = type;
this.time = time.Bind(t => t == -1 ? None : Some(TimeSpan.FromSeconds(t)));
this.interval = interval.Bind(t => t == -1 ? None : Some(TimeSpan.FromSeconds(t)));
this.strength = strength / StrengthFactor;
}
public override string ToString()
{
return "VibrateStart(type: " + type + ", time: " + time + ", strength: " + strength + ")";
}
}
class VibrateStop : VibrateCommand {}
class VibrateNone : VibrateCommand {}
// Since not everyone is probably going to want to run under C# 7.1+,
// we'll use a non-async Main and call to a Wait()'d task. C# 8 can't
// come soon enough.
private static void Main()
{
string logFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"My Games", "Skyrim", "Logs", "Script", "User", "Controller Rumble.0.log");
// Setup a client, and wait until everything is done before exiting.
RunExample(logFile).Wait();
}
}
}