예제 #1
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);
            }
        }
예제 #2
0
        /// <summary>
        /// Function to send "CountOfBytes" data bytes from the "BufferOffset" offset of transmitting buffer value to USB HID device by Report ID in Endpoint 1 from the 0 offset
        /// </summary>
        /// <param name="ReportID_OUT">Output Report ID value</param>
        /// <param name="CountOfBytes">Count of transmitting bytes</param>
        /// <param name="BufferOffset">Start transmitting buffer index</param>
        public void SendData(Int32 ReportID_OUT, int CountOfBytes, int BufferOffset)
        {
            // send CountOfBytes bytes of data to USB HID device by Report ID
            // in Endpoint 1 from the BufferOffset offset
            try
            {
                var ReportID = ReportID_OUT;

                if (MyUsbDevice != null)
                {
                    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 write endpoint 1.
                    UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01, LibUsbDotNet.Main.EndpointType.Interrupt);

                    USBwriteBuffer[0] = Convert.ToByte(ReportID_OUT);
                    //ec = writer.Write(USBwriteBuffer, 2000, out bytesWritten); this function worked ok
                    ec = writer.Write(USBwriteBuffer, BufferOffset, CountOfBytes, 2000, out CountOfSentBytes); //byte[] buffer, int offset, int count, int timeout, out int transferLength

                    if (ec != ErrorCode.None)
                    {
                        throw new Exception(UsbDevice.LastErrorString);
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "SendData function error: " + "Error: " + (ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message;
            }
        }
예제 #3
0
        /// <summary>
        /// Initializes the device via LibUSB, and sets the refresh interval of the controller data
        /// </summary>
        /// <param name="Interval">The interval that the device is polled for information.</param>
        public void Init(int Interval)
        {
            //ErrorCode ec = ErrorCode.None;

            // Find and open the usb device.
            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);
            }

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

            int readByteCount = 0;

            byte[] buf = new byte[64];
            reader.Read(buf, 0, 64, 1000, out readByteCount);


            ButtonMasks.InitializeMasks();

            SetPollingInterval(Interval);
            pollTimer.Elapsed += new ElapsedEventHandler(pollTimer_Elapsed);
            pollTimer.Start();

            TestLEDs();
            if (updateGearLights)
            {
                GearLightsRefresh((int)unchecked ((sbyte)buf[25]));
            }
            RefreshLEDState();
        }
        private void configureDevice()
        {
            device = UsbDevice.OpenUsbDevice(usbFinder);

            if (device == null)
            {
                throw new InvalidOperationException("Could not find the barcode scanner.");
            }

            IUsbDevice wholeUsbDevice = device as IUsbDevice;

            if (!ReferenceEquals(wholeUsbDevice, null))
            {
                wholeUsbDevice.SetConfiguration(1);

                wholeUsbDevice.ClaimInterface(interfaceId);
            }


            reader = device.OpenEndpointReader(ReadEndpointID.Ep01);
        }
예제 #5
0
        private void InitUSB()
        {
            // the code below is based on the example code provided on the LibUsbDotNet website

            MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

            if (MyUsbDevice == null)
            {
                throw new Exception("Device Not Found.");
            }
            else
            {
                toolStripStatusLabel1.Text = "Device 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.
            reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

            reader.DataReceived       += (OnRxEndPointData);
            reader.DataReceivedEnabled = true;
        }
예제 #6
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);
            }
        }
예제 #7
0
        public static void OpenDevice(Int32 vid, Int32 pid)
        {
            if (usbDevice != null)
            {
                Program.ShowError("A device is already openned, please close it first.");
            }

            Logger.Log("Connecting to device vid." + vid + " pid." + pid);
            UsbDeviceFinder usbFinder = new UsbDeviceFinder(vid, pid);

            // Find and open the usb device.
            usbDevice = UsbDevice.OpenUsbDevice(usbFinder);

            // If the device is open and ready
            if (usbDevice == 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 = 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);
            }
        }
예제 #8
0
 private void openToolStripMenuItem_Click(object sender, EventArgs e)
 {
     try
     {
         if (vidbox.Text.Length == 0 || pidbox.Text.Length == 0)
         {
             Clear();
             Print("vid or pid error. Try open again");
             return;
         }
         vid = vidbox.Text;
         pid = pidbox.Text;
         // Find and open the usb device.
         MyUsbDevice = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(Convert.ToInt32(vid, 16), Convert.ToInt32(pid, 16)));
         if (MyUsbDevice == null)
         {
             Clear();
             Print("Connect usb device and install driver. Try open again");
             //lisbusbdriver();
             // libusbinf();
             return;
         }
         IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
         if (!ReferenceEquals(wholeUsbDevice, null))
         {
             wholeUsbDevice.SetConfiguration(1);
             wholeUsbDevice.ClaimInterface(0);
         }
         Clear();
         Print("Device OK");
         Print("vid: 0x" + vid);
         Print("pid: 0x" + pid);
     }
     catch (Exception ex)
     {
         Print(ex.ToString());
     }
 }
