OpenEndpointReader() public method

Opens a EndpointType.Bulk endpoint for reading
public OpenEndpointReader ( ReadEndpointID readEndpointID ) : UsbEndpointReader
readEndpointID ReadEndpointID Endpoint number for read operations.
return UsbEndpointReader
コード例 #1
1
        /// <summary>
        /// Class constructor for the traq|paq
        /// </summary>
        public TraqpaqDevice()
        {
            // find the device
            traqpaqDeviceFinder = new UsbDeviceFinder(Constants.VID, Constants.PID);

            // open the device
            this.MyUSBDevice = UsbDevice.OpenUsbDevice(traqpaqDeviceFinder);

            // If the device is open and ready
            if (MyUSBDevice == null) throw new TraqPaqNotConnectedException("Device not found");

            this.reader = MyUSBDevice.OpenEndpointReader(ReadEndpointID.Ep01);
            this.writer = MyUSBDevice.OpenEndpointWriter(WriteEndpointID.Ep02);

            // create the battery object
            this.battery = new Battery(this);

            // get a list of saved tracks
            getAllTracks();

            // get the record table data
            tableReader = new RecordTableReader(this);
            tableReader.readRecordTable();
            this.recordTableList = tableReader.recordTable;
        }
コード例 #2
0
 public void open()
 {
     // Find and open the usb device.
     MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
     if (MyUsbDevice == null) throw new Exception("Device Not Found.");
     UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
 }
コード例 #3
0
        public SmartScopeUsbInterfaceLibUsb(UsbDevice usbDevice)
        {
            if (usbDevice is IUsbDevice)
            {
                bool succes1 = (usbDevice as IUsbDevice).SetConfiguration(1);
                if (!succes1)
                    throw new ScopeIOException("Failed to set usb device configuration");
                bool succes2 = (usbDevice as IUsbDevice).ClaimInterface(0);
                if (!succes2)
                    throw new ScopeIOException("Failed to claim usb interface");
            }
            device = usbDevice;
            serial = usbDevice.Info.SerialString;
            dataEndpoint = usbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
            commandWriteEndpoint = usbDevice.OpenEndpointWriter(WriteEndpointID.Ep02);
            commandReadEndpoint = usbDevice.OpenEndpointReader(ReadEndpointID.Ep03);

            Common.Logger.Debug("Created new ScopeUsbInterface from device with serial " + serial);
        }
コード例 #4
0
ファイル: GarminUnit.cs プロジェクト: GSharp-Project/GSharp
        public GarminUnit(UsbDevice Device)
        {
            Configuration = new Dictionary<string, ushort>();

            IUsbDevice wholedevice = Device as IUsbDevice;
            if ( !ReferenceEquals(wholedevice, null))
            {
                wholedevice.SetConfiguration(1);
                wholedevice.ClaimInterface(0);
            }
            Reader = Device.OpenEndpointReader(ReadEndpointID.Ep01);
            Writer = Device.OpenEndpointWriter(WriteEndpointID.Ep02);
        }
コード例 #5
0
        public PolhemusStream()
        {
            try
            {
                // Find and open the usb device.
                PolhemusUsbDevice = UsbDevice.OpenUsbDevice(UsbFinder);

                // If the device is open and ready
                if (PolhemusUsbDevice == null) throw new Exception("Polhemus not found.");

                // 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 = PolhemusUsbDevice 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);
                }

                //Polhemus uses EndPoint 2 for both read and write
                PolhemusReader = PolhemusUsbDevice.OpenEndpointReader(ReadEndpointID.Ep02);
                PolhemusWriter = PolhemusUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep02);
            }
            catch (Exception e)
            {
                throw new Exception("Error in PolhemusStream constructor: " + e.Message);
            }
        }
コード例 #6
0
        /// <summary> 
        /// The method performs the main function of the service. It runs on  
        /// a thread pool worker thread. 
        /// </summary> 
        /// <param name="state"></param> 
        private void ServiceWorkerThread(object state)
        {
            GetIDs();
            ErrorCode ec = ErrorCode.None;
            try
            {
                // Find and open the usb device.
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
                // If the device is open and ready
                if (MyUsbDevice == null) throw new Exception("Device Not Found.");

                IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    wholeUsbDevice.SetConfiguration(1);
                    wholeUsbDevice.ClaimInterface(0);
                }
                // open read endpoint 1.
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

                byte[] readBuffer = new byte[1024];
                int bytesRead = 0;

                // Periodically check if the service is stopping.
                while (!this.stopping)
                {
                    //Thread.Sleep(2000);  // Simulate some lengthy operations.
                    ec = reader.Read(readBuffer, 30000, out bytesRead);
                    if (bytesRead > 0)
                    {
                        string trackString = Encoding.Default.GetString(readBuffer, 0, bytesRead);
                        string[] words = trackString.Split('?');
                        System.IO.StreamWriter fileReader2 = new System.IO.StreamWriter(trackFile, true);

                        if (words.Length > 0)
                        {
                            //Console.WriteLine();
                            string[] track1 = words[0].Split('%');
                            if (track1.Length > 1 && track1[1].Length > 0)
                            {
                                fileReader2.WriteLine(track1[1]);
                                //Console.WriteLine(track1[1]);
                            }
                        }
                        if (words.Length > 1)
                        {
                            string[] track2 = words[1].Split(';');
                            if (track2.Length > 1 && track2[1].Length > 0)
                            {
                                fileReader2.WriteLine(track2[1]);
                                //Console.WriteLine(track2[1]);
                            }
                        }
                        if (words.Length > 2)
                        {
                            string[] track3 = words[2].Split(';');
                            if (track3.Length > 1 && track3[1].Length > 0)
                            {
                                fileReader2.WriteLine(track3[1]);
                                //Console.WriteLine(track3[1]);
                            }
                        }
                        fileReader2.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                System.IO.StreamWriter file = new System.IO.StreamWriter(logFile, true);
                file.WriteLine();
                file.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
                file.Close();
            }
            finally
            {
                if (MyUsbDevice != null)
                {
                    if (MyUsbDevice.IsOpen)
                    {
                        IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                        if (!ReferenceEquals(wholeUsbDevice, null))
                        {
                            // Release interface #0.
                            wholeUsbDevice.ReleaseInterface(0);
                        }
                        MyUsbDevice.Close();
                    }
                    MyUsbDevice = null;
                    UsbDevice.Exit();
                }
            }
            // Signal the stopped event.
            this.stoppedEvent.Set();
        }
コード例 #7
0
ファイル: CM15.cs プロジェクト: florpan/HomeGenie
 public bool Open()
 {
     bool success = true;
     //
     try
     {
         // Find and open the usb device.
         myUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
         //
         // If the device is open and ready
         if (myUsbDevice == null) throw new Exception("X10 CM15Pro device not connected.");
         //
         // 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 = 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(0);
         }
         //
         // open read endpoint 1.
         reader = myUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
         // open write endpoint 2.
         writer = myUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep02);
         //
         this.WriteData(new byte[] { 0x8B }); // status request
     }
     catch
     {
         success = false;
         //throw new Exception("Error opening X10 CM15Pro device.");
     }
     return success;
 }
コード例 #8
0
ファイル: Teensy.cs プロジェクト: GotoHack/NANDORway
        private void OpenDevice()
        {
            if(_usbDevice != null && _usbDevice.IsOpen)
                return;

            // Find and open the usb device.
            _usbDevice = UsbDevice.OpenUsbDevice(_usbFinder);

            // If the device is open and ready
            Debug.Assert(_usbDevice != null, string.Format("No device with PID: {0:X4} & VID: {1:X4} Found!", _pid, _vid));

            // 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.
            var wholeUsbDevice = _usbDevice 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);
            }

            // open read endpoint 1.
            _epReader = _usbDevice.OpenEndpointReader((ReadEndpointID) EpIn);
            _epReader.Flush();

            // open write endpoint 1.
            _epWriter = _usbDevice.OpenEndpointWriter((WriteEndpointID) EpOut);
            LibMain.OnConnectedChanged(true);
        }
