Пример #1
0
        private void DataInitialize()
        {
            DataBase      db       = new DataBase();
            List <string> dataList = new List <string>();

            dataList = getSqlList(Properties.Resources.DatabaseTable);
            db.BatchOperate(dataList);

            dataList.Clear();
            dataList = GetSubjectSqlList();
            db.BatchOperate(dataList);

            //插入数据
            dataList.Clear();
            dataList = getSqlList(Properties.Resources.DatabaseData);
            string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            //获取U盘唯一码
            UsbController usb  = new UsbController();
            string        _str = usb.getSerialNumberFromDriveLetter();
            string        sql  = "insert into t_systeminfo (op_time,rkey,value,comments) values ('" + date
                                 + "','" + (int)ENUM.EM_KEY.软件版本 + "','" + (int)ENUM.EM_SOFTWARESTATE.未注册 + "','第一次运行显示未注册'),('" + date
                                 + "','" + (int)ENUM.EM_KEY.注册码 + "','','注册码'),('" + date
                                 + "','" + (int)ENUM.EM_KEY.U盘标识 + "','" + _str + "','USB')";

            dataList.Add(sql);
            db.BatchOperate(dataList);
        }
Пример #2
0
        /// <summary>
        /// Adds the supported controller models to the LibUsb list.
        /// </summary>
        /// <param name="ids">A list of VID+PID identifiers to search</param>
        internal static void AddSupportedControllers(string[] ids)
        {
            foreach (string id in ids)
            {
                int  vid = int.Parse(id.Substring(0, 4), NumberStyles.HexNumber);
                int  pid = int.Parse(id.Substring(5, 4), NumberStyles.HexNumber);
                Guid guid;
                switch (DenshaDeGoInput.CurrentHost.Platform)
                {
                case OpenBveApi.Hosts.HostPlatform.MicrosoftWindows:
                    guid = new Guid(id.Substring(5, 4) + id.Substring(0, 4) + "-ffff-ffff-ffff-ffffffffffff");
                    break;

                default:
                    string vendor  = id.Substring(2, 2) + id.Substring(0, 2);
                    string product = id.Substring(7, 2) + id.Substring(5, 2);
                    guid = new Guid("ffffffff-" + vendor + "-ffff-" + product + "-ffffffffffff");
                    break;
                }
                UsbController controller = new UsbController(vid, pid);
                if (!supportedUsbControllers.ContainsKey(guid))
                {
                    // Add new controller
                    supportedUsbControllers.Add(guid, controller);
                }
                else
                {
                    // Replace existing controller
                    supportedUsbControllers[guid] = controller;
                }
            }
        }
Пример #3
0
        public NVForm()
        {
            InitializeComponent();

            usbController         = new UsbController();
            usbController.Notify += HandleDevices;
            usbController.StartWorker();

            bootloaders = Bootloader.GetBootloaders();

            foreach (var bl in bootloaders)
            {
                deviceBootloader.Items.Add(bl.Title);
            }

            if (bootloaders.Length > 0)
            {
                deviceBootloader.SelectedIndex = 0;
            }

            var random = new Random(Guid.NewGuid().GetHashCode());

            nvUnlockCode.Text = new string(Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 16)
                                           .Select(s => s[random.Next(s.Length)]).ToArray());
        }
Пример #4
0
 public static void Print()
 {
     UsbController[] controllers = UsbController.GetControllers();
     for (int i = 0; i < controllers.Length; i++)
     {
         Debug.Print("USB" + i + ": " + Convert(controllers[i].Status));
         Thread.Sleep(500);
     }
 }
        public MFTestResults CompositeDeviceTest()
        {
            MFTestResults testResult = MFTestResults.Pass;

            // Gain access to all USB controllers
            UsbController[] controllers = UsbController.GetControllers();

            // Set up all buttons to be monitored
            buttons.up    = new InputPort((Cpu.Pin) 43, true, Port.ResistorMode.Disabled);
            buttons.down  = new InputPort((Cpu.Pin) 42, true, Port.ResistorMode.Disabled);
            buttons.left  = new InputPort((Cpu.Pin) 48, true, Port.ResistorMode.Disabled);
            buttons.right = new InputPort((Cpu.Pin) 44, true, Port.ResistorMode.Disabled);
            buttons.b1    = new InputPort((Cpu.Pin) 40, true, Port.ResistorMode.Disabled);
            buttons.b2    = new InputPort((Cpu.Pin) 45, true, Port.ResistorMode.Disabled);
            buttons.b3    = new InputPort((Cpu.Pin) 46, true, Port.ResistorMode.Disabled);
            buttons.done  = new InputPort((Cpu.Pin) 47, true, Port.ResistorMode.Disabled);


            // Use the first available USB controller if it exists
            if (controllers.Length < 1)
            {
                Debug.Print("No USB controllers exist for this device - we're done!");
                return(MFTestResults.Skip);
            }
            UsbController UsbPort = controllers[0];


            // Configure the USB port and open streams to both interfaces
            if (!ConfigureMouseAndPinger(UsbPort))      // If USB configure fails, we're done
            {
                testResult = MFTestResults.Fail;
            }
            UsbStream pinger = UsbPort.CreateUsbStream(1, 2);                      // Pinger writes to endpoint 1 and reads from endpoint 2
            UsbStream mouse  = UsbPort.CreateUsbStream(3, UsbStream.NullEndpoint); // Mouse is write only to endpoint 3

            MouseAndPingerLoop(mouse, pinger);                                     // Behave like both a mouse and "TinyBooter

            // Done being a mouse and a pinger.  Start being just a pinger
            pinger.Close();
            mouse.Close();
            UsbPort.Stop();
            Thread.Sleep(500);          // Keep USB port disconnected for half a second to be sure host has seen
            if (!ConfigurePinger(UsbPort))
            {
                testResult = MFTestResults.Fail;
            }
            pinger = UsbPort.CreateUsbStream(1, 2);       // Pinger writes to endpoint 1 and reads from endpoint 2
            PingerLoop(pinger);

            // Done being just a pinger.  Start being a mouse and pinger again
            pinger.Close();
            UsbPort.Stop();
            Thread.Sleep(500);          // Keep USB port disconnected for half a second to be sure host has seen

            return(testResult);
        }
Пример #6
0
        public static IEnumerable <UsbTreeItem> TextController(int depth, UsbController controller)
        {
            var hub = controller.GetRootHub();

            yield return(new UsbTreeItem {
                Depth = depth, Value = $"H-{hub?.Name} ({hub?.Address})"
            });

            foreach (var item in UsbTreeView.TextHub(depth + 1, hub))
            {
                yield return(item);
            }
        }