예제 #9
0
파일: MainForm.cs 프로젝트: mo10/PigeonUI
        /// <summary>
        /// 打开USB设备
        /// </summary>
        /// <param name="usb"></param>
        private void OpenDevice()
        {
            if (inUsingDevice != null)
            {
                return;
            }
            // Open Device
            inUsingDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
            if (inUsingDevice != null)
            {
                IUsbDevice wholeUsbDevice = inUsingDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    // Select config #1
                    wholeUsbDevice.SetConfiguration(1);
                    // Claim interface #0.
                    wholeUsbDevice.ClaimInterface(0);
                }
                EndpointWriter = inUsingDevice.OpenEndpointWriter(WriteEndpointID.Ep02);
                EndpointReader = inUsingDevice.OpenEndpointReader(ReadEndpointID.Ep02);

                EndpointReader.DataReceived       += (OnRxEndPointData);
                EndpointReader.DataReceivedEnabled = true;
                // Update controls
                lb_status.Text      = "已连接";
                lb_status.ForeColor = Color.Green;

                Pigeon_Comm_Data data = new Pigeon_Comm_Data();
                data.Head = 0x66;
                data.Cmd  = Pigeon_Comm_Cmd.READ_SETTINGS;
                data.Len  = 0;
                //
                byte[] vs = Data.ToBytes(data);
                // Send to device
                int bytesWritten;
                EndpointWriter.Write(vs, 1000, out bytesWritten);
            }
        }
예제 #10
0
        public void Open()
        {
            if (!Driver.IsOpen)
            {
                Driver.Open();
                IUsbDevice wholeUsbDevice = Driver as IUsbDevice;
                if (wholeUsbDevice is not null)
                {
                    wholeUsbDevice.Open();
                    wholeUsbDevice.SetConfiguration(1);
                    wholeUsbDevice.ClaimInterface(0);
                }
                //Get the first config number of the interface
                Driver.ClaimInterface(Driver.Configs[0].Interfaces[0].Number);
                EndpointWriter = Driver.OpenEndpointWriter(WriteEndpointID.Ep01);
                EndpointReader = Driver.OpenEndpointReader(ReadEndpointID.Ep01);

                DeviceInfo.Manufacturer = Driver.Info.Manufacturer;
                DeviceInfo.Product      = Driver.Info.Product;
                DeviceInfo.SerialNumber = Driver.Info.SerialNumber;
            }
            DeviceInfo.Ready = Driver.IsOpen;
        }
예제 #11
0
        private void USBDeviceInit()
        {
            // 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))
            {
                // 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);
        }
예제 #12
0
 public UsbEndpointWriter getWriter()
 {
     if (writer == null)
     {
         if (MyUsbDevice == null)
         {
             //throw new Exception("Device Not Found");
             MessageBox.Show("未连接上打印机");
         }
         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);
         }
         writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep03);
     }
     return(writer);
 }
예제 #13
0
        /// <summary>
        /// Search for and open all Helios Laser DACs connected to the computer.
        /// </summary>
        /// <returns>The number of DACs found.</returns>
        public int OpenDevices()
        {
            CloseDevices();

            foreach (UsbRegistry usbRegistry in UsbDevice.AllDevices)
            {
                if (usbRegistry.Pid == HELIOS_PID && usbRegistry.Vid == HELIOS_VID)
                {
                    if (usbRegistry.Open(out UsbDevice dac))
                    {
                        IUsbDevice libUsbDevice = dac as IUsbDevice;
                        if (libUsbDevice != null)
                        {
                            libUsbDevice.ClaimInterface(0);
                            libUsbDevice.SetAltInterface(1);
                        }
                        dacs.Add(new HeliosDevice(dac));
                    }
                }
            }

            return(dacs.Count);
        }
예제 #14
0
파일: dfu.cs 프로젝트: glocklueng/NXP_DFU
   public bool claimIface()
   {
     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.
         wholeUsbDevice.SetConfiguration(DFUconfig);
         wholeUsbDevice.ClaimInterface(DFUinterface);
       }
     //Now we need to get  wTransferSize and we get that
     //from a byte array returned by CustomDescriptors
     foreach (byte[] aCustomDesc in myDFUiface.CustomDescriptors)
       {
         if (aCustomDesc[1] == 33) //DFU Interface desc
           {
             //USB Bus format is LITTLE ENDIAN
             wTransferSize = ((aCustomDesc[6]*256) + aCustomDesc[5]);
             if (wTransferSize < myUSBDevice.Info.Descriptor.MaxPacketSize0) wTransferSize=myUSBDevice.Info.Descriptor.MaxPacketSize0;
           }
       }
     return(true);
 }
예제 #15
0
        /// <summary>
        /// Try to connect to the device
        /// </summary>
        /// <returns>1 for success, 0 for fail</returns>
        public int connect()
        {
            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);
                }

                return(1); // Device found!
            }
            catch
            {
                return(0); // Failed to find one.
            }
        }
예제 #16
0
 internal bool reopenPort()
 {
     lock (lock_access)
     {
         ClosePort();
         scanDevice();
         UsbRegistry usb_reg;
         if (devicesDIC.TryGetValue(last_device_name, out usb_reg) == false)
         {
             return(false);
         }
         selected_device = usb_reg.Device;
         if (!(selected_device.Open()))
         {
             throw new DriveNotFoundException(string.Format("open USB (port)device {0} fail", Selected_device_name));
         }
         IUsbDevice wholeUsbDevice = selected_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);
         }
         else
         {
             throw new DriveNotFoundException(string.Format("selected_device can not as IUsbDevice"));
         }
         srb_reader = selected_device.OpenEndpointReader((ReadEndpointID)(1 | 0x80), 1000, EndpointType.Interrupt);
         srb_writer = selected_device.OpenEndpointWriter((WriteEndpointID)2);
         // srb_reader.DataReceived += mEp_DataReceived;
         srb_reader.Flush();
         return(true);
     }
 }
