private void btnConnect_Click(object sender, EventArgs e) { try { if (serial == null) { try { string portName = this.cmbPort.Text; SerialPortBaudRates baud = (SerialPortBaudRates)Enum.Parse(typeof(SerialPortBaudRates), cmbBaudRate.Text); SerialPortDatabit databit = (SerialPortDatabit)Enum.Parse(typeof(SerialPortDatabit), cmbDataBit.Text); Parity parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text); StopBits stopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBit.Text); //使用枚举构造函数 //serial = new SerialPortUtil(portName, baud, parity, databit, stopBits); //使用字符串构造函数 serial = new SerialPortUtil(portName, cmbBaudRate.Text, cmbParity.Text, cmbDataBit.Text, cmbStopBit.Text); serial.DataReceived += serial_DataReceived; } catch (Exception ex) { MessageBox.Show(ex.Message); serial = null; return; } } if (!isOpen) { //打开串口通讯 serial.OpenPort(); btnConnect.Text = "断开"; //m_receiveT = new Thread(Receive); //m_receiveT.IsBackground = true; //m_receiveT.Start(); } else { serial.ClosePort(); //m_receiveT.Abort(); btnConnect.Text = "连接"; } isOpen = !isOpen; this.btnSend.Enabled = isOpen; this.labState.Text = isOpen ? "已连接" : "未连接"; } catch (Exception ex) { this.labState.Text = ex.Message; MessageBox.Show(ex.Message); } }
/// <summary> /// 定时任务的回调方法 /// </summary> /// <param name="state"></param> public void ReissueThreeTimes(Object state) { if (times < 3 && !isReceive) { byte[] send = (byte[])state; if (serialPort != null) { if (!serialPort.IsOpen) { try { serialPort.Open(); } catch (UnauthorizedAccessException ex) { MessageBoxX.Warning(LanguageUtils.ConvertLanguage("串口被占用", "Serial port is occupied")); return; } catch (IOException ex) { MessageBoxX.Warning(LanguageUtils.ConvertLanguage("串口不存在", "Serial port does not exist")); return; } } serialPort.Write(send, 0, send.Length); } times++; } else if (times >= 3 && !isReceive) { threadTimer.Dispose(); //关闭串口 SerialPortUtil.ClosePort(ref serialPort); Dispatcher.Invoke(new Action(() => { MessageBoxX.Warning(LanguageUtils.ConvertLanguage("设备长时间未应答,请查看是否选对串口,或设备未启动", "The device has not answered for a long time. Check whether the serial port is selected or the device is not started.")); this.Close(); })); } else { threadTimer.Dispose(); } }
private void button1_Click(object sender, EventArgs e) { if (button1.Text == "启动服务") { try { connect(); comPort.PortName = "COM4"; comPort1.PortName = "COM3"; comPort.OpenPort(); comPort1.OpenPort(); timer1.Start(); pp = false; textBox1.AppendText("启动成功!"); timer3.Start(); button1.Text = "停止服务"; button2.Enabled = true; } catch { textBox1.AppendText("启动失败!"); } } else { timer1.Stop(); timer3.Stop(); comPort.ClosePort(); comPort1.ClosePort(); labelwinDir.Text = "NULL"; labelwinSpe.Text = "NULL"; labelPot.Text = "NULL"; if (button2.Text == "取消模拟") { button2_Click(sender, e); button2.Text = "应急模拟"; } button2.Enabled = false; button1.Text = "启动服务"; winDirPic("qqq"); stSocket.Close(); } }
/// <summary> /// 接收数据的监听方法 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnPortDataReceived(Object sender, SerialDataReceivedEventArgs e) { try { Thread.Sleep(50); isReceive = true;//收到数据,取消重发 byte[] buffer = null;; int len = serialPort.BytesToRead; byte[] receiveData = new byte[len]; serialPort.Read(receiveData, 0, len); //Console.WriteLine("收到的数据:" + ProtocolUtil.ByteToStringOk(receiveData)); int offset = 0; Int32 datalen = 0; if (len > 0 && receiveData[0] == 0xAA)//第一包数据 { datalen = Convert.ToInt32((receiveData[2].ToString("X2") + receiveData[3].ToString("X2")), 16); //Console.WriteLine("数据的长度:" + datalen); buffer = new byte[datalen + 6]; for (int i = 0; i < receiveData.Length; i++) { buffer[i] = receiveData[i]; } offset = receiveData.Length; } else { return; } while (buffer != null && buffer[buffer.Length - 1] != 0xCC) { Thread.Sleep(50); int len2 = serialPort.BytesToRead; if (len2 <= 0) { return; } serialPort.Read(buffer, offset, len2); offset += len2; if (offset > buffer.Length) { return; } } //下面是完整数据 if (buffer != null) { byte[] data = new byte[datalen + 3]; Array.Copy(buffer, 1, data, 0, data.Length); if (buffer[buffer.Length - 2] == ProtocolUtil.XorByByte(data)) { object result = null;//用于存放uuid的鉴权加密 new ParserUSBDogFrame().Parser(ref result, buffer); string b = ProtocolUtil.BytesToString((byte[])result); //Console.WriteLine("解密通讯加密后的数据:" + b); byte[] uuidBytes = null; uuidBytes = AesUtil.Decrypt((byte[])result, ProtocolConstant.USB_DOG_AUTH_PASSWORD); //Console.WriteLine("解密鉴权加密后的数据:" + ProtocolUtil.ByteToStringOk(uuidBytes)); string strUUID = System.Text.Encoding.ASCII.GetString(uuidBytes); if (strUUID == Get_UUID()) { //MessageBoxX.Info("激活成功"); //todo 全局变量 ProtocolConstant.USB_SUCCESS = 1; MessageBoxX.Info(LanguageUtils.ConvertLanguage("激活成功", "Activated successfully")); //Console.WriteLine("激活成功"); logger.Debug("激活成功"); } else { //MessageBox.Show("激活失败"); //Console.WriteLine("激活失败"); logger.Debug("激活失败"); } } else { //Console.WriteLine("校验失败"); logger.Debug("校验失败"); } } } catch (Exception ex) { } finally { //收到消息后至空串口并关闭 SerialPortUtil.ClosePort(ref serialPort); Dispatcher.Invoke(new Action(() => { this.Close(); })); } }