工具表定模块 使用科学计数法

This commit is contained in:
XingCheng3
2026-05-12 13:28:37 +08:00
parent 36a4084d3a
commit 08b0d4e5e3
9 changed files with 261 additions and 67 deletions

View File

@@ -0,0 +1,131 @@
using DynamicExpresso;
using System;
using System.Collections.Generic;
using System.Globalization;
namespace MesWork
{
/// <summary>
/// 重量标定公式计算工具。
/// </summary>
public static class WeightCalibrationHelper
{
private class CalibrationCache
{
public string ToolName;
public string CalibrationValue;
public string Formula;
public string Description;
public DateTime LoadedAt;
}
private static readonly object CacheLock = new object();
private static readonly Dictionary<string, CalibrationCache> Cache = new Dictionary<string, CalibrationCache>(StringComparer.OrdinalIgnoreCase);
private static readonly TimeSpan CacheLife = TimeSpan.FromSeconds(3);
public static bool Apply(string opName, decimal rawWeight, out decimal calibratedWeight, out string formula, out string message)
{
calibratedWeight = rawWeight;
formula = "x";
message = "";
if (!TryGetConfig(opName, out CalibrationCache config, out string queryMsg))
{
message = string.IsNullOrWhiteSpace(queryMsg) ? "未找到工具标定配置" : queryMsg;
return false;
}
formula = NormalizeFormula(config.Formula);
return TryEvaluateFormula(formula, rawWeight, out calibratedWeight, out message);
}
public static void ClearCache()
{
lock (CacheLock)
{
Cache.Clear();
}
}
public static bool ValidateFormula(string formula, out string message)
{
decimal _;
return TryEvaluateFormula(NormalizeFormula(formula), 1M, out _, out message);
}
private static string NormalizeFormula(string formula)
{
return string.IsNullOrWhiteSpace(formula) ? "" : formula.Trim();
}
private static bool TryEvaluateFormula(string formula, decimal xValue, out decimal result, out string message)
{
result = xValue;
message = "";
if (string.IsNullOrWhiteSpace(formula))
{
message = "计算公式不能为空,至少填写 x";
return false;
}
try
{
var interpreter = new Interpreter();
interpreter.Reference(typeof(Math));
interpreter.SetVariable("x", xValue);
interpreter.SetVariable("X", xValue);
object value = interpreter.Eval(formula);
if (value == null)
{
message = "计算公式未返回数值";
return false;
}
result = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
return true;
}
catch (Exception err)
{
message = $"计算公式错误:{err.Message}";
return false;
}
}
private static bool TryGetConfig(string opName, out CalibrationCache config, out string message)
{
config = null;
message = "";
string key = string.IsNullOrWhiteSpace(opName) ? "" : opName.Trim();
lock (CacheLock)
{
if (Cache.TryGetValue(key, out config) && DateTime.Now - config.LoadedAt < CacheLife)
{
return true;
}
}
if (!B_DB_Opera.QueryToolCalibration(key, out string toolName, out string calibrationValue, out string formula, out string description, out message))
{
return false;
}
config = new CalibrationCache
{
ToolName = toolName,
CalibrationValue = calibrationValue,
Formula = formula,
Description = description,
LoadedAt = DateTime.Now
};
lock (CacheLock)
{
Cache[key] = config;
}
return true;
}
}
}

View File

@@ -233,9 +233,6 @@ namespace MesWork
}
// ====================================================================
// 称重业务数据库方法(调用存储过程,统一 result/msg 返回格式)
// ====================================================================
/// <summary>
/// 根据订货号匹配工件管理规则,查询机型参数(加油量/抽油量/密度/残油量上下限)
@@ -263,6 +260,52 @@ namespace MesWork
return false;
}
/// <summary>
/// 查询指定工位的工具标定配置。
/// </summary>
public static bool QueryToolCalibration(string opName, out string toolName, out string calibrationValue, out string formula, out string description, out string msg)
{
toolName = "";
calibrationValue = "";
formula = "";
description = "";
msg = "";
try
{
using (var conn = new SqlConnection(MesWorkForm.ConnectionString))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = @"
SELECT TOP 1 [工具名称], [重量标定], [计算公式], [说明]
FROM [工具管理]
WHERE [工位号] = @工位号
ORDER BY [ID]";
cmd.Parameters.Add(new SqlParameter("@工位号", opName ?? ""));
conn.Open();
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
{
msg = $"未找到[{opName}]工具标定配置";
return false;
}
toolName = reader["工具名称"]?.ToString() ?? "";
calibrationValue = reader["重量标定"]?.ToString() ?? "";
formula = reader["计算公式"]?.ToString() ?? "";
description = reader["说明"]?.ToString() ?? "";
return true;
}
}
}
catch (Exception err)
{
msg = $"查询[{opName}]工具标定配置失败:{err.Message}";
return false;
}
}
/// <summary>
/// 插入称重记录
/// </summary>