예제 #17
0
 private bool reconnect()
 {
     //clear the info so far
     if (MyUsbDevice != null)
     {
         writer.Dispose();
         wholeUsbDevice.ReleaseInterface(0);
         wholeUsbDevice.Close();
         MyUsbDevice.Close();
         UsbDevice.Exit();
     }
     //now start over
     MyUsbFinder = new UsbDeviceFinder(0x06D3, 0x01D0);
     MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
     // If the device is open and ready
     if (MyUsbDevice == null)
     {
         msgchnl.setcurrMessage("Problem in reconnect() MyUsbDevice is null");
         return(false);
     }
     else
     {
         wholeUsbDevice = MyUsbDevice as IUsbDevice;
         if (!ReferenceEquals(wholeUsbDevice, null))
         {
             // Select config #1
             wholeUsbDevice.SetConfiguration(1);
             // Claim interface #0.
             wholeUsbDevice.ClaimInterface(0);
         }
         writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep02);
         reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
         //Console.WriteLine("New Writer an reader was assigned");
         return(true);
     }
 }
예제 #18
0
        //--------------------------------------------------------------------------------------------------------
        public static Boolean Open()
        {
            UsbDeviceFinder PCBRulerIIFinder = new UsbDeviceFinder(DEV_VID, DEV_PID);

            USBDev = UsbDevice.OpenUsbDevice(PCBRulerIIFinder);

            if (USBDev == null)
            {
                return(false);
            }

            IUsbDevice wholeUsbDevice = USBDev as IUsbDevice;

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

            USBDevReader = USBDev.OpenEndpointReader(ReadEndpointID.Ep01);
            USBDevWriter = USBDev.OpenEndpointWriter(WriteEndpointID.Ep01);

            return(true);
        }
예제 #19
0
        public override bool InitializeCommu()
        {
            m_USBParam.InitUsbParam();
            m_UsbFinder = new UsbDeviceFinder(m_USBParam.Vid, m_USBParam.Pid);
            m_UsbDevice = UsbDevice.OpenUsbDevice(m_UsbFinder);
            if (m_UsbDevice == null)
            {
                return(false);
            }

            #region  // 当设备是一个 "whole" 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 = m_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);
            }
            #endregion

            m_UsbReader = m_UsbDevice.OpenEndpointReader(ReadEndpointID.Ep02);
            m_UsbReader.ReadBufferSize = nReadBufSize;

            m_UsbWriter = m_UsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);

            return(true);
        }
