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.

416 lines
14 KiB

  1. /*
  2. POWER MODULE
  3. Copyright (C) 2016-2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  6. // -----------------------------------------------------------------------------
  7. // MODULE GLOBALS AND CACHE
  8. // -----------------------------------------------------------------------------
  9. #include "libs/MedianFilter.h"
  10. #include <Hash.h>
  11. #include <ArduinoJson.h>
  12. bool _power_enabled = false;
  13. bool _power_newdata = false;
  14. bool _power_realtime = API_REAL_TIME_VALUES;
  15. unsigned long _power_read_interval = POWER_READ_INTERVAL;
  16. unsigned long _power_report_interval = POWER_REPORT_INTERVAL;
  17. double _power_current = 0;
  18. double _power_voltage = 0;
  19. double _power_apparent = 0;
  20. double _power_energy = 0;
  21. MedianFilter _filter_current = MedianFilter();
  22. #if POWER_HAS_ACTIVE
  23. double _power_active = 0;
  24. double _power_reactive = 0;
  25. double _power_factor = 0;
  26. MedianFilter _filter_voltage = MedianFilter();
  27. MedianFilter _filter_active = MedianFilter();
  28. MedianFilter _filter_apparent = MedianFilter();
  29. #endif
  30. #if POWER_HAS_ENERGY
  31. double _power_last_energy = 0;
  32. #endif
  33. // -----------------------------------------------------------------------------
  34. // PRIVATE METHODS
  35. // -----------------------------------------------------------------------------
  36. #if WEB_SUPPORT
  37. void _powerWebSocketOnSend(JsonObject& root) {
  38. root["pwrVisible"] = 1;
  39. root["pwrCurrent"] = getCurrent();
  40. root["pwrVoltage"] = getVoltage();
  41. root["pwrApparent"] = getApparentPower();
  42. root["pwrEnergy"] = getPowerEnergy();
  43. root["pwrReadEvery"] = powerReadInterval();
  44. root["pwrReportEvery"] = powerReportInterval();
  45. #if POWER_HAS_ACTIVE
  46. root["pwrActive"] = getActivePower();
  47. root["pwrReactive"] = getReactivePower();
  48. root["pwrFactor"] = int(100 * getPowerFactor());
  49. #endif
  50. #if (POWER_PROVIDER == POWER_PROVIDER_EMON_ANALOG) || (POWER_PROVIDER == POWER_PROVIDER_EMON_ADC121)
  51. root["emonVisible"] = 1;
  52. #endif
  53. #if POWER_PROVIDER == POWER_PROVIDER_HLW8012
  54. root["hlwVisible"] = 1;
  55. #endif
  56. #if POWER_PROVIDER == POWER_PROVIDER_V9261F
  57. root["v9261fVisible"] = 1;
  58. #endif
  59. #if POWER_PROVIDER == POWER_PROVIDER_ECH1560
  60. root["ech1560fVisible"] = 1;
  61. #endif
  62. }
  63. void _powerAPISetup() {
  64. apiRegister(MQTT_TOPIC_CURRENT, MQTT_TOPIC_CURRENT, [](char * buffer, size_t len) {
  65. dtostrf(_power_realtime ? _powerCurrent() : getCurrent(), 1-len, POWER_CURRENT_DECIMALS, buffer);
  66. });
  67. apiRegister(MQTT_TOPIC_VOLTAGE, MQTT_TOPIC_VOLTAGE, [](char * buffer, size_t len) {
  68. snprintf_P(buffer, len, PSTR("%d"), (int) (_power_realtime ? _powerVoltage() : getVoltage()));
  69. });
  70. apiRegister(MQTT_TOPIC_POWER_APPARENT, MQTT_TOPIC_POWER_APPARENT, [](char * buffer, size_t len) {
  71. snprintf_P(buffer, len, PSTR("%d"), (int) (_power_realtime ? _powerApparentPower() : getApparentPower()));
  72. });
  73. #if POWER_HAS_ENERGY
  74. apiRegister(MQTT_TOPIC_ENERGY_TOTAL, MQTT_TOPIC_ENERGY_TOTAL, [](char * buffer, size_t len) {
  75. snprintf_P(buffer, len, PSTR("%lu"), (int) (_power_realtime ? _powerEnergy() : getPowerEnergy()));
  76. });
  77. #endif
  78. #if POWER_HAS_ACTIVE
  79. apiRegister(MQTT_TOPIC_POWER_ACTIVE, MQTT_TOPIC_POWER_ACTIVE, [](char * buffer, size_t len) {
  80. snprintf_P(buffer, len, PSTR("%d"), (int) (_power_realtime ? _powerActivePower() : getActivePower()));
  81. });
  82. apiRegister(MQTT_TOPIC_POWER_FACTOR, MQTT_TOPIC_POWER_FACTOR, [](char * buffer, size_t len) {
  83. snprintf_P(buffer, len, PSTR("%d"), (int) (100 * (_power_realtime ? _powerPowerFactor() : getPowerFactor())));
  84. });
  85. #endif
  86. }
  87. #endif // WEB_SUPPORT
  88. void _powerReset() {
  89. _filter_current.reset();
  90. #if POWER_HAS_ACTIVE
  91. _filter_apparent.reset();
  92. _filter_voltage.reset();
  93. _filter_active.reset();
  94. #endif
  95. }
  96. void _powerRead() {
  97. // Get instantaneous values from HAL
  98. double current = _powerCurrent();
  99. double voltage = _powerVoltage();
  100. double apparent = _powerApparentPower();
  101. #if POWER_HAS_ACTIVE
  102. double active = _powerActivePower();
  103. double reactive = (apparent > active) ? sqrt(apparent * apparent - active * active) : 0;
  104. double factor = (apparent > 0) ? active / apparent : 1;
  105. if (factor > 1) factor = 1;
  106. #endif
  107. #if POWER_HAS_ENERGY
  108. _power_energy = _powerEnergy(); // Due to its nature this value doesn't have to be filtered
  109. #endif
  110. // Filters
  111. _filter_current.add(current);
  112. #if POWER_HAS_ACTIVE
  113. _filter_apparent.add(apparent);
  114. _filter_voltage.add(voltage);
  115. _filter_active.add(active);
  116. #endif
  117. // Debug
  118. /*
  119. char current_buffer[10];
  120. dtostrf(current, 1-sizeof(current_buffer), POWER_CURRENT_DECIMALS, current_buffer);
  121. DEBUG_MSG_P(PSTR("[POWER] Current: %sA\n"), current_buffer);
  122. DEBUG_MSG_P(PSTR("[POWER] Voltage: %dV\n"), (int) voltage);
  123. DEBUG_MSG_P(PSTR("[POWER] Apparent Power: %dW\n"), (int) apparent);
  124. DEBUG_MSG_P(PSTR("[POWER] Energy: %dJ\n"), (int) _power_energy);
  125. #if POWER_HAS_ACTIVE
  126. DEBUG_MSG_P(PSTR("[POWER] Active Power: %dW\n"), (int) active);
  127. DEBUG_MSG_P(PSTR("[POWER] Reactive Power: %dW\n"), (int) reactive);
  128. DEBUG_MSG_P(PSTR("[POWER] Power Factor: %d%%\n"), (int) (100 * factor));
  129. #endif
  130. */
  131. // Update websocket clients
  132. #if WEB_SUPPORT
  133. if (wsConnected()) {
  134. DynamicJsonBuffer jsonBuffer;
  135. JsonObject& root = jsonBuffer.createObject();
  136. root["pwrVisible"] = 1;
  137. root["pwrCurrent"] = roundTo(current, POWER_CURRENT_DECIMALS);
  138. root["pwrVoltage"] = roundTo(voltage, POWER_VOLTAGE_DECIMALS);
  139. root["pwrApparent"] = roundTo(apparent, POWER_POWER_DECIMALS);
  140. root["pwrEnergy"] = roundTo(_power_energy, POWER_ENERGY_DECIMALS);
  141. #if POWER_HAS_ACTIVE
  142. root["pwrActive"] = roundTo(active, POWER_POWER_DECIMALS);
  143. root["pwrReactive"] = roundTo(reactive, POWER_POWER_DECIMALS);
  144. root["pwrFactor"] = int(100 * factor);
  145. #endif
  146. #if (POWER_PROVIDER == POWER_PROVIDER_EMON_ANALOG) || (POWER_PROVIDER == POWER_PROVIDER_EMON_ADC121)
  147. root["emonVisible"] = 1;
  148. #endif
  149. #if POWER_PROVIDER == POWER_PROVIDER_HLW8012
  150. root["hlwVisible"] = 1;
  151. #endif
  152. #if POWER_PROVIDER == POWER_PROVIDER_V9261F
  153. root["v9261fVisible"] = 1;
  154. #endif
  155. #if POWER_PROVIDER == POWER_PROVIDER_ECH1560
  156. root["ech1560Visible"] = 1;
  157. #endif
  158. String output;
  159. root.printTo(output);
  160. wsSend(output.c_str());
  161. }
  162. #endif
  163. }
  164. void _powerReport() {
  165. // Get the fitered values
  166. _power_current = _filter_current.result(true);
  167. #if POWER_HAS_ACTIVE
  168. _power_apparent = _filter_apparent.result(true);
  169. _power_voltage = _filter_voltage.result(true);
  170. _power_active = _filter_active.result(true);
  171. if (_power_active > _power_apparent) _power_apparent = _power_active;
  172. _power_reactive = (_power_apparent > _power_active) ? sqrt(_power_apparent * _power_apparent - _power_active * _power_active) : 0;
  173. _power_factor = (_power_apparent > 0) ? _power_active / _power_apparent : 1;
  174. if (_power_factor > 1) _power_factor = 1;
  175. double power = _power_active;
  176. #else
  177. _power_apparent = _power_current * _power_voltage;
  178. double power = _power_apparent;
  179. #endif
  180. #if POWER_HAS_ENERGY
  181. double energy_delta = _power_energy - _power_last_energy;
  182. _power_last_energy = _power_energy;
  183. #else
  184. double energy_delta = power * (_power_report_interval / 1000.);
  185. _power_energy += energy_delta;
  186. #endif
  187. char buf_current[10];
  188. char buf_energy_delta[20];
  189. char buf_energy_total[20];
  190. dtostrf(_power_current, 1-sizeof(buf_current), POWER_CURRENT_DECIMALS, buf_current);
  191. dtostrf(energy_delta * POWER_ENERGY_FACTOR, 1-sizeof(buf_energy_delta), POWER_ENERGY_DECIMALS, buf_energy_delta);
  192. dtostrf(_power_energy * POWER_ENERGY_FACTOR, 1-sizeof(buf_energy_total), POWER_ENERGY_DECIMALS, buf_energy_total);
  193. #if MQTT_SUPPORT
  194. {
  195. mqttSend(MQTT_TOPIC_CURRENT, buf_current);
  196. mqttSend(MQTT_TOPIC_POWER_APPARENT, String((int) _power_apparent).c_str());
  197. mqttSend(MQTT_TOPIC_ENERGY_DELTA, buf_energy_delta);
  198. mqttSend(MQTT_TOPIC_ENERGY_TOTAL, buf_energy_total);
  199. #if POWER_HAS_ACTIVE
  200. mqttSend(MQTT_TOPIC_POWER_ACTIVE, String((int) _power_active).c_str());
  201. mqttSend(MQTT_TOPIC_POWER_REACTIVE, String((int) _power_reactive).c_str());
  202. mqttSend(MQTT_TOPIC_VOLTAGE, String((int) _power_voltage).c_str());
  203. mqttSend(MQTT_TOPIC_POWER_FACTOR, String((int) 100 * _power_factor).c_str());
  204. #endif
  205. }
  206. #endif
  207. #if DOMOTICZ_SUPPORT
  208. if (domoticzEnabled()) {
  209. // Domoticz expects energy in kWh
  210. char buf_energy_kwh[10];
  211. dtostrf(energy_delta * POWER_ENERGY_FACTOR_KWH, 1-sizeof(buf_energy_kwh), POWER_ENERGY_DECIMALS_KWH, buf_energy_kwh);
  212. char buffer[20];
  213. snprintf_P(buffer, sizeof(buffer), PSTR("%d;%s"), (int) power, buf_energy_kwh);
  214. domoticzSend("dczPowIdx", 0, buffer);
  215. domoticzSend("dczCurrentIdx", 0, buf_current);
  216. domoticzSend("dczEnergyIdx", 0, buf_energy_kwh);
  217. #if POWER_HAS_ACTIVE
  218. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), (int) _power_voltage);
  219. domoticzSend("dczVoltIdx", 0, buffer);
  220. #endif
  221. }
  222. #endif
  223. #if INFLUXDB_SUPPORT
  224. if (idbEnabled()) {
  225. idbSend(MQTT_TOPIC_CURRENT, buf_current);
  226. idbSend(MQTT_TOPIC_POWER_APPARENT, String((int) _power_apparent).c_str());
  227. idbSend(MQTT_TOPIC_ENERGY_DELTA, buf_energy_delta);
  228. idbSend(MQTT_TOPIC_ENERGY_TOTAL, buf_energy_total);
  229. #if POWER_HAS_ACTIVE
  230. idbSend(MQTT_TOPIC_POWER_ACTIVE, String((int) _power_active).c_str());
  231. idbSend(MQTT_TOPIC_POWER_REACTIVE, String((int) _power_reactive).c_str());
  232. idbSend(MQTT_TOPIC_VOLTAGE, String((int) _power_voltage).c_str());
  233. idbSend(MQTT_TOPIC_POWER_FACTOR, String((int) 100 * _power_factor).c_str());
  234. #endif
  235. }
  236. #endif
  237. }
  238. void _powerConfigure() {
  239. _power_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  240. _power_read_interval = atol(getSetting("pwrReadEvery", POWER_READ_INTERVAL).c_str());
  241. _power_report_interval = atol(getSetting("pwrReportEvery", POWER_REPORT_INTERVAL).c_str());
  242. if (_power_read_interval < POWER_MIN_READ_INTERVAL) {
  243. _power_read_interval = POWER_MIN_READ_INTERVAL;
  244. setSetting("pwrReadEvery", _power_read_interval);
  245. }
  246. if (_power_report_interval < _power_read_interval) {
  247. _power_report_interval = _power_read_interval;
  248. setSetting("pwrReportEvery", _power_report_interval);
  249. }
  250. _powerConfigureProvider();
  251. }
  252. // -----------------------------------------------------------------------------
  253. // MAGNITUDE API
  254. // -----------------------------------------------------------------------------
  255. bool hasActivePower() {
  256. return POWER_HAS_ACTIVE;
  257. }
  258. double getCurrent() {
  259. return roundTo(_power_current, POWER_CURRENT_DECIMALS);
  260. }
  261. double getVoltage() {
  262. return roundTo(_power_voltage, POWER_VOLTAGE_DECIMALS);
  263. }
  264. double getApparentPower() {
  265. return roundTo(_power_apparent, POWER_POWER_DECIMALS);
  266. }
  267. double getPowerEnergy() {
  268. roundTo(_power_energy, POWER_ENERGY_DECIMALS);
  269. }
  270. #if POWER_HAS_ACTIVE
  271. double getActivePower() {
  272. return roundTo(_power_active, POWER_POWER_DECIMALS);
  273. }
  274. double getReactivePower() {
  275. return roundTo(_power_reactive, POWER_POWER_DECIMALS);
  276. }
  277. double getPowerFactor() {
  278. return roundTo(_power_factor, 2);
  279. }
  280. #endif
  281. // -----------------------------------------------------------------------------
  282. // PUBLIC API
  283. // -----------------------------------------------------------------------------
  284. unsigned long powerReadInterval() {
  285. return _power_read_interval;
  286. }
  287. unsigned long powerReportInterval() {
  288. return _power_report_interval;
  289. }
  290. bool powerEnabled() {
  291. return _power_enabled;
  292. }
  293. void powerEnabled(bool enabled) {
  294. if (enabled & !_power_enabled) _powerReset();
  295. _power_enabled = enabled;
  296. _powerEnabledProvider();
  297. }
  298. void powerCalibrate(unsigned char magnitude, double value) {
  299. _powerCalibrateProvider(magnitude, value);
  300. }
  301. void powerResetCalibration() {
  302. _powerResetCalibrationProvider();
  303. }
  304. void powerSetup() {
  305. // backwards compatibility
  306. moveSetting("pwMainsVoltage", "pwrVoltage");
  307. moveSetting("emonMains", "pwrVoltage");
  308. moveSetting("emonVoltage", "pwrVoltage");
  309. moveSetting("pwCurrentRatio", "pwrRatioC");
  310. moveSetting("emonRatio", "pwrRatioC");
  311. moveSetting("powPowerMult", "pwrRatioP");
  312. moveSetting("powCurrentMult", "pwrRatioC");
  313. moveSetting("powVoltageMult", "pwrRatioV");
  314. moveSetting("powerVoltage", "pwrVoltage");
  315. moveSetting("powerRatioC", "pwrRatioC");
  316. moveSetting("powerRatioV", "pwrRatioV");
  317. moveSetting("powerRatioP", "pwrRatioP");
  318. _powerSetupProvider();
  319. _powerConfigure();
  320. // API
  321. #if WEB_SUPPORT
  322. wsOnSendRegister(_powerWebSocketOnSend);
  323. wsOnAfterParseRegister(_powerConfigure);
  324. _powerAPISetup();
  325. #endif
  326. DEBUG_MSG_P(PSTR("[POWER] POWER_PROVIDER = %d\n"), POWER_PROVIDER);
  327. }
  328. void powerLoop() {
  329. _powerLoopProvider(true);
  330. if (_power_newdata) {
  331. _power_newdata = false;
  332. _powerRead();
  333. }
  334. static unsigned long last = 0;
  335. if (millis() - last > _power_report_interval) {
  336. last = millis();
  337. _powerReport();
  338. }
  339. _powerLoopProvider(false);
  340. }
  341. #endif // POWER_PROVIDER != POWER_PROVIDER_NONE