HomeViewModel.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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 Prism.Commands;
  9. using Prism.Events;
  10. using Prism.Ioc;
  11. using Prism.Mvvm;
  12. using Prism.Regions;
  13. using Prism.Services.Dialogs;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Collections.ObjectModel;
  17. using System.Linq;
  18. using System.Threading.Tasks;
  19. using System.Windows;
  20. using System.Windows.Media;
  21. using TeamAAS_VP;
  22. using TeamAAS_VP.Controls;
  23. using TeamAAS_VP.Core;
  24. using TeamAAS_VP.Data;
  25. using TeamAAS_VP.Enums;
  26. using TeamAAS_VP.Events;
  27. using TeamAAS_VP.Interfaces;
  28. using TeamAAS_VP.Models;
  29. using TeamAAS_VP.Resources.Languages;
  30. using TeamAAS_VP.Services;
  31. using TeamAAS_VP.ViewModels.DebugMod;
  32. using TeamAAS_VP.Views.DebugMod;
  33. namespace TeamAAS_VP.ViewModels
  34. {
  35. public class HomeViewModel : BindableBase, IConfirmNavigationRequest
  36. {
  37. IEventAggregator _eventAggregator;
  38. IContainerProvider _container;
  39. IProductService _productService;
  40. IConfigService _configService;
  41. IRemoteCommandService _remoteCommandService;
  42. ISystemDatabaseService _systemDatabaseService;
  43. IDialogService _dialogService;
  44. #region 属性
  45. private bool _IsShowLabel = false;
  46. /// <summary>
  47. /// Mes标签显示
  48. /// </summary>
  49. public bool IsShowLabel
  50. {
  51. get { return _IsShowLabel; }
  52. set { SetProperty(ref _IsShowLabel, value); }
  53. }
  54. private bool _IsNoCode = true;
  55. /// <summary>
  56. /// 无SN
  57. /// </summary>
  58. public bool IsNoCode
  59. {
  60. get { return _IsNoCode; }
  61. set { SetProperty(ref _IsNoCode, value); }
  62. }
  63. private bool _IsResultTrue = true;
  64. /// <summary>
  65. /// 检测结果为1
  66. /// </summary>
  67. public bool IsResultTrue
  68. {
  69. get { return _IsResultTrue; }
  70. set { SetProperty(ref _IsResultTrue, value); }
  71. }
  72. private ObservableCollection<TaskMessage> messageQueue=new ObservableCollection<TaskMessage>();
  73. /// <summary>
  74. /// 运行信息队列
  75. /// </summary>
  76. public ObservableCollection<TaskMessage> MessageQueue
  77. {
  78. get { return messageQueue; }
  79. set { SetProperty(ref messageQueue,value); }
  80. }
  81. private ObservableCollection<ProductModel> _ProductList;
  82. public ObservableCollection<ProductModel> ProductList
  83. {
  84. get { return _ProductList; }
  85. set { SetProperty(ref _ProductList, value); }
  86. }
  87. private Management _management;
  88. public Management management
  89. {
  90. get { return _management; }
  91. set { SetProperty(ref _management, value); }
  92. }
  93. private double _CTTotalSeconds;
  94. public double CTTotalSeconds
  95. {
  96. get { return _CTTotalSeconds; }
  97. set { SetProperty(ref _CTTotalSeconds, value); }
  98. }
  99. private ProductModel _SelectProduct;
  100. public ProductModel SelectProduct
  101. {
  102. get { return _SelectProduct; }
  103. set { SetProperty(ref _SelectProduct,value); }
  104. }
  105. private bool CanLoad
  106. {
  107. get
  108. {
  109. if (SelectProduct!=null && IsLoadProduct)
  110. {
  111. return true;
  112. }
  113. else
  114. {
  115. return false;
  116. }
  117. }
  118. }
  119. private bool _IsLoadProduct = true;
  120. public bool IsLoadProduct
  121. {
  122. get { return _IsLoadProduct; }
  123. set { SetProperty(ref _IsLoadProduct, value); }
  124. }
  125. private bool _isCanExecute = true;
  126. public bool isCanExecute
  127. {
  128. get { return _isCanExecute; }
  129. set { SetProperty(ref _isCanExecute, value); }
  130. }
  131. private ProductModel _CurrentProduct;
  132. public ProductModel CurrentProduct
  133. {
  134. get { return _CurrentProduct; }
  135. set { SetProperty(ref _CurrentProduct, value); }
  136. }
  137. private PlotModel _LockCurvePlotModel;
  138. /// <summary>
  139. /// 锁付曲线
  140. /// </summary>
  141. public PlotModel LockCurvePlotModel
  142. {
  143. get { return _LockCurvePlotModel; }
  144. set { SetProperty(ref _LockCurvePlotModel, value); }
  145. }
  146. private ObservableCollection<LockResult> _LockResults = new ObservableCollection<LockResult>();
  147. /// <summary>
  148. /// 锁付结果列表
  149. /// </summary>
  150. public ObservableCollection<LockResult> LockResults
  151. {
  152. get { return _LockResults; }
  153. set { SetProperty(ref _LockResults, value); }
  154. }
  155. private bool _IsAllowEdit = false;
  156. public bool IsAllowEdit
  157. {
  158. get { return _IsAllowEdit; }
  159. set { SetProperty(ref _IsAllowEdit, value); }
  160. }
  161. #endregion
  162. #region 命令
  163. public DelegateCommand LoadedCommand { get; set; }
  164. private DelegateCommand<ProductModel> _LoadProductCommand;
  165. public DelegateCommand<ProductModel> LoadProductCommand =>
  166. _LoadProductCommand ?? (_LoadProductCommand = new DelegateCommand<ProductModel>(ExecuteLoadProductCommand).ObservesCanExecute(()=> CanLoad).ObservesProperty(()=> SelectProduct).ObservesProperty(()=> IsLoadProduct));
  167. private DelegateCommand _ResetCounterCommand;
  168. public DelegateCommand ResetCounterCommand =>
  169. _ResetCounterCommand ?? (_ResetCounterCommand = new DelegateCommand(ExecuteResetCounterCommand).ObservesCanExecute(() => DoCondition).ObservesProperty(()=>isCanExecute));
  170. private bool DoCondition
  171. {
  172. get { return isCanExecute; }
  173. }
  174. private DelegateCommand<string> _CopyCommand;
  175. public DelegateCommand<string> CopyCommand =>
  176. _CopyCommand ?? (_CopyCommand = new DelegateCommand<string>(ExecuteCopyCommand));
  177. #endregion
  178. #region 事件
  179. #endregion
  180. public HomeViewModel(IEventAggregator ea, IContainerProvider container, IProductService productService, IConfigService configService, IRemoteCommandService remoteCommandService
  181. , IDialogService dialogService, ISystemDatabaseService systemDatabaseService)
  182. {
  183. _eventAggregator = ea;
  184. _container = container;
  185. _productService = productService;
  186. _dialogService = dialogService;
  187. LoadedCommand = new DelegateCommand(OnLoad);
  188. _eventAggregator.GetEvent<TaskMessageNotification>().Subscribe(AddMessageInvoke);
  189. //订阅权限登录事件
  190. _eventAggregator.GetEvent<UserLoginNotification>().Subscribe(LoginChange);
  191. management = _container.Resolve<Management>();
  192. _configService = configService;
  193. _productService.OnProductChanged += _productService_OnProductChanged;
  194. _remoteCommandService = remoteCommandService;
  195. _remoteCommandService.CycleTimingTicked += _remoteCommandService_CycleTimingTicked;
  196. _systemDatabaseService = systemDatabaseService;
  197. _eventAggregator.GetEvent<LockFinishNotification>().Subscribe(OnLockFinish);
  198. _eventAggregator.GetEvent<LockResetNotification>().Subscribe(OnLockReset);
  199. }
  200. private void _remoteCommandService_CycleTimingTicked(object sender, TimeSpan e)
  201. {
  202. try
  203. {
  204. if (App.Current!=null)
  205. {
  206. App.Current.Invoke(() =>
  207. {
  208. CTTotalSeconds = e.TotalSeconds;
  209. });
  210. }
  211. }
  212. catch (Exception)
  213. {
  214. }
  215. }
  216. #region 方法
  217. bool isFirst=true;
  218. private void OnLoad()
  219. {
  220. if (!isFirst)
  221. {
  222. return;
  223. }
  224. InitLockCurvePlotModel();
  225. isFirst = false;
  226. var sysConfig = _configService.GetSystemConfiguration();
  227. if (sysConfig.LabelUse == true)
  228. {
  229. IsShowLabel =true;
  230. }
  231. else
  232. {
  233. IsShowLabel = false;
  234. }
  235. }
  236. async void ExecuteLoadProductCommand(ProductModel product)
  237. {
  238. if (product == null) return;
  239. var view = new ShowMessage(Lang.是否加载产品, $"{Lang.加载产品}:{product.Name}?");
  240. var result = await DialogHost.Show(view, "RootDialog", null, null, null);
  241. if (result != null && result is bool)
  242. {
  243. if (((bool)result))
  244. {
  245. var _ = Application.Current.Dispatcher.BeginInvoke(new Action(() => { _dialogService.ShowDialog("UProgressBar", rst => { }); }));
  246. await Task.Delay(50);
  247. _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
  248. {
  249. _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = 2, Minimum = 0, SubTitle = $"切换产品...", Message = $"切换{product.Name}产品中...", Value = 0 });
  250. }));
  251. IsLoadProduct = false;
  252. await _productService.LoadProductAsync(product.ID);
  253. _productService.SetCurrentProduct(product.ID);
  254. await management.WritePositionToPlcAsync();
  255. IsLoadProduct = true;
  256. _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
  257. {
  258. _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = 2, Minimum = 0, SubTitle = $"切换产品...", Message = $"{Lang.完成}", Value = -1 });
  259. }));
  260. }
  261. }
  262. }
  263. void ExecuteCopyCommand(string textToCopy)
  264. {
  265. Clipboard.SetText(textToCopy);
  266. }
  267. /// <summary>
  268. /// 添加消息至消息队列
  269. /// </summary>
  270. /// <param name="msg"></param>
  271. /// <param name="color"></param>
  272. public void AddMessage(string msg, Color color)
  273. {
  274. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  275. try
  276. {
  277. MessageQueue.Add(new TaskMessage()
  278. {
  279. DT = DateTime.Now,
  280. Message = msg,
  281. FontColol = new SolidColorBrush(color)
  282. });
  283. LogHelper.WriteLogInfo(msg);
  284. }
  285. catch (Exception)
  286. {
  287. }
  288. }));
  289. }
  290. /// <summary>
  291. /// 添加消息至消息队列
  292. /// </summary>
  293. /// <param name="msg"></param>
  294. /// <param name="color"></param>
  295. public void AddMessage(string msg, MessageLevel level)
  296. {
  297. MessageStruct messageStruct = new MessageStruct() { Message = msg, level = level };
  298. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  299. AddMessage(messageStruct);
  300. }));
  301. }
  302. /// <summary>
  303. /// 添加消息至消息队列
  304. /// </summary>
  305. /// <param name="messageStruct"></param>
  306. public void AddMessage(MessageStruct messageStruct)
  307. {
  308. try
  309. {
  310. if (MessageQueue.Count >= 200)
  311. {
  312. MessageQueue.RemoveAt(0);// 从队列头部移除最早的消息
  313. }
  314. Color color = Colors.Black;
  315. switch (messageStruct.level)
  316. {
  317. case MessageLevel.Info:
  318. color = Colors.Black;
  319. break;
  320. case MessageLevel.Debug:
  321. color = Colors.Green;
  322. break;
  323. case MessageLevel.Alarm:
  324. color = Colors.Orange;
  325. break;
  326. case MessageLevel.Error:
  327. color = Colors.Red;
  328. break;
  329. }
  330. MessageQueue.Add(new TaskMessage()
  331. {
  332. DT = DateTime.Now,
  333. Message = messageStruct.Message,
  334. FontColol = new SolidColorBrush(color)
  335. });
  336. LogHelper.WriteLogInfo(messageStruct.Message);
  337. }
  338. catch (Exception)
  339. {
  340. }
  341. }
  342. public void AddMessageInvoke(MessageStruct messageStruct)
  343. {
  344. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  345. AddMessage(messageStruct);
  346. }));
  347. }
  348. private void LoginChange(Models.User user)
  349. {
  350. if (user.userPart == Enums.UserPart.Operator)
  351. {
  352. IsAllowEdit = false;
  353. }
  354. else
  355. {
  356. IsAllowEdit = true;
  357. }
  358. }
  359. /// <summary>
  360. /// 重置计数
  361. /// </summary>
  362. async void ExecuteResetCounterCommand()
  363. {
  364. var currentProduct = _productService.GetCurrentProduct();
  365. if (currentProduct == null) return;
  366. var view = new ShowMessage(Lang.计数清零, Lang.是否重置当前产品的计数);
  367. //show the dialog
  368. var result = await DialogHost.Show(view, "RootDialog", null, null, null);
  369. if (result != null && result is bool)
  370. {
  371. if (((bool)result))
  372. {
  373. isCanExecute = false;
  374. await _systemDatabaseService.ResetProductionAsync(currentProduct.Name);
  375. isCanExecute = true;
  376. }
  377. }
  378. }
  379. //初始化曲线图
  380. private void InitLockCurvePlotModel()
  381. {
  382. var model = new PlotModel { Title = "锁付曲线", TitleFontSize = 16};
  383. // 设置图例
  384. var legend = new Legend
  385. {
  386. LegendPosition = LegendPosition.TopRight,
  387. LegendPlacement = LegendPlacement.Outside,
  388. LegendOrientation = LegendOrientation.Vertical,
  389. LegendBorderThickness = 0
  390. };
  391. model.Legends.Add(legend);
  392. // 设置X轴
  393. var xAxis = new LinearAxis
  394. {
  395. Position = AxisPosition.Bottom,
  396. Title = "角度 (°)",
  397. Minimum = 0,
  398. MajorGridlineStyle = LineStyle.Solid,
  399. MinorGridlineStyle = LineStyle.Dot
  400. };
  401. model.Axes.Add(xAxis);
  402. // 设置Y轴
  403. var yAxis = new LinearAxis
  404. {
  405. Position = AxisPosition.Left,
  406. Title = "力矩 (kgf)",
  407. MajorGridlineStyle = LineStyle.Solid,
  408. MinorGridlineStyle = LineStyle.Dot
  409. };
  410. model.Axes.Add(yAxis);
  411. // 添加示例数据系列
  412. var series = new LineSeries
  413. {
  414. Title = "锁付力矩曲线",
  415. StrokeThickness = 2,
  416. MarkerSize = 3,
  417. MarkerType = MarkerType.Circle,
  418. CanTrackerInterpolatePoints = false,
  419. };
  420. model.Series.Add(series);
  421. LockCurvePlotModel = model;
  422. }
  423. /// <summary>
  424. /// 清楚结果列表
  425. /// </summary>
  426. /// <exception cref="NotImplementedException"></exception>
  427. private void OnLockReset()
  428. {
  429. LockResults.Clear();
  430. }
  431. /// <summary>
  432. /// 螺丝锁付完成时调用
  433. /// </summary>
  434. /// <param name="result"></param>
  435. /// <exception cref="NotImplementedException"></exception>
  436. private void OnLockFinish(LockResult result)
  437. {
  438. //如果当前螺丝编号为1,则清除之前的结果
  439. //if (result.Number == 1)
  440. //{
  441. // LockResults.Clear();
  442. //}
  443. LockResults.Add(result);
  444. //更新曲线图
  445. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  446. var series = LockCurvePlotModel.Series[0] as LineSeries;
  447. series.Points.Clear();
  448. foreach (var waveData in result.WaveDatas)
  449. {
  450. series.Points.Add(new OxyPlot.DataPoint(waveData.LockAngle, waveData.Torque));
  451. }
  452. LockCurvePlotModel.InvalidatePlot(true);
  453. }));
  454. }
  455. #endregion
  456. #region 继承
  457. /// <summary>
  458. /// 确认导航请求时调用。此方法允许您在导航之前执行一些操作。
  459. /// </summary>
  460. /// <param name="navigationContext"></param>
  461. /// <param name="continuationCallback"></param>
  462. public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
  463. {
  464. continuationCallback(true);
  465. }
  466. /// <summary>
  467. /// 接收导航请求时调用。传入导航参数,包含有关导航目标的信息。
  468. /// </summary>
  469. /// <param name="navigationContext"></param>
  470. /// <exception cref="NotImplementedException"></exception>
  471. public async void OnNavigatedTo(NavigationContext navigationContext)
  472. {
  473. if (_systemDatabaseService.GetCurrentUser().userPart == Enums.UserPart.Operator || _systemDatabaseService.GetCurrentUser().userPart == Enums.UserPart.Engineer)
  474. {
  475. IsAllowEdit = false;
  476. }
  477. else
  478. {
  479. IsAllowEdit = true;
  480. }
  481. try
  482. {
  483. ProductList = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
  484. }
  485. catch (Exception ex)
  486. {
  487. LogHelper.WriteLogError("主界面界面进入时出错!", ex);
  488. }
  489. }
  490. /// <summary>
  491. /// 是否允许导航到此视图模型。
  492. /// </summary>
  493. /// <param name="navigationContext"></param>
  494. /// <returns></returns>
  495. public bool IsNavigationTarget(NavigationContext navigationContext)
  496. {
  497. return true;
  498. }
  499. /// <summary>
  500. /// 导航离开此视图模型时调用。您可以在此处执行清理操作或保存状态。
  501. /// </summary>
  502. /// <param name="navigationContext"></param>
  503. public void OnNavigatedFrom(NavigationContext navigationContext)
  504. {
  505. }
  506. #endregion
  507. private void _productService_OnProductChanged(ProductModel obj)
  508. {
  509. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  510. CurrentProduct = obj;
  511. }));
  512. }
  513. }
  514. }