예제 #20
0
        public static UsbLibDotNetHIDDevice FindDevice(int vendorID, int productID, byte configID = 1, byte interfaceID = 0)
        {
            UsbLibDotNetHIDDevice newDev    = null;
            UsbDeviceFinder       usbFinder = new UsbDeviceFinder(vendorID, productID);
            UsbDevice             usbDev    = null;
            //Byte configID = 255;
            bool endpointsFound = false;

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

                // If the device is open and ready
                if (usbDev == null)
                {
                    Console.WriteLine("Device Not Found [0x" + vendorID.ToString("x4") + ":0x" + productID.ToString("x4") + "].");
                    return(null);
                }

                newDev = new UsbLibDotNetHIDDevice();

                for (int iConfig = 0; iConfig < usbDev.Configs.Count; iConfig++)
                {
                    UsbConfigInfo configInfo = usbDev.Configs[iConfig];

                    if (configID == configInfo.Descriptor.ConfigID)
                    {
                        ReadOnlyCollection <UsbInterfaceInfo> interfaceList = configInfo.InterfaceInfoList;

                        //Console.WriteLine("Config Found: " + configInfo.Descriptor.ConfigID.ToString());
                        for (int iInterface = 0; iInterface < interfaceList.Count; iInterface++)
                        {
                            UsbInterfaceInfo interfaceInfo = interfaceList[iInterface];

                            if (interfaceID == interfaceInfo.Descriptor.InterfaceID)
                            {
                                //Console.WriteLine("Interface Found: " + interfaceInfo.Descriptor.EndpointCount.ToString());
                                // We need 2 Endpoints
                                if (interfaceInfo.Descriptor.EndpointCount == 2)
                                {
                                    ReadOnlyCollection <UsbEndpointInfo> endpointList = interfaceInfo.EndpointInfoList;

                                    //Console.WriteLine("Two Endpoints Found");
                                    for (int iEndpoint = 0; iEndpoint < endpointList.Count; iEndpoint++)
                                    {
                                        if (iEndpoint == 0)
                                        {
                                            newDev.m_readEndpoint = (ReadEndpointID)endpointList[iEndpoint].Descriptor.EndpointID;
                                        }
                                        else
                                        {
                                            newDev.m_writeEndpoint = (WriteEndpointID)endpointList[iEndpoint].Descriptor.EndpointID;
                                        }

                                        newDev.m_configID    = configInfo.Descriptor.ConfigID;
                                        newDev.m_interfaceID = interfaceInfo.Descriptor.InterfaceID;
                                    }

                                    endpointsFound = true;
                                }
                            }
                        }
                    }
                }

                if (String.Compare(System.Environment.GetEnvironmentVariable("USBLIBDOTNET_VERBOSE"), "yes", true) == 0)
                {
                    Console.WriteLine("*** GD77 USB Device Infos:\n  - " + usbDev.Info.ToString().Replace("\n", "\n  - "));
                    for (int iConfig = 0; iConfig < usbDev.Configs.Count; iConfig++)
                    {
                        UsbConfigInfo configInfo = usbDev.Configs[iConfig];

                        Console.WriteLine("   *** ConfigID: " + configInfo.Descriptor.ConfigID);
                        Console.WriteLine("   CONFIGURATION INFO: \n     - " + configInfo.ToString().Replace("\n", "\n        - "));

                        ReadOnlyCollection <UsbInterfaceInfo> interfaceList = configInfo.InterfaceInfoList;
                        for (int iInterface = 0; iInterface < interfaceList.Count; iInterface++)
                        {
                            UsbInterfaceInfo interfaceInfo = interfaceList[iInterface];
                            Console.WriteLine("         *** InterfaceID: " + interfaceInfo.Descriptor.InterfaceID);
                            Console.WriteLine("         INTERFACE INFO: \n        - " + interfaceInfo.ToString().Replace("\n", "\n        - "));

                            ReadOnlyCollection <UsbEndpointInfo> endpointList = interfaceInfo.EndpointInfoList;
                            for (int iEndpoint = 0; iEndpoint < endpointList.Count; iEndpoint++)
                            {
                                Console.WriteLine("            ENDPOINT LIST: \n           - " + endpointList[iEndpoint].ToString().Replace("\n", "\n           - "));
                            }
                        }
                    }
                    Console.WriteLine("***\n");
                }
                if (endpointsFound == false)
                {
                    Console.WriteLine("Couldn't find 2 endpoints for interface #" + interfaceID.ToString() + " of configuration #" + configID.ToString());
                    return(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 = usbDev as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
#if DUMP_USB_INFOS
                    Console.WriteLine("*** ConfigID: " + newDev.m_configID);
                    Console.WriteLine("*** InterfaceID: " + newDev.m_interfaceID);
#endif
                    // This is a "whole" USB device. Before it can be used,
                    // the desired configuration and interface must be selected.

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

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

                // open read endpoint 1.
                newDev.m_usbReader = usbDev.OpenEndpointReader(newDev.m_readEndpoint);
                newDev.m_usbReader.ReadThreadPriority = ThreadPriority.AboveNormal;

                // open write endpoint 2
                newDev.m_usbWriter = usbDev.OpenEndpointWriter(newDev.m_writeEndpoint);
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: " + ex.Message);
                return(null);
            }

            newDev.m_usbDevice = usbDev;
            newDev.m_vendorID  = vendorID;
            newDev.m_productID = productID;

            return(newDev);
        }
예제 #21
0
        public void Start()
        {
            lock (_lock)
            {
                UsbRegDeviceList allLibUsbDevices = UsbDevice.AllLibUsbDevices;
                if (allLibUsbDevices.Count > 0)
                {
                    UsbDevice dev;
                    IsOpen = ((LibUsbRegistry)allLibUsbDevices.First()).Open(out dev);
                    _device = dev as IUsbDevice;
                    // Select config
                    bool configuration = _device.SetConfiguration(1);

                    // Claim interface
                    bool claimInterface = _device.ClaimInterface(0);
                    /*bool found = false;
                byte readerId = (byte) ReadEndpointID.Ep01;
                while (!found && (byte)readerId <= (byte)ReadEndpointID.Ep15)
                {
                    _reader = _device.OpenEndpointReader((ReadEndpointID)readerId);
                    byte[] buffer = new byte[1024];
                    int length;
                    ErrorCode ret = _reader.Read(buffer, 100, out length);
                    found = (ret != ErrorCode.Win32Error);
                    readerId++;
                }*/
                    EndPointId = GetEndpoint();
                    _reader = _device.OpenEndpointReader(EndPointId);
                    _thread.Start();
                    //_reader.DataReceivedEnabled = true;
                    //_reader.ReadBufferSize = 8;
                    //_reader.DataReceived += OnReaderDataReceived;
                }
            }
        }
예제 #22
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);
            }
        }
예제 #23
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]");
        }
예제 #24
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();
            }
        }
