public static StenoDevice Open()
        {
            UsbRegDeviceList devices     = UsbDevice.AllDevices;
            UsbRegistry      usbRegistry = devices.Find(x => x.Vid == VendorId && x.Pid == ProductId && x.Name == Name);

            if (usbRegistry == null)
            {
                return(null);
            }

            UsbDevice stenoDevice;

            if (!usbRegistry.Open(out stenoDevice))
            {
                return(null);
            }

            var wholeUsbDevice = stenoDevice as IUsbDevice;

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

            return(new StenoDevice(stenoDevice));
        }
Ejemplo n.º 2
0
        public override bool Open()
        {
            try
            {
                UsbDeviceFinder MyUsbFinder   = new UsbDeviceFinder(((UsbConfigModel)Configuration).PID, ((UsbConfigModel)Configuration).VID);
                UsbRegistry     myUsbRegistry = UsbDevice.AllWinUsbDevices.Find(MyUsbFinder);

                if (myUsbRegistry is null)
                {
                    return(false);
                }
                // Open this usb device.

                _dev = UsbDevice.OpenUsbDevice(MyUsbFinder) as IUsbDevice;

                _dev.SetConfiguration(1);

                _dev.ClaimInterface(0);
                _writer = _dev.OpenEndpointWriter(WriteEndpointID.Ep01);
                _reader = _dev.OpenEndpointReader(ReadEndpointID.Ep01);
            }
            catch (Exception exp)
            {
                throw new Exception(exp.ToString());
            }
            return(true);
        }
Ejemplo n.º 3
0
 public static ConnectedDeviceDefinition ToConnectedDevice(this UsbRegistry usbRegistry)
 => usbRegistry == null ? throw new ArgumentNullException(nameof(usbRegistry)) :
       new ConnectedDeviceDefinition(
           usbRegistry.DevicePath,
           vendorId: (uint)usbRegistry.Vid,
           productId: (uint)usbRegistry.Pid,
           deviceType: DeviceType.Usb);
Ejemplo n.º 4
0
        private static StringBuilder getDescriptorReport(UsbRegistry usbRegistry)
        {
            UsbDevice     usbDevice;
            StringBuilder sbReport = new StringBuilder();

            if (!usbRegistry.Open(out usbDevice))
            {
                return(sbReport);
            }

            sbReport.AppendLine(string.Format("{0} OSVersion:{1} LibUsbDotNet Version:{2} DriverMode:{3}", usbRegistry.FullName, UsbDevice.OSVersion, LibUsbDotNetVersion, usbDevice.DriverMode));
            sbReport.AppendLine(usbDevice.Info.ToString("", UsbDescriptor.ToStringParamValueSeperator, UsbDescriptor.ToStringFieldSeperator));
            foreach (UsbConfigInfo cfgInfo in usbDevice.Configs)
            {
                sbReport.AppendLine(string.Format("CONFIG #{1}\r\n{0}", cfgInfo.ToString("", UsbDescriptor.ToStringParamValueSeperator, UsbDescriptor.ToStringFieldSeperator), cfgInfo.Descriptor.ConfigID));
                foreach (UsbInterfaceInfo interfaceInfo in cfgInfo.InterfaceInfoList)
                {
                    sbReport.AppendLine(string.Format("INTERFACE ({1},{2})\r\n{0}", interfaceInfo.ToString("", UsbDescriptor.ToStringParamValueSeperator, UsbDescriptor.ToStringFieldSeperator), interfaceInfo.Descriptor.InterfaceID, interfaceInfo.Descriptor.AlternateID));

                    foreach (UsbEndpointInfo endpointInfo in interfaceInfo.EndpointInfoList)
                    {
                        sbReport.AppendLine(string.Format("ENDPOINT 0x{1:X2}\r\n{0}", endpointInfo.ToString("", UsbDescriptor.ToStringParamValueSeperator, UsbDescriptor.ToStringFieldSeperator), endpointInfo.Descriptor.EndpointID));
                    }
                }
            }
            usbDevice.Close();

            return(sbReport);
        }
Ejemplo n.º 5
0
        public void Dispose()
        {
            Registry   = null;
            IsDisposed = true;
            if (Device != null)
            {
                Writer.Abort();
                Writer.Dispose();
                Writer = null;
                if (Device.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 = Device as IUsbDevice;
                    if (!ReferenceEquals(wholeUsbDevice, null))
                    {
                        // Release interface #0.
                        wholeUsbDevice.ReleaseInterface(0);
                    }

                    Device.Close();
                }
                Device = null;

                // Free usb resources
                UsbDevice.Exit();
            }
        }
Ejemplo n.º 6
0
 public CH341(UsbRegistry registry)
 {
     if (!registry.IsAlive || !registry.Open(out CH341device))
     {
         throw new DeviceNotFoundException(registry.Vid, registry.Pid);
     }
     Constructors_common();
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Attempts to open a USB registry as a USB DFU device.
        /// </summary>
        /// <param name="registry">The input USB registry of a connected device</param>
        /// <param name="dfuDevice">The opened DFU device in case of success</param>
        /// <returns>True if the DFU device is successfully opened</returns>
        public static bool TryOpen(UsbRegistry registry, out Device dfuDevice)
        {
            dfuDevice = null;
            UsbDevice dev;
            byte      cfIndex = 0;
            byte      ifIndex = 0;

            if (!registry.Open(out dev))
            {
                return(false);
            }

            var confInfo = dev.Configs[cfIndex];

            // This is a "whole" USB device. Before it can be used,
            // the desired configuration and interface must be selected.
            IUsbDevice usbDevice = dev as IUsbDevice;

            if (usbDevice != null)
            {
                // Select config
                usbDevice.SetConfiguration(confInfo.Descriptor.ConfigID);
            }

            // find DFU interface
            for (ifIndex = 0; ifIndex < confInfo.InterfaceInfoList.Count; ifIndex++)
            {
                var iface = confInfo.InterfaceInfoList[ifIndex];

                if (!IsDfuInterface(iface))
                {
                    continue;
                }

                if (usbDevice != null)
                {
                    // Claim interface
                    usbDevice.ClaimInterface(iface.Descriptor.InterfaceID);
                }
                break;
            }

            try
            {
                if (ifIndex == confInfo.InterfaceInfoList.Count)
                {
                    throw new ArgumentException("The device doesn't have valid DFU interface");
                }
                dfuDevice = new Device(dev, cfIndex, ifIndex);
                return(true);
            }
            catch (Exception)
            {
                var d = dev as IDisposable;
                d.Dispose();
                return(false);
            }
        }
Ejemplo n.º 8
0
        public override void OpenDevice()
        {
            log.Info("QDLUsb trying to find device");
            UsbDevice.UsbErrorEvent += new EventHandler <UsbError>(UsbErrorEvent);
            UsbRegistry regDev = null;

            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                regDev = UsbDevice.AllWinUsbDevices.Find((reg) => reg.Vid == VID && reg.Pid == PID);
            }
            else
            {
                regDev = UsbDevice.AllDevices.Find((reg) => reg.Vid == VID && reg.Pid == PID);
            }
            if (regDev == null)
            {
                log.Error("No QDLUSB Devices found");
                throw new QDLDeviceNotFoundException("Unable to find device");
            }

            if (!regDev.Open(out device) || device == null)
            {
                log.Error("No QDLUSB Devices found");
                throw new QDLDeviceNotFoundException("Unable to open device");
            }

            if (UsbDevice.IsLinux)
            {
                log.Debug("Running on linux, detaching kernel driver");
                MonoUsbDevice monodev = device as MonoUsbDevice;
                if (!monodev.DetachKernelDriver())
                {
                    log.Error("Failed to detach kernel driver");
                    throw new Exception("Failed to detach kernel driver");
                }
            }

            IUsbDevice wholeUsbDevice = device as IUsbDevice;

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

            reader = device.OpenEndpointReader(ReadEndpointID.Ep01);
            writer = device.OpenEndpointWriter(WriteEndpointID.Ep01, EndpointType.Bulk);
            if (reader == null || writer == null)
            {
                device.Close();
                device = null;
                UsbDevice.Exit();
                log.Error("Failed to open endpoints");
                throw new Exception("Unable to open endpoints");
            }
            log.Info("Found QDLUSB device");
        }
        public static int GetInterfaceId(this UsbRegistry registry)
        {
            if (registry is WinUsbRegistry win)
            {
                return(win.InterfaceID);
            }

            return(0);
        }
