libusbk-sys 0.2.0

Rust Windows library for accessing USB devices via libusbK
Documentation
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
#region Copyright(c) Travis Robinson

// Copyright (c) 2012 Travis Robinson <libusbdotnet@gmail.com>
// All rights reserved.
// 
// TestParameters.cs
// 
// Created:      03.05.2012
// Last Updated: 03.05.2012
// 
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
// 	  
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL TRAVIS LEE ROBINSON 
// BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 
// THE POSSIBILITY OF SUCH DAMAGE.
#endregion


using System;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using Win32;


namespace libusbK.Examples
{
    internal abstract class TestParameters
    {
        protected TestParameters(int vid,
                                 int pid,
                                 int altInterfaceId,
                                 int pipeId,
                                 int maxTransfersTotal,
                                 string logFilename)
        {
            MI = -1;
            ;
            Vid = vid;
            Pid = pid;
            PipeId = pipeId;
            AltInterfaceId = altInterfaceId;
            MaxTransfersTotal = maxTransfersTotal;
            LogFilename = logFilename;
        }


        #region Public Members

        public int AltInterfaceId;

        public bool ConfigureDevice(out WINUSB_PIPE_INFORMATION_EX pipeInfo,
                                    out UsbK usb,
                                    out USB_INTERFACE_DESCRIPTOR interfaceDescriptor)
        {
            bool success;
            Console.WriteLine("Finding usb device by VID/PID.. ({0:X4}h / {1:X4}h)",
                              Vid,
                              Pid);

            // Use a patttern match to include only matching devices.
            // NOTE: You can use the '*' and '?' chars as wildcards for all chars or a single char (respectively). 
            KLST_PATTERN_MATCH patternMatch = new KLST_PATTERN_MATCH();
            if (MI != -1)
                patternMatch.DeviceID = String.Format("USB\\VID_{0:X4}&PID_{1:X4}&MI_{2:X2}*",
                                                        Vid,
                                                        Pid,
                                                        MI);
            else
                patternMatch.DeviceID = String.Format("USB\\VID_{0:X4}&PID_{1:X4}*",
                                                        Vid,
                                                        Pid);

            LstK deviceList = new LstK(KLST_FLAG.NONE,
                                       ref patternMatch);
            KLST_DEVINFO_HANDLE deviceInfo;
            interfaceDescriptor = new USB_INTERFACE_DESCRIPTOR();
            pipeInfo = new WINUSB_PIPE_INFORMATION_EX();
            usb = null;

            // Iterate the devices looking for a matching alt-interface and endpoint id.
            while (deviceList.MoveNext(out deviceInfo))
            {
                // libusbK class contructors can throw exceptions; For instance, if the device is
                // using the WinUsb driver and already in-use by another application.
                Console.WriteLine("Opening usb device..");
                usb = new UsbK(deviceInfo);

                Console.WriteLine("Finding interface and endpoint by PipeId..");
                success = FindPipeAndInterface(usb,
                                               out interfaceDescriptor,
                                               out pipeInfo);
                if (success) break;

                Console.WriteLine("PipeId {0:X2}h not found on this device.",
                                  PipeId);
                usb.Free();
                usb = null;
            }
            if (ReferenceEquals(usb,
                                null))
            {
                Console.WriteLine("Usb device not found: {0}",
                                  patternMatch.DeviceID);
                success = false;
                goto Done;
            }

            MI = interfaceDescriptor.bInterfaceNumber;
            AltInterfaceId = interfaceDescriptor.bAlternateSetting;
            PipeId = pipeInfo.PipeId;

            // Set interface alt setting.
            Console.WriteLine("Setting interface #{0} to bAlternateSetting #{1}..",
                              interfaceDescriptor.bInterfaceNumber,
                              interfaceDescriptor.bAlternateSetting);
            success = usb.SetAltInterface(interfaceDescriptor.bInterfaceNumber,
                                          false,
                                          interfaceDescriptor.bAlternateSetting);
            if (!success)
            {
                Console.WriteLine("SetAltInterface failed. ErrorCode={0:X8}h",
                                  Marshal.GetLastWin32Error());
                Console.WriteLine(interfaceDescriptor.ToString());
            }

            Done:
            deviceList.Free();

            return success;
        }

