using Modbus.Device;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using 软胶囊弹性硬度测试仪;
using 软胶囊弹性硬度测试仪.Data;
namespace EmptyLoadTest
{
///
/// Window1.xaml 的交互逻辑
///
public partial class TorqueParameterWindow : Window
{
#region 私有字段
private TcpClient _tcpClient => ModbusResourceManager.Instance.TcpClient;
private IModbusMaster _modbusMaster => ModbusResourceManager.Instance.ModbusMaster;
private readonly DispatcherTimer _readTimer;
#endregion
软胶囊弹性硬度测试仪.Function ma;
DataChange c = new DataChange();
public TorqueParameterWindow()
{
InitializeComponent();
InitializeModbusTcp();
_readTimer = InitDispatcherTimer();
}
private static TorqueParameterWindow _instance;
public static TorqueParameterWindow Instance
{
get
{
if (_instance == null || !_instance.IsLoaded)
{
_instance = new TorqueParameterWindow();
}
return _instance;
}
}
private void InitializeModbusTcp()
{
try
{
string plcIp = "192.168.1.10";
bool initSuccess = 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);
}
catch (Exception ex)
{
ShowError($"Modbus初始化失败: {ex.Message}");
}
}
private void ShowError(string msg) => MessageBox.Show(msg, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
private DispatcherTimer InitDispatcherTimer()
{
var timer = new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(100)
};
timer.Tick += async (s, e) =>
{
if (_modbusMaster != null)
{
try
{
await ReadAddr262DataAsync();
}
catch { }
}
};
return timer;
}
private async System.Threading.Tasks.Task ReadAddr262DataAsync()
{
try
{
// 创建任务列表
var tasks = new List
{
ReadAndUpdateFloatAsync(1314, 2, force1, "F2", " "),
ReadAndUpdateFloatAsync(290, 2, firstspeed, "F2", " "),
ReadAndUpdateFloatAsync(500, 2, pressure, "F2", " "),
ReadAndUpdateFloatAsync(1360, 2, force2, "F2", " "),
ReadAndUpdateFloatAsync(1366, 2, nishizhen, "F2", " "),
ReadAndUpdateFloatAsync(1368 ,2, shunshizhen, "F2", " "),
ReadAndUpdateFloatAsync(320 ,2, position, "F2", " "),
ReadAndUpdateFloatAsync(102 ,2, actualpress, "F2", " "),
};
await Task.WhenAll(tasks);
}
catch (Exception ex)
{
ShowError($"读取数据失败:{ex.Message}");
}
}
private async Task ReadAndUpdateFloatAsync(int address, int length, System.Windows.Controls.TextBox control, string format, string unit)
{
try
{
ushort[] registers = await Task.Run(async () =>
await _modbusMaster?.ReadHoldingRegistersAsync(1, (ushort)address, (ushort)length)
);
if (registers != null && registers.Length >= 2)
{
float value = c.UshortToFloat(registers[1], registers[0]);
Dispatcher.Invoke(() => control.Text = value.ToString(format) + unit);
}
else if (registers != null && registers.Length >= 1)
{
int value = registers[0];
Dispatcher.Invoke(() => control.Text = value.ToString(format) + unit);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"读取地址{address}失败:{ex.Message}");
}
}
private async Task ReadAndUpdateFloatAsync(int address, int length, System.Windows.Controls.TextBlock control, string format, string unit)
{
try
{
ushort[] registers = await Task.Run(async () =>
await _modbusMaster?.ReadHoldingRegistersAsync(1, (ushort)address, (ushort)length)
);
if (registers != null && registers.Length >= 2)
{
float value = c.UshortToFloat(registers[1], registers[0]);
Dispatcher.Invoke(() => control.Text = value.ToString(format) + unit);
}
else if (registers != null && registers.Length >= 1)
{
int value = registers[0];
Dispatcher.Invoke(() => control.Text = value.ToString(format) + unit);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"读取地址{address}失败:{ex.Message}");
}
}
private async Task ReadAndUpdateIntAsync(int address, int length, System.Windows.Controls.Control control, string format)
{
try
{
ushort[] registers = await Task.Run(() =>
_modbusMaster?.ReadHoldingRegisters(1, (ushort)address, (ushort)length)
);
if (registers != null && registers.Length >= 1)
{
int value = registers[0];
Dispatcher.Invoke(() =>
{
if (control is System.Windows.Controls.ContentControl contentControl)
contentControl.Content = value.ToString(format);
else if (control is System.Windows.Controls.TextBox textBox)
textBox.Text = value.ToString(format);
});
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"读取地址{address}失败:{ex.Message}");
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
_readTimer?.Start();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ma.BtnClickFunctionForNew(Function.ButtonType.复归型, 11);
}
private void force1_GotFocus(object sender, RoutedEventArgs e)
{
ma.WriteToPLCForNew(force1.Text.Trim(), 1314, 软胶囊弹性硬度测试仪.Function.DataType.浮点型);
System.Threading.Tasks.Task.Delay(50);
t0.Focus();
}
private void firstspeed_GotFocus(object sender, RoutedEventArgs e)
{
ma.WriteToPLCForNew(firstspeed.Text.Trim(), 290, 软胶囊弹性硬度测试仪.Function.DataType.浮点型);
System.Threading.Tasks.Task.Delay(50);
t0.Focus();
}
private void pressure_GotFocus(object sender, RoutedEventArgs e)
{
ma.WriteToPLCForNew(pressure.Text.Trim(), 500, 软胶囊弹性硬度测试仪.Function.DataType.浮点型);
System.Threading.Tasks.Task.Delay(50);
t0.Focus();
}
private void force2_GotFocus(object sender, RoutedEventArgs e)
{
ma.WriteToPLCForNew(force2.Text.Trim(), 1360, 软胶囊弹性硬度测试仪.Function.DataType.浮点型);
System.Threading.Tasks.Task.Delay(50);
t0.Focus();
}
private void shunshizhen_GotFocus(object sender, RoutedEventArgs e)
{
ma.WriteToPLCForNew(shunshizhen.Text.Trim(), 1368, 软胶囊弹性硬度测试仪.Function.DataType.浮点型);
System.Threading.Tasks.Task.Delay(50);
t0.Focus();
}
private void nishizhen_GotFocus(object sender, RoutedEventArgs e)
{
ma.WriteToPLCForNew(nishizhen.Text.Trim(), 1366, 软胶囊弹性硬度测试仪.Function.DataType.浮点型);
System.Threading.Tasks.Task.Delay(50);
t0.Focus();
}
private void position_GotFocus(object sender, RoutedEventArgs e)
{
ma.WriteToPLCForNew(position.Text.Trim(), 320, 软胶囊弹性硬度测试仪.Function.DataType.浮点型);
System.Threading.Tasks.Task.Delay(50);
t0.Focus();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var mainWindow = MainWindow.Instance;
if (!mainWindow.IsVisible)
{
mainWindow.Show();
}
else
{
mainWindow.Activate();
}
Close();
}
}
}