Example #1
0
        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));
        }
Example #2
0
        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));
            }
        }
Example #3
0
        public ButtplugStuff()
        {
            client              = new ButtplugClient("osu!");
            client.DeviceAdded += DeviceFound;

            Connect();
        }
Example #4
0
        public async Task <bool> Connect()
        {
            try
            {
                var client = new ButtplugClient("ScriptPlayer", new ButtplugWebsocketConnector(new Uri(_url)));
                client.DeviceAdded      += Client_DeviceAdded;
                client.DeviceRemoved    += Client_DeviceRemoved;
                client.ErrorReceived    += Client_ErrorReceived;
                client.Log              += Client_Log;
                client.PingTimeout      += Client_PingTimeout;
                client.ScanningFinished += Client_ScanningFinished;
                client.ServerDisconnect += Client_ServerDisconnect;

                await client.ConnectAsync();

                _client = client;

                return(true);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                File.AppendAllText(
                    Environment.ExpandEnvironmentVariables("%APPDATA%\\ScriptPlayer\\ButtplugConnectionError.log"),
                    ExceptionHelper.BuildException(e));
                _client = null;
                return(false);
            }
        }
Example #5
0
 public void SetUp()
 {
     _connector             = new ButtplugClientTestConnector();
     _client                = new ButtplugClient("Other Test Device Client", _connector);
     _client.ErrorReceived += HandleErrorInvoked;
     _errorInvoked          = false;
 }
Example #6
0
        // This function is run before all mods are finished loading.
        protected override void OnPreInitialize()
        {
            base.OnPreInitialize();

            Debug.Log("[DGBP] PreInit");

            Assembly    duckGame     = typeof(Mod).Assembly;                                                             // Get the Duck Game assembly reference
            Type        tGameMode    = duckGame.GetType("DuckGame.DM");                                                  // Get the DM class
            MethodInfo  mDoAddPoints = tGameMode.GetMethod("AddPoints", BindingFlags.NonPublic | BindingFlags.Instance); // Find the AddPoints method
            HookManager manager      = new HookManager();

            manager.Hook(mDoAddPoints, typeof(DGButtplugClient).GetMethod("AddPointsHook"));             // Redirect DM.AddPoints to our method
            connector = new ButtplugWebsocketConnector(new Uri("ws://localhost:6969/b******g"));
            client    = new ButtplugClient("DG B******g", connector);

            try {
                client.ConnectAsync().Wait();
                client.StartScanningAsync().Wait();
                Task.Delay(5000).Wait();
                client.StopScanningAsync().Wait();
            } catch (Exception ex) {
                Debug.Log("[DGBP] B******g error. Restart your game if you want your plug to work!");
                Debug.Log($"[DGBP] {ex.Message}");
            }
        }
        private static async Task LogExample()
        {
            // Set up our log handler to print logs to stdout
            ButtplugFFILog.LogMessage += (obj, msg) =>
            {
                Console.WriteLine(msg);
            };
            // Report everything at level Debug and higher, and since we're reporting to the
            // console, don't use JSON output. (JSON output is handy for log parsing later if
            // you need it.)
            ButtplugFFILog.StartLogHandler(ButtplugLogLevel.Debug, false);

            // If you want to change log levels without recompiling, you can use the Env Logger.
            // Just make sure you don't try to use StartLogHandler and ActivateEnvLogger in the
            // same session, they will conflict with each other and throw errors.
            //
            // To set the env logger filter level, you'll need to set the RUST_LOG environment
            // variable. i.e. in powershell: $env:RUST_LOG="debug"
            //
            // Comment the code above this and uncomment this if you want to try the env logger.
            //
            // ButtplugFFILog.ActivateEnvLogger();

            // Completing our embedded connection should cause log messages to print.
            var connector = new ButtplugEmbeddedConnectorOptions();
            var client    = new ButtplugClient("Example Client");
            await client.ConnectAsync(connector);
        }
