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
67 changes: 39 additions & 28 deletions src/Device.Net.UnitTests/IntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,43 +67,54 @@ public async Task TestConnectToSTMDFUMode2()
var windowsUsbDevice = new UsbDevice(deviceID, new WindowsUsbInterfaceManager(deviceID));
await windowsUsbDevice.InitializeAsync();

const int USB_DIR_IN = 128; //0x80
const int DFU_RequestType = 0x21; // '2' => Class request ; '1' => to interface
const byte DFU_GETSTATUS = 0x03;
//var buffer = new byte[6];
const byte DFU_CLEARSTATUS = 0x04;

//Get status? Is this correct?
const byte STATE_DFU_IDLE = 0x02;

// setup packet to send a DFU Clear Status command
var setupPacket = new SetupPacket
(
requestType: DFU_RequestType | USB_DIR_IN,
requestType: new UsbDeviceRequestType(
RequestDirection.In,
RequestType.Class,
RequestRecipient.Interface),
request: DFU_CLEARSTATUS,
length: 0
);

// send control transfer, no need to check the return
_ = await windowsUsbDevice.SendControlTransferAsync(setupPacket);

// setup packet to send a DFU GetStatus command
setupPacket = new SetupPacket
(
requestType: new UsbDeviceRequestType(
RequestDirection.In,
RequestType.Class,
RequestRecipient.Interface),
request: DFU_GETSTATUS,
length: 6
);

//According to Florian get status
//var setupPacket = new WINUSB_SETUP_PACKET
//{
// RequestType = 161,
// Request = 3,
// Length = (ushort)buffer.Length,
// Value = 0,
// Index = 0
//};

//// DFU CLEAR SETUP PACKET
//var setupPacket = new WINUSB_SETUP_PACKET
//{
// RequestType = 33,
// Request = 4,
// Length = 0,
// Value = 2,
// Index = 0
//};

var result = await windowsUsbDevice.SendControlTransferAsync(setupPacket);
var dfuStatus = new ControlTransferResult();

//Assert that the response part meets the specification
Assert.IsTrue(new byte[] { 0x02 }.Equals(result.Data));
// because the device is not always able to reply, may take a couple of attempts to get one
for (var attempt = 0; attempt < 3; attempt++)
{
dfuStatus = await windowsUsbDevice.SendControlTransferAsync(setupPacket);

if (dfuStatus.BytesTransferred == 0)
{
// wait for a little while before the next attempt
await Task.Delay(250);
}
}

// Assert that the received buffer has the requested lenght ADN that DFU State (at position 4) is STATE_DFU_IDLE
Assert.IsTrue(
dfuStatus.BytesTransferred == setupPacket.Length &&
dfuStatus.Data[4] == STATE_DFU_IDLE);
}
#endif

Expand Down
30 changes: 30 additions & 0 deletions src/Device.Net/ControlTransferResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
namespace Device.Net

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.

@josesimoes why is this necessary?

It's exactly the same as ReadResult

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Almost... the property BytesTransferred name is different to make it clear that's the bytes transferred.
That is properly set for both send and receive operations.

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.

Hmm...

It's still reading the bytes from the device... Is the distinction that important?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I believe it is. Because when you are sending data it will report how many bytes where actually SENT.
And you're reading data it will tell you how many bytes where actually RECEIVED.

On both that's the gold check for the operation actually succeeding. Not only the return from the call.

Plus on the name, I feel that ReadResult is a bit... short... because it's being used for READ AND WRITE operations, therefore the name ControlTransferResult which works for both.

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.

I could change the name to TransferResult, and the property to BytesTransferred but this would break all the existing implementations.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

You're the boss... that's your call...
ReadResult is not used for write operations because there is none, yet. (I guess).
Where there is the name will be kind of awkward, no?!

Suggestion:

  1. keep the existing ReadResult and methods and add the [Obsolete] attribute to them.
  2. Implement the "new" TransferResult with those calls.
  3. At some future version remove the deprecated ones.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

@josesimoes after reading this a few times, I'm more confused now.

When we do a control transfer, we send a buffer of data to the device. Then, the device sends a buffer back with different data. So, technically, we may be interested in the transfer length for both operations (send and receive). However, the Windows API does not give us that. We only get the length of the data that was read back from the device. Isn't that understanding correct?

Nope... The LengthTransferred in WinUsb_ControlTransfer reports the actuall number of bytes that were SENT or RECEIVED according to the operation that was requested (RequestDirection.In or RequestDirection.Out).

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.

No @josesimoes. you're pointing out something that I must be misunderstanding. I need to get this straight.

