简体   繁体   English

如何永久检查 UWP C# 中的串行设备是否连接/断开?

[英]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.我有一个 UWP 应用程序在 Raspberry Pi 上的 Windows IoT 上运行。 I have to connect several Barcode Scanners via USB-Com and receive Data via a serial port.我必须通过 USB-Com 连接多个条码扫描仪并通过串行端口接收数据。 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).然后我尝试通过使用设备 HardwareString(包含 PID 和 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.这将 go 开启,直到设备重新物理连接并能够创建串行端口并在其上接收数据。

Is there a more elegant way to permanently check for a specific device using the HardwareString?有没有更优雅的方法来使用 HardwareString 永久检查特定设备?

Thank you very much.非常感谢。

You may try to use DeviceWatcher .您可以尝试使用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. DeviceWatcher 用于动态枚举所有设备,如果在初始枚举完成后添加、删除或更改设备,您的应用程序可以收到通知。 If the USB-Com added it will raise DeviceWatcher.Added Event , while the device removed, it will raise DeviceWatcher.Removed Event .如果添加了 USB-Com,它将引发DeviceWatcher.Added Event ,而移除设备时,它将引发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 .请参考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.Dispose();

        device = null;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM