Exemple #1
0
        public async Task DeviceDestroyedAsync(Guid deviceId, CancellationToken cancellationToken)
        {
            await _shell.SwitchToMainThreadAsync(cancellationToken);

            var device = FindDevice(deviceId);

            Debug.Assert(device != null, "List of devices is out of sync.");
            if (device == null)
            {
                return;
            }

            lock (_devicesLock) {
                _devices.Remove(device);
            }

            IRPlotDeviceVisualComponent component;

            if (_assignedVisualComponents.TryGetValue(deviceId, out component))
            {
                component.Unassign();
                _assignedVisualComponents.Remove(deviceId);
                _unassignedVisualComponents.Add(component);
            }
            else
            {
                Debug.Assert(false, "Failed to destroy a plot visual component.");
            }

            DeviceRemoved?.Invoke(this, new RPlotDeviceEventArgs(device));
        }
Exemple #2
0
        public async Task DeviceDestroyedAsync(Guid deviceId)
        {
            InteractiveWorkflow.Shell.AssertIsOnMainThread();

            var device = FindDevice(deviceId);

            Debug.Assert(device != null, "List of devices is out of sync.");
            if (device == null)
            {
                return;
            }

            _devices.Remove(device);

            IRPlotDeviceVisualComponent component;

            if (_assignedVisualComponents.TryGetValue(deviceId, out component))
            {
                await component.UnassignAsync();

                _assignedVisualComponents.Remove(deviceId);
                _unassignedVisualComponents.Add(component);
            }
            else
            {
                Debug.Assert(false, "Failed to destroy a plot visual component.");
            }

            DeviceRemoved?.Invoke(this, new RPlotDeviceEventArgs(device));
        }
Exemple #3
0
        private void CompareDrives()
        {
            var drivesNow = GetRemovableDrives();

            var addedDrives   = drivesNow.Except(_drives);
            var removedDrives = _drives.Except(drivesNow);

            if (addedDrives.Any())
            {
                foreach (var addedDrive in addedDrives)
                {
                    if (DeviceAdded != null)
                    {
                        DeviceAdded.Invoke(new Device(addedDrive));
                    }

                    DisplayNewDeviceToast(addedDrive);
                }
            }

            if (removedDrives.Any())
            {
                foreach (var removedDrive in removedDrives)
                {
                    if (DeviceRemoved != null)
                    {
                        DeviceRemoved.Invoke(new Device(removedDrive));
                    }
                }
            }
        }
 void IMMNotificationClient.OnDeviceRemoved(string deviceId)
 {
     InvokeOnSynchronizationContext(() =>
     {
         DeviceRemoved?.Invoke(this, new AudioDeviceRemovedEventArgs(deviceId));
     });
 }
        private void TryToRemoveOldDevices()
        {
            var lastCheck = DateTime.Now.AddMinutes(-1 * _removeDevicesAfterMinutes);

            if (_lastRemovalOfOldDevices < lastCheck)
            {
                DeviceRemoved?.Invoke(this, $"Removal length: {this.Count} ");

                _lastRemovalOfOldDevices = DateTime.Now;

                for (var i = this.Count - 1; i > 0; i--)
                {
                    var item = this.ElementAt(i);

                    if (item.Value.DateTimeLastVisit < lastCheck)
                    {
                        item.Value.Thread.Abort();

                        DeviceRemoved?.Invoke(this, item.Key);

                        this.Remove(item.Key);
                    }
                }

                DeviceRemoved?.Invoke(this, $"Removal count afterwards: {this.Count} ");
            }
        }
