예제 #1
0
        private static void FillEndpointInfo(TreeNode tvEndpoint, UsbEndpointBase i)
        {
            tvEndpoint.Nodes.Add(string.Format("{0}: {1}", "Endpoint Number", i.EpNum));
            tvEndpoint.Nodes.Add(string.Format("{0}: {1} (0x{2:X2})", "Type", i.Type, (int)i.Type));

            FillEndpointInfo(tvEndpoint, i.EndpointInfo);
        }
예제 #2
0
        private void allocTransfer(UsbEndpointBase endpointBase, bool ownsTransfer, int isoPacketSize, int count)
        {
            int numIsoPackets = 0;

            if (isoPacketSize > 0)
            {
                numIsoPackets = count / isoPacketSize;
            }
            freeTransfer();
            mTransfer               = MonoUsbTransfer.Alloc(numIsoPackets);
            mOwnsTransfer           = ownsTransfer;
            mTransfer.Type          = endpointBase.Type;
            mTransfer.Endpoint      = endpointBase.EpNum;
            mTransfer.NumIsoPackets = numIsoPackets;

            if (!mCompleteEventHandle.IsAllocated)
            {
                mCompleteEventHandle = GCHandle.Alloc(mTransferCompleteEvent);
            }
            mTransfer.PtrUserData = GCHandle.ToIntPtr(mCompleteEventHandle);

            if (numIsoPackets > 0)
            {
                mTransfer.SetIsoPacketLengths(isoPacketSize);
            }
        }
예제 #3
0
        public override bool ReadPipe(UsbEndpointBase endPointBase,
                                      IntPtr buffer,
                                      int bufferLength,
                                      out int lengthTransferred,
                                      int isoPacketSize,
                                      IntPtr pOverlapped)
        {
            LibUsbRequest req = new LibUsbRequest();

            req.Endpoint.ID         = endPointBase.EpNum;
            req.Endpoint.PacketSize = isoPacketSize;
            req.Timeout             = UsbConstants.DEFAULT_TIMEOUT;

            int cltCode = endPointBase.Type == EndpointType.Isochronous ? LibUsbIoCtl.ISOCHRONOUS_READ : LibUsbIoCtl.INTERRUPT_OR_BULK_READ;


            return(Kernel32.DeviceIoControl(endPointBase.Device.Handle,
                                            cltCode,
                                            req,
                                            LibUsbRequest.Size,
                                            buffer,
                                            bufferLength,
                                            out lengthTransferred,
                                            pOverlapped));
        }
        private ErrorCode WriteReadBytesCommand(UsbEndpointBase endpoint)
        {
            UsbPacket   usbPacket = CreateReadBytesCommandPacket();
            UsbTransfer transfer  = null;

            try
            {
                ErrorCode errorCode = endpoint.SubmitAsyncTransfer(usbPacket, 0, (int)(_usbPacketSizeWithoutData + usbPacket.uiDataLen), _transferTimeoutInMilliseconds, out transfer);

                if (errorCode != ErrorCode.None)
                {
                    return(errorCode);
                }

                WaitHandle.WaitAll(new[] { transfer.AsyncWaitHandle }, _waitTimeout, false);

                if (!transfer.IsCompleted)
                {
                    transfer.Cancel();
                }

                int bytesTransferred;

                return(transfer.Wait(out bytesTransferred));
            }
            finally
            {
                transfer?.Dispose();
            }
        }
예제 #5
0
        //public override bool WritePipe(UsbEndpointBase endPointBase,
        //                               byte[] Buffer,
        //                               int BufferLength,
        //                               out int LengthTransferred,
        //                               int isoPacketSize,
        //                               IntPtr pOVERLAPPED) { return WinUsb_WritePipe(endPointBase.Device.Handle, endPointBase.EpNum, Buffer, BufferLength, out LengthTransferred, pOVERLAPPED); }

        public override bool WritePipe(UsbEndpointBase endPointBase,
                                       IntPtr pBuffer,
                                       int BufferLength,
                                       out int LengthTransferred,
                                       int isoPacketSize,
                                       IntPtr pOVERLAPPED)
        {
            return(WinUsb_WritePipe(endPointBase.Device.Handle, endPointBase.EpNum, pBuffer, BufferLength, out LengthTransferred, pOVERLAPPED));
        }
