Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/Device.Net.LibUsb/LibUsbDevice.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<byte>();
UsbDevice.ControlTransfer(ref setupPacket, buffer, buffer.Length, out var length);
return (uint)length;
}

#endregion

#region Public Static Methods
Expand Down
120 changes: 120 additions & 0 deletions src/Device.Net.UnitTests/IntegrationTestControlTransfer.cs
Original file line number Diff line number Diff line change
@@ -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()

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@networkfusion beautiful!

This is what I need.

{
//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<FilterDeviceDefinition>
{
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)...

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@networkfusion Perfect.



//Assert that the response part meets the specification
Assert.IsTrue(expectedResult.Equals(buffer[4]));
}
}
}

#endif
6 changes: 6 additions & 0 deletions src/Device.Net/Device.Net.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,10 @@
</PackageReference>
</ItemGroup>

<ItemGroup>
<Reference Include="Windows.Foundation.FoundationContract">
<HintPath>C:\Program Files (x86)\Windows Kits\10\References\10.0.17134.0\Windows.Foundation.FoundationContract\3.0.0.0\Windows.Foundation.FoundationContract.winmd</HintPath>
</Reference>
</ItemGroup>

</Project>
6 changes: 6 additions & 0 deletions src/Device.Net/IDevice.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ public interface IDevice : IDisposable
/// </summary>
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)

/// <summary>
/// Close any existing connections and reinitialize the device.
/// </summary>
Expand Down
31 changes: 31 additions & 0 deletions src/Usb.Net/ISetupPacket.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
namespace Usb.Net
{
public interface ISetupPacket
{
/// <summary>
/// Gets or sets the wIndex field in the setup packet of the USB control transfer.
/// </summary>
uint Index { get; set; }

/// <summary>
/// Gets the length, in bytes, of the setup packet.
/// </summary>
uint Length { get; set; }


/// <summary>
/// Gets or sets the bRequest field in the setup packet of the USB control transfer.
/// </summary>
byte Request { get; set; }

/// <summary>
/// Gets or sets the bmRequestType field in the setup packet of the USB control transfer. That field is represented by a UsbControlRequestType object.
/// </summary>
UsbControlRequestType RequestType { get; set; }

/// <summary>
/// Gets or sets the wValue field in the setup packet of the USB control transfer.
/// </summary>
uint Value { get; set; }
}
}
2 changes: 2 additions & 0 deletions src/Usb.Net/IUsbInterface.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ public interface IUsbInterface : IDisposable
ushort WriteBufferSize { get; }
Task WriteAsync(byte[] data, CancellationToken cancellationToken = default);
Task<ReadResult> 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();

Expand Down
40 changes: 40 additions & 0 deletions src/Usb.Net/UsbControlRecipient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
namespace Usb.Net
{
/// <summary>
/// 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 (<see cref="www.usb.org"/>).
/// </summary>
public enum UsbControlRecipient

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@networkfusion question...

Where do these enums and descriptions come from? Is this from some official documentation?

{
/// <summary>
/// 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.
/// </summary>
DefaultInterface = 4,

/// <summary>
/// The recipient of the control transfer is the device.
/// </summary>
Device = 0,

/// <summary>
/// The recipient of the control transfer is an endpoint.
/// </summary>
Endpoint = 2,

/// <summary>
/// The recipient of the control transfer is other.
/// </summary>
Other = 3,

/// <summary>
/// The recipient of the control transfer is the USB interface that is specified in the request.
/// </summary>
SpecifiedInterface = 1


}
}
26 changes: 26 additions & 0 deletions src/Usb.Net/UsbControlRequestType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
namespace Usb.Net
{
public class UsbControlRequestType
{
/// <summary>
/// Gets or sets the bmRequestType value as a byte.
/// </summary>
public byte AsByte { get; set; }

/// <summary>
/// Gets or sets the type of USB control transfer: standard, class, or vendor.
/// </summary>
public UsbControlTransferType ControlTransferType { get; set; }

/// <summary>
/// Gets or sets the direction of the USB control transfer.
/// </summary>
public UsbTransferDirection Direction { get; set; }

/// <summary>
/// Gets or sets the direction of the USB control transfer.
/// </summary>
public UsbControlRecipient Recipient { get; set; }

}
}
24 changes: 24 additions & 0 deletions src/Usb.Net/UsbControlTransferType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
namespace Usb.Net
{
/// <summary>
/// Defines constants that indicate the type of USB control transfer: standard, class, or vendor.
/// </summary>
public enum UsbControlTransferType
{
/// <summary>
/// Indicates a class-specific USB control request described by a specific device class specification.
/// </summary>
Class = 1,

/// <summary>
/// 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).
/// </summary>
Standard = 0,

/// <summary>
/// Indicates a vendor-specified USB control request and depends on the requests supported by the device.
/// </summary>
Vendor = 2
}
}
6 changes: 6 additions & 0 deletions src/Usb.Net/UsbDevice.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ public override Task WriteAsync(byte[] data, CancellationToken cancellationToken
: UsbInterfaceManager.WriteUsbInterface.WriteAsync(data, cancellationToken);
}

//TODO: public Task<uint> SendControlOutTransferAsync(UsbSetupPacket setupPacket, IBuffer buffer);
public uint SendControlOutTransfer(ISetupPacket setupPacket, byte[] buffer) => UsbInterfaceManager.WriteUsbInterface.SendControlOutTransfer(setupPacket, buffer);

//TODO: public Task<uint> SendControlInTransferAsync(UsbSetupPacket setupPacket);
public uint SendControlInTransfer(ISetupPacket setupPacket) => UsbInterfaceManager.ReadUsbInterface.SendControlInTransfer(setupPacket);

public void Close()
{
if (_IsClosing) return;
Expand Down
49 changes: 49 additions & 0 deletions src/Usb.Net/UsbSetupPacket.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
namespace Usb.Net
{
public class UsbSetupPacket
{
/// <summary>
/// Creates a UsbSetupPacket object.
/// </summary>
public UsbSetupPacket()
{

}

///// <summary>
///// Creates a UsbSetupPacket object from a formatted buffer (eight bytes) that contains the setup packet.
///// </summary>
///// <param name="">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.</param>
//public UsbSetupPacket(byte[] buffer)
//{
// //TODO: add implementation
//}

/// <summary>
/// Gets or sets the wIndex field in the setup packet of the USB control transfer.
/// </summary>
public uint Index { get; set; }

/// <summary>
/// Gets the length, in bytes, of the setup packet.
/// </summary>
public uint Length { get; set; }


/// <summary>
/// Gets or sets the bRequest field in the setup packet of the USB control transfer.
/// </summary>
public byte Request { get; set; }

/// <summary>
/// Gets or sets the bmRequestType field in the setup packet of the USB control transfer. That field is represented by a UsbControlRequestType object.
/// </summary>
public UsbControlRequestType RequestType { get; set; }

/// <summary>
/// Gets or sets the wValue field in the setup packet of the USB control transfer.
/// </summary>
public uint Value { get; set; }
}
}
22 changes: 22 additions & 0 deletions src/Usb.Net/UsbTransferDirection.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
namespace Usb.Net
{
/// <summary>
/// Defines constants that indicate the direction of USB transfer: IN or OUT transfers.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public enum UsbTransferDirection
{
/// <summary>
/// Indicates an IN transfer from the device to the host.
/// </summary>
In = 1,

/// <summary>
/// Indicates an OUT transfer from the host to the device.
/// </summary>
Out = 0
}
}
Loading