        public HiPerfTimer Dcs = new HiPerfTimer();

        public void FillFromCommandLine(string commandLine)
        {
            commandLine = Regex.Replace(commandLine,
                                        "^(\".+?\"|\\S+)\\s*",
                                        "");
            string exp = String.Empty;
            exp += makeArgExpression("Vid",
                                     NumberStyles.HexNumber) + "|";
            exp += makeArgExpression("Pid",
                                     NumberStyles.HexNumber) + "|";
            exp += makeArgExpression("PipeId",
                                     NumberStyles.HexNumber) + "|";
            exp += makeArgExpression("AltId",
                                     NumberStyles.Integer) + "|";
            exp += makeArgExpression("MI",
                                     NumberStyles.Integer) + "|";
            exp += makeArgExpression("Log",
                                     NumberStyles.None);

            m_CommandArguments = Regex.Matches(commandLine,
                                               exp,
                                               RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase |
                                               RegexOptions.IgnorePatternWhitespace);

            foreach (Match m in m_CommandArguments)
            {
                Group gVid = m.Groups["Vid"];
                Group gPid = m.Groups["Pid"];
                Group gMI = m.Groups["MI"];
                Group gPipeId = m.Groups["PipeId"];
                Group gAltId = m.Groups["AltId"];
                Group gLog = m.Groups["Log"];
                Group gIsHex = m.Groups["IsHex"];

                if (gVid.Success)
                    Vid = gIsHex.Success
                              ? UInt16.Parse(gVid.Value,
                                             NumberStyles.HexNumber)
                              : UInt16.Parse(gVid.Value);
                else if (gPid.Success)
                    Pid = gIsHex.Success
                              ? UInt16.Parse(gPid.Value,
                                             NumberStyles.HexNumber)
                              : UInt16.Parse(gPid.Value);
                else if (gMI.Success)
                    MI = gIsHex.Success
                             ? UInt16.Parse(gMI.Value,
                                            NumberStyles.HexNumber)
                             : UInt16.Parse(gMI.Value);
                else if (gPipeId.Success)
                    PipeId = gIsHex.Success
                                 ? Byte.Parse(gPipeId.Value,
                                              NumberStyles.HexNumber)
                                 : Byte.Parse(gPipeId.Value);
                else if (gAltId.Success)
                    AltInterfaceId = gIsHex.Success
                                         ? Byte.Parse(gAltId.Value,
                                                      NumberStyles.HexNumber)
                                         : Byte.Parse(gAltId.Value);
                else if (gLog.Success)
                    LogFilename = gLog.Value;
                else
                {
                    throw new Exception("Invalid argument:" + m.Value);
                }
            }
        }

        public bool FindPipeAndInterface(UsbK usb,
                                         out USB_INTERFACE_DESCRIPTOR interfaceDescriptor,
                                         out WINUSB_PIPE_INFORMATION_EX pipeInfo)
        {
            if (FindPipeAndInterface(usb,
                                     out interfaceDescriptor,
                                     out pipeInfo,
                                     AltInterfaceId,
                                     PipeId))
            {
                AltInterfaceId = interfaceDescriptor.bAlternateSetting;
                PipeId = pipeInfo.PipeId;

                return true;
            }
            return false;
        }

