RandomMainPageViewModel.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. using Avalonia;
  2. using Avalonia.Collections;
  3. using Avalonia.Controls;
  4. using Avalonia.Controls.ApplicationLifetimes;
  5. using CommunityToolkit.Mvvm.Input;
  6. using OxyPlot;
  7. using OxyPlot.Series;
  8. using Shaker.Models;
  9. using ShakerApp.Tools;
  10. using ShakerApp.Views;
  11. using System;
  12. using System.Collections;
  13. using System.Collections.Generic;
  14. using System.Linq;
  15. using System.Text;
  16. using System.Threading.Tasks;
  17. using System.Windows.Input;
  18. namespace ShakerApp.ViewModels
  19. {
  20. internal class RandomMainPageViewModel:BaseMainPageViewModel<RandomDataModel>
  21. {
  22. public const string SpectrumData = "SpectrumData";
  23. [PropertyAssociation(nameof(RandomDataModel.TestTotalRunTime))]
  24. public uint TestTotalRunTime => Model.TestTotalRunTime;
  25. [PropertyAssociation(nameof(RandomDataModel.CurrentIdentifyDisplacement))]
  26. public double CurrentIdentifyDisplacement => Model.CurrentIdentifyDisplacement;
  27. [PropertyAssociation(nameof(RandomDataModel.CurrentIdentifyRms))]
  28. public double CurrentIdentifyRms => Model.CurrentIdentifyRms;
  29. [PropertyAssociation(nameof(RandomDataModel.IdentifyIndex))]
  30. public double IdentifyIndex => Model.IdentifyIndex;
  31. [PropertyAssociation(nameof(RandomDataModel.RandomStatus))]
  32. public RandomStatus RandomStatus => Model.RandomStatus;
  33. [PropertyAssociation(nameof(RandomDataModel.TimeDomainRMS))]
  34. public double TimeDomainRMS => Model.TimeDomainRMS;
  35. public bool NextButtonVisilily => RandomTestStep == RandomTestStep.Test;
  36. [PropertyAssociation(nameof(RandomDataModel.RandomTestStep))]
  37. public RandomTestStep RandomTestStep => Model.RandomTestStep;
  38. [PropertyAssociation(nameof(RandomDataModel.RandomTestStep))]
  39. public string RandomTestStepKey => RandomTestStep.Description();
  40. public bool NextButtonIsEnabled { get => nextButtonIsEnabled; set =>SetProperty(ref nextButtonIsEnabled , value); }
  41. [PropertyAssociation(nameof(RandomDataModel.CurrentTestLevel))]
  42. public double CurrentTestLevel => Model.CurrentTestLevel;
  43. [PropertyAssociation(nameof(RandomDataModel.CurrentTestTime))]
  44. public uint CurrentTestTime => Model.CurrentTestTime;
  45. [PropertyAssociation(nameof(RandomDataModel.CurrentLevelTestMaxTime))]
  46. public uint CurrentLevelTestMaxTime => Model.CurrentLevelTestMaxTime;
  47. public AvaloniaList<LineSeries> LineSeries { get; } = new AvaloniaList<LineSeries>();
  48. List<OxyColor> oxyColors = new List<OxyColor>() {OxyColors.Blue, OxyColors.Black, OxyColors.Green, OxyColors.Red, OxyColors.Red, OxyColors.Yellow, OxyColors.Yellow };
  49. List<LineStyle> lineStyles = new List<LineStyle>() { LineStyle.Solid, LineStyle.Solid, LineStyle.Solid, LineStyle.Solid, LineStyle.Solid, LineStyle.LongDashDotDot, LineStyle.LongDashDotDot };
  50. List<string> properties = new List<string>() {nameof(RandomData.Driver), nameof(RandomData.Acceleration), nameof(RandomData.TargetAcceleration), nameof(RandomData.UpStopAcceleration), nameof(RandomData.DownStopAcceleration), nameof(RandomData.UpWarnAcceleration), nameof(RandomData.DownWarnAcceleration) };
  51. List<RandomData> datas = new List<RandomData>();
  52. private bool nextButtonIsEnabled = true;
  53. private RandomMainPageViewModel()
  54. {
  55. Content = typeof(Views.RandomMainPage);
  56. #region 加速度谱曲线
  57. PlotModel.Axes.Add(new OxyPlot.Axes.LogarithmicAxis()
  58. {
  59. MaximumPadding = 0,
  60. MinimumPadding = 0,
  61. Title = App.Current?.FindResource(ShakerConstant.FrequencyKey) + "",
  62. Unit = "Hz",
  63. MajorGridlineStyle = LineStyle.Solid,
  64. Position = OxyPlot.Axes.AxisPosition.Bottom,
  65. Key = "Freq"
  66. });
  67. PlotModel.Axes.Add(new OxyPlot.Axes.LogarithmicAxis()
  68. {
  69. Key = "Ampt",
  70. Title = App.Current?.FindResource(ShakerConstant.AmptAxisTitleKey) + "",
  71. Unit = App.Current?.FindResource("RandomValueUnit")?.ToString() ?? string.Empty,
  72. MajorGridlineStyle = LineStyle.Solid,
  73. Position = OxyPlot.Axes.AxisPosition.Left,
  74. });
  75. PlotModel.Title = App.Current?.FindResource(MainPageType.RandomPage.Description()) + "";
  76. for (int i = 0; i < oxyColors.Count; i++)
  77. {
  78. LineSeries line = new LineSeries();
  79. line.Title = App.Current?.FindResource(ShakerConstant.ShowRandomAccelerationSpectrumNames[i]) + "";
  80. line.Color = oxyColors[i];
  81. line.StrokeThickness = 1;
  82. line.DataFieldX = nameof(SweepData.Frequency);
  83. line.DataFieldY = properties[i];
  84. line.LineStyle = lineStyles[i];
  85. line.XAxisKey = "Freq";
  86. line.YAxisKey = "Ampt";
  87. line.Tag = App.Current?.FindResource("RandomValueUnit")?.ToString() ?? string.Empty;
  88. LineSeries.Add(line);
  89. PlotModel.Series.Add(line);
  90. }
  91. PlotModel.Legends.Add(new OxyPlot.Legends.Legend()
  92. {
  93. ShowInvisibleSeries = true,
  94. });
  95. PlotModel.Title = App.Current?.FindResource(MainPageType.RandomPage.Description()) + "";
  96. #endregion
  97. GetEvent(ShakerSettingViewModel.LANGUAGECHANGEDEVENT).Subscrip((_, _) =>
  98. {
  99. PlotModel.InvalidatePlot(false);
  100. PlotModel.Title = App.Current?.FindResource(MainPageType.RandomPage.Description()) + "";
  101. PlotModel.Axes[0].Title = App.Current?.FindResource("Frequency") + "";
  102. PlotModel.Axes[1].Title = Title = App.Current?.FindResource("Ampt") + "";
  103. PlotModel.InvalidatePlot(true);
  104. });
  105. GetEvent<AllConfig>().Subscrip((_, _) =>
  106. {
  107. CommunicationViewModel.Instance.LocalCommunication?.GetEvent<RandomDataModel>()?.Subscrip((_, args) =>
  108. {
  109. UpdateData(new List<IResultDataModel>() { args.Data });
  110. CommunicationViewModel.Instance.ServiceCommunication?.GetEvent<RandomDataModel>()?.Publish(this, args.Data);
  111. });
  112. CommunicationViewModel.Instance.LocalCommunication?.GetEvent(nameof(RandomDataModel.TransferFunction))?.Subscrip((sender, args) =>
  113. {
  114. if (args.Data.Length > 0 && args.Data[0] is double[] func)
  115. {
  116. Tools.DispatherInovke.Inovke(()=> ShowTransferFunction(func));
  117. CommunicationViewModel.Instance.ServiceCommunication?.GetEvent(nameof(RandomDataModel.TransferFunction))?.Publish(this, null, func);
  118. }
  119. });
  120. });
  121. }
  122. private async void ShowTransferFunction(double[] data)
  123. {
  124. if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  125. {
  126. RandomTransferFunctionViewModel.Instance.InitData();
  127. RandomTransferFunctionViewModel.Instance.InitTransferFunctionData(data);
  128. RandomTransferFunctionViewModel.Instance.Title = "TransferFunction";
  129. BaseDialogWindow window = new BaseDialogWindow();
  130. window.DataContext = RandomTransferFunctionViewModel.Instance;
  131. bool isclose = false;
  132. RandomTransferFunctionViewModel.Instance.CloseWindowAction = () =>
  133. {
  134. if (isclose) return;
  135. isclose = true;
  136. window?.Close();
  137. };
  138. await window.ShowDialog(desktop.MainWindow!);
  139. }
  140. }
  141. static RandomMainPageViewModel()
  142. {
  143. }
  144. public override void InitUI()
  145. {
  146. }
  147. public ICommand NextLevelCommand => new RelayCommand(NextLevel);
  148. private async void NextLevel()
  149. {
  150. NextButtonIsEnabled = false;
  151. CommunicationViewModel.Instance.LocalCommunication?.GetEvent(Topic.RANDOMNEXTLEVEL)?.Publish(this);
  152. await Task.Delay(1000);
  153. NextButtonIsEnabled = true;
  154. }
  155. public override void SaveTdmsConfig(TDMS.ITDMSFile? config)
  156. {
  157. if (config == null) return;
  158. base.SaveTdmsConfig(config);
  159. var group = config.Contains(nameof(RandomConfigModel)) ? config[nameof(RandomConfigModel)]:config.AddGroup(nameof(RandomConfigModel));
  160. if (group == null) return;
  161. typeof(RandomConfigModel).GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
  162. .Select(x => (x, x.GetValue(RandomConfigViewModel.Instance.Model)))
  163. .ToList()
  164. .ForEach(x =>
  165. {
  166. if (x.Item2 == null)
  167. {
  168. return;
  169. }
  170. if (x.x.FieldType.IsAssignableTo(typeof(IList)) || x.x.FieldType.IsArray)
  171. {
  172. group.CreateOrUpdateProperty($"{x.x.Name}", string.Join("", Tools.Tools.Serialize(x.x.FieldType, x.Item2).Select(x => $"{x:X2}")));
  173. }
  174. else
  175. {
  176. group.CreateOrUpdateProperty($"{x.x.Name}", x.Item2?.ToString() ?? string.Empty);
  177. }
  178. });
  179. }
  180. public override void SaveTestData(TDMS.ITDMSFile? file)
  181. {
  182. if (file == null) return;
  183. base.SaveTestData(file);
  184. var group = file.Contains(SpectrumData) ? file[SpectrumData] : file.AddGroup(SpectrumData);
  185. if (group == null) return;
  186. var acc = ShakerConfigViewModel.Instance.Model.AnalogSignalConfigs.Where(x => x.AnalogType == AnalogType.DivideAcceleration).ToArray();
  187. if(acc.Length>0)
  188. {
  189. for(int i=0;i<acc.Length;i++)
  190. {
  191. var ch = group.Contains(acc[i].Name) ? group[acc[i].Name] : group.AddChannel(TDMS.Common.TDMSDataType.Double, acc[i].Name, App.Current?.FindResource("RandomValueUnit") + "");
  192. ch?.AppendData(Model.CurrentAccelerationPSD[i]);
  193. }
  194. }
  195. {
  196. var ch = group.Contains("AccelerationSpectrum") ? group["AccelerationSpectrum"] : group.AddChannel(TDMS.Common.TDMSDataType.Double, "AccelerationSpectrum", App.Current?.FindResource("RandomValueUnit") + "");
  197. ch?.AppendData(Model.CurrentAccelerationSynthesisPSD);
  198. }
  199. {
  200. var dr = ShakerConfigViewModel.Instance.Model.AnalogSignalConfigs.FirstOrDefault(x => x.AnalogType == AnalogType.GivenDriver);
  201. if (dr != null)
  202. {
  203. var ch = group.Contains(dr.Name) ? group[dr.Name] : group.AddChannel(TDMS.Common.TDMSDataType.Double, dr.Name, App.Current?.FindResource("RandomValueUnit") + "");
  204. ch?.AppendData(Model.DriverPSD);
  205. }
  206. }
  207. }
  208. public override bool Start()
  209. {
  210. SetRefSpectrum(RandomConfigViewModel.Instance.RefSpectrum);
  211. return true;
  212. }
  213. public override void Stop()
  214. {
  215. }
  216. public override void UpDateModel(RandomDataModel model)
  217. {
  218. if (RandomConfigViewModel.Instance.Model.PlanItems.Count > 0)
  219. {
  220. if (model.CurrentTestLevel == RandomConfigViewModel.Instance.Model.PlanItems[^1].Level)
  221. {
  222. NextButtonIsEnabled = false;
  223. }
  224. else
  225. {
  226. NextButtonIsEnabled = true;
  227. }
  228. }
  229. base.UpDateModel(model);
  230. int startindex = (int)(RandomConfigViewModel.Instance.MinFrequency / RandomConfigViewModel.Instance.FrequencyResolution);
  231. for(int i=0;i<datas.Count;i++)
  232. {
  233. datas[i].SetAcceleration(model.CurrentAccelerationSynthesisPSD[i + startindex]);
  234. datas[i].SetDriver(model.DriverPSD[i + startindex]);
  235. }
  236. PlotModel.InvalidatePlot(false);
  237. for(int i=0;i<LineSeries.Count;i++)
  238. {
  239. LineSeries[i].ItemsSource = datas;
  240. }
  241. PlotModel.InvalidatePlot(true);
  242. SaveSpectrumData();
  243. }
  244. private void SaveSpectrumData()
  245. {
  246. var file = ViewModels.ShakerDataViewModel.Instance.File;
  247. if (file == null) return;
  248. var group= file.Contains(SpectrumData) ? file[SpectrumData]:file.AddGroup(SpectrumData);
  249. if (group == null) return;
  250. }
  251. public override void UpdateData(List<IResultDataModel> model)
  252. {
  253. if(model !=null &&model.Count >0 && model.First() is RandomDataModel randomdata)
  254. {
  255. UpDateModel(randomdata);
  256. }
  257. }
  258. public void SetRefSpectrum(List<RandomData> data)
  259. {
  260. datas.Clear();
  261. datas.AddRange(data);
  262. PlotModel.InvalidatePlot(false);
  263. for (int i = 0; i < LineSeries.Count; i++)
  264. {
  265. LineSeries[i].ItemsSource = datas;
  266. }
  267. PlotModel.InvalidatePlot(true);
  268. }
  269. public override MainPageType PageType => MainPageType.RandomPage;
  270. public OxyPlot.PlotModel PlotModel { get; private set; } = new OxyPlot.PlotModel();
  271. public static RandomMainPageViewModel Instance { get; } = new RandomMainPageViewModel();
  272. }
  273. }