コード例 #9
0
ファイル: Battery.cs プロジェクト: patrikhl/battery-sync
        public Battery(UsbDevice usb = null)
        {
            usbDevice = usb;

            // 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 = usbDevice 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);
            }

            // open read endpoint 1
            UsbEndpointReader batInfoReader = usbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

            ErrorCode ec = ErrorCode.None;
            byte[] batInfoReadBuffer = new byte[64];
            int bytesRead = 0;

            // If the device hasn't sent data in the last 100 milliseconds,
            // a timeout error (ec = IoTimedOut) will occur.
            ec = batInfoReader.Read(batInfoReadBuffer, 100, out bytesRead);
            if (bytesRead == 0) throw new Exception("No more bytes!");

            // create BinaryReader and set source to readBuffer
            BatteryBinaryReader batInfoBReader = new BatteryBinaryReader(batInfoReadBuffer);

            // set battery variables using binary reader
            fwVersion = batInfoBReader.ReadByte() + ((float) batInfoBReader.ReadByte()) / 10;
            id = new string(batInfoBReader.ReadChars(6));
            name = new string(batInfoBReader.ReadChars(20));
            currentTime = batInfoBReader.ReadInt32();
            lastSyncTime = batInfoBReader.ReadInt32();
            capacity = batInfoBReader.ReadUInt16();
            lastFullCap = batInfoBReader.ReadUInt16();
            factoryCap = batInfoBReader.ReadUInt16();
            percentage = 100 * capacity / lastFullCap;
            int eepromPages = batInfoBReader.ReadUInt16();

            // get unix time
            int time = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            // check if battery time is correct
            if (currentTime != time || currentTime != time - 1)
            {
                // open write endpoint 1
                UsbEndpointWriter writer = usbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);

                // convert time to byte array
                byte[] timeArray = BitConverter.GetBytes(time);

                int bytesWritten = 0;

                // write time to endpoint 1
                ec = writer.Write(timeArray, 100, out bytesWritten);
            }

            UsbTransfer usbReadTransfer;
            UsbEndpointReader dataReader = usbDevice.OpenEndpointReader(ReadEndpointID.Ep02);
            int bytesToRead = 128 * eepromPages;
            byte[] dataReadBuffer = new byte[bytesToRead];

            // reset error code
            ec = ErrorCode.None;

            // read logged data using async bulk transfer
            ec = dataReader.SubmitAsyncTransfer(dataReadBuffer, 0, bytesToRead, 100, out usbReadTransfer);

            // dispose of the usb transfer
            usbReadTransfer.Dispose();

            // create a string array with the lines of text
            var dataReadString = System.Text.Encoding.Default.GetString(dataReadBuffer);

            // Set a variable to the My Documents path
            string docPath =
                Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            // write the string array to a new file named "DAS_battery.txt".
            using (StreamWriter outputFile = new StreamWriter(docPath + @"\DAS_battery.txt"))
            {
                outputFile.Write(dataReadString);
            }
        }
コード例 #10
0
        public void Thu()
        {
            ErrorCode        ec = ErrorCode.None;
            UsbRegDeviceList lu = LibUsbDotNet.UsbDevice.AllDevices;

            MyUsbFinder = new UsbDeviceFinder(1614, 33024);
            LibUsbDotNet.UsbDevice MyUsbDevice = null;
            try
            {
                // Find and open the usb device.
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
                //MyUsbDevice = lu[0].Device;
                // 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)
                // it will have an IUsbDevice interface. If not (WinUSB) the
                // variable will be null indicating this is an interface of a
                // device.

                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
                    wholeUsbDevice.SetConfiguration(1);

                    // Claim interface
                    wholeUsbDevice.ClaimInterface(1);
                }

                // open read endpoint
                UsbEndpointReader reader =
                    MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep02);

                // open write endpoint0123456789
                UsbEndpointWriter writer =
                    MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep03);

                // write data, read data
                int bytesWritten;
                //ec = writer.Write(new byte[] { 0x00, 0x03, 0x00, 0x00, 0x00,
                // 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 2000, out bytesWritten);

                //if (ec != ErrorCode.None)
                //    throw new Exception(UsbDevice.LastErrorString);
                ec = ErrorCode.None;

                byte[] readBuffer = new byte[1024];
                while (ec == ErrorCode.None)
                {
                    int bytesRead;

                    // If the device hasn't sent data in the last 100 milliseconds,
                    // a timeout error (ec = IoTimedOut) will occur.
                    ec = reader.Read(readBuffer, 100, out bytesRead);

                    if (bytesRead == 0)
                    {
                        throw new Exception("No more bytes!");
                    }

                    // Write that output to the console.
                    //  PrintHex(readBuffer, bytesRead);
                }

                //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
                            wholeUsbDevice.ReleaseInterface(1);
                        }

                        MyUsbDevice.Close();
                    }
                    MyUsbDevice = null;

                    // Free usb resources
                    UsbDevice.Exit();
                }
            }
        }
コード例 #11
0
        public static void Main(string[] args)
        {
            ErrorCode ec = ErrorCode.None;

            try
            {
                // Find and open the usb device.
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

                // 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(0);
                }

                // open read endpoint 1.
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

                // open write endpoint 1.
                UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);

                // Remove the exepath/startup filename text from the begining of the CommandLine.
                string cmdLine = Regex.Replace(
                    Environment.CommandLine, "^\".+?\"^.*? |^.*? ", "", RegexOptions.Singleline);

                if (!String.IsNullOrEmpty(cmdLine))
                {
                    reader.DataReceived += (OnRxEndPointData);
                    reader.DataReceivedEnabled = true;

                    int bytesWritten;
                    ec = writer.Write(Encoding.Default.GetBytes(cmdLine), 2000, out bytesWritten);
                    if (ec != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);

                    LastDataEventDate = DateTime.Now;
                    while ((DateTime.Now - LastDataEventDate).TotalMilliseconds < 100)
                    {
                    }

                    // Always disable and unhook event when done.
                    reader.DataReceivedEnabled = false;
                    reader.DataReceived -= (OnRxEndPointData);

                    Console.WriteLine("\r\nDone!\r\n");
                }
                else
                    throw new Exception("Nothing to do.");
            }
            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;

                // Free usb resources
                UsbDevice.Exit();

                // Wait for user input..
                Console.ReadKey();
            }
        }
