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.

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