HomeViewModel.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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 System;
  15. using System.Collections.Generic;
  16. using System.Collections.ObjectModel;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Threading.Tasks;
  20. using System.Windows;
  21. using System.Windows.Media;
  22. using TeamAAS_VP;
  23. using TeamAAS_VP.Controls;
  24. using TeamAAS_VP.Core;
  25. using TeamAAS_VP.Data;
  26. using TeamAAS_VP.Enums;
  27. using TeamAAS_VP.Events;
  28. using TeamAAS_VP.Interfaces;
  29. using TeamAAS_VP.Models;
  30. using TeamAAS_VP.Resources.Languages;
  31. using TeamAAS_VP.Services;
  32. using TeamAAS_VP.ViewModels.DebugMod;
  33. using TeamAAS_VP.Views.DebugMod;
  34. using static TeamAAS_VP.Models.SystemConfiguration;
  35. namespace TeamAAS_VP.ViewModels
  36. {
  37. public class HomeViewModel : BindableBase, IConfirmNavigationRequest
  38. {
  39. IEventAggregator _eventAggregator;
  40. IContainerProvider _container;
  41. IProductService _productService;
  42. IConfigService _configService;
  43. IRemoteCommandService _remoteCommandService;
  44. ISystemDatabaseService _systemDatabaseService;
  45. #region 属性
  46. private ObservableCollection<TaskMessage> messageQueue = new ObservableCollection<TaskMessage>();
  47. /// <summary>
  48. /// 运行信息队列
  49. /// </summary>
  50. public ObservableCollection<TaskMessage> MessageQueue
  51. {
  52. get { return messageQueue; }
  53. set { SetProperty(ref messageQueue, value); }
  54. }
  55. private ObservableCollection<ProductModel> _ProductList;
  56. public ObservableCollection<ProductModel> ProductList
  57. {
  58. get { return _ProductList; }
  59. set { SetProperty(ref _ProductList, value); }
  60. }
  61. private Management _management;
  62. public Management management
  63. {
  64. get { return _management; }
  65. set { SetProperty(ref _management, value); }
  66. }
  67. private double _CTTotalSeconds;
  68. public double CTTotalSeconds
  69. {
  70. get { return _CTTotalSeconds; }
  71. set { SetProperty(ref _CTTotalSeconds, value); }
  72. }
  73. private ProductModel _SelectProduct;
  74. public ProductModel SelectProduct
  75. {
  76. get { return _SelectProduct; }
  77. set { SetProperty(ref _SelectProduct, value); }
  78. }
  79. private bool CanLoad
  80. {
  81. get
  82. {
  83. if (SelectProduct != null && IsLoadProduct)
  84. {
  85. return true;
  86. }
  87. else
  88. {
  89. return false;
  90. }
  91. }
  92. }
  93. private bool _IsLoadProduct = true;
  94. public bool IsLoadProduct
  95. {
  96. get { return _IsLoadProduct; }
  97. set { SetProperty(ref _IsLoadProduct, value); }
  98. }
  99. private bool _isCanExecute = true;
  100. public bool isCanExecute
  101. {
  102. get { return _isCanExecute; }
  103. set { SetProperty(ref _isCanExecute, value); }
  104. }
  105. private ProductModel _CurrentProduct;
  106. public ProductModel CurrentProduct
  107. {
  108. get { return _CurrentProduct; }
  109. set { SetProperty(ref _CurrentProduct, value); }
  110. }
  111. private ObservableCollection<PlotModel> _PressurePlotModels = new ObservableCollection<PlotModel>();
  112. /// <summary>
  113. /// 每个元素是一个 PlotModel,对应一个压力传感器
  114. /// </summary>
  115. public ObservableCollection<PlotModel> PressurePlotModels
  116. {
  117. get { return _PressurePlotModels; }
  118. set { SetProperty(ref _PressurePlotModels, value); }
  119. }
  120. private PlotModel _LockCurvePlotModel;
  121. /// <summary>
  122. /// 锁付曲线
  123. /// </summary>
  124. public PlotModel LockCurvePlotModel
  125. {
  126. get { return _LockCurvePlotModel; }
  127. set { SetProperty(ref _LockCurvePlotModel, value); }
  128. }
  129. private ObservableCollection<LockResult> _LockResults = new ObservableCollection<LockResult>();
  130. /// <summary>
  131. /// 锁付结果列表
  132. /// </summary>
  133. public ObservableCollection<LockResult> LockResults
  134. {
  135. get { return _LockResults; }
  136. set { SetProperty(ref _LockResults, value); }
  137. }
  138. private ObservableCollection<AssemblyRecord> _AssemblyResults=new ObservableCollection<AssemblyRecord>();
  139. /// <summary>
  140. /// 组装结果列表
  141. /// </summary>
  142. public ObservableCollection<AssemblyRecord> AssemblyResults
  143. {
  144. get { return _AssemblyResults; }
  145. set { SetProperty(ref _AssemblyResults, value); }
  146. }
  147. // 可选:记录传感器 Id -> 索引 的映射,便于外部(如 Management)按 Id 更新
  148. private readonly Dictionary<string, int> _sensorIdToIndex = new Dictionary<string, int>();
  149. #endregion
  150. #region 命令
  151. public DelegateCommand LoadedCommand { get; set; }
  152. private DelegateCommand<ProductModel> _LoadProductCommand;
  153. public DelegateCommand<ProductModel> LoadProductCommand =>
  154. _LoadProductCommand ?? (_LoadProductCommand = new DelegateCommand<ProductModel>(ExecuteLoadProductCommand).ObservesCanExecute(() => CanLoad).ObservesProperty(() => SelectProduct).ObservesProperty(() => IsLoadProduct));
  155. private DelegateCommand _ResetCounterCommand;
  156. public DelegateCommand ResetCounterCommand =>
  157. _ResetCounterCommand ?? (_ResetCounterCommand = new DelegateCommand(ExecuteResetCounterCommand).ObservesCanExecute(() => DoCondition).ObservesProperty(() => isCanExecute));
  158. private bool DoCondition
  159. {
  160. get { return isCanExecute; }
  161. }
  162. private DelegateCommand<string> _CopyCommand;
  163. public DelegateCommand<string> CopyCommand =>
  164. _CopyCommand ?? (_CopyCommand = new DelegateCommand<string>(ExecuteCopyCommand));
  165. #endregion
  166. #region 事件
  167. #endregion
  168. public HomeViewModel(IEventAggregator ea, IContainerProvider container, IProductService productService, IConfigService configService, IRemoteCommandService remoteCommandService
  169. , ISystemDatabaseService systemDatabaseService)
  170. {
  171. _eventAggregator = ea;
  172. _container = container;
  173. _productService = productService;
  174. LoadedCommand = new DelegateCommand(OnLoad);
  175. _eventAggregator.GetEvent<TaskMessageNotification>().Subscribe(AddMessageInvoke);
  176. //订阅权限登录事件
  177. _eventAggregator.GetEvent<UserLoginNotification>().Subscribe(LoginChange);
  178. management = _container.Resolve<Management>();
  179. _configService = configService;
  180. _productService.OnProductChanged += _productService_OnProductChanged;
  181. _remoteCommandService = remoteCommandService;
  182. _remoteCommandService.CycleTimingTicked += _remoteCommandService_CycleTimingTicked;
  183. _systemDatabaseService = systemDatabaseService;
  184. _eventAggregator.GetEvent<LockFinishNotification>().Subscribe(OnLockFinish);
  185. _eventAggregator.GetEvent<PressureFinishNotification>().Subscribe(OnPressureFinish);
  186. _eventAggregator.GetEvent<AssemblyFinishNotification>().Subscribe(OnAssemblyFinish);
  187. //获取所有的压力传感器配置,初始化曲线图
  188. var systemConfig = _configService.GetSystemConfiguration();
  189. if (systemConfig.PressureSensorConfig != null)
  190. {
  191. InitPressurePlots(systemConfig.PressureSensorConfig.ToArray());
  192. }
  193. }
  194. private void _remoteCommandService_CycleTimingTicked(object sender, TimeSpan e)
  195. {
  196. try
  197. {
  198. if (App.Current != null)
  199. {
  200. App.Current.Invoke(() =>
  201. {
  202. CTTotalSeconds = e.TotalSeconds;
  203. });
  204. }
  205. }
  206. catch (Exception)
  207. {
  208. }
  209. }
  210. #region 方法
  211. bool isFirst = true;
  212. private void OnLoad()
  213. {
  214. if (!isFirst)
  215. {
  216. return;
  217. }
  218. InitLockCurvePlotModel();
  219. isFirst = false;
  220. }
  221. async void ExecuteLoadProductCommand(ProductModel product)
  222. {
  223. if (product == null) return;
  224. var view = new ShowMessage(Lang.是否加载产品, $"{Lang.加载产品}:{product.Name}?");
  225. //show the dialog
  226. var result = await DialogHost.Show(view, "RootDialog", null, null, null);
  227. if (result != null && result is bool)
  228. {
  229. if (((bool)result))
  230. {
  231. IsLoadProduct = false;
  232. var waiting = new WaitingControl();
  233. //show the dialog
  234. var task = DialogHost.Show(waiting, "RootDialog", null, null, null);
  235. await _productService.LoadProductAsync(product.ID);
  236. _productService.SetCurrentProduct(product.ID);
  237. await management.WriteParameterToPlcExAsync();
  238. if (DialogHost.IsDialogOpen("RootDialog"))
  239. {
  240. DialogHost.Close("RootDialog");
  241. }
  242. await task;
  243. //DatabaseHelper.AddLoadProductRecord(product.ID, product.Name, false);
  244. IsLoadProduct = true;
  245. }
  246. }
  247. }
  248. void ExecuteCopyCommand(string textToCopy)
  249. {
  250. Clipboard.SetText(textToCopy);
  251. }
  252. /// <summary>
  253. /// 添加消息至消息队列
  254. /// </summary>
  255. /// <param name="msg"></param>
  256. /// <param name="color"></param>
  257. public void AddMessage(string msg, Color color)
  258. {
  259. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  260. try
  261. {
  262. MessageQueue.Add(new TaskMessage()
  263. {
  264. DT = DateTime.Now,
  265. Message = msg,
  266. FontColol = new SolidColorBrush(color)
  267. });
  268. LogHelper.WriteLogInfo(msg);
  269. }
  270. catch (Exception)
  271. {
  272. }
  273. }));
  274. }
  275. /// <summary>
  276. /// 添加消息至消息队列
  277. /// </summary>
  278. /// <param name="msg"></param>
  279. /// <param name="color"></param>
  280. public void AddMessage(string msg, MessageLevel level)
  281. {
  282. MessageStruct messageStruct = new MessageStruct() { Message = msg, level = level };
  283. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  284. AddMessage(messageStruct);
  285. }));
  286. }
  287. /// <summary>
  288. /// 添加消息至消息队列
  289. /// </summary>
  290. /// <param name="messageStruct"></param>
  291. public void AddMessage(MessageStruct messageStruct)
  292. {
  293. try
  294. {
  295. if (MessageQueue.Count >= 200)
  296. {
  297. MessageQueue.RemoveAt(0);// 从队列头部移除最早的消息
  298. }
  299. Color color = Colors.Black;
  300. switch (messageStruct.level)
  301. {
  302. case MessageLevel.Info:
  303. color = Colors.Black;
  304. break;
  305. case MessageLevel.Debug:
  306. color = Colors.Green;
  307. break;
  308. case MessageLevel.Alarm:
  309. color = Colors.Orange;
  310. break;
  311. case MessageLevel.Error:
  312. color = Colors.Red;
  313. break;
  314. }
  315. MessageQueue.Add(new TaskMessage()
  316. {
  317. DT = DateTime.Now,
  318. Message = messageStruct.Message,
  319. FontColol = new SolidColorBrush(color)
  320. });
  321. LogHelper.WriteLogInfo(messageStruct.Message);
  322. }
  323. catch (Exception)
  324. {
  325. }
  326. }
  327. public void AddMessageInvoke(MessageStruct messageStruct)
  328. {
  329. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  330. AddMessage(messageStruct);
  331. }));
  332. }
  333. private void LoginChange(Models.User user)
  334. {
  335. }
  336. /// <summary>
  337. /// 重置计数
  338. /// </summary>
  339. async void ExecuteResetCounterCommand()
  340. {
  341. var currentProduct = _productService.GetCurrentProduct();
  342. if (currentProduct == null) return;
  343. var view = new ShowMessage(Lang.计数清零, Lang.是否重置当前产品的计数);
  344. //show the dialog
  345. var result = await DialogHost.Show(view, "RootDialog", null, null, null);
  346. if (result != null && result is bool)
  347. {
  348. if (((bool)result))
  349. {
  350. isCanExecute = false;
  351. await _systemDatabaseService.ResetProductionAsync(currentProduct.Name);
  352. await _systemDatabaseService.ResetThrowNumberAsync();
  353. isCanExecute = true;
  354. }
  355. }
  356. }
  357. //初始化曲线图
  358. private void InitLockCurvePlotModel()
  359. {
  360. var model = new PlotModel { Title = Lang.锁付曲线, TitleFontSize = 16 };
  361. // 设置图例
  362. var legend = new Legend
  363. {
  364. LegendPosition = LegendPosition.TopRight,
  365. LegendPlacement = LegendPlacement.Outside,
  366. LegendOrientation = LegendOrientation.Vertical,
  367. LegendBorderThickness = 0
  368. };
  369. model.Legends.Add(legend);
  370. // 设置X轴
  371. var xAxis = new LinearAxis
  372. {
  373. Key = "X",
  374. Position = AxisPosition.Bottom,
  375. Title = Lang.角度数,
  376. Minimum = 0,
  377. MajorGridlineStyle = LineStyle.Solid,
  378. MinorGridlineStyle = LineStyle.Dot
  379. };
  380. model.Axes.Add(xAxis);
  381. // 设置Y轴
  382. var yAxis = new LinearAxis
  383. {
  384. Key = "Y",
  385. Position = AxisPosition.Left,
  386. Title = Lang.力矩kgf,
  387. MajorGridlineStyle = LineStyle.Solid,
  388. MinorGridlineStyle = LineStyle.Dot
  389. };
  390. model.Axes.Add(yAxis);
  391. // 添加示例数据系列
  392. var series = new LineSeries
  393. {
  394. Title = Lang.锁付力矩曲线,
  395. StrokeThickness = 2,
  396. MarkerSize = 3,
  397. MarkerType = MarkerType.Circle,
  398. CanTrackerInterpolatePoints = false,
  399. };
  400. model.Series.Add(series);
  401. LockCurvePlotModel = model;
  402. }
  403. /// <summary>
  404. /// 螺丝锁付完成时调用
  405. /// </summary>
  406. /// <param name="result"></param>
  407. /// <exception cref="NotImplementedException"></exception>
  408. private void OnLockFinish(LockResult result)
  409. {
  410. //如果当前螺丝编号为1,则清除之前的结果
  411. if (result.Number == 1)
  412. {
  413. LockResults.Clear();
  414. }
  415. LockResults.Add(result);
  416. //更新曲线图
  417. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  418. var series = LockCurvePlotModel.Series[0] as LineSeries;
  419. //var yaxis = LockCurvePlotModel.Axes.FirstOrDefault(p=>p.Key=="Y");
  420. //yaxis.Maximum = result.TargetTorque;
  421. series.Points.Clear();
  422. foreach (var waveData in result.WaveDatas)
  423. {
  424. series.Points.Add(new OxyPlot.DataPoint(waveData.LockAngle, waveData.Torque));
  425. }
  426. LockCurvePlotModel.InvalidatePlot(true);
  427. }));
  428. }
  429. /// <summary>
  430. /// 锁付完成时调用
  431. /// </summary>
  432. /// <param name="record"></param>
  433. /// <exception cref="NotImplementedException"></exception>
  434. private void OnAssemblyFinish(AssemblyRecord record)
  435. {
  436. AssemblyResults.Add(record);
  437. //如果记录数超过1000,则删除最早的记录
  438. if (AssemblyResults.Count > 50)
  439. {
  440. AssemblyResults.RemoveAt(0);
  441. }
  442. }
  443. /// <summary>
  444. /// 保压完成时调用
  445. /// </summary>
  446. /// <param name="tuple"></param>
  447. private void OnPressureFinish((bool IsSuccess, int Index, (DateTime Timestamp, float Value)[] values, string SavePath) tuple)
  448. {
  449. //更新对应传感器的曲线图
  450. if (_sensorIdToIndex.TryGetValue(tuple.Index.ToString(), out int index))
  451. {
  452. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  453. var model = PressurePlotModels[index];
  454. var series = model.Series[0] as LineSeries;
  455. series.Points.Clear();
  456. //第一个点的时间作为X轴起点
  457. DateTime xAxisStart = tuple.values[0].Timestamp;
  458. foreach (var dataPoint in tuple.values)
  459. {
  460. // 计算相对于起点的秒数作为X轴坐标
  461. double xValue = (dataPoint.Timestamp - xAxisStart).TotalSeconds;
  462. series.Points.Add(new OxyPlot.DataPoint(xValue, dataPoint.Value));
  463. }
  464. // 重置所有轴的范围以适应新数据
  465. model.ResetAllAxes();
  466. model.InvalidatePlot(true);
  467. if (!string.IsNullOrEmpty(tuple.SavePath))
  468. {
  469. if (!Directory.Exists(Path.GetDirectoryName(tuple.SavePath)))
  470. {
  471. Directory.CreateDirectory(Path.GetDirectoryName(tuple.SavePath));
  472. }
  473. PngExporter.Export(model, tuple.SavePath, (int)model.Width, (int)model.Height);
  474. }
  475. }));
  476. }
  477. }
  478. // 初始化由配置决定的曲线数量(在读取 SystemConfiguration 后调用)
  479. public void InitPressurePlots(IEnumerable<PressureSensorSettings> sensors)
  480. {
  481. PressurePlotModels.Clear();
  482. _sensorIdToIndex.Clear();
  483. int idx = 0;
  484. foreach (var s in sensors)
  485. {
  486. var model = CreatePlotModelForSensor(s);
  487. PressurePlotModels.Add(model);
  488. // 假设 PressureSensorConfig 有唯一 Id(string 或 int)
  489. _sensorIdToIndex[s.SensorId.ToString()] = idx++;
  490. }
  491. }
  492. private PlotModel CreatePlotModelForSensor(PressureSensorSettings sensor)
  493. {
  494. var model = new PlotModel { Title = sensor.SensorName ?? $"Sensor {sensor.SensorId}", TitleFontSize = 16 };
  495. // 设置图例
  496. var legend = new Legend
  497. {
  498. LegendPosition = LegendPosition.TopRight,
  499. LegendPlacement = LegendPlacement.Outside,
  500. LegendOrientation = LegendOrientation.Vertical,
  501. LegendBorderThickness = 0
  502. };
  503. model.Legends.Add(legend);
  504. // 设置X轴
  505. var xAxis = new LinearAxis
  506. {
  507. Key = "X",
  508. Position = AxisPosition.Bottom,
  509. Title = "Time (s)",
  510. Minimum = 0,
  511. MajorGridlineStyle = LineStyle.Solid,
  512. MinorGridlineStyle = LineStyle.Dot
  513. };
  514. model.Axes.Add(xAxis);
  515. // 设置Y轴
  516. var yAxis = new LinearAxis
  517. {
  518. Key = "Y",
  519. Position = AxisPosition.Left,
  520. Title = "Pressure",
  521. MajorGridlineStyle = LineStyle.Solid,
  522. MinorGridlineStyle = LineStyle.Dot
  523. };
  524. model.Axes.Add(yAxis);
  525. // 添加示例数据系列
  526. var series = new LineSeries
  527. {
  528. Title = sensor.SensorName ?? $"Sensor {sensor.SensorId}",
  529. StrokeThickness = 2,
  530. MarkerSize = 3,
  531. MarkerType = MarkerType.Circle,
  532. CanTrackerInterpolatePoints = false,
  533. };
  534. model.Series.Add(series);
  535. return model;
  536. }
  537. #endregion
  538. #region 继承
  539. /// <summary>
  540. /// 确认导航请求时调用。此方法允许您在导航之前执行一些操作。
  541. /// </summary>
  542. /// <param name="navigationContext"></param>
  543. /// <param name="continuationCallback"></param>
  544. public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
  545. {
  546. continuationCallback(true);
  547. }
  548. /// <summary>
  549. /// 接收导航请求时调用。传入导航参数,包含有关导航目标的信息。
  550. /// </summary>
  551. /// <param name="navigationContext"></param>
  552. /// <exception cref="NotImplementedException"></exception>
  553. public async void OnNavigatedTo(NavigationContext navigationContext)
  554. {
  555. try
  556. {
  557. ProductList = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
  558. }
  559. catch (Exception ex)
  560. {
  561. LogHelper.WriteLogError("主界面界面进入时出错!", ex);
  562. }
  563. }
  564. /// <summary>
  565. /// 是否允许导航到此视图模型。
  566. /// </summary>
  567. /// <param name="navigationContext"></param>
  568. /// <returns></returns>
  569. public bool IsNavigationTarget(NavigationContext navigationContext)
  570. {
  571. return true;
  572. }
  573. /// <summary>
  574. /// 导航离开此视图模型时调用。您可以在此处执行清理操作或保存状态。
  575. /// </summary>
  576. /// <param name="navigationContext"></param>
  577. public void OnNavigatedFrom(NavigationContext navigationContext)
  578. {
  579. }
  580. #endregion
  581. private void _productService_OnProductChanged(ProductModel obj)
  582. {
  583. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  584. CurrentProduct = obj;
  585. }));
  586. }
  587. }
  588. }