Exemple #6
0
 /// <summary>
 /// New devices found.
 /// </summary>
 private void CallBack(List <AndroidDevice> list)
 {
     lock (devicesLock)
     {
         // Look for removed devices
         var removed = devices.Where(x => list.All(y => y.Serial != x.Serial)).ToList();
         foreach (var device in removed)
         {
             devices.Remove(device);
             DeviceRemoved.Fire(this, new EventArgs <AndroidDevice>(device));
         }
         // Look for added or changed devices
         foreach (var device in list)
         {
             var serial   = device.Serial;
             var existing = devices.FirstOrDefault(x => x.Serial == serial);
             if (existing == null)
             {
                 // Device added
                 devices.Add(device);
                 DeviceAdded.Fire(this, new EventArgs <AndroidDevice>(device));
             }
             else if (existing.DeviceState != device.DeviceState)
             {
                 // State changed
                 devices.Remove(existing);
                 devices.Add(device);
                 DeviceStateChanged.Fire(this, new EventArgs <AndroidDevice>(device));
             }
         }
         receivedInitialUpdate = true;
         Monitor.PulseAll(devicesLock);
     }
 }
Exemple #7
0
        private void SearchForDevice(object state)
        {
            var devices = HidDevices
                          .EnumeratePaths(_Filter)
                          .ToArray();

            // Get all the devices that has connected since the last check
            var newDevices = devices.Except(_SeenDevices);

            // Get all the device that has disconnected since the last check
            var removedDevices = _SeenDevices.Except(devices);

            foreach (var device in newDevices)
            {
                _Logger.Information("Detected attached HID devices matching filter {Filter}", _Filter);
                DeviceAttached?.Invoke(this, device);
            }

            foreach (var device in removedDevices)
            {
                _Logger.Information("Detected removed HID devices matching filter {Filter}", _Filter);
                DeviceRemoved?.Invoke(this, device);
            }

            _SeenDevices = devices;
        }
Exemple #8
0
        private void HandleMessage(ButtplugMessage message)
        {
            var callback = GetPromise(message.Id);

            if (callback != null)
            {
                callback.SetResult(message);
            }
            else
            {
                if (message is DeviceAdded)
                {
                    DeviceAdded added = (DeviceAdded)message;
                    Debug.WriteLine($"Device Added: {added.DeviceName} [{added.DeviceIndex}]");
                    AddDevice(added.DeviceName, added.DeviceIndex);
                }
                else if (message is DeviceRemoved)
                {
                    DeviceRemoved removed = (DeviceRemoved)message;
                    Debug.WriteLine($"Device Removed: [{removed.DeviceIndex}]");
                    RemoveDevice(removed.DeviceIndex);
                }
                else
                {
                    Debug.WriteLine("Unknown messageId");
                }
            }
        }
Exemple #9
0
 /// <summary>
 /// Raises the DeviceRemoved event.
 /// </summary>
 /// <param name="e">The event arguments.</param>
 protected virtual void OnDeviceRemoved(DeviceRemovedEventArgs e)
 {
     if (DeviceRemoved != null)
     {
         DeviceRemoved.GetInvocationList().InvokeEventGUIThreadSafe(this, e);
     }
 }
 private void ConnectionStatusChangedHandler([NotNull] BluetoothLEDevice aDevice, [NotNull] object aObj)
 {
     if (_bleDevice.ConnectionStatus == BluetoothConnectionStatus.Disconnected)
     {
         DeviceRemoved?.Invoke(this, new EventArgs());
     }
 }
Exemple #11
0
        private async static void HardDeviceList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
            {
                switch (e.Action)
                {
                case System.Collections.Specialized.NotifyCollectionChangedAction.Add:
                    {
                        foreach (DriveRelatedData Device in e.NewItems)
                        {
                            DeviceAdded?.Invoke(null, Device);
                        }

                        break;
                    }

                case System.Collections.Specialized.NotifyCollectionChangedAction.Remove:
                    {
                        foreach (DriveRelatedData Device in e.OldItems)
                        {
                            DeviceRemoved?.Invoke(null, Device);
                        }

                        break;
                    }
                }
            });
        }
Exemple #12
0
 private void OnDeviceRemoved(object sender, DeviceNotificationEventArgs e)
 {
     e.TryGetDevice(out var device);
     if (device.DeviceID.GetHashCode() == Device.DeviceID.GetHashCode())
     {
         DeviceRemoved?.Invoke(this);
     }
 }
