HomeViewModel.cs 22 KB

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