问题描述
private async void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e)
{
try
{
SerialPort sp = (SerialPort)sender;
var serialDevice = sender as SerialPort;
var buffer = new byte[serialDevice.BytesToRead];
serialDevice.Read(buffer,buffer.Length);
string indata2 = FormatHelper.ByteArrayToString(buffer);
await Application.Current.dispatcher.BeginInvoke(new Action(() =>
{
canSniffFlowData.Text = indata2;
}));
}
catch (Exception exc)
{
MessageBox.Show(" " + exc.ToString());
}
}
但是,当我尝试将传入数据转换为调度程序内或 datareceived 函数内的任何位置的模型列表时,datareceived 事件每一分钟而不是几秒开始触发
示例:当我在 dispatcher.BeginInvoke 中添加以下代码时
var formattedModel = FormatHelper.FormaSnaptData(indata2);
--> 这是我的 FormaSnaptData 和 ByteArrayToString 方法。
public static async Task<List<DataModel>> FormaSnaptData(string input)
{
List<DataModel> result = new List<DataModel>();
string pattern = "7E.+?7E";
Regex rgx = new Regex(pattern,RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(input);
if (matches.Count > 0)
{
Console.WriteLine("{0} ({1} matches):",input,matches.Count);
DataModel currentData;
foreach (Match match in matches)
{
currentData = new DataModel();
string formattedString = "";
int index = 0;
// Her iki satırda bir boşluk koy ( bytelar düzgün ayrışsın diye )
foreach (var item in match.Value)
{
index++;
if (index % 2 == 0)
{
formattedString += item;
formattedString += " ";
}
else
{
formattedString += item;
}
}
Console.WriteLine("Original -->" + match.Value);
currentData.ByteStringList = formattedString.Split(' ').ToList();
// Kontrol byte ını düzenle ( 7D 5E gelenleri 7E yap ve 5E'yi sil)
for (int i = 0; i < currentData.ByteStringList.Count(); i++)
{
if (currentData.ByteStringList[i].Equals("7D"))
{
currentData.ByteStringList[i] = "7E";
currentData.ByteStringList.RemoveAt(i + 1);
}
}
Console.WriteLine("Formatted 2-->" + String.Join(" ",currentData.ByteStringList));
// Burada gelen datayı formatlamamız lazım
currentData.CanId = currentData.ByteStringList.ToList()[10] + currentData.ByteStringList.ToList()[11];
int numberOfItems = currentData.ByteStringList.Count(); // 24 ise 8 data var ona göre alıcaz
int idCount = numberOfItems - 16;
List<string> dxList = new List<string>();
for (int i = 0; i < idCount; i++)
{
dxList.Add(currentData.ByteStringList.ToList()[i + 12]);
}
currentData.Dx = dxList;
currentData.ShownStringList = String.Join(" ",currentData.ByteStringList);
result.Add(currentData);
Console.WriteLine("Formatted -->" + String.Join(" ",currentData.ByteStringList));
}
}
return result;
}
public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}",b);
return hex.ToString();
}
我也在我的模拟器中尝试了这种方法。我将所有传入的数据保存到 txt 文件,然后在模拟器演示中读取它们,这种方法不会阻止任何东西并且工作得很好。我认为有些东西会触发“DataReceivedHandler”并停止它。任何解决方案都会很棒。抱歉我的代码不整洁我还在努力=/
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)