Пример #7
0
        private static void ShowController(UsbController controller)
        {
            if (controller != null)
            {
                WriteLine($"Controller: [{controller.GetDescription()}]");

                foreach (UsbHub hub in controller.Hubs)
                {
                    ShowHub(hub);
                }

                Console.WriteLine();
            }
            else
            {
                WriteLine("Controller  = null");
            }
        }
        public MFTestResults CheckDescriptors()
        {
            MFTestResults result = MFTestResults.Pass;

            manufacturerIndex      = 0;
            productIndex           = 0;
            descriptorFound        = false;
            displayNameFound       = false;
            friendlyNameFound      = false;
            manufacturerNameFound  = false;
            productNameFound       = false;
            sideshowOsStringFound  = false;
            sideshowXCompatIdFound = false;

            if (config == null)                                 // If the default configuration was totally bogus
            {
                if (UsbController.GetControllers().Length == 0) // If there were no controllers
                {
                    return(MFTestResults.Skip);                 // The test should not be run
                }
                return(MFTestResults.Fail);
            }

            // These tests must be done in this order to work properly
            if (!DeviceDescriptor())
            {
                result = MFTestResults.Fail;
            }
            if (!ConfigurationDescriptor())
            {
                result = MFTestResults.Fail;
            }
            if (!StringDescriptors())
            {
                result = MFTestResults.Fail;
            }
            if (!GenericDescriptors())
            {
                result = MFTestResults.Fail;
            }

            return(result);
        }
Пример #9
0
        public NVForm()
        {
            InitializeComponent();

            usbController         = new UsbController();
            usbController.Notify += HandleDevices;
            usbController.StartWorker();

            bootloaders = Bootloader.GetBootloaders();

            foreach (var bl in bootloaders)
            {
                deviceBootloader.Items.Add(bl.Title);
            }

            if (bootloaders.Length > 0)
            {
                deviceBootloader.SelectedIndex = 0;
            }
        }
Пример #10
0
        public bool Open()
        {
            bool succeed = true;

            started = false;

            UsbController[] usbControllers = UsbController.GetControllers();

            if (usbControllers.Length < 1)
            {
                succeed = false;
            }

            if (succeed)
            {
                usbController = usbControllers[0];

                try
                {
                    succeed = ConfigureHID();

                    if (succeed)
                    {
                        succeed = usbController.Start();
                    }

                    if (succeed)
                    {
                        stream = usbController.CreateUsbStream(WRITE_ENDPOINT, READ_ENDPOINT);
                    }
                }
                catch (Exception)
                {
                    succeed = false;
                }
            }

            started = true;
            return(succeed);
        }
