private void BindData() { //绑定端口号 SerialPortUtil.SetPortNameValue(cmbPort); cmbPort.SelectedIndex = 0; //波特率 SerialPortUtil.SetBaudRateValues(cmbBaudRate); cmbBaudRate.SelectedText = "9600"; //数据位 SerialPortUtil.SetDataBitsValues(cmbDataBit); cmbDataBit.SelectedText = "8"; //校验位 SerialPortUtil.SetParityValues(cmbParity); cmbParity.SelectedIndex = 0; //停止位 SerialPortUtil.SetStopBitsValues(cmbStopBit); cmbStopBit.SelectedIndex = 1; this.btnSend.Enabled = isOpen; }
private void button2_Click(object sender, EventArgs e) { if (button2.Text == "应急模拟") { pp = true; timer2.Start(); textBox1.AppendText("泄漏发生"); button2.Text = "取消模拟"; } else { pp = false; timer2.Stop(); gateLight1("blue"); gateLight2("blue"); gateLight3("blue"); gateLight4("blue"); gateLight5("blue"); gateLight6("blue"); gateLight7("blue"); gateLight8("blue"); comPort1.WriteData(SerialPortUtil.HexToByte("20")); textBox1.AppendText("取消警报"); button2.Text = "应急模拟"; } }
public void ScanPorts() { var portNames = SerialPortUtil.GetLatestPortsList(); if (portNames == null) { return; } var total = portNames.Length; for (var i = 0; i < portNames.Length; i++) { var portName = portNames[i]; try { SendProgressChanged(String.Format("Scaning port {0}...", portName), i, total); Port = portName; if (IsConnected) { SendProgressChanged(String.Format("Device found on {0}.", portName), total, total); SendReadCompleted(); return; } } catch (Exception e) { SendReadError(e); } } SendProgressChanged("Device not found! Check connection and device mode.", total, total); SendReadCompleted(); }
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); } }
private void timer1_Tick(object sender, EventArgs e) { windSpeed = Convert.ToInt64(getReal(getSpe()), 16) / 10.00; labelwinSpe.Text = windSpeed.ToString("F1") + "m/s"; windDir = labelwinDir.Text = getStrDir(getReal(getDir())); winDirPic(windDir); labelPot.Text = potency + " ppm"; comPort.WriteData(SerialPortUtil.HexToByte("01")); writeData(); string a = potency + " " + windSpeed.ToString() + " " + windDir; }
void comPort_DataReceived(DataReceivedEventArgs e)//触发接收事件(获得浓度) { string a = SerialPortUtil.ByteToHex(e.DataRecv); string temp = a[1].ToString(); temp += a[4].ToString(); temp += a[7].ToString(); temp += a[10].ToString(); int b = Convert.ToInt16(temp); b = b - 500; b = Convert.ToInt16(b * (Math.Sqrt(b)) / 20); potency = b.ToString(); }
public void Connect() { try { switch (_protocol) { case ProtocolType.Cywin: _synchronizedConnector = _basePoderosaInstance.ProtocolService.CreateFormBasedSynchronozedConnector(_window); _asyncConnection = _basePoderosaInstance.ProtocolService.AsyncCygwinConnect(_synchronizedConnector.InterruptableConnectorClient, (ICygwinParameter)_terminalParameter); _terminalConnection = _synchronizedConnector.WaitConnection(_asyncConnection, _basePoderosaInstance.TerminalSessionsPlugin.TerminalSessionOptions.TerminalEstablishTimeout); break; case ProtocolType.Raw: break; case ProtocolType.RLogin: break; case ProtocolType.Serial: _terminalConnection = (ITerminalConnection)SerialPortUtil.CreateNewSerialConnection(_window, (SerialTerminalParam)_terminalParameter, (SerialTerminalSettings)_terminalSettings); break; case ProtocolType.SSH1: case ProtocolType.SSH2: _synchronizedConnector = _basePoderosaInstance.ProtocolService.CreateFormBasedSynchronozedConnector(_window); _asyncConnection = _basePoderosaInstance.ProtocolService.AsyncSSHConnect(_synchronizedConnector.InterruptableConnectorClient, (ISSHLoginParameter)_terminalParameter); _terminalConnection = _synchronizedConnector.WaitConnection(_asyncConnection, _basePoderosaInstance.TerminalSessionsPlugin.TerminalSessionOptions.TerminalEstablishTimeout); break; case ProtocolType.Telnet: _synchronizedConnector = _basePoderosaInstance.ProtocolService.CreateFormBasedSynchronozedConnector(_window); _asyncConnection = _basePoderosaInstance.ProtocolService.AsyncTelnetConnect(_synchronizedConnector.InterruptableConnectorClient, (ITCPParameter)_terminalParameter); _terminalConnection = _synchronizedConnector.WaitConnection(_asyncConnection, _basePoderosaInstance.TerminalSessionsPlugin.TerminalSessionOptions.TerminalEstablishTimeout); break; default: _terminalConnection = null; break; } _terminalSession = new TerminalSession(_terminalConnection, _terminalSettings); _basePoderosaInstance.SessionManagerPlugin.StartNewSession(_terminalSession, _terminalView); _basePoderosaInstance.SessionManagerPlugin.ActivateDocument(_terminalSession.Terminal.IDocument, ActivateReason.InternalAction); } catch (Exception ex) { RuntimeUtil.ReportException(ex); //return CommandResult.Failed; } }
/// <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 timer2_Tick(object sender, EventArgs e) { string g = "green"; string r = "red"; string b = "blue"; if (windDir == "北") { gateLight1(g); gateLight2(g); gateLight3(r); gateLight4(r); gateLight5(r); gateLight6(r); gateLight7(r); gateLight8(g); comPort1.WriteData(SerialPortUtil.HexToByte("11")); } else if (windDir == "东北") { gateLight1(g); gateLight2(g); gateLight3(g); gateLight4(r); gateLight5(r); gateLight6(r); gateLight7(r); gateLight8(r); comPort1.WriteData(SerialPortUtil.HexToByte("12")); } else if (windDir == "东") { gateLight1(r); gateLight2(g); gateLight3(g); gateLight4(g); gateLight5(r); gateLight6(r); gateLight7(r); gateLight8(r); comPort1.WriteData(SerialPortUtil.HexToByte("13")); } else if (windDir == "东南") { gateLight1(r); gateLight2(r); gateLight3(g); gateLight4(g); gateLight5(g); gateLight6(r); gateLight7(r); gateLight8(r); comPort1.WriteData(SerialPortUtil.HexToByte("14")); } else if (windDir == "南") { gateLight1(r); gateLight2(r); gateLight3(r); gateLight4(g); gateLight5(g); gateLight6(g); gateLight7(r); gateLight8(r); comPort1.WriteData(SerialPortUtil.HexToByte("15")); } else if (windDir == "西南") { gateLight1(r); gateLight2(r); gateLight3(r); gateLight4(r); gateLight5(g); gateLight6(g); gateLight7(g); gateLight8(r); comPort1.WriteData(SerialPortUtil.HexToByte("16")); } else if (windDir == "西") { gateLight1(r); gateLight2(r); gateLight3(r); gateLight4(r); gateLight5(r); gateLight6(g); gateLight7(g); gateLight8(g); comPort1.WriteData(SerialPortUtil.HexToByte("17")); } else if (windDir == "西北") { gateLight1(g); gateLight2(r); gateLight3(r); gateLight4(r); gateLight5(r); gateLight6(r); gateLight7(g); gateLight8(g); comPort1.WriteData(SerialPortUtil.HexToByte("18")); } else if (windDir == "无风") { gateLight1(g); gateLight2(g); gateLight3(g); gateLight4(g); gateLight5(g); gateLight6(g); gateLight7(g); gateLight8(g); comPort1.WriteData(SerialPortUtil.HexToByte("10")); } else { gateLight1(b); gateLight2(b); gateLight3(b); gateLight4(b); gateLight5(b); gateLight6(b); gateLight7(b); gateLight8(b); comPort1.WriteData(SerialPortUtil.HexToByte("10")); } }
private void sbtnRfidCopy_Click(object sender, EventArgs e) { sbtnRfidCopy.Enabled = false; #region 输入 判断 string strRFID = tbRFID.Text.Trim(); if (string.IsNullOrEmpty(strRFID)) { MessageUtil.ShowTips("RFID编号不可为空"); sbtnRfidCopy.Enabled = true; return; } else { if (strRFID.Length != 12) { MessageUtil.ShowTips("RFID编号格式错误,请重新输入"); sbtnRfidCopy.Enabled = true; return; } } #endregion try { string strWriteEPC = tbRFID.Text; //strWriteEPC = MainControl.strServerAddr + strWriteEPC; int WriteEPCResult = 1; byte WriteEPClen = Convert.ToByte(strWriteEPC.Length / 4); //WriteEPC的字节长度 ////byte WriteEPClen = Convert.ToByte(strWriteEPC.Length / 4);//WriteEPC的字节长度 //20151109 8616 byte[] WriteEPC = new byte[WriteEPClen]; //访问密码数组形式 //WriteEPC = HexStringToByteArray(strWriteEPC); WriteEPC = SerialPortUtil.HexStrToByte(strWriteEPC); byte[] PassWord = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00 }; //byte[] PassWord = new byte[] { 0x00, 0x00, 0x00, 0x00 }; // 20151109 8616 for (int i = 0; i < 50; i++) //最多写50次 { WriteEPCResult = StaticClassReaderB.WriteEPC_G2(ref ComAdr, PassWord, WriteEPC, WriteEPClen, ref errorcode, frmHandle); //fCmdRet = StaticClassReaderB.WriteEPC_G2(ref fComAdr, fPassWord, EPC, ENum, ref ferrorcode, frmcomportindex); if (WriteEPCResult == 0) { i = 50; } } if (WriteEPCResult == 0)//写RFID成功 { MessageUtil.ShowTips("复制成功"); } else { MessageUtil.ShowError("复制失败,请检查RFID标签是否正确放置,请重新复制"); } } catch (Exception ex) { if (frmMain.blDebug) { MessageUtil.ShowError(ex.ToString()); } } sbtnRfidCopy.Enabled = true; }
private void sbtnOk_Click(object sender, EventArgs e) { sbtnOk.Enabled = false; #region 输入 判断 string strToolId = tbToolID.Text.Trim();//strToolId string strRFID = tbRFID.Text.Trim(); string strToolType = cbbToolType.Text.Trim(); string strToolName = cbbToolName.Text.Trim(); string strPlace = tbPlace.Text.Trim(); string strPeople = cbbOverPeople.Text.Trim(); string strTime = dtpTime.Text; if (string.IsNullOrEmpty(strToolId)) { MessageUtil.ShowTips("工具ID不可为空"); return; } if (string.IsNullOrEmpty(strPlace)) { MessageUtil.ShowTips("工具存放位置不可为空"); return; } if (this.Tag != null) { string strSql = ""; if (this.Tag.ToString() == TagType.修改.ToString()) { strSql = "Select ID From tb_Tools where ToolID='" + strToolId + "' and ID<>'" + sId + "'"; } else if (this.Tag.ToString() == TagType.添加.ToString()) { strSql = "Select ID From tb_Tools where ToolID='" + strToolId + "' "; } if (!string.IsNullOrEmpty(strSql)) { if (operatedata.blCheckHas(strSql)) { MessageUtil.ShowTips("工具ID重复,请重新输入"); return; } } } if (cboxRfid.Checked) { if (string.IsNullOrEmpty(strRFID)) { MessageUtil.ShowTips("RFID编号不可为空"); return; } else { if (strRFID.Length != 12) { MessageUtil.ShowTips("RFID编号格式错误,请重新输入"); return; } else { if (this.Tag != null) { string strSql = ""; if (this.Tag.ToString() == TagType.修改.ToString()) { strSql = "Select ID From tb_Tools where RFIDCoding='" + strRFID + "' and ID<>'" + sId + "'"; } else if (this.Tag.ToString() == TagType.添加.ToString()) { strSql = "Select ID From tb_Tools where RFIDCoding='" + strRFID + "' "; } if (!string.IsNullOrEmpty(strSql)) { if (operatedata.blCheckHas(strSql)) { MessageUtil.ShowTips("RFID编号重复,请重新输入"); return; } } } } } } #endregion #region 入库记录 及 写RFID if (this.Tag != null) { if (this.Tag.ToString() == TagType.修改.ToString()) { string strSql = "update tb_Tools set tvParent='" + strTreeSeleParent + "',ToolType='" + strToolType + "',ToolName='" + strToolName + "'" + ",ToolID='" + strToolId + "',RFIDCoding='" + strRFID + "',StoragePlace='" + strPlace + "' ,TestCycle='" + tbCycle.Text + "'" + "where ID='" + sId + "' "; datalogic.SqlComNonQuery(strSql); this.Close(); } else if (this.Tag.ToString() == TagType.添加.ToString()) { try { int WriteEPCResult = 1; string strWriteEPC = tbRFID.Text; if (cboxRfid.Checked) { //strWriteEPC = MainControl.strServerAddr + strWriteEPC; byte WriteEPClen = Convert.ToByte(strWriteEPC.Length / 4); //WriteEPC的字节长度 ////byte WriteEPClen = Convert.ToByte(strWriteEPC.Length / 4);//WriteEPC的字节长度 //20151109 8616 byte[] WriteEPC = new byte[WriteEPClen]; //访问密码数组形式 //WriteEPC = HexStringToByteArray(strWriteEPC); WriteEPC = SerialPortUtil.HexStrToByte(strWriteEPC); byte[] PassWord = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00 }; //byte[] PassWord = new byte[] { 0x00, 0x00, 0x00, 0x00 }; // 20151109 8616 for (int i = 0; i < 50; i++) //最多写50次 { WriteEPCResult = StaticClassReaderB.WriteEPC_G2(ref ComAdr, PassWord, WriteEPC, WriteEPClen, ref errorcode, frmHandle); //fCmdRet = StaticClassReaderB.WriteEPC_G2(ref fComAdr, fPassWord, EPC, ENum, ref ferrorcode, frmcomportindex); if (WriteEPCResult == 0) { break; } } } else { WriteEPCResult = 0; strWriteEPC = ""; } if (WriteEPCResult == 0)//写RFID成功 { #region 更新 显示树 TreeNode node = new TreeNode(); //获取ChildId string strChild = operatedata.GetChildId("tb_Tools", "tvChildId"); node.Name = strChild;// node.Name 为本节点的编号 string strParent = treeView1.SelectedNode.Name.ToString(); node.Tag = strParent; node.Text = strToolId; node.ImageIndex = 3; node.SelectedImageIndex = 3; treeView1.SelectedNode.Nodes.Add(node); //treeView1.CollapseAll(); #endregion string strTimeBorrRet = DateTime.Now.AddMinutes(-1).ToString("yyyy-MM-dd HH:mm:ss"); string strSql = "insert into tb_Tools (tvParent,tvChildId,IsArea,ToolType,ToolName,ToolID,RFIDCoding,StoragePlace,InPeople,InTime,IsInStore," + "TestCycle,TestState,BorrowReturnTime)" + "values ('" + strParent + "','" + strChild + "','" + ToolAreaType.工具.ToString() + "','" + strToolType + "','" + strToolName + "'," + "'" + strToolId + "','" + strWriteEPC + "','" + strPlace + "','" + strPeople + "','" + strTime + "'," + "'" + ToolsState.在库.ToString() + "','" + tbCycle.Text + "','未录入试验记录','" + strTime + "')"; datalogic.SqlComNonQuery(strSql); strSql = "insert into tb_RecordInRoom (ToolType,ToolName,ToolID,RFIDCoding,StoragePlace,InPeople,InTime) values ('" + strToolType + "'," + "'" + strToolName + "','" + strToolId + "','" + strWriteEPC + "','" + strPlace + "','" + strPeople + "','" + strTime + "')"; datalogic.SqlComNonQuery(strSql); #region 自动生成工具ID string strName = cbbToolName.Text; strSql = "select top 1 ToolID from tb_Tools where IsArea='" + ToolAreaType.工具.ToString() + "' " + "and ToolName='" + strName + "' order by id desc ";// select top 1 * from table order by id desc object ob = datalogic.SqlComScalar(strSql); int iNo = 0; if (ob != null) { int iLength = strName.Length; strToolId = ob.ToString(); string strNameOfId = strToolId.Substring(0, iLength);//strToolId中的工具名称 绝缘手套007 绝缘手套 if (strName == strNameOfId) { if ((strToolId.Length - iLength) == 3)//数字部分的长度 { string strNo = strToolId.Substring(iLength, 3); try { iNo = Convert.ToInt32(strNo); } catch (Exception ex) { //iNo = 0; if (frmMain.blDebug) { MessageUtil.ShowTips(ex.Message); } } } } } iNo++; string striNo = iNo.ToString(); int iLen = 3 - striNo.Length; striNo = clsCommon.FormatString(iLen) + striNo; tbToolIdAdd.Text = striNo; tbToolID.Text = strName + striNo; #endregion #region 自动生成 RFID if (cboxRfid.Checked) { //工具名称编码 tbRfidName strSql = "select ToolsNameCoding from tb_TypeAndName where ToolName='" + cbbToolName.Text + "' "; ob = datalogic.SqlComScalar(strSql); if (ob != null) { string strServerAddrRfid = infoOfSystem.strServerAddr; if (strServerAddrRfid.Length == 1) { strServerAddrRfid = "000" + strServerAddrRfid; } else if (strServerAddrRfid.Length == 2) { strServerAddrRfid = "00" + strServerAddrRfid; } if (strServerAddrRfid.Length > 4) { strServerAddrRfid = strServerAddrRfid.Substring(0, 4); } tbRfidName.Text = strServerAddrRfid + ob.ToString(); } //RFID 编码 strSql = "select top 1 RFIDCoding from tb_Tools where IsArea='" + ToolAreaType.工具.ToString() + "' and " + "ToolName='" + strName + "' order by id desc ";// select top 1 * from table order by id desc ob = datalogic.SqlComScalar(strSql); iNo = 0; if (ob != null) { string strLastCoding = ob.ToString(); if (strLastCoding.Length == 12) { string strLastNo = strLastCoding.Substring(8, 4); iNo = Convert.ToInt32(strLastNo); } } iNo++; striNo = iNo.ToString(); iLen = 4 - striNo.Length; striNo = clsCommon.FormatString(iLen) + striNo; tbRfidNo.Text = striNo; tbRFID.Text = tbRfidName.Text + tbRfidNo.Text; } #endregion } else { MessageUtil.ShowError("工具入库失败,请检查RFID标签是否正确放置或重新录"); } } catch (Exception ex) { if (frmMain.blDebug) { MessageUtil.ShowError(ex.ToString()); } //MessageUtil.ShowError("工具入库失败,请检查RFID标签是否正确放置、RFID读卡器是否正确连接或重新录入"); } } } #endregion //sbtnOk.Enabled = true; treeView1.SelectedNode = null; }
//确定按钮 private void Determine(object sender, RoutedEventArgs e) { String password = NonPublicInformationPassword.Password; if ("111" == password) { try { //与U盘交互 //1.打包协议到result; byte[] send = null; //获取电脑的uuid字节数组-即加密狗的内容 ProtocolConstant.USB_DOG_CONTENT = Encoding.UTF8.GetBytes(Get_UUID()); new MakerUSBDogFrame().PackData(ref send, new byte[] { 0xF0 }, ProtocolConstant.USB_DOG_CONTENT); //Console.WriteLine("加密后的报文" + ProtocolUtil.ByteToStringOk(send)); //byte[] test = null; //new MakerUSBDogFrame().PackData(ref test, new byte[] { 0xF0 }, Encoding.UTF8.GetBytes("hello")); logger.Debug("激活:" + ProtocolUtil.ByteToStringOk(send)); //2.判断当前是否已经连接过串口 SerialPortUtil.CheckPort(); if (SerialPortUtil.portName == "") { MessageBoxX.Warning(LanguageUtils.ConvertLanguage("请先连接串口", "Please connect the serial port first")); return; } if (SerialPortUtil.SerialPort != null) { SerialPortUtil.SerialPort = null; } if (serialPort == null) { serialPort = SerialPortUtil.ConnectSerialPort(OnPortDataReceived); 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")); this.Close(); return; } serialPort.Write(send, 0, send.Length); //发送的定时器 threadTimer = new System.Threading.Timer(new System.Threading.TimerCallback(ReissueThreeTimes), send, 500, 500); } } catch (Exception ex) { logger.Error("激活异常"); //Console.WriteLine("激活异常"); } //else //{ // if (!serialPort.IsOpen) // { // try // { // serialPort.Open(); // } // catch (UnauthorizedAccessException ex) // { // MessageBoxX.Warning("串口被占用", "温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning); // return; // } // catch (IOException ex) // { // MessageBoxX.Warning("串口不存在", "温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning); // return; // } // } //} } else { MessageBoxX.Warning(LanguageUtils.ConvertLanguage("密码错误,请重新输入", "Password error, please retype")); } }
/// <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(); })); } }
public bool ReadEpcInfo() { bool blRet = false; try { byte MaskMem = 0; byte[] MaskAdr = new byte[2]; byte MaskLen = 0; byte[] MaskData = new byte[100]; byte MaskFlag = 0; byte AdrTID = 0; byte LenTID = 0; byte TIDFlag = 0; byte Ant = 0; blScan = true; int CardCount = 0; //输出变量,电子标签的张数 int EpcLen = 0; //EPC 的字节数 byte[] bEpcArray = new byte[5000]; //指向输出数组变量 是读到的电子标签的EPC数据,是一张标签的EPC长度+一张标签的EPC号,依此累加 //int fCmdRet = StaticClassReaderB.Inventory_G2(ref fComAdr, MaskMem, MaskLen, MaskFlag); //if ((fCmdRet==0)|| (fCmdRet == 1) || (fCmdRet == 2) || (fCmdRet == 3) || (fCmdRet == 4) || (fCmdRet == 0xFB))//代表已查找结束, //{ } //else //{ // iReadEpcErr++; // blRet = false; //} int fCmdRet = StaticClassReaderB.Inventory_G2(ref fComAdr, MaskMem, MaskAdr, MaskLen, MaskData, MaskFlag, AdrTID, LenTID, TIDFlag, bEpcArray, ref Ant, ref EpcLen, ref CardCount, frmcomportindex); // 8616 if ((fCmdRet == 1) || (fCmdRet == 2) || (fCmdRet == 3) || (fCmdRet == 4) || (fCmdRet == 0xFB)) //代表已查找结束, { iReadEpcErr = 0; blRet = true; if (CardCount == 0) { blScan = false; return(blRet); } byte[] bEpcCopy = new byte[EpcLen]; Array.Copy(bEpcArray, bEpcCopy, EpcLen); string strEpcAll = SerialPortUtil.ByteToStr(bEpcCopy); int iEpcIndex = 0;//单张EPC的长度在bEpcCopy中的位置 for (int i = 0; i < CardCount; i++) { int iEpcLen = bEpcCopy[iEpcIndex]; //epc的长度 string strEpc = strEpcAll.Substring(iEpcIndex * 2 + 2, iEpcLen * 2); //得到一个EPC数据 iEpcIndex = iEpcIndex + iEpcLen + 1; //下一个EPC标签的 标签长度指示位置 if (strEpc.Length != 12) { break; } bool blHas = false; if (dicEpcInfo.ContainsKey(strEpc)) {//存在标签信息 #region 顺序读取 if (usingReadNo == DeviceUsing.启用) { if (dicEpcInfo[strEpc].IntAnt != Ant) { //查询到标签的天线和原来的不一样 if ((dicEpcInfo[strEpc].IntAnt & 0x01) == 0x01 || (dicEpcInfo[strEpc].IntAnt & 0x02) == 0x02) { //归还 原来是1# 2#天线扫描到 if ((Ant & 0x04) == 0x04 || (Ant & 0x08) == 0x08) { //现在是3# 4#天线扫描到 dicEpcInfo[strEpc].BorrOrRet = ToolsBorrRet.归还; dicEpcInfo[strEpc].DtReadedEpc = DateTime.Now; RfidManage.QEpcInfo.Enqueue(dicEpcInfo[strEpc]); } } else { //借出 if ((dicEpcInfo[strEpc].IntAnt & 0x04) == 0x04 || (dicEpcInfo[strEpc].IntAnt & 0x08) == 0x08) { //原来是3# 4#天线扫描到 if ((Ant & 0x01) == 0x01 || (Ant & 0x02) == 0x02) { //现在是1# 2#天线扫描到 dicEpcInfo[strEpc].BorrOrRet = ToolsBorrRet.借出; dicEpcInfo[strEpc].DtReadedEpc = DateTime.Now; RfidManage.QEpcInfo.Enqueue(dicEpcInfo[strEpc]); } } } dicEpcInfo[strEpc].IntAnt = Ant; } dicEpcInfo[strEpc].UsingReadNo = DeviceUsing.启用; } blHas = true; #endregion } else { EpcInfo ei = new EpcInfo(strEpc, Ant); ei.TimeLastRead = DateTime.Now; if (usingReadNo == DeviceUsing.启用) { ei.UsingReadNo = DeviceUsing.启用; } ei.BorrOrRet = ToolsBorrRet.未知; ei.IsEpcRead = IsReadShow.未读; dicEpcInfo.Add(strEpc, ei); } } } else { iReadEpcErr++; blRet = false; } blScan = false; } catch (Exception ee) { if (frmMain.blDebug) { MessageUtil.ShowTips(ee.Message); } } return(blRet); }
public bool ReadEpc() { bool blRet = false; try { byte MaskMem = 0; byte[] MaskAdr = new byte[2]; byte MaskLen = 0; byte[] MaskData = new byte[100]; byte MaskFlag = 0; byte AdrTID = 0; byte LenTID = 0; byte TIDFlag = 0; byte Ant = 0; blScan = true; int CardCount = 0; //输出变量,电子标签的张数 int EpcLen = 0; //EPC 的字节数 byte[] bEpcArray = new byte[5000]; //指向输出数组变量 是读到的电子标签的EPC数据,是一张标签的EPC长度+一张标签的EPC号,依此累加 int fCmdRet = StaticClassReaderB.Inventory_G2(ref fComAdr, MaskMem, MaskAdr, MaskLen, MaskData, MaskFlag, AdrTID, LenTID, TIDFlag, bEpcArray, ref Ant, ref EpcLen, ref CardCount, frmcomportindex); // 8616 if ((fCmdRet == 1) || (fCmdRet == 2) || (fCmdRet == 3) || (fCmdRet == 4) || (fCmdRet == 0xFB)) //代表已查找结束, { blRet = true; if (CardCount == 0) { blScan = false; return(blRet); } byte[] bEpcCopy = new byte[EpcLen]; Array.Copy(bEpcArray, bEpcCopy, EpcLen); string strEpcAll = SerialPortUtil.ByteToStr(bEpcCopy); int iEpcIndex = 0;//单张EPC的长度在bEpcCopy中的位置 for (int i = 0; i < CardCount; i++) { int iEpcLen = bEpcCopy[iEpcIndex]; //epc的长度 string strEpc = strEpcAll.Substring(iEpcIndex * 2 + 2, iEpcLen * 2); //得到一个EPC数据 iEpcIndex = iEpcIndex + iEpcLen + 1; //下一个EPC标签的 标签长度指示位置 if (strEpc.Length != 12) { break; } bool blHas = false; for (int iIndex = 0; iIndex < listEpc.Count; iIndex++) { if (listEpc[iIndex].StrEpc == strEpc) { #region 顺序读取 if (usingReadNo == DeviceUsing.启用) { if (listEpc[iIndex].IntAnt != Ant) { //归还 if (((listEpc[iIndex].IntAnt & 0x01) == 0x01 || (listEpc[iIndex].IntAnt & 0x02) == 0x02)) //if (((listEpc[iIndex].IntAnt & 0x01) == 0x01 || (listEpc[iIndex].IntAnt & 0x02) == 0x02) && // ((listEpc[iIndex].IntAnt & 0x04) != 0x04 && (listEpc[iIndex].IntAnt & 0x08) != 0x08)) { if ((Ant & 0x4) == 0x04 || (Ant & 0x8) == 0x08) { //TimeSpan span = DateTime.Now - listEpc[iIndex].TimeLastRead; //if (span.TotalSeconds < 5) //{ // lock (listEpc) // { // listEpc[iIndex].BorrOrRet = ToolsBorrRet.归还; // } //} lock (listEpc) { listEpc[iIndex].BorrOrRet = ToolsBorrRet.归还; } } } else if (((listEpc[iIndex].IntAnt & 0x04) == 0x04 || (listEpc[iIndex].IntAnt & 0x08) == 0x08)) //else if (((listEpc[iIndex].IntAnt & 0x04) == 0x04 || (listEpc[iIndex].IntAnt & 0x08) == 0x08) && // ((listEpc[iIndex].IntAnt & 0x01) != 0x01 && (listEpc[iIndex].IntAnt & 0x02) != 0x02)) { if ((Ant & 0x01) == 0x01 || (Ant & 0x02) == 0x02) { //TimeSpan span = DateTime.Now - listEpc[iIndex].TimeLastRead; //if (span.TotalSeconds < 5) //{ // lock (listEpc) // { // listEpc[iIndex].BorrOrRet = ToolsBorrRet.借出; // } //} lock (listEpc) { listEpc[iIndex].BorrOrRet = ToolsBorrRet.借出; } } } lock (listEpc) { listEpc[iIndex].IntAnt = Ant;//| listEpc[iIndex].IntAnt } //lock (listEpc) //{ // listEpc[iIndex].TimeLastRead = DateTime.Now; //} } if (listEpc[iIndex].UsingReadNo != DeviceUsing.启用) { lock (listEpc) { listEpc[iIndex].UsingReadNo = DeviceUsing.启用; } } } #endregion #region 常规读取 //else //{ // lock (listEpc) // { // listEpc[iIndex].TimeLastRead = DateTime.Now; // } //} #endregion blHas = true; break; } } if (blHas == false) { clsReadEpc clsEpc = new clsReadEpc(strEpc, Ant); clsEpc.TimeLastRead = DateTime.Now; if (usingReadNo == DeviceUsing.启用) { clsEpc.UsingReadNo = DeviceUsing.启用; } clsEpc.BorrOrRet = ToolsBorrRet.未知; clsEpc.IsEpcRead = IsReadShow.未读; lock (listEpc) { listEpc.Add(clsEpc); } } } } else { blRet = false; } blScan = false; } catch (Exception ee) { if (frmMain.blDebug) { MessageUtil.ShowTips(ee.Message); } } return(blRet); }