private static void free(UsbTransferQueue transferParam) { for (int i = 0; i < transferParam.MaxOutstandingIO; i++) { if (!ReferenceEquals(transferParam.mTransferHandles[i], null)) { if (transferParam.mTransferHandles[i].InUse) { if (!transferParam.mTransferHandles[i].Context.IsCompleted) { transferParam.EndpointBase.Abort(); Thread.Sleep(1); } transferParam.mTransferHandles[i].InUse = false; transferParam.mTransferHandles[i].Context.Dispose(); } transferParam.mTransferHandles[i] = null; } } transferParam.mOutstandingTransferCount = 0; transferParam.mTransferHandleNextIndex = 0; transferParam.mTransferHandleWaitIndex = 0; }
private static ErrorCode transfer(UsbTransferQueue transferParam, out Handle handle) { handle = null; ErrorCode ret = ErrorCode.Success; // Submit transfers until the maximum number of outstanding transfer(s) is reached. while (transferParam.mOutstandingTransferCount < transferParam.MaxOutstandingIO) { if (ReferenceEquals(transferParam.mTransferHandles[transferParam.mTransferHandleNextIndex], null)) { handle = transferParam.mTransferHandles[transferParam.mTransferHandleNextIndex] = new Handle(transferParam.EndpointBase.NewAsyncTransfer(), transferParam.mBuffer[transferParam.mTransferHandleNextIndex]); // Get the next available benchmark transfer handle. handle.Context.Fill(handle.Data, 0, handle.Data.Length, transferParam.Timeout, transferParam.IsoPacketSize); } else { // Get the next available benchmark transfer handle. handle = transferParam.mTransferHandles[transferParam.mTransferHandleNextIndex]; } handle.Transferred = 0; // Submit this transfer now. handle.Context.Reset(); ret = handle.Context.Submit(); if (ret != ErrorCode.Success) goto Done; // Mark this handle has InUse. handle.InUse = true; // When transfers ir successfully submitted, OutstandingTransferCount goes up; when // they are completed it goes down. // transferParam.mOutstandingTransferCount++; // Move TransferHandleNextIndex to the next available transfer. IncWithRoll(ref transferParam.mTransferHandleNextIndex, transferParam.MaxOutstandingIO); } // If the number of outstanding transfers has reached the limit, wait for the // oldest outstanding transfer to complete. // if (transferParam.mOutstandingTransferCount == transferParam.MaxOutstandingIO) { // TransferHandleWaitIndex is the index of the oldest outstanding transfer. handle = transferParam.mTransferHandles[transferParam.mTransferHandleWaitIndex]; ret = handle.Context.Wait(out handle.Transferred, false); if (ret != ErrorCode.Success) goto Done; // Mark this handle has no longer InUse. handle.InUse = false; // When transfers ir successfully submitted, OutstandingTransferCount goes up; when // they are completed it goes down. // transferParam.mOutstandingTransferCount--; // Move TransferHandleWaitIndex to the oldest outstanding transfer. IncWithRoll(ref transferParam.mTransferHandleWaitIndex, transferParam.MaxOutstandingIO); return ErrorCode.Success; } Done: return ret; }
private static ErrorCode transfer(UsbTransferQueue transferParam, out Handle handle) { handle = null; ErrorCode ret = ErrorCode.Success; // Submit transfers until the maximum number of outstanding transfer(s) is reached. while (transferParam.mOutstandingTransferCount < transferParam.MaxOutstandingIO) { if (ReferenceEquals(transferParam.mTransferHandles[transferParam.mTransferHandleNextIndex], null)) { handle = transferParam.mTransferHandles[transferParam.mTransferHandleNextIndex] = new Handle(transferParam.EndpointBase.NewAsyncTransfer(), transferParam.mBuffer[transferParam.mTransferHandleNextIndex]); // Get the next available benchmark transfer handle. handle.Context.Fill(handle.Data, 0, handle.Data.Length, transferParam.Timeout, transferParam.IsoPacketSize); } else { // Get the next available benchmark transfer handle. handle = transferParam.mTransferHandles[transferParam.mTransferHandleNextIndex]; } handle.Transferred = 0; // Submit this transfer now. handle.Context.Reset(); ret = handle.Context.Submit(); if (ret != ErrorCode.Success) { goto Done; } // Mark this handle has InUse. handle.InUse = true; // When transfers ir successfully submitted, OutstandingTransferCount goes up; when // they are completed it goes down. // transferParam.mOutstandingTransferCount++; // Move TransferHandleNextIndex to the next available transfer. IncWithRoll(ref transferParam.mTransferHandleNextIndex, transferParam.MaxOutstandingIO); } // If the number of outstanding transfers has reached the limit, wait for the // oldest outstanding transfer to complete. // if (transferParam.mOutstandingTransferCount == transferParam.MaxOutstandingIO) { // TransferHandleWaitIndex is the index of the oldest outstanding transfer. handle = transferParam.mTransferHandles[transferParam.mTransferHandleWaitIndex]; ret = handle.Context.Wait(out handle.Transferred, false); if (ret != ErrorCode.Success) { goto Done; } // Mark this handle has no longer InUse. handle.InUse = false; // When transfers ir successfully submitted, OutstandingTransferCount goes up; when // they are completed it goes down. // transferParam.mOutstandingTransferCount--; // Move TransferHandleWaitIndex to the oldest outstanding transfer. IncWithRoll(ref transferParam.mTransferHandleWaitIndex, transferParam.MaxOutstandingIO); return(ErrorCode.Success); } Done: return(ret); }
private static void free(UsbTransferQueue transferParam) { for (int i = 0; i < transferParam.MaxOutstandingIO; i++) { if (!ReferenceEquals(transferParam.mTransferHandles[i], null)) { if (transferParam.mTransferHandles[i].InUse) { if (!transferParam.mTransferHandles[i].Context.IsCompleted) { transferParam.EndpointBase.Abort(); Thread.Sleep(1); } transferParam.mTransferHandles[i].InUse = false; transferParam.mTransferHandles[i].Context.Dispose(); } transferParam.mTransferHandles[i] = null; } } transferParam.mOutstandingTransferCount = 0; transferParam.mTransferHandleNextIndex = 0; transferParam.mTransferHandleWaitIndex = 0; }
public static void Main(string[] args) { 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(); // 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.Descriptor.InterfaceID,1); MyUsbDevice.ControlTransfer(ref setTestTypePacket,ctrlData, 1, out transferred); #endif 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(); Console.WriteLine("\r\nDone!\r\n"); } catch (Exception ex) { Console.WriteLine(); Console.WriteLine((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; } // Wait for user input.. Console.ReadKey(); // Free usb resources UsbDevice.Exit(); } }
private static void showTransfer(UsbTransferQueue.Handle handle, int transferIndex) { if (mStartTime == DateTime.MinValue) { mStartTime = DateTime.Now; Console.WriteLine("Synchronizing.."); return; } mTotalBytes += handle.Transferred; double bytesSec = mTotalBytes/(DateTime.Now - mStartTime).TotalSeconds; Console.WriteLine("#{0} complete. {1} bytes/sec ({2} bytes) Data[1]={3:X2}", transferIndex, Math.Round(bytesSec, 2), handle.Transferred, handle.Data[1]); }
public void StartReading() { bool channelOne; ErrorCode ec = new ErrorCode(); try { 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.Descriptor.InterfaceID, 1); MyUsbDevice.ControlTransfer(ref setTestTypePacket, ctrlData, 1, out transferred); #endif TRANFER_SIZE -= (TRANFER_SIZE % usbEndpointInfo.Descriptor.MaxPacketSize); mTransferCount = 0; 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: " + ec.ToString()); // Show some information on the completed transfer. int seed; int i = AppSettings.InitialHeader; seed = 0; channelOne = true; int footerCheck = 0; for (int j = 192; j < handle.Data.Length + 3; j+=196) { footerCheck += handle.Data[j] + handle.Data[j + 1] + handle.Data[j + 2] + handle.Data[j + 3]; } // We've seen the four byte 0 delimiters start at byte 48 and at byte 96. This should reasonably detect where. bool delimAt96 = footerCheck == 0; int ch1Counter = 0, ch2Counter = 0; for (i = AppSettings.InitialHeader; i < handle.Data.Length; i += 2) { if (i != 0 && ((delimAt96 && i % 192 == 0) || (!delimAt96 && (i + 48 * 2) % 192 == 0) || (!delimAt96 && i == 48 * 2))) { i += 4; break; } if (channelOne) { InformationHolder.HighGainContainer().Add(Controller.GraphListComboBoxIndex, ch1SampleCounter++, (Int16)((handle.Data[i]) + (handle.Data[i + 1] << 8))); ch1Counter+=2; } else { InformationHolder.LowGainContainer().Add(Controller.GraphListComboBoxIndex, ch2SampleCounter++, (Int16)((handle.Data[i]) + (handle.Data[i + 1] << 8))); ch2Counter+=2; } if (ch1Counter == AppSettings.ChannelOneOffset) { ch1Counter = 0; channelOne = !channelOne; i += AppSettings.ChannelTwoHeader; } if (ch2Counter == AppSettings.ChannelTwoOffset) { ch2Counter = 0; channelOne = !channelOne; i += AppSettings.ChannelOneHeader; } } //_shouldStopUSB = true; } while (!_shouldStopUSB); //Send Parsed Data to MainForm //MainForm.UpdateZedGraph(); // Cancels any oustanding transfers and free's the transfer queue handles. // NOTE: A transfer queue can be reused after it's freed. transferQeue.Free(); rawAccelData.Clear(); Controller.AnalyticsSetConsoleTextboxThreadSafe("Done!" + Environment.NewLine); } catch (Exception ex) { Controller.AnalyticsSetConsoleTextboxThreadSafe((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message); } _shouldStopUSB = false; Thread.CurrentThread.Abort(); }
public void StartReading() { ErrorCode ec = new ErrorCode(); writer = new StreamWriter("Data.txt"); try { 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.Descriptor.InterfaceID, 1); MyUsbDevice.ControlTransfer(ref setTestTypePacket, ctrlData, 1, out transferred); #endif TRANFER_SIZE -= (TRANFER_SIZE % usbEndpointInfo.Descriptor.MaxPacketSize); mTransferCount = 0; UsbTransferQueue transferQeue = new UsbTransferQueue(reader, TRANFER_MAX_OUTSTANDING_IO, TRANFER_SIZE, 5000, usbEndpointInfo.Descriptor.MaxPacketSize); int seed; int i; 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: " + ec.ToString()); // Show some information on the completed transfer. seed = 0; for (i = 0; i < handle.Data.Length; i += 2) { InformationHolder.Instance().zedGraphData.Add(MainForm.graphXIndex++, (Int16)((handle.Data[i]) + (handle.Data[i + 1] << 8))); //writer.Write((Int16)((rawAccelData[i]) + (rawAccelData[i + 1] << 8)) + ","); //Only read one channel if (i == seed + 94) { i += 100; seed = i + 2; } } } while (!_shouldStopUSB); //Send Parsed Data to MainForm //MainForm.UpdateZedGraph(); // Cancels any oustanding transfers and free's the transfer queue handles. // NOTE: A transfer queue can be reused after it's freed. transferQeue.Free(); rawAccelData.Clear(); MainForm.SetConsoleTextboxThreadSafe("Done!\n"); } catch (Exception ex) { MainForm.SetConsoleTextboxThreadSafe((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message); } writer.Close(); _shouldStopUSB = false; Thread.CurrentThread.Abort(); }