110,499
社区成员
发帖
与我相关
我的任务
分享
private System.Windows.Forms.Timer 超时时钟 = new System.Windows.Forms.Timer();
private void 超时处理(object sender, EventArgs e)
{
内部命令 临时 = 命令;
命令 = 内部命令.无;
超时时钟.Enabled = false;
switch (临时)
{
case 内部命令.核对全参数:
MessageBox.Show("读出无响应!", "超时", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
case 内部命令.写入全参数:
// 出错提示
break;
case 内部命令.读取全参数:
// 出错提示
break;
case 内部命令.写入网号:
// 出错提示
break;
case 内部命令.写入信道:
// 出错提示
break;
case 内部命令.模块重启:
{
byte[] 协议_查询主从机状态 = new byte[5] { 0xAA, 0xA1, 0x00, 0x00, 0xFF };
超时时钟.Interval = 300;
命令 = 内部命令.重启检测;
超时时钟.Enabled = true;
串口.Write(协议_查询主从机状态, 0, 协议_查询主从机状态.Length); // 发重启检测查询命令
}
break;
case 内部命令.重启检测:
// 出错提示
break;
}
if (!超时时钟.Enabled) 引用委托更新状态(false);
}
private void 串口接收数据(object sender, SerialDataReceivedEventArgs e)
{
try
{
Thread.Sleep(15); // 避免帧读断情况
串口接受的数据 = new byte[串口.BytesToRead];
串口.Read(串口接受的数据, 0, 串口接受的数据.Length);
串口.DiscardInBuffer();
switch (命令)
{
case 内部命令.无:
引用委托发送一个消息(MSG.消息_收到串口数据);
break;
case 内部命令.写入全参数:
{
超时时钟.Enabled = false;
bool 写入成功 = true;
if (串口接受的数据[6] != 0x00) 写入成功 = false;
if (写入成功)
{
byte[] 协议_重启命令 = new byte[4] { 0xAA, 0xC9, 0x00, 0xFF};
超时时钟.Interval = 1500; // 实测重启时间很短
命令 = 内部命令.模块重启;
for (int i = 0; i < 8; i++) 协议_重启命令[8] += 协议_重启命令[i];
超时时钟.Enabled = true; // 重启等待重启完成
串口.Write(协议_重启命令, 0, 协议_重启命令.Length); // 重启模块
}
else
{
// 出错提示
}
}
break;
case 内部命令.读取全参数:
{
if (串口接受的数据.Length >= 全参数字节数)
{
for (int i = 0, j = 0; i < 串口接受的数据.Length; i++, j++) 全参数[i] = 串口接受的数据[j];
超时时钟.Enabled = false;
if (全参数与配置不同())
{
修改全参数();
命令 = 内部命令.写入全参数;
超时时钟.Interval = 800;
超时时钟.Enabled = true;
串口.Write(全参数, 0, 全参数.Length); // 写全参数
}
else
{
// 进入正常工作
}
}
else
无线模块自检结束后("读信息错误");
}
break;
case 内部命令.重启检测:
if (串口接受的数据.Length >= 6)
{
if (重启反馈正确())
{
// 进入正常工作
}
else
{
// 出错提示
}
}
else
{
// 出错提示
}
break;
case 内部命令.写入信道:
// 出错提示
break;
}
}
catch (System.Exception ex)
{
// 出错提示
}
}
public void 打开串口(string 串口名)
{
串口 = new SerialPort(串口名, 19200, Parity.None, 8, StopBits.One);
try
{
串口.Open();
串口.DiscardInBuffer();
串口.DiscardOutBuffer();
打开 = true;
串口.DataReceived += 串口接收数据;
超时时钟.Enabled = false;
超时时钟.Interval = 1800;
命令 = 内部命令.读取全参数;
超时时钟.Enabled = true;
串口.Write(协议_读取全参数, 0, 协议_读取全参数.Length);
}
catch
{
串口.Dispose();
串口 = null;
// 出错提示
}
}
超时时钟.Tick += new System.EventHandler(超时处理);
超时时钟.Enabled = false;