예제 #6
0
 public UsbCommand(UsbEndpointBase ep, byte[] buffer, int timeout)
 {
     this.endPoint           = ep;
     this.buffer             = buffer;
     this.timeout            = timeout;
     this.bytesReadOrWritten = -1;
     this.executed           = false;
     this.resultCode         = ErrorCode.None;
     this.result             = null;
 }
예제 #7
0
        private void OnDataReceived_Loop(object sender, DataReceivedArgs e)
        {
            UsbEndpointBase epSendender = (UsbEndpointBase)sender;
            String          sTemp       = "";

            for (int i = 0; i < e.Count; i++)
            {
                sTemp += e.Buffer[i].ToString("X2");
            }

            Debug.Print(" Len:" + e.Count.ToString() + " Data:" + sTemp);
        }
예제 #8
0
        void OnUsbError(object sender, UsbError e)
        {
            if (suppressErrors)
            {
                return;
            }

            string prefix = String.Format("Driver.OnUsbError: sender {0}", sender.GetType());

            if (sender is UsbEndpointBase)
            {
                logger.error("{0} [UsbEndPointBase]: Win32ErrorNumber {1} ({2}): {3}",
                             prefix, e.Win32ErrorNumber, e.Win32ErrorString, e.Description);

                // Magic number 31 came from here: http://libusbdotnet.sourceforge.net/V2/html/718df290-f19a-9033-3a26-1e8917adf15d.htm
                if (e.Win32ErrorNumber == 31)
                {
                    UsbDevice usb = sender as UsbDevice;
                    if (usb.IsOpen)
                    {
                        UsbEndpointBase baseDevice = sender as UsbEndpointBase;
                        // UsbEndpointInfo uei = baseDevice.EndpointInfo;
                        // LibUsbDotNet.Descriptors.UsbEndpointDescriptor ued = uei.Descriptor;
                        logger.error("{0} [UsbEndPointBase]: usb device still open on endpoint {1}", prefix, baseDevice.EpNum);

                        if (baseDevice.Reset())
                        {
                            // docs say to set e.Handled = true here, but UsbError has no such field;
                            // was commented out here:
                            // https://github.com/GeorgeHahn/LibUsbDotNet/blob/master/LibWinUsb/UsbDevice.Error.cs#L49
                            return;
                        }
                    }
                }
            }
            else if (sender is UsbTransfer)
            {
                logger.error("{0} [UsbTransfer]: Win32ErrorNumber {1} ({2}): {3}",
                             prefix, e.Win32ErrorNumber, e.Win32ErrorString, e.Description);
                UsbEndpointBase ep = ((UsbTransfer)sender).EndpointBase;
                logger.error("{0} [UsbTransfer]: Endpoint = 0x{1:x2}", prefix, ep.EpNum);
            }
            else if (sender is Type)
            {
                Type t = sender as Type;
                logger.error("{0} [Type]: type = {1}", prefix, t.Name);
            }
            else
            {
                logger.error("{0} [other]: {1}", prefix, e.ToString());
                // is there anything we should DO here, other than logging it?
            }
        }
        private void allocTransfer(UsbEndpointBase endpointBase, bool ownsTransfer, int isoPacketSize, int count)
        {
            int numIsoPackets = 0;

            // Patch for using libusb-1.0 on windows with libusbwK.sys
            EndpointType endpointType = endpointBase.Type;

            if (UsbDevice.IsLinux)
            {
                if (isoPacketSize > 0)
                {
                    numIsoPackets = count / isoPacketSize;
                }
            }
            else
            {
                if (endpointType == EndpointType.Isochronous)
                {
                    endpointType = EndpointType.Bulk;
                }
            }
            ///////////////////////////////////////////////////////////////

            freeTransfer();
            mTransfer               = MonoUsbTransfer.Alloc(numIsoPackets);
            mOwnsTransfer           = ownsTransfer;
            mTransfer.Type          = endpointType;
            mTransfer.Endpoint      = endpointBase.EpNum;
            mTransfer.NumIsoPackets = numIsoPackets;

            if (!mCompleteEventHandle.IsAllocated)
            {
                mCompleteEventHandle = GCHandle.Alloc(mTransferCompleteEvent);
            }
            mTransfer.PtrUserData = GCHandle.ToIntPtr(mCompleteEventHandle);


            if (numIsoPackets > 0)
            {
                mTransfer.SetIsoPacketLengths(isoPacketSize);
            }
        }
 public OverlappedTransferContext(UsbEndpointBase endpointBase)
     : base(endpointBase)
 {
 }
 public MonoUsbTransferContext(UsbEndpointBase endpointBase)
     : base(endpointBase)
 {
 }
