HomeViewModel.cs 16 KB

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