Files
2026-01-13 10:43:35 +08:00

1676 lines
68 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using BasicDemo;
using Modbus.Device;
using NModbus.Device;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using .Data;
using .Model;
using ;
namespace
{
public partial class PenetrationForm : UIForm
{
#region
private TcpClient _tcpClient => ModbusResourceManager.Instance.TcpClient;
private IModbusMaster _modbusMaster => ModbusResourceManager.Instance.ModbusMaster;
#endregion
SerialPort serialPort = null;
IModbusMaster master = null;
private bool _isSerialPortAvailable = false;
private CancellationTokenSource _cancellationTokenSource;
Function ma;
DataChange c = new DataChange();
private System.Windows.Forms.Timer _readtimer;
private readonly object _serialLock = new object();
private System.Windows.Forms.Timer _powerMeterTimer;
private readonly SemaphoreSlim _asyncLock = new SemaphoreSlim(1, 1);
ConductivityRepository conductivityRepository;
public bool RunStatus = false;
public PenetrationForm()
{
InitializeComponent();
conductivityRepository = new ConductivityRepository();
InitComboBoxPattern();
InitComboBox2Pattern();
InitTimer();
InitTimer2();
}
private System.Windows.Forms.Timer InitTimer()
{
var timer = new System.Windows.Forms.Timer()
{
Interval = 200,
};
timer.Tick += async (s, e) =>
{
if (_modbusMaster != null)
{
try
{
await ReadDataAsync();
}
catch { }
}
};
return timer;
}
private System.Windows.Forms.Timer InitTimer2()
{
var timer = new System.Windows.Forms.Timer()
{
Interval = 300,
};
timer.Tick += async (s, e) =>
{
if (_modbusMaster != null)
{
try
{
WriteDataAsync();
}
catch { }
}
};
timer.Start();
return timer;
}
private void WriteDataAsync()
{
try
{
if (_modbusMaster == null || _tcpClient == null || !_tcpClient.Connected)
{
return;
}
float value = float.Parse(uiLabel23.Text);
_modbusMaster.WriteMultipleRegistersAsync(1, 74, c.SplitFloatToUShortArray((float)value));
//});
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
//ShowError($"读取数据失败:{ex.Message}");
}
}
private async System.Threading.Tasks.Task ReadDataAsync()
{
try
{
if (this.IsDisposed || !this.IsHandleCreated)
{
return;
}
if (_modbusMaster == null || _tcpClient == null || !_tcpClient.Connected)
{
return;
}
var tasks = new List<Task>
{
ReadFloatAsync(60,1,uiLabel10,"F0",""),//测试项
ReadFloatAsync(68,2,uiLabel7,"F1",""),//点火时间
ReadFloatAsync(54,2,uiLabel8,"F1",""),//余焰时间
ReadFloatAsync(58,2,uiLabel12,"F1",""),//余辉时间
ReadFloatAsync(72,2,uiLabel2,"F1",""),//背部穿透时间
ReadFloatAsync(144,1,uiLabel25,"F1",""),//总测试时间
ReadFloatAsync(1334,2,uiLabel48,"F1",""),//试验舱温度
ReadFloatAsync(1384,2,uiLabel38,"F1",""),//试验舱湿度
ReadFloatAsync(102,2,uiLabel33,"F1",""),//试验舱氧浓度
ReadLightStatusAsync(),//指示灯
ReadtimeAsync(),//实时时间
ReadStartStatusAsync()//状态
};
await Task.WhenAll(tasks);
}
catch (Exception ex)
{
//ShowError($"读取数据失败:{ex.Message}");
MessageBox.Show(ex.Message);
}
}
private async Task ReadFloatAsync(int address, int length, Label control, string format, string unit)
{
if (control == null) return;
try
{
// 简化连接检查
if (_tcpClient == null || _modbusMaster == null)
{
return;
}
// 检查TCP连接状态简化版
bool isConnected = false;
try
{
isConnected = _tcpClient != null && _tcpClient.Connected;
}
catch
{
isConnected = false;
}
if (!isConnected)
{
// 不再输出调试信息,避免频繁输出
return;
}
var modbusMaster = _modbusMaster;
var result = modbusMaster.ReadHoldingRegistersAsync(1, (ushort)address, (ushort)length).Result;
ushort[] registers = result;
if (registers == null || registers.Length == 0) return;
string text;
if (registers.Length >= 2 && length >= 2)
{
float value = c.UshortToFloat(registers[1], registers[0]);
text = $"{value.ToString(format, CultureInfo.InvariantCulture)}{unit}";
}
else if (registers.Length >= 1)
{
int value = registers[0];
text = $"{value.ToString(format, CultureInfo.InvariantCulture)}{unit}";
}
else
{
return;
}
UpdateControlText(control, text);
}
catch (Exception ex) when (ex is SocketException ||
ex is ObjectDisposedException ||
ex is InvalidOperationException ||
ex is TimeoutException)
{
// 静默处理异常
Debug.WriteLine($"地址{address}: {ex.GetType().Name}");
}
catch (Exception ex)
{
// 其他异常也静默处理避免干扰UI
Debug.WriteLine($"地址{address}: {ex.Message}");
}
}
private void UpdateControlText(Label control, string text)
{
if (control.IsDisposed) return;
if (control.InvokeRequired)
{
try
{
control.BeginInvoke(new Action(() =>
{
if (!control.IsDisposed)
control.Text = text;
}));
}
catch (ObjectDisposedException)
{
}
}
else
{
control.Text = text;
}
}
private async Task ReadLightStatusAsync()
{
try
{
// 修复1移除 ? 操作符,先检查是否为 null
if (_modbusMaster == null) return;
bool[] registers1 = await _modbusMaster.ReadCoilsAsync(1, 4, 1);
if (registers1 != null && registers1.Length >= 1)
{
bool value1 = registers1[0];
// 修复2添加控件句柄检查
if (uiLight1.IsDisposed || !uiLight1.IsHandleCreated)
return;
if (uiLight1.InvokeRequired)
{
uiLight1.Invoke(new Action(() =>
{
// 再次检查,防止回调执行时控件已被销毁
if (!uiLight1.IsDisposed && uiLight1.IsHandleCreated)
uiLight1.State = value1 ? UILightState.On : UILightState.Off;
}));
}
else
{
uiLight1.State = value1 ? UILightState.On : UILightState.Off;
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"读取状态1失败: {ex.Message}");
}
try
{
// 修复3添加 null 检查
if (_modbusMaster == null) return;
bool[] registers2 = await _modbusMaster.ReadCoilsAsync(1, 10, 1);//是否复位
if (registers2 != null && registers2.Length >= 1)
{
bool value2 = registers2[0];
// 修复4添加控件句柄检查
if (uiLight3.IsDisposed || !uiLight3.IsHandleCreated)
return;
if (uiLight3.InvokeRequired)
{
uiLight3.Invoke(new Action(() =>
{
// 再次检查,防止回调执行时控件已被销毁
if (!uiLight3.IsDisposed && uiLight3.IsHandleCreated)
uiLight3.State = value2 ? UILightState.On : UILightState.Off;
}));
}
else
{
uiLight3.State = value2 ? UILightState.On : UILightState.Off;
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"读取状态3失败: {ex.Message}");
}
}
private bool _lastRunStatus = false;
private bool _isReported = false;
private async Task ReadStartStatusAsync()
{
try
{
bool[] registers3 = await _modbusMaster?.ReadCoilsAsync(1, 81, 1);
if (registers3 != null && registers3.Length >= 1)
{
bool currentRunStatus = registers3[0];
this.Invoke(new Action(() =>
{
uiLabel31.Text = currentRunStatus ? "运行中" : "空闲中";
}));
// ========== 关键修改1移除重复的插入逻辑只保留一段 ==========
// 仅在「运行→停止」且未上报过的情况下执行一次插入
if (_lastRunStatus && !currentRunStatus && !_isReported)
{
// 添加延迟确保数据稳定
//await Task.Delay(500);
//await Task.Delay(500);
// 加锁防止异步并发重复执行
await _asyncLock.WaitAsync();
try
{
// 二次校验,防止锁等待期间状态已变更
if (!_isReported)
{
var model = await InsertReportAsync();
if (model != null && !string.IsNullOrEmpty(model.Id2))
{
conductivityRepository.InsertReportItems(model);
_isReported = true; // 标记已上报
Debug.WriteLine($"报表插入成功:样品{model.sampleType2}, 分类{model.result2}");
}
}
}
finally
{
_asyncLock.Release(); // 释放锁
}
}
_lastRunStatus = currentRunStatus;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_readtimer?.Stop();
Debug.WriteLine($"读取状态失败: {ex.Message}");
}
//finally { _asyncLock.Release(); }
}
public async Task<bool[]> ReadModbusCoilAsync(ushort registerAddress, ushort readCount)
{
if (_modbusMaster == null) return null;
return await Task.Run(async () =>
{
return await _modbusMaster.ReadCoilsAsync(1, registerAddress, readCount);
});
}
List<PenetrationModel> reportList = new List<PenetrationModel>();
//private string classify;
//private float temperature;
//private float yh;
//private float yy;
//private bool isfire;
//private double costtime;
//private float penetime;
private bool _isCurrentRecordAdded = false;//重复添加标记
private async Task<PenetrationModel> InsertReportAsync()
{
if (_isReported) return new PenetrationModel();
if (!_isReported)
{
var report = new PenetrationModel();
if (uiLabel10.Text == null) return report;
var sampleId = uiLabel10.Text.Trim();
if (string.IsNullOrEmpty(sampleId)) return report;
// 解析样品ID
if (!int.TryParse(sampleId, out int sampleIndex) || sampleIndex < 1 || sampleIndex > 5)
{
Debug.WriteLine($"无效的样品ID: {sampleId}");
return report;
}
int coilBaseAddress = 159 + sampleIndex; // 160,161,162,163,164
int fireCoilAddress = 200 + sampleIndex; // 201,202,203,204,205
int timeRegAddress = 168 + sampleIndex * 2; // 170,172,174,176,178
int tempRegAddress = 108 + sampleIndex * 2; // 110,112,114,116,118
// 读取分类线圈
bool[] classificationResults = new bool[4];
classificationResults[0] = await ReadCoilWithCheckAsync(coilBaseAddress); // P4
classificationResults[1] = await ReadCoilWithCheckAsync(coilBaseAddress + 10); // P3
classificationResults[2] = await ReadCoilWithCheckAsync(coilBaseAddress + 20); // P2
classificationResults[3] = await ReadCoilWithCheckAsync(coilBaseAddress + 30); // P1
// 确定分类
string classify = null;
int classificationIndex = -1;
for (int i = 0; i < classificationResults.Length; i++)
{
if (classificationResults[i])
{
classify = $"P{4 - i}"; // P4, P3, P2, P1
classificationIndex = i;
break;
}
}
if (classify == null)
{
Debug.WriteLine("未检测到有效分类");
return report;
}
float yh = 0, yy = 0, penetime = 0, temperature = 0;
ushort costtime = 0;
bool isfire = false;
//ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
//if (yhlocation != null && yhlocation.Length >= 4)
//{
//yy = c.UshortToFloat(yhlocation[1], yhlocation[0]);
//yh = c.UshortToFloat(yhlocation[3], yhlocation[2]);
//}
yh = float.Parse(uiLabel12.Text);
yy = float.Parse(uiLabel8.Text);
//yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);
bool[] fire = await ReadModbusCoilAsync((ushort)fireCoilAddress, 1);
isfire = fire != null && fire.Length > 0 && fire[0];
ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, (ushort)timeRegAddress, 2);
if (time != null && time.Length > 0)
{
costtime = time[0];
}
//ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 1);
//if (petime != null )
//{
penetime = float.Parse(uiLabel2.Text);
//}
// 如果是P1分类读取温度
if (classificationIndex == 3) // P1是数组的第3个元素
{
ushort[] tem = _modbusMaster?.ReadHoldingRegisters(1, (ushort)tempRegAddress, 2);
if (tem != null && tem.Length >= 2)
{
temperature = c.UshortToFloat(tem[1], tem[0]);
}
}
try
{
string selectedO2Text = uiComboBox1.Text;
string id = uiLabel10.Text;
var model = new PenetrationModel
{
sampleType2 = sampleIndex,
Id2 = id,
O22 = selectedO2Text,
result2 = classify,
temperature2 = temperature,
yuhui2 = yh,
yuyan2 = yy,
Isfire = isfire,
costTime2 = costtime,
penetime2 = penetime,
Testtime2 = DateTime.Now
};
reportList.Add(model);
report = model;
_isCurrentRecordAdded = true; // 标记为已添加,避免重复
await Task.Delay(100);
return model;
}
catch (Exception ex)
{
Debug.WriteLine($"报表插入失败: {ex.Message}");
return report;
}
}
else
{
_isCurrentRecordAdded = false;
return new PenetrationModel(); ;
}
}
//private async Task InsertReportAsync()
//{
// if (uiLabel10.Text != null && uiLabel10.Text.Trim() == "1")
// {
// bool[] value1 = await ReadModbusCoilAsync(160, 1);
// bool[] value2 = await ReadModbusCoilAsync(170, 1);
// bool[] value3 = await ReadModbusCoilAsync(180, 1);
// bool[] value4 = await ReadModbusCoilAsync(190, 1);
// if (value1 != null && value1.Length > 0 && value1[0])
// {
// classify = "P4";//分类
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(201, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 170, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// else if (value2 != null && value2.Length > 0 && value2[0])
// {
// classify = "P3";
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(201, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 170, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// else if (value3 != null && value3.Length > 0 && value3[0])
// {
// classify = "P2";
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(201, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 170, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// else if (value4 != null && value4.Length > 0 && value4[0])
// {
// classify = "P1";
// ushort[] tem = _modbusMaster?.ReadHoldingRegisters(1, 110, 2);
// temperature = c.UshortToFloat(tem[1], tem[0]);//背部温度
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(201, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 170, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// }
// if (uiLabel10.Text != null && uiLabel10.Text.Trim() == "2")
// {
// bool[] value5 = await ReadModbusCoilAsync(161, 1);
// bool[] value6 = await ReadModbusCoilAsync(171, 1);
// bool[] value7 = await ReadModbusCoilAsync(181, 1);
// bool[] value8 = await ReadModbusCoilAsync(191, 1);
// if (value5 != null && value5.Length > 0 && value5[0])
// {
// classify = "P4";//分类
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(202, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 172, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// else if (value6 != null && value6.Length > 0 && value6[0])
// {
// classify = "P3";//分类
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(202, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 172, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// else if (value7 != null && value7.Length > 0 && value7[0])
// {
// classify = "P2";//分类
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(202, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 172, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// else if (value8 != null && value8.Length > 0 && value8[0])
// {
// classify = "P1";
// ushort[] tem = _modbusMaster?.ReadHoldingRegisters(1, 112, 2);
// temperature = c.UshortToFloat(tem[1], tem[0]);//背部温度
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(202, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 172, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// }
// if (uiLabel10.Text != null && uiLabel10.Text.Trim() == "3")
// {
// bool[] value9 = await ReadModbusCoilAsync(162, 1);
// bool[] value10 = await ReadModbusCoilAsync(172, 1);
// bool[] value11 = await ReadModbusCoilAsync(182, 1);
// bool[] value12 = await ReadModbusCoilAsync(192, 1);
// if (value9 != null && value9.Length > 0 && value9[0])
// {
// classify = "P4";//分类
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(203, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 174, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// else if (value10 != null && value10.Length > 0 && value10[0])
// {
// classify = "P3";//分类
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(203, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 174, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// else if (value11 != null && value11.Length > 0 && value11[0])
// {
// classify = "P2";//分类
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(203, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 174, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// else if (value12 != null && value12.Length > 0 && value12[0])
// {
// classify = "P1";
// ushort[] tem = _modbusMaster?.ReadHoldingRegisters(1, 114, 2);
// temperature = c.UshortToFloat(tem[1], tem[0]);//背部温度
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(203, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 174, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// }
// if (uiLabel10.Text != null && uiLabel10.Text.Trim() == "4")
// {
// bool[] value13 = await ReadModbusCoilAsync(163, 1);
// bool[] value14 = await ReadModbusCoilAsync(173, 1);
// bool[] value15 = await ReadModbusCoilAsync(183, 1);
// bool[] value16 = await ReadModbusCoilAsync(193, 1);
// if (value13 != null && value13.Length > 0 && value13[0])
// {
// classify = "P4";//分类
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(204, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 176, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// else if (value14 != null && value14.Length > 0 && value14[0])
// {
// classify = "P3";//分类
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(204, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 176, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// else if (value15 != null && value15.Length > 0 && value15[0])
// {
// classify = "P2";//分类
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(204, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 176, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// else if (value16 != null && value16.Length > 0 && value16[0])
// {
// classify = "P1";
// ushort[] tem = _modbusMaster?.ReadHoldingRegisters(1, 116, 2);
// temperature = c.UshortToFloat(tem[1], tem[0]);//背部温度
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(204, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 176, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// }
// if (uiLabel10.Text != null && uiLabel10.Text.Trim() == "5")
// {
// bool[] value17 = await ReadModbusCoilAsync(164, 1);
// bool[] value18 = await ReadModbusCoilAsync(174, 1);
// bool[] value19 = await ReadModbusCoilAsync(184, 1);
// bool[] value20 = await ReadModbusCoilAsync(194, 1);
// if (value17 != null && value17.Length > 0 && value17[0])
// {
// classify = "P4";//分类
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(205, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 178, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// else if (value18 != null && value18.Length > 0 && value18[0])
// {
// classify = "P3";//分类
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(205, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 178, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// else if (value19 != null && value19.Length > 0 && value19[0])
// {
// classify = "P2";//分类
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(205, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 178, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// else if (value20 != null && value20.Length > 0 && value20[0])
// {
// classify = "P1";
// ushort[] tem = _modbusMaster?.ReadHoldingRegisters(1, 118, 2);
// temperature = c.UshortToFloat(tem[1], tem[0]);//背部温度
// ushort[] yhlocation = _modbusMaster?.ReadHoldingRegisters(1, 320, 4);
// if (yhlocation != null && yhlocation.Length >= 3)
// {
// yh = c.UshortToFloat(yhlocation[1], yhlocation[0]);//余焰
// yy = c.UshortToFloat(yhlocation[3], yhlocation[2]);//余辉
// }
// bool[] fire = await ReadModbusCoilAsync(205, 1);
// isfire = (fire != null && fire.Length > 0 && fire[0]) ? true : false;//是否起火
// ushort[] time = _modbusMaster?.ReadHoldingRegisters(1, 178, 2);
// costtime = time[0];//总测试
// ushort[] petime = _modbusMaster?.ReadHoldingRegisters(1, 72, 2);
// penetime = c.UshortToFloat(petime[1], petime[0]);//穿透
// }
// }
// try
// {
// string selectedO2Text = uiComboBox1.Text;
// reportList.Add(new PenetrationModel
// {
// sampleType2 = uiLabel10.Text.Contains("1") ? 1
// : uiLabel10.Text.Contains("2") ? 2
// : uiLabel10.Text.Contains("3") ? 3
// : uiLabel10.Text.Contains("4") ? 4
// : uiLabel10.Text.Contains("5") ? 5 : 0,
// O22 = selectedO2Text,
// result2 = classify,
// temperature2 = temperature,
// yuhui2 = yh,
// yuyan2 = yy,
// Isfire = isfire,
// costTime2 = costtime,
// penetime2 = penetime
// });
// await Task.Delay(100);
// }
// catch (Exception ex)
// {
// Debug.WriteLine($"报表插入失败: {ex.Message}");
// }
//}
private async Task<bool> ReadCoilWithCheckAsync(int address)
{
var result = await ReadModbusCoilAsync((ushort)address, 1);
return result != null && result.Length > 0 && result[0];
}
private async Task ReadtimeAsync()
{
try
{
string currentTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
if (uiLabel25.IsDisposed || !uiLabel25.IsHandleCreated)
return;
if (uiLabel29.InvokeRequired)
{
uiLabel29.Invoke(new Action(() =>
{
uiLabel29.Text = currentTime;
}));
}
else
{
uiLabel29.Text = currentTime;
}
// 等待1秒再更新异步等待不阻塞UI线程
await Task.Delay(1000);
}
catch (Exception ex)
{
uiLabel29.Text = $"错误:{ex.Message}";
}
}
private void InitComboBoxPattern()
{
// 清空原有选项(可选,避免重复添加)
//Combox_pattern.Items.Clear();
// 定义需要添加的选项数组
string[] options = {
"环境空气 (21%)",
"富氧环境 (60%)",
"富氧环境 (98%)",
"无氧环境/灭火 (0%)"
};
uiComboBox1.Items.AddRange(options);
uiComboBox1.SelectedIndex = 0;
}
private void PenetrationForm_Load(object sender, EventArgs e)
{
string plcIp = "192.168.1.10";
//string plcIp = "127.0.0.1";
bool initSuccess = Data.ModbusResourceManager.Instance.Init(plcIp, 502);
if (!initSuccess)
{
MessageBox.Show("连接Modbus服务器失败", "错误");
this.Close();
return;
}
// 检查连接状态
if (_tcpClient == null || !_tcpClient.Connected)
{
MessageBox.Show("Modbus连接异常", "错误");
this.Close();
return;
}
ma = new Function(_modbusMaster);
this.comkou.DataSource = SerialPort.GetPortNames();
_readtimer = InitTimer();
if (_modbusMaster != null)
{
_readtimer.Start();
}
this.FormClosed += (s, args) =>
{
// 当子窗体关闭时,显示主窗体
Application.OpenForms["MainForm"]?.Show();
};
}
private void PenetrationForm_FormClosed(object sender, FormClosedEventArgs e)
{
// 停止功率计定时器
if (_powerMeterTimer != null)
{
_powerMeterTimer.Stop();
_powerMeterTimer.Dispose();
}
// 断开功率计连接
if (_isSerialPortAvailable && serialPort != null && serialPort.IsOpen)
{
Disconnect();
}
// 显示主窗体
foreach (Form form in Application.OpenForms)
{
if (form.Name == "MainForm" || form.Text.Contains("主界面"))
{
form.Show();
form.Activate();
break;
}
}
}
private void uiButton7_Click(object sender, EventArgs e)//帮助
{
string message = "请目测是否有余辉:\n有余辉请立即点击“余辉开始”按钮余辉时间开始计时\n余辉结束请立即点击“余辉结束”按钮余辉时间计时结束。";
Font font = new Font("Microsoft YaHei", 12, FontStyle.Regular);
// 创建一个自定义的消息框
TaskDialogPage page = new TaskDialogPage
{
Text = message,
Caption = "帮助",
SizeToContent = true
};
TaskDialog.ShowDialog(this, page);
}
private void uiButton4_Click(object sender, EventArgs e)
{
ma?.BtnClickFunctionForNew(Function.ButtonType., 78);//余辉开始
}
private void uiButton5_Click(object sender, EventArgs e)
{
ma?.BtnClickFunctionForNew(Function.ButtonType., 34);//余辉结束
}
private void uiButton6_Click(object sender, EventArgs e)
{
ma?.BtnClickFunctionForNew(Function.ButtonType., 33);//实验结束
}
private void uiButton1_Click(object sender, EventArgs e)
{
ma?.BtnClickFunctionForNew(Function.ButtonType., 80);//开始测试
}
private void uiButton2_Click(object sender, EventArgs e)
{
ma?.BtnClickFunctionForNew(Function.ButtonType., 42);//停止测试
}
private void uiButton3_Click(object sender, EventArgs e)
{
ma?.BtnClickFunctionForNew(Function.ButtonType., 99);//灭火
}
private void uiComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ushort selectedIndex = ushort.Parse(uiComboBox1.SelectedIndex.ToString());
_modbusMaster?.WriteSingleRegister(1, 10, selectedIndex);//下拉框
}
private void InitComboBox2Pattern()
{
// 清空原有选项(可选,避免重复添加)
//Combox_pattern.Items.Clear();
// 定义需要添加的选项数组
string[] options = {
"样品1",
"样品2",
"样品3",
"样品4",
"样品5"
};
uiComboBox2.Items.AddRange(options);
}
#region
private string _serialBuffer = "";
private bool _waitingResponse = false;
//private void uiButton11_Click(object sender, EventArgs e)
//{
// if (this.connect.Text == "🔗 连接功率计")
// {
// _cancellationTokenSource = new CancellationTokenSource();
// lock (_serialLock)
// {
// try
// {
// serialPort = new SerialPort();
// serialPort.PortName = this.comkou.Text;
// serialPort.BaudRate = 19200;
// serialPort.DataBits = 8;
// serialPort.Parity = Parity.None;
// serialPort.StopBits = StopBits.One;
// serialPort.Open();
// master = ModbusSerialMaster.CreateRtu(serialPort);
// master.Transport.ReadTimeout = 1000; // 设置合理的超时时间
// master.Transport.WriteTimeout = 1000;
// _isSerialPortAvailable = true;
// //updateTimer.Start();
// this.connect.Text = "断开连接";
// toolStripStatusLabel1.Text = "功率计已连接";
// toolStripStatusLabel1.BackColor = Color.Lime;
// WriteToLog("串口连接成功");
// }
// catch (Exception ex)
// {
// MessageBox.Show($"串口连接失败:{ex.Message}");
// _isSerialPortAvailable = false;
// _cancellationTokenSource?.Cancel();
// WriteToLog($"串口连接失败: {ex.Message}");
// return;
// }
// }
// }
// else
// {
// Disconnect();
// this.connect.Text = "🔗 连接功率计";
// toolStripStatusLabel1.Text = "功率计已断开";
// toolStripStatusLabel1.BackColor = Color.Red;
// }
//}
private void uiButton11_Click(object sender, EventArgs e)
{
if (this.connect.Text == "🔗 连接功率计")
{
lock (_serialLock)
{
try
{
_serialBuffer = "";
_waitingResponse = false;
serialPort = new SerialPort();
serialPort.PortName = this.comkou.Text;
serialPort.BaudRate = 38400;
serialPort.DataBits = 8;
serialPort.Parity = Parity.None;
serialPort.StopBits = StopBits.One;
serialPort.NewLine = "\r\n";
serialPort.DataReceived += SerialPort_DataReceived;
serialPort.Open();
_isSerialPortAvailable = true;
this.connect.Text = "断开连接";
toolStripStatusLabel1.Text = "功率计已连接";
toolStripStatusLabel1.BackColor = Color.Lime;
uiLabel27.Text = "";
WriteToLog("功率计串口连接成功");
_powerMeterTimer = new System.Windows.Forms.Timer();
_powerMeterTimer.Interval = 300; // 100ms读取一次
_powerMeterTimer.Tick += PowerMeterTimer_Tick;
_powerMeterTimer.Start();
//SendCommand("S01");
}
catch (Exception ex)
{
MessageBox.Show($"串口连接失败:{ex.Message}");
_isSerialPortAvailable = false;
WriteToLog($"串口连接失败: {ex.Message}");
return;
}
}
}
else
{
Disconnect();
this.connect.Text = "🔗 连接功率计";
uiLabel27.Text = "(请先连接功率计!!)";
toolStripStatusLabel1.Text = "功率计已断开";
toolStripStatusLabel1.BackColor = Color.Red;
}
}
// 串口数据接收事件
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
if (serialPort == null || !serialPort.IsOpen) return;
string data = serialPort.ReadExisting();
_serialBuffer += data;
int newLineIndex;
while ((newLineIndex = _serialBuffer.IndexOf("\r\n")) >= 0)
{
string line = _serialBuffer.Substring(0, newLineIndex);
_serialBuffer = _serialBuffer.Substring(newLineIndex + 2);
if (!string.IsNullOrEmpty(line))
{
this.Invoke(new Action(() =>
{
ProcessPowerMeterData(line);
}));
}
}
}
catch (Exception ex)
{
WriteToLog($"串口数据接收错误: {ex.Message}");
}
}
//private void ProcessPowerMeterData(string data)
//{
// try
// {
// if (string.IsNullOrEmpty(data)) return;
// string trimmedLine = data.Trim();
// WriteToLog($"处理数据行: '{trimmedLine}'");
// if (double.TryParse(trimmedLine, NumberStyles.Float, CultureInfo.InvariantCulture, out double powerValue))
// {
// uiLabel23.Text = $"{powerValue:F3}";
// _waitingResponse = false;
// }
// else if (trimmedLine.Contains(".") && trimmedLine.Length > 0)
// {
// string[] parts = trimmedLine.Split(' ');
// foreach (string part in parts)
// {
// if (double.TryParse(part, NumberStyles.Float, CultureInfo.InvariantCulture, out double power))
// {
// uiLabel23.Text = $"{power:F3} W";
// _waitingResponse = false;
// break;
// }
// }
// }
// else
// {
// WriteToLog($"未解析的数据: {trimmedLine}");
// _waitingResponse = false;
// }
// }
// catch (Exception ex)
// {
// WriteToLog($"处理功率计数据错误: {ex.Message}");
// _waitingResponse = false;
// }
//}
private void ProcessPowerMeterData(string data)
{
try
{
if (string.IsNullOrEmpty(data)) return;
string trimmedLine = data.Trim();
WriteToLog($"处理数据行: '{trimmedLine}'");
if (double.TryParse(trimmedLine, NumberStyles.Float, CultureInfo.InvariantCulture, out double powerValue))
{
if (ShouldFilterPowerValue(powerValue))
{
WriteToLog($"过滤噪声值: {powerValue:F3} ");
uiLabel23.Text = "0.000"; // 显示为0
}
else
{
uiLabel23.Text = $"{powerValue:F3} ";
}
_waitingResponse = false;
}
else if (trimmedLine.Contains(".") && trimmedLine.Length > 0)
{
string[] parts = trimmedLine.Split(' ');
foreach (string part in parts)
{
if (double.TryParse(part, NumberStyles.Float, CultureInfo.InvariantCulture, out double power))
{
if (ShouldFilterPowerValue(power))
{
WriteToLog($"过滤噪声值: {power:F3} ");
uiLabel23.Text = "0.000";
}
else
{
uiLabel23.Text = $"{power:F3} W";
}
_waitingResponse = false;
break;
}
}
}
else
{
WriteToLog($"未解析的数据: {trimmedLine}");
_waitingResponse = false;
}
}
catch (Exception ex)
{
WriteToLog($"处理功率计数据错误: {ex.Message}");
_waitingResponse = false;
}
}
private bool ShouldFilterPowerValue(double powerValue)
{
const double NOISE_THRESHOLD = 0.005; // 5mW根据实际情况调整
if (Math.Abs(powerValue) < NOISE_THRESHOLD)
{
return true; // 过滤掉接近0的小噪声
}
double[] suspiciousValues = { 2.0, 4.0, 8.0, 16.0, 32.0 };
foreach (double suspicious in suspiciousValues)
{
if (Math.Abs(powerValue - suspicious) < 0.1) // 允许0.1的误差
{
return true;
}
}
if (IsPowerOfTwo(powerValue))
{
return true;
}
return false;
}
private bool IsPowerOfTwo(double value)
{
if (value <= 0) return false;
int intValue = (int)Math.Round(value);
return (intValue != 0) && ((intValue & (intValue - 1)) == 0);
}
private void PowerMeterTimer_Tick(object sender, EventArgs e)
{
if (_isSerialPortAvailable && serialPort != null && serialPort.IsOpen && !_waitingResponse)
{
SendCommand("GD");
_waitingResponse = true;
}
}
// 发送命令到功率计
private void SendCommand(string command)
{
try
{
if (serialPort == null || !serialPort.IsOpen) return;
lock (_serialLock)
{
string fullCommand = command.ToUpper() + "\r\n";
serialPort.Write(fullCommand);
WriteToLog($"发送命令: {command}");
Task.Delay(2000).ContinueWith(t =>
{
if (_waitingResponse)
{
WriteToLog($"命令超时重置: {command}");
_waitingResponse = false;
}
});
}
}
catch (Exception ex)
{
WriteToLog($"发送命令失败: {ex.Message}");
_waitingResponse = false; // 出错时重置
}
}
private void Disconnect()
{
_isSerialPortAvailable = false;
_waitingResponse = false;
_serialBuffer = "";
if (_powerMeterTimer != null)
{
_powerMeterTimer.Stop();
_powerMeterTimer.Dispose();
_powerMeterTimer = null;
}
try
{
if (serialPort != null && serialPort.IsOpen)
{
SendCommand("S00");
}
}
catch { }
Task.Run(() =>
{
lock (_serialLock)
{
try
{
if (serialPort != null)
{
if (serialPort.IsOpen)
{
serialPort.Close();
}
serialPort.Dispose();
serialPort = null;
}
WriteToLog("功率计已断开连接");
}
catch (Exception ex)
{
WriteToLog($"断开连接异常:{ex.Message}");
}
}
});
}
private void WriteToLog(string message)
{
// 可以在界面上显示错误信息,比如在状态栏
try
{
if (InvokeRequired)
{
BeginInvoke(new Action<string>(WriteToLog), message);
return;
}
Console.WriteLine($"{DateTime.Now:HH:mm:ss} - {message}");
}
catch
{
// 忽略日志输出错误
}
}
#endregion
private void uiComboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string value = uiComboBox2.SelectedItem.ToString();
switch (value)
{
case "样品1":
{
var data = reportList?.OrderByDescending(s => s.Testtime2).FirstOrDefault(x => x.sampleType2 == 1);
uiLabel21.Text = data?.O22.ToString() ?? string.Empty;
uiLabel44.Text = data?.result2.ToString() ?? string.Empty;
uiLabel41.Text = data?.temperature2.ToString() ?? string.Empty;
uiLabel17.Text = data?.yuyan2.ToString() ?? string.Empty;
uiLabel36.Text = data?.yuhui2.ToString() ?? string.Empty;
uiLabel18.Text = data?.Isfire.ToString() ?? string.Empty;
uiLabel19.Text = data?.costTime2.ToString() ?? string.Empty;
uiLabel46.Text = data?.penetime2.ToString() ?? string.Empty;
uiLabel50.Text = data?.Testtime2.ToString() ?? string.Empty;
break;
}
case "样品2":
{
var data = reportList?.OrderByDescending(s => s.Testtime2).FirstOrDefault(x => x.sampleType2 == 2);
uiLabel21.Text = data?.O22.ToString() ?? string.Empty;
uiLabel44.Text = data?.result2.ToString() ?? string.Empty;
uiLabel41.Text = data?.temperature2.ToString() ?? string.Empty;
uiLabel17.Text = data?.yuyan2.ToString() ?? string.Empty;
uiLabel36.Text = data?.yuhui2.ToString() ?? string.Empty;
uiLabel18.Text = data?.Isfire.ToString() ?? string.Empty;
uiLabel19.Text = data?.costTime2.ToString() ?? string.Empty;
uiLabel46.Text = data?.penetime2.ToString() ?? string.Empty;
uiLabel50.Text = data?.Testtime2.ToString() ?? string.Empty;
break;
}
case "样品3":
{
var data = reportList?.OrderByDescending(s => s.Testtime2).FirstOrDefault(x => x.sampleType2 == 3);
uiLabel21.Text = data?.O22.ToString() ?? string.Empty;
uiLabel44.Text = data?.result2.ToString() ?? string.Empty;
uiLabel41.Text = data?.temperature2.ToString() ?? string.Empty;
uiLabel17.Text = data?.yuyan2.ToString() ?? string.Empty;
uiLabel36.Text = data?.yuhui2.ToString() ?? string.Empty;
uiLabel18.Text = data?.Isfire.ToString() ?? string.Empty;
uiLabel19.Text = data?.costTime2.ToString() ?? string.Empty;
uiLabel46.Text = data?.penetime2.ToString() ?? string.Empty;
uiLabel50.Text = data?.Testtime2.ToString() ?? string.Empty;
break;
}
case "样品4":
{
var data = reportList?.OrderByDescending(s => s.Testtime2).FirstOrDefault(x => x.sampleType2 == 4);
uiLabel21.Text = data?.O22.ToString() ?? string.Empty;
uiLabel44.Text = data?.result2.ToString() ?? string.Empty;
uiLabel41.Text = data?.temperature2.ToString() ?? string.Empty;
uiLabel17.Text = data?.yuyan2.ToString() ?? string.Empty;
uiLabel36.Text = data?.yuhui2.ToString() ?? string.Empty;
uiLabel18.Text = data?.Isfire.ToString() ?? string.Empty;
uiLabel19.Text = data?.costTime2.ToString() ?? string.Empty;
uiLabel46.Text = data?.penetime2.ToString() ?? string.Empty;
uiLabel50.Text = data?.Testtime2.ToString() ?? string.Empty;
break;
}
case "样品5":
{
var data = reportList?.OrderByDescending(s => s.Testtime2).FirstOrDefault(x => x.sampleType2 == 5);
uiLabel21.Text = data?.O22.ToString() ?? string.Empty;
uiLabel44.Text = data?.result2.ToString() ?? string.Empty;
uiLabel41.Text = data?.temperature2.ToString() ?? string.Empty;
uiLabel17.Text = data?.yuyan2.ToString() ?? string.Empty;
uiLabel36.Text = data?.yuhui2.ToString() ?? string.Empty;
uiLabel18.Text = data?.Isfire.ToString() ?? string.Empty;
uiLabel19.Text = data?.costTime2.ToString() ?? string.Empty;
uiLabel46.Text = data?.penetime2.ToString() ?? string.Empty;
uiLabel50.Text = data?.Testtime2.ToString() ?? string.Empty;
break;
}
default:
break;
}
}
//相机
private void uiButton8_Click(object sender, EventArgs e)
{
AutoCameraForm cameraForm = new AutoCameraForm(() => RunStatus);
this.SwitchToForm(() => cameraForm);
}
private void SwitchToForm(Func<Form> formCreator)
{
using (Form form = formCreator())
{
this.Hide();
form.ShowDialog();
this.Show();
this.Activate();
}
}
private void uiButton10_Click(object sender, EventArgs e)
{
ma?.BtnClickFunctionForNew(Function.ButtonType., 41, 1);//清除
}
private void uiButton13_Click(object sender, EventArgs e)
{
this.Close();//返回主页面
}
private void PrimaryIgnitionForm_FormClosing(object sender, FormClosingEventArgs e)
{
// 停止定时器
if (_readtimer != null)
{
_readtimer.Stop();
_readtimer.Dispose();
_readtimer = null;
}
}
private void uiButton11_Click_1(object sender, EventArgs e)
{
ma?.BtnClickFunctionForNew(Function.ButtonType., 11);//灯开关
}
private void uiButton9_Click(object sender, EventArgs e)
{
ma?.BtnClickFunctionForNew(Function.ButtonType., 101);//混氧开关
}
}
}