/// <summary> /// 处理接收到的动态计量数据 /// </summary> private void ReceiveJtjlSocketData() { SendQuit(); Thread.Sleep(200); SendCmd(JTJL_CMD.SEND_JTJL); WeightDeviceLogger.Debug("发送指令:" + JTJL_CMD.SEND_JTJL); //接收打开返回 ShowErrMsg("发送指令:" + JTJL_CMD.SEND_JTJL); while (_isProcessData) { try { var data = new byte[1024]; var recv = _udpcSend.ReceiveFrom(data, ref _remoteIpep); var message = Encoding.ASCII.GetString(data, 0, recv); ShowErrMsg("收到数据:" + message); WeightDeviceLogger.Debug("收到数据:" + message); lock (_receiveDataQueue) { _receiveDataQueue.Enqueue(message); } } catch (Exception ex) { ShowErrMsg("接收数据异常,原因:" + ex.Message); WeightDeviceLogger.Error("接收数据异常,原因:" + ex.Message); Thread.Sleep(50); } } }
/// <summary> /// 停止数据处理 /// </summary> /// <returns></returns> public bool Stop() { canRaiseWeightDataEvent = false; _isProcessWeightData = false; int waitTime = 0; while (_threadWeight.IsAlive) { Thread.Sleep(50); waitTime += 50; if (waitTime >= 300) { try { _threadWeight.Abort(); } catch { WeightDeviceLogger.Debug("强制结束衡器数据处理线程。"); } } } WeightDeviceLogger.Debug("停止表头数据处理。"); return(true); }
/// <summary> /// 清零 /// </summary> /// <param name="pDeviceName"></param> /// <returns></returns> public bool ClearZero() { bool rtn = false; try { bool isopen = _spCom.IsOpen; if (!_spCom.IsOpen) { _spCom.Open(); WeightDeviceLogger.Debug("表头清零时,先打开串口。"); } byte[] tClear = { 0X5A, 0X0D, 0X0A };//Z _spCom.Write(tClear, 0, tClear.Length); //if (isopen == false) //{ // _spCom.Close(); //} WeightDeviceLogger.Debug("表头清零成功。"); rtn = true; } catch (Exception ex) { rtn = false; WeightDeviceLogger.Error("表头清零失败.", ex); ShowErrorMsg(ErrorType.Error, "表头清零失败."); } return(rtn); }
/// <summary> /// 清零 /// </summary> /// <returns></returns> public bool ClearZero() { var rtn = false; try { var isopen = _spCom.IsOpen; if (!_spCom.IsOpen) { _spCom.Open(); } _spCom.Write("Z"); //if (isopen == false) //{ // _spCom.Close(); //} WeightDeviceLogger.Debug("表头清零成功."); rtn = true; } catch (Exception ex) { rtn = false; WeightDeviceLogger.Error("表头清零失败。", ex); ShowErrorMsg(ErrorType.Warning, "表头清零失败."); } return(rtn); }
/// <summary> /// 清零 /// </summary> /// <returns></returns> public bool ClearZero() { var rtn = false; try { var isopen = _spCom.IsOpen; if (!_spCom.IsOpen) { _spCom.Open(); } //_spCom.Write("Z"); //01 06 00 01 00 17 98 04 byte[] tClear = { 0X01, 0X06, 0X00, 0X01, 0X00, 0X17, 0X98, 0X04 };//Z _spCom.Write(tClear, 0, tClear.Length); //_spCom.Write("0X17"); //if (isopen == false) //{ // _spCom.Close(); //} WeightDeviceLogger.Debug("表头清零成功."); rtn = true; } catch (Exception ex) { rtn = false; WeightDeviceLogger.Error("表头清零失败。", ex); ShowErrorMsg(ErrorType.Warning, "表头清零失败."); } return(rtn); }
public WeightController() { WeightDeviceLogger.Debug("----------------------------------五岳通讯开始-----------------------------------"); var temp = TrainMeasureCfgReader.CfgReader.ReadWuYueConfig(); WeightDeviceLogger.Debug("读取到配置信息"); Init(temp); }
/// <summary> /// 启动发送和接收线程 /// </summary> /// <returns></returns> public void StartDTJL() { WeightDeviceLogger.Debug("启动动态计量!"); ShowErrMsg("启动动态计量!"); _isProcessData = false; Thread.Sleep(100); //if (_threadProcessData != null) //{ // while (_threadProcessData.IsAlive) // { // Thread.Sleep(50); // } //} //if (_threadSocket != null) //{ // while (_threadSocket.IsAlive) // { // Thread.Sleep(50); // } //} //_receiveDataQueue.Clear(); if (_threadProcessData != null && _threadProcessData.IsAlive) { _threadProcessData.Abort(); lock (_receiveDataQueue) { _receiveDataQueue.Clear(); } } if (_threadSocket != null && _threadSocket.IsAlive) { _threadSocket.Abort(); } _isProcessData = true; //启动数据处理线程 ThreadStart ts1 = ProcessDTJL; _threadProcessData = new Thread(ts1) { IsBackground = true }; _threadProcessData.Start(); //启动动态计量 ThreadStart ts = ReceiveDtjlSocketData; _threadSocket = new Thread(ts) { IsBackground = true }; _threadSocket.Start(); }
private void ReadComData() { try { if (_closeComPort) { _canRunThreadWeight = false; _spCom.Close(); if (_comData != null) { _comData.Clear(); } WeightDeviceLogger.Debug("读取数据前关闭表头串口成功。"); Thread.Sleep(200); return; } if (_spCom.IsOpen) { int readDataLen = _spCom.BytesToRead; byte[] buf = new byte[readDataLen]; _isDataReceiving = true; int length = _spCom.Read(buf, 0, readDataLen); _isDataReceiving = false; if (length > 0) { string readstr = Encoding.ASCII.GetString(buf); //FileHelpClass.WriteLog("金钟串口接收信息:" + readstr , "WEIGHT"); // weightSem.WaitOne(); lock (_comData) { if (_comData.Count <= 54) { _comData.AddRange(buf.Take(length)); } } // weightSem.Release(); } } } catch (TimeoutException ex) { WeightDeviceLogger.Error("读取表头串口数据超时1秒。", ex); } catch (Exception ex) { WeightDeviceLogger.Error("读取表头串口数据错误。", ex); } }
/// <summary> /// 构造函数 /// </summary> /// <param name="pConfigFile">配置文件</param> public WeightManager(string pConfigFile) { WeightDeviceLogger.Debug("--------------------------开始----------------------------"); ConfigReader cfgReader = new ConfigReader(pConfigFile); try { _curWeightCfg = ConfigReader.ReadWeighingApparatusCfg(); WeightDeviceLogger.Debug("读取衡器配置成功。"); } catch (Exception ex) { WeightDeviceLogger.Error("读取衡器配置异常。", ex); throw ex; } }
private void Init(WuYueConfig pWuYueConfig) { WeightDeviceLogger.Debug(string.Format("配置明细,发送IP地址:{0},端口:{1},接收端口:{2},零点最大偏差:{3}", pWuYueConfig.SendIp, pWuYueConfig.SendPort, pWuYueConfig.ReceivePort, pWuYueConfig.DynamicOffset)); _receiveDataQueue = new Queue <string>(20); _curWuYueConfig = pWuYueConfig; _localIpep = new IPEndPoint(IPAddress.Parse(_curWuYueConfig.SendIp), _curWuYueConfig.SendPort); // 本机IP,指定的端口号 _remoteIpep = new IPEndPoint(IPAddress.Any, _curWuYueConfig.ReceivePort); _udpcSend = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); _udpcSend.Bind(_remoteIpep); WeightDeviceLogger.Debug("初始化五岳通讯服务成功!"); ShowErrMsg("初始化五岳通讯服务成功!"); }
/// <summary> /// 读取com口数据,存入_comData中,与_spCom_DataReceived处理方法一致 /// </summary> private void ReadComData() { try { if (!_spCom.IsOpen) { WeightDeviceLogger.Error("接收数据时错误,原因:串口未打开"); return; } if (_closeComPort) { _canRunThreadWeight = false; _spCom.Close(); if (_comData != null) { _comData.Clear(); } WeightDeviceLogger.Debug("读取数据前关闭表头串口成功。"); Thread.Sleep(200); return; } var readDataLen = _spCom.BytesToRead; var buf = new byte[readDataLen]; _isDataReceiving = true; var length = _spCom.Read(buf, 0, readDataLen); _isDataReceiving = false; if (length <= 0) { return; } lock (_comData) { _comData.AddRange(buf.Take(length)); } } catch (TimeoutException ex) { WeightDeviceLogger.Error("读取表头串口数据超时1秒。", ex); } catch (Exception ex) { WeightDeviceLogger.Error("读取表头串口数据错误。", ex); } }
/// <summary> /// 释放 /// </summary> public void Close() { //SendQuit(); _isProcessData = false; if (_threadProcessData != null && _threadProcessData.IsAlive) { _threadProcessData.Abort(); _receiveDataQueue.Clear(); } if (_threadSocket != null && _threadSocket.IsAlive) { _threadSocket.Abort(); } _udpcSend.Close(); WeightDeviceLogger.Debug("退出五岳衡器。"); }
/// <summary> /// 记录串口通讯异常信息 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void _spCom_ErrorReceived(object sender, SerialErrorReceivedEventArgs e) { curErrCount++; if (curErrCount >= 10) { Stop(); Close(); Thread.Sleep(100); WeightDeviceLogger.Error("重新打开串口._spCom.IsOpen=" + _spCom.IsOpen); if (Open()) { Start(); WeightDeviceLogger.Debug("已重新打开串口._spCom.IsOpen=" + _spCom.IsOpen); } curErrCount = 0; } WeightDeviceLogger.Error("接受到串口通讯错误。e.EventType=" + e.EventType); //ShowErrorMsg(ErrorType.Error, "接受到串口通讯异常"); }
/// <summary> /// 获取数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _spCom_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { Thread.Sleep(50); // WeightDeviceLogger.Debug("接收到数据"); if (!_spCom.IsOpen) { WeightDeviceLogger.Error("接收数据时错误,原因:串口未打开"); return; } if (_closeComPort) { _spCom.Close(); Thread.Sleep(200); return; } var readDataLen = _spCom.BytesToRead; var buf = new byte[readDataLen]; _isDataReceiving = true; var length = _spCom.Read(buf, 0, readDataLen); _isDataReceiving = false; if (length <= 0) { return; } lock (_comData) { _comData.AddRange(buf.Take(length)); } WeightDeviceLogger.Debug("串口中数据为:" + ByteArrayToHexString(_comData.ToArray())); ProcessWeightByModbusNew(); } catch (Exception ex) { WeightDeviceLogger.Error("串口接收数据异常,原因:", ex); } }
/// <summary> /// 关闭表头 /// </summary> /// <returns></returns> public bool Close() { var rtn = true; try { if (_spCom.IsOpen) { //_log.Info("关闭串口。"); if (_isDataReceiving) { _closeComPort = true; WeightDeviceLogger.Debug("关闭表头时,串口正在接收数据。"); } else { //_canRunThreadWeight = false; _spCom.Close(); if (_comData != null) { lock (_comData) { _comData.Clear(); } WeightDeviceLogger.Debug("关闭表头时清除已接收的重量数据。_comData=" + ByteArrayToHexString(_comData.ToArray())); } Thread.Sleep(200); } } } catch (Exception ex) { rtn = false; WeightDeviceLogger.Error("关闭表头失败。", ex); ShowErrorMsg(ErrorType.Warning, "关闭表头失败。"); } return(rtn); }
/// <summary> /// 创建实例 /// </summary> private void CreateInstance() { try { string driverPath = System.AppDomain.CurrentDomain.BaseDirectory; driverPath = Path.Combine(driverPath, _curWeightCfg.DriverName); Assembly assembly = Assembly.LoadFile(driverPath); WeightDeviceLogger.Debug("加载衡器硬件封装。DLL=" + driverPath); string name = assembly.FullName.Split(',')[0] + ".WeightController"; Type type = assembly.GetType(name); _curWeightDev = Activator.CreateInstance(type, _curWeightCfg) as IWeightController; _curWeightDev.OnReceivedWeightData += _curWeightDev_OnReceivedWeightData; _curWeightDev.OnShowErrorMsg += _curWeightDev_OnShowErrorMsg; WeightDeviceLogger.Debug("创建衡器实例成功。"); } catch (Exception ex) { WeightDeviceLogger.Error("创建衡器实例异常。", ex); throw ex; } }
/// <summary> /// 关闭表头 /// </summary> /// <returns></returns> public bool Close() { bool rtn = true; try { if (_spCom.IsOpen) { if (_isDataReceiving) { _closeComPort = true; WeightDeviceLogger.Debug("关闭表头时,串口正在接收数据。"); } else { _canSendGetWeightCmd = false; _canRunThreadWeight = false; _spCom.Close(); WeightDeviceLogger.Debug("关闭表头成功。"); } } if (_comData != null) { _comData.Clear(); WeightDeviceLogger.Debug("关闭表头时清除已接收的重量数据。_comData=" + ByteArrayToHexString(_comData.ToArray())); } Thread.Sleep(200); } catch (Exception ex) { rtn = false; WeightDeviceLogger.Error("关闭表头失败。", ex); ShowErrorMsg(ErrorType.Error, "关闭表头失败。"); } return(rtn); }
/// <summary> /// 提取重量数据 /// </summary> private void ProcessWeight() { int dataLen = 18; int index = 0; while (_isProcessWeightData) { try { var tWeight = new Byte[7]; //重量 var rawData = new Byte[dataLen]; //原始数据 if (_comData.Count >= dataLen) { #region LeftToRight index = GetSegMarkerIndex() + 2; if (index == dataLen) { #region try string tag = "1"; Array.Copy(_comData.ToArray(), rawData, index); byte[] temp = new byte[] { rawData[0], rawData[1] }; if (temp[0] == 0X4F && temp[1] == 0X4C) // if (System.Text.ASCIIEncoding.Default.GetString(temp)!="OV") { tag = "0";//超重 } Array.Copy(rawData, 7, tWeight, 0, 7); string weightTemp = System.Text.Encoding.ASCII.GetString(tWeight); if (tag == "1" && int.Parse(weightTemp) > _curWeightCfg.MaxWeight) { tag = "0"; } //获取+-符号 if (rawData[6] == Convert.ToByte(0X2D))//"-"号 { weightTemp = "-" + (tag == "0"?"1":weightTemp.Trim()); } //触发事件 if (canRaiseWeightDataEvent) { WeightDeviceLogger.Debug(string.Format("触发重量事件。weightTemp={0},temp={1},tag={2}", weightTemp, ByteArrayToHexString(temp), tag)); OnGetWeightData(tag, tag == "0"?"-1":weightTemp, ""); curErrCount = 0; } if (tag == "0" || int.Parse(weightTemp.Trim()) == 0) { Thread.Sleep(50); } #endregion } else if (index > 0) { var exceptData = new Byte[index]; Array.Copy(_comData.ToArray(), exceptData, index); //_log.Warn("异常数据:" + exceptData); WeightDeviceLogger.Error("衡器异常数据。_comData=" + ByteArrayToHexString(_comData.ToArray())); //FileHelpClass.WriteLog("【【【【【【【【【【【【异常数据】】】】】】】】】】:" + exceptData, "WEIGHT"); Thread.Sleep(50); } #endregion } else { Thread.Sleep(50); } } catch (Exception ex) { WeightDeviceLogger.Error("数据线程处理内部异常,_comData=" + ByteArrayToHexString(_comData.ToArray()), ex); } finally { //跳过已处理的数据 lock (_comData) { if (index > 0) { try { _comData.RemoveRange(0, index); } catch (Exception ex) { WeightDeviceLogger.Error("移除已处理数据异常,index=" + index.ToString(), ex); } index = 0; } } } } }
/// <summary> /// 五岳衡器配置相关 /// </summary> /// <param name="pWuYueConfig"></param> public WeightController(WuYueConfig pWuYueConfig) { WeightDeviceLogger.Debug("----------------------------------五岳通讯开始-----------------------------------"); Init(pWuYueConfig); }
/// <summary> /// 打开串口,并注册数据接收方法 /// </summary> /// <returns></returns> public bool Open() { bool rtn = false; try { if (_curWeightCfg != null) { WeightDeviceLogger.Debug(string.Format("设置串口参数。ComPort={0},Baudrate={1},DataBits={2}, Parity={3},StopSize={4}", _curWeightCfg.ComPort, _curWeightCfg.Baudrate, _curWeightCfg.ByteSize, _curWeightCfg.Parity, _curWeightCfg.StopSize)); #region 打开表头 _spCom = new SerialPort(_curWeightCfg.ComPort, int.Parse(_curWeightCfg.Baudrate)); //_spCom.Encoding = Encoding.ASCII; _spCom.DataBits = _curWeightCfg.ByteSize; _spCom.ReadBufferSize = 100; _spCom.ReadTimeout = 1000; //奇偶校验 if (_curWeightCfg.Parity == ParityType.Even) { _spCom.Parity = Parity.Odd; } else if (_curWeightCfg.Parity == ParityType.Odd) { _spCom.Parity = Parity.Even; } else { _spCom.Parity = Parity.None; } //停止位 if (_curWeightCfg.StopSize == StopBitsType.One) { _spCom.StopBits = StopBits.One; } else if (_curWeightCfg.StopSize == StopBitsType.OnePointFive) { _spCom.StopBits = StopBits.OnePointFive; } else if (_curWeightCfg.StopSize == StopBitsType.Two) { _spCom.StopBits = StopBits.Two; } else { _spCom.StopBits = StopBits.None; } if (false == _IsCommandMode) { _spCom.DataReceived += _spCom_DataReceived; _spCom.ErrorReceived += _spCom_ErrorReceived; } try { _spCom.Open(); //if (_IsCommandMode) //{ // //启动发送命令的线程 // //StartGetWeightThread(); //} WeightDeviceLogger.Debug("表头打开串口。IsOpen=" + _spCom.IsOpen); if (_spCom.IsOpen) { _closeComPort = false; _isProcessWeightData = true; _canSendGetWeightCmd = true; ThreadStart ts = new ThreadStart(ProcessWeight); _threadWeight = new Thread(ts); _threadWeight.IsBackground = true; _canRunThreadWeight = true; _threadWeight.Start(); WeightDeviceLogger.Debug("启动表头数据处理线程成功。"); rtn = true; } } catch (Exception ex) { WeightDeviceLogger.Error("打开表头失败。", ex); ShowErrorMsg(ErrorType.Error, "表头串口失败."); throw ex; } #endregion } else { WeightDeviceLogger.Error("表头配置信息不存在。"); ShowErrorMsg(ErrorType.Error, "表头配置信息不存在."); } } catch (Exception ex) { WeightDeviceLogger.Error("表头打开异常.", ex); throw ex; } return(rtn); }
/// <summary> /// 发送清零指令 /// </summary> public void SendQuit() { SendCmd(DTJL_CMD.SEND_CJTJL); WeightDeviceLogger.Debug("发送退出指令:" + DTJL_CMD.SEND_CJTJL); }
/// <summary> /// 发送清零指令 /// </summary> public void SendQL() { SendCmd(JTJL_CMD.SEND_QL); WeightDeviceLogger.Debug("发送清零指令:" + JTJL_CMD.SEND_QL); }
/// <summary> /// 停止数据处理 /// </summary> /// <returns></returns> public bool Stop() { _canRaiseWeightDataEvent = false; WeightDeviceLogger.Debug("停止表头数据处理。"); return(true); }
/// <summary> /// 开始数据处理 /// </summary> /// <returns></returns> public bool Start() { WeightDeviceLogger.Debug("启动表头数据处理。"); return(_canRaiseWeightDataEvent = true); }
/// <summary> /// 打开串口,并注册数据接收方法 /// </summary> /// <returns></returns> public bool Open() { var rtn = false; if (_curWeightCfg != null) { WeightDeviceLogger.Debug( string.Format("设置串口参数。ComPort={0},Baudrate={1},DataBits={2}, Parity={3},StopSize={4}", _curWeightCfg.ComPort, _curWeightCfg.Baudrate, _curWeightCfg.ByteSize, _curWeightCfg.Parity, _curWeightCfg.StopSize)); _spCom = new SerialPort(_curWeightCfg.ComPort, int.Parse(_curWeightCfg.Baudrate)) { DataBits = _curWeightCfg.ByteSize, ReadBufferSize = 100 }; //奇偶校验 if (_curWeightCfg.Parity == ParityType.Even) { _spCom.Parity = Parity.Odd; } else if (_curWeightCfg.Parity == ParityType.Odd) { _spCom.Parity = Parity.Even; } else { _spCom.Parity = Parity.None; } //停止位 if (_curWeightCfg.StopSize == StopBitsType.One) { _spCom.StopBits = StopBits.One; } else if (_curWeightCfg.StopSize == StopBitsType.OnePointFive) { _spCom.StopBits = StopBits.OnePointFive; } else if (_curWeightCfg.StopSize == StopBitsType.Two) { _spCom.StopBits = StopBits.Two; } else { _spCom.StopBits = StopBits.None; } _spCom.DataReceived += _spCom_DataReceived; try { WeightDeviceLogger.Debug("表头打开串口。IsOpen=" + _spCom.IsOpen); _spCom.Open(); _canSendGetWeightCmd = true; if (_IsCommandMode) { //启动发送命令的线程 StartGetWeightThread(); if (_spCom.IsOpen) { //ThreadStart ts = ProcessWeight; //ThreadStart ts = ProcessWeightByModbus; //_threadWeight = new Thread(ts) //{ // IsBackground = true //}; //_threadWeight.Start(); //WeightDeviceLogger.Debug("modbus命令模式启动表头数据处理线程成功。"); _closeComPort = false; rtn = true; } } else { if (_spCom.IsOpen) { ThreadStart ts = ProcessWeight; _threadWeight = new Thread(ts) { IsBackground = true }; _threadWeight.Start(); WeightDeviceLogger.Debug("tf=0模式启动表头数据处理线程成功。"); _closeComPort = false; rtn = true; } } } catch (Exception ex) { WeightDeviceLogger.Error("打开表头失败。", ex); ShowErrorMsg(ErrorType.Error, "打开串口失败."); } } else { WeightDeviceLogger.Error("表头配置信息不存在。"); ShowErrorMsg(ErrorType.Error, "配置信息不存在."); } return(rtn); }
/// <summary> /// 提取重量数据 /// </summary> private void ProcessWeight() { const int dataLen = 12; var index = 0; while (true) { try { var tWeight = new byte[6]; //重量 var rawData = new byte[dataLen]; //原始数据 if (_comData.Count >= dataLen) { #region LeftToRight //index = _comData.IndexOf(Convert.ToByte(0X0D)) + 1; index = _comData.IndexOf(Convert.ToByte(0X03)) + 1; if (index == dataLen) { Array.Copy(_comData.ToArray(), rawData, index); Array.Copy(rawData, 2, tWeight, 0, 6); var weightTemp = Encoding.ASCII.GetString(tWeight); //获取+-符号 //if (BinaryHelper.IsOne(rawData[1], 1)) //{ // weightTemp = "-" + weightTemp.Trim(); //} if (rawData[1] == Convert.ToByte(0X2D))//"-"号 { weightTemp = "-" + weightTemp.Trim(); } //触发事件 if (!_canRaiseWeightDataEvent) { return; } WeightDeviceLogger.Debug(string.Format("触发重量事件。weightTemp={0},tag={1}", weightTemp, 0)); OnGetWeightData(weightTemp, ByteArrayToHexString(rawData)); if (int.Parse(weightTemp.Trim()) == 0) { Thread.Sleep(100); } } else if (index > 0) { var exceptData = new byte[index]; Array.Copy(_comData.ToArray(), exceptData, index); WeightDeviceLogger.Error("衡器异常数据。_comData=" + ByteArrayToHexString(_comData.ToArray())); Thread.Sleep(50); } #endregion } else { Thread.Sleep(50); } } catch (Exception ex) { WeightDeviceLogger.Error("数据线程处理内部异常,_comData=" + ByteArrayToHexString(_comData.ToArray()), ex); } finally { //跳过已处理的数据 if (index > 0) { lock (_comData) { _comData.RemoveRange(0, index); index = 0; } } } } }
//可能会出现多个数据的情况 private void ProcessWeightByModbus() { //接收的数据为13位 const int dataLen = 13; var index = 0; while (true) { try { var tWeight = new byte[6]; //重量 var rawData = new byte[dataLen]; //原始数据 if (_comData.Count >= dataLen) { #region LeftToRight //index = _comData.IndexOf(Convert.ToByte(0X0D)) + 1; index = _comData.IndexOf(Convert.ToByte(0X03)); //保证在一个完整的数据长度之内 if (index >= 1 && _comData.Count >= index + 12) { Array.Copy(_comData.ToArray(), index - 1, rawData, 0, 13); //从index=4 开始取6位位重量 Array.Copy(rawData, 4, tWeight, 0, 6); var weightTemp = Encoding.ASCII.GetString(tWeight); //获取+-符号 //if (BinaryHelper.IsOne(rawData[1], 1)) //{ // weightTemp = "-" + weightTemp.Trim(); //} if (rawData[3] == Convert.ToByte(0X2D))//"-"号 { weightTemp = "-" + weightTemp.Trim(); } //触发事件 if (!_canRaiseWeightDataEvent) { return; } WeightDeviceLogger.Debug(string.Format("触发重量事件。weightTemp={0},tag={1}", weightTemp, 0)); OnGetWeightData(weightTemp, ByteArrayToHexString(rawData)); if (int.Parse(weightTemp.Trim()) == 0) { Thread.Sleep(100); } } else { var exceptData = new byte[index]; Array.Copy(_comData.ToArray(), exceptData, index); WeightDeviceLogger.Error("衡器异常数据1。_comData=" + ByteArrayToHexString(_comData.ToArray())); Thread.Sleep(50); } #endregion } else { Thread.Sleep(250); } } catch (Exception ex) { WeightDeviceLogger.Error("命令数据线程处理内部异常2,_comData=" + ByteArrayToHexString(_comData.ToArray()) + ex.ToString()); } finally { //跳过已处理的数据 if (_comData.Count > 0) { if (_comData.Count < 13) { lock (_comData) { WeightDeviceLogger.Error("命令数据线程处理内部数据个数小于13,_comData个数" + _comData.Count + ",_comData=" + ByteArrayToHexString(_comData.ToArray())); _comData.RemoveRange(0, _comData.Count); } } else { if (_comData.Count >= index + 12) { lock (_comData) { _comData.RemoveRange(0, index + 12); } } else { lock (_comData) { WeightDeviceLogger.Error("命令数据线程处理内部数据个数大于13但数据片段不完整,_comData=" + ByteArrayToHexString(_comData.ToArray())); _comData.RemoveRange(0, _comData.Count); } } } } } } }