66 lines
1.9 KiB
C#
66 lines
1.9 KiB
C#
|
|
using System.Windows;
|
|||
|
|
using WpfApp.src.components;
|
|||
|
|
|
|||
|
|
namespace WpfApp.Services
|
|||
|
|
{
|
|||
|
|
/// <summary>
|
|||
|
|
/// SensorChart 管理器 - 负责传感器数据采集和更新
|
|||
|
|
/// </summary>
|
|||
|
|
public class SensorChartManager
|
|||
|
|
{
|
|||
|
|
private readonly Window dispatcherOwner;
|
|||
|
|
private CancellationTokenSource cts;
|
|||
|
|
private readonly Random rand = new Random();
|
|||
|
|
|
|||
|
|
// 绑定的传感器控件
|
|||
|
|
public SensorChart Sensor1 { get; set; }
|
|||
|
|
public SensorChart Sensor2 { get; set; }
|
|||
|
|
public SensorChart Sensor3 { get; set; }
|
|||
|
|
|
|||
|
|
public SensorChartManager(Window owner)
|
|||
|
|
{
|
|||
|
|
dispatcherOwner = owner;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 启动模拟数据采集
|
|||
|
|
/// </summary>
|
|||
|
|
public void Start()
|
|||
|
|
{
|
|||
|
|
if (Sensor1 == null || Sensor2 == null || Sensor3 == null)
|
|||
|
|
throw new InvalidOperationException("请先绑定传感器控件");
|
|||
|
|
|
|||
|
|
cts = new CancellationTokenSource();
|
|||
|
|
|
|||
|
|
Task.Run(async () =>
|
|||
|
|
{
|
|||
|
|
while (!cts.Token.IsCancellationRequested)
|
|||
|
|
{
|
|||
|
|
// 模拟数据
|
|||
|
|
double s1 = rand.NextDouble() * 100 - 50;
|
|||
|
|
double s2 = rand.NextDouble() * 100 - 50;
|
|||
|
|
double s3 = rand.NextDouble() * 100 - 50;
|
|||
|
|
|
|||
|
|
// 更新 UI
|
|||
|
|
dispatcherOwner.Dispatcher.Invoke(() =>
|
|||
|
|
{
|
|||
|
|
Sensor1.SetSensorData("传感器1", s1);
|
|||
|
|
Sensor2.SetSensorData("传感器2", s2);
|
|||
|
|
Sensor3.SetSensorData("传感器3", s3);
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
await Task.Delay(100); // 每100毫秒采集一次
|
|||
|
|
}
|
|||
|
|
}, cts.Token);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 停止采集
|
|||
|
|
/// </summary>
|
|||
|
|
public void Stop()
|
|||
|
|
{
|
|||
|
|
cts?.Cancel();
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|