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.

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