Ejemplo n.º 10
0
        private void addDevice(UsbRegistry deviceReg, string display)
        {
            if (!deviceReg.Open(out mUsbDevice))
            {
                return;
            }
            mUsbRegistry = deviceReg;

            TreeNode tvDevice = tvInfo.Nodes.Add(display);

            string[] sDeviceAdd = mUsbDevice.Info.ToString().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string s in sDeviceAdd)
            {
                tvDevice.Nodes.Add(s);
            }


            foreach (UsbConfigInfo cfgInfo in mUsbDevice.Configs)
            {
                TreeNode tvConfig = tvDevice.Nodes.Add("Config " + cfgInfo.Descriptor.ConfigID);
                string[] sCfgAdd  = cfgInfo.ToString().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string s in sCfgAdd)
                {
                    tvConfig.Nodes.Add(s);
                }

                TreeNode tvInterfaces = tvConfig; //.Nodes.Add("Interfaces");
                foreach (UsbInterfaceInfo interfaceInfo in cfgInfo.InterfaceInfoList)
                {
                    TreeNode tvInterface =
                        tvInterfaces.Nodes.Add("Interface [" + interfaceInfo.Descriptor.InterfaceID + "," + interfaceInfo.Descriptor.AlternateID + "]");
                    string[] sInterfaceAdd = interfaceInfo.ToString().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string s in sInterfaceAdd)
                    {
                        tvInterface.Nodes.Add(s);
                    }

                    TreeNode tvEndpoints = tvInterface; //.Nodes.Add("Endpoints");
                    foreach (UsbEndpointInfo endpointInfo in interfaceInfo.EndpointInfoList)
                    {
                        TreeNode tvEndpoint   = tvEndpoints.Nodes.Add("Endpoint 0x" + (endpointInfo.Descriptor.EndpointID).ToString("X2"));
                        string[] sEndpointAdd = endpointInfo.ToString().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string s in sEndpointAdd)
                        {
                            tvEndpoint.Nodes.Add(s);
                        }
                    }
                }
            }
            mUsbDevice.Close();
        }
Ejemplo n.º 11
0
        public void AddDevice(string content, int vid, int pid, int rev, UsbRegistry dev)
        {
            object[] o = new Object[] { vid, pid, rev, dev };
            if (AvailableDevices.Items.Contains(LoadingDevices))
            {
                LoadingDevices.Content = "Please select a device.";
            }

            ComboBoxItem item = new ComboBoxItem();

            item.Content = content;
            item.Tag     = o;
            AvailableDevices.Items.Insert(AvailableDevices.Items.Count - 1, item);
        }
Ejemplo n.º 12
0
        public static string GetDeviceSerial(UsbRegistry device)
        {
            switch (Environment.OSVersion.Platform)
            {
            case PlatformID.Win32NT:
            {
                var deviceID = device.DeviceProperties["DeviceID"].ToString();
                return(deviceID.Substring(deviceID.LastIndexOf("\\") + 1));
            }

            default:
                return(device.DeviceProperties["SerialNumber"].ToString());
            }
        }
Ejemplo n.º 13
0
        internal void OpenDevice(UsbRegistry registry)
        {
            this._device = registry.Device;

            IUsbDevice wholeUsbDevice = _device as IUsbDevice;

            if (!ReferenceEquals(wholeUsbDevice, null))
            {
                // Select config #1
                wholeUsbDevice.SetConfiguration(1);
                // Claim interface #0.
                wholeUsbDevice.ClaimInterface(0);
            }
        }
