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.

253 lines
8.7 KiB

7 years ago
  1. // -----------------------------------------------------------------------------
  2. // Abstract Energy Monitor Sensor (other EMON sensors extend this class)
  3. // Copyright (C) 2017-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. // -----------------------------------------------------------------------------
  5. #if SENSOR_SUPPORT
  6. #pragma once
  7. #include "BaseEmonSensor.h"
  8. #include "I2CSensor.h"
  9. extern "C" {
  10. #include "../libs/fs_math.h"
  11. }
  12. class EmonSensor : public I2CSensor<BaseEmonSensor> {
  13. public:
  14. // ---------------------------------------------------------------------
  15. // Public
  16. // ---------------------------------------------------------------------
  17. EmonSensor() {
  18. // Calculate # of magnitudes
  19. #if EMON_REPORT_CURRENT
  20. ++_magnitudes;
  21. #endif
  22. #if EMON_REPORT_POWER
  23. ++_magnitudes;
  24. #endif
  25. #if EMON_REPORT_ENERGY
  26. ++_magnitudes;
  27. #endif
  28. }
  29. // ---------------------------------------------------------------------
  30. void expectedPower(unsigned char channel, unsigned int expected) override {
  31. if (channel >= _channels) return;
  32. unsigned int actual = _current[channel] * _voltage;
  33. if (actual == 0) return;
  34. if (expected == actual) return;
  35. _current_ratio[channel] = _current_ratio[channel] * ((double) expected / (double) actual);
  36. calculateFactors(channel);
  37. _dirty = true;
  38. }
  39. void setVoltage(double voltage) override {
  40. if (_voltage == voltage) return;
  41. _voltage = voltage;
  42. _dirty = true;
  43. }
  44. void setReference(double reference) {
  45. if (_reference == reference) return;
  46. _reference = reference;
  47. _dirty = true;
  48. }
  49. double defaultCurrentRatio() const override {
  50. return EMON_CURRENT_RATIO;
  51. }
  52. void setCurrentRatio(unsigned char channel, double current_ratio) override {
  53. if (channel >= _channels) return;
  54. if (_current_ratio[channel] == current_ratio) return;
  55. _current_ratio[channel] = current_ratio;
  56. calculateFactors(channel);
  57. _dirty = true;
  58. }
  59. void resetRatios() override {
  60. for (unsigned char channel = 0; channel < _channels; ++channel) {
  61. setCurrentRatio(channel, defaultCurrentRatio());
  62. }
  63. }
  64. // ---------------------------------------------------------------------
  65. double getVoltage() override {
  66. return _voltage;
  67. }
  68. double getReference() {
  69. return _reference;
  70. }
  71. double getCurrentRatio(unsigned char channel) override {
  72. if (channel >= _channels) return 0;
  73. return _current_ratio[channel];
  74. }
  75. size_t countDevices() override {
  76. return _channels;
  77. }
  78. // ---------------------------------------------------------------------
  79. // Sensor API
  80. // ---------------------------------------------------------------------
  81. void begin() {
  82. // Resolution
  83. _adc_counts = 1 << _resolution;
  84. // Calculations
  85. for (unsigned char i=0; i<_channels; i++) {
  86. _energy[i] = _current[i] = 0.0;
  87. _pivot[i] = _adc_counts >> 1;
  88. calculateFactors(i);
  89. }
  90. #if SENSOR_DEBUG
  91. DEBUG_MSG("[EMON] Reference (mV): %d\n", int(1000 * _reference));
  92. DEBUG_MSG("[EMON] ADC counts: %d\n", _adc_counts);
  93. for (unsigned char i=0; i<_channels; i++) {
  94. DEBUG_MSG("[EMON] Channel #%d current ratio (mA/V): %d\n", i, int(1000 * _current_ratio[i]));
  95. DEBUG_MSG("[EMON] Channel #%d current factor (mA/bit): %d\n", i, int(1000 * _current_factor[i]));
  96. DEBUG_MSG("[EMON] Channel #%d Multiplier: %d\n", i, int(_multiplier[i]));
  97. }
  98. #endif
  99. _ready = true;
  100. _dirty = false;
  101. }
  102. // Convert slot # index to a magnitude # index
  103. unsigned char local(unsigned char index) override {
  104. return (_magnitudes) ? (index / _magnitudes) : 0u;
  105. }
  106. protected:
  107. // ---------------------------------------------------------------------
  108. // Protected
  109. // ---------------------------------------------------------------------
  110. // Initializes internal variables
  111. void init() {
  112. _current_ratio = new double[_channels];
  113. _current_factor = new double[_channels];
  114. _multiplier = new uint16_t[_channels];
  115. _pivot = new double[_channels];
  116. _current = new double[_channels];
  117. }
  118. virtual unsigned int readADC(unsigned char channel) = 0;
  119. void calculateFactors(unsigned char channel) {
  120. _current_factor[channel] = _current_ratio[channel] * _reference / _adc_counts;
  121. unsigned int s = 1;
  122. unsigned int i = 1;
  123. unsigned int m = 1;
  124. unsigned int multiplier = 1;
  125. while (m * _current_factor[channel] < 1) {
  126. multiplier = m;
  127. i = (i == 1) ? 2 : (i == 2) ? 5 : 1;
  128. if (i == 1) s *= 10;
  129. m = s * i;
  130. }
  131. _multiplier[channel] = multiplier;
  132. }
  133. double read(unsigned char channel) {
  134. int max = 0;
  135. int min = _adc_counts;
  136. double sum = 0;
  137. unsigned long time_span = millis();
  138. for (unsigned long i=0; i<_samples; i++) {
  139. int sample;
  140. double filtered;
  141. // Read analog value
  142. sample = readADC(channel);
  143. if (sample > max) max = sample;
  144. if (sample < min) min = sample;
  145. // Digital low pass filter extracts the VDC offset
  146. _pivot[channel] = (_pivot[channel] + (sample - _pivot[channel]) / EMON_FILTER_SPEED);
  147. filtered = sample - _pivot[channel];
  148. // Root-mean-square method
  149. sum += (filtered * filtered);
  150. }
  151. time_span = millis() - time_span;
  152. // Quick fix
  153. if (_pivot[channel] < min || max < _pivot[channel]) {
  154. _pivot[channel] = (max + min) / 2.0;
  155. }
  156. // Calculate current
  157. double rms = _samples > 0 ? fs_sqrt(sum / _samples) : 0;
  158. double current = _current_factor[channel] * rms;
  159. current = (double) (int(current * _multiplier[channel]) - 1) / _multiplier[channel];
  160. if (current < 0) current = 0;
  161. #if SENSOR_DEBUG
  162. DEBUG_MSG("[EMON] Channel: %d\n", channel);
  163. DEBUG_MSG("[EMON] Total samples: %d\n", _samples);
  164. DEBUG_MSG("[EMON] Total time (ms): %d\n", time_span);
  165. DEBUG_MSG("[EMON] Sample frequency (Hz): %d\n", int(1000 * _samples / time_span));
  166. DEBUG_MSG("[EMON] Max value: %d\n", max);
  167. DEBUG_MSG("[EMON] Min value: %d\n", min);
  168. DEBUG_MSG("[EMON] Midpoint value: %d\n", int(_pivot[channel]));
  169. DEBUG_MSG("[EMON] RMS value: %d\n", int(rms));
  170. DEBUG_MSG("[EMON] Current (mA): %d\n", int(1000 * current));
  171. #endif
  172. // Check timing
  173. if ((time_span > EMON_MAX_TIME)
  174. || ((time_span < EMON_MAX_TIME) && (_samples < EMON_MAX_SAMPLES))) {
  175. _samples = (_samples * EMON_MAX_TIME) / time_span;
  176. }
  177. return current;
  178. }
  179. unsigned char _channels = 0; // Number of ADC channels available
  180. unsigned char _magnitudes = 0; // Number of magnitudes per channel
  181. unsigned long _samples = EMON_MAX_SAMPLES; // Samples (dynamically modificable)
  182. unsigned char _resolution = 10; // ADC resolution in bits
  183. unsigned long _adc_counts; // Max count
  184. double _voltage = EMON_MAINS_VOLTAGE; // Mains voltage
  185. double _reference = EMON_REFERENCE_VOLTAGE; // ADC reference voltage (100%)
  186. double * _current_ratio; // Ratio ampers in main loop to voltage in secondary (per channel)
  187. double * _current_factor; // Calculated, reads (RMS) to current (per channel)
  188. uint16_t * _multiplier; // Calculated, error (per channel)
  189. double * _pivot; // Moving average mid point (per channel)
  190. double * _current; // Last current reading (per channel)
  191. };
  192. #endif // SENSOR_SUPPORT