        public static bool FindPipeAndInterface(UsbK usb,
                                                out USB_INTERFACE_DESCRIPTOR interfaceDescriptor,
                                                out WINUSB_PIPE_INFORMATION_EX pipeInfo,
                                                int altInterfaceId,
                                                int pipeId)
        {
            byte interfaceIndex = 0;
            interfaceDescriptor = new USB_INTERFACE_DESCRIPTOR();
            pipeInfo = new WINUSB_PIPE_INFORMATION_EX();
            while (usb.SelectInterface(interfaceIndex,
                                       true))
            {
                byte altSettingNumber = 0;
                while (usb.QueryInterfaceSettings(altSettingNumber,
                                                  out interfaceDescriptor))
                {
                    if (altInterfaceId == -1 || altInterfaceId == altSettingNumber)
                    {
                        byte pipeIndex = 0;
                        while (usb.QueryPipeEx(altSettingNumber,
                                             pipeIndex++,
                                             out pipeInfo))
                        {
                            if ((pipeInfo.MaximumPacketSize > 0) &&
                                pipeId == -1 || pipeInfo.PipeId == pipeId ||
                                ((pipeId & 0xF) == 0 && ((pipeId & 0x80) == (pipeInfo.PipeId & 0x80))))
                            {
                                goto FindInterfaceDone;
                            }
                            pipeInfo.PipeId = 0;
                        }
                    }
                    altSettingNumber++;
                }
                interfaceIndex++;
            }

            FindInterfaceDone:
            return pipeInfo.PipeId != 0;
        }

        public void Free()
        {
            if (fileLoggingEnabled && logStream != null)
            {
                logStream.Flush();
                logStream.Close();
                logStream = null;
            }
        }

        public void Init()
        {
            if (!String.IsNullOrEmpty(LogFilename))
            {
                logStream = new StreamWriter(LogFilename);
                fileLoggingEnabled = true;
            }
        }

        public void Log(String text)
        {
            if (fileLoggingEnabled) logStream.Write(text);
            else Console.Write(text);
        }

        public void Log(String format,
                        params object[] args)
        {
            if (fileLoggingEnabled)
                logStream.Write(format,
                                args);
            else
                Console.Write(format,
                              args);
        }

        public string LogFilename;

        public void LogLn(String text)
        {
            if (fileLoggingEnabled) logStream.WriteLine(text);
            else Console.WriteLine(text);
        }

        public void LogLn(String format,
                          params object[] args)
        {
            if (fileLoggingEnabled)
                logStream.WriteLine(format,
                                    args);
            else
                Console.WriteLine(format,
                                  args);
        }

        public int MI;
        public int MaxTransfersTotal;
        public int Pid;
        public int PipeId;

        public bool ShowTestReady()
        {
            while (Console.KeyAvailable)
                Console.ReadKey(true);

            Console.WriteLine("Test ready:");
            Console.Write(ToString());

            if (!String.IsNullOrEmpty(LogFilename))
                Console.WriteLine("Logging output to file: {0}",
                                  LogFilename);

            Console.WriteLine("Press 'Q' to abort or any other key to continue..");
            ConsoleKeyInfo key = Console.ReadKey(true);
            if (key.KeyChar == 'q' || key.KeyChar == 'Q') return false;

            Console.WriteLine();
            Console.WriteLine("Starting test..");
            Console.WriteLine();

            return true;
        }

        public override string ToString()
        {
            return
                String.Format(
                    "Vid: {0:X4}h\nPid: {1:X4}h\nMI: {2:X2}h\nPipeId: {3:X2}h\nMaxTransfersTotal: {4}\n\nLogFilename: {5}\n",
                    Vid,
                    Pid,
                    MI,
                    PipeId,
                    MaxTransfersTotal,
                    LogFilename);
        }

        public int Vid;
        #endregion


        #region Private Members

        private bool fileLoggingEnabled;

        private StreamWriter logStream;
        private MatchCollection m_CommandArguments;

        private string makeArgExpression(string argName,
                                         NumberStyles argType)
        {
            const string argsep = @"\W\s*";

            switch (argType)
            {
                case NumberStyles.None:
                    return String.Format(@"(({0}{1}(?<{0}>{2}))\s*)",
                                         argName,
                                         argsep,
                                         "(\".+?\"|\\S+)");
                case NumberStyles.Integer:
                case NumberStyles.HexNumber:
                    return String.Format(@"(({0}{1}(?<IsHex>0x)?(?<{0}>[0-9A-F]+))(?<IsHex>h)?\s*)",
                                         argName,
                                         argsep);
                default:
                    throw new Exception();
            }
        }
        #endregion
    }

