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.

284 lines
9.5 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_P(PSTR("[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_P(PSTR("[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(POW_POWER_TOPIC, POW_POWER_TOPIC, [](char * buffer, size_t len) {
  119. snprintf(buffer, len, "%d", getActivePower());
  120. });
  121. apiRegister(POW_CURRENT_TOPIC, POW_CURRENT_TOPIC, [](char * buffer, size_t len) {
  122. dtostrf(getCurrent(), len-1, 2, buffer);
  123. });
  124. apiRegister(POW_VOLTAGE_TOPIC, POW_VOLTAGE_TOPIC, [](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 unsigned long power_max = 0;
  133. static unsigned long power_min = 0;
  134. static double current_sum = 0;
  135. static double current_max = 0;
  136. static double current_min = 0;
  137. static unsigned long voltage_sum = 0;
  138. static unsigned long voltage_min = 0;
  139. static unsigned long voltage_max = 0;
  140. static bool powWasEnabled = false;
  141. // POW is disabled while there is no internet connection
  142. // When the HLW8012 measurements are enabled back we reset the timer
  143. if (!_powEnabled) {
  144. powWasEnabled = false;
  145. return;
  146. }
  147. if (!powWasEnabled) {
  148. last_update = millis();
  149. powWasEnabled = true;
  150. }
  151. if (millis() - last_update > POW_UPDATE_INTERVAL) {
  152. last_update = millis();
  153. unsigned int power = getActivePower();
  154. unsigned int voltage = getVoltage();
  155. double current = getCurrent();
  156. unsigned int apparent = getApparentPower();
  157. unsigned int factor = getPowerFactor();
  158. unsigned int reactive = getReactivePower();
  159. power_sum += power;
  160. if (power > power_max) power_max = power;
  161. if (power < power_min || power_min == 0) power_min = power;
  162. current_sum += current;
  163. if (current > current_max) current_max = current;
  164. if (current < current_min || current_min == 0) current_min = current;
  165. voltage_sum += voltage;
  166. if (voltage > voltage_max) voltage_max = voltage;
  167. if (voltage < voltage_min || voltage_min == 0) voltage_min = voltage;
  168. DynamicJsonBuffer jsonBuffer;
  169. JsonObject& root = jsonBuffer.createObject();
  170. root["powVisible"] = 1;
  171. root["powActivePower"] = power;
  172. root["powCurrent"] = current;
  173. root["powVoltage"] = voltage;
  174. root["powApparentPower"] = apparent;
  175. root["powReactivePower"] = reactive;
  176. root["powPowerFactor"] = factor;
  177. String output;
  178. root.printTo(output);
  179. wsSend(output.c_str());
  180. if (--report_count == 0) {
  181. power = (power_sum - power_max - power_min) / (POW_REPORT_EVERY - 2);
  182. current = (current_sum - current_max - current_min) / (POW_REPORT_EVERY - 2);
  183. voltage = (voltage_sum - voltage_max - voltage_min) / (POW_REPORT_EVERY - 2);
  184. apparent = current * voltage;
  185. reactive = (apparent > power) ? sqrt(apparent * apparent - power * power) : 0;
  186. factor = (apparent > 0) ? 100 * power / apparent : 100;
  187. if (factor > 100) factor = 100;
  188. // Calculate energy increment (ppower times time) and create C-string
  189. double energy_inc = (double) power * POW_REPORT_EVERY * POW_UPDATE_INTERVAL / 1000.0 / 3600.0;
  190. char energy_buf[11];
  191. dtostrf(energy_inc, 11, 3, energy_buf);
  192. char *e = energy_buf;
  193. while ((unsigned char) *e == ' ') ++e;
  194. // Report values to MQTT broker
  195. mqttSend(getSetting("powPowerTopic", POW_POWER_TOPIC).c_str(), String(power).c_str());
  196. mqttSend(getSetting("powEnergyTopic", POW_ENERGY_TOPIC).c_str(), e);
  197. mqttSend(getSetting("powCurrentTopic", POW_CURRENT_TOPIC).c_str(), String(current).c_str());
  198. mqttSend(getSetting("powVoltageTopic", POW_VOLTAGE_TOPIC).c_str(), String(voltage).c_str());
  199. mqttSend(getSetting("powAPowerTopic", POW_APOWER_TOPIC).c_str(), String(apparent).c_str());
  200. mqttSend(getSetting("powRPowerTopic", POW_RPOWER_TOPIC).c_str(), String(reactive).c_str());
  201. mqttSend(getSetting("powPFactorTopic", POW_PFACTOR_TOPIC).c_str(), String(factor).c_str());
  202. // Report values to Domoticz
  203. #if ENABLE_DOMOTICZ
  204. {
  205. char buffer[20];
  206. snprintf(buffer, 20, "%d;%s", power, e);
  207. domoticzSend("dczPowIdx", 0, buffer);
  208. snprintf(buffer, 20, "%s", e);
  209. domoticzSend("dczEnergyIdx", 0, buffer);
  210. snprintf(buffer, 20, "%d", voltage);
  211. domoticzSend("dczVoltIdx", 0, buffer);
  212. snprintf(buffer, 20, "%s", String(current).c_str());
  213. domoticzSend("dczCurrentIdx", 0, buffer);
  214. }
  215. #endif
  216. // Reset counters
  217. power_sum = power_max = power_min = 0;
  218. current_sum = current_max = current_min = 0;
  219. voltage_sum = voltage_max = voltage_min = 0;
  220. report_count = POW_REPORT_EVERY;
  221. }
  222. // Toggle between current and voltage monitoring
  223. #if POW_USE_INTERRUPTS == 0
  224. hlw8012.toggleMode();
  225. #endif
  226. }
  227. }
  228. #endif