Contains methods for retrieving data from a EndpointType.Bulk or EndpointType.Interrupt endpoint using the overloaded Read(byte[],int,out int) functions or a DataReceived event.
Before using the DataReceived event, the DataReceivedEnabled property must be set to true. While the DataReceivedEnabled property is True, the overloaded Read(byte[],int,out int) functions cannot be used.
Inheritance: LibUsbDotNet.Main.UsbEndpointBase
        /// <summary>
        /// Open the connection
        /// </summary>
        /// <returns>whether the connection was opened successfully</returns>
        public async Task<bool> OpenAsync()
        {
            dev = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(0x10C4, 0xEAC9));
            if (dev == null)
            {
                dev = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(0x10C4, 0xEACA));
                if (dev == null)
                    return false;
            }

            IUsbDevice wholeUsbDevice = dev 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);
            }


            writer = dev.OpenEndpointWriter(WriteEndpointID.Ep01, EndpointType.Interrupt);
            reader = dev.OpenEndpointReader(ReadEndpointID.Ep01, 64, EndpointType.Interrupt);

            return true;
        }
Example #2
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;
        }
Example #3
0
        public void CloseDevice()
        {
            if(_usbDevice == null || !_usbDevice.IsOpen)
                return;
            if(_epReader != null) {
                _epReader.Dispose();
                _epReader = null;
            }
            if(_epWriter != null) {
                _epWriter.Abort();
                _epWriter.Dispose();
                _epWriter = null;
            }

            // 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))
                wholeUsbDevice.ReleaseInterface(0); // Release interface #0.

            _usbDevice.Close();
            _usbDevice = null;
        }
        public override void Close()
        {
            try {
                write_lock.WaitOne ();

                if (ep_reader != null) {
                    // detach read event
                    ep_reader.DataReceivedEnabled = false;
                    ep_reader.DataReceived -= (read_usb);
                }

                ep_reader = null;
                ep_writer = null;

                if (IsOpen ()) {
                    // close devices
                    usb_device.Close ();
                    wholeUsbDevice.ReleaseInterface (1);
                    wholeUsbDevice.Close ();
                }

                // release devices
                usb_device = null;
                wholeUsbDevice = null;
                UsbDevice.Exit();
            } catch (Exception) {
                // Ignore everything
            } finally {
                write_lock.ReleaseMutex();
            }
        }
Example #5
0
        private static void ReadData(object context)
        {
            UsbTransfer       overlappedTransferContext = (UsbTransfer)context;
            UsbEndpointReader reader = (UsbEndpointReader)overlappedTransferContext.EndpointBase;

            reader.mDataReceivedEnabled = true;
            EventHandler <DataReceivedEnabledChangedEventArgs> dataReceivedEnabledChangedEvent;

            dataReceivedEnabledChangedEvent = reader.DataReceivedEnabledChanged;
            if (!ReferenceEquals(dataReceivedEnabledChangedEvent, null))
            {
                dataReceivedEnabledChangedEvent(reader, new DataReceivedEnabledChangedEventArgs(reader.mDataReceivedEnabled));
            }

            overlappedTransferContext.Reset();

            byte[] buf = new byte[reader.mReadBufferSize];
            try
            {
                while (!overlappedTransferContext.IsCancelled)
                {
                    int       iTransferLength;
                    ErrorCode eReturn = reader.Transfer(buf, 0, buf.Length, Timeout.Infinite, out iTransferLength);
                    if (eReturn == ErrorCode.None)
                    {
                        EventHandler <EndpointDataEventArgs> temp = reader.DataReceived;
                        if (!ReferenceEquals(temp, null) && !overlappedTransferContext.IsCancelled)
                        {
                            temp(reader, new EndpointDataEventArgs(buf, iTransferLength));
                        }
                        continue;
                    }
                    if (eReturn != ErrorCode.IoTimedOut)
                    {
                        break;
                    }
                }
            }
#if !NETSTANDARD1_5 && !NETSTANDARD1_6
            catch (ThreadAbortException)
            {
                UsbError.Error(ErrorCode.ReceiveThreadTerminated, 0, "ReadData:Read thread aborted.", reader);
            }
#endif
            finally
            {
                reader.Abort();
                reader.mDataReceivedEnabled = false;

                dataReceivedEnabledChangedEvent = reader.DataReceivedEnabledChanged;
                if (!ReferenceEquals(dataReceivedEnabledChangedEvent, null))
                {
                    dataReceivedEnabledChangedEvent(reader, new DataReceivedEnabledChangedEventArgs(reader.mDataReceivedEnabled));
                }
            }
        }