Пример #11
0
        /// <summary>
        /// Configures the USB port.
        /// </summary>
        /// <param name="port"></param>
        /// <param name="fAddMouse"></param>
        private static void ConfigureUsbPort(UsbController port, bool fAddMouse)
        {
            try
            {
                bool          fMouseConfigExists = false;
                Configuration configuration      = port.Configuration;
                Configuration.DeviceDescriptor        device;
                Configuration.ConfigurationDescriptor cfgDesc = null;
                int cfgDescIndex        = 0;
                int mouseInterfaceIndex = 0;

                if (configuration == null)
                {
                    configuration = new Configuration();

                    // Create the device descriptor.
                    device = new Configuration.DeviceDescriptor(0xBADA, 0x0026,
                                                                0x0100);
                    device.bcdUSB          = 0x110;
                    device.bDeviceClass    = 0;
                    device.bDeviceSubClass = 0;
                    device.bDeviceProtocol = 0;
                    device.bMaxPacketSize0 = 8;
                    device.iManufacturer   = 1; // String #1 is the manufacturer name.
                    device.iProduct        = 2; // String #2 is the product name.
                    device.iSerialNumber   = 0;
                }
                else
                {
                    for (int i = 0; i < configuration.descriptors.Length; i++)
                    {
                        if (configuration.descriptors[i] is Configuration.ConfigurationDescriptor)
                        {
                            Configuration.ConfigurationDescriptor cfg =
                                (Configuration.ConfigurationDescriptor)configuration.descriptors[i];

                            // We make the assumption here that the second
                            // interface is always a mouse.
                            for (int j = 0; j < cfg.interfaces.Length; j++)
                            {
                                if (cfg.interfaces[j].bInterfaceClass == 3 &&
                                    cfg.interfaces[j].bInterfaceProtocol == 2)
                                {
                                    fMouseConfigExists  = true;
                                    mouseInterfaceIndex = j;
                                }
                            }
                            cfgDesc =
                                (Configuration.ConfigurationDescriptor)configuration.descriptors[i];
                            break;
                        }
                        cfgDescIndex++;
                    }

                    device = configuration.descriptors[0] as
                             Configuration.DeviceDescriptor;
                }

                if (fAddMouse && !fMouseConfigExists)
                {
                    Configuration.Endpoint endpoint = new Configuration.Endpoint(
                        3, Configuration.Endpoint.ATTRIB_Interrupt |
                        Configuration.Endpoint.ATTRIB_Write);
                    endpoint.wMaxPacketSize = 8;  // Mouse data requires only eight bytes.
                    endpoint.bInterval      = 10; // Host should request data from mouse every 10 mS.

                    Configuration.Endpoint[] mouseEndpoints =
                        new Configuration.Endpoint[1] {
                        endpoint
                    };

                    // Set up the mouse interface.
                    Configuration.UsbInterface usbInterface =
                        new Configuration.UsbInterface(1, mouseEndpoints);
                    usbInterface.bInterfaceClass    = 3; // HID interface.
                    usbInterface.bInterfaceSubClass = 1; // Boot device.
                    usbInterface.bInterfaceProtocol = 2; // Standard mouse protocol.
                    usbInterface.iInterface         = 1; // Interface index.

                    // Assemble the HID class descriptor.
                    byte[] HidPayload = new byte[]
                    {
                        0x01, 0x01,     // bcdHID = HID version 1.01.
                        0x00,           // bCountryCode (unimportant).
                        0x01,           // bNumDescriptors = number of descriptors available for this device.
                        0x22,           // bDescriptorType = Report descriptor.
                        0x32, 0x00      // Total size of Report descriptor (50).
                    };

                    usbInterface.classDescriptors =
                        new Configuration.ClassDescriptor[1] {
                        new Configuration.ClassDescriptor(0x21, HidPayload)
                    };

                    if (cfgDesc == null)
                    {
                        Configuration.UsbInterface[] UsbInterfaces =
                            new Configuration.UsbInterface[1] {
                            usbInterface
                        };
                        cfgDesc = new Configuration.ConfigurationDescriptor(
                            280, UsbInterfaces);
                        mouseInterfaceIndex = 0;
                    }
                    else
                    {
                        Configuration.UsbInterface[] UsbInterfaces =
                            new Configuration.UsbInterface[cfgDesc.interfaces.Length + 1];

                        Array.Copy(cfgDesc.interfaces, UsbInterfaces,
                                   cfgDesc.interfaces.Length);

                        UsbInterfaces[UsbInterfaces.Length - 1] = usbInterface;

                        mouseInterfaceIndex = UsbInterfaces.Length - 1;

                        cfgDesc.interfaces = UsbInterfaces;
                    }

                    // Create the report descriptor as a Generic.  This data was
                    // created using...
                    byte[] BootMouseReportPayload = null;

                    BootMouseReportPayload = new byte[]
                    {
                        0x05, 0x01,  // USAGE_PAGE (Generic Desktop)
                        0x09, 0x02,  // USAGE (Mouse)
                        0xa1, 0x01,  // COLLECTION (Application)
                        0x09, 0x01,  //   USAGE (Pointer)
                        0xa1, 0x00,  //   COLLECTION (Physical)
                        0x05, 0x09,  //     USAGE_PAGE (Button)
                        0x19, 0x01,  //     USAGE_MINIMUM (Button 1)
                        0x29, 0x03,  //     USAGE_MAXIMUM (Button 3)
                        0x15, 0x00,  //     LOGICAL_MINIMUM (0)
                        0x25, 0x01,  //     LOGICAL_MAXIMUM (1)
                        0x95, 0x03,  //     REPORT_COUNT (3)
                        0x75, 0x01,  //     REPORT_SIZE (1)
                        0x81, 0x02,  //     INPUT (Data,Var,Abs)
                        0x95, 0x01,  //     REPORT_COUNT (1)
                        0x75, 0x05,  //     REPORT_SIZE (5)
                        0x81, 0x01,  //     INPUT (Cnst,Ary,Abs)
                        0x05, 0x01,  //     USAGE_PAGE (Generic Desktop)
                        0x09, 0x30,  //     USAGE (X)
                        0x09, 0x31,  //     USAGE (Y)
                        0x15, 0x81,  //     LOGICAL_MINIMUM (-127)
                        0x25, 0x7f,  //     LOGICAL_MAXIMUM (127)
                        0x75, 0x08,  //     REPORT_SIZE (8)
                        0x95, 0x02,  //     REPORT_COUNT (2)
                        0x81, 0x06,  //     INPUT (Data,Var,Rel)
                        0xc0,        //   END_COLLECTION
                        0xc0         // END_COLLECTION
                    };

                    const byte   DescriptorRequest = 0x81;
                    const byte   ReportDescriptor  = 0x22;
                    const byte   GetDescriptor     = 0x06;
                    const ushort Report_wValue     = (ushort)ReportDescriptor << 8;
                    Configuration.GenericDescriptor mouseReportDescriptor =
                        new Configuration.GenericDescriptor(DescriptorRequest,
                                                            Report_wValue, BootMouseReportPayload);
                    mouseReportDescriptor.bRequest = GetDescriptor;
                    mouseReportDescriptor.wIndex   =
                        (ushort)(mouseInterfaceIndex);  // The interface number.

                    Configuration.StringDescriptor manufacturerName;
                    Configuration.StringDescriptor productName;
                    Configuration.StringDescriptor displayName;
                    Configuration.StringDescriptor friendlyName;

                    // Create the standard strings for the USB device
                    manufacturerName = new Configuration.StringDescriptor(
                        1, "Sample Manufacturer");
                    productName = new Configuration.StringDescriptor(
                        2, "Micro Framework Mouse Sample");
                    displayName = new Configuration.StringDescriptor(
                        4, "Micro Framework Mouse");
                    friendlyName = new Configuration.StringDescriptor(
                        5, "NetMF_Mouse");

                    if (configuration.descriptors == null)
                    {
                        configuration.descriptors =
                            new Configuration.Descriptor[]
                        {
                            device,
                            cfgDesc,
                            manufacturerName,
                            productName,
                            displayName,
                            friendlyName,
                            mouseReportDescriptor
                        };
                    }
                    else
                    {
                        int descLength = configuration.descriptors.Length;

                        Configuration.Descriptor[] descriptors =
                            new Configuration.Descriptor[descLength + 1];

                        Array.Copy(configuration.descriptors, descriptors,
                                   descLength);

                        descriptors[cfgDescIndex] = cfgDesc;
                        descriptors[descLength]   = mouseReportDescriptor;

                        configuration.descriptors = descriptors;
                    }
                }
                else if (!fAddMouse && fMouseConfigExists)
                {
                    Configuration.UsbInterface[] UsbInterfaces =
                        new Configuration.UsbInterface[cfgDesc.interfaces.Length - 1];

                    Array.Copy(cfgDesc.interfaces, UsbInterfaces,
                               cfgDesc.interfaces.Length - 1);

                    // Make sure we are removing the correct interface.
                    if (mouseInterfaceIndex != (cfgDesc.interfaces.Length - 1))
                    {
                        cfgDesc.interfaces[mouseInterfaceIndex] =
                            cfgDesc.interfaces[cfgDesc.interfaces.Length - 1];
                    }

                    cfgDesc.interfaces = UsbInterfaces;

                    configuration.descriptors[cfgDescIndex] = cfgDesc;
                }

                port.Stop();

                // Give the PC some time to unload the driver.
                Thread.Sleep(500);

                port.Configuration = configuration;

                if (port.ConfigurationError !=
                    UsbController.ConfigError.ConfigOK)
                {
                    Debug.Print("Compound configuration reported an error " +
                                port.ConfigurationError.ToString());
                }

                // Kick the USB controller into action.
                if (!port.Start())
                {
                    Debug.Print("Compound USB could not be started.");
                }
            }
            catch (ArgumentException)
            {
                try
                {
                    // Try to recover from a bad USB configuration.
                    port.Configuration = null;
                    port.Start();
                }
                catch
                {
                }

                Debug.Print("Couldn't configure Compound USB due to error " +
                            port.ConfigurationError.ToString());
            }
        }
