Ejemplo n.º 1
0
        public static void Add(Socket _Socket)
        {
            Device _Device = new Device(_Socket);

            if (Devices.ContainsKey(_Socket.Handle))
            {
                Devices[_Socket.Handle].Connection = _Socket;
            }
            else
            {
                Devices.Add(_Socket.Handle, _Device);
            }
        }
        public void DeviceDataGridLoaded()
        {
            if (_loadExecuted == true)
            {
                return;
            }
            else
            {
                _loadExecuted = true;
            }

            foreach (var device in _machineRecordService.GetDevicesForClient(ClientId))
            {
                Devices.Add(device);
            }

            if (!string.IsNullOrEmpty(_deviceToSelect))
            {
                SelectedDevice  = Devices.First(r => r.SerialNumber == _deviceToSelect);
                _deviceToSelect = null;
            }
            else
            {
                SelectedDevice = Devices.FirstOrDefault();
            }
        }
Ejemplo n.º 3
0
 public void AddDevice(Device device)
 {
     MainWindow.Dispatcher.Invoke(() =>
     {
         Devices.Add(device);
     });
 }
        void UpdateDeviceUpdated(EventData data)
        {
            if (data != null)
            {
                if (data.Id == "DEVICE_UPDATED" && data.Data01 != null)
                {
                    var device = (DeviceDescription)data.Data01;

                    int i = Devices.ToList().FindIndex(x => x.UniqueId == device.UniqueId);
                    if (i >= 0)
                    {
                        if (device.Enabled)
                        {
                            Devices[i] = device;
                        }
                        else
                        {
                            Devices.RemoveAt(i);
                        }
                    }
                    else if (device.Enabled)
                    {
                        Devices.Add(device);
                    }
                }
            }
        }