예제 #12
0
        public static void Main(string[] args)
        {
            Error ec = Error.Success;

            using (UsbContext context = new UsbContext())
            {
                try
                {
                    UsbInterfaceInfo usbInterfaceInfo = null;
                    UsbEndpointInfo  usbEndpointInfo  = null;

                    // Find and open the usb device.
                    using (var regList = context.FindAll(MyUsbFinder))
                    {
                        if (regList.Count == 0)
                        {
                            throw new Exception("Device Not Found.");
                        }

                        // Look through all conected devices with this vid and pid until
                        // one is found that has and and endpoint that matches TRANFER_ENDPOINT.
                        //
                        foreach (var regDevice in regList)
                        {
                            if (regDevice.TryOpen())
                            {
                                if (regDevice.Configs.Count > 0)
                                {
                                    // if TRANFER_ENDPOINT is 0x80 or 0x00, LookupEndpointInfo will return the
                                    // first read or write (respectively).
                                    if (UsbEndpointBase.LookupEndpointInfo(MyUsbDevice.Configs[0], TRANFER_ENDPOINT,
                                                                           out usbInterfaceInfo, out usbEndpointInfo))
                                    {
                                        MyUsbDevice = regDevice.Clone();
                                        MyUsbDevice.Open();
                                        break;
                                    }

                                    regDevice.Close();
                                }
                            }
                        }
                    }

                    // If the device is open and ready
                    if (MyUsbDevice == null)
                    {
                        throw new Exception("Device Not Found.");
                    }

                    // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                    // it exposes an IUsbDevice interface. If not (WinUSB) the
                    // 'wholeUsbDevice' variable will be null indicating this is
                    // an interface of a device; it does not require or support
                    // configuration and interface selection.
                    IUsbDevice wholeUsbDevice = MyUsbDevice 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(usbInterfaceInfo.Number);
                    }

                    // open read endpoint.
                    var reader = MyUsbDevice.OpenEndpointReader(
                        (ReadEndpointID)usbEndpointInfo.EndpointAddress,
                        0,
                        (EndpointType)(usbEndpointInfo.Attributes & 0x3));

                    if (ReferenceEquals(reader, null))
                    {
                        throw new Exception("Failed locating read endpoint.");
                    }

                    reader.Reset();

                    // The benchmark device firmware works with this example but it must be put into PC read mode.
#if IS_BENCHMARK_DEVICE
                    int            transferred;
                    byte[]         ctrlData          = new byte[1];
                    UsbSetupPacket setTestTypePacket =
                        new UsbSetupPacket((byte)(UsbCtrlFlags.Direction_In | UsbCtrlFlags.Recipient_Device | UsbCtrlFlags.RequestType_Vendor),
                                           0x0E, 0x01, usbInterfaceInfo.Number, 1);
                    transferred = MyUsbDevice.ControlTransfer(setTestTypePacket, ctrlData, 0, 1);
#endif
                    TRANFER_SIZE -= (TRANFER_SIZE % usbEndpointInfo.MaxPacketSize);

                    UsbTransferQueue transferQeue = new UsbTransferQueue(reader,
                                                                         TRANFER_MAX_OUTSTANDING_IO,
                                                                         TRANFER_SIZE,
                                                                         5000,
                                                                         usbEndpointInfo.MaxPacketSize);

                    do
                    {
                        UsbTransferQueue.Handle handle;

                        // Begin submitting transfers until TRANFER_MAX_OUTSTANDING_IO has benn reached.
                        // then wait for the oldest outstanding transfer to complete.
                        //
                        ec = transferQeue.Transfer(out handle);
                        if (ec != Error.Success)
                        {
                            throw new Exception("Failed getting async result");
                        }

                        // Show some information on the completed transfer.
                        showTransfer(handle, mTransferCount);
                    } while (mTransferCount++ < TRANSFER_COUNT);

                    // Cancels any oustanding transfers and free's the transfer queue handles.
                    // NOTE: A transfer queue can be reused after it's freed.
                    transferQeue.Free();

                    Console.WriteLine("\r\nDone!\r\n");
                }
                catch (Exception ex)
                {
                    Console.WriteLine();
                    Console.WriteLine((ec != Error.Success ? ec + ":" : String.Empty) + ex.Message);
                }
                finally
                {
                    if (MyUsbDevice != null)
                    {
                        if (MyUsbDevice.IsOpen)
                        {
                            // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                            // it exposes an IUsbDevice interface. If not (WinUSB) the
                            // 'wholeUsbDevice' variable will be null indicating this is
                            // an interface of a device; it does not require or support
                            // configuration and interface selection.
                            IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                            if (!ReferenceEquals(wholeUsbDevice, null))
                            {
                                // Release interface #0.
                                wholeUsbDevice.ReleaseInterface(0);
                            }

                            MyUsbDevice.Close();
                        }
                        MyUsbDevice = null;
                    }

                    // Wait for user input..
                    Console.ReadKey();
                }
            }
        }
