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.

319 lines
11 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 ICACHE_RAM_ATTR hlw8012_cf1_interrupt() {
  19. hlw8012.cf1_interrupt();
  20. }
  21. void ICACHE_RAM_ATTR 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. unsigned int power = hlw8012.getActivePower();
  80. if (POW_MIN_POWER > power || power > POW_MAX_POWER) power = 0;
  81. return power;
  82. }
  83. unsigned int getApparentPower() {
  84. unsigned int power = hlw8012.getApparentPower();
  85. if (POW_MIN_POWER > power || power > POW_MAX_POWER) power = 0;
  86. return power;
  87. }
  88. unsigned int getReactivePower() {
  89. unsigned int power = hlw8012.getReactivePower();
  90. if (POW_MIN_POWER > power || power > POW_MAX_POWER) power = 0;
  91. return power;
  92. }
  93. double getCurrent() {
  94. double current = hlw8012.getCurrent();
  95. if (POW_MIN_CURRENT > current || current > POW_MAX_CURRENT) current = 0;
  96. return current;
  97. }
  98. unsigned int getVoltage() {
  99. return hlw8012.getVoltage();
  100. }
  101. double getPowerFactor() {
  102. return hlw8012.getPowerFactor();
  103. }
  104. // -----------------------------------------------------------------------------
  105. void powSetup() {
  106. // Initialize HLW8012
  107. // 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);
  108. // * cf_pin, cf1_pin and sel_pin are GPIOs to the HLW8012 IC
  109. // * currentWhen is the value in sel_pin to select current sampling
  110. // * set use_interrupts to true to use interrupts to monitor pulse widths
  111. // * leave pulse_timeout to the default value, recommended when using interrupts
  112. #if POW_USE_INTERRUPTS
  113. hlw8012.begin(POW_CF_PIN, POW_CF1_PIN, POW_SEL_PIN, POW_SEL_CURRENT, true);
  114. #else
  115. hlw8012.begin(POW_CF_PIN, POW_CF1_PIN, POW_SEL_PIN, POW_SEL_CURRENT, false, 1000000);
  116. #endif
  117. // These values are used to calculate current, voltage and power factors as per datasheet formula
  118. // These are the nominal values for the Sonoff POW resistors:
  119. // * The CURRENT_RESISTOR is the 1milliOhm copper-manganese resistor in series with the main line
  120. // * The VOLTAGE_RESISTOR_UPSTREAM are the 5 470kOhm resistors in the voltage divider that feeds the V2P pin in the HLW8012
  121. // * The VOLTAGE_RESISTOR_DOWNSTREAM is the 1kOhm resistor in the voltage divider that feeds the V2P pin in the HLW8012
  122. hlw8012.setResistors(POW_CURRENT_R, POW_VOLTAGE_R_UP, POW_VOLTAGE_R_DOWN);
  123. // Retrieve calibration values
  124. powRetrieveCalibration();
  125. // API definitions
  126. apiRegister(POW_POWER_TOPIC, POW_POWER_TOPIC, [](char * buffer, size_t len) {
  127. snprintf(buffer, len, "%d", getActivePower());
  128. });
  129. apiRegister(POW_CURRENT_TOPIC, POW_CURRENT_TOPIC, [](char * buffer, size_t len) {
  130. dtostrf(getCurrent(), len-1, 3, buffer);
  131. });
  132. apiRegister(POW_VOLTAGE_TOPIC, POW_VOLTAGE_TOPIC, [](char * buffer, size_t len) {
  133. snprintf(buffer, len, "%d", getVoltage());
  134. });
  135. }
  136. void powLoop() {
  137. static unsigned long last_update = 0;
  138. static unsigned char report_count = POW_REPORT_EVERY;
  139. static bool power_spike = false;
  140. static unsigned long power_sum = 0;
  141. static unsigned long power_previous = 0;
  142. static bool current_spike = false;
  143. static double current_sum = 0;
  144. static double current_previous = 0;
  145. static bool voltage_spike = false;
  146. static unsigned long voltage_sum = 0;
  147. static unsigned long voltage_previous = 0;
  148. static bool powWasEnabled = false;
  149. // POW is disabled while there is no internet connection
  150. // When the HLW8012 measurements are enabled back we reset the timer
  151. if (!_powEnabled) {
  152. powWasEnabled = false;
  153. return;
  154. }
  155. if (!powWasEnabled) {
  156. last_update = millis();
  157. powWasEnabled = true;
  158. }
  159. if (millis() - last_update > POW_UPDATE_INTERVAL) {
  160. last_update = millis();
  161. unsigned int power = getActivePower();
  162. unsigned int voltage = getVoltage();
  163. double current = getCurrent();
  164. unsigned int apparent = getApparentPower();
  165. double factor = getPowerFactor();
  166. unsigned int reactive = getReactivePower();
  167. if (power > 0) {
  168. power_spike = (power_previous == 0);
  169. } else if (power_spike) {
  170. power_sum -= power_previous;
  171. power_spike = false;
  172. }
  173. power_previous = power;
  174. if (current > 0) {
  175. current_spike = (current_previous == 0);
  176. } else if (current_spike) {
  177. current_sum -= current_previous;
  178. current_spike = false;
  179. }
  180. current_previous = current;
  181. if (voltage > 0) {
  182. voltage_spike = (voltage_previous == 0);
  183. } else if (voltage_spike) {
  184. voltage_sum -= voltage_previous;
  185. voltage_spike = false;
  186. }
  187. voltage_previous = voltage;
  188. DynamicJsonBuffer jsonBuffer;
  189. JsonObject& root = jsonBuffer.createObject();
  190. root["powVisible"] = 1;
  191. root["powActivePower"] = power;
  192. root["powCurrent"] = String(current, 3);
  193. root["powVoltage"] = voltage;
  194. root["powApparentPower"] = apparent;
  195. root["powReactivePower"] = reactive;
  196. root["powPowerFactor"] = String(factor, 2);
  197. String output;
  198. root.printTo(output);
  199. wsSend(output.c_str());
  200. if (--report_count == 0) {
  201. power = power_sum / POW_REPORT_EVERY;
  202. current = current_sum / POW_REPORT_EVERY;
  203. voltage = voltage_sum / POW_REPORT_EVERY;
  204. apparent = current * voltage;
  205. reactive = (apparent > power) ? sqrt(apparent * apparent - power * power) : 0;
  206. factor = (apparent > 0) ? (double) power / apparent : 1;
  207. if (factor > 1) factor = 1;
  208. // Calculate energy increment (ppower times time) and create C-string
  209. double energy_inc = (double) power * POW_REPORT_EVERY * POW_UPDATE_INTERVAL / 1000.0 / 3600.0;
  210. char energy_buf[11];
  211. dtostrf(energy_inc, 11, 3, energy_buf);
  212. char *e = energy_buf;
  213. while ((unsigned char) *e == ' ') ++e;
  214. // Report values to MQTT broker
  215. mqttSend(getSetting("powPowerTopic", POW_POWER_TOPIC).c_str(), String(power).c_str());
  216. mqttSend(getSetting("powEnergyTopic", POW_ENERGY_TOPIC).c_str(), e);
  217. mqttSend(getSetting("powCurrentTopic", POW_CURRENT_TOPIC).c_str(), String(current, 3).c_str());
  218. mqttSend(getSetting("powVoltageTopic", POW_VOLTAGE_TOPIC).c_str(), String(voltage).c_str());
  219. mqttSend(getSetting("powAPowerTopic", POW_APOWER_TOPIC).c_str(), String(apparent).c_str());
  220. mqttSend(getSetting("powRPowerTopic", POW_RPOWER_TOPIC).c_str(), String(reactive).c_str());
  221. mqttSend(getSetting("powPFactorTopic", POW_PFACTOR_TOPIC).c_str(), String(factor, 2).c_str());
  222. // Report values to Domoticz
  223. #if ENABLE_DOMOTICZ
  224. {
  225. char buffer[20];
  226. snprintf(buffer, 20, "%d;%s", power, e);
  227. domoticzSend("dczPowIdx", 0, buffer);
  228. snprintf(buffer, 20, "%s", e);
  229. domoticzSend("dczEnergyIdx", 0, buffer);
  230. snprintf(buffer, 20, "%d", voltage);
  231. domoticzSend("dczVoltIdx", 0, buffer);
  232. snprintf(buffer, 20, "%s", String(current).c_str());
  233. domoticzSend("dczCurrentIdx", 0, buffer);
  234. }
  235. #endif
  236. #if ENABLE_INFLUXDB
  237. influxDBSend(getSetting("powPowerTopic", POW_POWER_TOPIC).c_str(), String(power).c_str());
  238. //influxDBSend(getSetting("powEnergyTopic", POW_ENERGY_TOPIC).c_str(), e);
  239. //influxDBSend(getSetting("powCurrentTopic", POW_CURRENT_TOPIC).c_str(), String(current, 3).c_str());
  240. //influxDBSend(getSetting("powVoltageTopic", POW_VOLTAGE_TOPIC).c_str(), String(voltage).c_str());
  241. //influxDBSend(getSetting("powAPowerTopic", POW_APOWER_TOPIC).c_str(), String(apparent).c_str());
  242. //influxDBSend(getSetting("powRPowerTopic", POW_RPOWER_TOPIC).c_str(), String(reactive).c_str());
  243. //influxDBSend(getSetting("powPFactorTopic", POW_PFACTOR_TOPIC).c_str(), String(factor, 2).c_str());
  244. #endif
  245. // Reset counters
  246. power_sum = current_sum = voltage_sum = 0;
  247. report_count = POW_REPORT_EVERY;
  248. }
  249. // Post - Accumulators
  250. power_sum += power_previous;
  251. current_sum += current_previous;
  252. voltage_sum += voltage_previous;
  253. // Toggle between current and voltage monitoring
  254. #if POW_USE_INTERRUPTS == 0
  255. hlw8012.toggleMode();
  256. #endif
  257. }
  258. }
  259. #endif