HomeViewModel.cs 22 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.WritePositionToPlcAsync();
  238. await management.WriteParameterToPlcAsync();
  239. if (DialogHost.IsDialogOpen("RootDialog"))
  240. {
  241. DialogHost.Close("RootDialog");
  242. }
  243. await task;
  244. //DatabaseHelper.AddLoadProductRecord(product.ID, product.Name, false);
  245. IsLoadProduct = true;
  246. }
  247. }
  248. }
  249. void ExecuteCopyCommand(string textToCopy)
  250. {
  251. Clipboard.SetText(textToCopy);
  252. }
  253. /// <summary>
  254. /// 添加消息至消息队列
  255. /// </summary>
  256. /// <param name="msg"></param>
  257. /// <param name="color"></param>
  258. public void AddMessage(string msg, Color color)
  259. {
  260. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  261. try
  262. {
  263. MessageQueue.Add(new TaskMessage()
  264. {
  265. DT = DateTime.Now,
  266. Message = msg,
  267. FontColol = new SolidColorBrush(color)
  268. });
  269. LogHelper.WriteLogInfo(msg);
  270. }
  271. catch (Exception)
  272. {
  273. }
  274. }));
  275. }
  276. /// <summary>
  277. /// 添加消息至消息队列
  278. /// </summary>
  279. /// <param name="msg"></param>
  280. /// <param name="color"></param>
  281. public void AddMessage(string msg, MessageLevel level)
  282. {
  283. MessageStruct messageStruct = new MessageStruct() { Message = msg, level = level };
  284. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  285. AddMessage(messageStruct);
  286. }));
  287. }
  288. /// <summary>
  289. /// 添加消息至消息队列
  290. /// </summary>
  291. /// <param name="messageStruct"></param>
  292. public void AddMessage(MessageStruct messageStruct)
  293. {
  294. try
  295. {
  296. if (MessageQueue.Count >= 200)
  297. {
  298. MessageQueue.RemoveAt(0);// 从队列头部移除最早的消息
  299. }
  300. Color color = Colors.Black;
  301. switch (messageStruct.level)
  302. {
  303. case MessageLevel.Info:
  304. color = Colors.Black;
  305. break;
  306. case MessageLevel.Debug:
  307. color = Colors.Green;
  308. break;
  309. case MessageLevel.Alarm:
  310. color = Colors.Orange;
  311. break;
  312. case MessageLevel.Error:
  313. color = Colors.Red;
  314. break;
  315. }
  316. MessageQueue.Add(new TaskMessage()
  317. {
  318. DT = DateTime.Now,
  319. Message = messageStruct.Message,
  320. FontColol = new SolidColorBrush(color)
  321. });
  322. LogHelper.WriteLogInfo(messageStruct.Message);
  323. }
  324. catch (Exception)
  325. {
  326. }
  327. }
  328. public void AddMessageInvoke(MessageStruct messageStruct)
  329. {
  330. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  331. AddMessage(messageStruct);
  332. }));
  333. }
  334. private void LoginChange(Models.User user)
  335. {
  336. }
  337. /// <summary>
  338. /// 重置计数
  339. /// </summary>
  340. async void ExecuteResetCounterCommand()
  341. {
  342. var currentProduct = _productService.GetCurrentProduct();
  343. if (currentProduct == null) return;
  344. var view = new ShowMessage(Lang.计数清零, Lang.是否重置当前产品的计数);
  345. //show the dialog
  346. var result = await DialogHost.Show(view, "RootDialog", null, null, null);
  347. if (result != null && result is bool)
  348. {
  349. if (((bool)result))
  350. {
  351. isCanExecute = false;
  352. await _systemDatabaseService.ResetProductionAsync(currentProduct.Name);
  353. isCanExecute = true;
  354. }
  355. }
  356. }
  357. //初始化曲线图
  358. private void InitLockCurvePlotModel()
  359. {
  360. var model = new PlotModel { Title = "锁付曲线", 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 = "角度 (°)",
  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 = "力矩 (kgf)",
  387. MajorGridlineStyle = LineStyle.Solid,
  388. MinorGridlineStyle = LineStyle.Dot
  389. };
  390. model.Axes.Add(yAxis);
  391. // 添加示例数据系列
  392. var series = new LineSeries
  393. {
  394. Title = "锁付力矩曲线",
  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. model.InvalidatePlot(true);
  465. if (!string.IsNullOrEmpty(tuple.SavePath))
  466. {
  467. if (!Directory.Exists(Path.GetDirectoryName(tuple.SavePath)))
  468. {
  469. Directory.CreateDirectory(Path.GetDirectoryName(tuple.SavePath));
  470. }
  471. PngExporter.Export(model, tuple.SavePath, (int)model.Width, (int)model.Height);
  472. }
  473. }));
  474. }
  475. }
  476. // 初始化由配置决定的曲线数量(在读取 SystemConfiguration 后调用)
  477. public void InitPressurePlots(IEnumerable<PressureSensorSettings> sensors)
  478. {
  479. PressurePlotModels.Clear();
  480. _sensorIdToIndex.Clear();
  481. int idx = 0;
  482. foreach (var s in sensors)
  483. {
  484. var model = CreatePlotModelForSensor(s);
  485. PressurePlotModels.Add(model);
  486. // 假设 PressureSensorConfig 有唯一 Id(string 或 int)
  487. _sensorIdToIndex[s.SensorId.ToString()] = idx++;
  488. }
  489. }
  490. private PlotModel CreatePlotModelForSensor(PressureSensorSettings sensor)
  491. {
  492. var model = new PlotModel { Title = sensor.SensorName ?? $"Sensor {sensor.SensorId}", TitleFontSize = 16 };
  493. // 设置图例
  494. var legend = new Legend
  495. {
  496. LegendPosition = LegendPosition.TopRight,
  497. LegendPlacement = LegendPlacement.Outside,
  498. LegendOrientation = LegendOrientation.Vertical,
  499. LegendBorderThickness = 0
  500. };
  501. model.Legends.Add(legend);
  502. // 设置X轴
  503. var xAxis = new LinearAxis
  504. {
  505. Key = "X",
  506. Position = AxisPosition.Bottom,
  507. Title = "Time (s)",
  508. Minimum = 0,
  509. MajorGridlineStyle = LineStyle.Solid,
  510. MinorGridlineStyle = LineStyle.Dot
  511. };
  512. model.Axes.Add(xAxis);
  513. // 设置Y轴
  514. var yAxis = new LinearAxis
  515. {
  516. Key = "Y",
  517. Position = AxisPosition.Left,
  518. Title = "Pressure",
  519. MajorGridlineStyle = LineStyle.Solid,
  520. MinorGridlineStyle = LineStyle.Dot
  521. };
  522. model.Axes.Add(yAxis);
  523. // 添加示例数据系列
  524. var series = new LineSeries
  525. {
  526. Title = sensor.SensorName ?? $"Sensor {sensor.SensorId}",
  527. StrokeThickness = 2,
  528. MarkerSize = 3,
  529. MarkerType = MarkerType.Circle,
  530. CanTrackerInterpolatePoints = false,
  531. };
  532. model.Series.Add(series);
  533. return model;
  534. }
  535. #endregion
  536. #region 继承
  537. /// <summary>
  538. /// 确认导航请求时调用。此方法允许您在导航之前执行一些操作。
  539. /// </summary>
  540. /// <param name="navigationContext"></param>
  541. /// <param name="continuationCallback"></param>
  542. public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
  543. {
  544. continuationCallback(true);
  545. }
  546. /// <summary>
  547. /// 接收导航请求时调用。传入导航参数,包含有关导航目标的信息。
  548. /// </summary>
  549. /// <param name="navigationContext"></param>
  550. /// <exception cref="NotImplementedException"></exception>
  551. public async void OnNavigatedTo(NavigationContext navigationContext)
  552. {
  553. try
  554. {
  555. ProductList = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
  556. }
  557. catch (Exception ex)
  558. {
  559. LogHelper.WriteLogError("主界面界面进入时出错!", ex);
  560. }
  561. }
  562. /// <summary>
  563. /// 是否允许导航到此视图模型。
  564. /// </summary>
  565. /// <param name="navigationContext"></param>
  566. /// <returns></returns>
  567. public bool IsNavigationTarget(NavigationContext navigationContext)
  568. {
  569. return true;
  570. }
  571. /// <summary>
  572. /// 导航离开此视图模型时调用。您可以在此处执行清理操作或保存状态。
  573. /// </summary>
  574. /// <param name="navigationContext"></param>
  575. public void OnNavigatedFrom(NavigationContext navigationContext)
  576. {
  577. }
  578. #endregion
  579. private void _productService_OnProductChanged(ProductModel obj)
  580. {
  581. App.Current.Dispatcher.BeginInvoke(new Action(() => {
  582. CurrentProduct = obj;
  583. }));
  584. }
  585. }
  586. }