HomeViewModel.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. using MahApps.Metro.Controls;
  2. using MaterialDesignThemes.Wpf;
  3. using NPOI.SS.Formula.Functions;
  4. using OxyPlot;
  5. using OxyPlot.Axes;
  6. using OxyPlot.Legends;
  7. using OxyPlot.Series;
  8. using OxyPlot.Wpf;
  9. using Prism.Commands;
  10. using Prism.Events;
  11. using Prism.Ioc;
  12. using Prism.Mvvm;
  13. using Prism.Regions;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Collections.ObjectModel;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Threading.Tasks;
  20. using System.Windows;
  21. using System.Windows.Media;
  22. using TeamAAS_VP;
  23. using TeamAAS_VP.Controls;
  24. using TeamAAS_VP.Core;
  25. using TeamAAS_VP.Data;
  26. using TeamAAS_VP.Enums;
  27. using TeamAAS_VP.Events;
  28. using TeamAAS_VP.Interfaces;
  29. using TeamAAS_VP.Models;
  30. using TeamAAS_VP.Resources.Languages;
  31. using TeamAAS_VP.Services;
  32. using TeamAAS_VP.ViewModels.DebugMod;
  33. using TeamAAS_VP.Views.DebugMod;
  34. using static TeamAAS_VP.Models.SystemConfiguration;
  35. namespace TeamAAS_VP.ViewModels
  36. {
  37. public class HomeViewModel : BindableBase, IConfirmNavigationRequest
  38. {
  39. IEventAggregator _eventAggregator;
  40. IContainerProvider _container;
  41. IProductService _productService;
  42. IConfigService _configService;
  43. IRemoteCommandService _remoteCommandService;
  44. ISystemDatabaseService _systemDatabaseService;
  45. #region 属性
  46. private ObservableCollection<TaskMessage> messageQueue = new ObservableCollection<TaskMessage>();
  47. /// <summary>
  48. /// 运行信息队列
  49. /// </summary>
  50. public ObservableCollection<TaskMessage> MessageQueue
  51. {
  52. get { return messageQueue; }
  53. set { SetProperty(ref messageQueue, value); }
  54. }
  55. private ObservableCollection<ProductModel> _ProductList;
  56. public ObservableCollection<ProductModel> ProductList
  57. {
  58. get { return _ProductList; }
  59. set { SetProperty(ref _ProductList, value); }
  60. }
  61. private Management _management;
  62. public Management management
  63. {
  64. get { return _management; }
  65. set { SetProperty(ref _management, value); }
  66. }
  67. private double _CTTotalSeconds;
  68. public double CTTotalSeconds
  69. {
  70. get { return _CTTotalSeconds; }
  71. set { SetProperty(ref _CTTotalSeconds, value); }
  72. }
  73. private ProductModel _SelectProduct;
  74. public ProductModel SelectProduct
  75. {
  76. get { return _SelectProduct; }
  77. set { SetProperty(ref _SelectProduct, value); }
  78. }
  79. private bool CanLoad
  80. {
  81. get
  82. {
  83. if (SelectProduct != null && IsLoadProduct)
  84. {
  85. return true;
  86. }
  87. else
  88. {
  89. return false;
  90. }
  91. }
  92. }
  93. private bool _IsLoadProduct = true;
  94. public bool IsLoadProduct
  95. {
  96. get { return _IsLoadProduct; }
  97. set { SetProperty(ref _IsLoadProduct, value); }
  98. }
  99. private bool _isCanExecute = true;
  100. public bool isCanExecute
  101. {
  102. get { return _isCanExecute; }
  103. set { SetProperty(ref _isCanExecute, value); }
  104. }
  105. private ProductModel _CurrentProduct;
  106. public ProductModel CurrentProduct
  107. {
  108. get { return _CurrentProduct; }
  109. set { SetProperty(ref _CurrentProduct, value); }
  110. }
  111. private ObservableCollection<PlotModel> _PressurePlotModels = new ObservableCollection<PlotModel>();
  112. /// <summary>
  113. /// 每个元素是一个 PlotModel,对应一个压力传感器
  114. /// </summary>
  115. public ObservableCollection<PlotModel> PressurePlotModels
  116. {
  117. get { return _PressurePlotModels; }
  118. set { SetProperty(ref _PressurePlotModels, value); }
  119. }
  120. private PlotModel _LockCurvePlotModel;
  121. /// <summary>
  122. /// 锁付曲线
  123. /// </summary>
  124. public PlotModel LockCurvePlotModel
  125. {
  126. get { return _LockCurvePlotModel; }
  127. set { SetProperty(ref _LockCurvePlotModel, value); }
  128. }
  129. private ObservableCollection<LockResult> _LockResults = new ObservableCollection<LockResult>();
  130. /// <summary>
  131. /// 锁付结果列表
  132. /// </summary>
  133. public ObservableCollection<LockResult> LockResults
  134. {
  135. get { return _LockResults; }
  136. set { SetProperty(ref _LockResults, value); }
  137. }
  138. private ObservableCollection<AssemblyRecord> _AssemblyResults=new ObservableCollection<AssemblyRecord>();
  139. /// <summary>
  140. /// 组装结果列表
  141. /// </summary>
  142. public ObservableCollection<AssemblyRecord> AssemblyResults
  143. {
  144. get { return _AssemblyResults; }
  145. set { SetProperty(ref _AssemblyResults, value); }
  146. }
  147. // 可选:记录传感器 Id -> 索引 的映射,便于外部(如 Management)按 Id 更新
  148. private readonly Dictionary<string, int> _sensorIdToIndex = new Dictionary<string, int>();
  149. #endregion
  150. #region 命令
  151. public DelegateCommand LoadedCommand { get; set; }
  152. private DelegateCommand<ProductModel> _LoadProductCommand;
  153. public DelegateCommand<ProductModel> LoadProductCommand =>
  154. _LoadProductCommand ?? (_LoadProductCommand = new DelegateCommand<ProductModel>(ExecuteLoadProductCommand).ObservesCanExecute(() => CanLoad).ObservesProperty(() => SelectProduct).ObservesProperty(() => IsLoadProduct));
  155. private DelegateCommand _ResetCounterCommand;
  156. public DelegateCommand ResetCounterCommand =>
  157. _ResetCounterCommand ?? (_ResetCounterCommand = new DelegateCommand(ExecuteResetCounterCommand).ObservesCanExecute(() => DoCondition).ObservesProperty(() => isCanExecute));
  158. private bool DoCondition
  159. {
  160. get { return isCanExecute; }
  161. }
  162. private DelegateCommand<string> _CopyCommand;
  163. public DelegateCommand<string> CopyCommand =>
  164. _CopyCommand ?? (_CopyCommand = new DelegateCommand<string>(ExecuteCopyCommand));
  165. #endregion
  166. #region 事件
  167. #endregion
  168. public HomeViewModel(IEventAggregator ea, IContainerProvider container, IProductService productService, IConfigService configService, IRemoteCommandService remoteCommandService
  169. , ISystemDatabaseService systemDatabaseService)
  170. {
  171. _eventAggregator = ea;
  172. _container = container;
  173. _productService = productService;
  174. LoadedCommand = new DelegateCommand(OnLoad);
  175. _eventAggregator.GetEvent<TaskMessageNotification>().Subscribe(AddMessageInvoke);
  176. //订阅权限登录事件
  177. _eventAggregator.GetEvent<UserLoginNotification>().Subscribe(LoginChange);
  178. management = _container.Resolve<Management>();
  179. _configService = configService;
  180. _productService.OnProductChanged += _productService_OnProductChanged;
  181. _remoteCommandService = remoteCommandService;
  182. _remoteCommandService.CycleTimingTicked += _remoteCommandService_CycleTimingTicked;
  183. _systemDatabaseService = systemDatabaseService;
  184. _eventAggregator.GetEvent<LockFinishNotification>().Subscribe(OnLockFinish);
  185. _eventAggregator.GetEvent<PressureFinishNotification>().Subscribe(OnPressureFinish);
  186. _eventAggregator.GetEvent<AssemblyFinishNotification>().Subscribe(OnAssemblyFinish);
  187. //获取所有的压力传感器配置,初始化曲线图
  188. var systemConfig = _configService.GetSystemConfiguration();
  189. if (systemConfig.PressureSensorConfig != null)
  190. {
  191. InitPressurePlots(systemConfig.PressureSensorConfig.ToArray());
  192. }
  193. }
  194. private void _remoteCommandService_CycleTimingTicked(object sender, TimeSpan e)
  195. {
  196. try
  197. {
  198. if (App.Current != null)
  199. {
  200. App.Current.Invoke(() =>
  201. {
  202. CTTotalSeconds = e.TotalSeconds;
  203. });
  204. }
  205. }
  206. catch (Exception)
  207. {
  208. }
  209. }
  210. #region 方法
  211. bool isFirst = true;
  212. private void OnLoad()
  213. {
  214. if (!isFirst)
  215. {
  216. return;
  217. }
  218. InitLockCurvePlotModel();
  219. isFirst = false;
  220. }
  221. async void ExecuteLoadProductCommand(ProductModel product)
  222. {
  223. if (product == null) return;
  224. var view = new ShowMessage(Lang.是否加载产品, $"{Lang.加载产品}:{product.Name}?");
  225. //show the dialog
  226. var result = await DialogHost.Show(view, "RootDialog", null, null, null);
  227. if (result != null && result is bool)
  228. {
  229. if (((bool)result))
  230. {
  231. IsLoadProduct = false;
  232. var waiting = new WaitingControl();
  233. //show the dialog
  234. var task = DialogHost.Show(waiting, "RootDialog", null, null, null);
  235. _productService.LoadProduct(product.ID);
  236. _productService.SetCurrentProduct(product.ID);
  237. await management.WriteParameterToPlcAsync();
  238. await management.WritePositionToPlcAsync();
  239. if (DialogHost.IsDialogOpen("RootDialog"))
  240. {
  241. DialogHost.Close("RootDialog");
  242. }
  243. await task;
  244. //DatabaseHelper.AddLoadProductRecord(product.ID, product.Name, false);
  245. IsLoadProduct = true;
  246. }
  247. }
  248. }
  249. void ExecuteCopyCommand(string textToCopy)
  250. {
  251. Clipboard.SetText(textToCopy);
  252. }
  253. /// <summary>
  254. /// 添加消息至消息队列
  255. /// </summary>
  256. /// <param name="msg"></param>
  257. /// <param name="color"></param>
  258. public void AddMessage(string msg, Color color)
  259. {
  260. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  261. try
  262. {
  263. MessageQueue.Add(new TaskMessage()
  264. {
  265. DT = DateTime.Now,
  266. Message = msg,
  267. FontColol = new SolidColorBrush(color)
  268. });
  269. LogHelper.WriteLogInfo(msg);
  270. }
  271. catch (Exception)
  272. {
  273. }
  274. }));
  275. }
  276. /// <summary>
  277. /// 添加消息至消息队列
  278. /// </summary>
  279. /// <param name="msg"></param>
  280. /// <param name="color"></param>
  281. public void AddMessage(string msg, MessageLevel level)
  282. {
  283. MessageStruct messageStruct = new MessageStruct() { Message = msg, level = level };
  284. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  285. AddMessage(messageStruct);
  286. }));
  287. }
  288. /// <summary>
  289. /// 添加消息至消息队列
  290. /// </summary>
  291. /// <param name="messageStruct"></param>
  292. public void AddMessage(MessageStruct messageStruct)
  293. {
  294. try
  295. {
  296. if (MessageQueue.Count >= 200)
  297. {
  298. MessageQueue.RemoveAt(0);// 从队列头部移除最早的消息
  299. }
  300. Color color = Colors.Black;
  301. switch (messageStruct.level)
  302. {
  303. case MessageLevel.Info:
  304. color = Colors.Black;
  305. break;
  306. case MessageLevel.Debug:
  307. color = Colors.Green;
  308. break;
  309. case MessageLevel.Alarm:
  310. color = Colors.Orange;
  311. break;
  312. case MessageLevel.Error:
  313. color = Colors.Red;
  314. break;
  315. }
  316. MessageQueue.Add(new TaskMessage()
  317. {
  318. DT = DateTime.Now,
  319. Message = messageStruct.Message,
  320. FontColol = new SolidColorBrush(color)
  321. });
  322. LogHelper.WriteLogInfo(messageStruct.Message);
  323. }
  324. catch (Exception)
  325. {
  326. }
  327. }
  328. public void AddMessageInvoke(MessageStruct messageStruct)
  329. {
  330. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  331. AddMessage(messageStruct);
  332. }));
  333. }
  334. private void LoginChange(Models.User user)
  335. {
  336. }
  337. /// <summary>
  338. /// 重置计数
  339. /// </summary>
  340. async void ExecuteResetCounterCommand()
  341. {
  342. var currentProduct = _productService.GetCurrentProduct();
  343. if (currentProduct == null) return;
  344. var view = new ShowMessage(Lang.计数清零, Lang.是否重置当前产品的计数);
  345. //show the dialog
  346. var result = await DialogHost.Show(view, "RootDialog", null, null, null);
  347. if (result != null && result is bool)
  348. {
  349. if (((bool)result))
  350. {
  351. isCanExecute = false;
  352. await _systemDatabaseService.ResetProductionAsync(currentProduct.Name);
  353. await _systemDatabaseService.ResetThrowNumberAsync();
  354. isCanExecute = true;
  355. }
  356. }
  357. }
  358. //初始化曲线图
  359. private void InitLockCurvePlotModel()
  360. {
  361. var model = new PlotModel { Title = Lang.锁付曲线, TitleFontSize = 16 };
  362. // 设置图例
  363. var legend = new Legend
  364. {
  365. LegendPosition = LegendPosition.TopRight,
  366. LegendPlacement = LegendPlacement.Outside,
  367. LegendOrientation = LegendOrientation.Vertical,
  368. LegendBorderThickness = 0
  369. };
  370. model.Legends.Add(legend);
  371. // 设置X轴
  372. var xAxis = new LinearAxis
  373. {
  374. Key = "X",
  375. Position = AxisPosition.Bottom,
  376. Title = Lang.角度数,
  377. Minimum = 0,
  378. MajorGridlineStyle = LineStyle.Solid,
  379. MinorGridlineStyle = LineStyle.Dot
  380. };
  381. model.Axes.Add(xAxis);
  382. // 设置Y轴
  383. var yAxis = new LinearAxis
  384. {
  385. Key = "Y",
  386. Position = AxisPosition.Left,
  387. Title = Lang.力矩kgf,
  388. MajorGridlineStyle = LineStyle.Solid,
  389. MinorGridlineStyle = LineStyle.Dot
  390. };
  391. model.Axes.Add(yAxis);
  392. // 添加示例数据系列
  393. var series = new LineSeries
  394. {
  395. Title = Lang.锁付力矩曲线,
  396. StrokeThickness = 2,
  397. MarkerSize = 3,
  398. MarkerType = MarkerType.Circle,
  399. CanTrackerInterpolatePoints = false,
  400. };
  401. model.Series.Add(series);
  402. LockCurvePlotModel = model;
  403. }
  404. /// <summary>
  405. /// 螺丝锁付完成时调用
  406. /// </summary>
  407. /// <param name="result"></param>
  408. /// <exception cref="NotImplementedException"></exception>
  409. private void OnLockFinish(LockResult result)
  410. {
  411. //如果当前螺丝编号为1,则清除之前的结果
  412. if (result.Number == 1)
  413. {
  414. LockResults.Clear();
  415. }
  416. LockResults.Add(result);
  417. //更新曲线图
  418. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  419. var series = LockCurvePlotModel.Series[0] as LineSeries;
  420. //var yaxis = LockCurvePlotModel.Axes.FirstOrDefault(p=>p.Key=="Y");
  421. //yaxis.Maximum = result.TargetTorque;
  422. series.Points.Clear();
  423. foreach (var waveData in result.WaveDatas)
  424. {
  425. series.Points.Add(new OxyPlot.DataPoint(waveData.LockAngle, waveData.Torque));
  426. }
  427. LockCurvePlotModel.InvalidatePlot(true);
  428. }));
  429. }
  430. /// <summary>
  431. /// 锁付完成时调用
  432. /// </summary>
  433. /// <param name="record"></param>
  434. /// <exception cref="NotImplementedException"></exception>
  435. private void OnAssemblyFinish(AssemblyRecord record)
  436. {
  437. AssemblyResults.Add(record);
  438. //如果记录数超过1000,则删除最早的记录
  439. if (AssemblyResults.Count > 50)
  440. {
  441. AssemblyResults.RemoveAt(0);
  442. }
  443. }
  444. /// <summary>
  445. /// 保压完成时调用
  446. /// </summary>
  447. /// <param name="tuple"></param>
  448. private void OnPressureFinish((bool IsSuccess, int Index, (DateTime Timestamp, float Value)[] values, string SavePath) tuple)
  449. {
  450. //更新对应传感器的曲线图
  451. if (_sensorIdToIndex.TryGetValue(tuple.Index.ToString(), out int index))
  452. {
  453. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  454. var model = PressurePlotModels[index];
  455. var series = model.Series[0] as LineSeries;
  456. series.Points.Clear();
  457. //第一个点的时间作为X轴起点
  458. DateTime xAxisStart = tuple.values[0].Timestamp;
  459. foreach (var dataPoint in tuple.values)
  460. {
  461. // 计算相对于起点的秒数作为X轴坐标
  462. double xValue = (dataPoint.Timestamp - xAxisStart).TotalSeconds;
  463. series.Points.Add(new OxyPlot.DataPoint(xValue, dataPoint.Value));
  464. }
  465. // 重置所有轴的范围以适应新数据
  466. model.ResetAllAxes();
  467. model.InvalidatePlot(true);
  468. if (!string.IsNullOrEmpty(tuple.SavePath))
  469. {
  470. if (!Directory.Exists(Path.GetDirectoryName(tuple.SavePath)))
  471. {
  472. Directory.CreateDirectory(Path.GetDirectoryName(tuple.SavePath));
  473. }
  474. PngExporter.Export(model, tuple.SavePath, (int)model.Width, (int)model.Height);
  475. }
  476. }));
  477. }
  478. }
  479. // 初始化由配置决定的曲线数量(在读取 SystemConfiguration 后调用)
  480. public void InitPressurePlots(IEnumerable<PressureSensorSettings> sensors)
  481. {
  482. PressurePlotModels.Clear();
  483. _sensorIdToIndex.Clear();
  484. int idx = 0;
  485. foreach (var s in sensors)
  486. {
  487. var model = CreatePlotModelForSensor(s);
  488. PressurePlotModels.Add(model);
  489. // 假设 PressureSensorConfig 有唯一 Id(string 或 int)
  490. _sensorIdToIndex[s.SensorId.ToString()] = idx++;
  491. }
  492. }
  493. private PlotModel CreatePlotModelForSensor(PressureSensorSettings sensor)
  494. {
  495. var model = new PlotModel { Title = sensor.SensorName ?? $"Sensor {sensor.SensorId}", TitleFontSize = 16 };
  496. // 设置图例
  497. var legend = new Legend
  498. {
  499. LegendPosition = LegendPosition.TopRight,
  500. LegendPlacement = LegendPlacement.Outside,
  501. LegendOrientation = LegendOrientation.Vertical,
  502. LegendBorderThickness = 0
  503. };
  504. model.Legends.Add(legend);
  505. // 设置X轴
  506. var xAxis = new LinearAxis
  507. {
  508. Key = "X",
  509. Position = AxisPosition.Bottom,
  510. Title = "Time (s)",
  511. Minimum = 0,
  512. MajorGridlineStyle = LineStyle.Solid,
  513. MinorGridlineStyle = LineStyle.Dot
  514. };
  515. model.Axes.Add(xAxis);
  516. // 设置Y轴
  517. var yAxis = new LinearAxis
  518. {
  519. Key = "Y",
  520. Position = AxisPosition.Left,
  521. Title = "Pressure",
  522. MajorGridlineStyle = LineStyle.Solid,
  523. MinorGridlineStyle = LineStyle.Dot
  524. };
  525. model.Axes.Add(yAxis);
  526. // 添加示例数据系列
  527. var series = new LineSeries
  528. {
  529. Title = sensor.SensorName ?? $"Sensor {sensor.SensorId}",
  530. StrokeThickness = 2,
  531. MarkerSize = 3,
  532. MarkerType = MarkerType.Circle,
  533. CanTrackerInterpolatePoints = false,
  534. };
  535. model.Series.Add(series);
  536. return model;
  537. }
  538. #endregion
  539. #region 继承
  540. /// <summary>
  541. /// 确认导航请求时调用。此方法允许您在导航之前执行一些操作。
  542. /// </summary>
  543. /// <param name="navigationContext"></param>
  544. /// <param name="continuationCallback"></param>
  545. public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
  546. {
  547. continuationCallback(true);
  548. }
  549. /// <summary>
  550. /// 接收导航请求时调用。传入导航参数,包含有关导航目标的信息。
  551. /// </summary>
  552. /// <param name="navigationContext"></param>
  553. /// <exception cref="NotImplementedException"></exception>
  554. public async void OnNavigatedTo(NavigationContext navigationContext)
  555. {
  556. try
  557. {
  558. ProductList = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
  559. }
  560. catch (Exception ex)
  561. {
  562. LogHelper.WriteLogError("主界面界面进入时出错!", ex);
  563. }
  564. }
  565. /// <summary>
  566. /// 是否允许导航到此视图模型。
  567. /// </summary>
  568. /// <param name="navigationContext"></param>
  569. /// <returns></returns>
  570. public bool IsNavigationTarget(NavigationContext navigationContext)
  571. {
  572. return true;
  573. }
  574. /// <summary>
  575. /// 导航离开此视图模型时调用。您可以在此处执行清理操作或保存状态。
  576. /// </summary>
  577. /// <param name="navigationContext"></param>
  578. public void OnNavigatedFrom(NavigationContext navigationContext)
  579. {
  580. }
  581. #endregion
  582. private void _productService_OnProductChanged(ProductModel obj)
  583. {
  584. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  585. CurrentProduct = obj;
  586. }));
  587. }
  588. }
  589. }