Ejemplo n.º 14
0
 private void ChangeDevice(object sender, SelectionChangedEventArgs e)
 {
     if (AvailableDevices.SelectedItem != null && AvailableDevices.SelectedIndex != 0 && AvailableDevices.SelectedIndex != AvailableDevices.Items.Count - 1)
     {
         object[] tag = (AvailableDevices.SelectedItem as ComboBoxItem).Tag as object[];
         VendorId  = (int)tag[0];
         ProductId = (int)tag[1];
         Rev       = (int)tag[2];
         Device    = (UsbRegistry)tag[3];
         canLog    = true;
         string name = (AvailableDevices.SelectedItem as ComboBoxItem).Content.ToString().Substring(0, (AvailableDevices.SelectedItem as ComboBoxItem).Content.ToString().IndexOf("[") - 1);
         if (handler.IsLogging)
         {
             handler.StopLogging();
         }
         if (handler.IsRecording)
         {
             handler.StopRecording();
         }
         handler.StartLogging();
     }
     if (AvailableDevices.SelectedIndex == 0 && handler != null)
     {
         canLog = false;
         if (handler.IsRecording)
         {
             handler.StopRecording();
         }
         if (handler.IsLogging)
         {
             handler.StopLogging();
         }
         ChangePollingButton();
     }
     else if (AvailableDevices.SelectedIndex == AvailableDevices.Items.Count - 1)
     {
         if (handler.IsRecording)
         {
             handler.StopRecording();
         }
         if (handler.IsLogging)
         {
             handler.StopLogging();
         }
         ReloadDevices();
         ChangePollingButton();
     }
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Opens the usb device that matches the find predicate.
        /// </summary>
        /// <param name="findDevicePredicate">The predicate function used to find the usb device.</param>
        /// <returns>An valid/open usb device class if the device was found or Null if the device was not found.</returns>
        public static UsbDevice OpenUsbDevice(Predicate <UsbRegistry> findDevicePredicate)
        {
            UsbDevice usbDeviceFound;

            UsbRegDeviceList allDevices     = AllDevices;
            UsbRegistry      regDeviceFound = allDevices.Find(findDevicePredicate);

            if (ReferenceEquals(regDeviceFound, null))
            {
                return(null);
            }

            usbDeviceFound = regDeviceFound.Device;

            return(usbDeviceFound);
        }
Ejemplo n.º 16
0
        public Form1()
        {
            InitializeComponent();

            devs = UsbDevice.AllDevices;

            if (devs.Count > 0)
            {
                reg = devs[0];
            }

            Process p = Process.GetCurrentProcess();

            p.PriorityClass = ProcessPriorityClass.High;

            this.WindowState = FormWindowState.Maximized;
        }
Ejemplo n.º 17
0
        private bool FindAndOpenUSB(int VID, int PID)
        {
            UsbDeviceFinder usbFinder   = new UsbDeviceFinder(VID, PID);
            UsbRegistry     usbRegistry = UsbDevice.AllDevices.Find(usbFinder);

            if (ReferenceEquals(usbRegistry, null))
            {
                return(false);
            }
            // Open this usb device.
            if (!usbRegistry.Open(out USBDevice))
            {
                return(false);
            }
            ((LibUsbDevice)USBDevice).SetConfiguration(1);
            ((LibUsbDevice)USBDevice).ClaimInterface(0);
            return(true);
        }
Ejemplo n.º 18
0
        private bool FindAndOpenUSB(int PID, int VID)
        {
            UsbDeviceFinder MyUsbFinder   = new UsbDeviceFinder(PID, VID);
            UsbRegistry     myUsbRegistry = UsbGlobals.AllDevices.Find(MyUsbFinder);

            if (ReferenceEquals(myUsbRegistry, null))
            {
                return(false);
            }
            // Open this usb device.
            if (!myUsbRegistry.Open(out MyUsbDevice))
            {
                return(false);
            }

            MyUsbDevice.SetConfiguration(1);

            ((LibUsbDevice)MyUsbDevice).ClaimInterface(0);

            ShowMsg(string.Format("Find Device:{0}", myUsbRegistry[SPDRP.DeviceDesc]));
            return(true);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Opens the usb device that matches the find predicate.
        /// </summary>
        /// <param name="findDevicePredicate">The predicate function used to find the usb device.</param>
        /// <returns>An valid/open usb device class if the device was found or Null if the device was not found.</returns>
        public static UsbDevice OpenUsbDevice(Predicate <UsbRegistry> findDevicePredicate)
        {
            UsbDevice usbDeviceFound;

            UsbRegDeviceList allDevices     = AllDevices;
            UsbRegistry      regDeviceFound = allDevices.Find(findDevicePredicate);

            if (ReferenceEquals(regDeviceFound, null))
            {
                return(null);
            }

            // just in case there are several device with the same PID and VID check the ones that is connected and has a Device attached
            if (ReferenceEquals(regDeviceFound.Device, null))
            {
                regDeviceFound = allDevices.FindLast(findDevicePredicate);
            }

            usbDeviceFound = regDeviceFound.Device;

            return(usbDeviceFound);
        }
Ejemplo n.º 20
0
        private void cmdOpenClose_Click(object sender, EventArgs e)
        {
            cmdOpenClose.Enabled = false;
            if (cmdOpenClose.Text == "Open" && cboDevice.SelectedIndex != -1)
            {
                // Open Device
                UsbRegistry winUsbRegistry = mRegInfo[cboDevice.SelectedIndex];

                if (openAsTestDevice(winUsbRegistry))
                {
                    benchParamsPropertyGrid.Enabled = false;
                    SetStatus("Device Opened", false);
                    cmdOpenClose.Text = "Close";
                    panDevice.Enabled = true;
                }
            }
            else
            {
                closeTestDevice(mUsbDevice);
                benchParamsPropertyGrid.Enabled = true;
                SetStatus("Device Closed", false);
            }
            cmdOpenClose.Enabled = true;
        }
Ejemplo n.º 21
0
        public void LoadDevices()
        {
            UsbRegDeviceList devices = UsbDevice.AllDevices;

            for (int i = 0; i < devices.Count; i++)
            {
                if (loadDevices.ThreadState == System.Threading.ThreadState.AbortRequested)
                {
                    break;
                }
                else
                {
                    UsbRegistry dev  = devices[i];
                    string      name = "";
                    if (dev.Vid == 0x1A86 && dev.Pid == 0xE008)
                    {
                        name = "Tenma 72-7730A";
                    }
                    else if (dev.Vid == 0x04FA && dev.Pid == 0x2490)
                    {
                        name = "Tenma 72-7730";
                    }
                    else
                    {
                        name = dev.Name;
                    }

                    string content = name + " [" + dev.Vid.ToString() + ":" + dev.Pid.ToString() + "]";

                    Application.Current.Dispatcher.BeginInvoke(new ThreadStart(() =>
                    {
                        AddDevice(content, dev.Vid, dev.Pid, dev.Rev, dev);
                    }));
                }
            }
        }
Ejemplo n.º 22
0
 public LibUsbCommunication(UsbRegistry usbRegistry, UsbResolverInfo resolverInfo)
 {
     _usbRegistry  = usbRegistry;
     _resolverInfo = resolverInfo;
 }
Ejemplo n.º 23
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();
        }
Ejemplo n.º 24
0
        public static void getSPDRPProperties(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, Dictionary <string, object> deviceProperties)
        {
            byte[] propBuffer = new byte[1024];
            Dictionary <string, int> allProps = Helper.GetEnumData(typeof(SPDRP));

            foreach (KeyValuePair <string, int> prop in allProps)
            {
                object            oValue = String.Empty;
                int               iReturnBytes;
                RegistryValueKind regPropType;
                bool              bSuccess = SetupDiGetDeviceRegistryProperty(deviceInfoSet,
                                                                              ref deviceInfoData,
                                                                              (SPDRP)prop.Value,
                                                                              out regPropType,
                                                                              propBuffer,
                                                                              propBuffer.Length,
                                                                              out iReturnBytes);
                if (bSuccess)
                {
                    switch ((SPDRP)prop.Value)
                    {
                    case SPDRP.PhysicalDeviceObjectName:
                    case SPDRP.LocationInformation:
                    case SPDRP.Class:
                    case SPDRP.Mfg:
                    case SPDRP.DeviceDesc:
                    case SPDRP.Driver:
                    case SPDRP.EnumeratorName:
                    case SPDRP.FriendlyName:
                    case SPDRP.ClassGuid:
                        oValue = UsbRegistry.GetAsString(propBuffer, iReturnBytes);
                        break;

                    case SPDRP.HardwareId:
                    case SPDRP.CompatibleIds:
                    case SPDRP.LocationPaths:
                        oValue = UsbRegistry.GetAsStringArray(propBuffer, iReturnBytes);
                        break;

                    case SPDRP.BusNumber:
                    case SPDRP.InstallState:
                    case SPDRP.LegacyBusType:
                    case SPDRP.RemovalPolicy:
                    case SPDRP.UiNumber:
                    case SPDRP.Address:
                        oValue = UsbRegistry.GetAsStringInt32(propBuffer, iReturnBytes);
                        break;

                    case SPDRP.BusTypeGuid:
                        oValue = UsbRegistry.GetAsGuid(propBuffer, iReturnBytes);
                        break;
                    }
                }
                else
                {
                    oValue = String.Empty;
                }

                deviceProperties.Add(prop.Key, oValue);
            }
        }
Ejemplo n.º 25
0
        public void InstallDevices()
        {
            if (System.Environment.Is64BitOperatingSystem == false)
            {
                if (File.Exists("C:/Windows/System32/libusb-1.0.dll") == false)
                {
                    byte[] dll = Properties.Resources.libusb1x86;
                    using (FileStream file = new FileStream("C:/Windows/System32/libusb-1.0.dll", FileMode.Create))
                    {
                        file.Write(dll, 0, dll.Length);
                    }
                }
                byte[] exeBytes = Properties.Resources.installFilter32;
                string exeToRun = "install-filter.exe";
                using (FileStream exeFile = new FileStream(exeToRun, FileMode.Create))
                {
                    exeFile.Write(exeBytes, 0, exeBytes.Length);
                }

                UsbRegDeviceList usbDevices = UsbDevice.AllDevices;
                for (int i = 0; i < usbDevices.Count; i++)
                {
                    UsbRegistry dev = usbDevices[i];
                    using (Process exeProcess = Process.Start(exeToRun, "-i --device=USB\\Vid_" + dev.Vid.ToString("X4") + ".Pid_" + dev.Pid.ToString("X4") + ".Rev_" + dev.Rev.ToString("X4")))
                    {
                        exeProcess.WaitForExit();
                    }
                }

                /*string[] devices = new string[] { "-i --device=USB\\Vid_1a86.Pid_e008.Rev_1200", "-i --device=USB\\Vid_04fa.Pid_2490.Rev_0000" };
                 * for (int i = 0; i < devices.Length; i++)
                 * {
                 *  if (installDevices.ThreadState == System.Threading.ThreadState.AbortRequested)
                 *  {
                 *      break;
                 *  }
                 *  else
                 *  {
                 *      using (Process exeProcess = Process.Start(exeToRun, devices[i]))
                 *      {
                 *
                 *          exeProcess.WaitForExit();
                 *      }
                 *  }
                 * }*/
                File.Delete(exeToRun);
            }
            else if (System.Environment.Is64BitOperatingSystem)
            {
                if (File.Exists("C:/Windows/SysWOW64/libusb-1.0.dll") == false)
                {
                    byte[] dll = Properties.Resources.libusb1amd64;
                    using (FileStream file = new FileStream("C:/Windows/SysWOW64/libusb-1.0.dll", FileMode.Create))
                    {
                        file.Write(dll, 0, dll.Length);
                    }
                }
                if (File.Exists("C:/Windows/System32/libusb-1.0.dll") == false)
                {
                    byte[] dll = Properties.Resources.libusb1x86;
                    using (FileStream file = new FileStream("C:/Windows/System32/libusb-1.0.dll", FileMode.Create))
                    {
                        file.Write(dll, 0, dll.Length);
                    }
                }
                byte[] exeBytes = Properties.Resources.installFilter64;
                string exeToRun = "install-filter.exe";
                using (FileStream exeFile = new FileStream(exeToRun, FileMode.Create))
                {
                    exeFile.Write(exeBytes, 0, exeBytes.Length);
                }

                UsbRegDeviceList usbDevices = UsbDevice.AllDevices;
                for (int i = 0; i < usbDevices.Count; i++)
                {
                    UsbRegistry dev = usbDevices[i];
                    using (Process exeProcess = Process.Start(exeToRun, "-i --device=USB\\Vid_" + dev.Vid.ToString("X4") + ".Pid_" + dev.Pid.ToString("X4") + ".Rev_" + dev.Rev.ToString("X4")))
                    {
                        exeProcess.WaitForExit();
                    }
                }

                /*string[] devices = new string[] { "-i --device=USB\\Vid_1a86.Pid_e008.Rev_1200", "-i --device=USB\\Vid_04fa.Pid_2490.Rev_0000" };
                 * for (int i = 0; i < devices.Length; i++)
                 * {
                 *  if (installDevices.ThreadState == System.Threading.ThreadState.AbortRequested)
                 *  {
                 *      break;
                 *  }
                 *  else
                 *  {
                 *      using (Process exeProcess = Process.Start(exeToRun, devices[i]))
                 *      {
                 *
                 *          exeProcess.WaitForExit();
                 *      }
                 *  }
                 * }*/
                File.Delete(exeToRun);
            }
            else
            {
                new WPFMessageBox(this, "Hold on there cowboy!", "It appears that you are neither running a 32bit nor 64bit system. Currently this program only supports 32 and 64 bit systems. Sorry!").Display();
            }
        }
Ejemplo n.º 26
0
        void logDevice(UsbRegistry usbRegistry)
        {
            UsbDevice device;

            if (!usbRegistry.Open(out device))
            {
                return;
            }

            // split device.Info's string representation on linefeeds
            //   iterateDevice: Vid:0x2457 Pid:0x101E (rev:2) - Ocean Optics USB2000+ (WinUSB)
            //   iterateDevice: Vid:0x24AA Pid:0x1000 (rev:100) - Wasatch Photonics Spectrometer
            // Not all device info summaries will appear in device.Configs...not sure why
            string[] deviceInfoSummaries = device.Info.ToString().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string line in deviceInfoSummaries)
            {
                logger.debug("Summary: {0}", line);
            }

            foreach (UsbConfigInfo cfgInfo in device.Configs)
            {
                logger.debug("Config {0}", cfgInfo.Descriptor.ConfigID);

                // log UsbConfigInfo
                logNameValuePairs(cfgInfo.ToString().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries));

                // log UsbInterfaceInfo
                foreach (UsbInterfaceInfo interfaceInfo in cfgInfo.InterfaceInfoList)
                {
                    logger.debug("Interface [InterfaceID {0}, AlternateID {1}]", interfaceInfo.Descriptor.InterfaceID, interfaceInfo.Descriptor.AlternateID);
                    logNameValuePairs(interfaceInfo.ToString().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries));

                    // log UsbEndpointInfo
                    foreach (UsbEndpointInfo endpointInfo in interfaceInfo.EndpointInfoList)
                    {
                        logger.debug("  Endpoint 0x" + (endpointInfo.Descriptor.EndpointID).ToString("x2"));
                        logNameValuePairs(endpointInfo.ToString().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries), "    ");
                    }
                }

                // log SymbolicName
                UsbSymbolicName symName = UsbSymbolicName.Parse(usbRegistry.SymbolicName);
                logger.debug("Symbolic Name:");
                logger.debug("  VID:          0x{0:x4}", symName.Vid);
                logger.debug("  PID:          0x{0:x4}", symName.Pid);
                logger.debug("  SerialNumber: {0}", symName.SerialNumber);
                logger.debug("  Class Guid:   {0}", symName.ClassGuid);

                logger.debug("Device Properties:");
                foreach (KeyValuePair <string, object> pair in usbRegistry.DeviceProperties)
                {
                    string key   = pair.Key;
                    object value = pair.Value;

                    // handle array values
                    if (value is string[])
                    {
                        string[] values = value as string[];
                        logger.debug("  {0}: [ {1} ]", key, string.Join(", ", values));
                    }
                    else
                    {
                        logger.debug("  {0}: {1}", key, value);
                    }
                }

                logger.debug(" ");
            }
            device.Close();
        }