You're saying that the you want to use the structure for the result of sends, and receives, but the Windows API doesn't give us the result of sends - only receive. We only get the read result of what comes back from the device.,

This is the method signature:

public static extern bool WinUsb_ControlTransfer(IntPtr InterfaceHandle, WINUSB_SETUP_PACKET SetupPacket, byte[] Buffer, uint BufferLength, ref uint LengthTransferred, IntPtr Overlapped);

I could be wrong, but my understanding is that LengthTransferred is the length read from the device.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Please check here: https://docs.microsoft.com/en-us/windows/win32/api/winusb/nf-winusb-winusb_controltransfer

Depending if you're sending data to the device or reading from it, it will tell you how many bytes were actually transferred. I insist! 😉

@MelbourneDeveloper MelbourneDeveloper Nov 11, 2020 •

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.

Nope... The LengthTransferred in WinUsb_ControlTransfer reports the actuall number of bytes that were SENT or RECEIVED according to the operation that was requested (RequestDirection.In or RequestDirection.Out).

OK. That's where my misunderstanding was. Thanks

@josesimoes

{
#pragma warning disable CA1815 // Override equals and operator equals on value types
public readonly struct ControlTransferResult

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.

@josesimoes let's rename ReadResult to TranserResult ,and rename BytesRead to BytesTransferred. Then we can delete this class.

You can do that in your branch, or I can change that after the PR. Let me know.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Suggest that we tackle that after this is merged, so the PR is more atomic.

#pragma warning restore CA1815 // Override equals and operator equals on value types
{
#region Public Properties
#pragma warning disable CA1819 // Properties should not return arrays
public byte[] Data { get; }
#pragma warning restore CA1819 // Properties should not return arrays

public uint BytesTransferred { get; }
#endregion

#region Conversion Operators
public byte[] ToByteArray() => Data;

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.

ReadResult has an implicit operator for converting to arrays

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Yes, but the code analyser complains about that....
I'm quite all right if you want to default to that implicit operation here too.

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.

@josesimoes what's the issue with analyzer?

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.

@josesimoes in my branch I fixed the code analyzer rule.

csharp_style_expression_bodied_operators = true:error

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

That's good!


#endregion

#region Constructor
public ControlTransferResult(
uint bytesTransferred,
byte[] data = null)
{
Data = data;
BytesTransferred = bytesTransferred;
}
#endregion
}
}
2 changes: 1 addition & 1 deletion src/Usb.Net/Android/AndroidUsbInterface.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ public override Task ClaimInterface()
}

