Search code examples
c#.netusbhidmaui

How to start DeviceWatcher in MAUI?


So I've managed to create a platform-specific service which task is to communicate with an USB device via HID. As the platform-specific code doesn't work as described in MAUI docs, I've done it by DI in app builder: .AddSingleton<IHidCommunicationService, HidCommunicationService>();. Thanks to this mate:)

The communication works fine but now I want to refresh devices list at runtime and to do so I wish to use DeviceWatcher in my HidCommunicationService. And here's the issue: when I try to fire the device watcher by using Start() method I get this error: A method was called at an unexpected time.

I've tried the same code in WPF app and it works fine:

string aqsFilter = HidDevice.GetDeviceSelector(usagePage, usageId, vendorId, productId);
DeviceWatcher deviceWatcher = DeviceInformation.CreateWatcher(aqsFilter);
deviceWatcher.Start();

Solution

  • The deviceWatcher.Start() has to be fired after adding at least one event handler to deviceWatcher's events: Added, Removed or Updated.

    WinRT information: At least an Added, Updated or Removed event handler must be registered before a watcher can be started. A method was called at an unexpected time.

    And it should be fired from UI thread to work properly: Application.Current.Dispatcher.Dispatch(() => deviceWatcher.Start());