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.

104 lines
2.8 KiB

  1. // -----------------------------------------------------------------------------
  2. // Eergy monitor sensor
  3. // -----------------------------------------------------------------------------
  4. #pragma once
  5. #include "Arduino.h"
  6. #include "BaseSensor.h"
  7. #include "EmonSensor.h"
  8. class EmonAnalogSensor : public EmonSensor {
  9. public:
  10. EmonAnalogSensor(unsigned char gpio, double voltage, unsigned char bits, double ref, double ratio): EmonSensor(voltage, bits, ref, ratio) {
  11. // Cache
  12. _gpio = gpio;
  13. _count = _magnitudes;
  14. // Prepare GPIO
  15. pinMode(gpio, INPUT);
  16. // warmup
  17. read(_gpio, _pivot);
  18. }
  19. // Descriptive name of the sensor
  20. String name() {
  21. char buffer[20];
  22. snprintf(buffer, sizeof(buffer), "EMON @ GPIO%d", _gpio);
  23. return String(buffer);
  24. }
  25. // Descriptive name of the slot # index
  26. String slot(unsigned char index) {
  27. return name();
  28. }
  29. // Type for slot # index
  30. magnitude_t type(unsigned char index) {
  31. _error = SENSOR_ERROR_OK;
  32. unsigned char i=0;
  33. #if EMON_REPORT_CURRENT
  34. if (index == i++) return MAGNITUDE_CURRENT;
  35. #endif
  36. #if EMON_REPORT_POWER
  37. if (index == i++) return MAGNITUDE_POWER_APPARENT;
  38. #endif
  39. #if EMON_REPORT_ENERGY
  40. if (index == i) return MAGNITUDE_ENERGY;
  41. #endif
  42. _error = SENSOR_ERROR_OUT_OF_RANGE;
  43. return MAGNITUDE_NONE;
  44. }
  45. // Current value for slot # index
  46. double value(unsigned char index) {
  47. _error = SENSOR_ERROR_OK;
  48. // Cache the value
  49. static unsigned long last = 0;
  50. if ((last == 0) || (millis() - last > 1000)) {
  51. _current = read(0, _pivot);
  52. #if EMON_REPORT_ENERGY
  53. _energy += (_current * _voltage * (millis() - last) / 1000);
  54. #endif
  55. last = millis();
  56. }
  57. // Report
  58. unsigned char i=0;
  59. #if EMON_REPORT_CURRENT
  60. if (index == i++) return _current;
  61. #endif
  62. #if EMON_REPORT_POWER
  63. if (index == i++) return _current * _voltage;
  64. #endif
  65. #if EMON_REPORT_ENERGY
  66. if (index == i) return _energy;
  67. #endif
  68. _error = SENSOR_ERROR_OUT_OF_RANGE;
  69. return 0;
  70. }
  71. protected:
  72. unsigned int readADC(unsigned char channel) {
  73. return analogRead(_gpio);
  74. }
  75. unsigned char _gpio;
  76. double _pivot = 0;
  77. double _current;
  78. #if EMON_REPORT_ENERGY
  79. unsigned long _energy = 0;
  80. #endif
  81. };