using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Runtime.Remoting.Channels;
namespace YZ_LOT
{
public enum CurrSetTypeName
{
Lora_Read,
Lora_Write,
Lora_Su_Read,
Lora_Su_Write,
GuanLi_Read,
GuanLi_Write,
Rs485_Read,
Rs485_Write,
XiaoYan_Read,
XiaoYan_Write
}
public partial class UserControl_Machine_Debug : UserControl
{
private delegate void InvokeHandler();
SerialPort sp = null; //申明一个串口类
bool isOpen = false; //打开串口的标志
bool isSetProperty = false;
bool isHex = true;
CurrSetTypeName MingLing_Type;
string Machine_Name = "";
public UserControl_Machine_Debug()
{
InitializeComponent();
}
public UserControl_Machine_Debug(string mName)
{
InitializeComponent();
Machine_Name = mName;
}
private void GetChuanKou()
{
bool comExistence = false; //有无可用串口标志位
comboBox_ChuanKou.Items.Clear(); //清除当前串口号中的所有串口名称
for (int i = 0; i < 10; i++)
{
try
{
SerialPort sp = new SerialPort("COM" + (i + 1).ToString()); //sp依次赋值COM1、COM2、、COM10
sp.Open();
sp.Close();
comboBox_ChuanKou.Items.Add("COM" + (i + 1).ToString()); //串口可以打开关闭说明串口可以使用,否则跳到异常
comExistence = true; //有可用串口则标志位为true
}
catch (Exception)
{
continue; //COM1串口不存在,则继续COM2,依次循环到COM10
}
}
if (comExistence)
{
comboBox_ChuanKou.SelectedIndex = 0; //串口号更新为最先有效的串口
}
}
private void SetPortProperty()
{
sp = new SerialPort(); //初始化sp
sp.PortName = comboBox_ChuanKou.Text.Trim(); //设置串口名
sp.BaudRate = Convert.ToInt32(comboBox_BoTe.Text.Trim()); //设置波特率,波特率是把字符串转换为32位整型
Console.WriteLine(comboBox_BoTe.Text);
if (comboBox_TingZhi.Text.Trim() == "0")
{
sp.StopBits = StopBits.None; //停止位为0
}
else if (comboBox_TingZhi.Text.Trim() == "1.5")
{
sp.StopBits = StopBits.OnePointFive; //停止位为1.5
}
else if (comboBox_TingZhi.Text.Trim() == "2")
{
sp.StopBits = StopBits.Two; //停止位为2
}
else
{
sp.StopBits = StopBits.One; //停止位为1
}
sp.DataBits = Convert.ToInt16(comboBox_ShuJu.Text.Trim()); //设置数据位,数据位是把字符串转换为16位整型
if (comboBox_XiaoYan.Text.Trim() == "ODD")
{
sp.Parity = Parity.Odd; //奇校验
}
else if (comboBox_XiaoYan.Text.Trim() == "EVEN")
{
sp.Parity = Parity.Even; //偶校验
}
else
{
sp.Parity = Parity.None; //不校验
}
sp.ReceivedBytesThreshold = 1;
sp.DtrEnable = true;
sp.ReadTimeout = 1000;
sp.RtsEnable = true;
sp.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived);
}
private void Sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
System.Threading.Thread.Sleep(100); //延时100ms,等待接收完数据
bool IsSuccess = true;
string recvData = "";
try
{
if (isHex == false)
{
recvData += sp.ReadLine(); //字符型,把接收字符直接显示在tbxRecvData上面,sp.ReadLine读串口字符串
}
else
{
Byte[] ReceivedData = new Byte[sp.BytesToRead]; //定义并初始化字符数组,sp.ByteToRead串口读字符串长度
sp.Read(ReceivedData, 0, ReceivedData.Length); //字符数组读取串口数据
recvData = BitConverter.ToString(ReceivedData, 0, ReceivedData.Length).Replace("-", " ");
}
}
catch (TimeoutException)
{
IsSuccess = false;
}
sp.DiscardInBuffer(); //清除串口接收缓冲区数据
string[] mingling_Arr = recvData.Split(' ');
if(mingling_Arr.Length == 7 || mingling_Arr.Length == 8)
{
this.Invoke(new InvokeHandler(delegate ()
{
switch (MingLing_Type)
{
case CurrSetTypeName.Lora_Read:
if(IsSuccess)
{
label_Lora.Text = "读取成功";
label_Lora.ForeColor = Color.Green;
int iNum = int.Parse(Get10string(mingling_Arr[4]));
comboBox_Lora.SelectedIndex = iNum - 1;
}
else
{
label_Lora.Text = "读取失败";
label_Lora.ForeColor = Color.Red;
}
break;
case CurrSetTypeName.Lora_Write:
if(IsSuccess)
{
label_Lora.Text = "设置成功";
label_Lora.ForeColor = Color.Green;
}
else
{
label_Lora.Text = "设置失败";
label_Lora.ForeColor = Color.Red;
}
break;
case CurrSetTypeName.Lora_Su_Read:
if(IsSuccess)
{
label_Lora_Su.Text = "读取成功";
label_Lora_Su.ForeColor = Color.Green;
int iNum_Su = int.Parse(Get10string(mingling_Arr[4]));
comboBox_Lora_Su.SelectedIndex = iNum_Su - 1;
}
else
{
label_Lora_Su.Text = "读取失败";
label_Lora_Su.ForeColor = Color.Red;
}
break;
case CurrSetTypeName.Lora_Su_Write:
if (IsSuccess)
{
label_Lora_Su.Text = "设置成功";
label_Lora_Su.ForeColor = Color.Green;
}
else
{
label_Lora_Su.Text = "设置失败";
label_Lora_Su.ForeColor = Color.Red;
}
break;
case CurrSetTypeName.GuanLi_Read:
if(IsSuccess)
{
label_GuanLi.Text = "读取成功";
label_GuanLi.ForeColor = Color.Green;
textBox_GuanLi.Text = Get10string(mingling_Arr[4]);
}
else
{
label_GuanLi.Text = "读取失败";
label_GuanLi.ForeColor = Color.Red;
}
break;
case CurrSetTypeName.GuanLi_Write:
if (IsSuccess)
{
label_GuanLi.Text = "设置成功";
label_GuanLi.ForeColor = Color.Green;
}
else
{
label_GuanLi.Text = "设置失败";
label_GuanLi.ForeColor = Color.Red;
}
break;
case CurrSetTypeName.Rs485_Read:
if(IsSuccess)
{
label_BoTe.Text = "读取成功";
label_BoTe.ForeColor = Color.Green;
int iNum_BoTe = int.Parse(Get10string(mingling_Arr[4]));
comboBox_SuLu.SelectedIndex = iNum_BoTe - 1;
}
else
{
label_BoTe.Text = "读取失败";
label_BoTe.ForeColor = Color.Red;
}
break;
case CurrSetTypeName.Rs485_Write:
if (IsSuccess)
{
label_BoTe.Text = "设置成功";
label_BoTe.ForeColor = Color.Green;
}
else
{
label_BoTe.Text = "设置失败";
label_BoTe.ForeColor = Color.Red;
}
break;
case CurrSetTypeName.XiaoYan_Read:
if(IsSuccess)
{
label_XiaoJian.Text = "读取成功";
label_XiaoJian.ForeColor = Color.Green;
int iNum_XiaoYan = int.Parse(Get10string(mingling_Arr[4]));
comboBox_Data_XiaoYan.SelectedIndex = iNum_XiaoYan - 1;
}
else
{
label_XiaoJian.Text = "读取失败";
label_BoTe.ForeColor = Color.Red;
}
break;
case CurrSetTypeName.XiaoYan_Write:
if (IsSuccess)
{
label_XiaoJian.Text = "设置成功";
label_XiaoJian.ForeColor = Color.Green;
}
else
{
label_XiaoJian.Text = "设置失败";
label_XiaoJian.ForeColor = Color.Red;
}
break;
default:
break;
}
}));
}
}
private void UserControl_Machine_Debug_Load(object sender, EventArgs e)
{
//加载串口
GetChuanKou();
comboBox_BoTe.SelectedIndex = 3;
comboBox_ShuJu.SelectedIndex = 0;
comboBox_TingZhi.SelectedIndex = 0;
comboBox_XiaoYan.SelectedIndex = 0;
this.label_BoTe.Text = "";
label_Lora.Text = "";
label_GuanLi.Text = "";
label_Lora_Su.Text = "";
label_XiaoJian.Text = "";
comboBox_Lora.SelectedIndex = 0;
comboBox_Lora_Su.SelectedIndex = 2;
comboBox_SuLu.SelectedIndex = 3;
comboBox_Data_XiaoYan.SelectedIndex = 0;
groupBox_MachineName.Text = Machine_Name + "配置";
label7.Text = Machine_Name + "配置";
if(Machine_Name == "YZ-IOT_LORA_RS485网关")
{
this.label.Text = "管理设备数量";
}
}
private void button_ResetMachine_Click(object sender, EventArgs e)
{
UserControl_Machine_List control_Machine_Debug = new UserControl_Machine_List();
control_Machine_Debug.Dock = DockStyle.Fill;
control_Machine_Debug.Show();
this.Parent.Controls.Add(control_Machine_Debug);
this.Parent.Controls.Remove(this);
}
private bool CheckPortSetting()
{
if (comboBox_ChuanKou.Text.Trim() =="") return false; //Trim()删除开头和结尾的空白字符
if (comboBox_BoTe.Text.Trim() =="") return false;
if (comboBox_ShuJu.Text.Trim() =="") return false;
if (comboBox_TingZhi.Text.Trim() =="") return false;
if (comboBox_XiaoYan.Text.Trim() =="") return false;
return true; //串口号、波特率、数据位、停止位、校验同时不为空,则返回true
}
private void button_OpenCom_Click(object sender, EventArgs e)
{
if (isOpen == false) //之前串口是关闭的,则执行if语句块
{
if (!CheckPortSetting()) //串口未设置
{
MessageBox.Show("串口未设置", "错误提示");
return; //void函数加return,退出函数体
}
if(!isSetProperty)
{
SetPortProperty(); //设置串口属性
isSetProperty = true; //串口属性设置标志位设置为true
}
try
{
sp.Open(); //打开串口
isOpen = true; //串口打开标志位设置为true
button_OpenCom.Text = "关闭串口"; //btnOpenCom的文本设置为“关闭串口”
comboBox_ChuanKou.Enabled = false; //串口号失能
comboBox_BoTe.Enabled = false; //波特率
comboBox_ShuJu.Enabled = false; //数据位
comboBox_TingZhi.Enabled = false; //停止位
comboBox_XiaoYan.Enabled = false; //校验
}
catch (Exception)
{
isSetProperty = false; //串口设置标志位设置为false
isOpen = false; //串口打开标志位设置为false
MessageBox.Show("串口无效或已被占用", "错误提示"); //打开失败提示消息框
}
}
else //之前串口是打开的,则执行else语句块
{
try
{
sp.Close(); //关闭串口
isOpen = false; //串口打开标志位设置为false
isSetProperty = false;
button_OpenCom.Text = "打开串口"; //btnOpenCom的文本设置为“打开串口”
comboBox_ChuanKou.Enabled = true; //串口号失能
comboBox_BoTe.Enabled = true; //波特率
comboBox_ShuJu.Enabled = true; //数据位
comboBox_TingZhi.Enabled = true; //停止位
comboBox_XiaoYan.Enabled = true; //校验
}
catch (Exception)
{
MessageBox.Show("关闭串口时发生错误", "错误提示"); //关闭失败提示消息框
}
}
}
public byte[] strToToHexByte(String hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16); return returnBytes;
}
private void SendData(string data, CurrSetTypeName typeid)
{
if (isOpen) //串口打开状态
{
try
{
MingLing_Type = typeid;
data += CRC.ToModbusCRC16(data).Insert(2, " ");
Console.WriteLine("发送数据--" + data);
byte[] writeBytes = strToToHexByte(data);
sp.Write(writeBytes, 0, writeBytes.Length); //串口发送数据
}
catch
{
MessageBox.Show("发送数据时发生错误!", "错误提示");
return;
}
}
else
{
MessageBox.Show("串口未打开", "错误提示");
}
}
private void comboBox_ChuanKou_MouseEnter(object sender, EventArgs e)
{
}
private string Get16String(string sDiZhi)
{
if (int.Parse(sDiZhi) > 9)
{
sDiZhi = Convert.ToString(int.Parse(sDiZhi), 16);
if (sDiZhi.Length < 2)
{
sDiZhi += "0" + sDiZhi.ToString();
}
}
else
{
sDiZhi = "0" + sDiZhi;
}
return sDiZhi;
}
private string Get10string(string num)
{
int RtnMsg10 = int.Parse(num.Replace(" ", ""), System.Globalization.NumberStyles.HexNumber);
return RtnMsg10.ToString();
}
private void button_Lora_Read_Click(object sender, EventArgs e)
{
SendData("FF 03 00 64 00 01 ",CurrSetTypeName.Lora_Read);
}
private void button_Lora_Sy_Read_Click(object sender, EventArgs e)
{
SendData("FF 03 00 65 00 01 ",CurrSetTypeName.Lora_Su_Read);
}
private void button_Lora_Set_Click(object sender, EventArgs e)
{
if(comboBox_Lora.Text != "")
{
int dataId = comboBox_Lora.SelectedIndex + 1;
string sDiZhi = Get16String(dataId.ToString());
SendData("FF 06 00 64 00 " + sDiZhi + " ",CurrSetTypeName.Lora_Write);
}
else
{
MessageBox.Show("请输入设置信息");
}
}
private void button_GuanLi_Read_Click(object sender, EventArgs e)
{
SendData("FF 03 00 66 00 01 ",CurrSetTypeName.GuanLi_Read);
}
private void button_BoTe_Read_Click(object sender, EventArgs e)
{
SendData("FF 03 00 67 00 01 ",CurrSetTypeName.Rs485_Read);
}
private void button_XiaoJian_Read_Click(object sender, EventArgs e)
{
SendData("FF 03 00 68 00 01 ",CurrSetTypeName.XiaoYan_Read);
}
private void button_Lora_Su_Set_Click(object sender, EventArgs e)
{
if (comboBox_Lora_Su.Text != "")
{
int dataId = comboBox_Lora_Su.SelectedIndex + 1;
string sDiZhi = Get16String(dataId.ToString());
SendData("FF 06 00 65 00 " + sDiZhi + " ",CurrSetTypeName.Lora_Su_Write);
}
else
{
MessageBox.Show("请输入设置信息");
}
}
private void button_GuanLi_Set_Click(object sender, EventArgs e)
{
if (textBox_GuanLi.Text != "")
{
string sDiZhi = Get16String(textBox_GuanLi.Text);
SendData("FF 06 00 66 00 " + sDiZhi + " ",CurrSetTypeName.GuanLi_Write);
}
else
{
MessageBox.Show("请输入设置信息");
}
}
private void button_BoTe_Set_Click(object sender, EventArgs e)
{
if (comboBox_SuLu.Text != "")
{
int dataId = comboBox_SuLu.SelectedIndex + 1;
string sDiZhi = Get16String(dataId.ToString());
SendData("FF 06 00 67 00 " + sDiZhi + " ",CurrSetTypeName.Rs485_Write);
}
else
{
MessageBox.Show("请输入设置信息");
}
}
private void button_XiaoJian_Set_Click(object sender, EventArgs e)
{
if (comboBox_Data_XiaoYan.Text != "")
{
int dataId = comboBox_Data_XiaoYan.SelectedIndex + 1;
string sDiZhi = Get16String(dataId.ToString());
SendData("FF 06 00 68 00 " + sDiZhi + " ",CurrSetTypeName.XiaoYan_Write);
}
else
{
MessageBox.Show("请输入设置信息");
}
}
private void textBox_GuanLi_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8)
{
if(int.Parse(textBox_GuanLi.Text) > 0 && int.Parse(textBox_GuanLi.Text) <= 250)
{
e.Handled = true;
}
}
}
private void textBox_GuanLi_TextChanged(object sender, EventArgs e)
{
try
{
if (int.Parse(textBox_GuanLi.Text) <= 0 )
{
textBox_GuanLi.Text = "1";
}
if(int.Parse(textBox_GuanLi.Text) > 250)
{
textBox_GuanLi.Text = "250";
}
}
catch (Exception)
{
}
}
private void button_SearchMachine_Click(object sender, EventArgs e)
{
GetChuanKou();
}
}
}