#pragma warning disable IDE0060 // Remove unused parameter
public Task<ReadResult> SendControlTransferAsync(SetupPacket setupPacket, byte[] buffer = null, CancellationToken cancellationToken = default) => throw new NotImplementedException();
public Task<ControlTransferResult> SendControlTransferAsync(SetupPacket setupPacket, byte[] buffer = null, CancellationToken cancellationToken = default) => throw new NotImplementedException();
#pragma warning restore IDE0060 // Remove unused parameter
#endregion
}
Expand Down
2 changes: 1 addition & 1 deletion src/Usb.Net/IUsbInterface.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,6 @@ public interface IUsbInterface : IDisposable
/// Can we just create the buffer in the method?
/// Or, do we sometimes need to send data here?
/// </summary>
Task<ReadResult> SendControlTransferAsync(SetupPacket setupPacket, byte[] buffer = null, CancellationToken cancellationToken = default);
Task<ControlTransferResult> SendControlTransferAsync(SetupPacket setupPacket, byte[] buffer = null, CancellationToken cancellationToken = default);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
/// Defines constants that indicate the direction of USB transfer: IN or OUT transfers.
/// </summary>
/// <remarks>
/// See 9.3 of the Universal Serial Bus (USB) specification (<see cref="www.usb.org"/>)
/// 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
public enum RequestDirection
{
/// <summary>
/// Indicates an IN transfer from the device to the host.
Expand Down
41 changes: 41 additions & 0 deletions src/Usb.Net/RequestRecipient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
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.
/// </summary>
/// <remarks>
/// See Table 9.2 of section 9.3 of the Universal Serial Bus (USB) specification (<see cref="www.usb.org"/>)
/// </remarks>
public enum RequestRecipient
{
///// <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 the USB interface that is specified in the request.
/// </summary>
Interface = 1,

/// <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,
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
namespace Usb.Net
{
/// <summary>
/// Defines constants that indicate the type of USB control transfer: standard, class, or vendor.
/// Defines the type of USB device request.
/// </summary>
public enum UsbControlTransferType
/// <remarks>
/// See 9.3 of the Universal Serial Bus (USB) specification (<see cref="www.usb.org"/>)
/// </remarks>
public enum RequestType
{
/// <summary>
/// Indicates a class-specific USB control request described by a specific device class specification.
Expand Down
22 changes: 13 additions & 9 deletions src/Usb.Net/SetupPacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,27 @@
{
public class SetupPacket
{
/// <summary>
/// Size of <see cref="SetupPacket"/> to be used in byte arrays.
/// </summary>
// this is the "byte" size of the properties below
public const int SetupPacketSize = 1 + 1 + 2 + 2 + 2;

#region Public Properties
public byte RequestType { get; }
public UsbDeviceRequestType RequestType { get; }
public byte Request { get; }
public ushort Value { get; }
public ushort Index { get; }
public ushort Length { get; }
#endregion

#region Constructors
public SetupPacket
(
byte requestType,
byte request,
ushort value = 0,
ushort index = 0,
ushort length = 0
)
public SetupPacket(
UsbDeviceRequestType requestType,
byte request,
ushort value = 0,
ushort index = 0,
ushort length = 0)
{
RequestType = requestType;
Request = request;
Expand Down
9 changes: 5 additions & 4 deletions src/Usb.Net/UWP/UWPUsbInterface.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,11 @@ public async Task WriteAsync(byte[] data, CancellationToken cancellationToken =
throw;
}
}

#pragma warning disable IDE0060 // Remove unused parameter
public Task<ControlTransferResult> SendControlTransferAsync(SetupPacket setupPacket, byte[] buffer = null, CancellationToken cancellationToken = default) => throw new NotImplementedException();
#pragma warning restore IDE0060 // Remove unused parameter

#endregion

#region IDisposable Support
Expand All @@ -142,10 +147,6 @@ public void Dispose()
if (disposedValue) return;
disposedValue = true;
}

#pragma warning disable IDE0060 // Remove unused parameter
public Task<ReadResult> SendControlTransferAsync(SetupPacket setupPacket, byte[] buffer = null, CancellationToken cancellationToken = default) => throw new NotImplementedException();
#pragma warning restore IDE0060 // Remove unused parameter
#endregion
}
}
40 changes: 0 additions & 40 deletions src/Usb.Net/UsbControlRecipient.cs

This file was deleted.

26 changes: 0 additions & 26 deletions src/Usb.Net/UsbControlRequestType.cs

This file was deleted.

2 changes: 1 addition & 1 deletion src/Usb.Net/UsbDeviceExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace Usb.Net
{
public static class UsbDeviceExtensions
{
public static Task<ReadResult> SendControlTransferAsync(this IUsbDevice usbDevice, SetupPacket setupPacket, byte[] buffer = null, CancellationToken cancellationToken = default)
public static Task<ControlTransferResult> SendControlTransferAsync(this IUsbDevice usbDevice, SetupPacket setupPacket, byte[] buffer = null, CancellationToken cancellationToken = default)
=> usbDevice == null ? throw new ArgumentNullException(nameof(usbDevice)) :
(usbDevice.UsbInterfaceManager.UsbInterfaces.FirstOrDefault() ??
throw new Exception("There are no interfaces to send a control transfer to"))
Expand Down
40 changes: 40 additions & 0 deletions src/Usb.Net/UsbDeviceRequestType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System;

namespace Usb.Net
{
public class UsbDeviceRequestType

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.

@josesimoes this looks good.

{
/// <summary>
/// Gets the type of the USB device request.
/// </summary>
public RequestType Type { get; }

/// <summary>
/// Gets the direction of the USB device request.
/// </summary>
public RequestDirection Direction { get; }

/// <summary>
/// Gets the direction of the USB device request.
/// </summary>
public RequestRecipient Recipient { get; }

public UsbDeviceRequestType(
RequestDirection direction,
RequestType type,
RequestRecipient recipient)
{
Direction = direction;
Type = type;
Recipient = recipient;
}

public byte ToByte()
{
return (byte)(
((byte)Direction << 7) +
((byte)Type << 5) +
(byte)Recipient);
}
}
}
2 changes: 1 addition & 1 deletion src/Usb.Net/Windows/WindowsUsbExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public static WINUSB_SETUP_PACKET ToWindowsSetupPacket(this SetupPacket setupPac
Index = setupPacket.Length,
Length = setupPacket.Length,
Request = setupPacket.Request,
RequestType = setupPacket.RequestType,
RequestType = setupPacket.RequestType.ToByte(),
Value = setupPacket.Value
};
}
Expand Down
Loading