无法在 Windows 10 IoT 中使用 SerialDevice.ReadTimeout

Unable to use SerialDevice.ReadTimeout in Windows 10 IoT(无法在 Windows 10 IoT 中使用 SerialDevice.ReadTimeout)

本文介绍了无法在 Windows 10 IoT 中使用 SerialDevice.ReadTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Raspberry Pi 2 上的 Windows 10 IoT 上实现 ModBus 主控.我正在使用外部 USB 转 RS-232 适配器,因为内部串行端口是为内核调试保留的.

I'm trying to implement a ModBus master on Windows 10 IoT on a Raspberry Pi 2. I'm using an external USB to RS-232 adapter since the internal serial port is reserved for Kernel Debugging.

串行端口正在工作.我的问题主要是关于阅读时的超时.

Serial port is working. My question is mainly about timeout when reading.

这是我的代码:

// Initialization
serialDevice.ReadTimeout = new TimeSpan(0, 0, 0, allowedTimeBetweenBytes);
serialDataReader.InputStreamOptions = InputStreamOptions.Partial;

// Reading
uint bytesRead = await serialDataReader.LoadAsync(MaxBufferSize); // 256
// Now use ReadBytes to get actual bytes

由于串行端口 RX 输入上没有可用的字节,我希望 LoadAsync 方法在等待后返回 0.不幸的是,它永远不会回来.(好吧,它确实在收到 256 个字节后返回,但这不是我想要的)

With no bytes awailable at the serial port RX input, I'm expecting the LoadAsync method to return 0 after wait. Unfortunately, it never returns. (Ok, it DOES return after 256 bytes are received, but that is not what I want)

由于 ModBus 大量使用超时,我不知道如何实现它.我什至不确定我能做到...

Since ModBus intensively uses timeouts, I am not sure how to implement it. I am not even sure I could do it...

是否有人已经在 Windows 10 IoT 串行端口上使用了超时功能?

Does anyone already used timeouts on Windows 10 IoT serial ports?

推荐答案

是的,我也无法正常工作.我不确定 SerialDevice 类在内部实际使用了 ReadTimeout 的位置.但我确实通过将超时复制到 CancellationTokenSource 最终得到了一些工作.

Yeah, I couldn't get this working either. I'm not sure where ReadTimeout is actually used by the SerialDevice class internally. But I did end up getting something working by copying the timeout to a CancellationTokenSource.

您可以在以下示例中看到它的使用情况,我为旧系列 Mettler Toledo PS 60 运输秤编写,其中 deviceSerialDevice.至少在我的情况下似乎有效.

You can see it in use in the following example I wrote for an old serial Mettler Toledo PS 60 shipping scale, where device is an instance of SerialDevice. Seems to work in my case, at least.

using (var writer = new DataWriter(device.OutputStream))
{
    writer.WriteString("W
");

    using (var cts = new CancellationTokenSource(device.WriteTimeout))
    {
        await writer.StoreAsync().AsTask(cts.Token);
    }

    writer.DetachStream();
}

using (var reader = new DataReader(device.InputStream))
{
    using (var cts = new CancellationTokenSource(device.ReadTimeout))
    {
        var read = await reader.LoadAsync(12).AsTask(cts.Token);

        if (read >= 12)
        {
            var data = reader.ReadString(12);
            reader.DetachStream();

            return ExtractWeightChangedEventArgs(data);
        }
    }
}

这篇关于无法在 Windows 10 IoT 中使用 SerialDevice.ReadTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:无法在 Windows 10 IoT 中使用 SerialDevice.ReadTimeout

基础教程推荐