Ejemplo n.º 27
0
 public LibusbHidDevice(UsbRegistry key)
 {
     this.deviceRegistry = key;
 }
Ejemplo n.º 28
0
        private bool openAsTestDevice(UsbRegistry usbRegistry)
        {
            if (!ReferenceEquals(mUsbDevice, null))
            {
                closeTestDevice(mUsbDevice);
            }

            mUsbDevice = null;

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

                    UsbDevice.UsbErrorEvent += OnUsbError;

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

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

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

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

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

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

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

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

                    mInterfaceInfo = writeInterfaceInfo;

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

                    makeTestBytes(out loopTestBytes, mBenchMarkParameters.BufferSize);


                    // If this is a "whole" usb device (libusb-win32, linux libusb)
                    // it will have an IUsbDevice interface. If not (WinUSB) the
                    // variable will be null indicating this is an interface of a
                    // device.
                    IUsbDevice wholeUsbDevice = mUsbDevice as IUsbDevice;
                    if (!ReferenceEquals(wholeUsbDevice, null))
                    {
                        // This is a "whole" USB device. Before it can be used,
                        // the desired configuration and interface must be selected.

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

                        // Claim interface #0.
                        wholeUsbDevice.ClaimInterface(mInterfaceInfo.Descriptor.InterfaceID);
                    }
                    return(true);
                }
            }
            catch (Exception ex)
            {
                SetStatus(ex.Message, true);
            }

            if (!ReferenceEquals(mUsbDevice, null))
            {
                try
                {
                    closeTestDevice(mUsbDevice);
                }
                finally
                {
                    mUsbDevice = null;
                    mEP1Reader = null;
                    mEP1Writer = null;
                }
            }
            return(false);
        }
