예제 #1
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            backgroundTaskInstance = taskInstance;

            // Trigger details contain device id and arguments that are provided by the caller in the main app
            // The taskInstance can always be casted to DeviceUseDetails if this background task was started using a DeviceUseTrigger
            deviceSyncDetails = (DeviceUseDetails)taskInstance.TriggerDetails;

            deferral = taskInstance.GetDeferral();

            try
            {
                backgroundTaskInstance.Progress = 0;

                cancellationTokenSource = new CancellationTokenSource();

                taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

                // For simplicity, no error checking will be done after opening the device. Ideally, one should always
                // check if the device was successfully opened and respond accordingly. For an example on how to do this,
                // please see Scenario 1 of this sample.
                //
                // The user may also block the device via the settings charm while we are syncing (in background task). In order to deal with
                // the user changing permissions, we have to listen for DeviceAccessInformation->AccessChanged events. See EventHandlerForDevice 
                // for how to handle DeviceAccessInformation.AccessChanged event.
                OpenDevice();

                // The sample only demonstrates a bulk write for simplicity.
                // IO operations can be done after opening the device.
                // For more information on BackgroundTasks, please see the BackgroundTask sample on MSDN.
                UInt32 bytesWritten = await Task.Run(() =>
                {
                    return WriteToDeviceAsync();
                }, 
                cancellationTokenSource.Token);

                ApplicationData.Current.LocalSettings.Values[LocalSettingKeys.SyncBackgroundTaskResult] = bytesWritten;
                ApplicationData.Current.LocalSettings.Values[LocalSettingKeys.SyncBackgroundTaskStatus] = BackgroundTaskInformation.TaskCompleted;
            }
            catch (OperationCanceledException /*ex*/)
            {
                ApplicationData.Current.LocalSettings.Values[LocalSettingKeys.SyncBackgroundTaskResult] = 0;
                ApplicationData.Current.LocalSettings.Values[LocalSettingKeys.SyncBackgroundTaskStatus] = BackgroundTaskInformation.TaskCanceled;
            }
            finally
            {
                // Close the device because we are finished syncing and so that the app may reopen the device
                device.Dispose();

                device = null;
            }

            // Complete the background task (this raises the OnCompleted event on the corresponding BackgroundTaskRegistration)
            deferral.Complete();
        }
예제 #2
0
        internal UsbInterfaceInfo(UsbDevice usbDevice, MonoUsbAltInterfaceDescriptor monoUSBAltInterfaceDescriptor)
        {
            mUsbDevice = usbDevice;

            mUsbInterfaceDescriptor = new UsbInterfaceDescriptor(monoUSBAltInterfaceDescriptor);
            List<MonoUsbEndpointDescriptor> monoUsbEndpoints = monoUSBAltInterfaceDescriptor.EndpointList;
            foreach (MonoUsbEndpointDescriptor monoUSBEndpoint in monoUsbEndpoints)
            {
                mEndpointInfo.Add(new UsbEndpointInfo(monoUSBEndpoint));
            }
        }
예제 #3
0
        public void Dispose()
        {
            timer.Stop();
            timer = null;

            if (isConnected)
            {
                TurnOff();
                busylight = null;
            }
            isConnected = false;
        }
예제 #4
0
 internal UsbEndpointBase(UsbDevice usbDevice, byte epNum, EndpointType endpointType)
 {
     mUsbDevice = usbDevice;
     mUsbApi = mUsbDevice.mUsbApi;
     mUsbHandle = mUsbDevice.Handle;
     mEpNum = epNum;
     mEndpointType = endpointType;
     if ((mEpNum & 0x80) > 0)
     {
         mPipeTransferSubmit = ReadPipe;
     }
     else
         mPipeTransferSubmit = WritePipe;
 }
예제 #5
0
        internal UsbConfigInfo(MonoUsbDevice usbDevice, MonoUsbConfigDescriptor configDescriptor)
        {
            mUsbDevice = usbDevice;

            mUsbConfigDescriptor = new UsbConfigDescriptor(configDescriptor);

            List<MonoUsbInterface> monoUSBInterfaces = configDescriptor.InterfaceList;
            foreach (MonoUsbInterface usbInterface in monoUSBInterfaces)
            {
                List<MonoUsbAltInterfaceDescriptor> monoUSBAltInterfaces = usbInterface.AltInterfaceList;
                foreach (MonoUsbAltInterfaceDescriptor monoUSBAltInterface in monoUSBAltInterfaces)
                {
                    UsbInterfaceInfo usbInterfaceInfo = new UsbInterfaceInfo(mUsbDevice, monoUSBAltInterface);
                    mInterfaceList.Add(usbInterfaceInfo);
                }
            }
        }
