private async Task CheckDeviceAsync()
        {
            while (!_close)
            {
                Thread.Sleep(10000);
                var aqs       = UsbDevice.GetDeviceSelector(VendorId, ProductId);
                var myDevices = await DeviceInformation.FindAllAsync(aqs);

                if (myDevices.Count == 0)
                {
                    IsAttached = false;
                    continue;
                }
                else
                {
                    if (IsAttached)
                    {
                        continue;
                    }

                    IsAttached = true;

                    _targetDevice = await UsbDevice.FromIdAsync(myDevices[0].Id);

                    if (_targetDevice != null)
                    {
                        GetInterfaces();
                    }

                    NotifyDeviceAvailabilityObservers();
                }
            }
        }
示例#2
0
            //Having got access to Hid device can access it:
            //HidDevice hidDevice;
            //private async Task GetNumericInputReportAsync()
            //{
            //    var inputReport = await DeviceList.Current.CurrentDevice.GetInputReportAsync(hidDevice.ReadWriteBuffer.ReportId);
            //    var inputReportControl = inputReport.GetNumericControl(hidDevice..ReadWriteBuffer.NumericUsagePage, hidDevice.ReadWriteBuffer.NumericUsageId);
            //    var data = inputReportControl.Value;
            //    this.NotifyUser("Value read: " + data.ToString("X2", NumberFormatInfo.InvariantInfo), NotifyType.StatusMessage);
            //}

            ////////////////////////////////////////////////////////////////////////////////
            /// These direct USB calls don't work??? :

            /// <summary>
            /// Use VID PID and class GUID
            /// </summary>
            /// <param name="deviceVid"></param>
            /// <param name="devicePid"></param>
            /// <param name="deviceInterfaceClassGuid"></param>
            /// <returns></returns>
            public async Task SearchForUSBDevice(ushort deviceVid, ushort devicePid, Guid deviceInterfaceClassGuid)
            {
                string aqs       = UsbDevice.GetDeviceSelector(deviceVid, devicePid, deviceInterfaceClassGuid);
                var    myDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(aqs, null);

                if (myDevices.Count == 0)
                {
                    NotifyUser("USB Device not found!");
                    return;
                }

                UsbDevice device = null;

                foreach (var mydevice in myDevices)
                {
                    device = await UsbDevice.FromIdAsync(mydevice.Id);

                    if (device != null)
                    {
                        break;
                    }
                }
                if (device != null)
                {
                    NotifyUser("USB Device found.");
                }
                else
                {
                    NotifyUser("USB Device not found!");
                }
            }
示例#3
0
        /// <summary>
        /// This method opens the device using the WinRT USB API. After the device is opened, save the device
        /// so that it can be used across scenarios.
        ///
        /// It is important that the FromIdAsync call is made on the UI thread because the consent prompt can only be displayed
        /// on the UI thread.
        ///
        /// This method is used to reopen the device after the device reconnects to the computer and when the app resumes.
        /// </summary>
        /// <param name="deviceInfo">Device information of the device to be opened</param>
        /// <param name="deviceSelector">The AQS used to find this device</param>
        /// <returns>True if the device was successfully opened, false if the device could not be opened for well known reasons.
        /// An exception may be thrown if the device could not be opened for extraordinary reasons.</returns>
        public async Task <bool> OpenDeviceAsync(DeviceInformation deviceInfo, String deviceSelector)
        {
            Device = await UsbDevice.FromIdAsync(deviceInfo.Id);

            Boolean successfullyOpenedDevice = false;

            MainPage.NotifyType notificationStatus;
            String notificationMessage = null;

            // Device could have been blocked by user or the device has already been opened by another app.
            if (Device != null)
            {
                successfullyOpenedDevice = true;

                DeviceInformation   = deviceInfo;
                this.DeviceSelector = deviceSelector;

                notificationStatus  = MainPage.NotifyType.StatusMessage;
                notificationMessage = "Device Opened";

                // Notify registered callback handle that the device has been opened
                if (OnDeviceConnected != null)
                {
                    OnDeviceConnected(this, DeviceInformation);
                }
            }
            else
            {
                successfullyOpenedDevice = false;

                notificationStatus = MainPage.NotifyType.ErrorMessage;

                DeviceAccessInformation dai = DeviceAccessInformation.CreateFromId(deviceInfo.Id);

                var deviceAccessStatus = dai.CurrentStatus;

                if (deviceAccessStatus == DeviceAccessStatus.DeniedByUser)
                {
                    notificationMessage = "Access to the device was blocked by the user.";
                }
                else if (deviceAccessStatus == DeviceAccessStatus.DeniedBySystem)
                {
                    // This status is most likely caused by app permissions (did not declare the device in the app's package.appxmanifest)
                    // This status does not cover the case where the device is already opened by another app.
                    notificationMessage = "Access to the device was blocked by the system.";
                }
                else
                {
                    // The only time I made it to this error I forgot to add Fadecandy to package.appxmanifest
                    // Most likely the device is opened by another app, but cannot be sure
                    notificationMessage = "Unknown error, possibly opened by another app.";
                }
            }

            MainPage.Current.NotifyUser(notificationMessage, deviceInfo.Id, notificationStatus);

            return(successfullyOpenedDevice);
        }
        private async void OnDeviceAdded(DeviceWatcher watcher, DeviceInformation deviceInformation)
        {
            if (deviceInformation.Name.StartsWith("ClearShot") && deviceInformation.IsEnabled)
            {
                _targetDevice = await UsbDevice.FromIdAsync(deviceInformation.Id);

                OnConnected(EventArgs.Empty);
            }
        }