Example #6
0
 public PTPDevice(UsbDevice dev)
 {
     _Device = dev;
     PTPSupported = false;
     _Name = dev.Info.ProductString; // TODO: try get better name
     Reader = null;
     Writer = null;
     ConfigurationID = 1;
     InterfaceID = 0;
     ReaderEndpointID = ReadEndpointID.Ep01;
     WriterEndpointID = WriteEndpointID.Ep02;
 }
Example #7
0
 public PTPDevice(UsbDevice dev)
 {
     this.Device = dev;
     this.PTPSupported = false;
     this._Name = dev.Info.ProductString; // TODO: try get better name
     this.Reader = null;
     this.Writer = null;
     this.ConfigurationID = 1;
     this.InterfaceID = 0;
     this.ReaderEndpointID = ReadEndpointID.Ep01;
     this.WriterEndpointID = WriteEndpointID.Ep02;
 }
Example #8
0
        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);
        }
Example #9
0
        /// <summary>
        /// Opens an endpoint for reading
        /// </summary>
        /// <param name="readEndpointID">Endpoint number for read operations.</param>
        /// <param name="readBufferSize">Size of the read buffer allocated for the <see cref="UsbEndpointReader.DataReceived"/> event.</param>
        /// <param name="endpointType">The type of endpoint to open.</param>
        /// <returns>A <see cref="UsbEndpointReader"/> class ready for reading. If the specified endpoint is already been opened, the original <see cref="UsbEndpointReader"/> class is returned.</returns>
        public virtual UsbEndpointReader OpenEndpointReader(ReadEndpointID readEndpointID, int readBufferSize, EndpointType endpointType)
        {
            foreach (UsbEndpointBase activeEndpoint in mActiveEndpoints)
            {
                if (activeEndpoint.EpNum == (byte)readEndpointID)
                {
                    return((UsbEndpointReader)activeEndpoint);
                }
            }

            UsbEndpointReader epNew = new UsbEndpointReader(this, readBufferSize, readEndpointID, endpointType);

            return((UsbEndpointReader)mActiveEndpoints.Add(epNew));
        }
Example #10
0
        /// <summary>
        /// Opens an endpoint for reading
        /// </summary>
        /// <param name="readEndpointID">Endpoint number for read operations.</param>
        /// <param name="readBufferSize">Size of the read buffer allocated for the <see cref="UsbEndpointReader.DataReceived"/> event.</param>
        /// <param name="endpointType">The type of endpoint to open.</param>
        /// <returns>A <see cref="UsbEndpointReader"/> class ready for reading. If the specified endpoint is already been opened, the original <see cref="UsbEndpointReader"/> class is returned.</returns>
        public virtual UsbEndpointReader OpenEndpointReader(ReadEndpointID readEndpointID, int readBufferSize, EndpointType endpointType)
        {
            foreach (UsbEndpointBase activeEndpoint in mActiveEndpoints)
            {
                if (activeEndpoint.EpNum == (byte)readEndpointID)
                {
                    return((UsbEndpointReader)activeEndpoint);
                }
            }

            byte altIntefaceID = mClaimedInterfaces.Count == 0 ? UsbAltInterfaceSettings[0] : UsbAltInterfaceSettings[mClaimedInterfaces[mClaimedInterfaces.Count - 1]];

            UsbEndpointReader epNew = new UsbEndpointReader(this, readBufferSize, altIntefaceID, readEndpointID, endpointType);

            return((UsbEndpointReader)mActiveEndpoints.Add(epNew));
        }
        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);
        }
