HomeViewModel.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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. await _productService.LoadProductAsync(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 >= 20)
  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. isCanExecute = true;
  368. }
  369. }
  370. }
  371. /// <summary>
  372. /// 初始化曲线图
  373. /// </summary>
  374. private void InitLockCurvePlotModel()
  375. {
  376. var model = new PlotModel { Title = Lang.锁付曲线, TitleFontSize = 16};
  377. // 设置图例
  378. var legend = new Legend
  379. {
  380. LegendPosition = LegendPosition.TopRight,
  381. LegendPlacement = LegendPlacement.Outside,
  382. LegendOrientation = LegendOrientation.Vertical,
  383. LegendBorderThickness = 0
  384. };
  385. model.Legends.Add(legend);
  386. // 设置X轴
  387. var xAxis = new LinearAxis
  388. {
  389. Key="X",
  390. Position = AxisPosition.Bottom,
  391. Title = Lang.角度,
  392. Minimum = 0,
  393. MajorGridlineStyle = LineStyle.Solid,
  394. MinorGridlineStyle = LineStyle.Dot
  395. };
  396. model.Axes.Add(xAxis);
  397. // 设置Y轴
  398. var yAxis = new LinearAxis
  399. {
  400. Key = "Y",
  401. Position = AxisPosition.Left,
  402. Title = Lang.力矩kgf,
  403. MajorGridlineStyle = LineStyle.Solid,
  404. MinorGridlineStyle = LineStyle.Dot
  405. };
  406. model.Axes.Add(yAxis);
  407. // 添加示例数据系列
  408. var series = new LineSeries
  409. {
  410. Title = Lang.锁付力矩曲线,
  411. StrokeThickness = 2,
  412. MarkerSize = 3,
  413. MarkerType = MarkerType.Circle,
  414. CanTrackerInterpolatePoints = false,
  415. };
  416. model.Series.Add(series);
  417. LockCurvePlotModel = model;
  418. }
  419. /// <summary>
  420. /// 螺丝锁付完成时调用
  421. /// </summary>
  422. /// <param name="result"></param>
  423. /// <exception cref="NotImplementedException"></exception>
  424. private void OnLockFinish(LockResult result)
  425. {
  426. //如果当前螺丝编号为1,则清除之前的结果
  427. if (result.Number == 1)
  428. {
  429. LockResults.Clear();
  430. }
  431. LockResults.Add(result);
  432. //更新曲线图
  433. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  434. try
  435. {
  436. var series = LockCurvePlotModel.Series[0] as LineSeries;
  437. //var yaxis = LockCurvePlotModel.Axes.FirstOrDefault(p=>p.Key=="Y");
  438. //yaxis.Maximum = result.TargetTorque;
  439. series.Points.Clear();
  440. foreach (var waveData in result.WaveDatas)
  441. {
  442. series.Points.Add(new OxyPlot.DataPoint(waveData.LockAngle, waveData.Torque));
  443. }
  444. LockCurvePlotModel.InvalidatePlot(true);
  445. if (!string.IsNullOrEmpty(result.LockCurveImagePath))
  446. {
  447. PngExporter.Export(LockCurvePlotModel, result.LockCurveImagePath, (int)LockCurvePlotModel.Width, (int)LockCurvePlotModel.Height);
  448. }
  449. }
  450. catch (Exception ex)
  451. {
  452. LogHelper.WriteLogError("更新曲线图和保存曲线图时出错!", ex);
  453. }
  454. }));
  455. }
  456. /// <summary>
  457. /// 添加螺丝
  458. /// </summary>
  459. private void ExecuteAddScrewCommand()
  460. {
  461. _dialogService.ShowDialog("AddScrew", rst =>
  462. {
  463. //对话框关闭之后的回调函数,可以在这解析结果。
  464. ButtonResult result1 = rst.Result;
  465. if (result1 == ButtonResult.OK)
  466. {
  467. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  468. }
  469. });
  470. }
  471. /// <summary>
  472. /// 更换披头
  473. /// </summary>
  474. void ExecuteChangeHeaderCommand()
  475. {
  476. _dialogService.ShowDialog("ChangeHeader", rst =>
  477. {
  478. //对话框关闭之后的回调函数,可以在这解析结果。
  479. ButtonResult result1 = rst.Result;
  480. if (result1 == ButtonResult.OK)
  481. {
  482. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  483. }
  484. });
  485. }
  486. /// <summary>
  487. /// 更换吸嘴
  488. /// </summary>
  489. void ExecuteChangeNozzleCommand()
  490. {
  491. _dialogService.ShowDialog("ChangeNozzle", rst =>
  492. {
  493. //对话框关闭之后的回调函数,可以在这解析结果。
  494. ButtonResult result1 = rst.Result;
  495. if (result1 == ButtonResult.OK)
  496. {
  497. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  498. }
  499. });
  500. }
  501. void ExecuteTorqueInspectionCommand()
  502. {
  503. _dialogService.ShowDialog("TorqueCheck", rst =>
  504. {
  505. //对话框关闭之后的回调函数,可以在这解析结果。
  506. ButtonResult result1 = rst.Result;
  507. if (result1 == ButtonResult.OK)
  508. {
  509. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  510. }
  511. });
  512. }
  513. void ExecuteSetAlarmValueCommand()
  514. {
  515. _dialogService.ShowDialog("SetAlarmValue", rst =>
  516. {
  517. //对话框关闭之后的回调函数,可以在这解析结果。
  518. ButtonResult result1 = rst.Result;
  519. if (result1 == ButtonResult.OK)
  520. {
  521. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  522. }
  523. });
  524. }
  525. #endregion
  526. #region 继承
  527. /// <summary>
  528. /// 确认导航请求时调用。此方法允许您在导航之前执行一些操作。
  529. /// </summary>
  530. /// <param name="navigationContext"></param>
  531. /// <param name="continuationCallback"></param>
  532. public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
  533. {
  534. continuationCallback(true);
  535. }
  536. /// <summary>
  537. /// 接收导航请求时调用。传入导航参数,包含有关导航目标的信息。
  538. /// </summary>
  539. /// <param name="navigationContext"></param>
  540. /// <exception cref="NotImplementedException"></exception>
  541. public async void OnNavigatedTo(NavigationContext navigationContext)
  542. {
  543. try
  544. {
  545. ProductList = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
  546. }
  547. catch (Exception ex)
  548. {
  549. LogHelper.WriteLogError(Lang.主界面界面进入时出错, ex);
  550. }
  551. }
  552. /// <summary>
  553. /// 是否允许导航到此视图模型。
  554. /// </summary>
  555. /// <param name="navigationContext"></param>
  556. /// <returns></returns>
  557. public bool IsNavigationTarget(NavigationContext navigationContext)
  558. {
  559. return true;
  560. }
  561. /// <summary>
  562. /// 导航离开此视图模型时调用。您可以在此处执行清理操作或保存状态。
  563. /// </summary>
  564. /// <param name="navigationContext"></param>
  565. public void OnNavigatedFrom(NavigationContext navigationContext)
  566. {
  567. }
  568. #endregion
  569. private void _productService_OnProductChanged(ProductModel obj)
  570. {
  571. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  572. CurrentProduct = obj;
  573. }));
  574. }
  575. }
  576. }