예제 #13
0
        private void PollUSBDevice()
        {
            ErrorCode ec = ErrorCode.None;

            UsbDevice MyUsbDevice = null;

            UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(multimeter.VendorId, multimeter.ProductId);

            UsbEndpointReader reader = null;

            try
            {
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

                UsbEndpointInfo  endpointInfo     = null;
                UsbInterfaceInfo usbInterfaceInfo = null;

                if (UsbEndpointBase.LookupEndpointInfo(MyUsbDevice.Configs[0], UsbConstants.ENDPOINT_DIR_MASK, out usbInterfaceInfo, out endpointInfo) == false)
                {
                    MyUsbDevice.Close();
                    MyUsbDevice = null;
                }

                if (MyUsbDevice == null)
                {
                    Application.Current.Dispatcher.BeginInvoke(
                        new WriteConsolasDelegate(multimeter.WriteConsolas),
                        new object[] { "Can't find multimeter device!", "Error" });
                }

                IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    wholeUsbDevice.SetConfiguration(1);
                    wholeUsbDevice.SetConfiguration(0);
                    wholeUsbDevice.SetConfiguration(1);

                    wholeUsbDevice.ClaimInterface(usbInterfaceInfo.Descriptor.InterfaceID);
                }

                UsbSetupPacket packetSettings = new UsbSetupPacket(0x21, 0x09, 0x0300, 0x0000, 0x0005);

                byte[] buffer      = { 0x60, 0x09, 0x00, 0x00, 0x03 };
                int    transferred = 0;

                MyUsbDevice.ControlTransfer(ref packetSettings, buffer, 5, out transferred);

                transferred = 0;
                MyUsbDevice.ControlTransfer(ref packetSettings, buffer, 5, out transferred);

                try
                {
                    reader = MyUsbDevice.OpenEndpointReader((ReadEndpointID)endpointInfo.Descriptor.EndpointID, 0, (EndpointType)(endpointInfo.Descriptor.Attributes & 0x3));
                }
                catch (Exception e)
                {
                    Application.Current.Dispatcher.BeginInvoke(
                        new WriteConsolasDelegate(multimeter.WriteConsolas),
                        new object[] { e.Message, "Error" });
                }


                Application.Current.Dispatcher.BeginInvoke(
                    new WriteConsolasDelegate(multimeter.WriteConsolas),
                    new object[] { String.Format("Starting read from device <{0}:{1}>.", multimeter.VendorId.ToString(), multimeter.ProductId.ToString()), "Log" });

                while (ec == ErrorCode.None && !stopRequested)
                {
                    if (fixRequested)
                    {
                        Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            CloseFix();
                        }));
                        transferred = 0;
                        MyUsbDevice.ControlTransfer(ref packetSettings, buffer, 5, out transferred);
                        transferred = 0;
                        MyUsbDevice.ControlTransfer(ref packetSettings, buffer, 5, out transferred);
                        transferred = 0;
                        MyUsbDevice.ControlTransfer(ref packetSettings, buffer, 5, out transferred);

                        Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            multimeter.WriteConsolas("Fix attempt ended.");
                        }));
                    }

                    byte[] readBuffer = new byte[8];
                    int    bytesRead;
                    ec = reader.Read(readBuffer, 100, out bytesRead);

                    byte[] cloneBuffer = readBuffer;

                    Application.Current.Dispatcher.BeginInvoke(
                        new OneArgDelegate(HandleData),
                        new object[] { cloneBuffer });
                }
            }
            catch (Exception ex)
            {
                try
                {
                    Application.Current.Dispatcher.BeginInvoke(
                        new WriteConsolasDelegate(multimeter.WriteConsolas),
                        new object[] { ex.Message, "Error" });
                }
                catch (Exception e)
                {
                }
            }
            finally
            {
                Application.Current.Dispatcher.BeginInvoke(
                    new WriteConsolasDelegate(multimeter.WriteConsolas),
                    new object[] { "Stopping read. " + ec.ToString(), "Log" });


                if (reader != null)
                {
                    reader.Abort();
                }
                if (MyUsbDevice != null)
                {
                    if (MyUsbDevice.IsOpen)
                    {
                        IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                        if (!ReferenceEquals(wholeUsbDevice, null))
                        {
                            wholeUsbDevice.ReleaseInterface(0);
                        }

                        MyUsbDevice.Close();
                    }
                    MyUsbDevice = null;
                    try
                    {
                        UsbDevice.Exit();
                    }
                    catch (Exception e)
                    {
                        Application.Current.Dispatcher.BeginInvoke(
                            new WriteConsolasDelegate(multimeter.WriteConsolas),
                            new object[] { e.Message, "Error" });
                    }
                }
            }
        }
 protected TransferContextBase(UsbEndpointBase endpointBase)
 {
     mEndpointBase = endpointBase;
 }
