diff --git a/src/Device.Net.LibUsb/LibUsbDevice.cs b/src/Device.Net.LibUsb/LibUsbDevice.cs index be0d5eb5..5489cd65 100644 --- a/src/Device.Net.LibUsb/LibUsbDevice.cs +++ b/src/Device.Net.LibUsb/LibUsbDevice.cs @@ -145,6 +145,27 @@ await Task.Run(() => } } + //TODO: make async? + //TODO: setupPacket not exposed + public uint SendControlOutTransfer(UsbSetupPacket setupPacket, byte[] buffer) + { + if (buffer != null && buffer.Length > 0) + { + UsbDevice.ControlTransfer(ref setupPacket, buffer, buffer.Length, out var length); + return (uint)length; + } + return 0; + } + + //TODO: make async? + //TODO: setupPacket not exposed + public uint SendControlInTransfer(UsbSetupPacket setupPacket) + { + var buffer = Array.Empty(); + UsbDevice.ControlTransfer(ref setupPacket, buffer, buffer.Length, out var length); + return (uint)length; + } + #endregion #region Public Static Methods diff --git a/src/Device.Net.UnitTests/IntegrationTestControlTransfer.cs b/src/Device.Net.UnitTests/IntegrationTestControlTransfer.cs new file mode 100644 index 00000000..457af505 --- /dev/null +++ b/src/Device.Net.UnitTests/IntegrationTestControlTransfer.cs @@ -0,0 +1,120 @@ +#if !NET45 + +using Microsoft.Extensions.Logging; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Usb.Net; +using Usb.Net.Windows; +namespace Device.Net.UnitTests +{ + [TestClass] + public class IntegrationTestControlTransfer + { + [TestMethod] + public async Task Get_status_from_DFU_device_using_contol_transfer() + { + //Note: creating a LoggerFactory like this is easier than creating a mock + var loggerFactory = LoggerFactory.Create((builder) => + { + _ = builder.AddDebug().SetMinimumLevel(LogLevel.Trace); + }); + + var factory = new WindowsUsbDeviceFactory(loggerFactory); + var deviceManager = new DeviceManager(loggerFactory); + deviceManager.DeviceFactories.Add(factory); + + //Get the filtered devices + var devices = await deviceManager.GetDevicesAsync(new List + { + new FilterDeviceDefinition + { + DeviceType= DeviceType.Usb, + VendorId= 0x0483, + ProductId=0xDF11, + //This does not affect the filtering + Label="USB Device in DFU Mode" + }, + }); + + //Get the first available device + var dfuDevice = devices.FirstOrDefault(); + + //Ensure that it gets picked up + Assert.IsNotNull(dfuDevice); + + //Initialize the device + await dfuDevice.InitializeAsync(); + + + /////////////////////////////////////////////// + /// code that I am trying to verify against, can be removed later (or used as a seperate unit test directly against libUsb + //byte[] buffer = new byte[6]; + ////int length = usb.controlTransfer(DFU_RequestType | USB_DIR_IN, DFU_GETSTATUS, 0, 0, buffer, 6, 500); + //LibUsbDotNet.Main.UsbSetupPacket setup = new LibUsbDotNet.Main.UsbSetupPacket() + //{ + // RequestType = (byte)(DFU_RequestType | USB_DIR_IN), + // Request = (byte)DFU_GETSTATUS, + // Value = 0, + // Index = 0 + //}; + //int length = usb.ControlTransfer(setup, buffer, 0, 6); + + //if (length < 0) + //{ + // throw new Exception("USB Failed during getStatus"); + //} + //status.bStatus = buffer[0]; // state during request + //status.bState = buffer[4]; // state after request + //status.bwPollTimeout = (buffer[3] & 0xFF) << 16; + //status.bwPollTimeout |= (buffer[2] & 0xFF) << 8; + //status.bwPollTimeout |= (buffer[1] & 0xFF); + /// + /////////////////////////////////////////////// + + const byte DFU_GETSTATUS = 0x03; + var buffer = new byte[6]; + + var setupPacket = new UsbSetupPacket + { + RequestType = new UsbControlRequestType + { + Direction = UsbTransferDirection.In, + Recipient = UsbControlRecipient.Device, //probably not correct, needs verifying + ControlTransferType = UsbControlTransferType.Class, + }, + Request = DFU_GETSTATUS, + Length = (uint)buffer.Length + }; + + //var response = await dfuDevice.SendControlInTransferAsync(setupPacket, buffer); //for when async is added... + var response = dfuDevice.SendControlOutTransfer(setupPacket, buffer); + + //Possible return states + //const int STATE_IDLE = 0x00; //usually this one??? + //const int STATE_DETACH = 0x01; + //const int STATE_DFU_IDLE = 0x02; //or would it be this one??? + //const int STATE_DFU_DOWNLOAD_SYNC = 0x03; + //const int STATE_DFU_DOWNLOAD_BUSY = 0x04; + //const int STATE_DFU_DOWNLOAD_IDLE = 0x05; + //const int STATE_DFU_MANIFEST_SYNC = 0x06; + //const int STATE_DFU_MANIFEST = 0x07; + //const int STATE_DFU_MANIFEST_WAIT_RESET = 0x08; + //const int STATE_DFU_UPLOAD_IDLE = 0x09; + //const int STATE_DFU_ERROR = 0x0A; + //const int STATE_DFU_UPLOAD_SYNC = 0x91; + //const int STATE_DFU_UPLOAD_BUSY = 0x92; + + + //Specify the response part of the Message Contract + var expectedResult = new byte[] { 0x02 }; //lets try STATE_DFU_IDLE first (since we are in DFU mode)... + + + //Assert that the response part meets the specification + Assert.IsTrue(expectedResult.Equals(buffer[4])); + } + } +} + +#endif diff --git a/src/Device.Net/Device.Net.csproj b/src/Device.Net/Device.Net.csproj index ebcecd77..cbf08171 100644 --- a/src/Device.Net/Device.Net.csproj +++ b/src/Device.Net/Device.Net.csproj @@ -65,4 +65,10 @@ + + + C:\Program Files (x86)\Windows Kits\10\References\10.0.17134.0\Windows.Foundation.FoundationContract\3.0.0.0\Windows.Foundation.FoundationContract.winmd + + + diff --git a/src/Device.Net/IDevice.cs b/src/Device.Net/IDevice.cs index 8ed37fe1..d457773a 100644 --- a/src/Device.Net/IDevice.cs +++ b/src/Device.Net/IDevice.cs @@ -21,6 +21,12 @@ public interface IDevice : IDisposable /// Task WriteAsync(byte[] data, CancellationToken cancellationToken = default); + //TODO: Device.Net does not understand ISetupPacket, so currently using Object + uint SendControlOutTransfer(object setupPacket, byte[] buffer); //TODO: setup packet is defined differently between libUsb and WinUsb (also possibly convert to async) + + //TODO: Device.Net does not understand ISetupPacket, so currently using Object + uint SendControlInTransfer(object setupPacket); //TODO: setup packet is defined differently between libUsb and WinUsb (also possibly convert to async) + /// /// Close any existing connections and reinitialize the device. /// diff --git a/src/Usb.Net/ISetupPacket.cs b/src/Usb.Net/ISetupPacket.cs new file mode 100644 index 00000000..a6d8a517 --- /dev/null +++ b/src/Usb.Net/ISetupPacket.cs @@ -0,0 +1,31 @@ +namespace Usb.Net +{ + public interface ISetupPacket + { + /// + /// Gets or sets the wIndex field in the setup packet of the USB control transfer. + /// + uint Index { get; set; } + + /// + /// Gets the length, in bytes, of the setup packet. + /// + uint Length { get; set; } + + + /// + /// Gets or sets the bRequest field in the setup packet of the USB control transfer. + /// + byte Request { get; set; } + + /// + /// Gets or sets the bmRequestType field in the setup packet of the USB control transfer. That field is represented by a UsbControlRequestType object. + /// + UsbControlRequestType RequestType { get; set; } + + /// + /// Gets or sets the wValue field in the setup packet of the USB control transfer. + /// + uint Value { get; set; } + } +} diff --git a/src/Usb.Net/IUsbInterface.cs b/src/Usb.Net/IUsbInterface.cs index 847a6e3a..ce437b36 100644 --- a/src/Usb.Net/IUsbInterface.cs +++ b/src/Usb.Net/IUsbInterface.cs @@ -18,6 +18,8 @@ public interface IUsbInterface : IDisposable ushort WriteBufferSize { get; } Task WriteAsync(byte[] data, CancellationToken cancellationToken = default); Task ReadAsync(uint bufferLength, CancellationToken cancellationToken = default); + uint SendControlOutTransfer(ISetupPacket setupPacket, byte[] buffer); //TODO: setup packet is defined differently between libUsb and WinUsb (also possibly convert to async) + uint SendControlInTransfer(ISetupPacket setupPacket); //TODO: setup packet is defined differently between libUsb and WinUsb (also possibly convert to async) byte InterfaceNumber { get; } Task ClaimInterface(); diff --git a/src/Usb.Net/UsbControlRecipient.cs b/src/Usb.Net/UsbControlRecipient.cs new file mode 100644 index 00000000..47b3a5f0 --- /dev/null +++ b/src/Usb.Net/UsbControlRecipient.cs @@ -0,0 +1,40 @@ +namespace Usb.Net +{ + /// + /// Defines constants that indicate the recipient of a USB control transfer. + /// The recipient is defined in the setup packet of the control request. See Table 9.2 of section 9.3 of the Universal Serial Bus (USB) specification (). + /// + public enum UsbControlRecipient + { + /// + /// The recipient of the control transfer is the default (or the first) USB interface in the selected configuration of the device. + /// If the recipient is the first interface of the active configuration(DefaultInterface ), + /// SendControlInTransferAsync and SendControlOutTransferAsync methods overwrite the low byte of UsbSetupPacket.Index with the interface number of the default interface. + /// + /// By using this value, an app can omit the interface number in an interface-recipient request. + /// + DefaultInterface = 4, + + /// + /// The recipient of the control transfer is the device. + /// + Device = 0, + + /// + /// The recipient of the control transfer is an endpoint. + /// + Endpoint = 2, + + /// + /// The recipient of the control transfer is other. + /// + Other = 3, + + /// + /// The recipient of the control transfer is the USB interface that is specified in the request. + /// + SpecifiedInterface = 1 + + + } +} diff --git a/src/Usb.Net/UsbControlRequestType.cs b/src/Usb.Net/UsbControlRequestType.cs new file mode 100644 index 00000000..b5d90ae2 --- /dev/null +++ b/src/Usb.Net/UsbControlRequestType.cs @@ -0,0 +1,26 @@ +namespace Usb.Net +{ + public class UsbControlRequestType + { + /// + /// Gets or sets the bmRequestType value as a byte. + /// + public byte AsByte { get; set; } + + /// + /// Gets or sets the type of USB control transfer: standard, class, or vendor. + /// + public UsbControlTransferType ControlTransferType { get; set; } + + /// + /// Gets or sets the direction of the USB control transfer. + /// + public UsbTransferDirection Direction { get; set; } + + /// + /// Gets or sets the direction of the USB control transfer. + /// + public UsbControlRecipient Recipient { get; set; } + + } +} diff --git a/src/Usb.Net/UsbControlTransferType.cs b/src/Usb.Net/UsbControlTransferType.cs new file mode 100644 index 00000000..d88a5e30 --- /dev/null +++ b/src/Usb.Net/UsbControlTransferType.cs @@ -0,0 +1,24 @@ +namespace Usb.Net +{ + /// + /// Defines constants that indicate the type of USB control transfer: standard, class, or vendor. + /// + public enum UsbControlTransferType + { + /// + /// Indicates a class-specific USB control request described by a specific device class specification. + /// + Class = 1, + + /// + /// Indicates a standard USB control request that the app can send to obtain information about the device, its configurations, interfaces, and endpoints. + /// The standard requests are described in section 9.4 of the Universal Serial Bus(USB) specification(www.usb.org). + /// + Standard = 0, + + /// + /// Indicates a vendor-specified USB control request and depends on the requests supported by the device. + /// + Vendor = 2 + } +} diff --git a/src/Usb.Net/UsbDevice.cs b/src/Usb.Net/UsbDevice.cs index 94a10789..24e85ba7 100644 --- a/src/Usb.Net/UsbDevice.cs +++ b/src/Usb.Net/UsbDevice.cs @@ -56,6 +56,12 @@ public override Task WriteAsync(byte[] data, CancellationToken cancellationToken : UsbInterfaceManager.WriteUsbInterface.WriteAsync(data, cancellationToken); } + //TODO: public Task SendControlOutTransferAsync(UsbSetupPacket setupPacket, IBuffer buffer); + public uint SendControlOutTransfer(ISetupPacket setupPacket, byte[] buffer) => UsbInterfaceManager.WriteUsbInterface.SendControlOutTransfer(setupPacket, buffer); + + //TODO: public Task SendControlInTransferAsync(UsbSetupPacket setupPacket); + public uint SendControlInTransfer(ISetupPacket setupPacket) => UsbInterfaceManager.ReadUsbInterface.SendControlInTransfer(setupPacket); + public void Close() { if (_IsClosing) return; diff --git a/src/Usb.Net/UsbSetupPacket.cs b/src/Usb.Net/UsbSetupPacket.cs new file mode 100644 index 00000000..4d99bcd8 --- /dev/null +++ b/src/Usb.Net/UsbSetupPacket.cs @@ -0,0 +1,49 @@ +namespace Usb.Net +{ + public class UsbSetupPacket + { + /// + /// Creates a UsbSetupPacket object. + /// + public UsbSetupPacket() + { + + } + + ///// + ///// Creates a UsbSetupPacket object from a formatted buffer (eight bytes) that contains the setup packet. + ///// + ///// A caller-supplied buffer that contains the setup packet formatted as per the standard USB specification. + ///// The length of the buffer must be eight bytes because that is the size of a setup packet on the bus. + //public UsbSetupPacket(byte[] buffer) + //{ + // //TODO: add implementation + //} + + /// + /// Gets or sets the wIndex field in the setup packet of the USB control transfer. + /// + public uint Index { get; set; } + + /// + /// Gets the length, in bytes, of the setup packet. + /// + public uint Length { get; set; } + + + /// + /// Gets or sets the bRequest field in the setup packet of the USB control transfer. + /// + public byte Request { get; set; } + + /// + /// Gets or sets the bmRequestType field in the setup packet of the USB control transfer. That field is represented by a UsbControlRequestType object. + /// + public UsbControlRequestType RequestType { get; set; } + + /// + /// Gets or sets the wValue field in the setup packet of the USB control transfer. + /// + public uint Value { get; set; } + } +} diff --git a/src/Usb.Net/UsbTransferDirection.cs b/src/Usb.Net/UsbTransferDirection.cs new file mode 100644 index 00000000..00fe6f80 --- /dev/null +++ b/src/Usb.Net/UsbTransferDirection.cs @@ -0,0 +1,22 @@ +namespace Usb.Net +{ + /// + /// Defines constants that indicate the direction of USB transfer: IN or OUT transfers. + /// + /// + /// The direction of a USB transfer is determined from the host side and not the target USB device. + /// In an IN transfer, data moves from the device to the host. In an OUT transfer, data moves from the host to the device. + /// + public enum UsbTransferDirection + { + /// + /// Indicates an IN transfer from the device to the host. + /// + In = 1, + + /// + /// Indicates an OUT transfer from the host to the device. + /// + Out = 0 + } +} diff --git a/src/Usb.Net/Windows/WindowsUsbInterface.cs b/src/Usb.Net/Windows/WindowsUsbInterface.cs index 32fc2a24..450599e7 100644 --- a/src/Usb.Net/Windows/WindowsUsbInterface.cs +++ b/src/Usb.Net/Windows/WindowsUsbInterface.cs @@ -54,6 +54,39 @@ await Task.Run(() => }, cancellationToken); } + //TODO: make async? + //TODO: WINUSB_SETUP_PACKET not exposed + public uint SendControlOutTransfer(ISetupPacket setupPacket, byte[] buffer) + { + //TODO: convert from ISetupPacket to WINUSB_SETUP_PACKET + var winSetupPacket = new WINUSB_SETUP_PACKET(); + + uint bytesWritten = 0; + + if (buffer != null && buffer.Length > 0) + { + WinUsbApiCalls.WinUsb_ControlTransfer(_SafeFileHandle.DangerousGetHandle(), winSetupPacket, buffer, (uint)buffer.Length, ref bytesWritten, IntPtr.Zero); //last pointer is overlapped structure for async operations + } + else + { + throw new Exception("Buffer must not be empty"); + } + return bytesWritten; + } + + //TODO: make async? + //TODO: WINUSB_SETUP_PACKET not exposed + public uint SendControlInTransfer(ISetupPacket setupPacket) + { + //TODO: convert from ISetupPacket to WINUSB_SETUP_PACKET + var winSetupPacket = new WINUSB_SETUP_PACKET(); + uint bytesWritten = 0; + var buffer = Array.Empty(); + + WinUsbApiCalls.WinUsb_ControlTransfer(_SafeFileHandle.DangerousGetHandle(), winSetupPacket, buffer, (uint)buffer.Length, ref bytesWritten, IntPtr.Zero); //last pointer is overlapped structure for async operations + return bytesWritten; + } + public void Dispose() { if (_IsDisposed) return;