Example #8
0
        public async Task <bool> Connect()
        {
            if (_client?.Connected ?? false)
            {
                return(true);
            }

            try
            {
                var client = new ButtplugClient("ScriptPlayer");
                client.DeviceAdded      += Client_DeviceAdded;
                client.DeviceRemoved    += Client_DeviceRemoved;
                client.ErrorReceived    += Client_ErrorReceived;
                client.PingTimeout      += Client_PingTimeout;
                client.ScanningFinished += Client_ScanningFinished;
                client.ServerDisconnect += Client_ServerDisconnect;

                await client.ConnectAsync(new ButtplugWebsocketConnectorOptions(new Uri(_url)));

                _client = client;

                foreach (var buttplugClientDevice in _client.Devices)
                {
                    AddDevice(buttplugClientDevice);
                }

                return(true);
            }
            catch (Exception e)
            {
                RecordButtplugException("ButtplugAdapter.Connect", e);
                _client = null;
                return(false);
            }
        }
Example #9
0
        private static async Task RunExample()
        {
            var client = new ButtplugClient("Test Client");

            client.DeviceAdded += async(obj, args) =>
            {
                var device = args.Device;
                if (device.AllowedMessages.ContainsKey(ButtplugFFI.MessageAttributeType.VibrateCmd))
                {
                    await device.SendVibrateCmd(0.5);
                }
                device.Dispose();
                device = null;
            };
            await client.ConnectLocal();

            //await client.ConnectWebsocket();
            await client.StartScanning();

            await WaitForKey();

            client.Dispose();
            client = null;
            await WaitForKey();
        }
        /********************************
        * Service start/stop
        ********************************/
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Toy Web Bridge is starting.");

            if (_settings.SecretKey == string.Empty)
            {
                _settings.SecretKey = KeyGenerator.GetUniqueKey(20);
                _logger.LogWarning($"\n /!\\ Web bridge (generated) SecretKey: " + _settings.SecretKey + " /!\\\n");
            }
            else
            {
                _logger.LogWarning($"\n /!\\ Web bridge SecretKey: " + _settings.SecretKey + " /!\\\n");
            }

            client                   = new ButtplugClient("Simple HTTP Bridge");
            client.DeviceAdded      += (source, args) => Register.OnDeviceAdded(args.Device);
            client.DeviceRemoved    += (source, args) => Register.OnDeviceRemoved(args.Device);
            client.ErrorReceived    += OnErrorReceived;
            client.PingTimeout      += OnPingTimeout;
            client.ScanningFinished += OnScanningFinished;
            client.ServerDisconnect += OnServerDisconnect;
            client.ServerDisconnect += (source, args) => Register.OnServerDisconnect();

            _websocket_url = string.Format("ws://localhost:{0}/b******g", _settings.WebSocketPort);
            _logger.LogInformation("Websocket url is: " + _websocket_url);

            _timer = new Timer(MonitorWebsocket, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));

            return(Task.CompletedTask);
        }
        public async Task ConnectTask()
        {
            Dispatcher.Invoke(() => { ConnectionStatus.Content = "Connecting"; });
            IButtplugClientConnector connector;
            //if (_useEmbeddedServer)
            {
                var embeddedConnector = new ButtplugEmbeddedConnector("VaMLaunch Embedded Server", 0, _deviceManager);
                if (_deviceManager == null)
                {
                    _deviceManager = embeddedConnector.Server.DeviceManager;
                }
                connector = embeddedConnector;
            }

            var client = new ButtplugClient("VaMLaunch Client", connector);

            while (!_quitting)
            {
                try
                {
                    client.DeviceAdded      += OnDeviceAdded;
                    client.DeviceRemoved    += OnDeviceRemoved;
                    client.Log              += OnLogMessage;
                    client.ServerDisconnect += OnDisconnect;
                    await client.ConnectAsync();

                    await client.RequestLogAsync(ButtplugLogLevel.Debug);

                    _client = client;
                    await Dispatcher.Invoke(async() =>
                    {
                        ConnectedHandler?.Invoke(this, new EventArgs());
                        ConnectionStatus.Content = "Connected";
                        await StartScanning();
                        _scanningButton.Visibility = Visibility.Visible;
                    });

                    break;
                }
                catch (ButtplugClientConnectorException)
                {
                    Debug.WriteLine("Retrying");
                    // Just keep trying to connect.
                    // If the exception was thrown after connect, make sure we disconnect.
                    if (_client != null && _client.Connected)
                    {
                        await _client.DisconnectAsync();
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Did something else fail? {ex})");
                    // If the exception was thrown after connect, make sure we disconnect.
                    if (_client != null && _client.Connected)
                    {
                        await _client.DisconnectAsync();
                    }
                }
            }
        }
 public void OnDisconnect(object aObj, EventArgs aArgs)
 {
     _connectTask = new Task(async() => await ConnectTask());
     _connectTask.Start();
     _devices.Clear();
     _client = null;
 }
        private static void SetupBP()
        {
            bpClient = new ButtplugClient("VRCVibratorController");
            bpClient.ConnectAsync(new ButtplugEmbeddedConnectorOptions());
            bpClient.DeviceAdded += async(object aObj, DeviceAddedEventArgs args) => {
                await AsyncUtils.YieldToMainThread();

                new Toy(args.Device, TabButton.SubMenu);
            };

            bpClient.DeviceRemoved += async(object aObj, DeviceRemovedEventArgs args) => {
                await AsyncUtils.YieldToMainThread();

                if (Toy.myToys.ContainsKey(args.Device.Index))
                {
                    Toy.myToys[args.Device.Index].disable();
                }
            };

            bpClient.ErrorReceived += async(object aObj, ButtplugExceptionEventArgs args) =>
            {
                MelonLogger.Msg($"B******g Client recieved error: {args.Exception.Message}");
                await AsyncUtils.YieldToMainThread();

                buttplugError.SubtitleText = "Error occured";
            };
        }
