Created
December 29, 2020 02:13
-
-
Save kraftboy/bc2b5f61de470b590d2c27bc5f4865eb to your computer and use it in GitHub Desktop.
quick and dirty enumeration of USB devices, endpoint polling, and setting windows default audio playback device
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using LibUsbDotNet.Info; | |
using LibUsbDotNet.LibUsb; | |
using LibUsbDotNet.Main; | |
using System; | |
using System.Collections.ObjectModel; | |
using System.Linq; | |
using AudioEndPoint; | |
namespace Examples | |
{ | |
internal class ShowInfo | |
{ | |
public static void Main(string[] args) | |
{ | |
// Dump all devices and descriptor information to console output. | |
using (UsbContext context = new UsbContext()) | |
{ | |
var allDevices = context.List(); | |
foreach(var usbRegistry in allDevices) | |
{ | |
if (usbRegistry.TryOpen()) | |
{ | |
UsbDevice device = usbRegistry as UsbDevice; | |
if(device.Descriptor.Manufacturer == "foobar.com") | |
{ | |
byte[] epBuf = new byte[1]; | |
var myDevice = device; | |
if(myDevice.ClaimInterface(0)) | |
{ | |
Console.WriteLine($"Device open, interface 0 claimed: {device.ToString()}"); | |
UsbEndpointReader reader = myDevice.OpenEndpointReader(ReadEndpointID.Ep01, 1, EndpointType.Interrupt); | |
byte buttonState = 0; | |
while (true) | |
{ | |
int bytesRead = 0; | |
var err = reader.Read(epBuf, 0, out bytesRead); | |
if (epBuf[0] != buttonState) | |
{ | |
buttonState = epBuf[0]; | |
// Console.WriteLine($"Button: {buttonState}"); | |
if(buttonState != 0) | |
{ | |
var audioPlaybackDevices = AudioEndPointControllerWrapper.AudioController.GetActivePlaybackDevices(); | |
bool setDefault = false; | |
Action<AudioEndPointControllerWrapper.IAudioDevice> setAsDefault = x => | |
{ | |
Console.WriteLine($"{x} set as default."); | |
x.SetAsDefault(AudioEndPointControllerWrapper.Role.Multimedia); | |
}; | |
foreach (var audioDevice in audioPlaybackDevices) | |
{ | |
if(setDefault) | |
{ | |
setAsDefault(audioDevice); | |
break; | |
} | |
if (audioDevice.IsDefault(AudioEndPointControllerWrapper.Role.Multimedia)) | |
{ | |
if(audioDevice == audioPlaybackDevices.Last()) | |
{ | |
setAsDefault(audioPlaybackDevices.First()); | |
break; | |
} | |
setDefault = true; | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
usbRegistry.Close(); | |
} | |
} | |
} | |
// Wait for user input.. | |
Console.WriteLine("Press any key to exit"); | |
Console.ReadKey(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment