Unable to use SerialDevice.ReadTimeout in Windows 10 IoT

前端 未结 2 1543
温柔的废话
温柔的废话 2021-01-03 05:37

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

2条回答
  •  旧时难觅i
    2021-01-03 06:26

    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.

    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\r\n");
    
        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);
            }
        }
    }
    

提交回复
热议问题