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.

348 lines
12 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. /*
  7. #if HLW8012_SUPPORT
  8. #include <HLW8012.h>
  9. #include <Hash.h>
  10. #include <ArduinoJson.h>
  11. HLW8012 hlw8012;
  12. bool _hlw8012Enabled = false;
  13. bool _hlwReady = false;
  14. int _hlwPower = 0;
  15. double _hlwCurrent = 0;
  16. int _hlwVoltage = 0;
  17. // -----------------------------------------------------------------------------
  18. // POW
  19. // -----------------------------------------------------------------------------
  20. // When using interrupts we have to call the library entry point
  21. // whenever an interrupt is triggered
  22. void ICACHE_RAM_ATTR hlw8012_cf1_interrupt() {
  23. hlw8012.cf1_interrupt();
  24. }
  25. void ICACHE_RAM_ATTR hlw8012_cf_interrupt() {
  26. hlw8012.cf_interrupt();
  27. }
  28. void hlw8012Enable(bool status) {
  29. _hlw8012Enabled = status;
  30. if (_hlw8012Enabled) {
  31. #if HLW8012_USE_INTERRUPTS == 1
  32. attachInterrupt(HLW8012_CF1_PIN, hlw8012_cf1_interrupt, CHANGE);
  33. attachInterrupt(HLW8012_CF_PIN, hlw8012_cf_interrupt, CHANGE);
  34. #endif
  35. DEBUG_MSG_P(PSTR("[POW] Enabled\n"));
  36. } else {
  37. #if HLW8012_USE_INTERRUPTS == 1
  38. detachInterrupt(HLW8012_CF1_PIN);
  39. detachInterrupt(HLW8012_CF_PIN);
  40. #endif
  41. DEBUG_MSG_P(PSTR("[POW] Disabled\n"));
  42. }
  43. }
  44. // -----------------------------------------------------------------------------
  45. void hlw8012SaveCalibration() {
  46. setSetting("powPowerMult", hlw8012.getPowerMultiplier());
  47. setSetting("powCurrentMult", hlw8012.getCurrentMultiplier());
  48. setSetting("powVoltageMult", hlw8012.getVoltageMultiplier());
  49. saveSettings();
  50. }
  51. void hlw8012RetrieveCalibration() {
  52. double value;
  53. value = getSetting("powPowerMult", 0).toFloat();
  54. if (value > 0) hlw8012.setPowerMultiplier(value);
  55. value = getSetting("powCurrentMult", 0).toFloat();
  56. if (value > 0) hlw8012.setCurrentMultiplier(value);
  57. value = getSetting("powVoltageMult", 0).toFloat();
  58. if (value > 0) hlw8012.setVoltageMultiplier(value);
  59. }
  60. void hlw8012SetExpectedActivePower(unsigned int power) {
  61. if (power > 0) {
  62. hlw8012.expectedActivePower(power);
  63. hlw8012SaveCalibration();
  64. }
  65. }
  66. void hlw8012SetExpectedCurrent(double current) {
  67. if (current > 0) {
  68. hlw8012.expectedCurrent(current);
  69. hlw8012SaveCalibration();
  70. }
  71. }
  72. void hlw8012SetExpectedVoltage(unsigned int voltage) {
  73. if (voltage > 0) {
  74. hlw8012.expectedVoltage(voltage);
  75. hlw8012SaveCalibration();
  76. }
  77. }
  78. void hlw8012Reset() {
  79. hlw8012.resetMultipliers();
  80. hlw8012SaveCalibration();
  81. }
  82. // -----------------------------------------------------------------------------
  83. // HAL
  84. // -----------------------------------------------------------------------------
  85. unsigned int getActivePower() {
  86. unsigned int power = hlw8012.getActivePower();
  87. if (HLW8012_MIN_POWER > power || power > HLW8012_MAX_POWER) power = 0;
  88. return power;
  89. }
  90. unsigned int getApparentPower() {
  91. unsigned int power = hlw8012.getApparentPower();
  92. if (HLW8012_MIN_POWER > power || power > HLW8012_MAX_POWER) power = 0;
  93. return power;
  94. }
  95. unsigned int getReactivePower() {
  96. unsigned int power = hlw8012.getReactivePower();
  97. if (HLW8012_MIN_POWER > power || power > HLW8012_MAX_POWER) power = 0;
  98. return power;
  99. }
  100. double getCurrent() {
  101. double current = hlw8012.getCurrent();
  102. if (HLW8012_MIN_CURRENT > current || current > HLW8012_MAX_CURRENT) current = 0;
  103. return current;
  104. }
  105. //unsigned int getVoltage() {
  106. // return hlw8012.getVoltage();
  107. //}
  108. double getPowerFactor() {
  109. return hlw8012.getPowerFactor();
  110. }
  111. // -----------------------------------------------------------------------------
  112. void hlw8012Setup() {
  113. // Initialize HLW8012
  114. // 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);
  115. // * cf_pin, cf1_pin and sel_pin are GPIOs to the HLW8012 IC
  116. // * currentWhen is the value in sel_pin to select current sampling
  117. // * set use_interrupts to true to use interrupts to monitor pulse widths
  118. // * leave pulse_timeout to the default value, recommended when using interrupts
  119. #if HLW8012_USE_INTERRUPTS
  120. hlw8012.begin(HLW8012_CF_PIN, HLW8012_CF1_PIN, HLW8012_SEL_PIN, HLW8012_SEL_CURRENT, true);
  121. #else
  122. hlw8012.begin(HLW8012_CF_PIN, HLW8012_CF1_PIN, HLW8012_SEL_PIN, HLW8012_SEL_CURRENT, false, 1000000);
  123. #endif
  124. // These values are used to calculate current, voltage and power factors as per datasheet formula
  125. // These are the nominal values for the Sonoff POW resistors:
  126. // * The CURRENT_RESISTOR is the 1milliOhm copper-manganese resistor in series with the main line
  127. // * The VOLTAGE_RESISTOR_UPSTREAM are the 5 470kOhm resistors in the voltage divider that feeds the V2P pin in the HLW8012
  128. // * The VOLTAGE_RESISTOR_DOWNSTREAM is the 1kOhm resistor in the voltage divider that feeds the V2P pin in the HLW8012
  129. hlw8012.setResistors(HLW8012_CURRENT_R, HLW8012_VOLTAGE_R_UP, HLW8012_VOLTAGE_R_DOWN);
  130. // Retrieve calibration values
  131. hlw8012RetrieveCalibration();
  132. // API definitions
  133. #if WEB_SUPPORT
  134. apiRegister(HLW8012_POWER_TOPIC, HLW8012_POWER_TOPIC, [](char * buffer, size_t len) {
  135. if (_hlwReady) {
  136. snprintf_P(buffer, len, PSTR("%d"), _hlwPower);
  137. } else {
  138. buffer = NULL;
  139. }
  140. });
  141. apiRegister(HLW8012_CURRENT_TOPIC, HLW8012_CURRENT_TOPIC, [](char * buffer, size_t len) {
  142. if (_hlwReady) {
  143. dtostrf(_hlwCurrent, len-1, 3, buffer);
  144. } else {
  145. buffer = NULL;
  146. }
  147. });
  148. apiRegister(HLW8012_VOLTAGE_TOPIC, HLW8012_VOLTAGE_TOPIC, [](char * buffer, size_t len) {
  149. if (_hlwReady) {
  150. snprintf_P(buffer, len, PSTR("%d"), _hlwVoltage);
  151. } else {
  152. buffer = NULL;
  153. }
  154. });
  155. #endif // WEB_SUPPORT
  156. }
  157. void hlw8012Loop() {
  158. static unsigned long last_update = 0;
  159. static unsigned char report_count = HLW8012_REPORT_EVERY;
  160. static bool power_spike = false;
  161. static unsigned long power_sum = 0;
  162. static unsigned long power_previous = 0;
  163. static bool current_spike = false;
  164. static double current_sum = 0;
  165. static double current_previous = 0;
  166. static bool voltage_spike = false;
  167. static unsigned long voltage_sum = 0;
  168. static unsigned long voltage_previous = 0;
  169. static bool powWasEnabled = false;
  170. // POW is disabled while there is no internet connection
  171. // When the HLW8012 measurements are enabled back we reset the timer
  172. if (!_hlw8012Enabled) {
  173. powWasEnabled = false;
  174. return;
  175. }
  176. if (!powWasEnabled) {
  177. last_update = millis();
  178. powWasEnabled = true;
  179. }
  180. if (millis() - last_update > HLW8012_UPDATE_INTERVAL) {
  181. last_update = millis();
  182. unsigned int power = getActivePower();
  183. unsigned int voltage = getVoltage();
  184. double current = getCurrent();
  185. if (power > 0) {
  186. power_spike = (power_previous == 0);
  187. } else if (power_spike) {
  188. power_sum -= power_previous;
  189. power_spike = false;
  190. }
  191. power_previous = power;
  192. if (current > 0) {
  193. current_spike = (current_previous == 0);
  194. } else if (current_spike) {
  195. current_sum -= current_previous;
  196. current_spike = false;
  197. }
  198. current_previous = current;
  199. if (voltage > 0) {
  200. voltage_spike = (voltage_previous == 0);
  201. } else if (voltage_spike) {
  202. voltage_sum -= voltage_previous;
  203. voltage_spike = false;
  204. }
  205. voltage_previous = voltage;
  206. #if WEB_SUPPORT
  207. {
  208. unsigned int apparent = getApparentPower();
  209. double factor = getPowerFactor();
  210. unsigned int reactive = getReactivePower();
  211. DynamicJsonBuffer jsonBuffer;
  212. JsonObject& root = jsonBuffer.createObject();
  213. root["powVisible"] = 1;
  214. root["powActivePower"] = power;
  215. root["powCurrent"] = String(current, 3);
  216. root["powVoltage"] = voltage;
  217. root["powApparentPower"] = apparent;
  218. root["powReactivePower"] = reactive;
  219. root["powPowerFactor"] = String(factor, 2);
  220. String output;
  221. root.printTo(output);
  222. wsSend(output.c_str());
  223. }
  224. #endif
  225. if (--report_count == 0) {
  226. // Update globals
  227. _hlwPower = power_sum / HLW8012_REPORT_EVERY;
  228. _hlwCurrent = current_sum / HLW8012_REPORT_EVERY;
  229. _hlwVoltage = voltage_sum / HLW8012_REPORT_EVERY;
  230. _hlwReady = true;
  231. // Calculate subproducts (apparent and reactive power, power factor and delta energy)
  232. unsigned int apparent = _hlwCurrent * _hlwVoltage;
  233. unsigned int reactive = (apparent > _hlwPower) ? sqrt(apparent * apparent - _hlwPower * _hlwPower) : 0;
  234. double factor = (apparent > 0) ? (double) _hlwPower / apparent : 1;
  235. if (factor > 1) factor = 1;
  236. double energy_delta = (double) _hlwPower * HLW8012_REPORT_EVERY * HLW8012_UPDATE_INTERVAL / 1000.0 / 3600.0;
  237. // Report values to MQTT broker
  238. mqttSend(getSetting("powPowerTopic", HLW8012_POWER_TOPIC).c_str(), String(_hlwPower).c_str());
  239. mqttSend(getSetting("powCurrentTopic", HLW8012_CURRENT_TOPIC).c_str(), String(_hlwCurrent, 3).c_str());
  240. mqttSend(getSetting("powVoltageTopic", HLW8012_VOLTAGE_TOPIC).c_str(), String(_hlwVoltage).c_str());
  241. mqttSend(getSetting("powEnergyTopic", HLW8012_ENERGY_TOPIC).c_str(), String(energy_delta, 3).c_str());
  242. mqttSend(getSetting("powAPowerTopic", HLW8012_APOWER_TOPIC).c_str(), String(apparent).c_str());
  243. mqttSend(getSetting("powRPowerTopic", HLW8012_RPOWER_TOPIC).c_str(), String(reactive).c_str());
  244. mqttSend(getSetting("powPFactorTopic", HLW8012_PFACTOR_TOPIC).c_str(), String(factor, 2).c_str());
  245. // Report values to Domoticz
  246. #if DOMOTICZ_SUPPORT
  247. {
  248. char buffer[20];
  249. snprintf_P(buffer, sizeof(buffer), PSTR("%d;%s"), _hlwPower, String(energy_delta, 3).c_str());
  250. domoticzSend("dczPowIdx", 0, buffer);
  251. snprintf_P(buffer, sizeof(buffer), PSTR("%s"), String(energy_delta, 3).c_str());
  252. domoticzSend("dczEnergyIdx", 0, buffer);
  253. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _hlwVoltage);
  254. domoticzSend("dczVoltIdx", 0, buffer);
  255. snprintf_P(buffer, sizeof(buffer), PSTR("%s"), String(_hlwCurrent).c_str());
  256. domoticzSend("dczCurrentIdx", 0, buffer);
  257. }
  258. #endif
  259. #if INFLUXDB_SUPPORT
  260. influxDBSend(getSetting("powPowerTopic", HLW8012_POWER_TOPIC).c_str(), String(_hlwPower).c_str());
  261. influxDBSend(getSetting("powCurrentTopic", HLW8012_CURRENT_TOPIC).c_str(), String(_hlwCurrent, 3).c_str());
  262. influxDBSend(getSetting("powVoltageTopic", HLW8012_VOLTAGE_TOPIC).c_str(), String(_hlwVoltage).c_str());
  263. influxDBSend(getSetting("powEnergyTopic", HLW8012_ENERGY_TOPIC).c_str(), String(energy_delta, 3).c_str());
  264. influxDBSend(getSetting("powAPowerTopic", HLW8012_APOWER_TOPIC).c_str(), String(apparent).c_str());
  265. influxDBSend(getSetting("powRPowerTopic", HLW8012_RPOWER_TOPIC).c_str(), String(reactive).c_str());
  266. influxDBSend(getSetting("powPFactorTopic", HLW8012_PFACTOR_TOPIC).c_str(), String(factor, 2).c_str());
  267. #endif
  268. // Reset counters
  269. power_sum = current_sum = voltage_sum = 0;
  270. report_count = HLW8012_REPORT_EVERY;
  271. }
  272. // Post - Accumulators
  273. power_sum += power_previous;
  274. current_sum += current_previous;
  275. voltage_sum += voltage_previous;
  276. // Toggle between current and voltage monitoring
  277. #if HLW8012_USE_INTERRUPTS == 0
  278. hlw8012.toggleMode();
  279. #endif
  280. }
  281. }
  282. #endif
  283. */