示例#5
0
        private void OpenDevice()
        {
            var deviceTask = UsbDevice.FromIdAsync(deviceSyncDetails.DeviceId).AsTask(cancellationTokenSource.Token);

            deviceTask.Wait();

            device = deviceTask.Result;

            // We opened the device, so notify the app that we've completed a bit of the background task
            backgroundTaskInstance.Progress = 10;
        }
示例#6
0
        private async void Watcher_Added(Windows.Devices.Enumeration.DeviceWatcher sender, DeviceInformation args)
        {
            // FIXME: async void - need to log error or something
            var device = await UsbDevice.FromIdAsync(args.Id);

            if (device == null)
            {
                // we probably don't have permission to use it
                return;
            }
            subject.OnNext(new Device(args, device));
        }
        public async Task Reset()
        {
            var aqs       = UsbDevice.GetDeviceSelector(VendorId, ProductId);
            var myDevices = await DeviceInformation.FindAllAsync(aqs);

            if (myDevices.Count > 0)
            {
                _targetDevice = await UsbDevice.FromIdAsync(myDevices[0].Id);

                if (_targetDevice != null)
                {
                    GetInterfaces();
                }
            }
        }
        /// <summary>
        /// Finds the first enumerated device, attempts to open it, and starts updating the firmare.
        ///
        /// The device must be opened and closed before starting the background task because we must get permission from
        /// the user (the consent prompt) in the UI or else the background task will not be able to open the device.
        /// </summary>
        /// <returns></returns>
        private async Task UpdateFirmwareForFirstEnumeratedDeviceAsync()
        {
            DeviceInformation deviceToDoFirmwareUpdate = await FindFirstSuperMuttDeviceAsync();

            String firmwareStatusMessage = null;

            if (deviceToDoFirmwareUpdate != null)
            {
                // Open device here and get permission from the user
                var usbDevice = await UsbDevice.FromIdAsync(deviceToDoFirmwareUpdate.Id);

                if (usbDevice != null)
                {
                    // Firmware version before update (for the SuperMutt, the device revision is the firmware version)
                    var oldFirmwareVersion = "0x" + usbDevice.DeviceDescriptor.BcdDeviceRevision.ToString("X4", NumberFormatInfo.InvariantInfo);
                    UpdateOldFirmwareVersionInUI(oldFirmwareVersion);

                    // After getting permission, we need to close the device so that the background task can open
                    // the device. See comment for the function StartFirmwareForDeviceAsync().
                    usbDevice.Dispose();
                    usbDevice = null;

                    // Create a background task for the firmware update
                    RegisterForFirmwareUpdateBackgroundTask();

                    // Triggers the background task to update.
                    firmwareStatusMessage = await StartFirmwareForDeviceAsync(deviceToDoFirmwareUpdate);
                }
                else
                {
                    firmwareStatusMessage = "Could not open the device";
                }
            }
            else
            {
                firmwareStatusMessage = "No supported devices found";
            }

            // The firmware should be updating now, if not something went wrong
            if (isUpdatingFirmware)
            {
                rootPage.NotifyUser("Updating firmware...", NotifyType.StatusMessage);
            }
            else
            {
                rootPage.NotifyUser("Unable to update firmware: " + firmwareStatusMessage, NotifyType.ErrorMessage);
            }
        }
        private async void OnDeviceAdded(DeviceWatcher watcher, DeviceInformation deviceInformation)
        {
            if (deviceInformation.Name.StartsWith("acA1920-40um") && deviceInformation.IsEnabled)
            {
                _targetDevice = await UsbDevice.FromIdAsync(deviceInformation.Id);
                foreach (var interf in _targetDevice.Configuration.UsbInterfaces)
                {
                    if (interf.InterfaceNumber == 0)
                    {
                        _controlInPipe = interf.BulkInPipes[0];
                        _controlOutPipe = interf.BulkOutPipes[0];
                    }
                    else if (interf.InterfaceNumber == 2)
                        _streamInPipe = interf.BulkInPipes[0];
                }

                OnConnected(EventArgs.Empty);
            }
        }