Пример #12
0
        public static void Main()
        {
            Debug.Print("\n\n");
            Debug.Print("Hello world - i'm trying to find what are hidden to this firmware ");
            Debug.Print("\n\n");

            HardwareProvider provider = HardwareProvider.HwProvider;

            var cnt = provider.GetAnalogChannelsCount();

            for (int i = 0; i < cnt; i++)
            {
                var     channel    = (Cpu.AnalogChannel)i;
                Cpu.Pin pin        = provider.GetAnalogPinForChannel(channel);
                int[]   precisions = provider.GetAvailablePrecisionInBitsForChannel(channel);

                Debug.Print("AnalogChannel" + channel + ": pin=" + pin.ToString() + "(" + STM32F411RE.Hardware.Pin.GetPinName(pin) + "): precisions=" + precisions[0].ToString() + " bit");
            }
            Debug.Print("\n\n");

            cnt = 0;
            cnt = provider.GetAnalogOutputChannelsCount();
            for (int i = 0; i < cnt; i++)
            {
                var     channel    = (Cpu.AnalogOutputChannel)i;
                Cpu.Pin pin        = provider.GetAnalogOutputPinForChannel(channel);
                int[]   precisions = provider.GetAvailableAnalogOutputPrecisionInBitsForChannel(channel);

                Debug.Print("AnalogOutputChannel" + ": pin=" + pin.ToString() + "(" + STM32F411RE.Hardware.Pin.GetPinName(pin) + "): precisions=" + precisions[0].ToString() + " bit");
            }
            Debug.Print("\n\n");

            /* find pwm */
            cnt = 0;
            cnt = provider.GetPWMChannelsCount();
            for (int i = 0; i < cnt; i++)
            {
                var     channel = (Cpu.PWMChannel)i;
                Cpu.Pin pin     = provider.GetPwmPinForChannel(channel);
                Debug.Print("PWMChannel" + channel + ": pin=" + pin.ToString() + "(" + STM32F411RE.Hardware.Pin.GetPinName(pin) + ")");
            }
            Debug.Print("\n\n");

            /*find uart */
            cnt = 0;
            cnt = provider.GetSerialPortsCount();
            for (int i = 0; i < cnt; i++)
            {
                string  comPort = Serial.COM1.Substring(0, 3) + (i + 1);
                Cpu.Pin rxPin, txPin, ctsPin, rtsPin;
                provider.GetSerialPins(comPort, out rxPin, out txPin, out ctsPin, out rtsPin);
                uint max, min;
                provider.GetBaudRateBoundary(i, out max, out min);

                Debug.Print(comPort + ": (rx, tx, cts, rts)=(" +
                            STM32F411RE.Hardware.Pin.GetPinName(rxPin) + ", " +
                            STM32F411RE.Hardware.Pin.GetPinName(txPin) + ", " +
                            STM32F411RE.Hardware.Pin.GetPinName(ctsPin) + ", " +
                            STM32F411RE.Hardware.Pin.GetPinName(rtsPin) + ")" +
                            " baud=" + min + "..." + max);
            }
            Debug.Print("\n\n");
            /* find i2c */
            Cpu.Pin i2cscl, i2csda;
            provider.GetI2CPins(out i2cscl, out i2csda);
            Debug.Print("I2C module:(scl value=" + i2cscl.ToString() + "(" + STM32F411RE.Hardware.Pin.GetPinName(i2cscl) + "),sda=" + i2csda.ToString() + "(" + STM32F411RE.Hardware.Pin.GetPinName(i2csda) + "));");
            Debug.Print("\n\n");

            /* find SPI */
            var spicnt = provider.GetSpiPortsCount();

            for (int i = 0; i < spicnt; i++)
            {
                var module = (SPI.SPI_module)i;

                Cpu.Pin msk, miso, mosi;
                provider.GetSpiPins(module, out msk, out miso, out mosi);
                Debug.Print("SPI_module" + (i + 1) + ": (msk=" + msk.ToString() + "(" + STM32F411RE.Hardware.Pin.GetPinName(msk) + "), miso=" + miso.ToString() + "(" + STM32F411RE.Hardware.Pin.GetPinName(miso) + "), mosi=" + mosi.ToString() + "(" + STM32F411RE.Hardware.Pin.GetPinName(mosi) + "));");
            }
            Debug.Print("\n\n");

            UsbController[] controllers = UsbController.GetControllers();
            for (int i = 0; i < controllers.Length; i++)
            {
                Debug.Print("USB" + i + ": " + Convert(controllers[i].Status));
                Thread.Sleep(500);
            }

            Debug.Print("\n\n");
            Debug.Print("Finished check of hardware ");
        }
        static bool ConfigurePinger(UsbController port)
        {
            UsbController.PortState portState = port.Status;

            if (portState != UsbController.PortState.Stopped)
            {
                Debug.Print("The controller has already been initialized and is in state " + portState.ToString() + ".");
                // return false;
            }

            // Create the device descriptor
            Configuration.DeviceDescriptor device = new Configuration.DeviceDescriptor(0x15A2, 0x0026, 0x0100);
            device.iManufacturer = 1;      // String 1 is the manufacturer name
            device.iProduct      = 2;      // String 2 is the product name
            device.bcdUSB        = 0x0200; // USB version 2.00

            // Create the simple configuration descriptor
            Configuration.Endpoint endpoint1 = new Configuration.Endpoint(1, Configuration.Endpoint.ATTRIB_Bulk | Configuration.Endpoint.ATTRIB_Write);
            Configuration.Endpoint endpoint2 = new Configuration.Endpoint(2, Configuration.Endpoint.ATTRIB_Bulk | Configuration.Endpoint.ATTRIB_Read);
            endpoint1.wMaxPacketSize = 64;
            endpoint2.wMaxPacketSize = 64;      // Pinger endpoints use the maximum allowable buffer
            Configuration.Endpoint[] endpoints = new Configuration.Endpoint[2] {
                endpoint1, endpoint2
            };
            // Assign the endpoints to the interface and set up the interface fields
            Configuration.UsbInterface UsbInterface0 = new Configuration.UsbInterface(0, endpoints);
            UsbInterface0.bInterfaceClass    = 0xFF; // Vendor class
            UsbInterface0.bInterfaceSubClass = 1;
            UsbInterface0.bInterfaceProtocol = 1;
            // Finish by assigning the interfaces to the configuration descriptor
            Configuration.UsbInterface[] UsbInterfaces = new Configuration.UsbInterface[1] {
                UsbInterface0
            };
            Configuration.ConfigurationDescriptor config = new Configuration.ConfigurationDescriptor(280, UsbInterfaces);

            // Create the standard strings needed for the iMXS board Pinger
            Configuration.StringDescriptor manufacturerName = new Configuration.StringDescriptor(1, "Freescale");
            Configuration.StringDescriptor productName      = new Configuration.StringDescriptor(2, "Micro Framework MXS Reference ");
            Configuration.StringDescriptor displayName      = new Configuration.StringDescriptor(4, "iMXS");
            Configuration.StringDescriptor friendlyName     = new Configuration.StringDescriptor(5, "a7e70ea2");

            // Create the Sideshow OS String descriptor as if it were a standard string descriptor
            Configuration.StringDescriptor OS_StringDescriptor = new Configuration.StringDescriptor(0xEE, "MSFT100\xA5");

            // Create the Sideshow OS Extended Compatible ID Descriptor as a Generic
            byte[] compatibleIdPayload = new byte[]
            {
                40, 0, 0, 0,                                                                    // Size of the payload
                00, 1,                                                                          // Version 1.00
                04, 0,                                                                          // OS Compatible ID request
                1,                                                                              // Interface count
                0, 0, 0, 0, 0, 0, 0,                                                            // padding (7 zeros)

                0,                                                                              // Interface number
                1,                                                                              // reserved
                (byte)'S', (byte)'I', (byte)'D', (byte)'E', (byte)'S', (byte)'H', (byte)'W', 0, // Compatible ID
                (byte)'E', (byte)'N', (byte)'H', (byte)'V', (byte)'1', 0, 0, 0,                 // Sub-compatible ID
                0, 0, 0, 0, 0, 0                                                                // padding (6 zeros)
            };
            // Assign the payload to the generic and fill in the generic descriptor fields
            const byte RequestType          = Configuration.GenericDescriptor.REQUEST_IN | Configuration.GenericDescriptor.REQUEST_Vendor;
            const byte RequestCommand       = 0xA5;
            const byte XCompatibleOsRequest = 4;

            Configuration.GenericDescriptor XCompatibleOsDescriptor = new Configuration.GenericDescriptor(RequestType, 0, compatibleIdPayload);
            XCompatibleOsDescriptor.bRequest = RequestCommand;
            XCompatibleOsDescriptor.wIndex   = XCompatibleOsRequest;

            // Now assemble all of these descriptors into the final configuration
            Configuration simpleConfig = new Configuration();

            simpleConfig.descriptors = new Configuration.Descriptor[]
            {
                device,
                config,
                manufacturerName,
                productName,
                displayName,
                friendlyName,
                OS_StringDescriptor,
                XCompatibleOsDescriptor,
            };

            try
            {
                // Set the configuration to the USB Controller
                port.Configuration = simpleConfig;

                if (port.ConfigurationError != UsbController.ConfigError.ConfigOK)
                {
                    Debug.Print("Simple configuration reported an error " + port.ConfigurationError.ToString());
                    return(false);
                }

                // Kick the USB Controller into action
                if (!port.Start())
                {
                    Debug.Print("Simple USB could not be started.");
                    return(false);
                }
            }
            catch (ArgumentException)
            {
                Debug.Print("Couldn't configure Simple USB due to error " + port.ConfigurationError.ToString());
                return(false);
            }

            const int MaxTenths = 20;       // Wait up to two seconds for controller to finish handshake
            int       tenths;

            for (tenths = 0; tenths < MaxTenths; tenths++)
            {
                if (port.Status == UsbController.PortState.Running)     // If host has finished with handshake
                {
                    break;
                }
                System.Threading.Thread.Sleep(100);
            }
            if (tenths < MaxTenths)
            {
                return(true);
            }

            Debug.Print("After " + MaxTenths.ToString() + " tenths of a second, Simple USB still had status of " + port.Status.ToString());
            return(false);
        }
        static bool ConfigureMouseAndPinger(UsbController port)
        {
            UsbController.PortState portState = port.Status;

            if (portState != UsbController.PortState.Stopped)
            {
                Debug.Print("The controller has already been initialized and is in state " + portState.ToString() + ".");
                // return false;
            }

            // Create the device descriptor
            Configuration.DeviceDescriptor device = new Configuration.DeviceDescriptor(0x15A2, 0x0026, 0x0100);
            device.iManufacturer = 1;     // String 1 is the manufacturer name
            device.iProduct      = 2;     // String 2 is the product name
            device.bcdUSB        = 0x200; // USB version 2.00

            // Create the compound configuration descriptor
            Configuration.Endpoint endpoint1 = new Configuration.Endpoint(1, Configuration.Endpoint.ATTRIB_Bulk | Configuration.Endpoint.ATTRIB_Write);
            Configuration.Endpoint endpoint2 = new Configuration.Endpoint(2, Configuration.Endpoint.ATTRIB_Bulk | Configuration.Endpoint.ATTRIB_Read);
            Configuration.Endpoint endpoint3 = new Configuration.Endpoint(3, Configuration.Endpoint.ATTRIB_Interrupt | Configuration.Endpoint.ATTRIB_Write);
            endpoint1.wMaxPacketSize = 64;
            endpoint2.wMaxPacketSize = 64; // Pinger endpoints use the maximum allowable buffer
            endpoint3.wMaxPacketSize = 8;  // Mouse data requires only eight bytes
            endpoint3.bInterval      = 10; // Host should request data from mouse every 10 mS
            Configuration.Endpoint[] pingerEndpoints = new Configuration.Endpoint[2] {
                endpoint1, endpoint2
            };
            Configuration.Endpoint[] mouseEndpoints = new Configuration.Endpoint[1] {
                endpoint3
            };
            // Set up the Pinger interface
            Configuration.UsbInterface UsbInterface0 = new Configuration.UsbInterface(0, pingerEndpoints);
            UsbInterface0.bInterfaceClass    = 0xFF; // Vendor class
            UsbInterface0.bInterfaceSubClass = 1;
            UsbInterface0.bInterfaceProtocol = 1;
            // Set up the Mouse interface
            Configuration.UsbInterface UsbInterface1 = new Configuration.UsbInterface(1, mouseEndpoints);
            UsbInterface1.bInterfaceClass    = 3; // HID interface
            UsbInterface1.bInterfaceSubClass = 1; // Boot device
            UsbInterface1.bInterfaceProtocol = 2; // Standard mouse protocol
            // Assemble the HID class descriptor
            byte[] HidPayload = new byte[]
            {
                0x01, 0x01,     // bcdHID = HID version 1.01
                0x00,           // bCountryCode (unimportant)
                0x01,           // bNumDescriptors = number of descriptors available for this device
                0x22,           // bDescriptorType = Report descriptor
                0x32, 0x00      // Total size of Report descriptor (50)
            };
            UsbInterface1.classDescriptors    = new Configuration.ClassDescriptor[1];
            UsbInterface1.classDescriptors[0] = new Configuration.ClassDescriptor(0x21, HidPayload);
            Configuration.UsbInterface[] UsbInterfaces = new Configuration.UsbInterface[2] {
                UsbInterface0, UsbInterface1
            };
            Configuration.ConfigurationDescriptor config = new Configuration.ConfigurationDescriptor(280, UsbInterfaces);

            // Create the report descriptor as a Generic
            // This data was created using
            byte[] BootMouseReportPayload = new byte[]
            {
                0x05, 0x01,                    // USAGE_PAGE (Generic Desktop)
                0x09, 0x02,                    // USAGE (Mouse)
                0xa1, 0x01,                    // COLLECTION (Application)
                0x09, 0x01,                    //   USAGE (Pointer)
                0xa1, 0x00,                    //   COLLECTION (Physical)
                0x05, 0x09,                    //     USAGE_PAGE (Button)
                0x19, 0x01,                    //     USAGE_MINIMUM (Button 1)
                0x29, 0x03,                    //     USAGE_MAXIMUM (Button 3)
                0x15, 0x00,                    //     LOGICAL_MINIMUM (0)
                0x25, 0x01,                    //     LOGICAL_MAXIMUM (1)
                0x95, 0x03,                    //     REPORT_COUNT (3)
                0x75, 0x01,                    //     REPORT_SIZE (1)
                0x81, 0x02,                    //     INPUT (Data,Var,Abs)
                0x95, 0x01,                    //     REPORT_COUNT (1)
                0x75, 0x05,                    //     REPORT_SIZE (5)
                0x81, 0x01,                    //     INPUT (Cnst,Ary,Abs)
                0x05, 0x01,                    //     USAGE_PAGE (Generic Desktop)
                0x09, 0x30,                    //     USAGE (X)
                0x09, 0x31,                    //     USAGE (Y)
                0x15, 0x81,                    //     LOGICAL_MINIMUM (-127)
                0x25, 0x7f,                    //     LOGICAL_MAXIMUM (127)
                0x75, 0x08,                    //     REPORT_SIZE (8)
                0x95, 0x02,                    //     REPORT_COUNT (2)
                0x81, 0x06,                    //     INPUT (Data,Var,Rel)
                0xc0,                          //     END_COLLECTION
                0xc0                           // END_COLLECTION
            };
            const byte   DescriptorRequest = 0x81;
            const byte   ReportDescriptor  = 0x22;
            const byte   GetDescriptor     = 0x06;
            const ushort Report_wValue     = (ushort)ReportDescriptor << 8;

            Configuration.GenericDescriptor mouseReportDescriptor = new Configuration.GenericDescriptor(DescriptorRequest, Report_wValue, BootMouseReportPayload);
            mouseReportDescriptor.bRequest = GetDescriptor;
            mouseReportDescriptor.wIndex   = 1;      // The interface number

            // Create the standard strings needed for the iMXS board Pinger
            Configuration.StringDescriptor manufacturerName = new Configuration.StringDescriptor(1, "Freescale");
            Configuration.StringDescriptor productName      = new Configuration.StringDescriptor(2, "Micro Framework MXS Reference ");
            Configuration.StringDescriptor displayName      = new Configuration.StringDescriptor(4, "iMXS");
            Configuration.StringDescriptor friendlyName     = new Configuration.StringDescriptor(5, "a7e70ea2");

            // Create the Sideshow OS String descriptor as if it were a standard string descriptor
            Configuration.StringDescriptor OS_StringDescriptor = new Configuration.StringDescriptor(0xEE, "MSFT100\xA5");

            // Create the Sideshow OS Extended Compatible ID Descriptor as a Generic
            byte[] compatibleIdPayload = new byte[]
            {
                40, 0, 0, 0,                                                                    // Size of the payload
                00, 1,                                                                          // Version 1.00
                04, 0,                                                                          // OS Compatible ID request
                1,                                                                              // Interface count
                0, 0, 0, 0, 0, 0, 0,                                                            // padding (7 zeros)

                0,                                                                              // Interface number
                1,                                                                              // reserved
                (byte)'S', (byte)'I', (byte)'D', (byte)'E', (byte)'S', (byte)'H', (byte)'W', 0, // Compatible ID
                (byte)'E', (byte)'N', (byte)'H', (byte)'V', (byte)'1', 0, 0, 0,                 // Sub-compatible ID
                0, 0, 0, 0, 0, 0                                                                // padding (6 zeros)
            };
            // Create the report descriptor as a Generic
            const byte RequestType          = Configuration.GenericDescriptor.REQUEST_IN | Configuration.GenericDescriptor.REQUEST_Vendor;
            const byte RequestCommand       = 0xA5;
            const byte XCompatibleOsRequest = 4;

            Configuration.GenericDescriptor XCompatibleOsDescriptor = new Configuration.GenericDescriptor(RequestType, 0, compatibleIdPayload);
            XCompatibleOsDescriptor.bRequest = RequestCommand;
            XCompatibleOsDescriptor.wIndex   = XCompatibleOsRequest;

            // Now assemble all of these descriptors into the final configuration
            Configuration compoundConfig = new Configuration();

            compoundConfig.descriptors = new Configuration.Descriptor[]
            {
                device,
                config,
                manufacturerName,
                productName,
                displayName,
                friendlyName,
                OS_StringDescriptor,
                XCompatibleOsDescriptor,
                mouseReportDescriptor
            };

            try
            {
                // Set the configuration to the USB Controller
                port.Configuration = compoundConfig;

                if (port.ConfigurationError != UsbController.ConfigError.ConfigOK)
                {
                    Debug.Print("Compound configuration reported an error " + port.ConfigurationError.ToString());
                    return(false);
                }

                // Kick the USB Controller into action
                if (!port.Start())
                {
                    Debug.Print("Compound USB could not be started.");
                    return(false);
                }
            }
            catch (ArgumentException)
            {
                Debug.Print("Couldn't configure Compound USB due to error " + port.ConfigurationError.ToString());
                return(false);
            }

            const int MaxTenths = 20;       // Wait up to two seconds for controller to finish handshake
            int       tenths;

            for (tenths = 0; tenths < MaxTenths; tenths++)
            {
                if (port.Status == UsbController.PortState.Running)     // If host has finished with handshake
                {
                    break;
                }
                System.Threading.Thread.Sleep(100);
            }
            if (tenths < MaxTenths)
            {
                return(true);
            }

            Debug.Print("After " + MaxTenths.ToString() + " tenths of a second, Compound USB still had status of " + port.Status.ToString());
            return(false);
        }
