【发布时间】:2019-07-18 20:31:34
【问题描述】:
我在 netcore 中有一个串行端口类 - 它只是侦听端口并尝试检测奇偶校验错误。奇偶校验设置为空格,并且所有传入字节都以 parity=mark 发送,这将导致奇偶校验错误。 不幸的是,这仅被检测到大约 1/3 次。我需要这种检测,因为这是协议声明消息开头的方式。 字节(80 和 81)每 1 秒发送一次,因此缓冲区应该始终有 1 个字节。
我做错了什么?
// Use this code inside a project created with the Visual C# > Windows Desktop > Console Application template.
// Replace the code in Program.cs with this code.
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Threading;
using SASComms;
public class PortChat
{
static bool _continue;
static SASSerialPort _serialPort;
static object msgsLock = new object();
static Queue<byte[]> msgs = new Queue<byte[]>();
static Queue<byte> receiveQeue = new Queue<byte>();
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
// Create a new SerialPort object with default settings.
_serialPort = new MachineSerialPort();
// Allow the user to set the appropriate properties.
_serialPort.PortName = "COM2";
_serialPort.BaudRate = 19200;
_serialPort.ParityReplace = (byte)'\0' ;
_serialPort.ReadBufferSize = 128;
_serialPort.Parity = Parity.Space;
_serialPort.DataBits = 8;
_serialPort.StopBits = StopBits.One;
_serialPort.Handshake = Handshake.None;
// Set the read/write timeouts
_serialPort.ReadTimeout = 5;
_serialPort.WriteTimeout = 5;
_serialPort.ErrorReceived += new SerialErrorReceivedEventHandler(sp_SerialErrorReceivedEventHandler);
_serialPort.Open();
_continue = true;
readThread.Start();
}
public static void sp_SerialErrorReceivedEventHandler(Object sender, SerialErrorReceivedEventArgs e)
{
if (e.EventType == SerialError.RXParity)
{
Console.WriteLine("Parity error");
}
}
public static void Read()
{
while (_continue)
{
try
{
while (_serialPort.BytesToRead > 0)
{
receiveQeue.Enqueue((byte)_serialPort.ReadByte());
}
if (receiveQeue.Count > 0)
{
foreach (byte r in receiveQeue)
{
Console.Write(r.ToString("X")+" " );
Console.WriteLine();
}
}
}
receiveQeue.Clear();
}
catch (TimeoutException) { }
}
}
}
控制台正在输出:
80
Parity error
81
80
Parity error
81
Parity error
80
Parity error
81
80
Parity error
81
80
81
80
81
Parity error
80
Parity error
81
80
Parity error
我期待每个字节后出现“奇偶校验错误”。
【问题讨论】:
-
您的代码似乎有不匹配的大括号。
-
我不明白你的问题。 The documentation seems crystal clear 关于如何处理(或不处理)奇偶校验错误:“由于操作系统决定是否引发此事件,因此可能不会报告所有奇偶校验错误” .这还不包括错误事件是异步引发的,因此从不保证写入控制台的字节值与写入控制台的错误消息之间存在一对一的关联。控制台。
-
嗨@PeterDuniho 感谢您参考文档。不幸的是,声明在那里,但一点也不清晰。没有关于操作系统用于引发事件的标准是什么的解释。这完全在黑盒中且不可触碰吗?
-
它说的是“操作系统决定”而不是“操作系统玩骰子” 必须使用标准来“确定”某事,并且该标准应该是文档的一部分。
-
如果我启动两个任务并发运行,操作系统会确定这些任务中的哪些顺序程序语句应该相对于彼此执行。按照您的逻辑,文档应该包含对操作系统线程调度程序组件的完整描述,以使读者能够预测两个任务中的语句将以什么顺序执行?呃……不。这不是它的工作原理。您不能期望 .NET 文档为您提供底层操作系统如何工作的所有细节,尤其是因为每个操作系统都不同。
标签: c# .net-core serial-port