HomeViewModel.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  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 Prism.Services.Dialogs;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Collections.ObjectModel;
  18. using System.IO;
  19. using System.Linq;
  20. using System.Threading.Tasks;
  21. using System.Windows;
  22. using System.Windows.Media;
  23. using TeamAAS_VP;
  24. using TeamAAS_VP.Controls;
  25. using TeamAAS_VP.Core;
  26. using TeamAAS_VP.Data;
  27. using TeamAAS_VP.Enums;
  28. using TeamAAS_VP.Events;
  29. using TeamAAS_VP.Interfaces;
  30. using TeamAAS_VP.Models;
  31. using TeamAAS_VP.Resources.Languages;
  32. using TeamAAS_VP.Services;
  33. using TeamAAS_VP.ViewModels.DebugMod;
  34. using TeamAAS_VP.Views.DebugMod;
  35. using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
  36. using static TeamAAS_VP.Models.SystemConfiguration;
  37. namespace TeamAAS_VP.ViewModels
  38. {
  39. public class HomeViewModel : BindableBase, IConfirmNavigationRequest
  40. {
  41. IEventAggregator _eventAggregator;
  42. IContainerProvider _container;
  43. IProductService _productService;
  44. IConfigService _configService;
  45. IRemoteCommandService _remoteCommandService;
  46. ISystemDatabaseService _systemDatabaseService;
  47. IDialogService _dialogService;
  48. #region 属性
  49. private PlotModel _PressurePlotModel = new PlotModel();
  50. /// <summary>
  51. /// 每个元素是一个 PlotModel,对应一个压力传感器
  52. /// </summary>
  53. public PlotModel PressurePlotModel
  54. {
  55. get { return _PressurePlotModel; }
  56. set { SetProperty(ref _PressurePlotModel, value); }
  57. }
  58. private ObservableCollection<TaskMessage> messageQueue = new ObservableCollection<TaskMessage>();
  59. /// <summary>
  60. /// 运行信息队列
  61. /// </summary>
  62. public ObservableCollection<TaskMessage> MessageQueue
  63. {
  64. get { return messageQueue; }
  65. set { SetProperty(ref messageQueue, value); }
  66. }
  67. private ObservableCollection<ProductModel> _ProductList;
  68. public ObservableCollection<ProductModel> ProductList
  69. {
  70. get { return _ProductList; }
  71. set { SetProperty(ref _ProductList, value); }
  72. }
  73. private Management _management;
  74. public Management management
  75. {
  76. get { return _management; }
  77. set { SetProperty(ref _management, value); }
  78. }
  79. private double _CTTotalSeconds;
  80. public double CTTotalSeconds
  81. {
  82. get { return _CTTotalSeconds; }
  83. set { SetProperty(ref _CTTotalSeconds, value); }
  84. }
  85. private ProductModel _SelectProduct;
  86. public ProductModel SelectProduct
  87. {
  88. get { return _SelectProduct; }
  89. set { SetProperty(ref _SelectProduct, value); }
  90. }
  91. private bool CanLoad
  92. {
  93. get
  94. {
  95. if (SelectProduct != null && IsLoadProduct)
  96. {
  97. return true;
  98. }
  99. else
  100. {
  101. return false;
  102. }
  103. }
  104. }
  105. private bool _IsLoadProduct = true;
  106. public bool IsLoadProduct
  107. {
  108. get { return _IsLoadProduct; }
  109. set { SetProperty(ref _IsLoadProduct, value); }
  110. }
  111. private bool _isCanExecute = true;
  112. public bool isCanExecute
  113. {
  114. get { return _isCanExecute; }
  115. set { SetProperty(ref _isCanExecute, value); }
  116. }
  117. private ProductModel _CurrentProduct;
  118. public ProductModel CurrentProduct
  119. {
  120. get { return _CurrentProduct; }
  121. set { SetProperty(ref _CurrentProduct, value); }
  122. }
  123. private ObservableCollection<PlotModel> _PressurePlotModels = new ObservableCollection<PlotModel>();
  124. /// <summary>
  125. /// 每个元素是一个 PlotModel,对应一个压力传感器
  126. /// </summary>
  127. public ObservableCollection<PlotModel> PressurePlotModels
  128. {
  129. get { return _PressurePlotModels; }
  130. set { SetProperty(ref _PressurePlotModels, value); }
  131. }
  132. private PlotModel _LockCurvePlotModel;
  133. /// <summary>
  134. /// 锁付曲线
  135. /// </summary>
  136. public PlotModel LockCurvePlotModel
  137. {
  138. get { return _LockCurvePlotModel; }
  139. set { SetProperty(ref _LockCurvePlotModel, value); }
  140. }
  141. private ObservableCollection<LockResult> _LockResults = new ObservableCollection<LockResult>();
  142. /// <summary>
  143. /// 锁付结果列表
  144. /// </summary>
  145. public ObservableCollection<LockResult> LockResults
  146. {
  147. get { return _LockResults; }
  148. set { SetProperty(ref _LockResults, value); }
  149. }
  150. private bool _IsAllowEdit = false;
  151. public bool IsAllowEdit
  152. {
  153. get { return _IsAllowEdit; }
  154. set { SetProperty(ref _IsAllowEdit, value); }
  155. }
  156. // 可选:记录传感器 Id -> 索引 的映射,便于外部(如 Management)按 Id 更新
  157. private readonly Dictionary<string, int> _sensorIdToIndex = new Dictionary<string, int>();
  158. #endregion
  159. #region 命令
  160. public DelegateCommand LoadedCommand { get; set; }
  161. private DelegateCommand<ProductModel> _LoadProductCommand;
  162. public DelegateCommand<ProductModel> LoadProductCommand =>
  163. _LoadProductCommand ?? (_LoadProductCommand = new DelegateCommand<ProductModel>(ExecuteLoadProductCommand).ObservesCanExecute(() => CanLoad).ObservesProperty(() => SelectProduct).ObservesProperty(() => IsLoadProduct));
  164. private DelegateCommand _ResetCounterCommand;
  165. public DelegateCommand ResetCounterCommand =>
  166. _ResetCounterCommand ?? (_ResetCounterCommand = new DelegateCommand(ExecuteResetCounterCommand).ObservesCanExecute(() => DoCondition).ObservesProperty(() => isCanExecute));
  167. private bool DoCondition
  168. {
  169. get { return isCanExecute; }
  170. }
  171. private DelegateCommand<string> _CopyCommand;
  172. public DelegateCommand<string> CopyCommand =>
  173. _CopyCommand ?? (_CopyCommand = new DelegateCommand<string>(ExecuteCopyCommand));
  174. private DelegateCommand _TorqueInspectionCommand;
  175. public DelegateCommand TorqueInspectionCommand =>
  176. _TorqueInspectionCommand ?? (_TorqueInspectionCommand = new DelegateCommand(ExecuteTorqueInspectionCommand));
  177. //更换吸嘴
  178. private DelegateCommand _ChangeNozzleCommand;
  179. public DelegateCommand ChangeNozzleCommand =>
  180. _ChangeNozzleCommand ?? (_ChangeNozzleCommand = new DelegateCommand(ExecuteChangeNozzleCommand));
  181. //更换披头
  182. private DelegateCommand _ChangeHeaderCommand;
  183. public DelegateCommand ChangeHeaderCommand =>
  184. _ChangeHeaderCommand ?? (_ChangeHeaderCommand = new DelegateCommand(ExecuteChangeHeaderCommand));
  185. //添加螺丝
  186. private DelegateCommand _AddScrewCommand;
  187. public DelegateCommand AddScrewCommand =>
  188. _AddScrewCommand ?? (_AddScrewCommand = new DelegateCommand(ExecuteAddScrewCommand));
  189. private DelegateCommand _SetAlarmValueCommand;
  190. public DelegateCommand SetAlarmValueCommand =>
  191. _SetAlarmValueCommand ?? (_SetAlarmValueCommand = new DelegateCommand(ExecuteSetAlarmValueCommand));
  192. #endregion
  193. #region 事件
  194. #endregion
  195. public HomeViewModel(IEventAggregator ea, IContainerProvider container, IProductService productService, IConfigService configService, IRemoteCommandService remoteCommandService
  196. , ISystemDatabaseService systemDatabaseService, IDialogService dialogService)
  197. {
  198. _eventAggregator = ea;
  199. _container = container;
  200. _dialogService = dialogService;
  201. _productService = productService;
  202. LoadedCommand = new DelegateCommand(OnLoad);
  203. _eventAggregator.GetEvent<TaskMessageNotification>().Subscribe(AddMessageInvoke);
  204. //订阅权限登录事件
  205. _eventAggregator.GetEvent<UserLoginNotification>().Subscribe(LoginChange);
  206. management = _container.Resolve<Management>();
  207. _configService = configService;
  208. _productService.OnProductChanged += _productService_OnProductChanged;
  209. _remoteCommandService = remoteCommandService;
  210. _remoteCommandService.CycleTimingTicked += _remoteCommandService_CycleTimingTicked;
  211. _systemDatabaseService = systemDatabaseService;
  212. _eventAggregator.GetEvent<LockFinishNotification>().Subscribe(OnLockFinish);
  213. _eventAggregator.GetEvent<PressureFinishNotification>().Subscribe(OnPressureFinish);
  214. InitPressurePlots();
  215. //获取所有的压力和温度传感器配置,初始化曲线图
  216. var systemConfig = _configService.GetSystemConfiguration();
  217. if (systemConfig.PressureSensorConfig != null)
  218. {
  219. InitPressurePlots(systemConfig.PressureSensorConfig.ToArray());
  220. }
  221. }
  222. private void _remoteCommandService_CycleTimingTicked(object sender, TimeSpan e)
  223. {
  224. try
  225. {
  226. if (App.Current != null)
  227. {
  228. App.Current.Invoke(() =>
  229. {
  230. CTTotalSeconds = e.TotalSeconds;
  231. });
  232. }
  233. }
  234. catch (Exception)
  235. {
  236. }
  237. }
  238. #region 方法
  239. bool isFirst = true;
  240. private void OnLoad()
  241. {
  242. if (!isFirst)
  243. {
  244. return;
  245. }
  246. InitLockCurvePlotModel();
  247. isFirst = false;
  248. if (_systemDatabaseService.GetCurrentUser().userPart == Enums.UserPart.Operator)
  249. {
  250. IsAllowEdit = false;
  251. }
  252. else
  253. {
  254. IsAllowEdit = true;
  255. }
  256. }
  257. async void ExecuteLoadProductCommand(ProductModel product)
  258. {
  259. if (product == null) return;
  260. var view = new ShowMessage(Lang.是否加载产品, $"{Lang.加载产品}:{product.Name}?");
  261. //show the dialog
  262. var result = await DialogHost.Show(view, "RootDialog", null, null, null);
  263. if (result != null && result is bool)
  264. {
  265. if (((bool)result))
  266. {
  267. IsLoadProduct = false;
  268. var waiting = new WaitingControl();
  269. //show the dialog
  270. var task = DialogHost.Show(waiting, "RootDialog", null, null, null);
  271. await _productService.LoadProductAsync(product.ID);
  272. _productService.SetCurrentProduct(product.ID);
  273. await management.WriteParameterToPlcExAsync();
  274. if (DialogHost.IsDialogOpen("RootDialog"))
  275. {
  276. DialogHost.Close("RootDialog");
  277. }
  278. await task;
  279. //DatabaseHelper.AddLoadProductRecord(product.ID, product.Name, false);
  280. IsLoadProduct = true;
  281. }
  282. }
  283. }
  284. void ExecuteCopyCommand(string textToCopy)
  285. {
  286. Clipboard.SetText(textToCopy);
  287. }
  288. /// <summary>
  289. /// 添加消息至消息队列
  290. /// </summary>
  291. /// <param name="msg"></param>
  292. /// <param name="color"></param>
  293. public void AddMessage(string msg, Color color)
  294. {
  295. App.Current.Dispatcher.BeginInvoke(new Action(() =>
  296. {
  297. try
  298. {
  299. MessageQueue.Add(new TaskMessage()
  300. {
  301. DT = DateTime.Now,
  302. Message = msg,
  303. FontColol = new SolidColorBrush(color)
  304. });
  305. LogHelper.WriteLogInfo(msg);
  306. }
  307. catch (Exception)
  308. {
  309. }
  310. }));
  311. }
  312. /// <summary>
  313. /// 添加消息至消息队列
  314. /// </summary>
  315. /// <param name="msg"></param>
  316. /// <param name="color"></param>
  317. public void AddMessage(string msg, MessageLevel level)
  318. {
  319. MessageStruct messageStruct = new MessageStruct() { Message = msg, level = level };
  320. App.Current.Dispatcher.BeginInvoke(new Action(() =>
  321. {
  322. AddMessage(messageStruct);
  323. }));
  324. }
  325. /// <summary>
  326. /// 添加消息至消息队列
  327. /// </summary>
  328. /// <param name="messageStruct"></param>
  329. public void AddMessage(MessageStruct messageStruct)
  330. {
  331. try
  332. {
  333. if (MessageQueue.Count >= 100)
  334. {
  335. MessageQueue.RemoveAt(0);// 从队列头部移除最早的消息
  336. }
  337. Color color = Colors.Black;
  338. switch (messageStruct.level)
  339. {
  340. case MessageLevel.Info:
  341. color = Colors.Black;
  342. break;
  343. case MessageLevel.Debug:
  344. color = Colors.Green;
  345. break;
  346. case MessageLevel.Alarm:
  347. color = Colors.Orange;
  348. break;
  349. case MessageLevel.Error:
  350. color = Colors.Red;
  351. break;
  352. }
  353. MessageQueue.Add(new TaskMessage()
  354. {
  355. DT = DateTime.Now,
  356. Message = messageStruct.Message,
  357. FontColol = new SolidColorBrush(color)
  358. });
  359. LogHelper.WriteLogInfo(messageStruct.Message);
  360. }
  361. catch (Exception)
  362. {
  363. }
  364. }
  365. public void AddMessageInvoke(MessageStruct messageStruct)
  366. {
  367. App.Current.Dispatcher.BeginInvoke(new Action(() =>
  368. {
  369. AddMessage(messageStruct);
  370. }));
  371. }
  372. private void LoginChange(Models.User user)
  373. {
  374. if (user.userPart == Enums.UserPart.Operator)
  375. {
  376. IsAllowEdit = false;
  377. }
  378. else
  379. {
  380. IsAllowEdit = true;
  381. }
  382. }
  383. /// <summary>
  384. /// 重置计数
  385. /// </summary>
  386. async void ExecuteResetCounterCommand()
  387. {
  388. var currentProduct = _productService.GetCurrentProduct();
  389. if (currentProduct == null) return;
  390. var view = new ShowMessage(Lang.计数清零, Lang.是否重置当前产品的计数);
  391. //show the dialog
  392. var result = await DialogHost.Show(view, "RootDialog", null, null, null);
  393. if (result != null && result is bool)
  394. {
  395. if (((bool)result))
  396. {
  397. isCanExecute = false;
  398. await _systemDatabaseService.ResetProductionAsync(currentProduct.Name);
  399. await _systemDatabaseService.ResetThrowNumberAsync();
  400. isCanExecute = true;
  401. }
  402. }
  403. }
  404. /// <summary>
  405. /// 初始化曲线图
  406. /// </summary>
  407. private void InitLockCurvePlotModel()
  408. {
  409. var model = new PlotModel
  410. {
  411. Title = Lang.锁付曲线,
  412. TitleFontSize = 16
  413. };
  414. // 图例
  415. var legend = new Legend
  416. {
  417. LegendPosition = LegendPosition.TopRight,
  418. LegendPlacement = LegendPlacement.Outside,
  419. LegendOrientation = LegendOrientation.Vertical,
  420. LegendBorderThickness = 0
  421. };
  422. model.Legends.Add(legend);
  423. // X轴(圈数)
  424. var xAxis = new LinearAxis
  425. {
  426. Key = "X",
  427. Position = AxisPosition.Bottom,
  428. Title = Lang.锁付圈数,
  429. Minimum = 0,
  430. MajorGridlineStyle = LineStyle.Solid,
  431. MinorGridlineStyle = LineStyle.Dot
  432. };
  433. model.Axes.Add(xAxis);
  434. // Y轴(力矩)
  435. var yAxis = new LinearAxis
  436. {
  437. Key = "Y",
  438. Position = AxisPosition.Left,
  439. Title = Lang.力矩kgf,
  440. MajorGridlineStyle = LineStyle.Solid,
  441. MinorGridlineStyle = LineStyle.Dot
  442. };
  443. model.Axes.Add(yAxis);
  444. // 实际锁付曲线
  445. var torqueSeries = new LineSeries
  446. {
  447. Title = Lang.锁付力矩曲线,
  448. StrokeThickness = 2,
  449. MarkerSize = 3,
  450. MarkerType = MarkerType.Circle,
  451. CanTrackerInterpolatePoints = false,
  452. Color = OxyColors.Blue
  453. };
  454. model.Series.Add(torqueSeries);
  455. // 上限线
  456. var upperLimitSeries = new LineSeries
  457. {
  458. Title = "Torque Upper Limit",
  459. StrokeThickness = 2,
  460. LineStyle = LineStyle.Dash,
  461. Color = OxyColors.Red
  462. };
  463. model.Series.Add(upperLimitSeries);
  464. // 下限线
  465. var lowerLimitSeries = new LineSeries
  466. {
  467. Title = "Torque Lower Limit",
  468. StrokeThickness = 2,
  469. LineStyle = LineStyle.Dash,
  470. Color = OxyColors.Green
  471. };
  472. model.Series.Add(lowerLimitSeries);
  473. LockCurvePlotModel = model;
  474. }
  475. /// <summary>
  476. /// 螺丝锁付完成时调用
  477. /// </summary>
  478. /// <param name="result"></param>
  479. private void OnLockFinish(LockResult result)
  480. {
  481. //如果当前螺丝编号为1,则清除之前的结果
  482. if (result.Number == 1)
  483. {
  484. LockResults.Clear();
  485. }
  486. LockResults.Add(result);
  487. App.Current.Dispatcher.BeginInvoke(new Action(() =>
  488. {
  489. try
  490. {
  491. //获取三条曲线
  492. var torqueSeries = LockCurvePlotModel.Series[0] as LineSeries; //实际扭矩
  493. var upperSeries = LockCurvePlotModel.Series[1] as LineSeries; //上限
  494. var lowerSeries = LockCurvePlotModel.Series[2] as LineSeries; //下限
  495. torqueSeries.Points.Clear();
  496. upperSeries.Points.Clear();
  497. lowerSeries.Points.Clear();
  498. //上下限值(根据你的工艺设置)
  499. double upperLimit = result.TargetTorqueUpperLimit; //上限扭矩
  500. double lowerLimit = result.TargetTorqueLowerLimit; //下限扭矩
  501. foreach (var waveData in result.WaveDatas)
  502. {
  503. //实际曲线
  504. torqueSeries.Points.Add(new OxyPlot.DataPoint(waveData.Turns, waveData.Torque));
  505. //上限曲线(固定扭矩)
  506. upperSeries.Points.Add(new OxyPlot.DataPoint(waveData.Turns, upperLimit));
  507. //下限曲线
  508. lowerSeries.Points.Add(new OxyPlot.DataPoint(waveData.Turns, lowerLimit));
  509. }
  510. //刷新
  511. LockCurvePlotModel.ResetAllAxes();
  512. LockCurvePlotModel.InvalidatePlot(true);
  513. //保存图片
  514. if (!string.IsNullOrEmpty(result.LockCurveImagePath))
  515. {
  516. PngExporter.Export(
  517. LockCurvePlotModel,
  518. result.LockCurveImagePath,
  519. (int)LockCurvePlotModel.Width,
  520. (int)LockCurvePlotModel.Height);
  521. }
  522. }
  523. catch (Exception ex)
  524. {
  525. LogHelper.WriteLogError("更新曲线图和保存曲线图时出错!", ex);
  526. }
  527. }));
  528. }
  529. /// <summary>
  530. /// 添加螺丝
  531. /// </summary>
  532. private void ExecuteAddScrewCommand()
  533. {
  534. _dialogService.ShowDialog("AddScrew", rst =>
  535. {
  536. //对话框关闭之后的回调函数,可以在这解析结果。
  537. ButtonResult result1 = rst.Result;
  538. if (result1 == ButtonResult.OK)
  539. {
  540. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  541. }
  542. });
  543. }
  544. /// <summary>
  545. /// 更换披头
  546. /// </summary>
  547. void ExecuteChangeHeaderCommand()
  548. {
  549. _dialogService.ShowDialog("ChangeHeader", rst =>
  550. {
  551. //对话框关闭之后的回调函数,可以在这解析结果。
  552. ButtonResult result1 = rst.Result;
  553. if (result1 == ButtonResult.OK)
  554. {
  555. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  556. }
  557. });
  558. }
  559. /// <summary>
  560. /// 更换吸嘴
  561. /// </summary>
  562. void ExecuteChangeNozzleCommand()
  563. {
  564. _dialogService.ShowDialog("ChangeNozzle", rst =>
  565. {
  566. //对话框关闭之后的回调函数,可以在这解析结果。
  567. ButtonResult result1 = rst.Result;
  568. if (result1 == ButtonResult.OK)
  569. {
  570. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  571. }
  572. });
  573. //management.Test();
  574. }
  575. void ExecuteTorqueInspectionCommand()
  576. {
  577. _dialogService.ShowDialog("TorqueCheck", rst =>
  578. {
  579. //对话框关闭之后的回调函数,可以在这解析结果。
  580. ButtonResult result1 = rst.Result;
  581. if (result1 == ButtonResult.OK)
  582. {
  583. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  584. }
  585. });
  586. }
  587. void ExecuteSetAlarmValueCommand()
  588. {
  589. _dialogService.ShowDialog("SetAlarmValue", rst =>
  590. {
  591. //对话框关闭之后的回调函数,可以在这解析结果。
  592. ButtonResult result1 = rst.Result;
  593. if (result1 == ButtonResult.OK)
  594. {
  595. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  596. }
  597. });
  598. }
  599. /// <summary>
  600. /// 保压完成时调用
  601. /// </summary>
  602. /// <param name="tuple"></param>
  603. private void OnPressureFinish((bool IsSuccess, (DateTime Timestamp, float Value)[] values, string SavePath) tuple)
  604. {
  605. //更新对应传感器的曲线图
  606. //App.Current.Dispatcher.BeginInvoke(new Action(() =>
  607. //{
  608. // var model = PressurePlotModel;
  609. // var series = model.Series[0] as LineSeries;
  610. // series.Points.Clear();
  611. // //第一个点的时间作为X轴起点
  612. // DateTime xAxisStart = tuple.values[0].Timestamp;
  613. // foreach (var dataPoint in tuple.values)
  614. // {
  615. // // 计算相对于起点的秒数作为X轴坐标
  616. // double xValue = (dataPoint.Timestamp - xAxisStart).TotalSeconds;
  617. // series.Points.Add(new OxyPlot.DataPoint(xValue, dataPoint.Value));
  618. // }
  619. // // 重置所有轴的范围以适应新数据
  620. // model.ResetAllAxes();
  621. // model.InvalidatePlot(true);
  622. // if (!string.IsNullOrEmpty(tuple.SavePath))
  623. // {
  624. // if (!Directory.Exists(Path.GetDirectoryName(tuple.SavePath)))
  625. // {
  626. // Directory.CreateDirectory(Path.GetDirectoryName(tuple.SavePath));
  627. // }
  628. // PngExporter.Export(model, tuple.SavePath, (int)model.Width, (int)model.Height);
  629. // }
  630. //}));
  631. }
  632. // 初始化由配置决定的曲线数量(在读取 SystemConfiguration 后调用)
  633. public void InitPressurePlots()
  634. {
  635. var model = CreatePlotModelForSensor();
  636. PressurePlotModel = model;
  637. }
  638. private PlotModel CreatePlotModelForSensor()
  639. {
  640. var model = new PlotModel { Title = $"压力曲线", TitleFontSize = 16 };
  641. // 设置图例
  642. var legend = new Legend
  643. {
  644. LegendPosition = LegendPosition.TopRight,
  645. LegendPlacement = LegendPlacement.Outside,
  646. LegendOrientation = LegendOrientation.Vertical,
  647. LegendBorderThickness = 0
  648. };
  649. model.Legends.Add(legend);
  650. // 设置X轴
  651. var xAxis = new LinearAxis
  652. {
  653. Key = "X",
  654. Position = AxisPosition.Bottom,
  655. Title = "Time (s)",
  656. Minimum = 0,
  657. MajorGridlineStyle = LineStyle.Solid,
  658. MinorGridlineStyle = LineStyle.Dot
  659. };
  660. model.Axes.Add(xAxis);
  661. // 设置Y轴
  662. var yAxis = new LinearAxis
  663. {
  664. Key = "Y",
  665. Position = AxisPosition.Left,
  666. Title = "Pressure",
  667. MajorGridlineStyle = LineStyle.Solid,
  668. MinorGridlineStyle = LineStyle.Dot
  669. };
  670. model.Axes.Add(yAxis);
  671. // 添加示例数据系列
  672. var series = new LineSeries
  673. {
  674. Title = $"Sensor 1",
  675. StrokeThickness = 2,
  676. MarkerSize = 3,
  677. MarkerType = MarkerType.Circle,
  678. CanTrackerInterpolatePoints = false,
  679. };
  680. model.Series.Add(series);
  681. return model;
  682. }
  683. /// <summary>
  684. /// 保压完成时调用
  685. /// </summary>
  686. /// <param name="tuple"></param>
  687. private void OnPressureFinish((bool IsSuccess, int Index, (DateTime Timestamp, float Value)[] values, string SavePath) tuple)
  688. {
  689. //更新对应传感器的曲线图
  690. if (_sensorIdToIndex.TryGetValue(tuple.Index.ToString(), out int index))
  691. {
  692. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  693. var model = PressurePlotModels[index];
  694. var series = model.Series[0] as LineSeries;
  695. series.Points.Clear();
  696. //第一个点的时间作为X轴起点
  697. DateTime xAxisStart = tuple.values[0].Timestamp;
  698. foreach (var dataPoint in tuple.values)
  699. {
  700. // 计算相对于起点的秒数作为X轴坐标
  701. double xValue = (dataPoint.Timestamp - xAxisStart).TotalSeconds;
  702. series.Points.Add(new OxyPlot.DataPoint(xValue, dataPoint.Value));
  703. }
  704. // 重置所有轴的范围以适应新数据
  705. model.ResetAllAxes();
  706. model.InvalidatePlot(true);
  707. if (!string.IsNullOrEmpty(tuple.SavePath))
  708. {
  709. if (!Directory.Exists(Path.GetDirectoryName(tuple.SavePath)))
  710. {
  711. Directory.CreateDirectory(Path.GetDirectoryName(tuple.SavePath));
  712. }
  713. PngExporter.Export(model, tuple.SavePath, (int)model.Width, (int)model.Height);
  714. }
  715. }));
  716. }
  717. }
  718. // 初始化由配置决定的曲线数量(在读取 SystemConfiguration 后调用)
  719. public void InitPressurePlots(IEnumerable<PressureSensorSettings> sensors)
  720. {
  721. PressurePlotModels.Clear();
  722. _sensorIdToIndex.Clear();
  723. int idx = 0;
  724. foreach (var s in sensors)
  725. {
  726. var model = CreatePlotModelForSensor(s);
  727. PressurePlotModels.Add(model);
  728. // 假设 PressureSensorConfig 有唯一 Id(string 或 int)
  729. _sensorIdToIndex[s.SensorId.ToString()] = idx++;
  730. }
  731. }
  732. private PlotModel CreatePlotModelForSensor(PressureSensorSettings sensor)
  733. {
  734. var model = new PlotModel { Title = sensor.SensorName ?? $"Sensor {sensor.SensorId}", TitleFontSize = 16 };
  735. // 设置图例
  736. var legend = new Legend
  737. {
  738. LegendPosition = LegendPosition.TopRight,
  739. LegendPlacement = LegendPlacement.Outside,
  740. LegendOrientation = LegendOrientation.Vertical,
  741. LegendBorderThickness = 0
  742. };
  743. model.Legends.Add(legend);
  744. // 设置X轴
  745. var xAxis = new LinearAxis
  746. {
  747. Key = "X",
  748. Position = AxisPosition.Bottom,
  749. Title = "Time (s)",
  750. Minimum = 0,
  751. MajorGridlineStyle = LineStyle.Solid,
  752. MinorGridlineStyle = LineStyle.Dot
  753. };
  754. model.Axes.Add(xAxis);
  755. // 设置Y轴
  756. var yAxis = new LinearAxis
  757. {
  758. Key = "Y",
  759. Position = AxisPosition.Left,
  760. Title = sensor.SensorName.Contains("压力") ?"Pressure": "Temperature",
  761. MajorGridlineStyle = LineStyle.Solid,
  762. MinorGridlineStyle = LineStyle.Dot
  763. };
  764. model.Axes.Add(yAxis);
  765. // 添加示例数据系列
  766. var series = new LineSeries
  767. {
  768. Title = sensor.SensorName ?? $"Sensor {sensor.SensorId}",
  769. StrokeThickness = 2,
  770. MarkerSize = 3,
  771. MarkerType = MarkerType.Circle,
  772. CanTrackerInterpolatePoints = false,
  773. };
  774. model.Series.Add(series);
  775. return model;
  776. }
  777. #endregion
  778. #region 继承
  779. /// <summary>
  780. /// 确认导航请求时调用。此方法允许您在导航之前执行一些操作。
  781. /// </summary>
  782. /// <param name="navigationContext"></param>
  783. /// <param name="continuationCallback"></param>
  784. public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
  785. {
  786. continuationCallback(true);
  787. }
  788. /// <summary>
  789. /// 接收导航请求时调用。传入导航参数,包含有关导航目标的信息。
  790. /// </summary>
  791. /// <param name="navigationContext"></param>
  792. /// <exception cref="NotImplementedException"></exception>
  793. public async void OnNavigatedTo(NavigationContext navigationContext)
  794. {
  795. try
  796. {
  797. ProductList = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
  798. }
  799. catch (Exception ex)
  800. {
  801. LogHelper.WriteLogError(Lang.主界面界面进入时出错, ex);
  802. }
  803. }
  804. /// <summary>
  805. /// 是否允许导航到此视图模型。
  806. /// </summary>
  807. /// <param name="navigationContext"></param>
  808. /// <returns></returns>
  809. public bool IsNavigationTarget(NavigationContext navigationContext)
  810. {
  811. return true;
  812. }
  813. /// <summary>
  814. /// 导航离开此视图模型时调用。您可以在此处执行清理操作或保存状态。
  815. /// </summary>
  816. /// <param name="navigationContext"></param>
  817. public void OnNavigatedFrom(NavigationContext navigationContext)
  818. {
  819. }
  820. #endregion
  821. private void _productService_OnProductChanged(ProductModel obj)
  822. {
  823. App.Current.Dispatcher.BeginInvoke(new Action(() =>
  824. {
  825. CurrentProduct = obj;
  826. }));
  827. }
  828. }
  829. }