예제 #15
0
 public TransferContext(UsbEndpointBase usbEndpointBase)
 {
     mEndpointBase = usbEndpointBase;
 }
        private unsafe ReadUsbPacketResult ReadUsbPacket(UsbEndpointBase endpoint)
        {
            UsbTransfer transfer = null;

            try
            {
                var       usbPacketBuffer = new byte[_usbPacketSize];
                ErrorCode errorCode       = endpoint.SubmitAsyncTransfer(usbPacketBuffer, 0, usbPacketBuffer.Length, _transferTimeoutInMilliseconds, out transfer);

                if (errorCode != ErrorCode.None)
                {
                    _error.OnNext(errorCode);

                    return(new ReadUsbPacketResult(errorCode));
                }

                WaitHandle.WaitAll(new[] { transfer.AsyncWaitHandle }, _waitTimeout, false);

                if (!transfer.IsCompleted)
                {
                    transfer.Cancel();
                }

                int bytesTransferred;

                errorCode = transfer.Wait(out bytesTransferred);

                if (bytesTransferred == 0)
                {
                    return(new ReadUsbPacketResult(errorCode));
                }

                GCHandle gcHandle  = GCHandle.Alloc(usbPacketBuffer, GCHandleType.Pinned);
                var      usbPacket = Marshal.PtrToStructure <UsbPacket>(gcHandle.AddrOfPinnedObject());

                if (usbPacket.uiSeqNum != _sequenceNumber)
                {
                    _incorrectSequenceNumberReceived.OnNext(new IncorrectSequenceNumberReceivedArgs(_sequenceNumber, usbPacket.uiSeqNum));

                    return(new ReadUsbPacketResult(errorCode));
                }

                _sequenceNumber++;

                if (bytesTransferred < _usbPacketSizeWithoutData)
                {
                    _incorrectNumberOfBytesReceived.OnNext(bytesTransferred);

                    return(new ReadUsbPacketResult(errorCode));
                }
                if (errorCode != ErrorCode.None)
                {
                    return(new ReadUsbPacketResult(errorCode));
                }
                if (usbPacket.uiDataLen == 0)
                {
                    _noData.OnNext(Unit.Default);

                    return(new ReadUsbPacketResult(errorCode));
                }

                _fileOffset += usbPacket.uiDataLen;

                var strokes    = new List <Stroke>();
                var dataBuffer = new byte[usbPacket.uiDataLen];
                Marshal.Copy(new IntPtr(usbPacket.pData), dataBuffer, 0, dataBuffer.Length);

                for (var i = 0; i < dataBuffer.Length; i += 8)
                {
                    strokes.Add(new Stroke(dataBuffer[i], dataBuffer[i + 1], dataBuffer[i + 2], dataBuffer[i + 3]));
                }

                return(new ReadUsbPacketResult(errorCode, strokes));
            }
            finally
            {
                transfer?.Dispose();
            }
        }