Ejemplo n.º 29
0
 internal void Init(HidDevice hidDevice, UsbRegistry registry)
 {
     _hidDevice = hidDevice;
     OpenDevice(registry);
 }
Ejemplo n.º 30
0
        private void buttonInitialize_Click(object sender, EventArgs e)
        {
            UsbDevice.UsbErrorEvent += OnUsbError;

            UsbRegDeviceList deviceRegistries = UsbDevice.AllDevices;
            UsbRegistry      myUsbRegistry    = null;

            foreach (UsbRegistry usbRegistry in deviceRegistries)
            {
                String desc = String.Format("Vid:0x{0:x4} Pid:0x{1:x4} (rev:{2}) - {3}",
                                            usbRegistry.Vid,
                                            usbRegistry.Pid,
                                            (ushort)usbRegistry.Rev,
                                            usbRegistry[SPDRP.DeviceDesc]);

                if (usbRegistry.Vid == 0x24aa)
                {
                    logger.info("found Wasatch device: {0}", desc);
                    if (myUsbRegistry == null)
                    {
                        myUsbRegistry = usbRegistry;
                    }
                }
                else
                {
                    logger.debug("ignored {0}", desc);
                }
            }

            logger.info("opening {0:x4}:{1:x4}", myUsbRegistry.Vid, myUsbRegistry.Pid);

            if (!myUsbRegistry.Open(out usbDevice))
            {
                logger.error("test: failed to open UsbRegistry");
                return;
            }

            IUsbDevice wholeUsbDevice = usbDevice as IUsbDevice;

            if (!ReferenceEquals(wholeUsbDevice, null))
            {
                logger.info("setting configuration");
                wholeUsbDevice.SetConfiguration(1);

                logger.info("claiming interface");
                wholeUsbDevice.ClaimInterface(0);
            }
            else
            {
                logger.info("WinUSB detected (not setting configuration or claiming interface)");
            }

            if (myUsbRegistry.Pid == 0x4000)
            {
                checkBoxUseARM.Checked = true;
            }
            if (myUsbRegistry.Pid == 0x2000)
            {
                isInGaAs = true;
            }

            buttonInitialize.Enabled = false;
            if (commands != null)
            {
                enableAll();
            }
        }