Ejemplo n.º 5
0
 void DeviceMonitor_UpdateDeviceListEvent(object sendor, UpdateDeviceListEventArgs e)
 {
     System.Windows.Application.Current.Dispatcher.Invoke(() => {
         try
         {
             Devices.Clear();
             if (e != null && e.DeviceList != null)
             {
                 foreach (var device in e.DeviceList)
                 {
                     Devices.Add(device);
                 }
             }
             if (Devices.Count > 0)
             {
                 ConnectedState = DeviceConncectState.CanConncect;
             }
             else
             {
                 ConnectedState = DeviceConncectState.NoDevice;
             }
         }
         catch (Exception ex)
         {
         }
     });
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Loads devices useing the SDK
        /// </summary>
        async Task LoadDevicesAsync()
        {
            IsLoadingDevices = true;
            IsDevicesVisible = !IsLoadingDevices;

            try
            {
                var devices = await DeviceDriveManager.Current.GetDevicesAsync();

                Devices.Clear();
                foreach (var device in devices)
                {
                    Devices.Add(device);
                }

                // Update GUI
                OnPropertyChanged(nameof(SelectedDeviceName));
            }
            finally
            {
                IsLoadingDevices = false;
                IsDevicesVisible = !IsLoadingDevices;
            }


            // Update properties
            await LoadDevicePropertiesAsync(SelectedDevice);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 如果已经知道一个设备,则更新已有设备的信息。如果是一个新设备,把它添加到列表中。
        ///
        /// 改这个要慎重,它被LANDiscoverer调用,还被Device的Connect调用。
        /// </summary>
        /// <param name="device"></param>
        /// <param name="needMerge"></param>
        /// <returns></returns>

        public Device AddOrUpdateDevice(Device device, bool needMerge = true)
        {
            //检查这个Device是否已知。
            lock (locker)
            {
                Preconditions.Check(device != null && !string.IsNullOrEmpty(device.ID));
                if (device.ID == LocalDevice.ID)
                {
                    return(null);
                }

                var existingDevice = Devices.FirstOrDefault(o => o.ID == device.ID);
                if (existingDevice == null)
                {
                    Devices.Add(device);
                    device.IsFirstSeen = true;
                    _deviceDiscovered?.Invoke(device);
                }
                else
                {
                    if (needMerge)
                    {
                        //如果这个设备原来已经存在了,那么其实应该返回原来的设备,只是需要将新发现的不同的地方复制到原来的设备上
                        //各事件都是绑定到原来的设备的。
                        existingDevice.CopyFrom(device);
                    }
                    //不管是否Merge,都要修改IP。
                    existingDevice.DefaultIP = device.DefaultIP;
                    device             = existingDevice;
                    device.IsFirstSeen = false;
                }
                device.LastUpdateTime = Environment.TickCount;
                return(device);
            }
        }
Ejemplo n.º 8
0
        void OnRefresh(object arg = null)
        {
            IsRefreshing = true;

            Task.Run(() => {
                var devices = DeviceManager.GetDevices(DeviceManager.DeviceType.Joystick, DeviceManager.DeviceType.Gamepad);

                // removing disconnected devices
                var devicesToRemove = Devices.Where(x => !devices.Any(y => y.Id == x.Id)).ToArray();
                foreach (var device in devicesToRemove)
                {
                    Application.Current.Dispatcher.Invoke(() => {
                        Devices.Remove(device);
                    });
                }

                // adding connected devices
                foreach (var device in devices)
                {
                    var config = ConfigManager.Config.DeviceConfigs?.FirstOrDefault(x => x.Id == device.Id);
                    if (config == null || Devices.Any(x => x.Id == device.Id))
                    {
                        continue;
                    }

                    Application.Current.Dispatcher.Invoke(() => {
                        Devices.Add(new DeviceViewModel(config));
                    });
                }
            }).ContinueWith(_ => {
                IsRefreshing = false;
            });
        }
Ejemplo n.º 9
0
        private void Devices_CmdCopy_Executed(object sender, ExecutedRoutedEventArgs evt)
        {
            Device device = Devices.First(d => IsSelectedDevice(d));

            if (device is DectDevice dectDevice)
            {
                DectDevice newDevice = new DectDevice(dectDevice)
                {
                    DeviceName = string.Empty
                };
                if (newDevice.Edit(this))
                {
                    Devices.Add(newDevice);
                    Devices_SelectDevice(newDevice);
                }
            }
            if (device is JuisDevice juisDevice)
            {
                JuisDevice newDevice = new JuisDevice(juisDevice)
                {
                    DeviceName = string.Empty
                };
                if (newDevice.Edit(this))
                {
                    Devices.Add(newDevice);
                    Devices_SelectDevice(newDevice);
                }
            }

            Devices_SetDataGridFocus();
        }
Ejemplo n.º 10
0
        private void Sniffer_DeviceFound(MTConnectDevice device)
        {
            if (Configuration.Devices != null)
            {
                // Generate the Device ID Hash
                string deviceId = DataClient.GenerateDeviceId(device);

                // Check to make sure the Device is not already added
                if (!Configuration.Devices.Exists(o => o.DeviceId == deviceId))
                {
                    var conn = new Api.v2.Data.Connection();
                    conn.Address         = device.IpAddress.ToString();
                    conn.PhysicalAddress = device.MacAddress.ToString();
                    conn.Port            = device.Port;

                    // Create a new Device and start it
                    var d = new Device(deviceId, conn, device.DeviceName);

                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        Devices.Add(d);
                    }));

                    log.Info("New Device Added : " + deviceId + " : " + device.DeviceName + " : " + device.IpAddress + " : " + device.Port);
                }
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Accept the new client and store it in memory.
        /// </summary>
        /// <param name="AsyncEvent">The <see cref="SocketAsyncEventArgs"/> instance containing the event data.</param>
        private static void ProcessAccept(SocketAsyncEventArgs AsyncEvent)
        {
            if (AsyncEvent.AcceptSocket.Connected)
            {
                string IpAddress = ((IPEndPoint)AsyncEvent.AcceptSocket.RemoteEndPoint).Address.ToString();

                if (IpAddress.StartsWith("192.168."))
                {
                    SocketAsyncEventArgs ReadEvent = NetworkTcp.ReadPool.Dequeue();

                    if (ReadEvent != null)
                    {
                        NetworkToken Token  = new NetworkToken(ReadEvent, AsyncEvent.AcceptSocket);
                        Device       Device = new Device(Token);

                        Devices.Add(Device);

                        if (!Token.Socket.ReceiveAsync(ReadEvent))
                        {
                            NetworkTcp.ProcessReceive(ReadEvent);
                        }
                    }
                    else
                    {
                        Logging.Warning(typeof(NetworkTcp), "Server is full, new connections cannot be accepted.");
                    }
                }
            }

            NetworkTcp.StartAccept(AsyncEvent);
        }
Ejemplo n.º 12
0
        private void OnTick(object sender, object e)
        {
            var devicesList = ftManager.GetDeviceList();

            // add devices we don't have yet
            var devicesToAdd = devicesList.Where(x => Devices.All(y => y.DeviceId != x.DeviceId)).ToList();

            foreach (var device in devicesToAdd)
            {
                Devices.Add(new DeviceNode(device));
            }

            //
            if (DeviceConnection == null && devicesList.Count > 0)
            {
                OnSelectDevice(Devices[0]);
            }

            // remove any devices that are no longer connected
            var devicesToDelete = Devices.Where(x => devicesList.All(y => y.DeviceId != x.DeviceId)).ToList();

            foreach (var deviceNode in devicesToDelete)
            {
                Devices.Remove(deviceNode);
            }
        }
Ejemplo n.º 13
0
 public override bool Connect()
 {
     Disconnect();
     try
     {
         // Find all the GameControl devices that are attached.
         var dinput = new DirectInput();
         foreach (
             var di in
             dinput.GetDevices(DeviceClass.GameController,
                               DeviceEnumerationFlags.AttachedOnly))
         {
             var joy = new JoystickDevice(di, dinput);
             Devices.Add(joy.GetJoystickGuid(), joy);
             joy.Connect();
         }
     }
     catch (ArgumentException ex)
     {
         var message = LanguageManager.GetPhrase(Phrases.SettingsHardwareGuidConflict);
         var header  = LanguageManager.GetPhrase(Phrases.MainFormName) + " - " + LanguageManager.GetPhrase(Phrases.MessageBoxWarningHeader);
         MessageBox.Show(message, header, MessageBoxButton.OK, MessageBoxImage.Warning);
         return(false);
     }
     catch (Exception)
     {
         return(false);
     }
     return(true);
 }
Ejemplo n.º 14
0
        private DeviceMonitor AddOrGetDevice(string deviceName, DeviceType deviceType, Guid deviceGuid)
        {
            DeviceMonitor deviceMonitor = null;

            if (!_nameToDeviceMonitor.TryGetValue(deviceName, out deviceMonitor))
            {
                deviceMonitor = new DeviceMonitor(deviceName, deviceType, deviceGuid, _mapper);
                _nameToDeviceMonitor.Add(deviceName, deviceMonitor);
                Devices.Add(deviceMonitor);
                switch (deviceType)
                {
                case DeviceType.Unknown:
                    UnknownDevices.Add(deviceMonitor);
                    break;

                case DeviceType.Keyboard:
                    KeyboardDevices.Add(deviceMonitor);
                    break;

                case DeviceType.Mouse:
                    MouseDevices.Add(deviceMonitor);
                    break;

                case DeviceType.Joystick:
                    JoystickDevices.Add(deviceMonitor);
                    break;
                }
            }
            return(deviceMonitor);
        }
        async Task LoadItems()
        {
            if (IsBusy)
            {
                return;
            }
            IsBusy = true;
            try
            {
                Devices.Clear();
                using (var bt = CrossBluetooth.Current)
                {
                    var bts = await bt.GetPairedDevices();

                    foreach (var device in bts)
                    {
                        Devices.Add(device);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
Ejemplo n.º 16
0
 private void OnDeviceDiscovered(IDevice device)
 {
     if (device.Name != null)
     {
         Devices.Add(device);
     }
 }
Ejemplo n.º 17
0
        public void Investigate()
        {
            foreach (ManagementObject obj in searcher.Get())
            {
                PCIDevice device = new PCIDevice(obj);
                Devices.Add(device);

                bool hasNoDriver = (device.InfName == string.Empty);

                if (device.ID.Contains("DEV_C000"))
                {
                    FoundC000      = true;
                    FoundCleanC000 = hasNoDriver;
                    device.Clean   = hasNoDriver;
                }
                else if (device.ID.Contains("DEV_0001"))
                {
                    Found0001      = true;
                    FoundClean0001 = hasNoDriver;
                    device.Clean   = hasNoDriver;
                }
                else if (device.ID.Contains("DEV_0002"))
                {
                    Found0002      = true;
                    FoundClean0002 = hasNoDriver;
                    device.Clean   = hasNoDriver;
                }
                else if (device.ID.Contains(@"VEN_XEN&DEV_0000"))
                {
                    device.Clean = true;
                }
                else
                {
                    FoundOther = true;
                }
            }

            if (!FoundAny)
            {
                Result     = InvestigationResult.Unclean;
                ResultText = "No XEN PCI devices found!";
            }
            else if (FoundOther)
            {
                Result     = InvestigationResult.Unclean;
                ResultText = "Unclean XEN PCI devices found!";
            }
            else if (Clean)
            {
                Result     = InvestigationResult.Clean;
                ResultText = "Clean XEN PCI devices found.";
            }
            else
            {
                Result     = InvestigationResult.Unknown;
                ResultText = "Unexpected situation. Please create bug report!";
            }

            hasInvestigated = true;
        }
Ejemplo n.º 18
0
 private void CheckForControllers()
 {
     lock (base.Devices)
     {
         var compatibleDevices = HidDevices.Enumerate().ToList();
         var regex             = new Regex("^.*2717.+3144.*$");
         compatibleDevices =
             compatibleDevices.Where(d => (d.Attributes.VendorId == 0x2717 && d.Attributes.ProductId == 0x3144) || regex.IsMatch(d.DevicePath))
             .ToList();
         foreach (var deviceInstance in compatibleDevices)
         {
             if (Devices.Any(d => ((MyMiDevice)d).Device.DevicePath == deviceInstance.DevicePath))
             {
                 continue;
             }
             Devices.Add(new MyMiDevice(deviceInstance));
         }
         foreach (var inputDevice in Devices)
         {
             var deviceReference = (MyMiDevice)inputDevice;
             if (compatibleDevices.All(d => d.DevicePath != deviceReference.Device.DevicePath))
             {
                 Devices.Remove(deviceReference);
             }
         }
     }
 }
Ejemplo n.º 19
0
 public void DeserializeElements(string settingsFileName)
 {
     Debug.WriteLine($"Deserializing LocalDevices from {settingsFileName}");
     Logger.Debug($"Deserializing LocalDevices from {settingsFileName}");
     try
     {
         if (!string.IsNullOrEmpty(settingsFileName) && File.Exists(settingsFileName))
         {
             XmlDocument settings = new XmlDocument();
             settings.Load(settingsFileName);
             var           devicesXml       = settings.DocumentElement.SelectSingleNode("Devices");
             XmlSerializer deviceSerializer = new XmlSerializer(typeof(AdvantechDevice));
             foreach (XmlNode deviceXml in devicesXml.SelectNodes("AdvantechDevice"))
             {
                 Devices.Add((AdvantechDevice)deviceSerializer.Deserialize(new StringReader(deviceXml.OuterXml)));
             }
             var           engineBindingsXml = settings.DocumentElement.SelectSingleNode("EngineBindings");
             XmlSerializer bindingSerializer = new XmlSerializer(typeof(LocalGpiDeviceBinding), new XmlRootAttribute("EngineBinding"));
             foreach (XmlNode bindingXml in engineBindingsXml.SelectNodes("EngineBinding"))
             {
                 EngineBindings.Add((LocalGpiDeviceBinding)bindingSerializer.Deserialize(new StringReader(bindingXml.OuterXml)));
             }
         }
     }
     catch (Exception e) {
         Debug.WriteLine(e);
         Logger.Error(e, $"Exception while DeserializeElements:\n {e}");
     }
 }
Ejemplo n.º 20
0
        public void UpdateDevicesList()
        {
            var devices = AdbShell.GetDevices().Select((id) => new Device(id)).ToList();

            if (devices.Count > 0)
            {
                var myIdSets = new List <string>(devices.Select(c => c.Id));
                Devices.Clear();
                myIdSets.ForEach((x) => Devices.Add(new Device(x)));
                SelectedDevice = new Device(String.Empty);
            }
            else
            {
                Devices.Clear();
                SelectedDevice = new Device(String.Empty);
            }
            //Devices.Clear();
            //var devices = AdbShell.GetDevices().Select((id) => new Device(id)).ToList();
            //if (devices.Count > 0)
            //{
            //    SelectedDevice = new Device(String.Empty);
            //}
            //else
            //{
            //    SelectedDevice = new Device(String.Empty);
            //}
            //devices.ForEach((x) => Devices.Add(x));
        }
Ejemplo n.º 21
0
        private void addDevice(Device rawDevice)
        {
            _tsiFile.AddDevice(rawDevice);
            var dvm = new DeviceViewModel(rawDevice, this);

            Devices.Add(dvm);
        }
Ejemplo n.º 22
0
 //Copy Constructor
 public TECSubScope(TECSubScope sourceSubScope, Dictionary <Guid, Guid> guidDictionary = null,
                    ObservableListDictionary <ITECObject> characteristicReference      = null) : this()
 {
     if (guidDictionary != null)
     {
         guidDictionary[_guid] = sourceSubScope.Guid;
     }
     foreach (IEndDevice device in sourceSubScope.Devices)
     {
         Devices.Add(device);
     }
     foreach (TECPoint point in sourceSubScope.Points)
     {
         var toAdd = new TECPoint(point);
         characteristicReference?.AddItem(point, toAdd);
         Points.Add(toAdd);
     }
     foreach (TECInterlockConnection interlock in sourceSubScope.Interlocks)
     {
         var toAdd = new TECInterlockConnection(interlock);
         characteristicReference?.AddItem(interlock, toAdd);
         Interlocks.Add(toAdd);
     }
     foreach (TECScopeBranch branch in sourceSubScope.ScopeBranches)
     {
         var toAdd = new TECScopeBranch(branch);
         characteristicReference?.AddItem(branch, toAdd);
         ScopeBranches.Add(toAdd);
     }
     this.copyPropertiesFromScope(sourceSubScope);
 }
Ejemplo n.º 23
0
        private unsafe void Initialize(Guid guid)
        {
            ClassGuid = guid;

            _handle = new HANDLE((IntPtr)PInvoke.SetupDiGetClassDevs(ClassGuid, null, new HWND((IntPtr)0), 0));
            if (_handle.Equals(Constants.INVALID_HANDLE_VALUE))
            {
                throw new Win32Exception();
            }


            uint            idx = 0;
            SP_DEVINFO_DATA data;

            data.cbSize = (uint)sizeof(SP_DEVINFO_DATA);
            while (PInvoke.SetupDiEnumDeviceInfo((void *)_handle.Value, idx, out data))
            {
                uint status         = 0;
                uint problem_number = 0;
                if (PInvoke.CM_Get_DevNode_Status(out status, out problem_number, data.DevInst, 0) == CONFIGRET.CR_SUCCESS)
                {
                    if ((status & (uint)DeviceNodeStatus.Started) == (uint)DeviceNodeStatus.Started)
                    {
                        Devices.Add(DeviceInfoFactory.Create(this, data));
                    }
                }

                idx++;
            }
        }
Ejemplo n.º 24
0
        private TsiFileViewModel(TsiFile tsiFile)
        {
            _tsiFile = tsiFile;

            // Is new file?
            if (tsiFile.Path == null)
            {
                IsChanged = true;
            }
            else
            {
                foreach (var device in _tsiFile.Devices)
                {
                    var dvm = new DeviceViewModel(device, this);
                    Devices.Add(dvm);
                    dvm.DirtyStateChanged += (s, a) => onDeviceChanged();
                }

                // Set selection if possible
                SelectedDevice = Devices.FirstOrDefault();

                AcceptChanges();
            }

            Devices.CollectionChanged += Devices_CollectionChanged;
        }
 public void PopupDevices(List <Device> devices)
 {
     ThreadInvoker.UIInvoke(() => {
         Devices.Clear();
         try {
             if (devices == null || devices.Count == 0)
             {
                 TipWord = ServiceProvider.Current?.GetInstance <ILanguageService>()?.FindResourceString("PleaseConnectToPhone");
                 return;
             }
             devices.ForEach(p => {
                 var newDev = new AdbDeviceModel {
                     Name = p.Disply, Device = p
                 };
                 Devices.Add(newDev);
             });
             SelectedDevice = Devices[0];
             TipWord        = ServiceProvider.Current?.GetInstance <ILanguageService>()?.FindResourceString("ChooseDeviceDetected");
         }
         catch (Exception ex) {
             Logger.WriteLine($"{nameof(DeviceSelectorViewModel)}->{ nameof(PopupDevices)}:{ ex.Message}");
             MsgBoxService.ShowError($"{nameof(PopupDevices)}:{ex.Message}");
         }
     });
 }
Ejemplo n.º 26
0
        private void Devices_EditDevice(Device device)
        {
            Window deviceDialog;

            switch (device.DeviceKind)
            {
            case DeviceKind.DECT:
                deviceDialog = new DectDeviceDialog(device);
                break;

            case DeviceKind.JUIS:
                deviceDialog = new JuisDeviceDialog(device);
                break;

            default:
                throw new InvalidOperationException("Unsupported device kind");
            }

            deviceDialog.Owner = this;
            deviceDialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;

            if (deviceDialog.ShowDialog() == true)
            {
                if (Devices.IndexOf(device) < 0)
                {
                    Devices.Add(device);
                }

                Devices_RefreshView();
                Devices_SelectDevice(device);
            }
        }
Ejemplo n.º 27
0
        public async void RefreshDevicesList()
        {
            NoBluetooth       = false;
            BluetoothDisabled = false;
            NoDevicesPaired   = false;

            Devices.Clear();

            var result = await _commandRunner.EnqueueCommand(new ListDevicesCommand()).GetCompletedTask();

            if (result.Status != CommandStatus.Succeeded)
            {
                DiagnoseProblem();
                return;
            }

            foreach (var deviceInfoViewModel in result.Devices.Select(t => new DeviceInfoViewModel(t)))
            {
                Devices.Add(deviceInfoViewModel);
            }

            SortAndUpdateDisplayedCollection();

            if (Devices.Count == 0)
            {
                DiagnoseProblem();
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        ///     Devices  discoveared.
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        public void DeviceDiscovered(object sender, DeviceDiscoveredEventArgs e)
        {
            if (Devices == null)
            {
                Devices = new List <IDevice> ();
            }


            if (e.Device != null && !string.IsNullOrEmpty(e.Device.Name) &&
                e.Device.Name.ToLower() == HaccpConstant.Blue2DeviceName)
            {
                {
                    Devices.Add(e.Device);

                    if (IsConnected || Devices.Count != 1)
                    {
                        return;
                    }
                    if (Device.OS == TargetPlatform.Android)
                    {
                        Device.BeginInvokeOnMainThread(() => {
                            ConnectToWand(e.Device);
                        });
                    }
                    else
                    {
                        ConnectToWand(e.Device);
                    }
                }
            }
        }
Ejemplo n.º 29
0
        private void OnDefaultPlaybackDeviceChanged(object sender, DeviceViewModel e)
        {
            // no longer any device
            if (e == null)
            {
                return;
            }

            var foundDevice = Devices.FirstOrDefault(d => d.Id == e.Id);

            if (foundDevice != null)
            {
                // Move to bottom.
                Devices.Move(Devices.IndexOf(foundDevice), Devices.Count - 1);
            }
            else
            {
                var foundAllDevice = _mainViewModel.AllDevices.FirstOrDefault(d => d.Id == e.Id);
                if (foundAllDevice != null)
                {
                    Devices.Clear();
                    foundAllDevice.Apps.CollectionChanged += Apps_CollectionChanged;
                    Devices.Add(foundAllDevice);
                }
            }
            UpdateTextVisibility();
            RaiseDevicesChanged();
        }
Ejemplo n.º 30
0
 private void RebuildMapForNewDevice(IHOTASDevice device, IHOTASDevice newDevice)
 {
     newDevice.ApplyButtonMap(device.ButtonMap.ToObservableCollection());
     newDevice.SetModeProfile(device.ModeProfiles);
     newDevice.SetModeActivation(ModeProfileActivationButtons);
     Devices.Add(newDevice);
 }
Ejemplo n.º 31
0
        /// <summary>
        /// Finds devices by device or service type synchronously using a timeout period.
        /// </summary>
        /// <param name="uriString">The URI string to search for or null / empty for all.</param>
        /// <param name="timeoutMS">The maximum timeout time in milliseconds to wait or -1 for wait forever.</param>
        /// <param name="maxDevices">The maximum number of devices to find before returning or 0 for as many as possible.</param>
        /// <param name="searchCompleted">True if the search completed and all available devices were returned.</param>
        /// <param name="addressFamily">The address family to search in. (Vista or above only).</param>
        /// <param name="resolveNetworkInterfaces">True to resolve network interface Guids.</param>
        /// <returns>A Devices list containing the found devices.</returns>
        public static Devices FindDevices(
            string uriString,
            int timeoutMS,
            int maxDevices,
            out bool searchCompleted,
            AddressFamilyFlags addressFamily = AddressFamilyFlags.IPvBoth,
            bool resolveNetworkInterfaces = false)
        {
            Discovery ldDiscovery = new Discovery(uriString, addressFamily, resolveNetworkInterfaces);
            Devices ldDevices = new Devices();
            bool lbSearchCompleted = false;
            ManualResetEvent lmreComplete = new ManualResetEvent(false);

            ldDiscovery.DeviceAdded +=
                (sender, args) =>
                {
                    ldDevices.Add(args.Device);
                    if (maxDevices > 0 && ldDevices.Count >= maxDevices)
                        lmreComplete.Set();
                };

            ldDiscovery.SearchComplete += (sender, args) =>
                {
                    lbSearchCompleted = true;
                    lmreComplete.Set();
                };

            ldDiscovery.Start();

            lmreComplete.WaitOne(timeoutMS);

            searchCompleted = lbSearchCompleted;
            ldDiscovery.Dispose();

            return ldDevices;
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Gets the devices by ModelName for this list.
        /// </summary>
        /// <param name="modelName">The ModelName for the devices to get.</param>
        /// <param name="recursive">True to search recursively.</param>
        /// <returns>The Devices that matched the type.</returns>
        public Devices DevicesByModelName(string modelName, bool recursive = true)
        {
            Devices ldDevices = new Devices();

            if (ModelName == modelName) ldDevices.Add(this);
            if (HasChildren) Children.AddDevicesByModelName(modelName, ldDevices, recursive);

            return ldDevices;
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Gets the devices by Type for this list.
        /// </summary>
        /// <param name="type">The Type for the devices to get.</param>
        /// <param name="recursive">True to search recursively.</param>
        /// <returns>The Devices that matched the type.</returns>
        public Devices DevicesByType(string type, bool recursive = true)
        {
            Devices ldDevices = new Devices();

            if (Type == type) ldDevices.Add(this);
            if (HasChildren) Children.AddDevicesByType(type, ldDevices, recursive);

            return ldDevices;
        }