예제 #25
0
        /// <summary>
        /// Open the TreehopperBoard. The board must be opened before any other methods are called.
        /// </summary>
        public void Open()
        {
            if (usb.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 = usb 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);
                }

                pinStateBuffer = new byte[64];

                Pins = new List <Pin>();

                // Initialize Pins
                pin1  = new Pin1(this);
                pin2  = new Pin2(this);
                pin3  = new Pin3(this);
                pin4  = new Pin4(this);
                pin5  = new Pin5(this);
                pin6  = new Pin6(this);
                pin7  = new Pin7(this);
                pin8  = new Pin8(this);
                pin9  = new Pin9(this);
                pin10 = new Pin10(this);
                pin11 = new Pin11(this);
                pin12 = new Pin12(this);
                pin13 = new Pin13(this);
                pin14 = new Pin14(this);

                Pins.Add(pin1);
                Pins.Add(pin2);
                Pins.Add(pin3);
                Pins.Add(pin4);
                Pins.Add(pin5);
                Pins.Add(pin6);
                Pins.Add(pin7);
                Pins.Add(pin8);
                Pins.Add(pin9);
                Pins.Add(pin10);
                Pins.Add(pin11);
                Pins.Add(pin12);
                Pins.Add(pin13);
                Pins.Add(pin14);

                SoftPwmMgr = new SoftPwmManager(this);

                // Comparator
                //Comparator1 = new Comparator(1);
                //Comparator2 = new Comparator(2);

                // Initialize modules
                analogOut = new AnalogOut(this);
                i2c       = new I2c(this);
                spi       = new Spi(this);
                //UART = new UART();

                // Initialize endpoint readers/writers
                PinConfig    = usb.OpenEndpointWriter(WriteEndpointID.Ep01);
                pinState     = usb.OpenEndpointReader(ReadEndpointID.Ep01);
                CommsConfig  = usb.OpenEndpointWriter(WriteEndpointID.Ep02);
                CommsReceive = usb.OpenEndpointReader(ReadEndpointID.Ep02);

                // Start reader events
                pinState.DataReceived       += pinState_DataReceived;
                pinState.DataReceivedEnabled = true;
                this.IsConnected             = true;
            }
            else
            {
                if (usb != null)
                {
                    if (usb.IsOpen)
                    {
                        usb.Close();
                    }
                    usb = null;
                }
            }
        }
        void mainThreadLoop()
        {
            try
            {
                while (enabled)
                {
                    online = false;
                    //Debug.WriteLine("Waiting for clovershell");
                    while (enabled)
                    {
                        try
                        {
                            var devices = UsbDevice.AllDevices;
                            device = null;
                            foreach (UsbRegistry regDevice in devices)
                            {
                                if (regDevice.Vid == vid && regDevice.Pid == pid)
                                {
                                    regDevice.Open(out device);
                                    break;
                                }
                            }
                            //device = USBDevice.GetSingleDevice(vid, pid);
                            if (device == null)
                            {
                                break;
                            }
                            IUsbDevice wholeUsbDevice = device as IUsbDevice;
                            if (!ReferenceEquals(wholeUsbDevice, null))
                            {
                                // This is a "whole" USB device. Before it can be used,
                                // the desired configuration and interface must be selected.

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

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

                            int inEndp  = -1;
                            int outEndp = -1;
                            int inMax   = 0;
                            int outMax  = 0;
                            foreach (var config in device.Configs)
                            {
                                foreach (var @interface in config.InterfaceInfoList)
                                {
                                    foreach (var endp in @interface.EndpointInfoList)
                                    {
                                        if ((endp.Descriptor.EndpointID & 0x80) != 0)
                                        {
                                            inEndp = endp.Descriptor.EndpointID;
                                            inMax  = endp.Descriptor.MaxPacketSize;
                                            //Debug.WriteLine("IN endpoint found: " + inEndp);
                                            //Debug.WriteLine("IN endpoint maxsize: " + inMax);
                                        }
                                        else
                                        {
                                            outEndp = endp.Descriptor.EndpointID;
                                            outMax  = endp.Descriptor.MaxPacketSize;
                                            //Debug.WriteLine("OUT endpoint found: " + outEndp);
                                            //Debug.WriteLine("OUT endpoint maxsize: " + outMax);
                                        }
                                    }
                                }
                            }
                            if (inEndp != 0x81 || outEndp != 0x01)
                            {
                                break;
                            }
                            epReader = device.OpenEndpointReader((ReadEndpointID)inEndp, 65536);
                            epWriter = device.OpenEndpointWriter((WriteEndpointID)outEndp);
                            Debug.WriteLine("clovershell connected");
                            // Kill all other sessions and drop all output
                            killAll();
                            var body = new byte[65536];
                            int len;
                            while (epReader.Read(body, 50, out len) == ErrorCode.Ok)
                            {
                                ;
                            }
                            epReader.ReadBufferSize      = 65536;
                            epReader.DataReceived       += epReader_DataReceived;
                            epReader.ReadThreadPriority  = ThreadPriority.AboveNormal;
                            epReader.DataReceivedEnabled = true;
                            lastAliveTime = DateTime.Now;
                            online        = true;
                            OnConnected();
                            while (device.mUsbRegistry.IsAlive)
                            {
                                Thread.Sleep(100);
                                if ((IdleTime.TotalSeconds >= 10) && (Ping() < 0))
                                {
                                    throw new ClovershellException("no answer from device");
                                }
                            }
                            break;
                        }
                        catch (ThreadAbortException)
                        {
                            return;
                        }
                        catch (ClovershellException ex)
                        {
                            Debug.WriteLine(ex.Message + ex.StackTrace);
                            break;
                        }
                    }
                    if (online)
                    {
                        dropAll();
                        OnDisconnected();
                        Debug.WriteLine("clovershell disconnected");
                    }
                    online = false;
                    if (device != null)
                    {
                        device.Close();
                    }
                    device = null;
                    if (epReader != null)
                    {
                        epReader.Dispose();
                    }
                    epReader = null;
                    if (epWriter != null)
                    {
                        epWriter.Dispose();
                    }
                    epWriter = null;
                    if (!autoreconnect)
                    {
                        Enabled = false;
                    }
                    Thread.Sleep(1000);
                }
            }
            catch (ThreadAbortException)
            {
                return;
            }
            catch (ClovershellException ex)
            {
                Debug.WriteLine("Critical error: " + ex.Message + ex.StackTrace);
            }
        }
예제 #27
0
        //
        //переделать всё
        //

        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();
                }
            }
        }
예제 #28
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]");
        }
예제 #29
0
        public void Open()
        {
            if (_deviceReg.Open(out _device) == false)
            {
                throw new InvalidOperationException("Unable to open the dongle, was it removed?");
            }

            _writer = _device.OpenEndpointWriter(WriteEndpointID.Ep01, EndpointType.Bulk);
            _reader = _device.OpenEndpointReader(ReadEndpointID.Ep01, 32, EndpointType.Bulk);

            _iDevice = _device as IUsbDevice;

            if (_iDevice != null)
            {
                _iDevice.SetConfiguration(1);
                _iDevice.ClaimInterface(0);
            }

            Setup();
        }