示例#10
0
        private void buttonDeviceSelect_Click(object sender, RoutedEventArgs e)
        {
            // No device selected.
            if (this.comboBoxDevices.SelectedIndex == -1)
            {
                return;
            }

            var dispatcher = this.Dispatcher;
            var deviceId   = (this.comboBoxDevices.SelectedItem as UsbDeviceComboBoxItem).Id;
            var deviceName = (this.comboBoxDevices.SelectedItem as UsbDeviceComboBoxItem).Content as String;

            UsbDevice.FromIdAsync(deviceId).Completed = new AsyncOperationCompletedHandler <UsbDevice>(async(op, status) =>
            {
                var usbDevice  = op.GetResults();
                var serialport = await UsbCdcControlAccess.UsbSerialPort.CreateAsync(usbDevice);
                if (serialport == null)
                {
                    await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() =>
                    {
                        SDKTemplate.MainPage.Current.NotifyUser(deviceName + " is not compatible with CDC ACM.", SDKTemplate.NotifyType.ErrorMessage);
                    }));
                    if (usbDevice != null)
                    {
                        usbDevice.Dispose();
                    }
                    return;
                }
                UsbCdcControl.UsbDeviceList.Singleton.Add(new UsbCdcControl.UsbSerialPortInfo(serialport, deviceId, deviceName));

                await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() =>
                {
                    this.comboBoxDevices.IsEnabled      = false;
                    this.buttonDeviceSelect.IsEnabled   = false;
                    this.buttonInitialize.IsEnabled     = true;
                    this.buttonDeviceDeselect.IsEnabled = true;
                    SDKTemplate.MainPage.Current.NotifyUser("", SDKTemplate.NotifyType.ErrorMessage);
                }));
            });
        }
示例#11
0
        public async Task <bool> OpenAsync()
        {
            if (IsOpen)
            {
                return(true); // we're already open
            }
            // Calling this will "open" the device, blocking any other app from using it.
            // This will return null if another program already has the device open.
            usbDevice = await UsbDevice.FromIdAsync(DevicePath);

            if (usbDevice == null)
            {
                return(false);
            }

            cts = new CancellationTokenSource();

            // https://msdn.microsoft.com/en-us/library/windows/hardware/dn303346(v=vs.85).aspx

            Version = (ushort)usbDevice.DeviceDescriptor.BcdDeviceRevision;

            pinConfigPipe     = usbDevice.DefaultInterface.BulkOutPipes[0];
            peripheralOutPipe = usbDevice.DefaultInterface.BulkOutPipes[1];

            pinConfigWriter  = new DataWriter(pinConfigPipe.OutputStream);
            peripheralWriter = new DataWriter(peripheralOutPipe.OutputStream);

            pinEventPipe   = usbDevice.DefaultInterface.BulkInPipes[0];
            pinEventReader = new DataReader(pinEventPipe.InputStream);

            peripheralInPipe = usbDevice.DefaultInterface.BulkInPipes[1];
            peripheralReader = new DataReader(peripheralInPipe.InputStream);

            IsOpen = true;
            pinEventListerner(cts.Token);

            Debug.WriteLine("Connection opened");

            return(true);
        }
        /// <summary>
        /// This method opens the device using the WinRT Usb API. After the device is opened, save the device
        /// so that it can be used across scenarios.
        ///
        /// It is important that the FromIdAsync call is made on the UI thread because the consent prompt can only be displayed
        /// on the UI thread.
        ///
        /// This method is used to reopen the device after the device reconnects to the computer and when the app resumes.
        /// </summary>
        /// <param name="deviceInfo">Device information of the device to be opened</param>
        /// <param name="deviceSelector">The AQS used to find this device</param>
        /// <returns>True if the device was successfully opened, false if the device could not be opened for well known reasons.
        /// An exception may be thrown if the device could not be opened for extraordinary reasons.</returns>
        public async Task <Boolean> OpenDeviceAsync(DeviceInformation deviceInfo, String deviceSelector)
        {
            device = await UsbDevice.FromIdAsync(deviceInfo.Id);

            Boolean    successfullyOpenedDevice = false;
            NotifyType notificationStatus;
            String     notificationMessage = null;

            // Device could have been blocked by user or the device has already been opened by another app.
            if (device != null)
            {
                successfullyOpenedDevice = true;

                deviceInformation   = deviceInfo;
                this.deviceSelector = deviceSelector;

                notificationStatus  = NotifyType.StatusMessage;
                notificationMessage = "Device " + deviceInformation.Id + " opened";

                // Notify registered callback handle that the device has been opened
                if (deviceConnectedCallback != null)
                {
                    deviceConnectedCallback(this, deviceInformation);
                }

                // Background tasks are not part of the app, so app events will not have an affect on the device
                if (!isBackgroundTask && (appSuspendEventHandler == null || appResumeEventHandler == null))
                {
                    RegisterForAppEvents();
                }

                // User can block the device after it has been opened in the Settings charm. We can detect this by registering for the
                // DeviceAccessInformation.AccessChanged event
                if (deviceAccessEventHandler == null)
                {
                    RegisterForDeviceAccessStatusChange();
                }

                // Create and register device watcher events for the device to be opened unless we're reopening the device
                if (deviceWatcher == null)
                {
                    deviceWatcher = DeviceInformation.CreateWatcher(deviceSelector);

                    RegisterForDeviceWatcherEvents();
                }

                if (!watcherStarted)
                {
                    // Start the device watcher after we made sure that the device is opened.
                    StartDeviceWatcher();
                }
            }
            else
            {
                successfullyOpenedDevice = false;

                notificationStatus = NotifyType.ErrorMessage;

                var deviceAccessStatus = DeviceAccessInformation.CreateFromId(deviceInfo.Id).CurrentStatus;

                switch (deviceAccessStatus)
                {
                case DeviceAccessStatus.DeniedByUser:
                    notificationMessage = "Access to the device was blocked by the user : "******"Access to the device was blocked by the system : " + deviceInfo.Id;
                    break;

                default:
                    // Most likely the device is opened by another app, but cannot be sure
                    notificationMessage = "Unknown error, possibly opened by another app : " + deviceInfo.Id;
                    break;
                }
            }

            MainPage.Current.NotifyUser(notificationMessage, notificationStatus);

            return(successfullyOpenedDevice);
        }
