Welcome to mirror list, hosted at ThFree Co, Russian Federation.

WinUsbDevice.cs « WinUsb « LibWinUsb - github.com/ClusterM/hakchi2.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 55ac2cd085a30ce555f8398cb72bcc35aaf5e866 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// Copyright © 2006-2010 Travis Robinson. All rights reserved.
// 
// website: http://sourceforge.net/projects/libusbdotnet
// e-mail:  libusbdotnet@gmail.com
// 
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2 of the License, or 
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful, but 
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
// for more details.
// 
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA. or 
// visit www.gnu.org.
// 
// 
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using LibUsbDotNet.Descriptors;
using LibUsbDotNet.Internal;
using LibUsbDotNet.Internal.WinUsb;
using LibUsbDotNet.Main;
using LibUsbDotNet.WinUsb.Internal;
using Microsoft.Win32.SafeHandles;

namespace LibUsbDotNet.WinUsb
{
    /// <summary> 
    /// Contains members specific to Microsofts WinUSB driver.
    /// </summary> 
    /// <remarks>
    /// A <see cref="WinUsbDevice"/> should be thought of as a part of, or an interface of a USB device.
    /// The <see cref="WinUsbDevice"/> class does not have members for selecting configurations and
    /// intefaces.  This is done at a lower level by the winusb driver depending on which interface the
    /// <see cref="WinUsbDevice"/> belongs to.
    /// </remarks> 
    public class WinUsbDevice : UsbDevice, IUsbInterface
    {
        private readonly string mDevicePath;
        private PowerPolicies mPowerPolicies;
        private SafeFileHandle mSafeDevHandle;

        internal WinUsbDevice(UsbApiBase usbApi,
                              SafeFileHandle usbHandle,
                              SafeHandle handle,
                              string devicePath)
            : base(usbApi, handle)
        {
            mDevicePath = devicePath;
            mSafeDevHandle = usbHandle;
            mPowerPolicies = new PowerPolicies(this);
        }

        /// <summary>
        /// Gets the power policies for this <see cref="WinUsbDevice"/>.
        /// </summary>
        public PowerPolicies PowerPolicy
        {
            get { return mPowerPolicies; }
        }

        /// <summary>
        /// Gets the device path used to open this <see cref="WinUsbDevice"/>.
        /// </summary>
        public string DevicePath
        {
            get { return mDevicePath; }
        }

        #region IUsbInterface Members

        /// <summary>
        /// Returns the DriverMode this USB device is using.
        /// </summary>
        public override DriverModeType DriverMode
        {
            get { return DriverModeType.WinUsb; }
        }

        /// <summary>
        /// Closes the <see cref="UsbDevice"/> and disposes any <see cref="UsbDevice.ActiveEndpoints"/>.
        /// </summary>
        /// <returns>True on success.</returns>
        public override bool Close()
        {
            if (IsOpen)
            {
                ActiveEndpoints.Clear();
                mUsbHandle.Close();

                if (mSafeDevHandle != null)
                    if (!mSafeDevHandle.IsClosed)
                        mSafeDevHandle.Close();
            }
            return true;
        }

        ///<summary>
        /// Opens the USB device handle.
        ///</summary>
        ///<returns>
        ///True if the device is already opened or was opened successfully.
        ///False if the device does not exists or is no longer valid.  
        ///</returns>
        public override bool Open()
        {
            if (IsOpen) return true;

            SafeFileHandle sfhDev;

            bool bSuccess = WinUsbAPI.OpenDevice(out sfhDev, mDevicePath);
            if (bSuccess)
            {
                SafeWinUsbInterfaceHandle handle = new SafeWinUsbInterfaceHandle();
                if ((bSuccess = WinUsbAPI.WinUsb_Initialize(sfhDev, ref handle)))
                {
                    mSafeDevHandle = sfhDev;
                    mUsbHandle = handle;
                    mPowerPolicies = new PowerPolicies(this);
                }
                else
                    UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "Open:Initialize", typeof (UsbDevice));
            }
            else
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "Open", typeof(UsbDevice));


