HomeViewModel.cs 28 KB

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