private void onNetWeightReceive(CalcStableResult args) { if (this.NetWeightReceiveEventHandler != null) { NetWeightReceiveEventHandler.Invoke(sender: null, e: args); } }
private void dataReceived() { string content = readSerialPortData(); // System.Diagnostics.Debug.WriteLine("dataReceived : {0}".FormatWith(content)); string valueStr = this.fixData(content); // 根据电子秤型号处理数据 // System.Diagnostics.Debug.WriteLine("valueStr : {0}".FormatWith(valueStr)); #region 测试错误信息显示 //mIsTestShowError = true; //if (mIsTestShowError == true) //{ // int temp = rand.Next(100); // if (temp % 10 == 0) // { // valueStr = valueStr + "mIsTestShowError ** mIsTestShowError"; // } //} #endregion decimal inputValue = 0M; if (decimal.TryParse(valueStr, out inputValue) == true) { CalcStableResult r = calcStable(inputValue); // 计算净重, 并判断是否稳定 // System.Diagnostics.Debug.WriteLine(r.GetConsoleInfo()); onNetWeightReceive(r); } else { CalcStableResult r = new CalcStableResult() { IsComplete = false, ExceptionInfo = "valueStr的值无法转换为 decimal。\r\ncontent :{0}\r\nvalueStr :{1}\r\n".FormatWith(content, valueStr), EntryTime = DateTime.Now }; onNetWeightReceive(r); } }
private CalcStableResult calcStable(decimal inputValue) { decimal finalValue = inputValue - mGrossWeight; CalcStableResult r = new CalcStableResult(); r.IsComplete = true; r.EntryTime = DateTime.Now; r.IsStable = false; r.OriginWeight = inputValue; r.GrossWeight = mGrossWeight; r.NetWeight = finalValue; r.UnitOfWeight = mUnitOfWeight; if (finalValue <= 0) { System.Diagnostics.Debug.WriteLine("由于净重值[{0}]小于0, 清空Buffer。".FormatWith(finalValue, mMinWeight)); mBuffer.Clear(); return(r); } if (finalValue > 0 && finalValue < this.mMinWeight) { System.Diagnostics.Debug.WriteLine("由于净重值[{0}]小于最小值[{1}], 清空Buffer。".FormatWith(finalValue, mMinWeight)); mBuffer.Clear(); return(r); } // 使用缓存设定的小数位值处理当前重量 mBuffer.Add(decimal.Round(finalValue, mRoundLenght)); if (mBuffer.Count > this.mCalcCount) { mBuffer.RemoveAt(0); } // 使用用于比较的小数位数处理所有缓存数据,排序并取出现次数最多的值 var query = mBuffer.Select(i => Math.Round(i, mBufferRoundLenght)); ValueOccur matchMaxOccur = (from p in query group p by p into g select new ValueOccur { Value = g.Key, Count = g.Count() }) .OrderByDescending(i => i.Count) .FirstOrDefault() ; if (matchMaxOccur != null && Math.Abs(finalValue - matchMaxOccur.Value) <= this.mFloatValue && matchMaxOccur.Count >= this.mStableCount && finalValue >= mMinWeight && finalValue <= mMaxWeight ) { r.IsStable = true; } return(r); }