Example #12
0
        public void closeDevice()
        {
            if (mUsbDevice != null)
            {
                if (mUsbDevice.IsOpen)
                {

                    if (mEpReader != null)
                    {
                        mEpReader.DataReceivedEnabled = false;
                        mEpReader.DataReceived -= mEp_DataReceived;
                        mEpReader.Dispose();
                        mEpReader = null;
                    }
                    if (mEpWriter != null)
                    {
                        mEpWriter.Abort();
                        mEpWriter.Dispose();
                        mEpWriter = null;
                    }

                    // 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))
                    {
                        // Release interface #0.
                        wholeUsbDevice.ReleaseInterface(0);
                    }
                    mUsbDevice.Close();
                    mUsbDevice = null;
                }

            }
        }
Example #13
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);
            }
        }
Example #14
0
	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);
	}
Example #15
0
	public void Shutdown(bool bUnexpected)
	{
		Global.Log("Shutting down iPhoneWrapper\n");

		// If device was unexpectedly removed (unplugged), don't try to send
		// goodbye packets.
		if (!bUnexpected)
		{
			foreach (USBMUXConnection C in MUXConnections)
			{
				try { C.CloseConnection(); }
				catch { }
			}
		}

		try
		{
			if (iPhoneUSBDevice != null)
			{
				if (iPhoneUSBDevice.UsbRegistryInfo.IsAlive)
				{
					IUsbDevice LibUsbDevice = iPhoneUSBDevice as IUsbDevice;
					if (!ReferenceEquals(LibUsbDevice, null))
					{
						// Release interface #1.
						LibUsbDevice.ReleaseInterface(1);
					}

					iPhoneUSBDevice.Close();
				}

				iPhoneUSBDevice = null;
				iPhoneEndpointReader = null;
				iPhoneEndpointWriter = null;
			}
		}
		catch { }
	}
        private bool openDevice(int index)
        {
            bool bRtn = false;

            closeDevice();
            chkRead.CheckedChanged -= chkRead_CheckedChanged;
            chkRead.Checked = false;
            cmdRead.Enabled = true;
            chkRead.CheckedChanged += chkRead_CheckedChanged;

            if (mRegDevices[index].Open(out mUsbDevice))
            {
                bRtn = true;

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

                if (bRtn)
                {
                    if (String.IsNullOrEmpty(comboBoxEndpoint.Text)) comboBoxEndpoint.SelectedIndex = 0;

                    byte epNum = byte.Parse(comboBoxEndpoint.Text);
                    mEpReader = mUsbDevice.OpenEndpointReader((ReadEndpointID)(epNum | 0x80));
                    mEpWriter = mUsbDevice.OpenEndpointWriter((WriteEndpointID)epNum);
                    mEpReader.DataReceived += mEp_DataReceived;
                    mEpReader.Flush();
                    panTransfer.Enabled = true;
                }
            }

            if (bRtn)
            {
                tsStatus.Text = "Device Opened.";
            }
            else
            {
                tsStatus.Text = "Device Failed to Opened!";
                if (!ReferenceEquals(mUsbDevice, null))
                {
                    if (mUsbDevice.IsOpen) mUsbDevice.Close();
                    mUsbDevice = null;
                }
            }

            return bRtn;
        }