예제 #6
0
파일: Utilities.cs 프로젝트: mbin/Win81App
        /// <summary>
        /// Device type of the device provided device.
        /// </summary>
        /// <param name="device"></param>
        /// <returns>The DeviceType of the device or DeviceType.None if there are no devices connected or is not recognized</returns>
        public static DeviceType GetDeviceType(UsbDevice device)
        {
            if (device != null)
            {
                if (device.DeviceDescriptor.VendorId == OsrFx2.DeviceVid
                    && device.DeviceDescriptor.ProductId == OsrFx2.DevicePid)
                {
                    return DeviceType.OsrFx2;
                }
                else if (device.DeviceDescriptor.VendorId == SuperMutt.DeviceVid
                    && device.DeviceDescriptor.ProductId == SuperMutt.DevicePid)
                {
                    return DeviceType.SuperMutt;
                }
            }

            return DeviceType.None;
        }
예제 #7
0
        internal UsbDeviceInfo(UsbDevice usbDevice, MonoUsbDeviceDescriptor usbDeviceDescriptor)
        {
            mUsbDevice = usbDevice;

            mDeviceDescriptor = new UsbDeviceDescriptor();
            mDeviceDescriptor.BcdDevice = usbDeviceDescriptor.BcdDevice;
            mDeviceDescriptor.BcdUsb = usbDeviceDescriptor.BcdUsb;
            mDeviceDescriptor.Class = usbDeviceDescriptor.Class;
            mDeviceDescriptor.ConfigurationCount = usbDeviceDescriptor.ConfigurationCount;
            mDeviceDescriptor.DescriptorType = usbDeviceDescriptor.DescriptorType;
            mDeviceDescriptor.Length = usbDeviceDescriptor.Length;
            mDeviceDescriptor.ManufacturerStringIndex = usbDeviceDescriptor.ManufacturerStringIndex;
            mDeviceDescriptor.MaxPacketSize0 = usbDeviceDescriptor.MaxPacketSize0;
            mDeviceDescriptor.ProductID = usbDeviceDescriptor.ProductID;
            mDeviceDescriptor.ProductStringIndex = usbDeviceDescriptor.ProductStringIndex;
            mDeviceDescriptor.Protocol = usbDeviceDescriptor.Protocol;
            mDeviceDescriptor.SerialStringIndex = usbDeviceDescriptor.SerialStringIndex;
            mDeviceDescriptor.SubClass = usbDeviceDescriptor.SubClass;
            mDeviceDescriptor.VendorID = usbDeviceDescriptor.VendorID;
        }
예제 #8
0
        internal UsbConfigInfo(UsbDevice usbDevice, UsbConfigDescriptor descriptor, ref List<byte[]> rawDescriptors)
        {
            mUsbDevice = usbDevice;
            mUsbConfigDescriptor = descriptor;
            mRawDescriptors = rawDescriptors;

            UsbInterfaceInfo currentInterface = null;
            for (int iRawDescriptor = 0; iRawDescriptor < rawDescriptors.Count; iRawDescriptor++)
            {
                byte[] bytesRawDescriptor = rawDescriptors[iRawDescriptor];

                switch (bytesRawDescriptor[1])
                {
                    case (byte) DescriptorType.Interface:
                        currentInterface = new UsbInterfaceInfo(usbDevice, bytesRawDescriptor);
                        mRawDescriptors.RemoveAt(iRawDescriptor);
                        mInterfaceList.Add(currentInterface);
                        iRawDescriptor--;
                        break;
                    case (byte) DescriptorType.Endpoint:
                        if (currentInterface == null)
                            throw new UsbException(this, "Recieved and endpoint descriptor before receiving an interface descriptor.");

                        currentInterface.mEndpointInfo.Add(new UsbEndpointInfo(bytesRawDescriptor));
                        mRawDescriptors.RemoveAt(iRawDescriptor);
                        iRawDescriptor--;
                        break;
                    default:
                        if (currentInterface != null)
                        {
                            currentInterface.mRawDescriptors.Add(bytesRawDescriptor);
                            mRawDescriptors.RemoveAt(iRawDescriptor);
                            iRawDescriptor--;
                        }
                        break;
                }
            }
        }