Пример #15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="port"></param>
        /// <param name="mouse"></param>
        static void MouseLoop(UsbController port, UsbStream mouse)
        {
            // Mouse report storage.
            byte[] report = new byte[5];

            // Offsets into mouse report storage.
            const byte BUTTONS    = 0;
            const byte X_MOVEMENT = 1;
            const byte Y_MOVEMENT = 2;

            // Size of mouse movement for each report (every 10 mS).
            const byte mouseStep = 3;
            bool       fAddMouse = true;

            // While the Done button is not pressed...
            while (buttons.Done.Read())
            {
                // Perform this operation once every 10 milliseconds (actually a
                // bit more than 10 milliseconds).  We've asked the host to
                // query for mouse info at least every 10 milliseconds, but it
                // actually queries every 8 milliseconds - it's OK not to
                // respond to every query.
                Thread.Sleep(10);

                report[X_MOVEMENT] = 0;      // Zero X movement
                report[Y_MOVEMENT] = 0;      // Zero Y movement

                // Add X,Y movement to the mouse report.
                if (!buttons.Left.Read())
                {
                    report[X_MOVEMENT] -= mouseStep;
                }
                if (!buttons.Right.Read())
                {
                    report[X_MOVEMENT] += mouseStep;
                }
                if (!buttons.Up.Read())
                {
                    report[Y_MOVEMENT] -= mouseStep;
                }
                if (!buttons.Down.Read())
                {
                    report[Y_MOVEMENT] += mouseStep;
                }

                if (!buttons.Toggle.Read())
                {
                    if (mouse != null)
                    {
                        mouse.Dispose();
                        mouse = null;
                    }

                    fAddMouse = !fAddMouse;

                    ConfigureUsbPort(port, fAddMouse);

                    if (fAddMouse)
                    {
                        mouse = port.CreateUsbStream(3, UsbStream.NullEndpoint);
                    }
                }

                // Add the button state to the mouse report.
                report[BUTTONS] = (byte)((!buttons.LeftMouseButton.Read() ?
                                          1 : 0) | (!buttons.RightMouseButton.Read() ? 2 : 0));

                if (mouse != null)
                {
                    // Send the mouse report to the host.
                    mouse.Write(report, 0, 3);
                }
            }

            // Wait for the Done button to be released.
            while (!buttons.Done.Read())
            {
                ;
            }
        }