Example #17
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);
				}
			}
		}
        /// <summary>
        /// Opens an endpoint for reading
        /// </summary>
        /// <param name="readEndpointID">Endpoint number for read operations.</param>
        /// <param name="readBufferSize">Size of the read buffer allocated for the <see cref="UsbEndpointReader.DataReceived"/> event.</param>
        /// <param name="endpointType">The type of endpoint to open.</param>
        /// <returns>A <see cref="UsbEndpointReader"/> class ready for reading. If the specified endpoint is already been opened, the original <see cref="UsbEndpointReader"/> class is returned.</returns>
        public virtual UsbEndpointReader OpenEndpointReader(ReadEndpointID readEndpointID, int readBufferSize, EndpointType endpointType)
        {
            foreach (UsbEndpointBase activeEndpoint in mActiveEndpoints)
                if (activeEndpoint.EpNum == (byte) readEndpointID) 
                    return (UsbEndpointReader) activeEndpoint;

            UsbEndpointReader epNew = new UsbEndpointReader(this, readBufferSize, readEndpointID, endpointType);
            return (UsbEndpointReader) mActiveEndpoints.Add(epNew);
        }
Example #19
0
        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);
            }
        }
Example #20
0
        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]");
        }
Example #21
0
        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);
        }
Example #22
0
 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;
 }
Example #23
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;
        }
        public bool Reset()
        {
            bool ret = true;

              Close();

              //Start message thread
              _messageThread = new Thread(new ThreadStart(_SendMessages));
              _messageThread.IsBackground = true;
              _messageThread.Start();

              //Find device
              _device = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(_VENDOR_ID, _PRODUCT_ID)) as IUsbDevice;

              if (_device != null)
              {
            //Set up the incoming and outgoing endpoints

            _reader = _device.OpenEndpointReader(LibUsbDotNet.Main.ReadEndpointID.Ep03);
            _reader.DataReceived += _reader_DataReceived;
            _reader.DataReceivedEnabled = true;

            lock (_writerLock)
            {
              _writer = _device.OpenEndpointWriter(LibUsbDotNet.Main.WriteEndpointID.Ep02);
            }
              }
              else
            ret = false;

              return ret;
        }
Example #25
0
        private bool openDevice(int index)
        {
            bool bRtn = false;

            closeDevice();

            if (mRegDevices[index].Open(out mUsbDevice))
            {
                bRtn = true;

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

                if (bRtn)
                {
                    byte epNum = endpoint;
                    mEpReader = mUsbDevice.OpenEndpointReader((ReadEndpointID)(epNum | 0x80), 64);
                    mEpWriter = mUsbDevice.OpenEndpointWriter((WriteEndpointID)epNum);
                    mEpReader.DataReceived += mEp_DataReceived;
                    mEpReader.ReadBufferSize = 64;
                    mEpReader.ReadThreadPriority = ThreadPriority.AboveNormal;
                    mEpReader.Flush();
                }
            }

            if (bRtn)
            {
                tsStatus.Text = "Device Opened.";
            }
            else
            {
                tsStatus.Text = "Device Failed to Opened!";
                if (!ReferenceEquals(mUsbDevice, null))
                {
                    if (mUsbDevice.IsOpen) mUsbDevice.Close();
                    mUsbDevice = null;
                }
            }

            return bRtn;
        }
        internal void Disconnect()
        {
            if (!isOpen) return; // already disconnected

            isOpen = false;
            pinListenerTask.Wait(); // wait for the task to return
            try
            {
                if (pinConfig != null)
                {
                    pinConfig.Abort();
                    pinConfig.Dispose();
                    pinConfig = null;
                }
                if (pinState != null)
                {
                    pinState.Dispose();
                    pinState = null;
                }
                if (peripheralConfig != null)
                {
                    peripheralConfig.Abort();
                    peripheralConfig.Dispose();
                    peripheralConfig = null;
                }
                if (peripheralReceive != null)
                {
                    peripheralReceive.Dispose();
                    peripheralReceive = null;
                }
            }
            catch (Exception e)
            {

            }

            if (device != null)
            {
                if (device.IsOpen)
                {
                    IUsbDevice wholeUsbDevice = device as IUsbDevice;
                    if (!ReferenceEquals(wholeUsbDevice, null))
                    {
                        wholeUsbDevice.ReleaseInterface(0);
                    }
                    device.Close();
                }
            }
        }
Example #27
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();
              }
        }