コード例 #12
0
ファイル: Form1.cs プロジェクト: Tradition-junior/usb_monitor
        //
        //переделать всё
        //
        private void connect()
        {
            if (comboBox1.SelectedIndex != -1)
                MyUsbFinder = new UsbDeviceFinder(Convert.ToInt32(devices_libusb[comboBox1.SelectedIndex].VID, 16),
                    Convert.ToInt32(devices_libusb[comboBox1.SelectedIndex].PID, 16));
            DataPoint temp = new DataPoint();
            ErrorCode ec = ErrorCode.None;
            try
            {
                //открываем поток
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

                if (MyUsbDevice == null) throw new Exception("Device Not Found.");

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

                //читает 1ый эндпоинт
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader((ReadEndpointID)comboBox2.SelectedItem);

                byte[] readBuffer = new byte[1024];
                int bytesRead;

                //Возвращает данные или ошибку, если через 5 секунд ничего не было возвращено
                ec = reader.Read(readBuffer, 5000, out bytesRead);

                if (bytesRead == 0) throw new Exception(string.Format("{0}:No more bytes!", ec));
                try
                {
                    if (trying)
                    {
                        temp.SetValueXY(i,
                            Convert.ToDouble(Encoding.Default.GetString(readBuffer, 0, bytesRead).Replace('.', ',')));
                        i++;
                        chart1.Series[0].Points.Add(temp);
                        data.Add(Encoding.Default.GetString(readBuffer, 0, bytesRead));
                    }
                }
                catch
                {
                    trying = false;
                }
                textBox2.AppendText(Encoding.Default.GetString(readBuffer, 0, bytesRead));
            }
            catch (Exception ex)
            {
                //кидает ошибку и останавливает таймер при ошибке
                timer1.Stop();
                MessageBox.Show((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
            }
            finally
            {
                //закрывает поток
                if (MyUsbDevice != null)
                {
                    if (MyUsbDevice.IsOpen)
                    {
                        IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                        if (!ReferenceEquals(wholeUsbDevice, null))
                        {
                            wholeUsbDevice.ReleaseInterface(0);
                        }

                        MyUsbDevice.Close();
                    }
                    MyUsbDevice = null;
                    UsbDevice.Exit();
                }
            }
        }
コード例 #13
0
ファイル: Form1.cs プロジェクト: heath/USB-Gameboy-Dumper
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
                if (MyUsbDevice == null)
                {
                    throw new Exception("Device Not Found.");
                    //connected = false;
                }
                else
                {
                    Device_l.Text = "Device: Connected";
                    //connected = true;

                    Scan_b.Enabled = true;

                    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(0);
                    }

                    reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep03);
                    writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep04);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
            }
        }
コード例 #14
0
ファイル: fBenchmark.cs プロジェクト: CoreCompat/LibUsbDotNet
        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;
        }
コード例 #15
0
        private static bool Get_connect_PlanetCNC()
        {
            //vid 2121 pid 2130 в десятичной системе будет как 8481 и 8496 соответственно
            UsbDeviceFinder myUsbFinder = new UsbDeviceFinder(8481, 8496);

            // Попытаемся установить связь
            _myUsbDevice = UsbDevice.OpenUsbDevice(myUsbFinder);

            if (_myUsbDevice == null)
            {

                string StringError = "Не найден подключенный контроллер.";
                _connected = false;

                AddMessage(StringError);

                //запустим событие о разрыве связи
                if (WasDisconnected != null) WasDisconnected(null, new DeviceEventArgsMessage(StringError));

                return false;
            }

            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(0);
            }

            // open read endpoint 1.
            _usbReader = _myUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

            // open write endpoint 1.
            _usbWriter = _myUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);


            return true;
        }