예제 #9
0
 public STM32SerialDriver(UsbDevice device)
 {
     mDevice = device;
     mPort   = new STM32SerialPort(mDevice, 0, this);
 }
 internal MonoUsbEndpointWriter(UsbDevice usbDevice, WriteEndpointID writeEndpointID,EndpointType endpointType)
     : base(usbDevice, writeEndpointID, endpointType) { }
예제 #11
0
        public bool Open(UInt16 vid, UInt16 pid)
        {
            try
            {
                this.vid = vid;
                this.pid = pid;
                Close();
                //Debug.WriteLine("Trying to open device...");
                var devices = UsbDevice.AllDevices;
                device = null;
                foreach (UsbRegistry regDevice in devices)
                {
                    if (regDevice.Vid == vid && regDevice.Pid == pid)
                    {
                        regDevice.Open(out device);
                        break;
                    }
                }
                if (device == null)
                {
#if VERY_DEBUG
                    Debug.WriteLine("Device with such VID and PID not found");
#endif
                    return(false);
                }

                IUsbDevice wholeUsbDevice = device as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    // This is a "whole" USB device. Before it can be used,
                    // the desired configuration and interface must be selected.

                    // Select config #1
                    wholeUsbDevice.SetConfiguration(1);

                    // Claim interface #0.
                    wholeUsbDevice.ClaimInterface(0);
                }

                int inEndp  = -1;
                int outEndp = -1;
                int inMax   = 0;
                int outMax  = 0;
                Debug.WriteLine("Checking USB endpoints...");
                foreach (var config in device.Configs)
                {
                    foreach (var @interface in config.InterfaceInfoList)
                    {
                        foreach (var endp in @interface.EndpointInfoList)
                        {
                            if ((endp.Descriptor.EndpointID & 0x80) != 0)
                            {
                                inEndp = endp.Descriptor.EndpointID;
                                inMax  = endp.Descriptor.MaxPacketSize;
                                Debug.WriteLine("IN endpoint found: " + inEndp);
                                Debug.WriteLine("IN endpoint maxsize: " + inMax);
                            }
                            else
                            {
                                outEndp = endp.Descriptor.EndpointID;
                                outMax  = endp.Descriptor.MaxPacketSize;
                                Debug.WriteLine("OUT endpoint found: " + outEndp);
                                Debug.WriteLine("OUT endpoint maxsize: " + outMax);
                            }
                        }
                    }
                }
                if (inEndp != 0x82 || outEndp != 0x01)
                {
                    Debug.WriteLine("Uncorrect FEL device/mode");
                    return(false);
                }
                epReader = device.OpenEndpointReader((ReadEndpointID)inEndp, 65536);
                epWriter = device.OpenEndpointWriter((WriteEndpointID)outEndp);

                Debug.WriteLine("Trying to verify device");
                if (VerifyDevice().Board != 0x00166700)
                {
                    Debug.WriteLine("Invalid board ID: " + VerifyDevice().Board);
                    return(false);
                }
                return(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error: " + ex.Message + ex.StackTrace);
                return(false);
            }
        }
예제 #12
0
        /// <summary>
        /// Dynamic predicate find function. Pass this function into any method that has a <see cref="Predicate{UsbDevice}"/> parameter.
        /// </summary>
        /// <remarks>
        /// Override this member when inheriting the <see cref="UsbDeviceFinder"/> class to change/alter the matching behavior.
        /// </remarks>
        /// <param name="usbDevice">The UsbDevice to check.</param>
        /// <returns>True if the <see cref="UsbDevice"/> instance matches the <see cref="UsbDeviceFinder"/> properties.</returns>
        public virtual bool Check(UsbDevice usbDevice)
        {
            if (mVid != int.MaxValue)
                if (((ushort)usbDevice.Info.Descriptor.VendorID) != mVid) return false;
            if (mPid != int.MaxValue)
                if (((ushort)usbDevice.Info.Descriptor.ProductID) != mPid) return false;
            if (mRevision != int.MaxValue)
                if (((ushort)usbDevice.Info.Descriptor.BcdDevice) != mRevision) return false;

            if (!String.IsNullOrEmpty(mSerialNumber))
                if (mSerialNumber!=usbDevice.Info.SerialString) return false;

            return true;
        }
