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.

245 lines
7.6 KiB

  1. /*
  2. POW MODULE
  3. Support for Sonoff POW HLW8012-based power monitor
  4. Copyright (C) 2016-2017 by Xose Pérez <xose dot perez at gmail dot com>
  5. */
  6. #if ENABLE_POW
  7. #include <HLW8012.h>
  8. #include <Hash.h>
  9. #include <ArduinoJson.h>
  10. HLW8012 hlw8012;
  11. bool _powEnabled = false;
  12. // -----------------------------------------------------------------------------
  13. // POW
  14. // -----------------------------------------------------------------------------
  15. // When using interrupts we have to call the library entry point
  16. // whenever an interrupt is triggered
  17. void hlw8012_cf1_interrupt() {
  18. hlw8012.cf1_interrupt();
  19. }
  20. void hlw8012_cf_interrupt() {
  21. hlw8012.cf_interrupt();
  22. }
  23. void powEnable(bool status) {
  24. _powEnabled = status;
  25. if (_powEnabled) {
  26. #if POW_USE_INTERRUPTS == 1
  27. attachInterrupt(POW_CF1_PIN, hlw8012_cf1_interrupt, CHANGE);
  28. attachInterrupt(POW_CF_PIN, hlw8012_cf_interrupt, CHANGE);
  29. #endif
  30. DEBUG_MSG("[POW] Enabled\n");
  31. } else {
  32. #if POW_USE_INTERRUPTS == 1
  33. detachInterrupt(POW_CF1_PIN);
  34. detachInterrupt(POW_CF_PIN);
  35. #endif
  36. DEBUG_MSG("[POW] Disabled\n");
  37. }
  38. }
  39. // -----------------------------------------------------------------------------
  40. void powSaveCalibration() {
  41. setSetting("powPowerMult", hlw8012.getPowerMultiplier());
  42. setSetting("powCurrentMult", hlw8012.getCurrentMultiplier());
  43. setSetting("powVoltageMult", hlw8012.getVoltageMultiplier());
  44. }
  45. void powRetrieveCalibration() {
  46. double value;
  47. value = getSetting("powPowerMult", 0).toFloat();
  48. if (value > 0) hlw8012.setPowerMultiplier((int) value);
  49. value = getSetting("powCurrentMult", 0).toFloat();
  50. if (value > 0) hlw8012.setCurrentMultiplier((int) value);
  51. value = getSetting("powVoltageMult", 0).toFloat();
  52. if (value > 0) hlw8012.setVoltageMultiplier((int) value);
  53. }
  54. void powSetExpectedActivePower(unsigned int power) {
  55. if (power > 0) {
  56. hlw8012.expectedActivePower(power);
  57. powSaveCalibration();
  58. }
  59. }
  60. void powSetExpectedCurrent(double current) {
  61. if (current > 0) {
  62. hlw8012.expectedCurrent(current);
  63. powSaveCalibration();
  64. }
  65. }
  66. void powSetExpectedVoltage(unsigned int voltage) {
  67. if (voltage > 0) {
  68. hlw8012.expectedVoltage(voltage);
  69. powSaveCalibration();
  70. }
  71. }
  72. void powReset() {
  73. hlw8012.resetMultipliers();
  74. powSaveCalibration();
  75. }
  76. // -----------------------------------------------------------------------------
  77. unsigned int getActivePower() {
  78. return hlw8012.getActivePower();
  79. }
  80. unsigned int getApparentPower() {
  81. return hlw8012.getApparentPower();
  82. }
  83. unsigned int getReactivePower() {
  84. return hlw8012.getReactivePower();
  85. }
  86. double getCurrent() {
  87. return hlw8012.getCurrent();
  88. }
  89. unsigned int getVoltage() {
  90. return hlw8012.getVoltage();
  91. }
  92. unsigned int getPowerFactor() {
  93. return (int) (100 * hlw8012.getPowerFactor());
  94. }
  95. // -----------------------------------------------------------------------------
  96. void powSetup() {
  97. // Initialize HLW8012
  98. // void begin(unsigned char cf_pin, unsigned char cf1_pin, unsigned char sel_pin, unsigned char currentWhen = HIGH, bool use_interrupts = false, unsigned long pulse_timeout = PULSE_TIMEOUT);
  99. // * cf_pin, cf1_pin and sel_pin are GPIOs to the HLW8012 IC
  100. // * currentWhen is the value in sel_pin to select current sampling
  101. // * set use_interrupts to true to use interrupts to monitor pulse widths
  102. // * leave pulse_timeout to the default value, recommended when using interrupts
  103. #if POW_USE_INTERRUPTS
  104. hlw8012.begin(POW_CF_PIN, POW_CF1_PIN, POW_SEL_PIN, POW_SEL_CURRENT, true);
  105. #else
  106. hlw8012.begin(POW_CF_PIN, POW_CF1_PIN, POW_SEL_PIN, POW_SEL_CURRENT, false, 1000000);
  107. #endif
  108. // These values are used to calculate current, voltage and power factors as per datasheet formula
  109. // These are the nominal values for the Sonoff POW resistors:
  110. // * The CURRENT_RESISTOR is the 1milliOhm copper-manganese resistor in series with the main line
  111. // * The VOLTAGE_RESISTOR_UPSTREAM are the 5 470kOhm resistors in the voltage divider that feeds the V2P pin in the HLW8012
  112. // * The VOLTAGE_RESISTOR_DOWNSTREAM is the 1kOhm resistor in the voltage divider that feeds the V2P pin in the HLW8012
  113. hlw8012.setResistors(POW_CURRENT_R, POW_VOLTAGE_R_UP, POW_VOLTAGE_R_DOWN);
  114. // Retrieve calibration values
  115. powRetrieveCalibration();
  116. // API definitions
  117. apiRegister("/api/power", "power", [](char * buffer, size_t len) {
  118. snprintf(buffer, len, "%d", getActivePower());
  119. });
  120. apiRegister("/api/current", "current", [](char * buffer, size_t len) {
  121. dtostrf(getCurrent(), len-1, 2, buffer);
  122. });
  123. apiRegister("/api/voltage", "voltage", [](char * buffer, size_t len) {
  124. snprintf(buffer, len, "%d", getVoltage());
  125. });
  126. }
  127. void powLoop() {
  128. static unsigned long last_update = 0;
  129. static unsigned char report_count = POW_REPORT_EVERY;
  130. static unsigned long power_sum = 0;
  131. static double current_sum = 0;
  132. static unsigned long voltage_sum = 0;
  133. static bool powWasEnabled = false;
  134. // POW is disabled while there is no internet connection
  135. // When the HLW8012 measurements are enabled back we reset the timer
  136. if (!_powEnabled) {
  137. powWasEnabled = false;
  138. return;
  139. }
  140. if (!powWasEnabled) {
  141. last_update = millis();
  142. powWasEnabled = true;
  143. }
  144. if (millis() - last_update > POW_UPDATE_INTERVAL) {
  145. last_update = millis();
  146. unsigned int power = getActivePower();
  147. unsigned int voltage = getVoltage();
  148. double current = getCurrent();
  149. unsigned int apparent = getApparentPower();
  150. unsigned int factor = getPowerFactor();
  151. unsigned int reactive = getReactivePower();
  152. power_sum += power;
  153. current_sum += current;
  154. voltage_sum += voltage;
  155. DynamicJsonBuffer jsonBuffer;
  156. JsonObject& root = jsonBuffer.createObject();
  157. root["powVisible"] = 1;
  158. root["powActivePower"] = power;
  159. root["powCurrent"] = current;
  160. root["powVoltage"] = voltage;
  161. root["powApparentPower"] = apparent;
  162. root["powReactivePower"] = reactive;
  163. root["powPowerFactor"] = factor;
  164. String output;
  165. root.printTo(output);
  166. wsSend(output.c_str());
  167. if (--report_count == 0) {
  168. power = power_sum / POW_REPORT_EVERY;
  169. current = current_sum / POW_REPORT_EVERY;
  170. voltage = voltage_sum / POW_REPORT_EVERY;
  171. apparent = current * voltage;
  172. reactive = (apparent > power) ? sqrt(apparent * apparent - power * power) : 0;
  173. factor = (apparent > 0) ? 100 * power / apparent : 100;
  174. if (factor > 100) factor = 100;
  175. mqttSend(getSetting("powPowerTopic", POW_POWER_TOPIC).c_str(), String(power).c_str());
  176. mqttSend(getSetting("powCurrentTopic", POW_CURRENT_TOPIC).c_str(), String(current).c_str());
  177. mqttSend(getSetting("powVoltageTopic", POW_VOLTAGE_TOPIC).c_str(), String(voltage).c_str());
  178. mqttSend(getSetting("powAPowerTopic", POW_APOWER_TOPIC).c_str(), String(apparent).c_str());
  179. mqttSend(getSetting("powRPowerTopic", POW_RPOWER_TOPIC).c_str(), String(reactive).c_str());
  180. mqttSend(getSetting("powPFactorTopic", POW_PFACTOR_TOPIC).c_str(), String(factor).c_str());
  181. #if ENABLE_DOMOTICZ
  182. domoticzSend("dczPowIdx", power);
  183. #endif
  184. power_sum = current_sum = voltage_sum = 0;
  185. report_count = POW_REPORT_EVERY;
  186. }
  187. // Toggle between current and voltage monitoring
  188. #if POW_USE_INTERRUPTS == 0
  189. hlw8012.toggleMode();
  190. #endif
  191. }
  192. }
  193. #endif