コード例 #16
0
ファイル: iphone.cs プロジェクト: jakubl/jphonewin
	public iPhoneWrapper(UsbDevice USBDevice, bool bAFC2)
	{
		if (USBDevice == null)
			throw new Exception("Failed to create iPhone wrapper");

		StartTime = DateTime.UtcNow;

		iPhoneUSBDevice = USBDevice;
		MUXConnections = new List<USBMUXConnection>();

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

			// Select config #3
			LibUsbDevice.SetConfiguration(3);

			// Claim interface #1.
			LibUsbDevice.ClaimInterface(1);
		}

		// Open read endpoint 5.
		iPhoneEndpointReader = iPhoneUSBDevice.OpenEndpointReader(ReadEndpointID.Ep05);

		// Open write endpoint 4.
		iPhoneEndpointWriter = iPhoneUSBDevice.OpenEndpointWriter(WriteEndpointID.Ep04);

		// Say hello to the device and set up lockdown.
		if (!Initialize())
			throw new Exception("Couldn't initialize iPhone");

		// Try to start AFC2 if requested. If it doesn't work (not jailbroken), start AFC.
		int nAFCPort = 0;
		if (bAFC2)
		{
			try { nAFCPort = Lockdown.StartService("com.apple.afc2"); }
			catch
			{
				nAFCPort = Lockdown.StartService("com.apple.afc");
			}

			if (nAFCPort != 0)
			{
				AFC = new AFCConnection(this, 5, (ushort)nAFCPort);
				MUXConnections.Add(AFC);
			}
		}
		else
		{
			nAFCPort = Lockdown.StartService("com.apple.afc");
			AFC = new AFCConnection(this, 5, (ushort)nAFCPort);
			MUXConnections.Add(AFC);
		}

		int nNPPort = Lockdown.StartService("com.apple.mobile.notification_proxy");
		NP = new NotificationProxyConnection(this, 6, (ushort)nNPPort);
		MUXConnections.Add(NP);

		Global.Log("Shutting down lockdownd (don't need it anymore).\n");
		try { Lockdown.CloseConnection(); } catch { }
		MUXConnections.Remove(Lockdown);
	}
コード例 #17
0
        public static void Main(string[] args)
        {
            ErrorCode ec = ErrorCode.None;

            try
            {
                // Find and open the usb device.
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

                // 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)
                // it will have an IUsbDevice interface. If not (WinUSB) the
                // variable will be null indicating this is an interface of a
                // device.
                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(0);
                }

                // open read endpoint 1.
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

                // open write endpoint 1.
                UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);

                // Remove the exepath/startup filename text from the begining of the CommandLine.
                string cmdLine = Regex.Replace(
                    Environment.CommandLine, "^\".+?\"^.*? |^.*? ", "", RegexOptions.Singleline);

                if (!String.IsNullOrEmpty(cmdLine))
                {
                    int bytesWritten;
                    ec = writer.Write(Encoding.Default.GetBytes(cmdLine), 2000, out bytesWritten);
                    if (ec != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);

                    byte[] readBuffer = new byte[1024];
                    while (ec == ErrorCode.None)
                    {
                        int bytesRead;

                        // If the device hasn't sent data in the last 100 milliseconds,
                        // a timeout error (ec = IoTimedOut) will occur.
                        ec = reader.Read(readBuffer, 100, out bytesRead);

                        if (bytesRead == 0) throw new Exception("No more bytes!");

                        // Write that output to the console.
                        Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
                    }

                    Console.WriteLine("\r\nDone!\r\n");
                }
                else
                    throw new Exception("Nothing to do.");
            }
            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;

                    // Free usb resources
                    UsbDevice.Exit();

                }

                // Wait for user input..
                Console.ReadKey();
            }
        }