예제 #17
0
        public void readIso()
        {
            ErrorCode ec = ErrorCode.None;

            try
            {
                // Find and open the usb device.
                UsbRegDeviceList regList = UsbDevice.AllDevices.FindAll(MyUsbFinder);
                if (regList.Count == 0)
                {
                    throw new Exception("Device Not Found.");
                }

                UsbInterfaceInfo usbInterfaceInfo = null;
                UsbEndpointInfo  usbEndpointInfo  = null;

                // Look through all conected devices with this vid and pid until
                // one is found that has and and endpoint that matches TRANFER_ENDPOINT.
                //
                foreach (UsbRegistry regDevice in regList)
                {
                    if (regDevice.Open(out MyUsbDevice))
                    {
                        if (MyUsbDevice.Configs.Count > 0)
                        {
                            // if TRANFER_ENDPOINT is 0x80 or 0x00, LookupEndpointInfo will return the
                            // first read or write (respectively).
                            if (UsbEndpointBase.LookupEndpointInfo(MyUsbDevice.Configs[0], TRANFER_ENDPOINT,
                                                                   out usbInterfaceInfo, out usbEndpointInfo))
                            {
                                break;
                            }

                            MyUsbDevice.Close();
                            MyUsbDevice = null;
                        }
                    }
                }

                // If the device is open and ready
                if (MyUsbDevice == null)
                {
                    throw new Exception("Device Not Found.");
                }

                // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                // it exposes an IUsbDevice interface. If not (WinUSB) the
                // 'wholeUsbDevice' variable will be null indicating this is
                // an interface of a device; it does not require or support
                // configuration and interface selection.
                IUsbDevice wholeUsbDevice = MyUsbDevice 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(usbInterfaceInfo.Descriptor.InterfaceID);
                }

                // open read endpoint.
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(
                    (ReadEndpointID)usbEndpointInfo.Descriptor.EndpointID,
                    0,
                    (EndpointType)(usbEndpointInfo.Descriptor.Attributes & 0x3));

                if (ReferenceEquals(reader, null))
                {
                    throw new Exception("Failed locating read endpoint.");
                }

                reader.Reset();


                TRANFER_SIZE -= (TRANFER_SIZE % usbEndpointInfo.Descriptor.MaxPacketSize);

                UsbTransferQueue transferQeue = new UsbTransferQueue(reader,
                                                                     TRANFER_MAX_OUTSTANDING_IO,
                                                                     TRANFER_SIZE,
                                                                     5000,
                                                                     usbEndpointInfo.Descriptor.MaxPacketSize);

                do
                {
                    UsbTransferQueue.Handle handle;

                    // Begin submitting transfers until TRANFER_MAX_OUTSTANDING_IO has benn reached.
                    // then wait for the oldest outstanding transfer to complete.
                    //
                    ec = transferQeue.Transfer(out handle);
                    if (ec != ErrorCode.Success)
                    {
                        throw new Exception("Failed getting async result");
                    }

                    // Show some information on the completed transfer.
                    showTransfer(handle, mTransferCount);
                } while (mTransferCount++ < TRANSFER_COUNT);

                // Cancels any oustanding transfers and free's the transfer queue handles.
                // NOTE: A transfer queue can be reused after it's freed.
                transferQeue.Free();
            }
            catch (Exception ex)
            {
                form.setText("\r\n");
                form.setText((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
            }
            finally
            {
                if (MyUsbDevice != null)
                {
                    if (MyUsbDevice.IsOpen)
                    {
                        // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                        // it exposes an IUsbDevice interface. If not (WinUSB) the
                        // 'wholeUsbDevice' variable will be null indicating this is
                        // an interface of a device; it does not require or support
                        // configuration and interface selection.
                        IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                        if (!ReferenceEquals(wholeUsbDevice, null))
                        {
                            // Release interface #0.
                            wholeUsbDevice.ReleaseInterface(0);
                        }

                        MyUsbDevice.Close();
                    }
                    MyUsbDevice = null;
                }

                // Free usb resources
                UsbDevice.Exit();
            }
        }
예제 #18
0
        //public abstract bool WritePipe(UsbEndpointBase endPointBase,
        //                               Byte[] buffer,
        //                               int bufferLength,
        //                               out int lengthTransferred,
        //                               int isoPacketSize,
        //                               IntPtr pOverlapped);

        public abstract bool WritePipe(UsbEndpointBase endPointBase,
                                       IntPtr pBuffer,
                                       int bufferLength,
                                       out int lengthTransferred,
                                       int isoPacketSize,
                                       IntPtr pOverlapped);
예제 #19
0
        private bool openAsTestDevice(UsbRegistry usbRegistry)
        {
            if (!ReferenceEquals(mUsbDevice, null))
            {
                closeTestDevice(mUsbDevice);
            }

            mUsbDevice = null;

            try
            {
                if (usbRegistry.Open(out mUsbDevice))
                {
                    UsbInterfaceInfo readInterfaceInfo;
                    UsbInterfaceInfo writeInterfaceInfo;

                    UsbDevice.UsbErrorEvent += OnUsbError;

                    if (!UsbEndpointBase.LookupEndpointInfo(mUsbDevice.Configs[0],
                                                            0x80,
                                                            out readInterfaceInfo,
                                                            out mReadEndpointInfo))
                    {
                        throw new Exception("failed locating read endpoint.");
                    }

                    mBenchMarkParameters.BufferSize -= (mBenchMarkParameters.BufferSize % (mReadEndpointInfo.Descriptor.MaxPacketSize));

                    if (!UsbEndpointBase.LookupEndpointInfo(mUsbDevice.Configs[0],
                                                            0x00,
                                                            out writeInterfaceInfo,
                                                            out mWriteEndpointInfo))
                    {
                        throw new Exception("failed locating write endpoint.");
                    }

                    if (((mWriteEndpointInfo.Descriptor.Attributes & 3) == (int)EndpointType.Isochronous) ||
                        ((mReadEndpointInfo.Descriptor.Attributes & 3) == (int)EndpointType.Isochronous))
                    {
                        throw new Exception("buenchmark GUI application does not support ISO endpoints. Use BenchmarkCon instead.");
                    }

                    mBenchMarkParameters.BufferSize -= (mBenchMarkParameters.BufferSize % (mWriteEndpointInfo.Descriptor.MaxPacketSize));

                    if (writeInterfaceInfo.Descriptor.InterfaceID != readInterfaceInfo.Descriptor.InterfaceID)
                    {
                        throw new Exception("read/write endpoints must be on the same interface.");
                    }

                    mEP1Reader = mUsbDevice.OpenEndpointReader(
                        (ReadEndpointID)mReadEndpointInfo.Descriptor.EndpointID,
                        mBenchMarkParameters.BufferSize,
                        (EndpointType)(mReadEndpointInfo.Descriptor.Attributes & 3));

                    mEP1Writer = mUsbDevice.OpenEndpointWriter(
                        (WriteEndpointID)mWriteEndpointInfo.Descriptor.EndpointID,
                        (EndpointType)(mWriteEndpointInfo.Descriptor.Attributes & 3));

                    mInterfaceInfo = writeInterfaceInfo;

                    mEP1Reader.ReadThreadPriority = mBenchMarkParameters.Priority;
                    mEP1Reader.DataReceived      += OnDataReceived;

                    makeTestBytes(out loopTestBytes, mBenchMarkParameters.BufferSize);


                    // If this is a "whole" usb device (libusb-win32, linux libusb)
                    // it will have an IUsbDevice interface. If not (WinUSB) the
                    // variable will be null indicating this is an interface of a
                    // device.
                    IUsbDevice wholeUsbDevice = mUsbDevice 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(mInterfaceInfo.Descriptor.InterfaceID);
                    }
                    return(true);
                }
            }
            catch (Exception ex)
            {
                SetStatus(ex.Message, true);
            }

            if (!ReferenceEquals(mUsbDevice, null))
            {
                try
                {
                    closeTestDevice(mUsbDevice);
                }
                finally
                {
                    mUsbDevice = null;
                    mEP1Reader = null;
                    mEP1Writer = null;
                }
            }
            return(false);
        }