Exemple #13
0
        private void IDestroyDevice(DeviceID id)
        {
            ResponseDevice device = m_devices[id];

            DeviceRemoved?.Invoke(this, new DeviceEventArgs(device, DeviceEventType.DeviceRemoved));
            m_devices.Remove(id);
            device.IDeviceRemoved();
        }
Exemple #14
0
        /// <summary>
        /// Message Received event handler. Either tries to match incoming messages as replies to
        /// messages we've sent, or fires an event related to an incoming event, like device
        /// additions/removals, log messages, etc.
        /// </summary>
        /// <param name="aSender">Object sending the open event, unused.</param>
        /// <param name="aArgs">Event parameters, including the data received.</param>
        private async void MessageReceivedHandler(object aSender, MessageReceivedEventArgs aArgs)
        {
            var msg = aArgs.Message;

            switch (msg)
            {
            case Log l:
                Log?.Invoke(this, new LogEventArgs(l));
                break;

            case DeviceAdded d:
                var dev = new ButtplugClientDevice(_bpLogManager, this, SendDeviceMessageAsync, d);
                _devices.Add(d.DeviceIndex, dev);
                DeviceAdded?.Invoke(this, new DeviceAddedEventArgs(dev));
                break;

            case DeviceRemoved d:
                if (!_devices.ContainsKey(d.DeviceIndex))
                {
                    ErrorReceived?.Invoke(this,
                                          new ButtplugExceptionEventArgs(
                                              new ButtplugDeviceException(_bpLogger,
                                                                          "Got device removed message for unknown device.",
                                                                          msg.Id)));
                    return;
                }

                var oldDev = _devices[d.DeviceIndex];
                _devices.Remove(d.DeviceIndex);
                DeviceRemoved?.Invoke(this, new DeviceRemovedEventArgs(oldDev));
                break;

            case ScanningFinished _:
                // The scanning finished event is self explanatory and doesn't require extra arguments.
                ScanningFinished?.Invoke(this, new EventArgs());
                break;

            case Error e:
                // This will both log the error and fire it from our ErrorReceived event handler.
                ErrorReceived?.Invoke(this, new ButtplugExceptionEventArgs(ButtplugException.FromError(_bpLogger, e)));

                if (e.ErrorCode == Error.ErrorClass.ERROR_PING)
                {
                    PingTimeout?.Invoke(this, EventArgs.Empty);
                    await DisconnectAsync().ConfigureAwait(false);
                }

                break;

            default:
                ErrorReceived?.Invoke(this,
                                      new ButtplugExceptionEventArgs(
                                          new ButtplugMessageException(_bpLogger,
                                                                       $"Got unhandled message: {msg}",
                                                                       msg.Id)));
                break;
            }
        }
Exemple #15
0
        private void OnDeviceRemoved(object sender, DeviceNotificationEventArgs e)
        {
            if (e.DeviceId != DeviceId)
            {
                return;
            }

            DeviceRemoved?.Invoke(this);
        }
Exemple #16
0
        public void OnDeviceRemoved(string deviceId)
        {
            if (deviceId != DeviceId)
            {
                return;
            }

            DeviceRemoved?.Invoke(this);
        }
Exemple #17
0
        public void OnDeviceStateChanged(string deviceId, DeviceState newState)
        {
            if (deviceId != DeviceId || newState.HasFlag(DeviceState.Active))
            {
                return;
            }

            DeviceRemoved?.Invoke(this);
        }