            return bSuccess;
        }

        #endregion

        /// <summary>
        /// Opens a WinUsb directly from the user supplied device path. 
        /// </summary>
        /// <param name="devicePath">Device path (symbolic link) of the WinUsb device to open.</param>
        /// <param name="usbDevice">Returns an opened WinUsb device on success, null on failure.</param>
        /// <returns>True on success.</returns>
        public static bool Open(string devicePath, out WinUsbDevice usbDevice)
        {
            usbDevice = null;

            SafeFileHandle sfhDev;

            bool bSuccess = WinUsbAPI.OpenDevice(out sfhDev, devicePath);
            if (bSuccess)
            {
                SafeWinUsbInterfaceHandle handle = new SafeWinUsbInterfaceHandle();
                bSuccess = WinUsbAPI.WinUsb_Initialize(sfhDev, ref handle);
                if (bSuccess)
                {
                    usbDevice = new WinUsbDevice(WinUsbApi, sfhDev, handle, devicePath);
                }
                else
                    UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "Open:Initialize", typeof(UsbDevice));
            }
            else
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "Open", typeof(UsbDevice));


            return bSuccess;
        }

        /// <summary>
        /// Gets endpoint policies for the specified endpoint id.
        /// </summary>
        /// <param name="epNum">The endpoint ID to retrieve <see cref="PipePolicies"/> for.</param>
        /// <returns>A <see cref="PipePolicies"/> class.</returns>
        public PipePolicies EndpointPolicies(ReadEndpointID epNum) { return new PipePolicies(mUsbHandle, (byte) epNum); }

        /// <summary>
        /// Gets endpoint policies for the specified endpoint id.
        /// </summary>
        /// <param name="epNum">The endpoint ID to retrieve <see cref="PipePolicies"/> for.</param>
        /// <returns>A <see cref="PipePolicies"/> class.</returns>
        public PipePolicies EndpointPolicies(WriteEndpointID epNum) { return new PipePolicies(mUsbHandle, (byte) epNum); }

        /// <summary>
        /// Gets an interface associated with this <see cref="WinUsbDevice"/>.
        /// </summary>
        /// <param name="associatedInterfaceIndex">The index to retrieve. (0 = next interface, 1= interface after next, etc.).</param>
        /// <param name="usbDevice">A new <see cref="WinUsbDevice"/> class for the specified AssociatedInterfaceIndex.</param>
        /// <returns>True on success.</returns>
        public bool GetAssociatedInterface(byte associatedInterfaceIndex, out WinUsbDevice usbDevice)
        {
            usbDevice = null;
            IntPtr pHandle = IntPtr.Zero;
            bool bSuccess = WinUsbAPI.WinUsb_GetAssociatedInterface(mUsbHandle, associatedInterfaceIndex, ref pHandle);
            if (bSuccess)
            {
                SafeWinUsbInterfaceHandle tempHandle = new SafeWinUsbInterfaceHandle(pHandle);

                usbDevice = new WinUsbDevice(mUsbApi, null, tempHandle, mDevicePath);
            }
            if (!bSuccess)
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetAssociatedInterface", this);

            return bSuccess;
        }

        /// <summary>
        /// Gets the currently selected alternate settings number for the selected inteface.
        /// </summary>
        /// <param name="settingNumber">The selected AlternateSetting number.</param>
        /// <returns>True on success.</returns>
        public bool GetCurrentAlternateSetting(out byte settingNumber)
        {
            bool bSuccess;
            //settingNumber = 0;
            //if (LockDevice() != ErrorCode.None) return false;

            //try
            //{
            bSuccess = WinUsbAPI.WinUsb_GetCurrentAlternateSetting(mUsbHandle, out settingNumber);

            if (!bSuccess)
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetCurrentAlternateSetting", this);
            //}
            //finally
            //{
            //    UnlockDevice();
            //}


            return bSuccess;
        }

        /// <summary>
        /// Gets the device speed.
        /// </summary>
        /// <param name="deviceSpeed">The device speed.</param>
        /// <returns>True on success.</returns>
        public bool QueryDeviceSpeed(out DeviceSpeedTypes deviceSpeed)
        {
            deviceSpeed = DeviceSpeedTypes.Undefined;
            byte[] buf = new byte[1];
            int uTransferLength = 1;
            bool bSuccess = WinUsbAPI.WinUsb_QueryDeviceInformation(mUsbHandle, DeviceInformationTypes.DeviceSpeed, ref uTransferLength, buf);

            if (bSuccess)
            {
                deviceSpeed = (DeviceSpeedTypes) buf[0];
            }
            else
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "QueryDeviceInformation:QueryDeviceSpeed", this);

            return bSuccess;
        }

        /// <summary>
        /// Gets a <see cref="UsbInterfaceDescriptor"/> for the specified AlternateInterfaceNumber,
        /// </summary>
        /// <param name="alternateInterfaceNumber">The alternate interface index for the <see cref="UsbInterfaceDescriptor"/> to retrieve. </param>
        /// <param name="usbAltInterfaceDescriptor">The <see cref="UsbInterfaceDescriptor"/> for the specified AlternateInterfaceNumber.</param>
        /// <returns>True on success.</returns>
        public bool QueryInterfaceSettings(byte alternateInterfaceNumber, ref UsbInterfaceDescriptor usbAltInterfaceDescriptor)
        {
            bool bSuccess;
            //if (mSemDeviceLock != null)
            //{
            //    if (LockDevice() != ErrorCode.None) return false;
            //}

            //try
            //{
            bSuccess = WinUsbAPI.WinUsb_QueryInterfaceSettings(Handle, alternateInterfaceNumber, usbAltInterfaceDescriptor);
            if (!bSuccess)
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "QueryInterfaceSettings", this);
            //}
            //finally
            //{
            //    if (mSemDeviceLock != null) UnlockDevice();
            //}

            return bSuccess;
        }

        internal bool GetPowerPolicy(PowerPolicyType policyType, ref int valueLength, IntPtr pBuffer)
        {
            bool bSuccess = WinUsbAPI.WinUsb_GetPowerPolicy(mUsbHandle, policyType, ref valueLength, pBuffer);

            if (!bSuccess)
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetPowerPolicy", this);

            return bSuccess;
        }

        /// <summary>
        /// Gets a list a valid, connected WinUSB device inteface paths for the a given WinUSB device interface guid.
        /// </summary>
        /// <param name="interfaceGuid">A WinUSB DeviceInterfaceGUID.  This is set in the usb devices inf file when the drivers for it are installed.</param>
        /// <param name="devicePathList">A list of connected WinUSB device inteface paths.</param>
        /// <returns>True if one or more device paths were found.  False if no devices are found or an error occured. <see cref="UsbDevice.UsbErrorEvent"/> </returns>
        public static bool GetDevicePathList(Guid interfaceGuid, out List<String> devicePathList) { return WinUsbRegistry.GetDevicePathList(interfaceGuid, out devicePathList); }

        internal bool SetPowerPolicy(PowerPolicyType policyType, int valueLength, IntPtr pBuffer)
        {
            bool bSuccess = WinUsbAPI.WinUsb_SetPowerPolicy(mUsbHandle, policyType, valueLength, pBuffer);

            if (!bSuccess)
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "SetPowerPolicy", this);

            return bSuccess;
        }

        /// <summary>
        /// Closes the device. <see cref="WinUsbDevice.Close"/>.
        /// </summary>
        ~WinUsbDevice() { Close(); }
    }
}