예제 #30
0
        private static void TheActualLoop()
        {
            var vid = 0x6b56;
            var pid = 0x8802;

            if (_shouldLogConnection)
            {
                _logger.Info($"Connecting to VID: {vid} PID: {pid}");
            }

            UsbRegistry volumeControllerRegistry = UsbDevice.AllDevices.FirstOrDefault(d => d.Vid == vid && d.Pid == pid);

            // If the device is open and ready
            if (volumeControllerRegistry == null || volumeControllerRegistry.Open(out var MyUsbDevice) == false)
            {
                if (_shouldLogConnection)
                {
                    _logger.Warn("Device Not Found.");
                    _shouldLogConnection = false;
                }
                System.Threading.Thread.Sleep(1000);
                return;
            }

            _shouldLogConnection = true;
            _logger.Info("Connected with great success.");
            App.notifyIcon.Text = "Tray Icon of Greatness";
            App.notifyIcon.Icon = Software.Properties.Resources.MainIcon;

            // 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 #2.
                wholeUsbDevice.ClaimInterface(2);
            }


            UsbEndpointWriter Writer3 = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep03);
            UsbEndpointWriter Writer4 = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep04);
            UsbEndpointReader reader  = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep03);

            sbyte[]      enc                 = new sbyte[ChannelCount];
            byte[][]     actualLedState      = new byte[ChannelCount][];
            Renderable[] actualLcdRenderable = new Renderable[ChannelCount];
            byte         ledCursor           = 0;
            byte         lcdCursor           = 0;

            bool firstLoop = true;

            do
            {
                int       transferredIn;
                byte[]    readBuffer = new byte[38];
                ErrorCode ecRead     = reader.Transfer(readBuffer, 0, readBuffer.Length, 1000, out transferredIn);
                if (ecRead != ErrorCode.None)
                {
                    throw new Exception($"Submit Async Read Failed. ErrorCode: {ecRead}");
                }

                if (transferredIn > 0)
                {
                    ushort touchReading   = (ushort)((ushort)readBuffer[2] | (ushort)(((ushort)readBuffer[3]) << 8));
                    ushort ambientReading = (ushort)((ushort)readBuffer[4] | (ushort)(((ushort)readBuffer[5]) << 8));
                    ambientReading = readBuffer[1];
                    for (int i = 0; i < ChannelCount; i++)
                    {
                        sbyte newenc  = (sbyte)(readBuffer[6 + 2 * i]);
                        sbyte encdiff = (sbyte)(firstLoop ? 0 : newenc - enc[i]);
                        enc[i] = newenc;
                        byte[]     newLedState;
                        Renderable newLcdRenderable;
                        _scriptManager.channels[i].HandleFrame(encdiff, readBuffer[7 + 2 * i], touchReading, ambientReading, out newLedState, out newLcdRenderable);
                        if (newLedState != null)
                        {
                            _wantedLedState[i] = newLedState;
                        }
                        if (newLcdRenderable != null)
                        {
                            _wantedLcdRenderable[i] = newLcdRenderable;
                        }
                    }

                    {
                        IEnumerable <byte> buffer = new byte[0];
                        for (int i = 0; i < ChannelCount && buffer.Count() < 52; i++)
                        {
                            if (_wantedLedState[ledCursor] != null && (actualLedState[ledCursor] == null || !_wantedLedState[ledCursor].SequenceEqual(actualLedState[ledCursor])))
                            {
                                byte[] wanted = _wantedLedState[ledCursor];
                                buffer = buffer.Concat(new byte[] {
                                    ledCursor, 0,
                                    wanted[0], wanted[1], wanted[2], wanted[3], wanted[4], wanted[5], wanted[6], wanted[7], wanted[8], wanted[9], wanted[20], wanted[20],
                                    wanted[10], wanted[11], wanted[12], wanted[13], wanted[14], wanted[15], wanted[16], wanted[17], wanted[18], wanted[19], wanted[20], wanted[20]
                                });
                                actualLedState[ledCursor] = wanted;
                            }
                            ledCursor = (byte)((ledCursor + 1) % ChannelCount);
                        }
                        if (buffer.Count() != 0)
                        {
                            if (buffer.Count() == 26)
                            {
                                buffer = buffer.Concat(buffer);
                            }

                            byte[] bytesToSend = buffer.ToArray();

                            int       transferredOut;
                            ErrorCode ecWrite = Writer4.Transfer(bytesToSend, 0, bytesToSend.Length, 100, out transferredOut);
                            if (ecWrite != ErrorCode.None)
                            {
                                // usbReadTransfer.Dispose();
                                throw new Exception($"Submit Async Write Failed on Writer4. ErrorCode: {ecWrite}");
                            }
                        }
                    }
                    {
                        for (int i = 0; i < ChannelCount; i++)
                        {
                            if (_wantedLcdRenderable[lcdCursor] != null && (actualLcdRenderable[lcdCursor] == null || !_wantedLcdRenderable[lcdCursor].Equals(actualLcdRenderable[lcdCursor])))
                            {
                                byte[] bytesToSend = (actualLcdRenderable[lcdCursor] = _wantedLcdRenderable[lcdCursor]).Render();

                                bytesToSend = new byte[] { 8, 2, lcdCursor, 0 }.Concat(bytesToSend).Concat(new byte[] { 0, 0, 0, 0 }).ToArray();

                                int       transferredOut;
                                ErrorCode ecLcdWrite = Writer3.Transfer(bytesToSend, 0, bytesToSend.Length, 900, out transferredOut);
                                if (ecLcdWrite != ErrorCode.None)
                                {
                                    // usbReadTransfer.Dispose();
                                    throw new Exception($"Submit Async Write Failed on Writer3. ErrorCode: {ecLcdWrite}");
                                }
                                else
                                {
                                    _logger.Info($"Wrote to LCD {lcdCursor}");
                                }
                                break;
                            }
                            lcdCursor = (byte)((lcdCursor + 1) % ChannelCount);
                        }
                    }
                }
                else
                {
                    _logger.Warn("Didn't get an interrupt packet?????");
                }

                firstLoop = false;
            } while (!_cancellationTokenSource.Token.IsCancellationRequested && !_shouldReloadConfig);

            MyUsbDevice.Close();
        }
