110,499
社区成员
发帖
与我相关
我的任务
分享
private void RealTimeInfor_Load(object sender, EventArgs e)
{
LoadDgvData();//加载DataGridView数据
comm.DataReceived += comm_DataReceived;//添加事件注册
comm.RtsEnable = true;
OpenPort();//打开端口
}
timer控件 是 20秒 执行一次 SendCmd方法
private void timer1_Tick(object sender, EventArgs e)
{
SendCmd();//发送命令
}
/// <summary>
/// 发送命令
/// </summary>
public void SendCmd()
{
List<string> userpowerList = UserInforManager.ProcessUserPower(TransferValue.uinfor.UserPower);//UserPower是用户 可以操作电子看板的Id号,和PortBaudrateCmd.xml里的key值对应
string _key = string.Empty;
string cmd = string.Empty;
Dictionary<string, string> dic = ProcessXml.GetSureValue(System.IO.Directory.GetCurrentDirectory() + "/PortBaudrateCmd.xml");
foreach (KeyValuePair<string, string> kvp in dic)
{
for (int j = 0; j < userpowerList.Count; j++)
{
if (userpowerList[j] == kvp.Key)
{
try
{
comm.WriteLine(kvp.Value);
Thread.Sleep(300);
}
catch (Exception ex)
{
comm = new SerialPort();//捕获到异常信息,创建一个新的comm对象,之前的不能用了。
Console.WriteLine(ex.Message);//现实异常信息给客户。
}
}
}
}
}
PortBaudrateCmd.xml
<?xml version="1.0" encoding="utf-8" ?>
<ConnectionInfor>
<cinfors portname="COM5" baudrate="9600">
<cinfor key="1" cmd="@01x39#"></cinfor>
<cinfor key="2" cmd="@02x3A#"></cinfor>
<cinfor key="3" cmd="@03x3B#"></cinfor>
<cinfor key="4" cmd="@04x3C#"></cinfor>
<cinfor key="5" cmd="@05x3D#"></cinfor>
<cinfor key="6" cmd="@06x3E#"></cinfor>
<cinfor key="7" cmd="@07x3F#"></cinfor>
<cinfor key="8" cmd="@08x30#"></cinfor>
<cinfor key="9" cmd="@09x31#"></cinfor>
<cinfor key="10" cmd="@10x39#"></cinfor>
<cinfor key="11" cmd="@11x38#"></cinfor>
<cinfor key="12" cmd="@12x3B#"></cinfor>
<cinfor key="13" cmd="@13x3A#"></cinfor>
<cinfor key="14" cmd="@14x3D#"></cinfor>
<cinfor key="15" cmd="@15x3C#"></cinfor>
<cinfor key="16" cmd="@16x3F#"></cinfor>
<cinfor key="17" cmd="@17x3E#"></cinfor>
</cinfors>
</ConnectionInfor>
private bool Listening = false;//是否没有执行完invoke相关操作
private bool Closing = false;//是否正在关闭串口,执行Application.DoEvents,并阻止再次invoke
void comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(500);
if (Closing) return;
try
{
int n = comm.BytesToRead;
byte[] buf = new byte[n];
comm.Read(buf, 0, n);
builder.Remove(0, builder.Length);
this.Invoke((EventHandler)(delegate
{
builder.Append(Encoding.ASCII.GetString(buf));
txtHome.Text = "";
txtHome.AppendText(builder.ToString());
//
Console.WriteLine(txtHome.Text);
if (txtHome.Text.Length > 0 && txtHome.Text.Length % 81 == 0)
{
string[] first = ProcessSerialportData.InitProcess(txtHome.Text); //第一次处理数据
if (first == null)
{
return;
}
RealTimeInfo rti = ProcessSerialportData.AgainProcess(first);//第二次处理数据
if (rti != null)//没有就增加,有就更新
{
int num = RealTimeInfoManager.AddRealTimeInfor(rti);
LoadDgvData();//重写绑定数据
Console.WriteLine(num);
}
}
}));
}
catch (Exception e2)
{
Console.WriteLine(e2.Message);
}
finally
{
Listening = false;
}
}