Mercurial > hg > ucis.core
annotate USBLib/Communication/USBIO/USBIODevice.cs @ 62:edc41c861d96
Updates and cleanup in Windows USB enumeration code
author | Ivo Smits <Ivo@UCIS.nl> |
---|---|
date | Sun, 13 Oct 2013 02:47:08 +0200 |
parents | 053cc617af54 |
children | abe0d55a2201 |
rev | line source |
---|---|
35 | 1 using System; |
2 using System.Collections.Generic; | |
3 using System.ComponentModel; | |
4 using System.IO; | |
5 using System.Runtime.InteropServices; | |
6 using Microsoft.Win32.SafeHandles; | |
7 using UCIS.USBLib.Internal.Windows; | |
8 | |
9 namespace UCIS.USBLib.Communication.USBIO { | |
10 public class USBIODevice : UsbInterface, IUsbDevice { | |
11 public string DeviceFilename { get; private set; } | |
12 public IUsbDeviceRegistry Registry { get; private set; } | |
13 private SafeFileHandle DeviceHandle; | |
14 private SafeFileHandle[] PipeHandlesIn = null; | |
15 private SafeFileHandle[] PipeHandlesOut = null; | |
16 | |
17 static int CTL_CODE(int DeviceType, int Function, int Method, int Access) { return ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method); } | |
18 static int _USBIO_IOCTL_CODE(int FnCode, int Method) { return CTL_CODE(0x8094, 0x800 + FnCode, Method, 0); } | |
19 const int METHOD_BUFFERED = 0; | |
20 const int METHOD_IN_DIRECT = 1; | |
21 const int METHOD_OUT_DIRECT = 2; | |
22 static readonly int IOCTL_USBIO_GET_DESCRIPTOR = _USBIO_IOCTL_CODE(1, METHOD_OUT_DIRECT); | |
23 static readonly int IOCTL_USBIO_GET_CONFIGURATION = _USBIO_IOCTL_CODE(6, METHOD_BUFFERED); | |
24 static readonly int IOCTL_USBIO_SET_CONFIGURATION = _USBIO_IOCTL_CODE(9, METHOD_BUFFERED); | |
38
a9c4fed19e99
USBLib: fixes in USBIO driver and LibUsbDotNet compatibility code
Ivo Smits <Ivo@UCIS.nl>
parents:
37
diff
changeset
|
25 static readonly int IOCTL_USBIO_UNCONFIGURE_DEVICE = _USBIO_IOCTL_CODE(10, METHOD_BUFFERED); |
35 | 26 static readonly int IOCTL_USBIO_CLASS_OR_VENDOR_IN_REQUEST = _USBIO_IOCTL_CODE(12, METHOD_OUT_DIRECT); |
27 static readonly int IOCTL_USBIO_CLASS_OR_VENDOR_OUT_REQUEST = _USBIO_IOCTL_CODE(13, METHOD_IN_DIRECT); | |
28 static readonly int IOCTL_USBIO_RESET_DEVICE = _USBIO_IOCTL_CODE(21, METHOD_BUFFERED); | |
29 static readonly int IOCTL_USBIO_BIND_PIPE = _USBIO_IOCTL_CODE(30, METHOD_BUFFERED); | |
46
053cc617af54
USBLib: added functions to clear USB endpoint halt state
Ivo Smits <Ivo@UCIS.nl>
parents:
44
diff
changeset
|
30 static readonly int IOCTL_USBIO_RESET_PIPE = _USBIO_IOCTL_CODE(32, METHOD_BUFFERED); |
35 | 31 |
32 [DllImport("kernel32.dll", SetLastError = true)] | |
33 static unsafe extern bool ReadFile(SafeFileHandle hFile, byte* lpBuffer, uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, IntPtr lpOverlapped); | |
34 [DllImport("kernel32.dll", SetLastError = true)] | |
35 static unsafe extern bool WriteFile(SafeFileHandle hFile, byte* lpBuffer, uint nNumberOfBytesToWrite, out uint lpNumberOfBytesWritten, IntPtr lpOverlapped); | |
36 | |
37 enum USBIO_REQUEST_RECIPIENT : uint { | |
38 Device = 0, | |
39 Interface, | |
40 Endpoint, | |
41 Other, | |
42 } | |
43 enum USBIO_REQUEST_TYPE : uint { | |
44 Class = 1, | |
45 Vendor, | |
46 } | |
47 | |
48 const UInt32 USBIO_SHORT_TRANSFER_OK = 0x00010000; | |
49 | |
50 [StructLayout(LayoutKind.Sequential, Pack = 1)] | |
51 struct USBIO_DESCRIPTOR_REQUEST { | |
52 public USBIO_REQUEST_RECIPIENT Recipient; | |
53 public Byte DescriptorType; | |
54 public Byte DescriptorIndex; | |
55 public Int16 LanguageId; | |
56 } | |
57 [StructLayout(LayoutKind.Sequential, Pack = 1)] | |
58 struct USBIO_BIND_PIPE { | |
59 public Byte EndpointAddress; | |
60 } | |
61 [StructLayout(LayoutKind.Sequential, Pack = 1, Size = 2 + 2 + 4)] | |
62 struct USBIO_INTERFACE_SETTING { | |
63 public UInt16 InterfaceIndex; | |
64 public UInt16 AlternateSettingIndex; | |
65 public UInt32 MaximumTransferSize; | |
66 } | |
67 [StructLayout(LayoutKind.Sequential, Pack = 1)] | |
68 unsafe struct USBIO_SET_CONFIGURATION{ | |
69 public UInt16 ConfigurationIndex; | |
70 public UInt16 NbOfInterfaces; | |
71 public fixed byte InterfaceList[32 * (2 + 2 + 4)]; | |
72 } | |
73 [StructLayout(LayoutKind.Sequential, Pack = 1)] | |
74 struct USBIO_CLASS_OR_VENDOR_REQUEST { | |
75 public UInt32 Flags; | |
76 public USBIO_REQUEST_TYPE Type; | |
77 public USBIO_REQUEST_RECIPIENT Recipient; | |
78 public Byte RequestTypeReservedBits; | |
79 public Byte Request; | |
80 public Int16 Value; | |
81 public Int16 Index; | |
82 } | |
83 | |
84 public USBIODevice(String path, USBIORegistry registry) { | |
85 DeviceFilename = path; | |
86 this.Registry = registry; | |
87 DeviceHandle = OpenHandle(); | |
88 } | |
89 private SafeFileHandle OpenHandle() { | |
90 SafeFileHandle handle = Kernel32.CreateFile(DeviceFilename, | |
91 NativeFileAccess.FILE_GENERIC_READ | NativeFileAccess.FILE_GENERIC_WRITE, | |
92 NativeFileShare.FILE_SHARE_WRITE | NativeFileShare.FILE_SHARE_READ, | |
93 IntPtr.Zero, | |
94 NativeFileMode.OPEN_EXISTING, | |
95 NativeFileFlag.FILE_ATTRIBUTE_NORMAL, | |
96 IntPtr.Zero); | |
97 if (handle.IsInvalid || handle.IsClosed) throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not open device"); | |
98 return handle; | |
99 } | |
100 public override void Close() { | |
101 if (PipeHandlesIn != null) for (int i = 0; i < PipeHandlesIn.Length; i++) if (PipeHandlesIn[i] != null) PipeHandlesIn[i].Close(); | |
102 if (PipeHandlesOut != null) for (int i = 0; i < PipeHandlesOut.Length; i++) if (PipeHandlesOut[i] != null) PipeHandlesOut[i].Close(); | |
103 if (DeviceHandle != null) DeviceHandle.Close(); | |
104 } | |
105 | |
106 public override Byte Configuration { | |
107 get { return base.Configuration; } | |
108 set { | |
109 IList<LibUsbDotNet.Info.UsbConfigInfo> configs = (new LibUsbDotNet.UsbDevice(this)).Configs; | |
110 for (int i = 0; i < configs.Count; i++) { | |
111 LibUsbDotNet.Info.UsbConfigInfo config = configs[i]; | |
112 if (config.Descriptor.ConfigID == value) { | |
113 unsafe { | |
114 USBIO_SET_CONFIGURATION req = new USBIO_SET_CONFIGURATION(); | |
115 req.ConfigurationIndex = (ushort)i; | |
116 req.NbOfInterfaces = Math.Min((ushort)32, config.Descriptor.InterfaceCount); | |
117 for (int j = 0; j < req.NbOfInterfaces; j++) { | |
38
a9c4fed19e99
USBLib: fixes in USBIO driver and LibUsbDotNet compatibility code
Ivo Smits <Ivo@UCIS.nl>
parents:
37
diff
changeset
|
118 LibUsbDotNet.Info.UsbInterfaceInfo intf = config.InterfaceInfoList[j]; |
a9c4fed19e99
USBLib: fixes in USBIO driver and LibUsbDotNet compatibility code
Ivo Smits <Ivo@UCIS.nl>
parents:
37
diff
changeset
|
119 *((USBIO_INTERFACE_SETTING*)(req.InterfaceList + sizeof(USBIO_INTERFACE_SETTING) * j)) = |
35 | 120 new USBIO_INTERFACE_SETTING() { InterfaceIndex = intf.Descriptor.InterfaceID, AlternateSettingIndex = 0, MaximumTransferSize = UInt16.MaxValue }; |
121 } | |
44
5a2b51b0d71b
USBLib: Fixed initialization of multi-interface USBIO devices
Ivo Smits <Ivo@UCIS.nl>
parents:
38
diff
changeset
|
122 try { |
5a2b51b0d71b
USBLib: Fixed initialization of multi-interface USBIO devices
Ivo Smits <Ivo@UCIS.nl>
parents:
38
diff
changeset
|
123 DeviceIoControl(DeviceHandle, IOCTL_USBIO_SET_CONFIGURATION, (IntPtr)(&req), sizeof(USBIO_SET_CONFIGURATION), IntPtr.Zero, 0); |
5a2b51b0d71b
USBLib: Fixed initialization of multi-interface USBIO devices
Ivo Smits <Ivo@UCIS.nl>
parents:
38
diff
changeset
|
124 } catch (Win32Exception ex) { |
5a2b51b0d71b
USBLib: Fixed initialization of multi-interface USBIO devices
Ivo Smits <Ivo@UCIS.nl>
parents:
38
diff
changeset
|
125 if (ex.NativeErrorCode == unchecked((int)0xE0001005L)) return; |
5a2b51b0d71b
USBLib: Fixed initialization of multi-interface USBIO devices
Ivo Smits <Ivo@UCIS.nl>
parents:
38
diff
changeset
|
126 throw; |
5a2b51b0d71b
USBLib: Fixed initialization of multi-interface USBIO devices
Ivo Smits <Ivo@UCIS.nl>
parents:
38
diff
changeset
|
127 } |
35 | 128 } |
129 return; | |
130 } | |
131 } | |
132 throw new InvalidOperationException("Requested configuration ID not found"); | |
133 } | |
134 } | |
135 | |
136 public void ClaimInterface(int interfaceID) { | |
137 } | |
138 public void ReleaseInterface(int interfaceID) { | |
139 } | |
140 public void SetAltInterface(int interfaceID, int alternateID) { | |
141 throw new NotImplementedException(); | |
142 } | |
143 public void ResetDevice() { | |
144 DeviceIoControl(DeviceHandle, IOCTL_USBIO_RESET_DEVICE, IntPtr.Zero, 0, IntPtr.Zero, 0); | |
145 } | |
146 public unsafe override int GetDescriptor(byte descriptorType, byte index, short langId, byte[] buffer, int offset, int length) { | |
147 if (offset < 0 || length < 0 || offset + length > buffer.Length) throw new ArgumentOutOfRangeException("length", "The specified offset and length exceed the buffer length"); | |
148 USBIO_DESCRIPTOR_REQUEST req = new USBIO_DESCRIPTOR_REQUEST() { DescriptorType = descriptorType, DescriptorIndex = index, LanguageId = langId, Recipient = USBIO_REQUEST_RECIPIENT.Device }; | |
149 fixed (Byte* b = buffer) { | |
150 return DeviceIoControl(DeviceHandle, IOCTL_USBIO_GET_DESCRIPTOR, (IntPtr)(&req), sizeof(USBIO_DESCRIPTOR_REQUEST), (IntPtr)(b + offset), length); | |
151 } | |
152 } | |
153 public override int BulkRead(byte endpoint, byte[] buffer, int offset, int length) { | |
154 return PipeRead(endpoint, buffer, offset, length); | |
155 } | |
156 public override int BulkWrite(byte endpoint, byte[] buffer, int offset, int length) { | |
157 return PipeWrite(endpoint, buffer, offset, length); | |
158 } | |
46
053cc617af54
USBLib: added functions to clear USB endpoint halt state
Ivo Smits <Ivo@UCIS.nl>
parents:
44
diff
changeset
|
159 public override void BulkReset(byte endpoint) { |
053cc617af54
USBLib: added functions to clear USB endpoint halt state
Ivo Smits <Ivo@UCIS.nl>
parents:
44
diff
changeset
|
160 PipeReset(endpoint); |
053cc617af54
USBLib: added functions to clear USB endpoint halt state
Ivo Smits <Ivo@UCIS.nl>
parents:
44
diff
changeset
|
161 } |
35 | 162 public override int InterruptRead(byte endpoint, byte[] buffer, int offset, int length) { |
163 return PipeRead(endpoint, buffer, offset, length); | |
164 } | |
165 public override int InterruptWrite(byte endpoint, byte[] buffer, int offset, int length) { | |
166 return PipeWrite(endpoint, buffer, offset, length); | |
167 } | |
46
053cc617af54
USBLib: added functions to clear USB endpoint halt state
Ivo Smits <Ivo@UCIS.nl>
parents:
44
diff
changeset
|
168 public override void InterruptReset(byte endpoint) { |
053cc617af54
USBLib: added functions to clear USB endpoint halt state
Ivo Smits <Ivo@UCIS.nl>
parents:
44
diff
changeset
|
169 PipeReset(endpoint); |
053cc617af54
USBLib: added functions to clear USB endpoint halt state
Ivo Smits <Ivo@UCIS.nl>
parents:
44
diff
changeset
|
170 } |
35 | 171 public unsafe override int ControlRead(UsbControlRequestType requestType, byte request, short value, short index, byte[] buffer, int offset, int length) { |
172 return ControlTransfer(requestType, request, value, index, buffer, offset, length); | |
173 } | |
174 public override int ControlWrite(UsbControlRequestType requestType, byte request, short value, short index, byte[] buffer, int offset, int length) { | |
175 return ControlTransfer(requestType, request, value, index, buffer, offset, length); | |
176 } | |
177 private unsafe int ControlTransfer(UsbControlRequestType requestType, byte request, short value, short index, byte[] buffer, int offset, int length) { | |
178 if (buffer == null) { | |
179 if (offset != 0 || length != 0) throw new ArgumentOutOfRangeException("length", "The specified offset and length exceed the buffer length"); | |
180 } else { | |
181 if (offset < 0 || length < 0 || offset + length > buffer.Length) throw new ArgumentOutOfRangeException("length", "The specified offset and length exceed the buffer length"); | |
182 } | |
183 switch (requestType & UsbControlRequestType.TypeMask) { | |
184 case UsbControlRequestType.TypeStandard: | |
185 switch ((UsbStandardRequest)request) { | |
186 case UsbStandardRequest.GetDescriptor: | |
187 return GetDescriptor((Byte)(value >> 8), (Byte)value, index, buffer, offset, length); | |
188 case UsbStandardRequest.GetConfiguration: | |
189 fixed (Byte* b = buffer) return DeviceIoControl(DeviceHandle, IOCTL_USBIO_GET_CONFIGURATION, IntPtr.Zero, 0, (IntPtr)(b + offset), length); | |
190 case UsbStandardRequest.SetConfiguration: | |
191 Configuration = (Byte)value; | |
192 return 0; | |
193 default: | |
194 throw new ArgumentException(String.Format("Invalid request: 0x{0:X8}", request)); | |
195 } | |
196 case UsbControlRequestType.TypeVendor: | |
197 case UsbControlRequestType.TypeClass: | |
198 USBIO_CLASS_OR_VENDOR_REQUEST req = new USBIO_CLASS_OR_VENDOR_REQUEST() { | |
199 Flags = USBIO_SHORT_TRANSFER_OK, | |
200 Type = (USBIO_REQUEST_TYPE)((int)(requestType & UsbControlRequestType.TypeMask) >> 5), | |
201 Recipient = (USBIO_REQUEST_RECIPIENT)((int)(requestType & UsbControlRequestType.RecipMask) >> 0), | |
202 RequestTypeReservedBits = 0, | |
203 Request = request, | |
204 Value = value, | |
205 Index = index, | |
206 }; | |
207 fixed (Byte* b = buffer) { | |
208 if ((requestType & UsbControlRequestType.EndpointMask) == UsbControlRequestType.EndpointIn) { | |
209 return DeviceIoControl(DeviceHandle, IOCTL_USBIO_CLASS_OR_VENDOR_IN_REQUEST, (IntPtr)(&req), sizeof(USBIO_CLASS_OR_VENDOR_REQUEST), (IntPtr)(b + offset), length); | |
210 } else { | |
211 return DeviceIoControl(DeviceHandle, IOCTL_USBIO_CLASS_OR_VENDOR_OUT_REQUEST, (IntPtr)(&req), sizeof(USBIO_CLASS_OR_VENDOR_REQUEST), (IntPtr)(b + offset), length); | |
212 } | |
213 } | |
214 case UsbControlRequestType.TypeReserved: | |
215 default: | |
216 throw new ArgumentException(String.Format("Invalid or unsupported request type: 0x{0:X8}", requestType)); | |
217 } | |
218 } | |
219 private unsafe SafeFileHandle OpenHandleForPipe(Byte epID) { | |
220 SafeFileHandle handle = OpenHandle(); | |
221 USBIO_BIND_PIPE req = new USBIO_BIND_PIPE() { EndpointAddress = epID }; | |
222 try { | |
223 DeviceIoControl(handle, IOCTL_USBIO_BIND_PIPE, (IntPtr)(&req), sizeof(USBIO_BIND_PIPE), IntPtr.Zero, 0); | |
224 } catch (Exception) { | |
225 handle.Close(); | |
226 throw; | |
227 } | |
228 return handle; | |
229 } | |
230 private SafeFileHandle GetHandleForPipe(Byte epID) { | |
231 int epidx = epID & 0x7F; | |
232 if ((epID & 0x80) != 0) { | |
233 if (PipeHandlesIn != null && PipeHandlesIn.Length >= epidx && PipeHandlesIn[epidx] != null) return PipeHandlesIn[epidx]; | |
234 SafeFileHandle handle = OpenHandleForPipe(epID); | |
235 if (PipeHandlesIn == null) PipeHandlesIn = new SafeFileHandle[epidx + 1]; | |
236 else Array.Resize(ref PipeHandlesIn, epidx + 1); | |
237 PipeHandlesIn[epidx] = handle; | |
238 return handle; | |
239 } else { | |
240 if (PipeHandlesOut != null && PipeHandlesOut.Length >= epidx && PipeHandlesOut[epidx] != null) return PipeHandlesOut[epidx]; | |
241 SafeFileHandle handle = OpenHandleForPipe(epID); | |
242 if (PipeHandlesOut == null) PipeHandlesOut = new SafeFileHandle[epidx + 1]; | |
243 else Array.Resize(ref PipeHandlesOut, epidx + 1); | |
244 PipeHandlesOut[epidx] = handle; | |
245 return handle; | |
246 } | |
247 } | |
248 unsafe int PipeRead(Byte epnum, Byte[] buffer, int offset, int length) { | |
249 if (offset < 0 || length < 0 || offset + length > buffer.Length) throw new ArgumentOutOfRangeException("length", "The specified offset and length exceed the buffer length"); | |
250 SafeFileHandle handle = GetHandleForPipe(epnum); | |
251 uint ret; | |
252 fixed (Byte* b = buffer) { | |
253 if (!ReadFile(handle, b + offset, (uint)length, out ret, IntPtr.Zero)) throw new Win32Exception(Marshal.GetLastWin32Error()); | |
254 } | |
255 return (int)ret; | |
256 } | |
257 unsafe int PipeWrite(Byte epnum, Byte[] buffer, int offset, int length) { | |
258 if (offset < 0 || length < 0 || offset + length > buffer.Length) throw new ArgumentOutOfRangeException("length", "The specified offset and length exceed the buffer length"); | |
259 SafeFileHandle handle = GetHandleForPipe(epnum); | |
260 uint ret; | |
261 fixed (Byte* b = buffer) { | |
262 if (!WriteFile(handle, b + offset, (uint)length, out ret, IntPtr.Zero)) throw new Win32Exception(Marshal.GetLastWin32Error()); | |
263 } | |
264 return (int)ret; | |
265 } | |
266 public void PipeReset(byte pipeID) { | |
46
053cc617af54
USBLib: added functions to clear USB endpoint halt state
Ivo Smits <Ivo@UCIS.nl>
parents:
44
diff
changeset
|
267 SafeFileHandle handle = GetHandleForPipe(pipeID); |
053cc617af54
USBLib: added functions to clear USB endpoint halt state
Ivo Smits <Ivo@UCIS.nl>
parents:
44
diff
changeset
|
268 DeviceIoControl(handle, IOCTL_USBIO_RESET_PIPE, IntPtr.Zero, 0, IntPtr.Zero, 0); |
35 | 269 } |
270 | |
271 private unsafe int DeviceIoControl(SafeHandle hDevice, int IoControlCode, IntPtr InBuffer, int nInBufferSize, IntPtr OutBuffer, int nOutBufferSize) { | |
272 int pBytesReturned; | |
273 if (Kernel32.DeviceIoControl(hDevice, IoControlCode, InBuffer, nInBufferSize, OutBuffer, nOutBufferSize, out pBytesReturned, null)) | |
274 return pBytesReturned; | |
275 throw new Win32Exception(Marshal.GetLastWin32Error()); | |
276 } | |
277 | |
278 public override UsbPipeStream GetBulkStream(byte endpoint) { | |
279 return new PipeStream(this, endpoint, false, GetHandleForPipe(endpoint)); | |
280 } | |
281 public override UsbPipeStream GetInterruptStream(byte endpoint) { | |
282 return new PipeStream(this, endpoint, true, GetHandleForPipe(endpoint)); | |
283 } | |
284 | |
285 class PipeStream : UsbPipeStream { | |
286 private SafeFileHandle Handle; | |
287 public PipeStream(IUsbInterface device, Byte endpoint, Boolean interrupt, SafeFileHandle handle) : base(device, endpoint, interrupt) { | |
288 this.Handle = handle; | |
289 } | |
290 | |
291 public unsafe override void Write(byte[] buffer, int offset, int length) { | |
292 if (offset < 0 || length < 0 || offset + length > buffer.Length) throw new ArgumentOutOfRangeException("length", "The specified offset and length exceed the buffer length"); | |
293 uint ret; | |
294 fixed (Byte* b = buffer) { | |
295 if (!WriteFile(Handle, b + offset, (uint)length, out ret, IntPtr.Zero)) throw new Win32Exception(Marshal.GetLastWin32Error()); | |
296 } | |
297 if (ret <= 0) throw new EndOfStreamException("Could not write all data"); | |
298 } | |
299 | |
300 public unsafe override int Read(byte[] buffer, int offset, int length) { | |
301 if (offset < 0 || length < 0 || offset + length > buffer.Length) throw new ArgumentOutOfRangeException("length", "The specified offset and length exceed the buffer length"); | |
302 uint ret; | |
303 fixed (Byte* b = buffer) { | |
304 if (!WriteFile(Handle, b + offset, (uint)length, out ret, IntPtr.Zero)) throw new Win32Exception(Marshal.GetLastWin32Error()); | |
305 } | |
306 return (int)ret; | |
307 } | |
308 } | |
309 } | |
310 } |