예제 #31
0
        public void Open(UInt16 vid, UInt16 pid)
        {
            this.vid = vid;
            this.pid = pid;
            Close();
            Debug.WriteLine("Trying to open device...");
            var devices = UsbDevice.AllDevices;

            device = null;
            foreach (UsbRegistry regDevice in devices)
            {
                if (regDevice.Vid == vid && regDevice.Pid == pid)
                {
                    regDevice.Open(out device);
                    break;
                }
            }
            if (device == null)
            {
                throw new FelException("Device with such VID and PID not found");
            }

            IUsbDevice wholeUsbDevice = device as IUsbDevice;

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

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

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

            int inEndp  = -1;
            int outEndp = -1;
            int inMax   = 0;
            int outMax  = 0;

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

            Debug.WriteLine("Trying to verify device");
            if (VerifyDevice().Board != 0x00166700)
            {
                throw new FelException("Invalid board ID: " + VerifyDevice().Board);
            }
        }
예제 #32
0
        private void _Init(int vendorId, int productId, int interfaceNumber)
        {
            _readers = new Dictionary<int, UsbEndpointReader>();
              _writers = new Dictionary<int, UsbEndpointWriter>();

              _forwardee = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(vendorId, productId)) as IUsbDevice;
              if (_forwardee == null) throw new InvalidOperationException("Device not found");

              _forwardee.ClaimInterface(interfaceNumber);
              _forwardee.SetConfiguration(1);
        }
예제 #33
0
        public void connectReceiver()
        {
            // Connect to the Xbox Wireless Receiver and register the endpoint
            // readers/writers as necessary.
            try
            {
                // Open the Xbox Wireless Receiver as a USB device
                // VendorID 0x045e, ProductID 0x0719
                wirelessReceiver = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(0x045E, 0x0719)) as IUsbDevice;

                // If primary IDs not found attempt secondary IDs
                // VendorID 0x045e, Product ID 0x0291
                if (wirelessReceiver == null)
                {
                    wirelessReceiver = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(0x045E, 0x0291)) as IUsbDevice;
                }

                // If secondary IDs not found report the error
                if (wirelessReceiver == null)
                {
                    parentWindow.Invoke(new logCallback(parentWindow.logMessage),
                                        "ERROR: Wireless Receiver Not Found.");
                }
                else
                {
                    // Set the Configuration, Claim the Interface
                    wirelessReceiver.ClaimInterface(1);
                    wirelessReceiver.SetConfiguration(1);

                    // Log if the Wireless Receiver was connected to successfully
                    if (wirelessReceiver.IsOpen)
                    {
                        receiverAttached = true;
                        parentWindow.Invoke(new logCallback(parentWindow.logMessage),
                                            "Xbox 360 Wireless Receiver Connected.");

                        // Connect Bulk Endpoint Readers/Writers and register the receiving event handler
                        // Controller 1
                        epReaders[0] = wirelessReceiver.OpenEndpointReader(ReadEndpointID.Ep01);
                        epWriters[0] = wirelessReceiver.OpenEndpointWriter(WriteEndpointID.Ep01);
                        epReaders[0].DataReceived       += new EventHandler <EndpointDataEventArgs>(xboxControllers[0].processDataPacket);
                        epReaders[0].DataReceivedEnabled = true;
                        xboxControllers[0].registerEndpointWriter(epWriters[0]);

                        // Controller 2
                        epReaders[1] = wirelessReceiver.OpenEndpointReader(ReadEndpointID.Ep03);
                        epWriters[1] = wirelessReceiver.OpenEndpointWriter(WriteEndpointID.Ep03);
                        epReaders[1].DataReceived       += new EventHandler <EndpointDataEventArgs>(xboxControllers[1].processDataPacket);
                        epReaders[1].DataReceivedEnabled = true;
                        xboxControllers[1].registerEndpointWriter(epWriters[1]);

                        // Controller 3
                        epReaders[2] = wirelessReceiver.OpenEndpointReader(ReadEndpointID.Ep05);
                        epWriters[2] = wirelessReceiver.OpenEndpointWriter(WriteEndpointID.Ep05);
                        epReaders[2].DataReceived       += new EventHandler <EndpointDataEventArgs>(xboxControllers[2].processDataPacket);
                        epReaders[2].DataReceivedEnabled = true;
                        xboxControllers[2].registerEndpointWriter(epWriters[2]);

                        // Controller 4
                        epReaders[3] = wirelessReceiver.OpenEndpointReader(ReadEndpointID.Ep07);
                        epWriters[3] = wirelessReceiver.OpenEndpointWriter(WriteEndpointID.Ep07);
                        epReaders[3].DataReceived       += new EventHandler <EndpointDataEventArgs>(xboxControllers[3].processDataPacket);
                        epReaders[3].DataReceivedEnabled = true;
                        xboxControllers[3].registerEndpointWriter(epWriters[3]);

                        parentWindow.Invoke(new logCallback(parentWindow.logMessage),
                                            "Searching for Controllers...Press the Guide Button Now.");
                    }
                }
            }
            catch
            {
                parentWindow.Invoke(new logCallback(parentWindow.logMessage),
                                    "ERROR: Problem Connecting to Wireless Receiver.");
            }
        }
