11// Copyright (c) .NET Foundation and Contributors
22// See LICENSE file in the project root for full license information.
33
4+ using System . Runtime . CompilerServices ;
5+ using nanoFramework . Runtime . Events ;
6+
47namespace System . Device . UsbClient
58{
9+ /// <summary>
10+ /// Indicates a change in the connection state of the USB device.
11+ /// </summary>
12+ /// <param name="sender">Specifies the object that sent the USB device connection state changed event. </param>
13+ /// <param name="e">Contains the connection changed event arguments. </param>
14+ public delegate void UsbDeviceConnectionChangedEventHandler ( object sender , DeviceConnectionEventArgs e ) ;
15+
616 /// <summary>
717 /// Provides static methods for the creation of USB client instances.
818 /// </summary>
919 public class UsbClient
1020 {
21+ /// <summary>
22+ /// Gets a value indicating whether the USB device is connected or not.
23+ /// </summary>
24+ public extern bool IsConnected
25+ {
26+ [ MethodImpl ( MethodImplOptions . InternalCall ) ]
27+ get ;
28+ }
29+
30+ static UsbClient ( )
31+ {
32+ UsbDeviceEventListener useDeviceEventListener = new ( ) ;
33+
34+ EventSink . AddEventProcessor ( EventCategory . Usb , useDeviceEventListener ) ;
35+ EventSink . AddEventListener ( EventCategory . Usb , useDeviceEventListener ) ;
36+ }
37+
38+ /// <summary>
39+ /// Event occurs when the connection state of the USB device changes.
40+ /// </summary>
41+ public static event UsbDeviceConnectionChangedEventHandler UsbDeviceConnectionChanged ;
42+
1143 /// <summary>
1244 /// Creates an USB Stream from a WinUSB device that will use the specified name as the device description.
1345 /// </summary>
@@ -22,5 +54,50 @@ public static UsbStream CreateUsbStream(
2254 classId ,
2355 name ) ;
2456 }
57+
58+ internal class UsbDeviceEventListener : IEventProcessor , IEventListener
59+ {
60+ public BaseEvent ProcessEvent ( uint data1 , uint data2 , DateTime time )
61+ {
62+ return new UsbDeviceEvent ( )
63+ {
64+ // Data1 is packed by PostManagedEvent, so we need to unpack the high word.
65+ EventType = ( UsbEventType ) ( data1 & 0xFF ) ,
66+
67+ // Data2 - Low 8 bits are the interface index
68+ InterfaceIndex = ( ushort ) ( data2 & 0xff )
69+ } ;
70+ }
71+
72+ public void InitializeForEventSource ( )
73+ {
74+ // This method has to exist
75+ }
76+
77+ public bool OnEvent ( BaseEvent ev )
78+ {
79+ if ( ev is UsbDeviceEvent myEvent )
80+ {
81+ switch ( myEvent . EventType )
82+ {
83+ case UsbEventType . DeviceDisconnected :
84+
85+ // fire event, if subscribed
86+ UsbDeviceConnectionChanged ? . Invoke ( this , new DeviceConnectionEventArgs ( false ) ) ;
87+
88+ break ;
89+
90+ case UsbEventType . DeviceConnected :
91+
92+ // fire event, if subscribed
93+ UsbDeviceConnectionChanged ? . Invoke ( this , new DeviceConnectionEventArgs ( true ) ) ;
94+
95+ break ;
96+ }
97+ }
98+
99+ return true ;
100+ }
101+ }
25102 }
26103}
0 commit comments