SpeedVariationModel.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace SWRIS.Models
  5. {
  6. public class SpeedVariationModel
  7. {
  8. private const int SampleSize = 5;
  9. private readonly Queue<double> RecentSpeeds = new Queue<double>();
  10. private double VariationThreshold { get; set; } = 0.25;
  11. public bool IsSpeedStable { get; private set; } = false;
  12. private double CurrentVariation { get; set; }
  13. public event EventHandler<bool> SpeedStableChanged;
  14. public SpeedVariationModel(double variationThreshold)
  15. {
  16. VariationThreshold = variationThreshold;
  17. }
  18. public void AddSpeedData(double speed)
  19. {
  20. // 更新数据窗口
  21. RecentSpeeds.Enqueue(speed);
  22. if (RecentSpeeds.Count > SampleSize)
  23. RecentSpeeds.Dequeue();
  24. bool _isStable = CheckStability();
  25. if (IsSpeedStable != _isStable)
  26. {
  27. IsSpeedStable = _isStable;
  28. SpeedStableChanged?.Invoke(this, IsSpeedStable);
  29. }
  30. }
  31. private bool CheckStability()
  32. {
  33. if (RecentSpeeds.Count < 2)
  34. {
  35. return false;
  36. }
  37. double currentSpeed = RecentSpeeds.Last();
  38. double avgSpeed = RecentSpeeds.Average();
  39. // 计算当前速度相对于平均值的偏差
  40. CurrentVariation = Math.Abs(currentSpeed - avgSpeed) / avgSpeed;
  41. return CurrentVariation <= VariationThreshold;
  42. }
  43. // 重置状态
  44. public void Reset()
  45. {
  46. RecentSpeeds.Clear();
  47. IsSpeedStable = false;
  48. CurrentVariation = 0;
  49. }
  50. }
  51. }