예제 #13
0
 public static void OnDevicesChanged(UsbDevice[] devices)
 {
   if (Usb.DevicesChanged == null || devices == null)
     return;
   Usb.DevicesChanged(devices);
 }
예제 #14
0
 /// <summary>
 /// Closes the device and sets the device member variable to null
 /// </summary>
 private void CloseDevice()
 {
     device.Dispose();
     device = null;
 }
예제 #15
0
        internal static bool GetDeviceDescriptor(UsbDevice usbDevice, out UsbDeviceDescriptor deviceDescriptor)
        {
            if (usbDevice.mCachedDeviceDescriptor!=null)
            {
                deviceDescriptor = usbDevice.mCachedDeviceDescriptor;
                return true;
            }
            deviceDescriptor = new UsbDeviceDescriptor();

            GCHandle gcDeviceDescriptor = GCHandle.Alloc(deviceDescriptor, GCHandleType.Pinned);
            int ret;
            bool bSuccess = usbDevice.GetDescriptor((byte) DescriptorType.Device,
                                                    0,
                                                    0,
                                                    gcDeviceDescriptor.AddrOfPinnedObject(),
                                                    UsbDeviceDescriptor.Size,
                                                    out ret);
            gcDeviceDescriptor.Free();

            if (bSuccess) return true;

            return false;
        }
예제 #16
0
 public STM32SerialPort(UsbDevice device, int portNumber, IUsbSerialDriver driver) : base(device, portNumber)
 {
     Driver             = driver;
     ENABLE_ASYNC_READS = true;
 }
예제 #17
0
 public UsbDeviceStatus(UsbDevice usbDevice)
 {
     this.usbDevice = usbDevice;
 }
예제 #18
0
        void mainThreadLoop()
        {
            try
            {
                while (enabled)
                {
                    online = false;
                    //Debug.WriteLine("Waiting for clovershell");
                    while (enabled)
                    {
                        try
                        {
                            var devices = UsbDevice.AllDevices;
                            device = null;
                            foreach (UsbRegistry regDevice in devices)
                            {
                                if (regDevice.Vid == vid && regDevice.Pid == pid)
                                {
                                    regDevice.Open(out device);
                                    break;
                                }
                            }
                            //device = USBDevice.GetSingleDevice(vid, pid);
                            if (device == null)
                            {
                                break;
                            }
                            IUsbDevice wholeUsbDevice = device as IUsbDevice;
                            if (!ReferenceEquals(wholeUsbDevice, null))
                            {
                                // This is a "whole" USB device. Before it can be used,
                                // the desired configuration and interface must be selected.

                                // Select config #1
                                wholeUsbDevice.SetConfiguration(1);

                                // Claim interface #0.
                                wholeUsbDevice.ClaimInterface(0);
                            }

                            int inEndp  = -1;
                            int outEndp = -1;
                            int inMax   = 0;
                            int outMax  = 0;
                            foreach (var config in device.Configs)
                            {
                                foreach (var @interface in config.InterfaceInfoList)
                                {
                                    foreach (var endp in @interface.EndpointInfoList)
                                    {
                                        if ((endp.Descriptor.EndpointID & 0x80) != 0)
                                        {
                                            inEndp = endp.Descriptor.EndpointID;
                                            inMax  = endp.Descriptor.MaxPacketSize;
                                            //Debug.WriteLine("IN endpoint found: " + inEndp);
                                            //Debug.WriteLine("IN endpoint maxsize: " + inMax);
                                        }
                                        else
                                        {
                                            outEndp = endp.Descriptor.EndpointID;
                                            outMax  = endp.Descriptor.MaxPacketSize;
                                            //Debug.WriteLine("OUT endpoint found: " + outEndp);
                                            //Debug.WriteLine("OUT endpoint maxsize: " + outMax);
                                        }
                                    }
                                }
                            }
                            if (inEndp != 0x81 || outEndp != 0x01)
                            {
                                break;
                            }
                            epReader = device.OpenEndpointReader((ReadEndpointID)inEndp, 65536);
                            epWriter = device.OpenEndpointWriter((WriteEndpointID)outEndp);
                            Debug.WriteLine("clovershell connected");
                            // Kill all other serrions and drop all output
                            killAll();
                            var body = new byte[65536];
                            int len;
                            while (epReader.Read(body, 50, out len) == ErrorCode.Ok)
                            {
                                ;
                            }
                            epReader.ReadBufferSize      = 65536;
                            epReader.DataReceived       += epReader_DataReceived;
                            epReader.DataReceivedEnabled = true;
                            lastAliveTime = DateTime.Now;
                            online        = true;
                            OnConnected();
                            while (device.mUsbRegistry.IsAlive)
                            {
                                Thread.Sleep(100);
                                if ((IdleTime.TotalSeconds >= 5) && (Ping() < 0))
                                {
                                    throw new ClovershellException("no answer from device");
                                }
                            }
                            break;
                        }
                        catch (ThreadAbortException)
                        {
                            return;
                        }
                        catch (ClovershellException ex)
                        {
                            Debug.WriteLine(ex.Message);
                            break;
                        }
                    }
                    if (online)
                    {
                        Debug.WriteLine("clovershell disconnected");
                    }
                    online = false;
                    if (device != null)
                    {
                        device.Close();
                    }
                    device = null;
                    if (epReader != null)
                    {
                        epReader.Dispose();
                    }
                    epReader = null;
                    if (epWriter != null)
                    {
                        epWriter.Dispose();
                    }
                    epWriter = null;
                    if (!autoreconnect)
                    {
                        Enabled = false;
                    }
                    Thread.Sleep(1000);
                }
            }
            catch (ThreadAbortException)
            {
                return;
            }
            catch (ClovershellException ex)
            {
                Debug.WriteLine("Critical error: " + ex.Message + ex.StackTrace);
            }
        }
        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.
            this.usbDevice = await UsbDevice.FromIdAsync(DevicePath);
            if (this.usbDevice == null)
                return false;

            cts = new CancellationTokenSource();

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

            Version = (short)usbDevice.DeviceDescriptor.BcdDeviceRevision;

            pinConfigPipe = usbDevice.DefaultInterface.BulkOutPipes[0];
            pinConfigPipe.WriteOptions |= UsbWriteOptions.ShortPacketTerminate;

            peripheralOutPipe = usbDevice.DefaultInterface.BulkOutPipes[1];
            peripheralOutPipe.WriteOptions |= UsbWriteOptions.ShortPacketTerminate;

            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;
        }
 public void Close()
 {
     if (!isOpen)
         return;
     cts.Cancel();
     usbDevice.Dispose();
     usbDevice = null;
     Debug.WriteLine("Connection closed");
     isOpen = false;
 }
