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.

236 lines
7.2 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. #define POW_USE_INTERRUPTS 1
  11. HLW8012 hlw8012;
  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 powAttachInterrupts() {
  24. attachInterrupt(POW_CF1_PIN, hlw8012_cf1_interrupt, CHANGE);
  25. attachInterrupt(POW_CF_PIN, hlw8012_cf_interrupt, CHANGE);
  26. DEBUG_MSG("[POW] Enabled\n");
  27. }
  28. void powDettachInterrupts() {
  29. detachInterrupt(POW_CF1_PIN);
  30. detachInterrupt(POW_CF_PIN);
  31. DEBUG_MSG("[POW] Disabled\n");
  32. }
  33. // -----------------------------------------------------------------------------
  34. void powSaveCalibration() {
  35. setSetting("powPowerMult", hlw8012.getPowerMultiplier());
  36. setSetting("powCurrentMult", hlw8012.getCurrentMultiplier());
  37. setSetting("powVoltageMult", hlw8012.getVoltageMultiplier());
  38. }
  39. void powRetrieveCalibration() {
  40. double value;
  41. value = getSetting("powPowerMult", 0).toFloat();
  42. if (value > 0) hlw8012.setPowerMultiplier((int) value);
  43. value = getSetting("powCurrentMult", 0).toFloat();
  44. if (value > 0) hlw8012.setCurrentMultiplier((int) value);
  45. value = getSetting("powVoltageMult", 0).toFloat();
  46. if (value > 0) hlw8012.setVoltageMultiplier((int) value);
  47. }
  48. void powSetExpectedActivePower(unsigned int power) {
  49. if (power > 0) {
  50. hlw8012.expectedActivePower(power);
  51. powSaveCalibration();
  52. }
  53. }
  54. void powSetExpectedCurrent(double current) {
  55. if (current > 0) {
  56. hlw8012.expectedCurrent(current);
  57. powSaveCalibration();
  58. }
  59. }
  60. void powSetExpectedVoltage(unsigned int voltage) {
  61. if (voltage > 0) {
  62. hlw8012.expectedVoltage(voltage);
  63. powSaveCalibration();
  64. }
  65. }
  66. void powReset() {
  67. hlw8012.resetMultipliers();
  68. powSaveCalibration();
  69. }
  70. // -----------------------------------------------------------------------------
  71. unsigned int getActivePower() {
  72. return hlw8012.getActivePower();
  73. }
  74. unsigned int getApparentPower() {
  75. return hlw8012.getApparentPower();
  76. }
  77. unsigned int getReactivePower() {
  78. return hlw8012.getReactivePower();
  79. }
  80. double getCurrent() {
  81. return hlw8012.getCurrent();
  82. }
  83. unsigned int getVoltage() {
  84. return hlw8012.getVoltage();
  85. }
  86. unsigned int getPowerFactor() {
  87. return (int) (100 * hlw8012.getPowerFactor());
  88. }
  89. // -----------------------------------------------------------------------------
  90. void powSetup() {
  91. // Initialize HLW8012
  92. // 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);
  93. // * cf_pin, cf1_pin and sel_pin are GPIOs to the HLW8012 IC
  94. // * currentWhen is the value in sel_pin to select current sampling
  95. // * set use_interrupts to true to use interrupts to monitor pulse widths
  96. // * leave pulse_timeout to the default value, recommended when using interrupts
  97. #if POW_USE_INTERRUPTS
  98. hlw8012.begin(POW_CF_PIN, POW_CF1_PIN, POW_SEL_PIN, POW_SEL_CURRENT, true);
  99. #else
  100. hlw8012.begin(POW_CF_PIN, POW_CF1_PIN, POW_SEL_PIN, POW_SEL_CURRENT, false, 1000000);
  101. #endif
  102. // These values are used to calculate current, voltage and power factors as per datasheet formula
  103. // These are the nominal values for the Sonoff POW resistors:
  104. // * The CURRENT_RESISTOR is the 1milliOhm copper-manganese resistor in series with the main line
  105. // * The VOLTAGE_RESISTOR_UPSTREAM are the 5 470kOhm resistors in the voltage divider that feeds the V2P pin in the HLW8012
  106. // * The VOLTAGE_RESISTOR_DOWNSTREAM is the 1kOhm resistor in the voltage divider that feeds the V2P pin in the HLW8012
  107. hlw8012.setResistors(POW_CURRENT_R, POW_VOLTAGE_R_UP, POW_VOLTAGE_R_DOWN);
  108. // Retrieve calibration values
  109. powRetrieveCalibration();
  110. // Attach interrupts
  111. #if POW_USE_INTERRUPTS
  112. powAttachInterrupts();
  113. #endif
  114. apiRegister("/api/power", "power", []() {
  115. sprintf(apibuffer, "%d", getActivePower());
  116. return apibuffer;
  117. });
  118. apiRegister("/api/current", "current", []() {
  119. dtostrf(getCurrent(), 5, 2, apibuffer);
  120. return apibuffer;
  121. });
  122. apiRegister("/api/voltage", "voltage", []() {
  123. sprintf(apibuffer, "%d", getVoltage());
  124. return apibuffer;
  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. if ((millis() - last_update > POW_UPDATE_INTERVAL) || (last_update == 0 )){
  134. last_update = millis();
  135. unsigned int power = getActivePower();
  136. unsigned int voltage = getVoltage();
  137. double current = getCurrent();
  138. unsigned int apparent = getApparentPower();
  139. unsigned int factor = getPowerFactor();
  140. unsigned int reactive = getReactivePower();
  141. power_sum += power;
  142. current_sum += current;
  143. voltage_sum += voltage;
  144. DynamicJsonBuffer jsonBuffer;
  145. JsonObject& root = jsonBuffer.createObject();
  146. root["powVisible"] = 1;
  147. root["powActivePower"] = power;
  148. root["powCurrent"] = current;
  149. root["powVoltage"] = voltage;
  150. root["powApparentPower"] = apparent;
  151. root["powReactivePower"] = reactive;
  152. root["powPowerFactor"] = factor;
  153. String output;
  154. root.printTo(output);
  155. wsSend(output.c_str());
  156. if (--report_count == 0) {
  157. power = power_sum / POW_REPORT_EVERY;
  158. current = current_sum / POW_REPORT_EVERY;
  159. voltage = voltage_sum / POW_REPORT_EVERY;
  160. apparent = current * voltage;
  161. reactive = (apparent > power) ? sqrt(apparent * apparent - power * power) : 0;
  162. factor = (apparent > 0) ? 100 * power / apparent : 100;
  163. if (factor > 100) factor = 100;
  164. mqttSend(getSetting("powPowerTopic", POW_POWER_TOPIC).c_str(), String(power).c_str());
  165. mqttSend(getSetting("powCurrentTopic", POW_CURRENT_TOPIC).c_str(), String(current).c_str());
  166. mqttSend(getSetting("powVoltageTopic", POW_VOLTAGE_TOPIC).c_str(), String(voltage).c_str());
  167. mqttSend(getSetting("powAPowerTopic", POW_APOWER_TOPIC).c_str(), String(apparent).c_str());
  168. mqttSend(getSetting("powRPowerTopic", POW_RPOWER_TOPIC).c_str(), String(reactive).c_str());
  169. mqttSend(getSetting("powPFactorTopic", POW_PFACTOR_TOPIC).c_str(), String(factor).c_str());
  170. #if ENABLE_DOMOTICZ
  171. domoticzSend("dczPowIdx", power);
  172. #endif
  173. power_sum = current_sum = voltage_sum = 0;
  174. report_count = POW_REPORT_EVERY;
  175. }
  176. // Toggle between current and voltage monitoring
  177. #if POW_USE_INTERRUPTS == 0
  178. hlw8012.toggleMode();
  179. #endif
  180. }
  181. }
  182. #endif