コード例 #18
0
ファイル: ReadWrite.cs プロジェクト: DOPS-CCI/CCI_project
        public static UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x0F44, 0xEF12); //Polhemus Patriot

        #endregion Fields

        #region Methods

        public static void Main(string[] args)
        {
            byte[] writeBuffer;
            byte[] readBuffer;
            ErrorCode ec = ErrorCode.None;

            try
            {
                // Find and open the usb device.
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

                // 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)
                // it will have an IUsbDevice interface. If not (WinUSB) the
                // variable will be null indicating this is an interface of a
                // device.
                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(0);
                }

                //Polhemus uses EndPoint 2 for both read and write
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep02);
                UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep02);

                while (true)
                {
                    Console.Write("New command: ");
                    string cmdLine = Console.ReadLine();
                    if (cmdLine == "") break;
                    if (cmdLine.Substring(0, 1) == "^") //control code
                    {
                        int ib = Encoding.ASCII.GetBytes(cmdLine.Substring(1, 1))[0];
                        writeBuffer = new byte[cmdLine.Length];
                        writeBuffer[0] = (byte)(ib & 0x1F); //calculate control code
                        if (cmdLine.Length > 2) //then there are arguments
                        {
                            byte[] arg = Encoding.ASCII.GetBytes(cmdLine.Substring(2)); //get arguments
                            for (int i = 0; i < arg.Length; i++) //and place in buffer
                                writeBuffer[i + 1] = arg[i];
                        }
                        writeBuffer[writeBuffer.Length - 1] = 0x0D; //CR
                    }
                    else //straight ASCII string command
                        writeBuffer = Encoding.ASCII.GetBytes(cmdLine +
                            ((cmdLine != "P") ? "\r" : ""));

                    int bytesWritten;
                    ec = writer.Write(writeBuffer, 1000, out bytesWritten);
                    if (ec != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);

                    readBuffer = new byte[1024];
                    while (ec == ErrorCode.None)
                    {
                        int bytesRead;

                        // If the device hasn't sent data in the last 100 milliseconds,
                        // a timeout error (ec = IoTimedOut) will occur.
                        ec = reader.Read(readBuffer, 100, out bytesRead);

                        if (bytesRead == 0) break;

                        // Write that output to the console.
                        Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
                        int byteCount = 1;
                        for (int i = 0; i < bytesRead; i++, byteCount++)
                        {
                            Console.Write(readBuffer[i].ToString("X2"));
                            if (byteCount >= 16)
                            {
                                byteCount = 0;
                                Console.Write(Environment.NewLine);
                            }
                            else
                                Console.Write(" ");
                        }
                        if (byteCount != 0) Console.Write(Environment.NewLine);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
                Console.Read();
            }
            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();

                }
            }
        }
コード例 #19
0
        public void Open()
        {
            _device = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(_vendorId, _productId));

              if (_device != null)
              {
            IUsbDevice whole = _device as IUsbDevice;

            if (!ReferenceEquals(whole, null))
            {
              whole.SetConfiguration(1);
              whole.ClaimInterface(1);
            }

            //Set up the endpoints
            var hci = _device.OpenEndpointReader(ReadEndpointID.Ep01);
            _reader = _device.OpenEndpointReader(ReadEndpointID.Ep02);
            _writer = _device.OpenEndpointWriter(WriteEndpointID.Ep02);
            _isoReader = _device.OpenEndpointReader(ReadEndpointID.Ep03);
            _isoWriter = _device.OpenEndpointWriter(WriteEndpointID.Ep03);

            //Set up our read callback(s)
            hci.DataReceived += hci_DataReceived;
            hci.DataReceivedEnabled = true;
            _reader.DataReceived += reader_DataReceived;
            _reader.DataReceivedEnabled = true;
            _isoReader.DataReceived += _isoReader_DataReceived;
            _isoReader.DataReceivedEnabled = true;

            //Reset the device
            Reset();
              }
        }
コード例 #20
0
		public LibUsb_AsyncUsbStream (string port)
		{
			var splited = port.Split ('-');
			var finder = new UsbDeviceFinder (int.Parse (splited [0]), int.Parse (splited [1]));
			device = UsbDevice.OpenUsbDevice (finder);
			if (device == null) {
				throw new Exception ("Failed to find device:" + port);
			}
			if (!device.IsOpen) {
				throw new Exception ("Device is not open:" + port);
			}

			var usbDevice = device as IUsbDevice;
			var interfaceInfo = device.Configs [0].InterfaceInfoList [0];

			if (usbDevice != null) {
				usbDevice.SetConfiguration (device.Configs [0].Descriptor.ConfigID);

				usbDevice.ClaimInterface (interfaceInfo.Descriptor.InterfaceID);
				deviceInterfaceId = interfaceInfo.Descriptor.InterfaceID;
			}

			foreach (var ep in interfaceInfo.EndpointInfoList) {
				if ((ep.Descriptor.EndpointID & 0x80) > 0) {
					reader = device.OpenEndpointReader ((ReadEndpointID)ep.Descriptor.EndpointID);
					reader.DataReceived += HandleDataReceived;
					reader.DataReceivedEnabled = true;
				} else {
					writer = device.OpenEndpointWriter ((WriteEndpointID)ep.Descriptor.EndpointID);
				}
			}
		}
