- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
Latest commit
502 lines (447 loc) · 20.6 KB
/
Copy pathProgram.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
usingButtplug.Client;
usingButtplug.Core;
usingButtplug.Core.Messages;
usingButtplug.Client.Connectors.WebsocketConnector;
usingLanguageExt;
usingstaticLanguageExt.Prelude;
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Threading.Tasks;
usingSystem.Threading;
usingSystem.IO;
namespaceskybutt
{
internalclassProgram
{
privatestaticasyncTaskWaitForKey()
{
Console.WriteLine("Press any key to continue.");
while(!Console.KeyAvailable)
{
awaitTask.Delay(1);
}
Console.ReadKey(true);
}
privatestaticasyncTaskRunExample(stringlogFile)
{
// 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.
varclient=newButtplugClient("skybutt client",new
ButtplugWebsocketConnector(newUri("ws://localhost:12345/buttplug")));
awaitclient.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.
voidHandleDeviceAdded(objectaObj,DeviceAddedEventArgsaArgs)
{
Console.WriteLine($"Device connected: {aArgs.Device.Name}");
}
client.DeviceAdded+=HandleDeviceAdded;
voidHandleDeviceRemoved(objectaObj,DeviceRemovedEventArgsaArgs)
{
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.
asyncTaskScanForDevices()
{
Console.WriteLine("Scanning for devices until key is pressed.");
Console.WriteLine("Found devices will be printed to console.");
awaitclient.StartScanningAsync();
awaitWaitForKey();
// Stop scanning now, 'cause we don't want new devices popping up anymore.
awaitclient.StopScanningAsync();
}
// Scan for devices before we get to the main menu.
awaitScanForDevices();
// 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.
asyncTaskControlDevice()
{
// 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;
}
varoptions=newList<uint>();
foreach(vardevinclient.Devices)
{
Console.WriteLine($"{dev.Index}. {dev.Name}");
options.Add(dev.Index);
}
uintvaginalDeviceChoice;
if(options.Length()==1)
{
vaginalDeviceChoice=client.Devices.Head().Index;
}else
{
Console.WriteLine("Choose vaginal device: ");
if(!uint.TryParse(Console.ReadLine(),outvaginalDeviceChoice)||
!options.Contains(vaginalDeviceChoice))
{
Console.WriteLine("Invalid choice");
return;
}
}
uintanalDeviceChoice;
if(options.Length()==1)
{
analDeviceChoice=client.Devices.Head().Index;
}else
{
Console.WriteLine("Choose anal device: ");
if(!uint.TryParse(Console.ReadLine(),outanalDeviceChoice)||
!options.Contains(analDeviceChoice))
{
Console.WriteLine("Invalid choice");
return;
}
}
varvaginalDevice=client.Devices.First(dev =>dev.Index==vaginalDeviceChoice);
foreach(varminvaginalDevice.AllowedMessages)
{
Console.WriteLine($"Device message: {m.Key} -> {m.Value}");
}
varanalDevice=client.Devices.First(dev =>dev.Index==analDeviceChoice);
foreach(varminanalDevice.AllowedMessages)
{
Console.WriteLine($"Device message: {m.Key} -> {m.Value}");
}
Console.WriteLine("Watching Controller Rumble log file");
awaitWatchLogFileAsync(logFile,client,vaginalDevice,analDevice);
}
asyncTaskControlDeviceRandom()
{
// 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;
}
varoptions=newList<uint>();
foreach(vardevinclient.Devices)
{
Console.WriteLine($"{dev.Index}. {dev.Name}");
options.Add(dev.Index);
}
uintdeviceChoice;
if(options.Length()==1)
{
deviceChoice=client.Devices.Head().Index;
}else
{
Console.WriteLine("Choose a device: ");
if(!uint.TryParse(Console.ReadLine(),outdeviceChoice)||
!options.Contains(deviceChoice))
{
Console.WriteLine("Invalid choice");
return;
}
}
vardevice=client.Devices.First(dev =>dev.Index==deviceChoice);
awaitRunRandom(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(),outvarchoice)||
(choice==0||choice>4))
{
Console.WriteLine("Invalid choice, try again.");
continue;
}
switch(choice)
{
case1:
awaitScanForDevices();
continue;
case2:
awaitControlDevice();
continue;
case3:
awaitControlDeviceRandom();
continue;
case4:
return;
default:
// Due to the check above, we'll never hit this, but eh.
continue;
}
}
}
staticasyncTaskRunRandom(ButtplugClientclient,ButtplugClientDevicedevice)
{
varrnd=newRandom();
while(true)
{
vardelay=rnd.NextDouble()*0.5+rnd.NextDouble()*rnd.NextDouble()*10.0;
try
{
if(IsVorze(device))
{
awaitdevice.SendVorzeA10CycloneCmd(Convert.ToUInt32(rnd.Next(101)),rnd.Next(2)==0?true:false);
}else
{
boolshouldStop=rnd.NextDouble()<0.35;
doublestrength=shouldStop?0:rnd.NextDouble();
awaitdevice.SendVibrateCmd(strength);
}
}
catch(ButtplugDeviceExceptione)
{
Console.WriteLine($"Device error: {e}");
device=awaitAttemptReconnect(client,device);
}
catch(Exceptione)
{
Console.WriteLine("Unknown exception, attempting reconnect anyway. Exception: "+e);
device=awaitAttemptReconnect(client,device);
}
awaitTask.Delay(TimeSpan.FromSeconds(delay));
}
}
staticasyncTask<ButtplugClientDevice>AttemptReconnect(ButtplugClientclient,ButtplugClientDevicedevice)
{
Console.WriteLine("Attempting to reconnect device"+device.Name);
awaitclient.StartScanningAsync();
returnawait_AttemptReconnect(client,device);
}
staticasyncTask<ButtplugClientDevice>_AttemptReconnect(ButtplugClientclient,ButtplugClientDevicedevice)
{
awaitTask.Delay(500);
vardeviceOption=client.Devices.Find(d =>d.Name.Equals(device.Name));
returnawaitdeviceOption.Match((ButtplugClientDeviced)=>
{
client.StopScanningAsync();
returnTask.FromResult(d);
},async()=>
{
returnawait_AttemptReconnect(client,device);
});
}
staticasyncTaskWatchLogFileAsync(stringfilename,ButtplugClientclient,ButtplugClientDevicevaginalDevice,ButtplugClientDeviceanalDevice)
{
varwh=newAutoResetEvent(false);
varfsw=newFileSystemWatcher(".");
fsw.Filter=filename;
fsw.EnableRaisingEvents=true;
fsw.Changed+=(s,e)=>wh.Set();
varfs=newFileStream(filename,FileMode.Open,FileAccess.Read,FileShare.ReadWrite);
fs.Seek(0,SeekOrigin.End);
// Watch the file
VibrateStatuscurrentSetting=VibrateStatus.Stopped();
using(varsr=newStreamReader(fs))
{
while(true)
{
// Reset position for new file
if(fs.Position>fs.Length)
fs.Seek(0,SeekOrigin.Begin);
strings=sr.ReadLine();
if(s!=null)
{
boolisAnal=s.Contains("JNAnal");
boolisVaginal=s.Contains("JNVaginal");
if(isAnal||isVaginal)
{
vardeviceToSendTo=isAnal?analDevice:vaginalDevice;
Either<Exception,VibrateCommand>vlOrE=ParseVibrateLine(s);
Console.WriteLine("[RumbleLog] "+vlOrE);
awaitvlOrE.Match(async vl =>
{
try
{
if(vlisVibrateStart)
{
currentSetting=awaitHandleVibrateStart(deviceToSendTo,vlasVibrateStart,currentSetting);
}
elseif(vlisVibrateStop)
{
awaitHandleVibrateStop(deviceToSendTo);
currentSetting=VibrateStatus.Stopped();
}
}
catch(ButtplugDeviceExceptione)
{
Console.WriteLine(e);
Console.WriteLine("Device disconnected.");
deviceToSendTo=awaitAttemptReconnect(client,deviceToSendTo);
}
catch(Exceptione)
{
Console.WriteLine("Unknown exception, attempting reconnect anyway. Exception: "+e);
deviceToSendTo=awaitAttemptReconnect(client,deviceToSendTo);
}
},async e =>Console.WriteLine(e));
}
}
else
{
wh.WaitOne(10);
}
}
}
// TODO end loop
//wh.Close();
}
privatestaticasyncTask<VibrateStatus>HandleVibrateStart(ButtplugClientDevicedevice,VibrateStartvs,VibrateStatusstatus)
{
if(IsVorze(device))
{
varnewDirection=random(2)==0?true:false;
awaitdevice.SendVorzeA10CycloneCmd(Convert.ToUInt32(vs.strength*100),newDirection);
returnawaitvs.time.MatchAsync(async time =>
{
awaitTask.Delay(time);
awaitdevice.SendVorzeA10CycloneCmd(StrengthToVorzeRotation(status.strength),status.direction);
returnstatus;
},()=>newVibrateStatus(vs.strength,newDirection));
}
else
{
awaitdevice.SendVibrateCmd(vs.strength);
// TODO handle intervals
returnawaitvs.time.MatchAsync(async time =>
{
awaitTask.Delay(time);
awaitdevice.SendVibrateCmd(status.strength);
returnstatus;
},()=>newVibrateStatus(vs.strength,false));
}
}
privatestaticboolIsVorze(ButtplugClientDevicedevice)
{
returndevice.AllowedMessages.ContainsKey(typeof(VorzeA10CycloneCmd));
}
privatestaticUInt32StrengthToVorzeRotation(doublestrength)
{
returnConvert.ToUInt32(Math.Pow(strength,2)*80);
}
privatestaticasyncTaskHandleVibrateStop(ButtplugClientDevicedevice)
{
awaitdevice.StopDeviceCmd();
}
staticEither<Exception,VibrateCommand>ParseVibrateLine(strings)
{
Arr<string>parts=newArr<string>(s.ToLower().Split(' '));
if(parts.Contains("start"))
{
Map<string,string>dict=newMap<string,string>(parts.Filter(s_ =>s_.Contains("=")).Map(p =>
{
string[]pp=p.Split('=');
return(pp.First(),pp.Last());
}));
try
{
returnRight<VibrateCommand>(newVibrateStart(
dict["type"],dict.Find("time").Map(Double.Parse),dict.Find("interval").Map(Double.Parse),Double.Parse(dict["strength"])));
}
catch(Exceptione)
{
returnLeft(e);
}
}
elseif(parts.Contains("stop"))
returnRight<VibrateCommand>(newVibrateStop());
else
returnRight<VibrateCommand>(newVibrateNone());
}
classVibrateStatus
{
publicdoublestrength;
publicbooldirection;
publicVibrateStatus(doublestrength,booldirection)
{
this.strength=strength;
this.direction=direction;
}
publicstaticVibrateStatusStopped()
{
returnnewVibrateStatus(0,true);
}
}
interfaceVibrateCommand{}
classVibrateStart:VibrateCommand
{
privateconstdoubleStrengthFactor=100;
publicstringtype;
publicOption<TimeSpan>time;
publicOption<TimeSpan>interval;
publicdoublestrength;
publicVibrateStart(stringtype,Option<double>time,Option<double>interval,doublestrength)
{
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;
}
publicoverridestringToString()
{
return"VibrateStart(type: "+type+", time: "+time+", strength: "+strength+")";
}
}
classVibrateStop:VibrateCommand{}
classVibrateNone: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.
privatestaticvoidMain()
{
stringlogFile=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();
}
}
}