HomeViewModel.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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. // 可选:记录传感器 Id -> 索引 的映射,便于外部(如 Management)按 Id 更新
  139. private readonly Dictionary<string, int> _sensorIdToIndex = new Dictionary<string, int>();
  140. #endregion
  141. #region 命令
  142. public DelegateCommand LoadedCommand { get; set; }
  143. private DelegateCommand<ProductModel> _LoadProductCommand;
  144. public DelegateCommand<ProductModel> LoadProductCommand =>
  145. _LoadProductCommand ?? (_LoadProductCommand = new DelegateCommand<ProductModel>(ExecuteLoadProductCommand).ObservesCanExecute(() => CanLoad).ObservesProperty(() => SelectProduct).ObservesProperty(() => IsLoadProduct));
  146. private DelegateCommand _ResetCounterCommand;
  147. public DelegateCommand ResetCounterCommand =>
  148. _ResetCounterCommand ?? (_ResetCounterCommand = new DelegateCommand(ExecuteResetCounterCommand).ObservesCanExecute(() => DoCondition).ObservesProperty(() => isCanExecute));
  149. private bool DoCondition
  150. {
  151. get { return isCanExecute; }
  152. }
  153. private DelegateCommand<string> _CopyCommand;
  154. public DelegateCommand<string> CopyCommand =>
  155. _CopyCommand ?? (_CopyCommand = new DelegateCommand<string>(ExecuteCopyCommand));
  156. #endregion
  157. #region 事件
  158. #endregion
  159. public HomeViewModel(IEventAggregator ea, IContainerProvider container, IProductService productService, IConfigService configService, IRemoteCommandService remoteCommandService
  160. , ISystemDatabaseService systemDatabaseService)
  161. {
  162. _eventAggregator = ea;
  163. _container = container;
  164. _productService = productService;
  165. LoadedCommand = new DelegateCommand(OnLoad);
  166. _eventAggregator.GetEvent<TaskMessageNotification>().Subscribe(AddMessageInvoke);
  167. //订阅权限登录事件
  168. _eventAggregator.GetEvent<UserLoginNotification>().Subscribe(LoginChange);
  169. management = _container.Resolve<Management>();
  170. _configService = configService;
  171. _productService.OnProductChanged += _productService_OnProductChanged;
  172. _remoteCommandService = remoteCommandService;
  173. _remoteCommandService.CycleTimingTicked += _remoteCommandService_CycleTimingTicked;
  174. _systemDatabaseService = systemDatabaseService;
  175. _eventAggregator.GetEvent<LockFinishNotification>().Subscribe(OnLockFinish);
  176. _eventAggregator.GetEvent<PressureFinishNotification>().Subscribe(OnPressureFinish);
  177. //获取所有的压力传感器配置,初始化曲线图
  178. var systemConfig = _configService.GetSystemConfiguration();
  179. if (systemConfig.PressureSensorConfig != null)
  180. {
  181. InitPressurePlots(systemConfig.PressureSensorConfig.ToArray());
  182. }
  183. }
  184. private void _remoteCommandService_CycleTimingTicked(object sender, TimeSpan e)
  185. {
  186. try
  187. {
  188. if (App.Current != null)
  189. {
  190. App.Current.Invoke(() =>
  191. {
  192. CTTotalSeconds = e.TotalSeconds;
  193. });
  194. }
  195. }
  196. catch (Exception)
  197. {
  198. }
  199. }
  200. #region 方法
  201. bool isFirst = true;
  202. private void OnLoad()
  203. {
  204. if (!isFirst)
  205. {
  206. return;
  207. }
  208. InitLockCurvePlotModel();
  209. isFirst = false;
  210. }
  211. async void ExecuteLoadProductCommand(ProductModel product)
  212. {
  213. if (product == null) return;
  214. var view = new ShowMessage(Lang.是否加载产品, $"{Lang.加载产品}:{product.Name}?");
  215. //show the dialog
  216. var result = await DialogHost.Show(view, "RootDialog", null, null, null);
  217. if (result != null && result is bool)
  218. {
  219. if (((bool)result))
  220. {
  221. IsLoadProduct = false;
  222. var waiting = new WaitingControl();
  223. //show the dialog
  224. var task = DialogHost.Show(waiting, "RootDialog", null, null, null);
  225. await _productService.LoadProductAsync(product.ID);
  226. _productService.SetCurrentProduct(product.ID);
  227. await management.WritePositionToPlcAsync();
  228. if (DialogHost.IsDialogOpen("RootDialog"))
  229. {
  230. DialogHost.Close("RootDialog");
  231. }
  232. await task;
  233. //DatabaseHelper.AddLoadProductRecord(product.ID, product.Name, false);
  234. IsLoadProduct = true;
  235. }
  236. }
  237. }
  238. void ExecuteCopyCommand(string textToCopy)
  239. {
  240. Clipboard.SetText(textToCopy);
  241. }
  242. /// <summary>
  243. /// 添加消息至消息队列
  244. /// </summary>
  245. /// <param name="msg"></param>
  246. /// <param name="color"></param>
  247. public void AddMessage(string msg, Color color)
  248. {
  249. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  250. try
  251. {
  252. MessageQueue.Add(new TaskMessage()
  253. {
  254. DT = DateTime.Now,
  255. Message = msg,
  256. FontColol = new SolidColorBrush(color)
  257. });
  258. LogHelper.WriteLogInfo(msg);
  259. }
  260. catch (Exception)
  261. {
  262. }
  263. }));
  264. }
  265. /// <summary>
  266. /// 添加消息至消息队列
  267. /// </summary>
  268. /// <param name="msg"></param>
  269. /// <param name="color"></param>
  270. public void AddMessage(string msg, MessageLevel level)
  271. {
  272. MessageStruct messageStruct = new MessageStruct() { Message = msg, level = level };
  273. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  274. AddMessage(messageStruct);
  275. }));
  276. }
  277. /// <summary>
  278. /// 添加消息至消息队列
  279. /// </summary>
  280. /// <param name="messageStruct"></param>
  281. public void AddMessage(MessageStruct messageStruct)
  282. {
  283. try
  284. {
  285. if (MessageQueue.Count >= 20)
  286. {
  287. MessageQueue.RemoveAt(0);// 从队列头部移除最早的消息
  288. }
  289. Color color = Colors.Black;
  290. switch (messageStruct.level)
  291. {
  292. case MessageLevel.Info:
  293. color = Colors.Black;
  294. break;
  295. case MessageLevel.Debug:
  296. color = Colors.Green;
  297. break;
  298. case MessageLevel.Alarm:
  299. color = Colors.Orange;
  300. break;
  301. case MessageLevel.Error:
  302. color = Colors.Red;
  303. break;
  304. }
  305. MessageQueue.Add(new TaskMessage()
  306. {
  307. DT = DateTime.Now,
  308. Message = messageStruct.Message,
  309. FontColol = new SolidColorBrush(color)
  310. });
  311. LogHelper.WriteLogInfo(messageStruct.Message);
  312. }
  313. catch (Exception)
  314. {
  315. }
  316. }
  317. public void AddMessageInvoke(MessageStruct messageStruct)
  318. {
  319. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  320. AddMessage(messageStruct);
  321. }));
  322. }
  323. private void LoginChange(Models.User user)
  324. {
  325. }
  326. /// <summary>
  327. /// 重置计数
  328. /// </summary>
  329. async void ExecuteResetCounterCommand()
  330. {
  331. if (management.CurrentProduct == null) return;
  332. var view = new ShowMessage(Lang.计数清零, Lang.是否重置当前产品的计数);
  333. //show the dialog
  334. var result = await DialogHost.Show(view, "RootDialog", null, null, null);
  335. if (result != null && result is bool)
  336. {
  337. if (((bool)result))
  338. {
  339. isCanExecute = false;
  340. await _systemDatabaseService.ResetProductionAsync(management.CurrentProduct.Name);
  341. isCanExecute = true;
  342. }
  343. }
  344. }
  345. //初始化曲线图
  346. private void InitLockCurvePlotModel()
  347. {
  348. var model = new PlotModel { Title = "锁付曲线", TitleFontSize = 16 };
  349. // 设置图例
  350. var legend = new Legend
  351. {
  352. LegendPosition = LegendPosition.TopRight,
  353. LegendPlacement = LegendPlacement.Outside,
  354. LegendOrientation = LegendOrientation.Vertical,
  355. LegendBorderThickness = 0
  356. };
  357. model.Legends.Add(legend);
  358. // 设置X轴
  359. var xAxis = new LinearAxis
  360. {
  361. Key = "X",
  362. Position = AxisPosition.Bottom,
  363. Title = "角度 (°)",
  364. Minimum = 0,
  365. MajorGridlineStyle = LineStyle.Solid,
  366. MinorGridlineStyle = LineStyle.Dot
  367. };
  368. model.Axes.Add(xAxis);
  369. // 设置Y轴
  370. var yAxis = new LinearAxis
  371. {
  372. Key = "Y",
  373. Position = AxisPosition.Left,
  374. Title = "力矩 (kgf)",
  375. MajorGridlineStyle = LineStyle.Solid,
  376. MinorGridlineStyle = LineStyle.Dot
  377. };
  378. model.Axes.Add(yAxis);
  379. // 添加示例数据系列
  380. var series = new LineSeries
  381. {
  382. Title = "锁付力矩曲线",
  383. StrokeThickness = 2,
  384. MarkerSize = 3,
  385. MarkerType = MarkerType.Circle,
  386. CanTrackerInterpolatePoints = false,
  387. };
  388. model.Series.Add(series);
  389. LockCurvePlotModel = model;
  390. }
  391. /// <summary>
  392. /// 螺丝锁付完成时调用
  393. /// </summary>
  394. /// <param name="result"></param>
  395. /// <exception cref="NotImplementedException"></exception>
  396. private void OnLockFinish(LockResult result)
  397. {
  398. //如果当前螺丝编号为1,则清除之前的结果
  399. if (result.Number == 1)
  400. {
  401. LockResults.Clear();
  402. }
  403. LockResults.Add(result);
  404. //更新曲线图
  405. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  406. var series = LockCurvePlotModel.Series[0] as LineSeries;
  407. //var yaxis = LockCurvePlotModel.Axes.FirstOrDefault(p=>p.Key=="Y");
  408. //yaxis.Maximum = result.TargetTorque;
  409. series.Points.Clear();
  410. foreach (var waveData in result.WaveDatas)
  411. {
  412. series.Points.Add(new OxyPlot.DataPoint(waveData.LockAngle, waveData.Torque));
  413. }
  414. LockCurvePlotModel.InvalidatePlot(true);
  415. }));
  416. }
  417. /// <summary>
  418. /// 保压完成时调用
  419. /// </summary>
  420. /// <param name="tuple"></param>
  421. private void OnPressureFinish((bool IsSuccess, int Index, (DateTime Timestamp, float Value)[] values, string SavePath) tuple)
  422. {
  423. //更新对应传感器的曲线图
  424. if (_sensorIdToIndex.TryGetValue(tuple.Index.ToString(), out int index))
  425. {
  426. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  427. var model = PressurePlotModels[index];
  428. var series = model.Series[0] as LineSeries;
  429. series.Points.Clear();
  430. //第一个点的时间作为X轴起点
  431. DateTime xAxisStart = tuple.values[0].Timestamp;
  432. foreach (var dataPoint in tuple.values)
  433. {
  434. // 计算相对于起点的秒数作为X轴坐标
  435. double xValue = (dataPoint.Timestamp - xAxisStart).TotalSeconds;
  436. series.Points.Add(new OxyPlot.DataPoint(xValue, dataPoint.Value));
  437. }
  438. model.InvalidatePlot(true);
  439. if (!string.IsNullOrEmpty(tuple.SavePath))
  440. {
  441. if (!Directory.Exists(Path.GetDirectoryName(tuple.SavePath)))
  442. {
  443. Directory.CreateDirectory(Path.GetDirectoryName(tuple.SavePath));
  444. }
  445. PngExporter.Export(model, tuple.SavePath, (int)model.Width, (int)model.Height);
  446. }
  447. }));
  448. }
  449. }
  450. // 初始化由配置决定的曲线数量(在读取 SystemConfiguration 后调用)
  451. public void InitPressurePlots(IEnumerable<PressureSensorSettings> sensors)
  452. {
  453. PressurePlotModels.Clear();
  454. _sensorIdToIndex.Clear();
  455. int idx = 0;
  456. foreach (var s in sensors)
  457. {
  458. var model = CreatePlotModelForSensor(s);
  459. PressurePlotModels.Add(model);
  460. // 假设 PressureSensorConfig 有唯一 Id(string 或 int)
  461. _sensorIdToIndex[s.SensorId.ToString()] = idx++;
  462. }
  463. }
  464. private PlotModel CreatePlotModelForSensor(PressureSensorSettings sensor)
  465. {
  466. var model = new PlotModel { Title = sensor.SensorName ?? $"Sensor {sensor.SensorId}", TitleFontSize = 16 };
  467. // 设置图例
  468. var legend = new Legend
  469. {
  470. LegendPosition = LegendPosition.TopRight,
  471. LegendPlacement = LegendPlacement.Outside,
  472. LegendOrientation = LegendOrientation.Vertical,
  473. LegendBorderThickness = 0
  474. };
  475. model.Legends.Add(legend);
  476. // 设置X轴
  477. var xAxis = new LinearAxis
  478. {
  479. Key = "X",
  480. Position = AxisPosition.Bottom,
  481. Title = "Time (s)",
  482. Minimum = 0,
  483. MajorGridlineStyle = LineStyle.Solid,
  484. MinorGridlineStyle = LineStyle.Dot
  485. };
  486. model.Axes.Add(xAxis);
  487. // 设置Y轴
  488. var yAxis = new LinearAxis
  489. {
  490. Key = "Y",
  491. Position = AxisPosition.Left,
  492. Title = "Pressure",
  493. MajorGridlineStyle = LineStyle.Solid,
  494. MinorGridlineStyle = LineStyle.Dot
  495. };
  496. model.Axes.Add(yAxis);
  497. // 添加示例数据系列
  498. var series = new LineSeries
  499. {
  500. Title = sensor.SensorName ?? $"Sensor {sensor.SensorId}",
  501. StrokeThickness = 2,
  502. MarkerSize = 3,
  503. MarkerType = MarkerType.Circle,
  504. CanTrackerInterpolatePoints = false,
  505. };
  506. model.Series.Add(series);
  507. return model;
  508. }
  509. #endregion
  510. #region 继承
  511. /// <summary>
  512. /// 确认导航请求时调用。此方法允许您在导航之前执行一些操作。
  513. /// </summary>
  514. /// <param name="navigationContext"></param>
  515. /// <param name="continuationCallback"></param>
  516. public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
  517. {
  518. continuationCallback(true);
  519. }
  520. /// <summary>
  521. /// 接收导航请求时调用。传入导航参数,包含有关导航目标的信息。
  522. /// </summary>
  523. /// <param name="navigationContext"></param>
  524. /// <exception cref="NotImplementedException"></exception>
  525. public async void OnNavigatedTo(NavigationContext navigationContext)
  526. {
  527. try
  528. {
  529. ProductList = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
  530. }
  531. catch (Exception ex)
  532. {
  533. LogHelper.WriteLogError("主界面界面进入时出错!", ex);
  534. }
  535. }
  536. /// <summary>
  537. /// 是否允许导航到此视图模型。
  538. /// </summary>
  539. /// <param name="navigationContext"></param>
  540. /// <returns></returns>
  541. public bool IsNavigationTarget(NavigationContext navigationContext)
  542. {
  543. return true;
  544. }
  545. /// <summary>
  546. /// 导航离开此视图模型时调用。您可以在此处执行清理操作或保存状态。
  547. /// </summary>
  548. /// <param name="navigationContext"></param>
  549. public void OnNavigatedFrom(NavigationContext navigationContext)
  550. {
  551. }
  552. #endregion
  553. private void _productService_OnProductChanged(ProductModel obj)
  554. {
  555. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  556. CurrentProduct = obj;
  557. }));
  558. }
  559. }
  560. }