示例#13
0
 /// <summary>
 /// Opens device and assigns member variable to the newly opened device
 /// </summary>
 /// <returns></returns>
 private async Task OpenDeviceAsync()
 {
     device = await UsbDevice.FromIdAsync(deviceServicingDetails.DeviceId).AsTask(cancellationTokenSource.Token);
 }
示例#14
0
        private void buttonInitialize_Click(object sender, RoutedEventArgs e)
        {
            if (this.comboBoxDevices1.SelectedIndex == -1 || this.comboBoxDevices2.SelectedIndex == -1)
            {
                return;
            }

            var dispatcher  = this.Dispatcher;
            var deviceId1   = (this.comboBoxDevices1.SelectedItem as UsbDeviceComboBoxItem).DeviceId;
            var deviceId2   = (this.comboBoxDevices2.SelectedItem as UsbDeviceComboBoxItem).DeviceId;
            var deviceName1 = (this.comboBoxDevices1.SelectedItem as UsbDeviceComboBoxItem).DeviceName;
            var deviceName2 = (this.comboBoxDevices2.SelectedItem as UsbDeviceComboBoxItem).DeviceName;
            var dteRate     = uint.Parse(this.textBoxDTERate.Text);
            var parity      = (Parity)this.comboBoxParityType.SelectedIndex;
            var dataBits    = int.Parse((this.comboBoxDataBits.SelectedItem as ComboBoxItem).Content.ToString());
            var charFormat  = (StopBits)this.comboBoxCharFormat.SelectedIndex;
            var dtr         = this.comboBoxDTR.SelectedIndex != 0;
            var rts         = this.comboBoxRTS.SelectedIndex != 0;

            var createSerialPortTasks = new List <System.Threading.Tasks.Task>();

            UsbDeviceInfo[] deviceInfos = { new UsbDeviceInfo(deviceId1, deviceName1), new UsbDeviceInfo(deviceId2, deviceName2) };
            foreach (var deviceInfo in deviceInfos)
            {
                var fromIdAsyncOp = UsbDevice.FromIdAsync(deviceInfo.Id);
                createSerialPortTasks.Add(System.Threading.Tasks.TaskExtensions.Unwrap(System.Threading.Tasks.Task.Run(async() =>
                {
                    var usbDevice = await fromIdAsyncOp;
                    var port      = await UsbCdcControlAccess.UsbSerialPort.CreateAsync(usbDevice);
                    if (port == null)
                    {
                        if (usbDevice != null)
                        {
                            usbDevice.Dispose();
                        }

                        // Return a dummy task.
                        return(System.Threading.Tasks.Task.Delay(0));
                    }

                    var addToListTask = dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() =>
                    {
                        UsbCdcControl.UsbDeviceList.Singleton.Add(new UsbCdcControl.UsbSerialPortInfo(port, deviceInfo.Id, deviceInfo.Name));
                    }));

                    await port.Open(dteRate, parity, dataBits, charFormat);

                    // DtrEnable
                    await port.DtrEnable_set(dtr);

                    // RtsEnable
                    await port.RtsEnable_set(rts);

                    return(addToListTask.AsTask());
                })));
            }

            var uiSyncContext = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();

            System.Threading.Tasks.Task.WhenAll(createSerialPortTasks).ContinueWith((task) =>
            {
                if (task.Exception != null)
                {
                    // Close all devices because some devices failed to be opened.
                    UsbCdcControl.UsbDeviceList.Singleton.DisposeAll();

                    // Throw the exception.
                    System.Threading.SynchronizationContext.Current.Post((state) =>
                    {
                        throw state as Exception;
                    }
                                                                         , task.Exception.GetBaseException());
                }
                else if (this.SerialPortInfo1 != null && this.SerialPortInfo2 != null)
                {
                    this.buttonLoopbackTest.IsEnabled = true;
                    this.buttonInitialize.IsEnabled   = false;
                    SDKTemplate.MainPage.Current.NotifyUser("Initialized.", SDKTemplate.NotifyType.StatusMessage);
                }
                else
                {
                    String deviceNumber;

                    if (this.SerialPortInfo1 == null)
                    {
                        if (this.SerialPortInfo2 == null)
                        {
                            deviceNumber = "Both devices";
                        }
                        else
                        {
                            deviceNumber = "Device 1";
                        }
                    }
                    else
                    {
                        deviceNumber = "Device 2";
                    }

                    SDKTemplate.MainPage.Current.NotifyUser(deviceNumber + " failed to be initialized.", SDKTemplate.NotifyType.ErrorMessage);

                    // Close all devices because some devices failed to be opened.
                    UsbCdcControl.UsbDeviceList.Singleton.DisposeAll();
                }
            }
                                                                                    , uiSyncContext);
        }