예제 #34
0
        public UsbDisplayDevice(int pVid, int pPid, WriteEndpointID pWriteEndpointID)
        {
            try
            {
                //Init Usb Finder
                UsbDeviceFinder usbFinder = new UsbDeviceFinder(pVid, pPid);

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

                // If the device is open and ready
                string message = string.Empty;
                if (_usbDevice == null)
                {
                    message = string.Format("UsbDisplayDevice: Device Not Found VID:{0} PID:{1}", pVid, pPid);
                    _log.Error(message);
                    //throw new Exception(message);
                }
                else
                {
                    message = string.Format("UsbDisplayDevice: Device Found VID:{0} PID:{1}", pVid, pPid);
                    _log.Debug(message);
                }

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

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

                // open write endpoint
                if (_usbDevice != null)
                {
                    _usbWriter = _usbDevice.OpenEndpointWriter(pWriteEndpointID);
                }

                //Init Display
                if (_usbWriter != null)
                {
                    InitializeDisplay();
                    if (_debug)
                    {
                        SetCursorInOff(0x01);
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Error((_usbErrorCode != ErrorCode.None ? _usbErrorCode + ":" : string.Empty) + ex.Message);
            }
        }
예제 #35
0
        public bool UsbConnect(bool buttonclick, int datalength)
        {
            if (buttonclick)
            {
                try
                {
                    if (UsbDeviceFinder())
                    {
                        _usbdevice = UsbDevice.OpenUsbDevice(_usbDeviceFinder);
                        IUsbDevice wholeUsbDevice = _usbdevice as IUsbDevice;

                        if (!(wholeUsbDevice is null))
                        {
                            wholeUsbDevice.SetConfiguration(1);
                            wholeUsbDevice.ClaimInterface(0);
                        }

                        _usbreader = _usbdevice.OpenEndpointReader(ReadEndpointID.Ep01);
                        _usbreader.DataReceived  += OnRxEndPointData;
                        _usbreader.ReadBufferSize = datalength;
                        _usbreader.Reset();
                        _usbreader.DataReceivedEnabled = true;

                        _usbwriter = _usbdevice.OpenEndpointWriter(WriteEndpointID.Ep01);
                    }
                    else
                    {
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    _msgserver.AddWindowsMsg("设备连接失败,请检查!");
                    return(false);
                }
                return(true);
            }
            else
            {
                if (_usbdevice != null)
                {
                    _usbreader.DataReceivedEnabled = false;
                    _usbreader.DataReceived       -= OnRxEndPointData;

                    _usbwriter.Dispose();

                    if (_usbdevice.IsOpen)
                    {
                        try
                        {
                            IUsbDevice wholeusbdevice = _usbdevice as IUsbDevice;
                            if (!(wholeusbdevice is null))
                            {
                                wholeusbdevice.ReleaseInterface(0);
                            }
                        }
                        catch (Exception ex)
                        {
                            return(false);
                        }
                    }

                    _usbdevice.Close();
                    _usbdevice = null;
                    UsbDevice.Exit();

                    for (int i = 0; i < _msgserver._usbDeviceList.Count; ++i)
                    {
                        _msgserver._usbDeviceList.RemoveAt(0);
                    }
                    _msgserver.AddMsg(_msgserver._usbBindList, $" > close device !");
                    _msgserver.AddWindowsMsg("采集设备需要重新上电");
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        }
예제 #36
0
        //The following are the bytes that can be sent to the nxt
        //reference sheet: http://kio4.com/b4a/programas/Appendix%202-LEGO%20MINDSTORMS%20NXT%20Direct%20commands.pdf

        public bool Connect(NXTControl nxt, string comPort = "COM3")
        {
            //thread that constantly monitors user commands in application.
            //Thread keyboardThread = new Thread(KeyboardListener);
            //keyboardThread.IsBackground = true;

            if (useBluetooth)
            {
                //connect over bluetooth
                _serialPort = new SerialPort(comPort);
                Console.WriteLine("Serial Port Initialized");

                //attempt to open the serial port and start reading data.
                int errorCount = 0;
                openport : try {
                    _serialPort.Open();
                    Console.WriteLine("Serial port opened and listener started.");
                } catch (Exception e) {
                    //catch System.UnauthorizedAccessException that arises when already connected.
                    if (e.GetType() == typeof(System.UnauthorizedAccessException))
                    {
                        Console.WriteLine("Already connected or line busy, assuming already connected.");
                        return(true);
                    }
                    Console.WriteLine("ERROR STARTING: " + e.ToString());
                    errorCount += 1;
                    if (errorCount < 5)
                    {
                        goto openport; //I hate myself.
                    }
                    else
                    {
                        Console.WriteLine("TOO MANY ERRORS TRYING TO CONNECT, ABORTED");
                        return(false);
                    }
                }
            }
            else
            {
                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)
                    {
                        Console.Error.WriteLine("[ERROR] Failed to connect over USB.");
                        return(false);
                    }

                    // 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.

                        Console.WriteLine("[DEBUG] This is whole usb device.");

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

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

                    // open read and write endpoint 1.
                    usbReader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep02, 64, EndpointType.Bulk);
                    usbWriter = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01, EndpointType.Bulk);

                    SetupReading();

                    Console.WriteLine("[DEBUG] Done initializing.");
                } catch (Exception ex) {
                    Console.WriteLine();
                    Console.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
                    Disconnect();
                }
            }

            //send a tone to nxt to notify user. 1khz for .5 seconds
            byte[] tonePacket = { 0x80, 0x03, 0xE8, 0x03, 0xF4, 0x01 };
            nxt.SendPacket(tonePacket);

            ////battery check message
            //byte[] message = { 0x00, 0x0B };

            ////attempt to send a battery check command
            //bool suc = SendPacket(message);
            //Console.WriteLine(suc);
            return(true);
        }
예제 #37
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();
                }
            }
        }