SineMainPageViewModel.cs 18 KB

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