forked from madrang/MFDebugger-Mono
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Streams - Original.cs
1381 lines (1119 loc) · 48.8 KB
/
Streams - Original.cs
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Text;
using System.Management;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Net;
using System.Net.Sockets;
namespace Microsoft.SPOT.Debugger
{
// This is an internal object implementing IAsyncResult with fields
// for all of the relevant data necessary to complete the IO operation.
// This is used by AsyncFSCallback and all of the async methods.
unsafe internal class AsyncFileStream_AsyncResult : IAsyncResult
{
private unsafe static readonly IOCompletionCallback s_callback = new IOCompletionCallback( DoneCallback );
internal AsyncCallback m_userCallback;
internal Object m_userStateObject;
internal ManualResetEvent m_waitHandle;
internal GCHandle m_bufferHandle; // GCHandle to pin byte[].
internal bool m_bufferIsPinned; // Whether our m_bufferHandle is valid.
internal bool m_isWrite; // Whether this is a read or a write
internal bool m_isComplete;
internal bool m_EndXxxCalled; // Whether we've called EndXxx already.
internal int m_numBytes; // number of bytes read OR written
internal int m_errorCode;
internal NativeOverlapped* m_overlapped;
internal AsyncFileStream_AsyncResult( AsyncCallback userCallback, Object stateObject, bool isWrite )
{
m_userCallback = userCallback;
m_userStateObject = stateObject;
m_waitHandle = new ManualResetEvent( false );
m_isWrite = isWrite;
Overlapped overlapped = new Overlapped( 0, 0, IntPtr.Zero, this );
m_overlapped = overlapped.Pack( s_callback, null );
}
public virtual Object AsyncState
{
get { return m_userStateObject; }
}
public bool IsCompleted
{
get { return m_isComplete; }
set { m_isComplete = value; }
}
public WaitHandle AsyncWaitHandle
{
get { return m_waitHandle; }
}
public bool CompletedSynchronously
{
get { return false; }
}
internal void SignalCompleted()
{
AsyncCallback userCallback = null;
lock(this)
{
if(m_isComplete == false)
{
userCallback = m_userCallback;
ManualResetEvent wh = m_waitHandle;
if(wh != null && wh.Set() == false)
{
Native.ThrowIOException( string.Empty );
}
// Set IsCompleted to true AFTER we've signalled the WaitHandle!
// Necessary since we close the WaitHandle after checking IsCompleted,
// so we could cause the SetEvent call to fail.
m_isComplete = true;
ReleaseMemory();
}
}
if(userCallback != null)
{
userCallback( this );
}
}
internal void WaitCompleted()
{
ManualResetEvent wh = m_waitHandle;
if(wh != null)
{
if(m_isComplete == false)
{
wh.WaitOne();
// There's a subtle race condition here. In AsyncFSCallback,
// I must signal the WaitHandle then set _isComplete to be true,
// to avoid closing the WaitHandle before AsyncFSCallback has
// signalled it. But with that behavior and the optimization
// to call WaitOne only when IsCompleted is false, it's possible
// to return from this method before IsCompleted is set to true.
// This is currently completely harmless, so the most efficient
// solution of just setting the field seems like the right thing
// to do. -- BrianGru, 6/19/2000
m_isComplete = true;
}
wh.Close();
}
}
internal NativeOverlapped* OverlappedPtr
{
get { return m_overlapped; }
}
internal unsafe void ReleaseMemory()
{
if(m_overlapped != null)
{
Overlapped.Free( m_overlapped );
m_overlapped = null;
}
UnpinBuffer();
}
internal void PinBuffer( byte[] buffer )
{
m_bufferHandle = GCHandle.Alloc( buffer, GCHandleType.Pinned );
m_bufferIsPinned = true;
}
internal void UnpinBuffer()
{
if(m_bufferIsPinned)
{
m_bufferHandle.Free();
m_bufferIsPinned = false;
}
}
// this callback is called by a free thread in the threadpool when the IO operation completes.
unsafe private static void DoneCallback( uint errorCode, uint numBytes, NativeOverlapped* pOverlapped )
{
if(errorCode == Native.ERROR_OPERATION_ABORTED)
{
numBytes = 0;
errorCode = 0;
}
// Unpack overlapped
Overlapped overlapped = Overlapped.Unpack( pOverlapped );
// Free the overlapped struct in EndRead/EndWrite.
// Extract async result from overlapped
AsyncFileStream_AsyncResult asyncResult = (AsyncFileStream_AsyncResult)overlapped.AsyncResult;
asyncResult.m_numBytes = (int)numBytes;
asyncResult.m_errorCode = (int)errorCode;
asyncResult.SignalCompleted();
}
}
public class GenericAsyncStream : System.IO.Stream, IDisposable, WireProtocol.IStreamAvailableCharacters
{
protected SafeHandle m_handle;
protected ArrayList m_outstandingRequests;
protected GenericAsyncStream(SafeHandle handle)
{
System.Diagnostics.Debug.Assert(handle != null);
m_handle = handle;
if(ThreadPool.BindHandle( m_handle ) == false)
{
throw new IOException( "BindHandle Failed" );
}
m_outstandingRequests = ArrayList.Synchronized(new ArrayList());
}
~GenericAsyncStream()
{
Dispose( false );
}
public void CancelPendingIO()
{
lock(m_outstandingRequests.SyncRoot)
{
for(int i = m_outstandingRequests.Count - 1; i >= 0; i--)
{
AsyncFileStream_AsyncResult asfar = (AsyncFileStream_AsyncResult)m_outstandingRequests[i];
asfar.SignalCompleted();
}
m_outstandingRequests.Clear();
}
}
protected override void Dispose( bool disposing )
{
// Nothing will be done differently based on whether we are disposing vs. finalizing.
lock (this)
{
if (m_handle != null && !m_handle.IsInvalid)
{
if(disposing)
{
CancelPendingIO();
}
m_handle.Close();
m_handle.SetHandleAsInvalid();
}
}
base.Dispose(disposing);
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return true; }
}
public override long Length
{
get { throw NotImplemented(); }
}
public override long Position
{
get { throw NotImplemented(); }
set { throw NotImplemented(); }
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return BeginReadCore(buffer, offset, count, callback, state);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return BeginWriteCore(buffer, offset, count, callback, state);
}
public override void Close()
{
Dispose(true);
}
public override int EndRead( IAsyncResult asyncResult )
{
AsyncFileStream_AsyncResult afsar = CheckParameterForEnd( asyncResult, false );
afsar.WaitCompleted();
m_outstandingRequests.Remove( afsar );
// Now check for any error during the read.
if(afsar.m_errorCode != 0) throw new IOException( "Async Read failed", afsar.m_errorCode );
return afsar.m_numBytes;
}
public override void EndWrite( IAsyncResult asyncResult )
{
AsyncFileStream_AsyncResult afsar = CheckParameterForEnd( asyncResult, true );
afsar.WaitCompleted();
m_outstandingRequests.Remove( afsar );
// Now check for any error during the write.
if(afsar.m_errorCode != 0) throw new IOException( "Async Write failed", afsar.m_errorCode );
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count)
{
IAsyncResult result = BeginRead(buffer, offset, count, null, null);
return EndRead( result );
}
public override long Seek(long offset, SeekOrigin origin)
{
throw NotImplemented();
}
public override void SetLength(long value)
{
throw NotImplemented();
}
public override void Write(byte[] buffer, int offset, int count)
{
IAsyncResult result = BeginWrite(buffer, offset, count, null, null);
EndWrite( result );
}
public SafeHandle Handle
{
get
{
return m_handle;
}
}
public virtual int AvailableCharacters
{
get
{
return 0;
}
}
private Exception NotImplemented()
{
return new NotSupportedException( "Not Supported" );
}
private void CheckParametersForBegin( byte[] array, int offset, int count )
{
if(array == null) throw new ArgumentNullException( "array" );
if(offset < 0) throw new ArgumentOutOfRangeException( "offset" );
if(count < 0 || array.Length - offset < count) throw new ArgumentOutOfRangeException( "count" );
if(m_handle.IsInvalid)
{
throw new ObjectDisposedException( null );
}
}
private AsyncFileStream_AsyncResult CheckParameterForEnd( IAsyncResult asyncResult, bool isWrite )
{
if(asyncResult == null) throw new ArgumentNullException( "asyncResult" );
AsyncFileStream_AsyncResult afsar = asyncResult as AsyncFileStream_AsyncResult;
if(afsar == null || afsar.m_isWrite != isWrite) throw new ArgumentException( "asyncResult" );
if(afsar.m_EndXxxCalled) throw new InvalidOperationException( "EndRead called twice" );
afsar.m_EndXxxCalled = true;
return afsar;
}
private unsafe IAsyncResult BeginReadCore( byte[] array, int offset, int count, AsyncCallback userCallback, Object stateObject )
{
CheckParametersForBegin( array, offset, count );
AsyncFileStream_AsyncResult asyncResult = new AsyncFileStream_AsyncResult( userCallback, stateObject, false );
if(count == 0)
{
asyncResult.SignalCompleted();
}
else
{
// Keep the array in one location in memory until the OS writes the
// relevant data into the array. Free GCHandle later.
asyncResult.PinBuffer( array );
fixed(byte* p = array)
{
int numBytesRead = 0;
bool res;
res = Native.ReadFile( m_handle.DangerousGetHandle(), p + offset, count, out numBytesRead, asyncResult.OverlappedPtr );
if(res == false)
{
if(HandleErrorSituation( "BeginRead", false ))
{
asyncResult.SignalCompleted();
}
else
{
m_outstandingRequests.Add( asyncResult );
}
}
}
}
return asyncResult;
}
private unsafe IAsyncResult BeginWriteCore( byte[] array, int offset, int count, AsyncCallback userCallback, Object stateObject )
{
CheckParametersForBegin( array, offset, count );
AsyncFileStream_AsyncResult asyncResult = new AsyncFileStream_AsyncResult( userCallback, stateObject, true );
if(count == 0)
{
asyncResult.SignalCompleted();
}
else
{
// Keep the array in one location in memory until the OS writes the
// relevant data into the array. Free GCHandle later.
asyncResult.PinBuffer( array );
fixed(byte* p = array)
{
int numBytesWritten = 0;
bool res;
res = Native.WriteFile( m_handle.DangerousGetHandle(), p + offset, count, out numBytesWritten, asyncResult.OverlappedPtr );
if(res == false)
{
if(HandleErrorSituation( "BeginWrite", true ))
{
asyncResult.SignalCompleted();
}
else
{
m_outstandingRequests.Add( asyncResult );
}
}
}
}
return asyncResult;
}
protected virtual bool HandleErrorSituation( string msg, bool isWrite )
{
int hr = Marshal.GetLastWin32Error();
// For invalid handles, detect the error and close ourselves
// to prevent a malicious app from stealing someone else's file
// handle when the OS recycles the handle number.
if(hr == Native.ERROR_INVALID_HANDLE)
{
m_handle.Close();
}
if(hr != Native.ERROR_IO_PENDING)
{
if(isWrite == false && hr == Native.ERROR_HANDLE_EOF)
{
throw new EndOfStreamException( msg );
}
throw new IOException( msg, hr );
}
return false;
}
#region IDisposable Members
void IDisposable.Dispose()
{
base.Dispose( true );
Dispose( true );
GC.SuppressFinalize( this );
}
#endregion
}
public class AsyncFileStream : GenericAsyncStream
{
private string m_fileName = null;
public AsyncFileStream( string file, System.IO.FileShare share ) : base( OpenHandle( file, share ) )
{
m_fileName = file;
}
static private SafeFileHandle OpenHandle( string file, System.IO.FileShare share )
{
if(file == null || file.Length == 0)
{
throw new ArgumentNullException( "file" );
}
SafeFileHandle handle = Native.CreateFile(file, Native.GENERIC_READ | Native.GENERIC_WRITE, share, Native.NULL, System.IO.FileMode.Open, Native.FILE_FLAG_OVERLAPPED, Native.NULL);
if(handle.IsInvalid)
{
throw new InvalidOperationException( String.Format( "Cannot open {0}", file ) );
}
return handle;
}
public String Name
{
get
{
return m_fileName;
}
}
public unsafe override int AvailableCharacters
{
get
{
int bytesRead;
int totalBytesAvail;
int bytesLeftThisMessage;
if(Native.PeekNamedPipe( m_handle.DangerousGetHandle(), (byte*)Native.NULL, 0, out bytesRead, out totalBytesAvail, out bytesLeftThisMessage ) == false)
{
totalBytesAvail = 1;
}
return totalBytesAvail;
}
}
}
public class AsyncSerialStream : AsyncFileStream
{
public AsyncSerialStream( string port, uint baudrate ) : base( port, System.IO.FileShare.None )
{
Native.COMMTIMEOUTS cto = new Native.COMMTIMEOUTS(); cto.Initialize();
Native.DCB dcb = new Native.DCB (); dcb.Initialize();
Native.GetCommState( m_handle.DangerousGetHandle(), ref dcb );
dcb.BaudRate = baudrate;
dcb.ByteSize = 8;
dcb.StopBits = 0;
dcb.__BitField = 0;
dcb.__BitField &= ~Native.DCB.mask_fDtrControl ;
dcb.__BitField &= ~Native.DCB.mask_fRtsControl ;
dcb.__BitField |= Native.DCB.mask_fBinary ;
dcb.__BitField &= ~Native.DCB.mask_fParity ;
dcb.__BitField &= ~Native.DCB.mask_fOutX ;
dcb.__BitField &= ~Native.DCB.mask_fInX ;
dcb.__BitField &= ~Native.DCB.mask_fErrorChar ;
dcb.__BitField &= ~Native.DCB.mask_fNull ;
dcb.__BitField |= Native.DCB.mask_fAbortOnError;
Native.SetCommState( m_handle.DangerousGetHandle(), ref dcb );
Native.SetCommTimeouts( m_handle.DangerousGetHandle(), ref cto );
}
public override int AvailableCharacters
{
get
{
Native.COMSTAT cs = new Native.COMSTAT(); cs.Initialize();
uint errors;
Native.ClearCommError( m_handle.DangerousGetHandle(), out errors, ref cs );
return (int)cs.cbInQue;
}
}
protected override bool HandleErrorSituation( string msg, bool isWrite )
{
if(Marshal.GetLastWin32Error() == Native.ERROR_OPERATION_ABORTED)
{
Native.COMSTAT cs = new Native.COMSTAT(); cs.Initialize();
uint errors;
Native.ClearCommError( m_handle.DangerousGetHandle(), out errors, ref cs );
return true;
}
return base.HandleErrorSituation( msg, isWrite );
}
public void ConfigureXonXoff( bool fEnable )
{
Native.DCB dcb = new Native.DCB(); dcb.Initialize();
Native.GetCommState( m_handle.DangerousGetHandle(), ref dcb );
if(fEnable)
{
dcb.__BitField |= Native.DCB.mask_fOutX;
}
else
{
dcb.__BitField &= ~Native.DCB.mask_fOutX;
}
Native.SetCommState( m_handle.DangerousGetHandle(), ref dcb );
}
static public PortDefinition[] EnumeratePorts()
{
SortedList lst = new SortedList();
try
{
RegistryKey key = Registry.LocalMachine.OpenSubKey( @"HARDWARE\DEVICEMAP\SERIALCOMM" );
foreach(string name in key.GetValueNames())
{
string val = (string)key.GetValue( name );
PortDefinition pd = PortDefinition.CreateInstanceForSerial( val, @"\\.\" + val, 115200 );
lst.Add( val, pd );
}
}
catch
{
}
ICollection col = lst.Values;
PortDefinition[] res = new PortDefinition[col.Count];
col.CopyTo( res, 0 );
return res;
}
}
public class AsyncNetworkStream : NetworkStream, WireProtocol.IStreamAvailableCharacters
{
public AsyncNetworkStream(Socket socket, bool ownsSocket)
: base(socket, ownsSocket)
{
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#region IStreamAvailableCharacters
int WireProtocol.IStreamAvailableCharacters.AvailableCharacters
{
get
{
return this.Socket.Available;
}
}
#endregion
}
[Serializable]
public class PortDefinition_Serial : PortDefinition
{
uint m_baudRate;
public PortDefinition_Serial( string displayName, string port, uint baudRate ) : base(displayName, port)
{
m_baudRate = baudRate;
}
public uint BaudRate
{
get
{
return m_baudRate;
}
set
{
m_baudRate = value;
}
}
public override Stream CreateStream()
{
return new AsyncSerialStream( m_port, m_baudRate );
}
public override string PersistName
{
get { return m_displayName; }
}
}
public class UsbDeviceDiscovery : IDisposable
{
public enum DeviceChanged : ushort
{
None = 0,
Configuration = 1,
DeviceArrival = 2,
DeviceRemoval = 3,
Docking = 4,
}
public delegate void DeviceChangedEventHandler( DeviceChanged change );
private const string c_EventQuery = "Win32_DeviceChangeEvent";
private const string c_InstanceQuery = "SELECT * FROM __InstanceOperationEvent WITHIN 5 WHERE TargetInstance ISA \"Win32_PnPEntity\"";
ManagementEventWatcher m_eventWatcher;
DeviceChangedEventHandler m_subscribers;
public UsbDeviceDiscovery()
{
}
~UsbDeviceDiscovery()
{
try
{
Dispose();
}
catch
{
}
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public void Dispose()
{
if( m_eventWatcher != null )
{
m_eventWatcher.Stop();
m_eventWatcher = null;
m_subscribers = null;
}
GC.SuppressFinalize(this);
}
// subscribing to this event allows applications to be notified when USB devices are plugged and unplugged
// as well as configuration changed and docking; upon receiving teh notification the applicaion can decide
// to call UsbDeviceDiscovery.EnumeratePorts to get an updated list of Usb devices
public event DeviceChangedEventHandler OnDeviceChanged
{
[MethodImplAttribute(MethodImplOptions.Synchronized)]
add
{
try
{
TryEventNotification( value );
}
catch
{
TryInstanceNotification( value );
}
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
remove
{
m_subscribers -= value;
if(m_subscribers == null)
{
if (m_eventWatcher != null)
{
m_eventWatcher.Stop();
m_eventWatcher = null;
}
}
}
}
private void TryEventNotification( DeviceChangedEventHandler handler )
{
m_eventWatcher = new ManagementEventWatcher( new WqlEventQuery( c_EventQuery ) );
m_eventWatcher.EventArrived += new EventArrivedEventHandler( HandleDeviceEvent );
if(m_subscribers == null)
{
m_eventWatcher.Start();
}
m_subscribers += handler;
}
private void TryInstanceNotification( DeviceChangedEventHandler handler )
{
m_eventWatcher = new ManagementEventWatcher( new WqlEventQuery( c_InstanceQuery ) );
m_eventWatcher.EventArrived += new EventArrivedEventHandler( HandleDeviceInstance );
if(m_subscribers == null)
{
m_eventWatcher.Start();
}
m_subscribers += handler;
}
private void HandleDeviceEvent( object sender, EventArrivedEventArgs args )
{
if(m_subscribers != null)
{
ManagementBaseObject deviceEvent = args.NewEvent;
ushort eventType = (ushort)deviceEvent["EventType"];
m_subscribers( (DeviceChanged)eventType );
}
}
private void HandleDeviceInstance( object sender, EventArrivedEventArgs args )
{
if(m_subscribers != null)
{
ManagementBaseObject deviceEvent = args.NewEvent;
if(deviceEvent.ClassPath.ClassName.Equals( "__InstanceCreationEvent" ))
{
m_subscribers( DeviceChanged.DeviceArrival );
}
else if(deviceEvent.ClassPath.ClassName.Equals( "__InstanceDeletionEvent" ))
{
m_subscribers( DeviceChanged.DeviceRemoval );
}
}
}
}
public class AsyncUsbStream : AsyncFileStream
{
// IOCTL codes
private const int IOCTL_SPOTUSB_READ_AVAILABLE = 0;
private const int IOCTL_SPOTUSB_DEVICE_HASH = 1;
private const int IOCTL_SPOTUSB_MANUFACTURER = 2;
private const int IOCTL_SPOTUSB_PRODUCT = 3;
private const int IOCTL_SPOTUSB_SERIAL_NUMBER = 4;
private const int IOCTL_SPOTUSB_VENDOR_ID = 5;
private const int IOCTL_SPOTUSB_PRODUCT_ID = 6;
private const int IOCTL_SPOTUSB_DISPLAY_NAME = 7;
private const int IOCTL_SPOTUSB_PORT_NAME = 8;
// paths
static readonly string SpotGuidKeyPath = @"System\CurrentControlSet\Services\SpotUsb\Parameters";
// discovery keys
static public readonly string InquiriesInterface = "InquiriesInterface";
static public readonly string DriverVersion = "DriverVersion";
// mandatory property keys
static public readonly string DeviceHash = "DeviceHash";
static public readonly string DisplayName = "DisplayName";
// optional property keys
static public readonly string Manufacturer = "Manufacturer";
static public readonly string Product = "Product";
static public readonly string SerialNumber = "SerialNumber";
static public readonly string VendorId = "VendorId";
static public readonly string ProductId = "ProductId";
private const int c_DeviceStringBufferSize = 260;
static private Hashtable s_textProperties;
static private Hashtable s_digitProperties;
static AsyncUsbStream()
{
s_textProperties = new Hashtable();
s_digitProperties = new Hashtable();
s_textProperties.Add( DeviceHash , IOCTL_SPOTUSB_DEVICE_HASH );
s_textProperties.Add( Manufacturer, IOCTL_SPOTUSB_MANUFACTURER );
s_textProperties.Add( Product , IOCTL_SPOTUSB_PRODUCT );
s_textProperties.Add( SerialNumber, IOCTL_SPOTUSB_SERIAL_NUMBER );
s_digitProperties.Add( VendorId , IOCTL_SPOTUSB_VENDOR_ID );
s_digitProperties.Add( ProductId , IOCTL_SPOTUSB_PRODUCT_ID );
}
public AsyncUsbStream( string port ) : base( port, System.IO.FileShare.None )
{
}
public unsafe override int AvailableCharacters
{
get
{
int code = Native.ControlCode( Native.FILE_DEVICE_UNKNOWN, 0, Native.METHOD_BUFFERED, Native.FILE_ANY_ACCESS );
int avail;
int read;
if(!Native.DeviceIoControl( m_handle.DangerousGetHandle(), code, null, IOCTL_SPOTUSB_READ_AVAILABLE, (byte*)&avail, sizeof(int), out read, null ) || read != sizeof(int))
{
return 0;
}
return avail;
}
}
public static PortDefinition[] EnumeratePorts()
{
SortedList lst = new SortedList();
// enumerate each guid under the discovery key
RegistryKey driverParametersKey = Registry.LocalMachine.OpenSubKey( SpotGuidKeyPath );
// if no parameters key is found, it means that no USB device has ever been plugged into the host
// or no driver was installed
if(driverParametersKey != null)
{
string inquiriesInterfaceGuid = (string)driverParametersKey.GetValue( InquiriesInterface );
string driverVersion = (string)driverParametersKey.GetValue( DriverVersion );
if((inquiriesInterfaceGuid != null) && (driverVersion != null))
{
EnumeratePorts( new Guid( inquiriesInterfaceGuid ), driverVersion, lst );
}
}
ICollection col = lst.Values;
PortDefinition[] res = new PortDefinition[col.Count];
col.CopyTo( res, 0 );
return res;
}
// The following procedure works with the USB device driver; upon finding all instances of USB devices
// that match the requested Guid, the procedure checks the corresponding registry keys to find the unique
// serial number to show to the user; the serial number is decided by the device driver at installation
// time and stored in a registry key whose name is the hash of the laser etched security key of the device
private static void EnumeratePorts( Guid inquiriesInterface, string driverVersion, SortedList lst )
{
IntPtr devInfo = Native.SetupDiGetClassDevs( ref inquiriesInterface, null, 0, Native.DIGCF_DEVICEINTERFACE | Native.DIGCF_PRESENT );
if(devInfo == Native.INVALID_HANDLE_VALUE)
{
return;
}
Native.SP_DEVICE_INTERFACE_DATA interfaceData = new Native.SP_DEVICE_INTERFACE_DATA(); interfaceData.cbSize = Marshal.SizeOf(interfaceData);
int index = 0;
while(Native.SetupDiEnumDeviceInterfaces( devInfo, 0, ref inquiriesInterface, index++, ref interfaceData ))
{
Native.SP_DEVICE_INTERFACE_DETAIL_DATA detail = new Native.SP_DEVICE_INTERFACE_DETAIL_DATA();
// explicit size of unmanaged structure must be provided, because it does not include transfer buffer
// for whatever reason on 64 bit machines the detail size is 8 rather than 5, likewise the interfaceData.cbSize
// is 32 rather than 28 for non 64bit machines, therefore, we make the detemination of the size based
// on the interfaceData.cbSize (kind of hacky but it works).
if( interfaceData.cbSize == 32 )
{
detail.cbSize = 8;
}
else
{
detail.cbSize = 5;
}
if(Native.SetupDiGetDeviceInterfaceDetail( devInfo, ref interfaceData, ref detail, Marshal.SizeOf(detail) * 2, 0, 0 ))
{
string port = detail.DevicePath.ToLower();
AsyncUsbStream s = null;
try
{
s = new AsyncUsbStream( port );
string displayName = s.RetrieveStringFromDevice( IOCTL_SPOTUSB_DISPLAY_NAME );
string hash = s.RetrieveStringFromDevice( IOCTL_SPOTUSB_DEVICE_HASH );