Пример #16
0
        private static bool ConfigureUSBController(UsbController usbController)
        {
            bool bRet = false;


            // Create the device descriptor


            Configuration.DeviceDescriptor device = new Configuration.DeviceDescriptor(0xDEAD, 0x0110, 0x0200);
            device.bcdUSB          = 0x110;
            device.bDeviceClass    = 0xFF; // Vendor defined class
            device.bDeviceSubClass = 0xFF; // Vendor defined subclass
            device.bDeviceProtocol = 0;
            device.bMaxPacketSize0 = 8;    // Maximum packet size of EP0
            device.iManufacturer   = 1;    // String #1 is manufacturer name (see string descriptors below)
            device.iProduct        = 2;    // String #2 is product name
            device.iSerialNumber   = 3;    // String #3 is the serial number

            // Create the endpoints
            Configuration.Endpoint writeEP = new Configuration.Endpoint(WRITE_EP, Configuration.Endpoint.ATTRIB_Write | Configuration.Endpoint.ATTRIB_Bulk | Configuration.Endpoint.ATTRIB_Synchronous);//Configuration.Endpoint.ATTRIB_Bulk | Configuration.Endpoint.ATTRIB_Write);
            writeEP.wMaxPacketSize = 64;
            writeEP.bInterval      = 0;


            Configuration.Endpoint readEP = new Configuration.Endpoint(READ_EP, Configuration.Endpoint.ATTRIB_Read | Configuration.Endpoint.ATTRIB_Bulk | Configuration.Endpoint.ATTRIB_Synchronous);// Configuration.Endpoint.ATTRIB_Bulk | Configuration.Endpoint.ATTRIB_Read);
            readEP.wMaxPacketSize = 64;
            readEP.bInterval      = 0;

            Configuration.Endpoint[] usbEndpoints = new Configuration.Endpoint[] { writeEP, readEP };

            // Set up the USB interface
            Configuration.UsbInterface usbInterface = new Configuration.UsbInterface(0, usbEndpoints);
            usbInterface.bInterfaceClass    = 0xFF; // Vendor defined class
            usbInterface.bInterfaceSubClass = 0xFF; // Vendor defined subclass
            usbInterface.bInterfaceProtocol = 0;

            // Create array of USB interfaces
            Configuration.UsbInterface[] usbInterfaces = new Configuration.UsbInterface[] { usbInterface };

            // Create configuration descriptor
            Configuration.ConfigurationDescriptor config = new Configuration.ConfigurationDescriptor(200, usbInterfaces);

            // Create the string descriptors
            Configuration.StringDescriptor manufacturerName = new Configuration.StringDescriptor(1, "YourName");
            Configuration.StringDescriptor productName      = new Configuration.StringDescriptor(2, "YourProductName");
            Configuration.StringDescriptor serialNumber     = new Configuration.StringDescriptor(3, "0000-0" + USB.SerialNumber.Substring(0, 3) + "-" + USB.SerialNumber.Substring(3, 4) + "-" + USB.SerialNumber.Substring(7, 4));
            Configuration.StringDescriptor displayName      = new Configuration.StringDescriptor(4, "YourDisplayName");
            Configuration.StringDescriptor friendlyName     = new Configuration.StringDescriptor(5, "YourFriendlyName");

            // Create the final configuration
            Configuration configuration = new Configuration();

            configuration.descriptors = new Configuration.Descriptor[] {
                device,
                config,
                manufacturerName,
                productName,
                serialNumber,
                displayName,
                friendlyName
            };
            try
            {
                // Set the configuration
                usbController.Configuration = configuration;

                if (UsbController.ConfigError.ConfigOK != usbController.ConfigurationError)
                {
                    throw new ArgumentException();
                }

                // If all ok, start the USB controller.
                bRet = usbController.Start();
            }
            catch (ArgumentException)
            {
                Debug.Print("Can't configure USB controller, error " + usbController.ConfigurationError.ToString());
            }


            return(bRet);
        }
Пример #17
0
        public static bool Init()
        {
            Cdc vsp = new Cdc();

            //activedevice is null
            Controller.ActiveDevice = vsp;

            // Send "Hello world!" to PC every second. (Append a new line too)
            //byte[] bytes = System.Text.Encoding.UTF8.GetBytes("Hello world!\r\n");
            while (true)
            {
                // Check if connected to PC
                if (Controller.State !=
                    UsbController.PortState.Running)
                {
                    Debug.Print("Waiting to connect to PC...");
                }
                else
                {
                    break;
                }
                //else
                //{
                //    vsp.Stream.Write(bytes, 0, bytes.Length);
                //}
                Thread.Sleep(500);
            }

            // See if the hardware supports USB
            UsbController[] controllers = UsbController.GetControllers();
            // Bail out if USB is not supported on this hardware!
            if (0 == controllers.Length)
            {
                Debug.Print("USB is not supported on this hardware!");
                return(false);
            }

            foreach (UsbController controller in controllers)
            {
                if (controller.Status != UsbController.PortState.Stopped)
                {
                    controller.Stop();
                    Thread.Sleep(1000);
                }
            }

            // Find a free USB controller
            UsbController usbController = null;

            foreach (UsbController controller in controllers)
            {
                if (controller.Status == UsbController.PortState.Stopped)
                {
                    usbController = controller;
                    break;
                }
            }
            // If no free USB controller
            if (null == usbController)
            {
                Debug.Print("All available USB controllers already in use. Set the device to use Ethernet or Serial debugging.");
                return(false);
            }

            try
            {   // Configure the USB controller
                if (ConfigureUSBController(usbController))
                {
                    usbStream              = usbController.CreateUsbStream(WRITE_EP, READ_EP);
                    usbStream.ReadTimeout  = 60000;
                    usbStream.WriteTimeout = 60000;
                }
                else
                {
                    throw new Exception();
                }
            }
            catch (Exception)
            {
                Debug.Print("USB stream could not be created, error " + usbController.ConfigurationError.ToString());
                return(false);
            }

            return(true);
        }
 public DefaultUSB()
 {
     controllers = UsbController.GetControllers();
 }