예제 #20
0
 public static void SubscribeForDataReceived(this UsbEndpointBase endpoint, Action <byte[]> handler)
 {
     Debug.Assert(endpoint is UsbEndpointReader);
     (endpoint as UsbEndpointReader).SubscribeForDataReceived(handler);
 }
예제 #21
0
        /// <summary>
        /// Get Endpoint reader
        /// </summary>
        /// <returns></returns>
        private static UsbEndpointReader GetReader(out UsbDevice MyUsbDevice, out int interfaceID)
        {
            UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x1915, 0x7B);

            // Find and open the usb device.
            UsbRegDeviceList regList = UsbDevice.AllDevices.FindAll(MyUsbFinder);

            if (regList.Count == 0)
            {
                throw new Exception("No receiver devices found.\r\n");
            }

            UsbInterfaceInfo usbInterfaceInfo = null;
            UsbEndpointInfo  usbEndpointInfo  = null;

            MyUsbDevice = null;

            // Look through all conected devices with this vid and pid until
            // one is found that has and and endpoint that matches TRANFER_ENDPOINT.
            //
            foreach (UsbRegistry regDevice in regList)
            {
                if (regDevice.Open(out MyUsbDevice))
                {
                    if (MyUsbDevice.Configs.Count > 0)
                    {
                        // if TRANFER_ENDPOINT is 0x80 or 0x00, LookupEndpointInfo will return the
                        // first read or write (respectively).
                        if (UsbEndpointBase.LookupEndpointInfo(MyUsbDevice.Configs[0], 0x88,//TRANSFER_ENDPOINT,
                                                               out usbInterfaceInfo, out usbEndpointInfo))
                        {
                            break;
                        }

                        MyUsbDevice.Close();
                        MyUsbDevice = null;
                    }
                }
            }

            // If the device is open and ready
            if (MyUsbDevice == null)
            {
                throw new Exception("Receiver device was found, but did not have the correct endpoint address.\r\n");
            }

            // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
            // it exposes an IUsbDevice interface. If not (WinUSB) the
            // 'wholeUsbDevice' variable will be null indicating this is
            // an interface of a device; it does not require or support
            // configuration and interface selection.
            IUsbDevice wholeUsbDevice = MyUsbDevice 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);

                wholeUsbDevice.ClaimInterface(usbInterfaceInfo.Descriptor.InterfaceID);
            }
            else
            {
                throw new Exception("Could not find Penny receiver device");
            }

            interfaceID = usbInterfaceInfo.Descriptor.InterfaceID;

            // open read endpoint.
            UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(
                (ReadEndpointID)usbEndpointInfo.Descriptor.EndpointID,
                0,
                (EndpointType)(usbEndpointInfo.Descriptor.Attributes & 0x3));

            if (ReferenceEquals(reader, null))
            {
                throw new Exception("Failed to locate read endpoint for JAGA Penny receiver.\r\n");
            }

            reader.Reset();

            return(reader);
        }