HomeViewModel.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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 ObservableCollection<TaskMessage> messageQueue=new ObservableCollection<TaskMessage>();
  49. /// <summary>
  50. /// 运行信息队列
  51. /// </summary>
  52. public ObservableCollection<TaskMessage> MessageQueue
  53. {
  54. get { return messageQueue; }
  55. set { SetProperty(ref messageQueue,value); }
  56. }
  57. private ObservableCollection<ProductModel> _ProductList;
  58. public ObservableCollection<ProductModel> ProductList
  59. {
  60. get { return _ProductList; }
  61. set { SetProperty(ref _ProductList, value); }
  62. }
  63. private Management _management;
  64. public Management management
  65. {
  66. get { return _management; }
  67. set { SetProperty(ref _management, value); }
  68. }
  69. private double _CTTotalSeconds;
  70. public double CTTotalSeconds
  71. {
  72. get { return _CTTotalSeconds; }
  73. set { SetProperty(ref _CTTotalSeconds, value); }
  74. }
  75. private ProductModel _SelectProduct;
  76. public ProductModel SelectProduct
  77. {
  78. get { return _SelectProduct; }
  79. set { SetProperty(ref _SelectProduct,value); }
  80. }
  81. private bool CanLoad
  82. {
  83. get
  84. {
  85. if (SelectProduct!=null && IsLoadProduct)
  86. {
  87. return true;
  88. }
  89. else
  90. {
  91. return false;
  92. }
  93. }
  94. }
  95. private bool _IsLoadProduct = true;
  96. public bool IsLoadProduct
  97. {
  98. get { return _IsLoadProduct; }
  99. set { SetProperty(ref _IsLoadProduct, value); }
  100. }
  101. private bool _isCanExecute = true;
  102. public bool isCanExecute
  103. {
  104. get { return _isCanExecute; }
  105. set { SetProperty(ref _isCanExecute, value); }
  106. }
  107. private ProductModel _CurrentProduct;
  108. public ProductModel CurrentProduct
  109. {
  110. get { return _CurrentProduct; }
  111. set { SetProperty(ref _CurrentProduct, value); }
  112. }
  113. private PlotModel _LockCurvePlotModel;
  114. /// <summary>
  115. /// 锁付曲线
  116. /// </summary>
  117. public PlotModel LockCurvePlotModel
  118. {
  119. get { return _LockCurvePlotModel; }
  120. set { SetProperty(ref _LockCurvePlotModel, value); }
  121. }
  122. private ObservableCollection<LockResult> _LockResults = new ObservableCollection<LockResult>();
  123. /// <summary>
  124. /// 锁付结果列表
  125. /// </summary>
  126. public ObservableCollection<LockResult> LockResults
  127. {
  128. get { return _LockResults; }
  129. set { SetProperty(ref _LockResults, value); }
  130. }
  131. private bool _IsAllowEdit = false;
  132. public bool IsAllowEdit
  133. {
  134. get { return _IsAllowEdit; }
  135. set { SetProperty(ref _IsAllowEdit, value); }
  136. }
  137. #endregion
  138. #region 命令
  139. public DelegateCommand LoadedCommand { get; set; }
  140. private DelegateCommand<ProductModel> _LoadProductCommand;
  141. public DelegateCommand<ProductModel> LoadProductCommand =>
  142. _LoadProductCommand ?? (_LoadProductCommand = new DelegateCommand<ProductModel>(ExecuteLoadProductCommand).ObservesCanExecute(()=> CanLoad).ObservesProperty(()=> SelectProduct).ObservesProperty(()=> IsLoadProduct));
  143. private DelegateCommand _ResetCounterCommand;
  144. public DelegateCommand ResetCounterCommand =>
  145. _ResetCounterCommand ?? (_ResetCounterCommand = new DelegateCommand(ExecuteResetCounterCommand).ObservesCanExecute(() => DoCondition).ObservesProperty(()=>isCanExecute));
  146. private bool DoCondition
  147. {
  148. get { return isCanExecute; }
  149. }
  150. private DelegateCommand<string> _CopyCommand;
  151. public DelegateCommand<string> CopyCommand =>
  152. _CopyCommand ?? (_CopyCommand = new DelegateCommand<string>(ExecuteCopyCommand));
  153. private DelegateCommand _TorqueInspectionCommand;
  154. public DelegateCommand TorqueInspectionCommand =>
  155. _TorqueInspectionCommand ?? (_TorqueInspectionCommand = new DelegateCommand(ExecuteTorqueInspectionCommand));
  156. //更换吸嘴
  157. private DelegateCommand _ChangeNozzleCommand;
  158. public DelegateCommand ChangeNozzleCommand =>
  159. _ChangeNozzleCommand ?? (_ChangeNozzleCommand = new DelegateCommand(ExecuteChangeNozzleCommand));
  160. //更换披头
  161. private DelegateCommand _ChangeHeaderCommand;
  162. public DelegateCommand ChangeHeaderCommand =>
  163. _ChangeHeaderCommand ?? (_ChangeHeaderCommand = new DelegateCommand(ExecuteChangeHeaderCommand));
  164. //添加螺丝
  165. private DelegateCommand _AddScrewCommand;
  166. public DelegateCommand AddScrewCommand =>
  167. _AddScrewCommand ?? (_AddScrewCommand = new DelegateCommand(ExecuteAddScrewCommand));
  168. private DelegateCommand _SetAlarmValueCommand;
  169. public DelegateCommand SetAlarmValueCommand =>
  170. _SetAlarmValueCommand ?? (_SetAlarmValueCommand = new DelegateCommand(ExecuteSetAlarmValueCommand));
  171. #endregion
  172. #region 事件
  173. #endregion
  174. public HomeViewModel(IEventAggregator ea, IContainerProvider container, IProductService productService, IConfigService configService, IRemoteCommandService remoteCommandService
  175. , ISystemDatabaseService systemDatabaseService,IDialogService dialogService)
  176. {
  177. _eventAggregator = ea;
  178. _container = container;
  179. _dialogService = dialogService;
  180. _productService = productService;
  181. LoadedCommand = new DelegateCommand(OnLoad);
  182. _eventAggregator.GetEvent<TaskMessageNotification>().Subscribe(AddMessageInvoke);
  183. //订阅权限登录事件
  184. _eventAggregator.GetEvent<UserLoginNotification>().Subscribe(LoginChange);
  185. management = _container.Resolve<Management>();
  186. _configService = configService;
  187. _productService.OnProductChanged += _productService_OnProductChanged;
  188. _remoteCommandService = remoteCommandService;
  189. _remoteCommandService.CycleTimingTicked += _remoteCommandService_CycleTimingTicked;
  190. _systemDatabaseService = systemDatabaseService;
  191. _eventAggregator.GetEvent<LockFinishNotification>().Subscribe(OnLockFinish);
  192. }
  193. private void _remoteCommandService_CycleTimingTicked(object sender, TimeSpan e)
  194. {
  195. try
  196. {
  197. if (App.Current!=null)
  198. {
  199. App.Current.Invoke(() =>
  200. {
  201. CTTotalSeconds = e.TotalSeconds;
  202. });
  203. }
  204. }
  205. catch (Exception)
  206. {
  207. }
  208. }
  209. #region 方法
  210. bool isFirst=true;
  211. private void OnLoad()
  212. {
  213. if (!isFirst)
  214. {
  215. return;
  216. }
  217. InitLockCurvePlotModel();
  218. isFirst = false;
  219. if (_systemDatabaseService.GetCurrentUser().userPart == Enums.UserPart.Operator)
  220. {
  221. IsAllowEdit = false;
  222. }
  223. else
  224. {
  225. IsAllowEdit = true;
  226. }
  227. }
  228. async void ExecuteLoadProductCommand(ProductModel product)
  229. {
  230. if (product == null) return;
  231. var view = new ShowMessage(Lang.是否加载产品, $"{Lang.加载产品}:{product.Name}?");
  232. //show the dialog
  233. var result = await DialogHost.Show(view, "RootDialog", null, null, null);
  234. if (result != null && result is bool)
  235. {
  236. if (((bool)result))
  237. {
  238. IsLoadProduct = false;
  239. var waiting = new WaitingControl();
  240. //show the dialog
  241. var task = DialogHost.Show(waiting, "RootDialog", null, null, null);
  242. _productService.LoadProduct(product.ID);
  243. _productService.SetCurrentProduct(product.ID);
  244. await management.WritePositionToPlcAsync();
  245. if (DialogHost.IsDialogOpen("RootDialog"))
  246. {
  247. DialogHost.Close("RootDialog");
  248. }
  249. await task;
  250. //DatabaseHelper.AddLoadProductRecord(product.ID, product.Name, false);
  251. IsLoadProduct = true;
  252. }
  253. }
  254. }
  255. void ExecuteCopyCommand(string textToCopy)
  256. {
  257. Clipboard.SetText(textToCopy);
  258. }
  259. /// <summary>
  260. /// 添加消息至消息队列
  261. /// </summary>
  262. /// <param name="msg"></param>
  263. /// <param name="color"></param>
  264. public void AddMessage(string msg, Color color)
  265. {
  266. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  267. try
  268. {
  269. MessageQueue.Add(new TaskMessage()
  270. {
  271. DT = DateTime.Now,
  272. Message = msg,
  273. FontColol = new SolidColorBrush(color)
  274. });
  275. LogHelper.WriteLogInfo(msg);
  276. }
  277. catch (Exception)
  278. {
  279. }
  280. }));
  281. }
  282. /// <summary>
  283. /// 添加消息至消息队列
  284. /// </summary>
  285. /// <param name="msg"></param>
  286. /// <param name="color"></param>
  287. public void AddMessage(string msg, MessageLevel level)
  288. {
  289. MessageStruct messageStruct = new MessageStruct() { Message = msg, level = level };
  290. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  291. AddMessage(messageStruct);
  292. }));
  293. }
  294. /// <summary>
  295. /// 添加消息至消息队列
  296. /// </summary>
  297. /// <param name="messageStruct"></param>
  298. public void AddMessage(MessageStruct messageStruct)
  299. {
  300. try
  301. {
  302. if (MessageQueue.Count >= 100)
  303. {
  304. MessageQueue.RemoveAt(0);// 从队列头部移除最早的消息
  305. }
  306. Color color = Colors.Black;
  307. switch (messageStruct.level)
  308. {
  309. case MessageLevel.Info:
  310. color = Colors.Black;
  311. break;
  312. case MessageLevel.Debug:
  313. color = Colors.Green;
  314. break;
  315. case MessageLevel.Alarm:
  316. color = Colors.Orange;
  317. break;
  318. case MessageLevel.Error:
  319. color = Colors.Red;
  320. break;
  321. }
  322. MessageQueue.Add(new TaskMessage()
  323. {
  324. DT = DateTime.Now,
  325. Message = messageStruct.Message,
  326. FontColol = new SolidColorBrush(color)
  327. });
  328. LogHelper.WriteLogInfo(messageStruct.Message);
  329. }
  330. catch (Exception)
  331. {
  332. }
  333. }
  334. public void AddMessageInvoke(MessageStruct messageStruct)
  335. {
  336. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  337. AddMessage(messageStruct);
  338. }));
  339. }
  340. private void LoginChange(Models.User user)
  341. {
  342. if (user.userPart == Enums.UserPart.Operator)
  343. {
  344. IsAllowEdit = false;
  345. }
  346. else
  347. {
  348. IsAllowEdit = true;
  349. }
  350. }
  351. /// <summary>
  352. /// 重置计数
  353. /// </summary>
  354. async void ExecuteResetCounterCommand()
  355. {
  356. var currentProduct =_productService.GetCurrentProduct();
  357. if (currentProduct == null) return;
  358. var view = new ShowMessage(Lang.计数清零, Lang.是否重置当前产品的计数);
  359. //show the dialog
  360. var result = await DialogHost.Show(view, "RootDialog", null, null, null);
  361. if (result != null && result is bool)
  362. {
  363. if (((bool)result))
  364. {
  365. isCanExecute = false;
  366. await _systemDatabaseService.ResetProductionAsync(currentProduct.Name);
  367. await _systemDatabaseService.ResetThrowNumberAsync();
  368. isCanExecute = true;
  369. }
  370. }
  371. }
  372. /// <summary>
  373. /// 初始化曲线图
  374. /// </summary>
  375. private void InitLockCurvePlotModel()
  376. {
  377. var model = new PlotModel { Title = Lang.锁付曲线, TitleFontSize = 16};
  378. // 设置图例
  379. var legend = new Legend
  380. {
  381. LegendPosition = LegendPosition.TopRight,
  382. LegendPlacement = LegendPlacement.Outside,
  383. LegendOrientation = LegendOrientation.Vertical,
  384. LegendBorderThickness = 0
  385. };
  386. model.Legends.Add(legend);
  387. // 设置X轴
  388. var xAxis = new LinearAxis
  389. {
  390. Key="X",
  391. Position = AxisPosition.Bottom,
  392. Title = Lang.锁付圈数,
  393. Minimum = 0,
  394. MajorGridlineStyle = LineStyle.Solid,
  395. MinorGridlineStyle = LineStyle.Dot
  396. };
  397. model.Axes.Add(xAxis);
  398. // 设置Y轴
  399. var yAxis = new LinearAxis
  400. {
  401. Key = "Y",
  402. Position = AxisPosition.Left,
  403. Title = Lang.力矩kgf,
  404. MajorGridlineStyle = LineStyle.Solid,
  405. MinorGridlineStyle = LineStyle.Dot
  406. };
  407. model.Axes.Add(yAxis);
  408. // 添加示例数据系列
  409. var series = new LineSeries
  410. {
  411. Title = Lang.锁付力矩曲线,
  412. StrokeThickness = 2,
  413. MarkerSize = 3,
  414. MarkerType = MarkerType.Circle,
  415. CanTrackerInterpolatePoints = false,
  416. };
  417. model.Series.Add(series);
  418. LockCurvePlotModel = model;
  419. }
  420. /// <summary>
  421. /// 螺丝锁付完成时调用
  422. /// </summary>
  423. /// <param name="result"></param>
  424. /// <exception cref="NotImplementedException"></exception>
  425. private void OnLockFinish(LockResult result)
  426. {
  427. //如果当前螺丝编号为1,则清除之前的结果
  428. if (result.Number == 1)
  429. {
  430. LockResults.Clear();
  431. }
  432. LockResults.Add(result);
  433. //更新曲线图
  434. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  435. try
  436. {
  437. var series = LockCurvePlotModel.Series[0] as LineSeries;
  438. series.Points.Clear();
  439. foreach (var waveData in result.WaveDatas)
  440. {
  441. series.Points.Add(new OxyPlot.DataPoint(waveData.Turns, waveData.Torque));
  442. }
  443. // 重置所有轴的范围以适应新数据
  444. LockCurvePlotModel.ResetAllAxes();
  445. LockCurvePlotModel.InvalidatePlot(true);
  446. if (!string.IsNullOrEmpty(result.LockCurveImagePath))
  447. {
  448. PngExporter.Export(LockCurvePlotModel, result.LockCurveImagePath, (int)LockCurvePlotModel.Width, (int)LockCurvePlotModel.Height);
  449. }
  450. }
  451. catch (Exception ex)
  452. {
  453. LogHelper.WriteLogError("更新曲线图和保存曲线图时出错!", ex);
  454. }
  455. }));
  456. }
  457. /// <summary>
  458. /// 添加螺丝
  459. /// </summary>
  460. private void ExecuteAddScrewCommand()
  461. {
  462. _dialogService.ShowDialog("AddScrew", rst =>
  463. {
  464. //对话框关闭之后的回调函数,可以在这解析结果。
  465. ButtonResult result1 = rst.Result;
  466. if (result1 == ButtonResult.OK)
  467. {
  468. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  469. }
  470. });
  471. }
  472. /// <summary>
  473. /// 更换披头
  474. /// </summary>
  475. void ExecuteChangeHeaderCommand()
  476. {
  477. _dialogService.ShowDialog("ChangeHeader", rst =>
  478. {
  479. //对话框关闭之后的回调函数,可以在这解析结果。
  480. ButtonResult result1 = rst.Result;
  481. if (result1 == ButtonResult.OK)
  482. {
  483. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  484. }
  485. });
  486. }
  487. /// <summary>
  488. /// 更换吸嘴
  489. /// </summary>
  490. void ExecuteChangeNozzleCommand()
  491. {
  492. _dialogService.ShowDialog("ChangeNozzle", rst =>
  493. {
  494. //对话框关闭之后的回调函数,可以在这解析结果。
  495. ButtonResult result1 = rst.Result;
  496. if (result1 == ButtonResult.OK)
  497. {
  498. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  499. }
  500. });
  501. }
  502. void ExecuteTorqueInspectionCommand()
  503. {
  504. _dialogService.ShowDialog("TorqueCheck", rst =>
  505. {
  506. //对话框关闭之后的回调函数,可以在这解析结果。
  507. ButtonResult result1 = rst.Result;
  508. if (result1 == ButtonResult.OK)
  509. {
  510. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  511. }
  512. });
  513. }
  514. void ExecuteSetAlarmValueCommand()
  515. {
  516. _dialogService.ShowDialog("SetAlarmValue", rst =>
  517. {
  518. //对话框关闭之后的回调函数,可以在这解析结果。
  519. ButtonResult result1 = rst.Result;
  520. if (result1 == ButtonResult.OK)
  521. {
  522. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  523. }
  524. });
  525. }
  526. #endregion
  527. #region 继承
  528. /// <summary>
  529. /// 确认导航请求时调用。此方法允许您在导航之前执行一些操作。
  530. /// </summary>
  531. /// <param name="navigationContext"></param>
  532. /// <param name="continuationCallback"></param>
  533. public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
  534. {
  535. continuationCallback(true);
  536. }
  537. /// <summary>
  538. /// 接收导航请求时调用。传入导航参数,包含有关导航目标的信息。
  539. /// </summary>
  540. /// <param name="navigationContext"></param>
  541. /// <exception cref="NotImplementedException"></exception>
  542. public async void OnNavigatedTo(NavigationContext navigationContext)
  543. {
  544. try
  545. {
  546. ProductList = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
  547. }
  548. catch (Exception ex)
  549. {
  550. LogHelper.WriteLogError(Lang.主界面界面进入时出错, ex);
  551. }
  552. }
  553. /// <summary>
  554. /// 是否允许导航到此视图模型。
  555. /// </summary>
  556. /// <param name="navigationContext"></param>
  557. /// <returns></returns>
  558. public bool IsNavigationTarget(NavigationContext navigationContext)
  559. {
  560. return true;
  561. }
  562. /// <summary>
  563. /// 导航离开此视图模型时调用。您可以在此处执行清理操作或保存状态。
  564. /// </summary>
  565. /// <param name="navigationContext"></param>
  566. public void OnNavigatedFrom(NavigationContext navigationContext)
  567. {
  568. }
  569. #endregion
  570. private void _productService_OnProductChanged(ProductModel obj)
  571. {
  572. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  573. CurrentProduct = obj;
  574. }));
  575. }
  576. }
  577. }