HomeViewModel.cs 17 KB

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