Exemple #18
0
        public void InterestedUSBChange(int VID, int PID, bool connected)
        {
            if (!connected)
            {
                var dev = devices.First(x => x is HyperXAlloyRgbControlDevice hx && hx.HID == PID);

                devices.Remove(dev);
                DeviceRemoved?.Invoke(this, new Events.DeviceChangeEventArgs(dev));
            }
            else
            {
                var sdevice = supportedDevices.First(x => x.Pid == PID);

                HyperXKeyboardSupport hyperX = new HyperXKeyboardSupport(sdevice.Vid, sdevice.Pid, sdevice.Usb);

                dv = new HyperXAlloyRgbControlDevice
                {
                    Name          = sdevice.Name,
                    DeviceType    = DeviceTypes.Keyboard,
                    Driver        = this,
                    ProductImage  = Assembly.GetExecutingAssembly().GetEmbeddedImage("Driver.HyperXAlloy.RGB." + sdevice.Name + ".png"),
                    HyperXSupport = hyperX,
                    GridHeight    = 6,
                    GridWidth     = 23,
                    Has2DSupport  = true,
                    HID           = sdevice.Pid
                };

                KeyboardHelper.AddKeyboardWatcher(sdevice.Vid, sdevice.Pid, dv.HandleInput);

                List <ControlDevice.LedUnit> leds = new List <ControlDevice.LedUnit>();
                int ctt  = 0;
                var tled = new ControlDevice.LedUnit[106];
                int ct   = 0;

                foreach (var tp in hyperX.humm)
                {
                    var ld = new ControlDevice.LedUnit
                    {
                        LEDName = HyperXKeyboardSupport.KeyNames[tp.Order],
                        Data    = new ControlDevice.PositionalLEDData
                        {
                            LEDNumber = Array.IndexOf(hyperX.humm, tp),
                            X         = tp.X,
                            Y         = tp.Y
                        },
                    };

                    leds.Add(ld);
                }

                dv.LEDs = leds.OrderBy(p => ((ControlDevice.PositionalLEDData)p.Data).X + ((ControlDevice.PositionalLEDData)p.Data).Y).ToArray();

                devices.Add(dv);
                DeviceAdded?.Invoke(this, new Events.DeviceChangeEventArgs(dv));
            }
        }
Exemple #19
0
        private void OnDeviceStateChanged(object sender, DeviceStateChangedEventArgs e)
        {
            if (e.DeviceId != DeviceId || e.DeviceState.HasFlag(DeviceState.Active))
            {
                return;
            }

            DeviceRemoved?.Invoke(this);
        }
        /// <summary>
        /// Websocket Message Received event handler. Either tries to match incoming messages as
        /// replies to messages we've sent, or fires an event related to an incoming event, like
        /// device additions/removals, log messages, etc.
        /// </summary>
        /// <param name="aSender">Object sending the open event, unused.</param>
        /// <param name="aArgs">Event parameters, including the data received.</param>
        private void MessageReceivedHandler(object aSender, WebSocket4Net.MessageReceivedEventArgs aArgs)
        {
            var msgs = Deserialize(aArgs.Message);

            foreach (var msg in msgs)
            {
                if (msg.Id > 0 && _waitingMsgs.TryRemove(msg.Id, out TaskCompletionSource <ButtplugMessage> queued))
                {
                    queued.TrySetResult(msg);
                    continue;
                }

                switch (msg)
                {
                case Log l:
                    _owningDispatcher.Send(_ =>
                    {
                        Log?.Invoke(this, new LogEventArgs(l));
                    }, null);
                    break;

                case DeviceAdded d:
                    var dev = new ButtplugClientDevice(d);
                    _devices.AddOrUpdate(d.DeviceIndex, dev, (idx, old) => dev);
                    _owningDispatcher.Send(_ =>
                    {
                        DeviceAdded?.Invoke(this, new DeviceEventArgs(dev, DeviceEventArgs.DeviceAction.ADDED));
                    }, null);
                    break;

                case DeviceRemoved d:
                    if (_devices.TryRemove(d.DeviceIndex, out ButtplugClientDevice oldDev))
                    {
                        _owningDispatcher.Send(_ =>
                        {
                            DeviceRemoved?.Invoke(this, new DeviceEventArgs(oldDev, DeviceEventArgs.DeviceAction.REMOVED));
                        }, null);
                    }

                    break;

                case ScanningFinished sf:
                    _owningDispatcher.Send(_ =>
                    {
                        ScanningFinished?.Invoke(this, new ScanningFinishedEventArgs(sf));
                    }, null);
                    break;

                case Error e:
                    _owningDispatcher.Send(_ =>
                    {
                        ErrorReceived?.Invoke(this, new ErrorEventArgs(e));
                    }, null);
                    break;
                }
            }
        }