Пример #19
0
        /// <summary>
        /// Execution entry point.
        /// </summary>
        public static void Main()
        {
            // Gain access to all USB controllers.
            UsbController[] controllers = UsbController.GetControllers();

            HardwareProvider hwProvider = new HardwareProvider();

            // Set up all buttons to be monitored.
            buttons.Up = new InputPort(hwProvider.GetButtonPins(Button.VK_UP),
                                       true, Port.ResistorMode.Disabled);
            buttons.Down = new InputPort(hwProvider.GetButtonPins(Button.VK_DOWN),
                                         true, Port.ResistorMode.Disabled);
            buttons.Left = new InputPort(hwProvider.GetButtonPins(Button.VK_LEFT),
                                         true, Port.ResistorMode.Disabled);
            buttons.Right = new InputPort(hwProvider.GetButtonPins(Button.VK_RIGHT),
                                          true, Port.ResistorMode.Disabled);
            buttons.LeftMouseButton = new InputPort(hwProvider.GetButtonPins(Button.VK_BACK),
                                                    true, Port.ResistorMode.Disabled);
            buttons.RightMouseButton = new InputPort(hwProvider.GetButtonPins(Button.VK_HOME),
                                                     true, Port.ResistorMode.Disabled);
            buttons.Toggle = new InputPort(hwProvider.GetButtonPins(Button.VK_SELECT),
                                           true, Port.ResistorMode.Disabled);
            buttons.Done = new InputPort(hwProvider.GetButtonPins(Button.VK_MENU),
                                         true, Port.ResistorMode.Disabled);

            // Use the first available USB controller, if it exists.
            if (controllers.Length < 1)
            {
                Debug.Print("No USB controllers exist for this device - we're done.");
                return;
            }
            UsbController UsbPort     = controllers[0];
            UsbStream     mouseStream = null;

            if (UsbPort.Status == UsbController.PortState.Running)
            {
                Debug.Print(
                    "USB controller 0 is up and running - are you debugging with USB?");

                Debug.Print(
                    "Make sure your platform supports overriding the debug transport.");

                Thread.Sleep(500);
            }

            try
            {
                ConfigureUsbPort(UsbPort, true);

                mouseStream = UsbPort.CreateUsbStream(3, UsbStream.NullEndpoint);
            }
            catch (Exception e)
            {
                Debug.Print(
                    "Mouse stream could not be created due to exception " +
                    e.Message);
                Debug.Print(
                    "Perhaps your native configuration does not contain endpoint 3?");
                return;
            }

            // Be a mouse until the Done button is pressed.
            MouseLoop(UsbPort, mouseStream);

            mouseStream.Close();
        }
Пример #20
0
        /// <summary>Return a list of USB Host Controllers</summary>
        /// <returns>List of USB Host Controllers</returns>
        static IEnumerable <UsbController> GetHostControllers()
        {
            List <UsbController> hostList = new List <UsbController>();
            var hostGuid = new Guid(GUID_DEVINTERFACE_HUBCONTROLLER);

            // We start at the "root" of the device tree and look for all
            // devices that match the interface GUID of a Hub Controller
            IntPtr h = SetupDiGetClassDevs(ref hostGuid, 0, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);

            if (h == INVALID_HANDLE_VALUE)
            {
                return(new ReadOnlyCollection <UsbController>(hostList));
            }

            IntPtr ptrBuf = Marshal.AllocHGlobal(BUFFER_SIZE);
            bool   success;
            int    i = 0;

            do
            {
                var host = new UsbController
                {
                    ControllerIndex = i
                };

                // create a Device Interface Data structure
                var dia = new SpDeviceInterfaceData();
                dia.cbSize = Marshal.SizeOf(dia);

                // start the enumeration
                success = SetupDiEnumDeviceInterfaces(h, IntPtr.Zero, ref hostGuid, i, ref dia);

                if (success)
                {
                    // build a DevInfo Data structure
                    var da = new SpDevinfoData();
                    da.cbSize = Marshal.SizeOf(da);

                    // build a Device Interface Detail Data structure
                    var didd = new SpDeviceInterfaceDetailData
                    {
                        cbSize = 4 + Marshal.SystemDefaultCharSize
                    };

                    // trust me :)

                    // now we can get some more detailed information
                    int       nRequiredSize = 0;
                    const int N_BYTES       = BUFFER_SIZE;

                    if (SetupDiGetDeviceInterfaceDetail(h, ref dia, ref didd, N_BYTES, ref nRequiredSize, ref da))
                    {
                        host.ControllerDevicePath = didd.DevicePath;

                        // get the Device Description and DriverKeyName
                        int requiredSize = 0;
                        int regType      = REG_SZ;

                        if (SetupDiGetDeviceRegistryProperty(h, ref da, SPDRP_DEVICEDESC, ref regType, ptrBuf,
                                                             BUFFER_SIZE, ref requiredSize))
                        {
                            host.ControllerDeviceDesc = Marshal.PtrToStringAuto(ptrBuf);
                        }

                        if (SetupDiGetDeviceRegistryProperty(h, ref da, SPDRP_DRIVER, ref regType, ptrBuf, BUFFER_SIZE,
                                                             ref requiredSize))
                        {
                            host.ControllerDriverKeyName = Marshal.PtrToStringAuto(ptrBuf);
                        }
                    }

                    hostList.Add(host);
                }

                i++;
            } while(success);

            Marshal.FreeHGlobal(ptrBuf);
            SetupDiDestroyDeviceInfoList(h);

            // convert it into a Collection
            return(new ReadOnlyCollection <UsbController>(hostList));
        }
Пример #21
0
 public USB()
 {
     controllers = UsbController.GetControllers();
 }