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