コード例 #21
0
        public static void Main(string[] args)
        {
            ErrorCode ec = ErrorCode.None;
            try
            {
                // Find and open the usb device.
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

                // 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)
                // it will have an IUsbDevice interface. If not (WinUSB) the
                // variable will be null indicating this is an interface of a
                // device.
                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(0);
                }

                // open read endpoint 1.
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

                // open write endpoint 1.
                UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);

                // the write test data.
                string testWriteString = "ABCDEFGH";

                ErrorCode ecWrite;
                ErrorCode ecRead;
                int transferredOut;
                int transferredIn;
                UsbTransfer usbWriteTransfer;
                UsbTransfer usbReadTransfer;
                byte[] bytesToSend = Encoding.Default.GetBytes(testWriteString);
                byte[] readBuffer = new byte[1024];
                int testCount = 0;
                do
                {
                    // Create and submit transfer
                    ecRead = reader.SubmitAsyncTransfer(readBuffer, 0, readBuffer.Length, 100, out usbReadTransfer);
                    if (ecRead != ErrorCode.None) throw new Exception("Submit Async Read Failed.");

                    ecWrite = writer.SubmitAsyncTransfer(bytesToSend, 0, bytesToSend.Length, 100, out usbWriteTransfer);
                    if (ecWrite != ErrorCode.None)
                    {
                        usbReadTransfer.Dispose();
                        throw new Exception("Submit Async Write Failed.");
                    }

                    WaitHandle.WaitAll(new WaitHandle[] { usbWriteTransfer.AsyncWaitHandle, usbReadTransfer.AsyncWaitHandle },200,false);
                    if (!usbWriteTransfer.IsCompleted) usbWriteTransfer.Cancel();
                    if (!usbReadTransfer.IsCompleted) usbReadTransfer.Cancel();

                    ecWrite = usbWriteTransfer.Wait(out transferredOut);
                    ecRead = usbReadTransfer.Wait(out transferredIn);

                    usbWriteTransfer.Dispose();
                    usbReadTransfer.Dispose();

                    Console.WriteLine("Read  :{0} ErrorCode:{1}", transferredIn, ecRead);
                    Console.WriteLine("Write :{0} ErrorCode:{1}", transferredOut, ecWrite);
                    Console.WriteLine("Data  :" + Encoding.Default.GetString(readBuffer, 0, transferredIn));
                    testCount++;
                } while (testCount < 5);
                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;

                    // Free usb resources
                    UsbDevice.Exit();
                }

                // Wait for user input..
                Console.ReadKey();
            }
        }
コード例 #22
0
ファイル: ReadOnly.cs プロジェクト: CoreCompat/LibUsbDotNet
        public static void Main(string[] args)
        {
            ErrorCode ec = ErrorCode.None;

            try
            {
                // Find and open the usb device.
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

                // 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(0);
                }

                // open read endpoint 1.
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

                byte[] readBuffer = new byte[1024];
                while (ec == ErrorCode.None)
                {
                    int bytesRead;

                    // If the device hasn't sent data in the last 5 seconds,
                    // a timeout error (ec = IoTimedOut) will occur.
                    ec = reader.Read(readBuffer, 5000, out bytesRead);

                    if (bytesRead == 0) throw new Exception(string.Format("{0}:No more bytes!", ec));
                    Console.WriteLine("{0} bytes read", bytesRead);

                    // Write that output to the console.
                    Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
                }

                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;

                    // Free usb resources
                    UsbDevice.Exit();

                }

                // Wait for user input..
                Console.ReadKey();
            }
        }
コード例 #23
0
 private bool DeviceInit(int vendorID, int productID, bool deviceReset = true)
 {
     try {
         _vendorID = vendorID;
         _productID = productID;
         Device = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(vendorID, productID));
         if(Device == null) {
             Main.SendDebug(string.Format("No Device Found with VendorID: 0x{0:X04} and ProductID: 0x{1:X04}", vendorID, productID));
             Release();
             return false;
         }
         if(deviceReset) {
             Release();
             Thread.Sleep(1000);
             return DeviceInit(vendorID, productID, false);
         }
         DeviceConfigInfo = Device.Configs[0];
         var wholeUsbDevice = Device as IUsbDevice;
         if(!ReferenceEquals(wholeUsbDevice, null)) {
             wholeUsbDevice.SetConfiguration(DeviceConfigInfo.Descriptor.ConfigID);
             wholeUsbDevice.ClaimInterface(0);
         }
         _reader = Device.OpenEndpointReader((ReadEndpointID) 0x82);
         ClearReadBuffer();
         _writer = Device.OpenEndpointWriter((WriteEndpointID) 0x05);
         UsbDevice.UsbErrorEvent += UsbDeviceOnUsbErrorEvent;
         return true;
     }
     catch(Exception ex) {
         Main.SendDebug(String.Format("Device Init exception occured: {0}", ex.Message));
         throw;
     }
 }
コード例 #24
0
ファイル: Form1.cs プロジェクト: heath/USB-Gameboy-Dumper
        public void OnDeviceNotifyEvent(object sender, DeviceNotifyEventArgs e)
        {
            // A Device system-level event has occured

            //Console.SetCursorPosition(0, Console.CursorTop);
            //MessageBox.Show(e.Device.IdVendor.ToString());
            if (e.EventType == EventType.DeviceArrival && e.Device.IdVendor == 0x16C0 && e.Device.IdProduct == 0x05DD)
            {
                try
                {
                    MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
                    if (MyUsbDevice == null)
                    {
                        //throw new Exception("Device Not Found.");
                        connected = false;
                    }
                    else
                    {

                        Device_l.Text = "Device: Connected";
                        connected = true;

                        Scan_b.Enabled = true;

                        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(0);
                        }
                        //MessageBox.Show(ReadEndpointID.Ep04.ToString());
                        reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
                        writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);
                        mode = 4;
                        backgroundWorker1.RunWorkerAsync();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
                }
            }
            if (e.EventType == EventType.DeviceRemoveComplete && e.Device.IdVendor == 0x16C0 && e.Device.IdProduct == 0x05DD)
            {
                timer1.Enabled = false;
                connected = false;
                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();
                    Device_l.Text = "Device: Not Connected";
                    Scan_b.Enabled = false;
                    DumpRAM_b.Enabled = false;
                    DumpROM_b.Enabled = false;
                    WriteRAM_b.Enabled = false;
                    Banks_l.Text = "Banks: ";
                    MBC_l.Text = "MBC: ";
                    RAM_l.Text = "RAM Size: ";
                    Size_l.Text = "Size:";
                    Title_l.Text = "Title:";

                }
            }
               // Console.WriteLine(e.ToString()); // Dump the event info to output.

            //Console.WriteLine();
            //Console.Write("[Press any key to exit]");
        }
コード例 #25
0
        // USB connection and adapter management
        public override void Open()
        {
            this.Close();

            try
            {
                caLibUsbAdapter.write_lock.WaitOne();

                usb_finder = new UsbDeviceFinder(this.vid, this.pid);
                Debug.Assert(this.usb_finder != null);

                // open device
                usb_device = UsbDevice.OpenUsbDevice(usb_finder);
                if (usb_device == null)
                {
                    throw new Exception("No compatible adapters found");
                }

                wholeUsbDevice = usb_device as IUsbDevice;
                if (!ReferenceEquals (wholeUsbDevice, null)) {
                    wholeUsbDevice.SetConfiguration(1);
                    wholeUsbDevice.ClaimInterface(1);
                } else {
                    throw new Exception("Failed to claim interface");
                }

                // open endpoints
                ep_reader = usb_device.OpenEndpointReader(this.read_ep_id);
                ep_writer = usb_device.OpenEndpointWriter(this.write_ep_id);
                if(ep_reader == null || ep_writer == null)
                {
                    throw new Exception("Failed to open endpoints");
                }

                // clear garbage from input
                this.ep_reader.ReadFlush();

                // attach read event
                ep_reader.DataReceived += (read_usb);
                ep_reader.DataReceivedEnabled = true;

            } catch (Exception e) {
                this.Close();
                throw e;
            } finally {
                caLibUsbAdapter.write_lock.ReleaseMutex();
            }
        }
コード例 #26
0
ファイル: Form1.cs プロジェクト: heath/USB-Gameboy-Dumper
        public Form1()
        {
            InitializeComponent();
            // Hook the device notifier event
            UsbDeviceNotifier.OnDeviceNotify += OnDeviceNotifyEvent;

            usb_command = new byte[64];
            try
            {
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
                if (MyUsbDevice == null)
                {
                    //throw new Exception("Device Not Found.");
                    connected = false;
                }
                else
                {

                    Device_l.Text = "Device: Connected";
                    connected = true;

                    Scan_b.Enabled = true;

                    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(0);
                    }
                    //MessageBox.Show(ReadEndpointID.Ep04.ToString());
                    reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
                    writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);
                    mode = 4;
                    backgroundWorker1.RunWorkerAsync();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
            }
        }
コード例 #27
0
ファイル: Device.cs プロジェクト: mdrucken/gipsi
        protected void OnOpen()
        {
            UsbDeviceFinder f = new UsbDeviceFinder(2334, 3);
            _device = UsbDevice.OpenUsbDevice(f);
            if (_device == null)
                throw new Exception("Device not found");
            IUsbDevice id = _device as IUsbDevice;
            if (id == null)
                throw new Exception("This is not a full usb device");

            id.SetConfiguration(1);
            id.ClaimInterface(0);

            _irIN = _device.OpenEndpointReader(ReadEndpointID.Ep01);
            _bulkOUT = _device.OpenEndpointWriter(WriteEndpointID.Ep02);
            _bulkIN = _device.OpenEndpointReader(ReadEndpointID.Ep03);
        }