Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
2.3 KiB

  1. // -----------------------------------------------------------------------------
  2. // Stream Injector
  3. // -----------------------------------------------------------------------------
  4. #pragma once
  5. /*
  6. class SpikesFilter {
  7. public:
  8. SpikesFilter() {
  9. reset();
  10. }
  11. virtual void reset() {
  12. _sum = 0;
  13. _spike = false;
  14. }
  15. virtual void add(double value) {
  16. // add previous value
  17. if (_last > 0) {
  18. _sum += _last;
  19. }
  20. // flag new possible spike
  21. if (value > 0) {
  22. _spike = (_last == 0);
  23. // delete previous spike
  24. } else if (_spike) {
  25. _sum -= _last;
  26. _spike = false;
  27. }
  28. _last = value;
  29. }
  30. virtual double sum() {
  31. return _sum;
  32. }
  33. private:
  34. double _last = 0;
  35. double _sum = 0;
  36. bool _spike = false;
  37. };
  38. */
  39. class MedianFilter {
  40. public:
  41. MedianFilter(unsigned char size) {
  42. _size = size;
  43. _data = new double[_size+1];
  44. reset();
  45. }
  46. virtual void reset() {
  47. _data[0] = _data[_size];
  48. _pointer = 1;
  49. for (unsigned char i=_pointer; i<=_size; i++) _data[i] = 0;
  50. }
  51. virtual void add(double value) {
  52. if (_pointer <= _size) {
  53. _data[_pointer] = value;
  54. ++_pointer;
  55. }
  56. }
  57. virtual double average(bool do_reset = false) {
  58. double sum = 0;
  59. for (unsigned char i = 1; i<_size; i++) {
  60. double previous = _data[i-1];
  61. double current = _data[i];
  62. double next = _data[i+1];
  63. if (previous > current) std::swap(previous, current);
  64. if (current > next) std::swap(current, next);
  65. if (previous > current) std::swap(previous, current);
  66. sum += current;
  67. }
  68. if (do_reset) reset();
  69. return sum / (_size-1);
  70. }
  71. virtual unsigned char count() {
  72. return _pointer - 1;
  73. }
  74. private:
  75. double *_data;
  76. unsigned char _size = 0;
  77. unsigned char _pointer = 0;
  78. };