using CommunityToolkit.Mvvm.Messaging;
using RJCP.IO.Ports;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace 项目名称
{
public class SerialPortHelper
{
/// <summary>
/// 串口连接工具
/// </summary>
public static SerialPortStream Serial { get; set; } = null;
static int ByteCount { get; set; }
static List<byte> readBuffer = new();
public static string Port = "COM1";
static System.Timers.Timer ctimer = new System.Timers.Timer { Interval = 1000 };
static int tm = 0;
static int successCount = 0;// 记录成功连接的串口数量
static int allCount = 0;// 记录串口数量
static int failCount = 0;// 记录失败连接的串口数量
private static System.Threading.Timer timeoutTimer;
static List<string> PnameList { get; set; } = new List<string>();
/// <summary>
/// 连接
/// </summary>
public static async void Connect()
{
try
{
// 获取可用的串口列表
var portNames = SerialPortStream.GetPortNames().ToList();
allCount = portNames.Count;
successCount = 0;
failCount = 0;
// 输出串口列表
if (allCount > 0)
{
PnameList?.Clear();
foreach (string portName in portNames)
{
var serialPort = new SerialPortStream(portName, 115200);
try
{
byte[] sendBuffer = new byte[15];
sendBuffer[0] = 0X5a;
sendBuffer[1] = 0Xa5;
sendBuffer[2] = 0X01;
sendBuffer[3] = 0;
sendBuffer[4] = 0;
sendBuffer[5] = 0;
sendBuffer[6] = 4;
sendBuffer[7] = 0;
sendBuffer[8] = 0;
sendBuffer[9] = 0;
sendBuffer[10] = 0;
var checkhumB = CRC16(sendBuffer, 15);
sendBuffer[11] = byte.Parse(checkhumB[0].ToString());
sendBuffer[12] = byte.Parse(checkhumB[1].ToString());
sendBuffer[13] = 0X3e;
sendBuffer[14] = 0Xe3;
serialPort.Open();
serialPort.DataReceived += SearchDateaReceived;
serialPort.Write(sendBuffer, 0, sendBuffer.Length);
// 设置超时机制
timeoutTimer = new Timer(CheckTimeout, serialPort, 1000, Timeout.Infinite);
await Task.Delay(1000);
}
catch (Exception)
{
failCount++;
if (serialPort != null)
{
serialPort.DataReceived -= SearchDateaReceived;
serialPort.Close();
if (serialPort != null && serialPort.IsDisposed == false) { serialPort?.Dispose(); }
}
CheckConnectionCompletion();
continue;
}
}
}
else
{
没有串口做的操作
//Application.Current.Dispatcher.Invoke(() =>
//{
//WeakReferenceMessenger.Default.Send("Close");
//var m = new MessageWin("Nspf") { Owner = MainWindow._This };
//m.ShowDialog();
//if (m.DialogResult != null)
//{
//MainWindow._This.Vm.SelfCollapsed();
//new LoginMainWin() { Owner = MainWindow._This }.Show();
//}
//});
return;
}
}
catch (Exception ex)
{
LogHelper.GetSingleObj().WriteLog(ex);
}
}
public static void Disconnect()
{
try
&
wpf SerialPortStream 循环串口进行连接仪器
最新推荐文章于 2025-12-04 08:29:53 发布

最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