Exemple #21
0
 public bool TryRemoveDevice(DeviceType device, out DeviceStatus status)
 {
     if (_devices.TryRemove(device, out status))
     {
         DeviceRemoved?.Invoke(this, status);
         return(true);
     }
     return(false);
 }
Exemple #22
0
        protected virtual void OnDeviceRemoved(DEV_BROADCAST_VOLUME volume)
        {
            char c = DriveMaskToLetter(volume.dbcv_unitmask);
            var  e = new RemovableMediaEventArgs()
            {
                Drive = c + ":\\",
            };

            DeviceRemoved?.BeginInvoke(this, e, null, null);
        }
Exemple #23
0
 // Remove a device handle from the internal list
 private bool _EnumerateRemove(IntPtr hDevice)
 {
     if (_devices.ContainsKey(hDevice))
     {
         DeviceRemoved?.Invoke(this, new RawInputEventArgs(_devices[hDevice], null));
         _devices.Remove(hDevice);
         return(true);
     }
     return(false);
 }
Exemple #24
0
        static private void HidDeviceRemovedEventHandler(HidDevice hd)
        {
            hd.Inserted           -= HidDeviceAddedEventHandler;
            hd.Removed            -= HidDeviceRemovedEventHandler;
            hd.MonitorDeviceEvents = false;
            hd.CloseDevice();

            Console.WriteLine("Device removed");
            DeviceRemoved?.Invoke(hd);
        }
        public void Disconnect()
        {
            DeviceRemoved?.Invoke(this, new EventArgs());
            _txChar = null;
            _rxChar = null;
            _indexedChars.Clear();

            _bleDevice.Dispose();
            _bleDevice = null;
        }
Exemple #26
0
 private void RaiseDeviceRemoved(int id)
 {
     if (SynchronizationContext.Current != _synchronizationContext)
     {
         _synchronizationContext.Post(o => DeviceRemoved?.Invoke(this, id), null);
     }
     else
     {
         DeviceRemoved?.Invoke(this, id);
     }
 }
Exemple #27
0
        private void DeleteProperty(Property property)
        {
            Device device = GetOrAddDevice(property.DeviceName);

            device.Delete(property);
            if (device.Properties.Count == 0)
            {
                devices.Remove(device.Name);
                DeviceRemoved?.Invoke(device);
            }
        }
Exemple #28
0
 private void OnDeviceStateChanged(object sender, DeviceStateChangedEventArgs e)
 {
     if (e.DeviceState == DeviceState.NotPresent || e.DeviceState == DeviceState.UnPlugged)
     {
         e.TryGetDevice(out var device);
         if (device.DeviceID.GetHashCode() == Device.DeviceID.GetHashCode())
         {
             DeviceRemoved?.Invoke(this);
         }
     }
 }
Exemple #29
0
        public void DestroyResource(TDevice device)
        {
            TResource resource;

            if (Resources.TryGetValue(device, out resource))
            {
                Resources.Remove(device);
                FDestroyResourceAction(Metadata, resource, DestroyReason.DeviceLost);
                DeviceRemoved?.Invoke(this, device);
            }
        }
Exemple #30
0
        public void Disconnect()
        {
            DeviceRemoved?.Invoke(this, new EventArgs());
            for (int i = 0; i < _gattCharacteristics.Length; i++)
            {
                _gattCharacteristics[i] = null;
            }

            _bleDevice.Dispose();
            _bleDevice = null;
        }