73 lines
2.7 KiB
C#
73 lines
2.7 KiB
C#
using CommunityToolkit.Mvvm.ComponentModel;
|
|
using CommunityToolkit.Mvvm.Input;
|
|
using System;
|
|
using System.Collections.ObjectModel;
|
|
using System.Threading.Tasks;
|
|
using System.Windows.Threading;
|
|
using TabletTester2025.Models;
|
|
using TabletTester2025.Services;
|
|
|
|
namespace TabletTester2025.ViewModels
|
|
{
|
|
public partial class MainViewModel : ObservableObject
|
|
{
|
|
private readonly IPlcService _plc;
|
|
private readonly DatabaseService _db;
|
|
private readonly ExcelExportService _excel;
|
|
private readonly AlarmService _alarm;
|
|
private readonly PlcConfiguration _plcConfig;
|
|
private DispatcherTimer _timer;
|
|
|
|
[ObservableProperty] private string _plcStatus = "断开";
|
|
[ObservableProperty] private string _currentTime;
|
|
[ObservableProperty] private string _globalAlarm;
|
|
|
|
public ObservableCollection<StationViewModel> Stations { get; }
|
|
|
|
public IAsyncRelayCommand ExportAllCommand { get; }
|
|
|
|
public MainViewModel(IPlcService plc, DatabaseService db, ExcelExportService excel, AlarmService alarm, PlcConfiguration plcConfig)
|
|
{
|
|
_plc = plc;
|
|
_db = db;
|
|
_excel = excel;
|
|
_alarm = alarm;
|
|
_plcConfig = plcConfig;
|
|
|
|
_alarm.PropertyChanged += (s, e) => { if (e.PropertyName == nameof(AlarmService.CurrentAlarm)) GlobalAlarm = _alarm.CurrentAlarm; };
|
|
|
|
Stations = new ObservableCollection<StationViewModel>();
|
|
for (int i = 1; i <= 3; i++)
|
|
Stations.Add(new StationViewModel(i, _plc, _plcConfig, _db, _excel, _alarm));
|
|
|
|
ExportAllCommand = new AsyncRelayCommand(ExportAllAsync);
|
|
|
|
_timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };
|
|
_timer.Tick += OnTimerTick;
|
|
_ = ConnectToPlc();
|
|
_timer.Start();
|
|
}
|
|
|
|
private async Task ConnectToPlc()
|
|
{
|
|
try { await _plc.ConnectAsync(); PlcStatus = "已连接"; }
|
|
catch { PlcStatus = "连接失败"; }
|
|
}
|
|
|
|
private async void OnTimerTick(object sender, EventArgs e)
|
|
{
|
|
CurrentTime = DateTime.Now.ToString("HH:mm:ss");
|
|
if (PlcStatus != "已连接") return;
|
|
foreach (var station in Stations)
|
|
await station.UpdateRealTimeData();
|
|
}
|
|
|
|
private async Task ExportAllAsync()
|
|
{
|
|
var batches = _db.GetBatches(null, 1000);
|
|
string path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), $"全工位报告_{DateTime.Now:yyyyMMddHHmmss}.xlsx");
|
|
_excel.ExportToExcel(batches, path);
|
|
System.Windows.MessageBox.Show($"报告已导出到:{path}");
|
|
}
|
|
}
|
|
} |