Example #14
0
        public void TestWrongAddress()
        {
            var wrongConnector = new ButtplugWebsocketConnector(new Uri("ws://invalid:12345/b******g"));
            var wrongClient    = new ButtplugClient("Websocket Client", wrongConnector);

            wrongClient.Awaiting(async aClient => await aClient.ConnectAsync()).Should()
            .Throw <ButtplugClientConnectorException>();
        }
 static async Task ConnectWebsocket()
 {
     // Creating a Websocket Connector is as easy as using the right
     // options object.
     var connector = new ButtplugWebsocketConnectorOptions(
         new Uri("ws://localhost:12345/b******g"));
     var client = new ButtplugClient("Example Client");
     await client.ConnectAsync(connector);
 }
 private void DisposeClient()
 {
     if (_client == null)
     {
         return;
     }
     _client.Dispose();
     _client = null;
 }
 static void Main(string[] args)
 {
     // Creating a Websocket Connector is as easy as adding the
     // Client.Connectors.WebsocketConnector package from nuget and
     // passing a websocket address to it.
     var connector = new ButtplugWebsocketConnector(
         new Uri("ws://localhost:12345/b******g"));
     var client = new ButtplugClient("Example Client", connector);
 }
        private static async Task RunExample()
        {
            // After you've created a connector, the connection looks the same no
            // matter what, though the errors thrown may be different.
            var connector = new ButtplugEmbeddedConnectorOptions();

            // If you'd like to try a remote network connection, comment the
            // connector line above and uncomment the one below. Note that you'll
            // need to turn off SSL on whatever server you're using.

            // var connector = new ButtplugWebsocketConnector(
            //   new Uri("ws://localhost:12345/b******g"));

            var client = new ButtplugClient("Example Client");

            // Now we connect. If anything goes wrong here, we'll either throw
            //
            // - A ButtplugClientConnectionException if there's a problem with
            //   the Connector, like the network address being wrong, server not
            //   being up, etc.
            // - A ButtplugHandshakeException if there is a client/server version
            //   mismatch.
            try
            {
                await client.ConnectAsync(connector);
            }
            catch (ButtplugConnectorException ex)
            {
                // If our connection failed, because the server wasn't turned on,
                // SSL/TLS wasn't turned off, etc, we'll just print and exit
                // here. This will most likely be a wrapped exception.
                Console.WriteLine(
                    $"Can't connect, exiting! Message: {ex.InnerException.Message}");
                await WaitForKey();

                return;
            }
            catch (ButtplugHandshakeException ex)
            {
                // This means our client is newer than our server, and we need to
                // upgrade the server we're connecting to.
                Console.WriteLine(
                    $"Handshake issue, exiting! Message: {ex.InnerException.Message}");
                await WaitForKey();

                return;
            }

            // We're connected, yay!
            Console.WriteLine("Connected! Check Server for Client Name.");

            await WaitForKey();

            // And now we disconnect as usual
            await client.DisconnectAsync();
        }
