SineMainPageViewModel.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. using Avalonia.Collections;
  2. using Avalonia.Controls;
  3. using OxyPlot;
  4. using OxyPlot.Series;
  5. using Shaker.Models;
  6. using Shaker.Models.Tools;
  7. using ShakerApp.Tools;
  8. using ShakerApp.Views;
  9. using System;
  10. using System.Collections;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Net.Http.Headers;
  14. using System.Runtime.CompilerServices;
  15. using System.Text;
  16. using System.Threading.Tasks;
  17. namespace ShakerApp.ViewModels
  18. {
  19. internal class SineMainPageViewModel : BaseMainPageViewModel<SineDataModel>
  20. {
  21. public const string TDMSDataName = "SweepData";
  22. List<OxyColor> oxyColors = new List<OxyColor>() {OxyColors.Black, OxyColors.Green, OxyColors.Red, OxyColors.Red, OxyColors.Yellow, OxyColors.Yellow };
  23. List<LineStyle> lineStyles = new List<LineStyle>() {LineStyle.Solid, LineStyle.Solid, LineStyle.Solid, LineStyle.Solid, LineStyle.LongDashDotDot, LineStyle.LongDashDotDot };
  24. List<string> properties = new List<string>() {nameof(SweepData.Acceleration), nameof(SweepData.TargetAcceleration), nameof(SweepData.UpStopAcceleration), nameof(SweepData.DownStopAcceleration), nameof(SweepData.UpWarnAcceleration), nameof(SweepData.DownWarnAcceleration) };
  25. List<SweepData> datas = new List<SweepData>();
  26. DateTime dateTime = DateTime.Now;
  27. OxyPlot.Annotations.ArrowAnnotation arrowAnnotation = new OxyPlot.Annotations.ArrowAnnotation();
  28. public AvaloniaList<LineSeries> LineSeries { get; } = new AvaloniaList<LineSeries>();
  29. private SineMainPageViewModel()
  30. {
  31. #region 加速度谱曲线
  32. PlotModel.Axes.Add(new OxyPlot.Axes.LogarithmicAxis()
  33. {
  34. MaximumPadding = 0,
  35. MinimumPadding = 0,
  36. Title = App.Current?.FindResource(ShakerConstant.FrequencyKey) + "",
  37. Unit = "Hz",
  38. MajorGridlineStyle = LineStyle.Solid,
  39. Position = OxyPlot.Axes.AxisPosition.Bottom,
  40. Key = "Freq"
  41. });
  42. PlotModel.Axes.Add(new OxyPlot.Axes.LogarithmicAxis()
  43. {
  44. Key = "Ampt",
  45. Title = App.Current?.FindResource(ShakerConstant.AmptAxisTitleKey) + "",
  46. Unit = "g",
  47. MajorGridlineStyle = LineStyle.Solid,
  48. Position = OxyPlot.Axes.AxisPosition.Left,
  49. });
  50. PlotModel.Title = App.Current?.FindResource(ShakerConstant.AccelerationSpectrumKey) + "";
  51. for (int i = 0; i < oxyColors.Count; i++)
  52. {
  53. LineSeries line = new LineSeries();
  54. line.Title = App.Current?.FindResource(ShakerConstant.ShowSweepAccelerationSpectrumNames[i]) + "";
  55. line.Color = oxyColors[i];
  56. line.StrokeThickness = 1;
  57. line.DataFieldX = nameof(SweepData.Frequency);
  58. line.DataFieldY = properties[i];
  59. line.LineStyle = lineStyles[i];
  60. line.XAxisKey = "Freq";
  61. line.YAxisKey = "Ampt";
  62. LineSeries.Add(line);
  63. PlotModel.Series.Add(line);
  64. }
  65. PlotModel.Annotations.Add(arrowAnnotation);
  66. arrowAnnotation.Selectable = false;
  67. arrowAnnotation.SelectionMode = OxyPlot.SelectionMode.Single;
  68. arrowAnnotation.Text = "Test";
  69. arrowAnnotation.TextColor = OxyColors.Transparent;
  70. arrowAnnotation.StartPoint = new DataPoint(8, 4);
  71. arrowAnnotation.EndPoint = new DataPoint();
  72. arrowAnnotation.Color = OxyColors.Transparent;
  73. PlotModel.Legends.Add(new OxyPlot.Legends.Legend()
  74. {
  75. ShowInvisibleSeries = true,
  76. });
  77. PlotModel.Title = App.Current?.FindResource(MainPageType.SinePage.Description()) + "";
  78. #endregion
  79. GetEvent(ShakerSettingViewModel.LANGUAGECHANGEDEVENT).Subscrip((_, _) =>
  80. {
  81. PlotModel.InvalidatePlot(false);
  82. PlotModel.Title = App.Current?.FindResource(MainPageType.SinePage.Description()) + "";
  83. PlotModel.Axes[0].Title = App.Current?.FindResource("Frequency") + "";
  84. PlotModel.Axes[1].Title = Title = App.Current?.FindResource("Ampt") + "";
  85. for(int i=0;i<LineSeries.Count;i++)
  86. {
  87. LineSeries[i].Title = App.Current?.FindResource(ShakerConstant.ShowSweepAccelerationSpectrumNames[i]) + "";
  88. }
  89. PlotModel.InvalidatePlot(true);
  90. });
  91. GetEvent<AllConfig>().Subscrip((_, _) =>
  92. {
  93. CommunicationViewModel.Instance.LocalCommunication?.GetEvent<List<SineDataModel>>()?.Subscrip((_, args) =>
  94. {
  95. UpdateData(args.Data.Cast<IResultDataModel>().ToList());
  96. CommunicationViewModel.Instance.ServiceCommunication?.GetEvent<List<SineDataModel>>()?.Publish(this, args.Data);
  97. });
  98. });
  99. }
  100. static SineMainPageViewModel()
  101. {
  102. }
  103. public override void InitUI()
  104. {
  105. SweepConfigViewModel.Instance.Refresh();
  106. SetRefSpectrum(SweepConfigViewModel.Instance.RefSpectrum);
  107. }
  108. public override void SaveTdmsConfig(TDMS.ITDMSFile? config)
  109. {
  110. if (config == null) return;
  111. base.SaveTdmsConfig(config);
  112. var group = config.Contains(nameof(SweepConfigModel)) ? config[nameof(SweepConfigModel)]:config.AddGroup(nameof(SweepConfigModel));
  113. if (group == null) return;
  114. typeof(SweepConfigModel) .GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
  115. .Select(x => (x, x.GetValue(SweepConfigViewModel.Instance.Model)))
  116. .ToList()
  117. .ForEach(x =>
  118. {
  119. if (x.Item2 == null)
  120. {
  121. return;
  122. }
  123. if (x.x.FieldType.IsAssignableTo(typeof(IList)) || x.x.FieldType.IsArray)
  124. {
  125. group.CreateOrUpdateProperty($"{x.x.Name}", string.Join("", Tools.Tools.Serialize(x.x.FieldType, x.Item2).Select(x => $"{x:X2}")));
  126. }
  127. else
  128. {
  129. group.CreateOrUpdateProperty($"{x.x.Name}", x.Item2?.ToString() ?? string.Empty);
  130. }
  131. });
  132. }
  133. public void SetRefSpectrum(List<SweepData> data)
  134. {
  135. datas.Clear();
  136. datas.AddRange(data);
  137. PlotModel.InvalidatePlot(false);
  138. for(int i=0;i<LineSeries.Count;i++)
  139. {
  140. LineSeries[i].ItemsSource = datas;
  141. }
  142. PlotModel.InvalidatePlot(true);
  143. }
  144. public override bool Start()
  145. {
  146. if (SweepConfigViewModel.Instance.DisplacementOverLimit)
  147. {
  148. MainViewModel.Default.ShowError(App.Current?.FindResource("DisplacementOverLimit") + "");
  149. return false;
  150. }
  151. if (SweepConfigViewModel.Instance.VelocityOverLimit)
  152. {
  153. MainViewModel.Default.ShowError(App.Current?.FindResource("VelocityOverLimit") + "");
  154. return false;
  155. }
  156. if (SweepConfigViewModel.Instance.AccelerationOverLimit)
  157. {
  158. MainViewModel.Default.ShowError(App.Current?.FindResource("AccelerationOverLimit") + "");
  159. return false;
  160. }
  161. if(!SweepConfigViewModel.Instance.IsConfigSetting)
  162. {
  163. MainViewModel.Default.ShowError(App.Current?.FindResource("SweepConfigNoSet")+"");
  164. return false;
  165. }
  166. SweepConfigViewModel.Instance.SendConfig();
  167. SetRefSpectrum(SweepConfigViewModel.Instance.RefSpectrum);
  168. lastwritefreq = 0;
  169. return true;
  170. }
  171. public override void Stop()
  172. {
  173. }
  174. public override void UpdateData(List<IResultDataModel> model)
  175. {
  176. if (model.Last() is SineDataModel sine)
  177. {
  178. UpDataModels(model.Cast<SineDataModel>().ToList());
  179. UpDateModel(sine);
  180. UpPlot();
  181. }
  182. }
  183. private double lastwritefreq = 0;
  184. private void UpDataModels(List<SineDataModel> models)
  185. {
  186. models.ForEach(sine =>
  187. {
  188. if (sine.SweepDirection != Model.SweepDirection && sine.SweepStep != Shaker.Models.SweepStep.Stop)
  189. {
  190. SetRefSpectrum(SweepConfigViewModel.Instance.RefSpectrum);
  191. }
  192. double currentacc = Shaker.Models.Tools.Tools.VoltageToQuantities(sine.CurrentAcceleration, ShakerConfigViewModel.Instance.AccelerationSensitivity);
  193. uint currentfreq = (uint)(sine.CurrentFrequency * 1000_000);
  194. int index = -1;
  195. for (int i = 0; i < datas.Count; i++)
  196. {
  197. uint tempfreq = (uint)(datas[i].Frequency * 1000_000);
  198. if (tempfreq == currentfreq)
  199. {
  200. index = i;
  201. {
  202. var tempdata = datas[i];
  203. tempdata.SetAcceleration(currentacc);
  204. datas[i] = tempdata;
  205. }
  206. if (sine.SweepDirection == Shaker.Models.SweepDirection.Up)
  207. {
  208. for (int j = i - 1; j >= 0; j--)
  209. {
  210. if (datas[j].Frequency > SweepConfigViewModel.Instance.EndFrequency) break;
  211. if (double.IsNaN(datas[j].Acceleration))
  212. {
  213. var tempdata = datas[j];
  214. tempdata.SetAcceleration(currentacc);
  215. datas[j] = tempdata;
  216. }
  217. else break;
  218. }
  219. }
  220. else
  221. {
  222. for (int j = i + 1; j < datas.Count; j++)
  223. {
  224. if (datas[j].Frequency < SweepConfigViewModel.Instance.StartFrequency) break;
  225. if (double.IsNaN(datas[j].Acceleration))
  226. {
  227. var tempdata = datas[j];
  228. tempdata.SetAcceleration(currentacc);
  229. datas[j] = tempdata;
  230. }
  231. else break;
  232. }
  233. }
  234. return;
  235. }
  236. else if (tempfreq > currentfreq)
  237. {
  238. if (i > 0)
  239. {
  240. index = i - 1;
  241. }
  242. else index = 0;
  243. break;
  244. }
  245. }
  246. if (index == -1) index = datas.Count - 1;
  247. if (sine.SweepDirection == Shaker.Models.SweepDirection.Up)
  248. {
  249. for (int j = index; j >= 0; j--)
  250. {
  251. if (datas[j].Frequency > SweepConfigViewModel.Instance.EndFrequency) break;
  252. if (double.IsNaN(datas[j].Acceleration))
  253. {
  254. var tempdata = datas[j];
  255. tempdata.SetAcceleration(currentacc);
  256. datas[j] = tempdata;
  257. }
  258. else break;
  259. }
  260. }
  261. else
  262. {
  263. for (int j = index + 1; j < datas.Count; j++)
  264. {
  265. if (datas[j].Frequency < SweepConfigViewModel.Instance.StartFrequency) break;
  266. if (double.IsNaN(datas[j].Acceleration))
  267. {
  268. var tempdata = datas[j];
  269. tempdata.SetAcceleration(currentacc);
  270. datas[j] = tempdata;
  271. }
  272. else break;
  273. }
  274. }
  275. double value = 0; double upstop = 0; double upwarn = 0; double downstop = 0; double downwarn = 0;
  276. SweepConfigViewModel.Instance.Model.CalcAmpt(sine.CurrentFrequency, ref value, ref upstop, ref upwarn, ref downstop, ref downwarn);
  277. datas.Insert(index + 1, new SweepData(sine.CurrentFrequency,currentacc, value, upstop, downstop, upwarn, downwarn));
  278. });
  279. var file = ShakerDataViewModel.Instance.File;
  280. if (file == null) return;
  281. var savemodels = models.DistinctBy(x => x.CurrentFrequency).Where(x=>x.CurrentFrequency!=lastwritefreq).ToList();
  282. if (savemodels.Count == 0) return;
  283. lastwritefreq = savemodels[^1].CurrentFrequency;
  284. try
  285. {
  286. var group= file.Contains(TDMSDataName) ? file[TDMSDataName]:file.AddGroup(TDMSDataName);
  287. if (group == null) return;
  288. var ch = group.Contains(nameof(SineDataModel.CurrentFrequency)) ? group[nameof(SineDataModel.CurrentFrequency)] : group.AddChannel(TDMS.Common.TDMSDataType.Double, nameof(SineDataModel.CurrentFrequency), "Hz");
  289. if (ch != null)
  290. {
  291. ch.AppendData(savemodels.Select(x => x.CurrentFrequency).ToArray());
  292. }
  293. ch = group.Contains(nameof(SineDataModel.CurrentAcceleration)) ? group[nameof(SineDataModel.CurrentAcceleration)] : group.AddChannel(TDMS.Common.TDMSDataType.Double,nameof(SineDataModel.CurrentAcceleration), "g");
  294. if (ch != null)
  295. {
  296. ch.AppendData(savemodels.Select(x => x.CurrentAcceleration).ToArray());
  297. }
  298. ch = group.Contains(nameof(SineDataModel.SweepIndex)) ? group[nameof(SineDataModel.SweepIndex)] : group.AddChannel(TDMS.Common.TDMSDataType.Int32, nameof(SineDataModel.SweepIndex), "");
  299. if (ch != null)
  300. {
  301. ch.AppendData(savemodels.Select(x => (int)x.SweepIndex).ToArray());
  302. }
  303. ch = group.Contains(nameof(SineDataModel.SweepDirection)) ? group[nameof(SineDataModel.SweepDirection)] : group.AddChannel(TDMS.Common.TDMSDataType.Int32, nameof(SineDataModel.SweepDirection), "");
  304. if (ch != null)
  305. {
  306. ch.AppendData(savemodels.Select(x => (int)x.SweepDirection).ToArray());
  307. }
  308. file.Save();
  309. }
  310. catch(Exception ex)
  311. {
  312. }
  313. }
  314. private void UpPlot()
  315. {
  316. PlotModel.InvalidatePlot(false);
  317. if (Model.SweepStep == Shaker.Models.SweepStep.Stop)
  318. {
  319. arrowAnnotation.TextColor = OxyColors.Transparent;
  320. arrowAnnotation.Color = OxyColors.Transparent;
  321. }
  322. else
  323. {
  324. arrowAnnotation.TextColor = OxyColors.Black;
  325. arrowAnnotation.Color = OxyColors.Green;
  326. arrowAnnotation.EndPoint = new DataPoint(CurrentFrequency, CurrentAcceleration);
  327. arrowAnnotation.StartPoint = new DataPoint(CurrentFrequency, PlotModel.Axes[1].ActualMinimum);
  328. arrowAnnotation.Text = $"{App.Current?.FindResource("Frequency")}:{CurrentFrequency:F2}Hz\r\n{App.Current?.FindResource("Acceleration")}:{CurrentAcceleration:F3}g";
  329. arrowAnnotation.TextPosition = arrowAnnotation.StartPoint;
  330. arrowAnnotation.TextHorizontalAlignment = HorizontalAlignment.Left;
  331. arrowAnnotation.TextVerticalAlignment = VerticalAlignment.Bottom;
  332. }
  333. for(int i=0;i<LineSeries.Count;i++)
  334. {
  335. LineSeries[i].ItemsSource = datas;
  336. }
  337. PlotModel.InvalidatePlot(true);
  338. }
  339. [PropertyAssociation(nameof(SineDataModel.TotalTime))]
  340. public double TotalTime { get => Model.TotalTime; set => SetProperty(ref Model.TotalTime, value); }
  341. [PropertyAssociation(nameof(SineDataModel.RunTime))]
  342. public double RunTime { get => Model.RunTime; set => SetProperty(ref Model.RunTime, value); }
  343. [PropertyAssociation(nameof(SineDataModel.CurrentFrequency))]
  344. public double CurrentFrequency { get => Model.CurrentFrequency; set => SetProperty(ref Model.CurrentFrequency, value); }
  345. [PropertyAssociation(nameof(SineDataModel.CurrentAcceleration))]
  346. public double CurrentAcceleration { get => Shaker.Models.Tools.Tools.VoltageToQuantities(Model.CurrentAcceleration, ShakerConfigViewModel.Instance.AccelerationSensitivity); set => SetProperty(ref Model.CurrentAcceleration, value); }
  347. [PropertyAssociation(nameof(SineDataModel.SweepDirection))]
  348. public string SweepDirection { get => Model.SweepDirection.Description(); }
  349. [PropertyAssociation(nameof(SineDataModel.SweepStep))]
  350. public string SweepStep { get => Model.SweepStep.Description(); }
  351. [PropertyAssociation(nameof(SineDataModel.SweepIndex))]
  352. public uint SweepIndex { get => Model.SweepIndex; set => SetProperty(ref Model.SweepIndex, value); }
  353. [PropertyAssociation(nameof(SineDataModel.MainPageType))]
  354. public override MainPageType PageType => Model.MainPageType;
  355. public OxyPlot.PlotModel PlotModel { get; private set; } = new OxyPlot.PlotModel();
  356. public static SineMainPageViewModel Instance { get; } = new SineMainPageViewModel();
  357. public OxyPlot.PlotModel DriverModel { get; private set; } = new PlotModel();
  358. }
  359. }