示例#15
0
        private async void Main_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                AvailableCameras.Clear();
                var cameras = await PhotoHelper.GetAvailableCameras(true);

                foreach (var c in cameras)
                {
                    AvailableCameras.Add(c);
                }

                await ConfigureCamera();

                ushort vendorId  = 0x19AB;
                ushort productId = 0x2000;
                //ushort vendorId = 0x203A;
                //ushort productId = 0xFFF9;
                // var aqs = UsbDevice.GetDeviceSelector(vendorId, productId, Guid.Parse("{ca3e7ab9-b4c3-4ae6-8251-579ef933890f}"));
                //var selector = "System.Devices.InterfaceClassGuid:=\"" + "{ca3e7ab9-b4c3-4ae6-8251-579ef933890f}"+ "\"";
                //                 + " AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True";
                // var myDevices = await DeviceInformation.FindAllAsync(aqs,null);

                //UsbDevice device = await UsbDevice.FromIdAsync(myDevices[0].Id);
                //var dev = interfaces.Where(x => x.Name.Contains("scope")).FirstOrDefault();

                var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                var device = devices[1];


                //var mydevice = await UsbDevice.FromIdAsync(device);
                var mydevice = await UsbDevice.FromIdAsync(device.Id);



                ////If this is a scope screen, enable the button click event from the scope

                //    //Bodelin Scope - HID
                //    ushort vendorId = 0x19AB;
                //    var productIdList = new List<ushort> { 0x1000, 0x1020, 0x2000 };

                //    ushort usageId = 1;
                //    ushort usagePage = 65440;
                //    foreach (ushort productId in productIdList)
                //    {
                //        string selector = HidDevice.GetDeviceSelector(usagePage, usageId, vendorId, productId);
                //        var myDevices = await DeviceInformation.FindAllAsync(selector);

                //        if (myDevices.Any())
                //        {
                //            _proscopeHidDevice = await HidDevice.FromIdAsync(myDevices[0].Id, FileAccessMode.Read);
                //            var status = DeviceAccessInformation.CreateFromId(myDevices[0].Id).CurrentStatus;

                //            if (_proscopeHidDevice != null)
                //            {
                //                _proscopeHidDevice.InputReportReceived += ProScopeClicked;
                //                break;
                //            }
                //        }
                //    }
            }
            catch
            {
                throw;
            }
        }