    internal class IsoTestParameters : TestParameters
    {
        #region Public Members

        public IsoTestParameters(int vid,
                                 int pid,
                                 int altInterfaceId,
                                 int pipeId,
                                 int maxOutstandingTransfers,
                                 int maxTransfersTotal,
                                 string logFilename,
                                 uint isoPacketsPerTransfer)
            : base(vid,
                   pid,
                   altInterfaceId,
                   pipeId,
                   maxTransfersTotal,
                   logFilename)
        {
            IsoPacketsPerTransfer = isoPacketsPerTransfer;
            MaxOutstandingTransfers = maxOutstandingTransfers;

            FillFromCommandLine(Environment.CommandLine);
            Init();
        }

        public uint IsoPacketsPerTransfer;
        public int MaxOutstandingTransfers;

        public override string ToString()
        {
            string fmt = String.Empty;
            fmt += "IsoPacketsPerTransfer: {0}\n";
            fmt += "MaxOutstandingTransfers: {1}\n";

            object[] args = new object[]
                                {
                                    IsoPacketsPerTransfer, MaxOutstandingTransfers
                                };
            return base.ToString() + string.Format(fmt,
                                                   args);
        }
        #endregion
    }

    internal class StmTestParameters : TestParameters
    {
        #region Public Members

        public StmTestParameters(int vid,
                                 int pid,
                                 int altInterfaceId,
                                 byte pipeId,
                                 int maxTransfersTotal,
                                 string logFilename,
                                 int transferBufferSize,
                                 int maxPendingIO,
                                 int maxPendingTransfers)
            : base(vid,
                   pid,
                   altInterfaceId,
                   pipeId,
                   maxTransfersTotal,
                   logFilename)
        {
            TransferBufferSize = transferBufferSize;
            MaxPendingIO = maxPendingIO;
            MaxPendingTransfers = maxPendingTransfers;

            FillFromCommandLine(Environment.CommandLine);
            Init();
        }

        public int MaxPendingIO;
        public int MaxPendingTransfers;

        public override string ToString()
        {
            string fmt = String.Empty;
            fmt += "TransferBufferSize: {0}\n";
            fmt += "MaxPendingIO: {1}\n";
            fmt += "MaxPendingTransfers: {2}\n";

            object[] args = new object[]
                                {
                                    TransferBufferSize, MaxPendingIO, MaxPendingTransfers
                                };
            return base.ToString() + string.Format(fmt,
                                                   args);
        }

        public int TransferBufferSize;
        #endregion
    }

    internal class AsyncTestParameters : TestParameters
    {
        #region Public Members

        public AsyncTestParameters(int vid,
                                 int pid,
                                 int altInterfaceId,
                                 byte pipeId,
                                 int maxTransfersTotal,
                                 string logFilename,
                                 int transferBufferSize,
                                 int maxPendingIO)
            : base(vid,
                   pid,
                   altInterfaceId,
                   pipeId,
                   maxTransfersTotal,
                   logFilename)
        {
            TransferBufferSize = transferBufferSize;
            MaxPendingIO = maxPendingIO;

            FillFromCommandLine(Environment.CommandLine);
            Init();
        }

        public int MaxPendingIO;

        public override string ToString()
        {
            string fmt = String.Empty;
            fmt += "TransferBufferSize: {0}\n";
            fmt += "MaxPendingIO: {1}\n";

            object[] args = new object[]
                                {
                                    TransferBufferSize, MaxPendingIO
                                };
            return base.ToString() + string.Format(fmt,
                                                   args);
        }

        public int TransferBufferSize;
        #endregion
    }
}