How to permanently check If serial device connects/disconnects in UWP C#?

i have a UWP App running on Windows IoT on a Raspberry Pi. I have to connect several Barcode Scanners via USB-Com and receive Data via a serial port. What would be the best way to recognize if a device disconnects or connects? Right now each Barcode Scanner runs a loop. If it throws an Exception while waiting for Data i know it physically disconnected. Then i try to reconnect it by creating a new serial port using the devices HardwareString(which contains PID and VID). If that fails, it will will run in an endless loop trying to create a serial port throwing exceptions because the device ist physically disconnected. This Will go on until the device reconnects physically and is able to create the serial Port an receive Data on it.

Is there a more elegant way to permanently check for a specific device using the HardwareString?

Thank you very much.

1 answer

  • answered 2019-10-16 01:57 Michael Xu - MSFT

    You may try to use DeviceWatcher. DeviceWatcher is used to enumerate all the devices dynamically, your app can receive notifications if devices are added, removed, or changed after the initial enumeration is complete. If the USB-Com added it will raise DeviceWatcher.Added Event, while the device removed, it will raise DeviceWatcher.Removed Event. Please note that when the device disconnects, it will raise the device removed event, but all pending operations need to be canceled properly, and all of the resources need to clean up. Please refer to following code in EventHandlerForDevice. The callback in the code is used to close the device explicitly is to clean up resources, to properly handle errors,and stop talking to the disconnected device.

    private async void CloseCurrentlyConnectedDevice()
        if (device != null)
            // Notify callback that we're about to close the device
            if (deviceCloseCallback != null)
                deviceCloseCallback(this, deviceInformation);
            // This closes the handle to the device
            device = null;