Example #19
0
        public override void SetUpConnector()
        {
            _subtypeMgr = new TestDeviceSubtypeManager(new TestDevice(_logMgr, "Test Device"));
            _server     = new TestServer();

            // This is a test, so just ignore the logger requirement for now.
            _server.AddDeviceSubtypeManager(aLog => _subtypeMgr);
            _connector = new ButtplugEmbeddedConnector(_server);
            _client    = new ButtplugClient("Test Client", _connector);
        }
Example #20
0
 private void Client_ServerDisconnect(object sender, EventArgs e)
 {
     _client = null;
     foreach (var device in _devices.Values)
     {
         OnDeviceRemoved(device);
     }
     _devices.Clear();
     OnDisconnected();
 }
Example #21
0
        public static async Task connectDevicesToClient(ButtplugClient client)
        {
            Log_Manager.write("Scanning for new devices...");
            await client.StartScanningAsync();

            Log_Manager.write("Client currently knows about these devices:");
            foreach (var device in client.Devices)
            {
                Log_Manager.write($"- {device.Name}");
            }
        }
Example #22
0
        public async Task TestBadIncomingJSON()
        {
            var jsonConnector = new ButtplugClientTestJSONConnector();
            var client        = new ButtplugClient("JSON Test", jsonConnector);

            client.ErrorReceived += HandleErrorInvoked;
            await client.ConnectAsync();

            jsonConnector.SendServerMessage("This is not json.");
            _errorInvoked.Should().BeTrue();
            _currentException.Should().BeOfType <ButtplugMessageException>();
        }
Example #23
0
        private async Task connectEmbeddedServer()
        {
            embeddedConnector = new ButtplugEmbeddedConnector("Buttplugin Server");
            embeddedConnector.Server.AddDeviceSubtypeManager((IButtplugLogManager aMgr)
                                                             => { return(new UWPBluetoothManager(aMgr)); });

            client = new ButtplugClient("Buttplugin Client", embeddedConnector);

            await Connection_Manager.connectClientToServer(client);

            client.DeviceAdded += clientDeviceAdded;
        }
Example #24
0
        public void TestClientDeviceEquality()
        {
            var logMgr = new ButtplugLogManager();
            var client = new ButtplugClient("Test Device Client", new ButtplugEmbeddedConnector("Test Device Server"));

            Task SendFunc(ButtplugClientDevice device, ButtplugMessage msg, CancellationToken token) => Task.CompletedTask;

            var testDevice = new ButtplugClientDevice(logMgr, client, SendFunc, 1, "Test Device", new Dictionary <string, MessageAttributes>()
            {
                { "SingleMotorVibrateCmd", new MessageAttributes() },
                { "VibrateCmd", new MessageAttributes(2) },
                { "StopDeviceCmd", new MessageAttributes() },
            });
            var testDevice2 = new ButtplugClientDevice(logMgr, client, SendFunc, 1, "Test Device", new Dictionary <string, MessageAttributes>()
            {
                { "SingleMotorVibrateCmd", new MessageAttributes() },
                { "VibrateCmd", new MessageAttributes(2) },
                { "StopDeviceCmd", new MessageAttributes() },
            });
            var testDevice3 = new ButtplugClientDevice(logMgr, client, SendFunc, 1, "Test Device", new Dictionary <string, MessageAttributes>()
            {
                { "SingleMotorVibrateCmd", new MessageAttributes() },
                { "VibrateCmd", new MessageAttributes(2) },
            });
            var testDevice4 = new ButtplugClientDevice(logMgr, client, SendFunc, 1, "Test Device", new Dictionary <string, MessageAttributes>()
            {
                { "SingleMotorVibrateCmd", new MessageAttributes() },
                { "VibrateCmd", new MessageAttributes(2) },
                { "FleshlightLaunchFW12Cmd", new MessageAttributes() },
            });
            var testDevice5 = new ButtplugClientDevice(logMgr, client, SendFunc, 1, "Test Device", new Dictionary <string, MessageAttributes>()
            {
                { "SingleMotorVibrateCmd", new MessageAttributes() },
                { "VibrateCmd", new MessageAttributes(2) },
                { "StopDeviceCmd", new MessageAttributes() },
                { "RotateCmd", new MessageAttributes(1) },
            });

            var newClient       = new ButtplugClient("Other Test Device Client", new ButtplugEmbeddedConnector("Other Test Device Server"));
            var otherTestDevice = new ButtplugClientDevice(logMgr, newClient, SendFunc, 1, "Test Device", new Dictionary <string, MessageAttributes>()
            {
                { "SingleMotorVibrateCmd", new MessageAttributes() },
                { "VibrateCmd", new MessageAttributes(2) },
                { "StopDeviceCmd", new MessageAttributes() },
            });

            testDevice.Should().BeEquivalentTo(testDevice2);
            testDevice.Should().NotBe(testDevice3);
            testDevice.Should().NotBe(testDevice4);
            testDevice.Should().NotBe(testDevice5);
            testDevice.Should().NotBe(otherTestDevice);
        }
 public void OnDisconnect(object aObj, EventArgs aArgs)
 {
     Dispatcher.Invoke(() =>
     {
         _connectButton.IsEnabled     = true;
         _connectButton.Visibility    = Visibility.Visible;
         _disconnectButton.Visibility = Visibility.Collapsed;
         _connectStatus.Text          = "Disconnected";
         DevicesList.Clear();
         _client.Dispose();
         _client = null;
     });
 }
Example #26
0
        public Device(String name, ButtplugClient client, ButtplugClientDevice device)
        {
            this.name           = name;
            this.device         = device;
            this.client         = client;
            this.active         = false;
            this.running_events = new List <Running_Event>();

            thread = new Thread(UpdateLoop)
            {
                IsBackground = true
            };
            thread.Start();
        }
Example #27
0
        private static async Task Sending(ButtplugClient client, double cachedValue)
        {
            Task.WaitAll(sendTasks.ToArray());
            foreach (var device in client.Devices)
            {
                var count = device.GetMessageAttributes <VibrateCmd>().FeatureCount;
                if (!count.HasValue)
                {
                    continue;
                }

                sendTasks.Add(device.SendVibrateCmd(cachedValue));
            }
        }
        private static async Task RunExample()
        {
            // Let's go back to our embedded connector now, to discuss what the
            // lifetime of a connection looks like.
            //
            // We'll create an embedded connector, but this time we're going to
            // include a maximum ping timeout of 100ms. This is a fairly short
            // timer, but since everything is running in our current process, it
            // should be fine.
            var connector = new ButtplugEmbeddedConnectorOptions();

            connector.MaxPingTime = 100;
            var client = new ButtplugClient("Example Client");

            // Just because the Client takes care of sending the ping message for
            // you doesn't mean that a connection is always perfect. It could be
            // that some code you write blocks the thread that the timer is
            // sending on, or sometimes the client's connection to the server can
            // be severed. In these cases, the client has events we can listen to
            // so we know when either we pinged out, or the server was disconnected.
            client.PingTimeout += (aObj, aEventArgs) =>
                                  Console.WriteLine("B******g ping timeout!");
            client.ServerDisconnect += (aObj, aEventArgs) =>
                                       Console.WriteLine("B******g disconnected!");

            // Let's go ahead and connect.
            await client.ConnectAsync(connector);

            Console.WriteLine("Client connected");

            // If you'd like more information on what's going on, uncomment these 2 lines.

            // client.Log += (aObj, aMsg) => Console.WriteLine(aMsg.Message.LogMessage);
            // await client.RequestLogAsync(ButtplugLogLevel.Debug);

            // If we just sit here and wait, the client and server will happily
            // ping each other internally, so we shouldn't see anything printed
            // outside of the "hit key to continue" message. Our wait function is
            // async, so the event loop still spins and the timer stays happy.
            await WaitForKey();

            // Now we'll kill the timer. You should see both a ping timeout and a
            // disconnected message from the event handlers we set up above.
            Console.WriteLine("Stopping ping timer");
            await WaitForKey();

            // At this point we should already be disconnected, so we'll just
            // show ourselves out.
        }
Example #29
0
        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);
            }));
        }
Example #30
0
        private void ConnectEmbedded()
        {
            // First off, we'll set up our Embedded Connector.
            var connector = new ButtplugEmbeddedConnectorOptions();

            // If we want to change anything after making the options object,
            // we can just access the members. We'll explain more about this
            // in a later chapter.
            connector.ServerName = "New Server Name";

            client = new ButtplugClient("Example Client");

            // Connecting using an embedded connection should never fail.
            client.ConnectAsync(connector);
        }