HomeViewModel.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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. private DelegateCommand _NozzleCounterResetCommand;
  157. public DelegateCommand NozzleCounterResetCommand =>
  158. _NozzleCounterResetCommand ?? (_NozzleCounterResetCommand = new DelegateCommand(ExecuteNozzleCounterResetCommand));
  159. private DelegateCommand _SetAlarmValueCommand;
  160. public DelegateCommand SetAlarmValueCommand =>
  161. _SetAlarmValueCommand ?? (_SetAlarmValueCommand = new DelegateCommand(ExecuteSetAlarmValueCommand));
  162. #endregion
  163. #region 事件
  164. #endregion
  165. public HomeViewModel(IEventAggregator ea, IContainerProvider container, IProductService productService, IConfigService configService, IRemoteCommandService remoteCommandService
  166. , ISystemDatabaseService systemDatabaseService,IDialogService dialogService)
  167. {
  168. _eventAggregator = ea;
  169. _container = container;
  170. _dialogService = dialogService;
  171. _productService = productService;
  172. LoadedCommand = new DelegateCommand(OnLoad);
  173. _eventAggregator.GetEvent<TaskMessageNotification>().Subscribe(AddMessageInvoke);
  174. //订阅权限登录事件
  175. _eventAggregator.GetEvent<UserLoginNotification>().Subscribe(LoginChange);
  176. management = _container.Resolve<Management>();
  177. _configService = configService;
  178. _productService.OnProductChanged += _productService_OnProductChanged;
  179. _remoteCommandService = remoteCommandService;
  180. _remoteCommandService.CycleTimingTicked += _remoteCommandService_CycleTimingTicked;
  181. _systemDatabaseService = systemDatabaseService;
  182. _eventAggregator.GetEvent<LockFinishNotification>().Subscribe(OnLockFinish);
  183. }
  184. private void _remoteCommandService_CycleTimingTicked(object sender, TimeSpan e)
  185. {
  186. try
  187. {
  188. if (App.Current!=null)
  189. {
  190. App.Current.Invoke(() =>
  191. {
  192. CTTotalSeconds = e.TotalSeconds;
  193. });
  194. }
  195. }
  196. catch (Exception)
  197. {
  198. }
  199. }
  200. #region 方法
  201. bool isFirst=true;
  202. private void OnLoad()
  203. {
  204. if (!isFirst)
  205. {
  206. return;
  207. }
  208. InitLockCurvePlotModel();
  209. isFirst = false;
  210. if (_systemDatabaseService.GetCurrentUser().userPart == Enums.UserPart.Operator)
  211. {
  212. IsAllowEdit = false;
  213. }
  214. else
  215. {
  216. IsAllowEdit = true;
  217. }
  218. }
  219. async void ExecuteLoadProductCommand(ProductModel product)
  220. {
  221. if (product == null) return;
  222. var view = new ShowMessage(Lang.是否加载产品, $"{Lang.加载产品}:{product.Name}?");
  223. //show the dialog
  224. var result = await DialogHost.Show(view, "RootDialog", null, null, null);
  225. if (result != null && result is bool)
  226. {
  227. if (((bool)result))
  228. {
  229. IsLoadProduct = false;
  230. var waiting = new WaitingControl();
  231. //show the dialog
  232. var task = DialogHost.Show(waiting, "RootDialog", null, null, null);
  233. await _productService.LoadProductAsync(product.ID);
  234. _productService.SetCurrentProduct(product.ID);
  235. await management.WritePositionToPlcAsync();
  236. if (DialogHost.IsDialogOpen("RootDialog"))
  237. {
  238. DialogHost.Close("RootDialog");
  239. }
  240. await task;
  241. //DatabaseHelper.AddLoadProductRecord(product.ID, product.Name, false);
  242. IsLoadProduct = true;
  243. }
  244. }
  245. }
  246. void ExecuteCopyCommand(string textToCopy)
  247. {
  248. Clipboard.SetText(textToCopy);
  249. }
  250. void ExecuteTorqueInspectionCommand()
  251. {
  252. _dialogService.ShowDialog("TorqueCheck", rst =>
  253. {
  254. //对话框关闭之后的回调函数,可以在这解析结果。
  255. ButtonResult result1 = rst.Result;
  256. if (result1 == ButtonResult.OK)
  257. {
  258. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  259. }
  260. });
  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. //初始化曲线图
  374. private void InitLockCurvePlotModel()
  375. {
  376. var model = new PlotModel { Title = "锁付曲线", 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 = "角度 (°)",
  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 = "力矩 (kgf)",
  403. MajorGridlineStyle = LineStyle.Solid,
  404. MinorGridlineStyle = LineStyle.Dot
  405. };
  406. model.Axes.Add(yAxis);
  407. // 添加示例数据系列
  408. var series = new LineSeries
  409. {
  410. Title = "锁付力矩曲线",
  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. var series = LockCurvePlotModel.Series[0] as LineSeries;
  435. //var yaxis = LockCurvePlotModel.Axes.FirstOrDefault(p=>p.Key=="Y");
  436. //yaxis.Maximum = result.TargetTorque;
  437. series.Points.Clear();
  438. foreach (var waveData in result.WaveDatas)
  439. {
  440. series.Points.Add(new OxyPlot.DataPoint(waveData.LockAngle, waveData.Torque));
  441. }
  442. LockCurvePlotModel.InvalidatePlot(true);
  443. }));
  444. }
  445. private void SaveAsPng(PlotModel LockCurvePlotModel)
  446. {
  447. string savePath = $"E:\\Data\\螺丝锁付曲线图\\{DateTime.Now:yyyyMMdd_HHmmss}.png";
  448. Application.Current.Dispatcher.Invoke(() =>
  449. {
  450. try
  451. {
  452. var exporter = new PngExporter { Width = 1200, Height = 800 };
  453. exporter.ExportToFile(LockCurvePlotModel, savePath);
  454. //SaveStatus = $"已保存到:{savePath}";
  455. }
  456. catch (Exception ex)
  457. {
  458. //SaveStatus = $"保存失败:{ex.Message}";
  459. }
  460. });
  461. }
  462. void ExecuteSetAlarmValueCommand()
  463. {
  464. _dialogService.ShowDialog("SetAlarmValue", rst =>
  465. {
  466. //对话框关闭之后的回调函数,可以在这解析结果。
  467. ButtonResult result1 = rst.Result;
  468. if (result1 == ButtonResult.OK)
  469. {
  470. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  471. }
  472. });
  473. }
  474. void ExecuteNozzleCounterResetCommand()
  475. {
  476. management.NumStatistics.NozzleNum = 0;
  477. management.NumStatistics.HeaderNum = 0;
  478. FileHelper.WriteJsonFile(management.NumStatistics, FilePath.NumberStatisticsPath);
  479. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
  480. }
  481. #endregion
  482. #region 继承
  483. /// <summary>
  484. /// 确认导航请求时调用。此方法允许您在导航之前执行一些操作。
  485. /// </summary>
  486. /// <param name="navigationContext"></param>
  487. /// <param name="continuationCallback"></param>
  488. public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
  489. {
  490. continuationCallback(true);
  491. }
  492. /// <summary>
  493. /// 接收导航请求时调用。传入导航参数,包含有关导航目标的信息。
  494. /// </summary>
  495. /// <param name="navigationContext"></param>
  496. /// <exception cref="NotImplementedException"></exception>
  497. public async void OnNavigatedTo(NavigationContext navigationContext)
  498. {
  499. try
  500. {
  501. ProductList = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
  502. }
  503. catch (Exception ex)
  504. {
  505. LogHelper.WriteLogError("主界面界面进入时出错!", ex);
  506. }
  507. }
  508. /// <summary>
  509. /// 是否允许导航到此视图模型。
  510. /// </summary>
  511. /// <param name="navigationContext"></param>
  512. /// <returns></returns>
  513. public bool IsNavigationTarget(NavigationContext navigationContext)
  514. {
  515. return true;
  516. }
  517. /// <summary>
  518. /// 导航离开此视图模型时调用。您可以在此处执行清理操作或保存状态。
  519. /// </summary>
  520. /// <param name="navigationContext"></param>
  521. public void OnNavigatedFrom(NavigationContext navigationContext)
  522. {
  523. }
  524. #endregion
  525. private void _productService_OnProductChanged(ProductModel obj)
  526. {
  527. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  528. CurrentProduct = obj;
  529. }));
  530. }
  531. }
  532. }