Example #28
0
        public bool Open()
        {
            if (IsOpen)
                return false;

            if (!_Device.Open())
                return false;

            IUsbDevice whole = _Device as IUsbDevice;
            if (!ReferenceEquals(whole, null))
            {
                if (!whole.SetConfiguration(ConfigurationID) || !whole.ClaimInterface(InterfaceID))
                {
                    _Device.Close();
                    throw new PTPException("could not set USB device configuration and interface to " + ConfigurationID + " and " + InterfaceID + ", respectively");
                }
            }

            Writer = _Device.OpenEndpointWriter(WriterEndpointID);
            Reader = _Device.OpenEndpointReader(ReaderEndpointID);

            return true;
        }
        public async Task<bool> OpenAsync()
        {
            if (isOpen)
                return true;

            if (device.Open())
            {
                // 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 = device as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    // This is a "whole" USB device. Before it can be used, 
                    // the desired configuration and interface must be selected.

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

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

                pinConfig = device.OpenEndpointWriter(WriteEndpointID.Ep01);
                pinState = device.OpenEndpointReader(ReadEndpointID.Ep01);
                peripheralConfig = device.OpenEndpointWriter(WriteEndpointID.Ep02);
                peripheralReceive = device.OpenEndpointReader(ReadEndpointID.Ep02);

                isOpen = true;

                pinListenerTask = new Task(() =>
                {
                    while (isOpen)
                    {
                        byte[] buffer = new byte[41];
                        int len = 0;
                        try
                        {
                            ErrorCode error;
                            error = pinState.Read(buffer, 100, out len);

                            if (error == ErrorCode.Success)
                                PinEventDataReceived?.Invoke(buffer);
                            else
                                if(error != ErrorCode.IoTimedOut)
                                    Debug.WriteLine("Pin Data Read Failure: " + error);
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("Exception: " + ex.Message);
                        }

                        if (updateDelay > 1) Task.Delay(updateDelay).Wait();
                    }

                });

                pinListenerTask.Start();

                return true;

            } else
            {
                return false;
            }
        }
Example #30
0
        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);
            }
        }
        /// <summary>
        /// Opens an endpoint for reading
        /// </summary>
        /// <param name="readEndpointID">Endpoint number for read operations.</param>
        /// <param name="readBufferSize">Size of the read buffer allocated for the <see cref="UsbEndpointReader.DataReceived"/> event.</param>
        /// <param name="endpointType">The type of endpoint to open.</param>
        /// <returns>A <see cref="UsbEndpointReader"/> class ready for reading. If the specified endpoint is already been opened, the original <see cref="UsbEndpointReader"/> class is returned.</returns>
        public virtual UsbEndpointReader OpenEndpointReader(ReadEndpointID readEndpointID, int readBufferSize, EndpointType endpointType)
        {
            foreach (UsbEndpointBase activeEndpoint in mActiveEndpoints)
                if (activeEndpoint.EpNum == (byte) readEndpointID)
                    return (UsbEndpointReader) activeEndpoint;

            byte altIntefaceID = mClaimedInterfaces.Count == 0 ? UsbAltInterfaceSettings[0] : UsbAltInterfaceSettings[mClaimedInterfaces[mClaimedInterfaces.Count - 1]];

            UsbEndpointReader epNew = new UsbEndpointReader(this, readBufferSize, altIntefaceID, readEndpointID, endpointType);
            return (UsbEndpointReader) mActiveEndpoints.Add(epNew);
        }
Example #32
0
        public void StartAcquisition()
        {
            if (usbDeviceReg.Open(out usbDevice))
            {
                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);
                }

                byte epNum = byte.Parse("1");
                usbReader = usbDevice.OpenEndpointReader((ReadEndpointID)(epNum | 0x80));
                usbReader.DataReceived += USB_DataReceived;
                usbReader.Flush();
                usbReader.DataReceivedEnabled = true;
            }
            else
            {
                MessageBox.Show("Failed to open USB device.", "USB Connection Error", MessageBoxButtons.OK);
            }
        }
Example #33
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();
            }
        }