如何在 UWP C# 中永久检查串行设备是否连接/断开连接? [英] How to permanently check If serial device connects/disconnects in UWP C#?

查看:53
本文介绍了如何在 UWP C# 中永久检查串行设备是否连接/断开连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在 Raspberry Pi 上的 Windows IoT 上运行的 UWP 应用程序.我必须通过 USB-Com 连接多个条码扫描器并通过串行端口接收数据.识别设备是否断开连接或连接的最佳方法是什么?现在每个条码扫描器都运行一个循环.如果它在等待数据时抛出异常,我知道它在物理上已断开连接.然后我尝试通过使用设备 HardwareString(包含 PID 和 VID)创建一个新的串行端口来重新连接它.如果失败,它将在无限循环中运行,试图创建一个抛出异常的串行端口,因为设备物理上断开连接.这将一直持续到设备重新物理连接并能够创建串行端口并在其上接收数据.

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.

是否有更优雅的方式使用 HardwareString 永久检查特定设备?

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

非常感谢.

推荐答案

您可以尝试使用 DeviceWatcher.DeviceWatcher 用于动态枚举所有设备,如果在初始枚举完成后添加、删除或更改设备,您的应用程序可以收到通知.如果添加了 USB-Com,它将引发 DeviceWatcher.添加事件,当设备被移除时,它会引发DeviceWatcher.Removed 事件.请注意,当设备断开连接时,会引发设备移除事件,但所有挂起的操作都需要正确取消,所有资源都需要清理.请参考EventHandlerForDevice<中的以下代码/a>.代码中的回调用于显式关闭设备,清理资源,正确处理错误,停止与断开连接的设备通话.

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.Dispose();

        device = null;
    }
}

这篇关于如何在 UWP C# 中永久检查串行设备是否连接/断开连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