View File

@@ -24,6 +24,7 @@ namespace MesWork
public decimal? StableWeight;
public int? StableStartSeq;
public int? StableEndSeq;
public DateTime LastCalibrationErrorLogTime;
}
private static readonly ConcurrentDictionary<string, CurveCollectorState> _curveCollectors
@@ -76,7 +77,7 @@ namespace MesWork
}
/// <summary>
/// 采集线程200ms读取一次实时重量缓存到内存,保存时一次性写库。
/// 采集线程200ms读取一次实时重量先按工具标定公式计算,再缓存到内存,保存时一次性写库。
/// </summary>
private void CurveCollector_Work(CurveCollectorState state)
{
@@ -84,7 +85,17 @@ namespace MesWork
{
try
{
decimal weight = Convert.ToDecimal(ReadPLC(100220, state.OpName)); // 实时重量点位
decimal rawWeight = Convert.ToDecimal(ReadPLC(100220, state.OpName)); // 实时重量点位
if (!WeightCalibrationHelper.Apply(state.OpName, rawWeight, out decimal weight, out _, out string msg))
{
if ((DateTime.Now - state.LastCalibrationErrorLogTime).TotalSeconds >= 5)
{
state.LastCalibrationErrorLogTime = DateTime.Now;
WeighingPage?.AppendLog($"[{state.OpName}] 曲线采样标定失败:{msg}");
}
Thread.Sleep(CurveCollectorSampleIntervalMs);
continue;
}
lock (state.BufferLock)
{
state.Buffer.Add(new CurveSamplePoint
@@ -139,7 +150,7 @@ namespace MesWork
}
/// <summary>
/// 优先用曲线点计算稳定重量失败时调用方继续使用PLC锁定重量。
/// 优先用已标定曲线点计算稳定重量失败时调用方继续使用PLC锁定重量。
/// </summary>
private bool CurveCollector_TryGetStableWeight(string opName, out decimal weight, out int pointCount, out string msg)
{

View File

@@ -177,7 +177,7 @@ namespace MesWork
int stIdx = WeighingPage?.GetStationIndex(opName) ?? 1;
if (!B_DB_Opera.QueryWorkpieceByOrderNo(orderNo, out string matchedModelNo, out decimal addOilQty, out decimal extractOilQty, out decimal density,
out decimal residualOilUpperLimit, out decimal residualOilLowerLimit))
out decimal residualOilUpperLimit, out decimal residualOilLowerLimit)) // 根据订货号 查询基本参数
{
WritePLC_IF(112, opName, 3); // 报警代码=3机型错误
B_DB_Opera.SaveLog_Response($"【{opName}】工件管理中未找到订货号[{orderNo}]的匹配规则,发动机={engineNo}", AID);
@@ -252,18 +252,26 @@ namespace MesWork
engineNo = parsedProductNo;
}
if (CurveCollector_TryGetStableWeight(opName, out decimal curveWeight, out int curvePointCount, out string curveMsg))
{
weight = curveWeight; // 优先使用曲线稳定段计算重量
B_DB_Opera.SaveLog_Response($"【{opName}】曲线重量={curveWeight:F3}kgPLC重量={plcWeight:F3}kg差值={(curveWeight - plcWeight):F3}kg点数={curvePointCount}", AID);
}
else
{
B_DB_Opera.SaveLog_Response($"【{opName}】曲线重量不可用使用PLC锁定重量={plcWeight:F3}kg原因={curveMsg}", AID);
}
long curveWeighingRecordId = 0;
B_DB_Opera.UpdateStationComplete(engineNo, opName, weight); // 过站记录保存最终采用重量
if (CurveCollector_TryGetStableWeight(opName, out decimal curveWeight, out int curvePointCount, out string curveMsg))
{
weight = curveWeight; // 曲线采样点已按工具标定公式处理,稳定重量不再二次标定
B_DB_Opera.SaveLog_Response($"【{opName}】标定曲线重量={curveWeight:F3}kgPLC锁定重量={plcWeight:F3}kg点数={curvePointCount}", AID);
}
else
{
B_DB_Opera.SaveLog_Response($"【{opName}】曲线重量不可用使用PLC锁定重量={plcWeight:F3}kg原因={curveMsg}", AID);
decimal rawWeight = plcWeight;
if (!WeightCalibrationHelper.Apply(opName, rawWeight, out decimal calibratedWeight, out string calibrationFormula, out string calibrationMsg))
{
throw new Exception($"工具标定公式处理失败:{calibrationMsg}");
}
weight = calibratedWeight;
B_DB_Opera.SaveLog_Response($"【{opName}】PLC锁定重量标定原始重量={rawWeight:F3}kg公式={calibrationFormula},标定后={weight:F3}kg", AID);
WeighingPage?.AppendLog($"[{opName}] PLC锁定重量标定原始={rawWeight:F3}kg公式={calibrationFormula},结果={weight:F3}kg");
}
long curveWeighingRecordId = 0;
B_DB_Opera.UpdateStationComplete(engineNo, opName, weight); // 过站记录保存最终采用重量
string weighType = GetWeighingType(opName);
decimal oilReleaseQty = 0;
decimal residualOilQty = 0;

View File

@@ -219,18 +219,18 @@ namespace MesWork
this.lbl_NavWorkpiece.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.lbl_NavWorkpiece.Cursor = System.Windows.Forms.Cursors.Hand;
this.pnl_NavWorkpiece.Controls.Add(this.lbl_NavWorkpiece);
// ── 导航项:工具管理 ──
// ── 导航项:工具标定 ──
this.pnl_NavTool.BackColor = System.Drawing.Color.FromArgb(30, 58, 95);
this.pnl_NavTool.Cursor = System.Windows.Forms.Cursors.Hand;
this.pnl_NavTool.Location = new System.Drawing.Point(1, 206);
this.pnl_NavTool.Size = new System.Drawing.Size(78, 64);
this.pnl_NavTool.Name = "pnl_NavTool";
this.pnl_NavTool.Tag = "🔧\n工具管理";
this.pnl_NavTool.Tag = "🔧\n工具标定";
this.lbl_NavTool.AutoSize = false;
this.lbl_NavTool.Dock = System.Windows.Forms.DockStyle.Fill;
this.lbl_NavTool.Font = new System.Drawing.Font("微软雅黑", 9F);
this.lbl_NavTool.ForeColor = System.Drawing.Color.FromArgb(148, 163, 184);
this.lbl_NavTool.Text = "🔧\n工具管理";
this.lbl_NavTool.Text = "🔧\n工具标定";
this.lbl_NavTool.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.lbl_NavTool.Cursor = System.Windows.Forms.Cursors.Hand;
this.pnl_NavTool.Controls.Add(this.lbl_NavTool);

View File

@@ -57,7 +57,7 @@ namespace MesWork.Pages
this.txt_Search.Name = "txt_Search";
this.txt_Search.Size = new System.Drawing.Size(280, 27);
this.txt_Search.TabIndex = 0;
this.txt_Search.Text = "输入工具名称搜索...";
this.txt_Search.Text = "输入工位号或工具名称搜索...";
this.txt_Search.GotFocus += new System.EventHandler(this.txt_Search_GotFocus);
this.txt_Search.LostFocus += new System.EventHandler(this.txt_Search_LostFocus);
this.txt_Search.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txt_Search_KeyDown);

View File

@@ -7,12 +7,12 @@ using System.Windows.Forms;
namespace MesWork.Pages
{
/// <summary>
/// 工具管理页面 — 传感器/工具校准和使用管理
/// 对应存储过程工具管理_分页查询、工具管理_新增、工具管理_修改、工具管理_删除
/// 工具标定页面 — 固定维护OP10/OP20重量标定公式。
/// 对应存储过程工具管理_分页查询、工具管理_编辑
/// </summary>
public partial class UC_ToolMgmt : UserControl
{
private const string SEARCH_HINT = "输入工具名称搜索...";
private const string SEARCH_HINT = "输入工位号或工具名称搜索...";
private PagerBar _pager;
public UC_ToolMgmt()
@@ -24,6 +24,9 @@ namespace MesWork.Pages
this.Controls.Remove(pnl_StatusBar);
this.Controls.Add(_pager);
this.Controls.SetChildIndex(_pager, this.Controls.Count - 2);
btn_Add.Visible = false;
btn_Delete.Visible = false;
btn_Edit.Location = btn_Delete.Location;
}
/// <summary>
@@ -34,14 +37,12 @@ namespace MesWork.Pages
dgv_Data.AutoGenerateColumns = false;
dgv_Data.Columns.Clear();
dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "ID", HeaderText = "ID", DataPropertyName = "ID", Visible = false });
dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "工具名称", HeaderText = "工具名称", DataPropertyName = "工具名称", FillWeight = 110 });
dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "说明", HeaderText = "说明", DataPropertyName = "说明", FillWeight = 120 });
dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "校准值", HeaderText = "校准值", DataPropertyName = "校准值", FillWeight = 70 });
dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "校准时间", HeaderText = "校准时间", DataPropertyName = "校准时间", FillWeight = 90 });
dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "使用次数", HeaderText = "使用次数", DataPropertyName = "使用次数", FillWeight = 60 });
dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "使用次数变更时间", HeaderText = "次数变更时间", DataPropertyName = "使用次数变更时间", FillWeight = 90 });
dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "创建时间", HeaderText = "创建时间", DataPropertyName = "创建时间", FillWeight = 90 });
dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "修改时间", HeaderText = "修改时间", DataPropertyName = "修改时间", FillWeight = 90 });
dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "工位号", HeaderText = "工位号", DataPropertyName = "工位号", FillWeight = 70 });
dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "工具名称", HeaderText = "工具名称", DataPropertyName = "工具名称", FillWeight = 120 });
dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "重量标定", HeaderText = "重量标定", DataPropertyName = "重量标定", FillWeight = 90 });
dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "计算公式", HeaderText = "计算公式", DataPropertyName = "计算公式", FillWeight = 150 });
dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "说明", HeaderText = "说明", DataPropertyName = "说明", FillWeight = 180 });
dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "修改时间", HeaderText = "修改时间", DataPropertyName = "修改时间", FillWeight = 100 });
}
public void LoadData(string keyword = "")
@@ -74,27 +75,13 @@ namespace MesWork.Pages
// ── 按钮事件 ──
private void btn_Search_Click(object sender, EventArgs e) { _pager.ResetPage(); LoadData(txt_Search.Text == SEARCH_HINT ? "" : txt_Search.Text.Trim()); }
private void btn_Add_Click(object sender, EventArgs e) => ShowEditDialog(null);
private void btn_Add_Click(object sender, EventArgs e) { }
private void btn_Edit_Click(object sender, EventArgs e)
{
if (dgv_Data.CurrentRow != null) ShowEditDialog(dgv_Data.CurrentRow);
else MessageBox.Show("请先选择一条记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void btn_Delete_Click(object sender, EventArgs e)
{
if (dgv_Data.CurrentRow == null) { MessageBox.Show("请先选择一条记录", "提示"); return; }
string name = dgv_Data.CurrentRow.Cells["工具名称"]?.Value?.ToString() ?? "";
if (MessageBox.Show($"确认删除工具「{name}」?", "确认删除", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
try
{
var parms = new SqlParameter[] { new SqlParameter("@ID", int.Parse(dgv_Data.CurrentRow.Cells["ID"]?.Value?.ToString() ?? "0")) };
SqlOperation.ExecuteStoredProcedure("工具管理_删除", parms, out string err);
LoadData();
}
catch (Exception ex) { MessageBox.Show($"删除失败:{ex.Message}"); }
}
}
private void btn_Delete_Click(object sender, EventArgs e) { }
private void btn_Refresh_Click(object sender, EventArgs e) { _pager.ResetPage(); LoadData(""); }
private void dgv_Data_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) btn_Edit_Click(sender, e); }
@@ -103,32 +90,41 @@ namespace MesWork.Pages
/// </summary>
private void ShowEditDialog(DataGridViewRow row)
{
bool isEdit = row != null;
using (var dlg = CrudHelper.CreateEditDialog(isEdit ? "修改工具" : "新增工具", 420, 380))
if (row == null) return;
using (var dlg = CrudHelper.CreateEditDialog("修改工具标定", 520, 360))
{
int y = 20;
var txtName = CrudHelper.AddTextField(dlg, "工具名称", ref y, isEdit ? row.Cells["工具名称"]?.Value?.ToString() : "");
var txtDesc = CrudHelper.AddTextField(dlg, "说明:", ref y, isEdit ? row.Cells["说明"]?.Value?.ToString() : "");
var txtCalVal = CrudHelper.AddTextField(dlg, "校准值:", ref y, isEdit ? row.Cells["校准值"]?.Value?.ToString() : "0");
var txtCalTime = CrudHelper.AddTextField(dlg, "校准时间", ref y, isEdit ? row.Cells["校准时间"]?.Value?.ToString() : DateTime.Now.ToString("yyyy-MM-dd"));
var txtUseCnt = CrudHelper.AddTextField(dlg, "使用次数", ref y, isEdit ? row.Cells["使用次数"]?.Value?.ToString() : "0");
var txtStation = CrudHelper.AddTextField(dlg, "工位号", ref y, row.Cells["工位号"]?.Value?.ToString(), inputWidth: 320);
txtStation.ReadOnly = true;
txtStation.BackColor = Color.FromArgb(245, 247, 250);
var txtName = CrudHelper.AddTextField(dlg, "工具名称", ref y, row.Cells["工具名称"]?.Value?.ToString(), inputWidth: 320);
var txtCalVal = CrudHelper.AddTextField(dlg, "重量标定", ref y, row.Cells["重量标定"]?.Value?.ToString(), inputWidth: 320);
var txtFormula = CrudHelper.AddTextField(dlg, "计算公式:", ref y, row.Cells["计算公式"]?.Value?.ToString(), inputWidth: 320);
var txtDesc = CrudHelper.AddTextField(dlg, "说明:", ref y, row.Cells["说明"]?.Value?.ToString(), inputWidth: 320);
CrudHelper.AddDialogButtons(dlg, ref y);
if (dlg.ShowDialog() == DialogResult.OK)
{
try
{
string sp = isEdit ? "工具管理_编辑" : "工具管理_增加";
if (!WeightCalibrationHelper.ValidateFormula(txtFormula.Text.Trim(), out string formulaMsg))
{
MessageBox.Show(formulaMsg, "公式错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
var pList = new System.Collections.Generic.List<SqlParameter>
{
new SqlParameter("@ID", int.Parse(row.Cells["ID"]?.Value?.ToString() ?? "0")),
new SqlParameter("@工位号", txtStation.Text.Trim()),
new SqlParameter("@工具名称", txtName.Text.Trim()),
new SqlParameter("@重量标定", txtCalVal.Text.Trim()),
new SqlParameter("@计算公式", txtFormula.Text.Trim()),
new SqlParameter("@说明", txtDesc.Text.Trim()),
new SqlParameter("@校准值", txtCalVal.Text.Trim()),
new SqlParameter("@校准时间", DateTime.Parse(txtCalTime.Text)),
new SqlParameter("@使用次数", int.Parse(txtUseCnt.Text))
};
if (isEdit) pList.Insert(0, new SqlParameter("@ID", int.Parse(row.Cells["ID"]?.Value?.ToString() ?? "0")));
SqlOperation.ExecuteStoredProcedure(sp, pList.ToArray(), out string err);
SqlOperation.ExecuteStoredProcedure("工具管理_编辑", pList.ToArray(), out string err);
WeightCalibrationHelper.ClearCache();
LoadData();
}
catch (Exception ex) { MessageBox.Show($"保存失败:{ex.Message}"); }
@@ -138,7 +134,7 @@ namespace MesWork.Pages
private void btn_Export_Click(object sender, EventArgs e)
{
CrudHelper.ExportToExcel("工具管理", "工具管理", () =>
CrudHelper.ExportToExcel("工具标定", "工具标定", () =>
{
string keyword = CrudHelper.GetSearchKeyword(txt_Search, SEARCH_HINT);
var (pageCountParam, itemCountParam) = PagerBar.CreateOutputParams();

View File

@@ -741,6 +741,10 @@ namespace MesWork.Pages
if (wv != null)
{
decimal weight = Convert.ToDecimal(wv);
if (WeightCalibrationHelper.Apply(opName, weight, out decimal calibratedWeight, out _, out _))
{
weight = calibratedWeight;
}
string newTxt = Convert.ToDouble(weight).ToString("F2");
if (lblWeight.Text != newTxt) lblWeight.Text = newTxt;
}

View File

@@ -165,8 +165,9 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Core\SqlOperation.cs" />
<Compile Include="Frm_Login.cs">
<Compile Include="Core\SqlOperation.cs" />
<Compile Include="Core\WeightCalibrationHelper.cs" />
<Compile Include="Frm_Login.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Frm_Login.Designer.cs">
@@ -363,4 +364,4 @@
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
</Project>