1.这个开关直接监听串口是没有用的,需要向串口发送数据,然后再监听判断哪一个按钮被按下
2.开关的配置文件配置在xml文件里
3.读取xml类
public class XmlHelper { public static string GetElementByName(string xmlFileName, string tagName) { try { string result = null; XmlDocument doc = new XmlDocument(); doc.Load(xmlFileName); XmlNodeList nodes = doc.GetElementsByTagName(tagName); foreach (XmlNode v in nodes) { result = v.InnerText; } return result; } catch { throw new Exception("打开文件错误"); } } }
4.打开开关串口
SerialPort sport = new SerialPort();
if (sport.IsOpen == true) { sport.Close(); } string sIniFile = appPath + "wmsconfig" + "\" + "SwitchSetting.xml"; if (File.Exists(sIniFile)) { sport.BaudRate = Convert.ToInt32(XmlHelper.GetElementByName(sIniFile, "BaudRate")); sport.DataBits = Convert.ToInt32(XmlHelper.GetElementByName(sIniFile, "DataBits")); sport.StopBits = (StopBits)Convert.ToInt32(XmlHelper.GetElementByName(sIniFile, "StopBits")); sport.Parity = (Parity)Convert.ToInt32(XmlHelper.GetElementByName(sIniFile, "Parity")); var portName = XmlHelper.GetElementByName(sIniFile, "PortName"); if (null != portName) sport.PortName = portName; } sport.BaudRate = 9600; sport.DataBits = 8; sport.StopBits = StopBits.One; //sport.PortName = "COM1"; sport.Parity = Parity.None; try { sport.Open();//打开串口 sport.DtrEnable = true;//设置DTR为高电平 sport.RtsEnable = true;//设置RTS位高电平 } catch (Exception ex) { MessageBox.Show(ex.Message); }
5.写一个定时器不停的向串口发送数据,监听串口
DispatcherTimer timer;
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(1000);
timer.Tick += timer2_Tick;
timer.Start();
sport.DataReceived -= new SerialDataReceivedEventHandler(serialPort_DataReceived);//订阅委
sport.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);//订阅委
private void timer2_Tick(object sender, EventArgs e) { if (sport.IsOpen == true) { strReceiveMessage = ""; byte[] sendData = new byte[] { 0x21, 0x02, 0x00, 0x00, 0x00, 0x08, 0x7E, 0xAC }; ////发送数据 sport.Write(sendData, 0, sendData.Length); } }
6.判断是开始按钮还是结束按钮
//接收按钮数据事件 private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { Thread.Sleep(100); //(毫秒)等待一定时间,确保数据的完整性 int len int len = sport.BytesToRead; string receivedata = string.Empty; if (len != 0) { byte[] buff = new byte[len]; sport.Read(buff, 0, len); for (int i = 0; i < buff.Length; i++) { strReceiveMessage += buff[i].ToString("X2"); //16进制显示 } ts2 = new TimeSpan(DateTime.Now.Ticks); if (strReceiveMessage!=null) { if (strReceiveMessage.Contains("21020104AB8B")) {// MessageBox.Show("开始按钮"); }
}
}
}