예제 #21
0
 internal UsbDeviceInfo(UsbDevice usbDevice)
 {
     mUsbDevice = usbDevice;
     GetDeviceDescriptor(mUsbDevice, out mDeviceDescriptor);
 }
예제 #22
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);
 }
예제 #23
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;
        }
 /// <summary>
 /// Attempts to open the device referenced.
 /// </summary>
 /// <param name="usbDevice">The open UsbDevice object.</param>
 /// <returns>True if success.</returns>
 public bool Open(out UsbDevice usbDevice)
 {
     foreach (UsbRegistry reg in UsbDevice.AllDevices)
     {
         if (reg.DevicePath == this.Name)
             return reg.Open(out usbDevice);
     }
     usbDevice = null;
     return false;
 }
        /// <summary>
        /// This method demonstrates how to close the device properly using the WinRT Usb API.
        ///
        /// When the UsbDevice is closing, it will cancel all IO operations that are still pending (not complete).
        /// The close will not wait for any IO completion callbacks to be called, so the close call may complete before any of
        /// the IO completion callbacks are called.
        /// The pending IO operations will still call their respective completion callbacks with either a task 
        /// cancelled error or the operation completed.
        /// </summary>
        private async void CloseCurrentlyConnectedDevice()
        {
            if (device != null)
            {
                // Notify callback that we're about to close the device
                if (deviceCloseCallback != null)
                {
                    deviceCloseCallback(this, deviceInformation);
                }

                // This closes the handle to the device
                device.Dispose();

                device = null;

                // Save the deviceInformation.Id in case deviceInformation is set to null when closing the
                // device
                String deviceId = deviceInformation.Id;

                await rootPage.Dispatcher.RunAsync(
                    CoreDispatcherPriority.Normal,
                    new DispatchedHandler(() =>
                    {
                        MainPage.Current.NotifyUser(deviceId + " is closed", NotifyType.StatusMessage);
                    }));
            }
        }
 internal MonoUsbEndpointReader(UsbDevice usbDevice, int readBufferSize, ReadEndpointID readEndpointID, EndpointType endpointType)
     : base(usbDevice, readBufferSize, readEndpointID, endpointType) { }
예제 #27
0
파일: MainForm.cs 프로젝트: mo10/PigeonUI
 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
 {
     DeviceDisconnect();
     UsbDevice.Exit();
 }
        /// <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;
        }
예제 #29
0
 /// <summary>
 /// Opens the USB device for communucation.
 /// </summary>
 /// <param name="usbDevice">The newly created UsbDevice.</param>
 /// <returns>True on success.</returns>
 public abstract bool Open(out UsbDevice usbDevice);
 internal MonoUsbEndpointReader(UsbDevice usbDevice, int readBufferSize, byte alternateInterfaceID, ReadEndpointID readEndpointID, EndpointType endpointType)
     : base(usbDevice, readBufferSize, alternateInterfaceID, readEndpointID, endpointType)
 {
 }
 internal MonoUsbEndpointWriter(UsbDevice usbDevice, byte alternateInterfaceID, WriteEndpointID writeEndpointID, EndpointType endpointType)
     : base(usbDevice, alternateInterfaceID, writeEndpointID, endpointType)
 {
 }
예제 #32
0
        /// <summary>
        /// Opens the USB device for communucation.
        /// </summary>
        /// <param name="usbDevice">The newly created UsbDevice.</param>
        /// <returns>True on success.</returns>
        public override bool Open(out UsbDevice usbDevice)
        {
            usbDevice = null;
            bool bSuccess = mUSBDevice.Open();
            if (bSuccess)
            {
                usbDevice = mUSBDevice;
                usbDevice.mUsbRegistry = this;
            }

            return bSuccess;
        }
예제 #33
0
        internal static void GetPropertiesSPDRP(UsbDevice usbDevice, Dictionary<string, object> deviceProperties)
        {


            deviceProperties.Add(DevicePropertyType.Mfg.ToString(),
                                  usbDevice.Info.Descriptor.ManufacturerStringIndex > 0 ? usbDevice.Info.ManufacturerString : string.Empty);

            deviceProperties.Add(DevicePropertyType.DeviceDesc.ToString(),
                                  usbDevice.Info.Descriptor.ProductStringIndex > 0 ? usbDevice.Info.ProductString : string.Empty);

            deviceProperties.Add("SerialNumber",
                                  usbDevice.Info.Descriptor.SerialStringIndex > 0 ? usbDevice.Info.SerialString : string.Empty);

            string fakeHardwareIds = GetRegistryHardwareID((ushort)usbDevice.Info.Descriptor.VendorID,
                                                           (ushort)usbDevice.Info.Descriptor.ProductID,
                                                           (ushort)usbDevice.Info.Descriptor.BcdDevice);

            deviceProperties.Add(DevicePropertyType.HardwareId.ToString(), new string[] { fakeHardwareIds });

            string fakeSymbolicName = fakeHardwareIds + "{" + Guid.Empty + " }";

            if (usbDevice.Info.Descriptor.SerialStringIndex > 0)
            {
                fakeSymbolicName += "#" + deviceProperties["SerialNumber"] + "#";
            }
            deviceProperties.Add(SYMBOLIC_NAME_KEY, fakeSymbolicName);
        }
예제 #34
0
 /// <summary>
 /// Opens the USB device for communucation.
 /// </summary>
 /// <param name="usbDevice">The newly created UsbDevice.</param>
 /// <returns>True on success.</returns>
 public override bool Open(out UsbDevice usbDevice)
 {
     usbDevice = null;
     LibUsbDevice libUsbDevice;
     bool bSuccess = Open(out libUsbDevice);
     if (bSuccess)
         usbDevice = libUsbDevice;
     return bSuccess;
 }
예제 #35
0
 internal LegacyUsbRegistry(UsbDevice usbDevice)
 {
     mUSBDevice = usbDevice;
     GetPropertiesSPDRP(mUSBDevice, mDeviceProperties);
 }
예제 #36
0
파일: Utilities.cs 프로젝트: mbin/Win81App
 public static Boolean IsSuperMuttDevice(UsbDevice device)
 {
     return (GetDeviceType(device) == DeviceType.SuperMutt);
 }
 public void Exit()
 {
     this.Disconnect();
     UsbDevice.Exit();
 }