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.

415 lines
14 KiB

7 years ago
  1. // -----------------------------------------------------------------------------
  2. // Event Counter Sensor
  3. // Copyright (C) 2017-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. // -----------------------------------------------------------------------------
  5. #if SENSOR_SUPPORT && HLW8012_SUPPORT
  6. #pragma once
  7. #include <Arduino.h>
  8. #include <HLW8012.h>
  9. #include "../debug.h"
  10. #include "BaseEmonSensor.h"
  11. // ref. HLW8012/src/HLW8012.h
  12. //
  13. // These values are used to calculate current, voltage and power factors as per datasheet formula
  14. // These are the nominal values for the Sonoff POW resistors:
  15. // * The CURRENT_RESISTOR is the 1milliOhm copper-manganese resistor in series with the main line
  16. // * The VOLTAGE_RESISTOR_UPSTREAM are the 5 470kOhm resistors in the voltage divider that feeds the V2P pin in the HLW8012
  17. // * The VOLTAGE_RESISTOR_DOWNSTREAM is the 1kOhm resistor in the voltage divider that feeds the V2P pin in the HLW8012
  18. //
  19. // (note: V_REF & F_OSC come from HLW8012.h)
  20. namespace {
  21. constexpr double _hlw8012_voltage_resistor(double voltage_upstream, double voltage_downstream) {
  22. return (voltage_upstream + voltage_downstream) / voltage_downstream;
  23. }
  24. constexpr double _hlw8012_default_voltage_resistor() {
  25. return _hlw8012_voltage_resistor(HLW8012_VOLTAGE_R_UP, HLW8012_VOLTAGE_R_DOWN);
  26. }
  27. constexpr double _hlw8012_default_current_resistor() {
  28. return HLW8012_CURRENT_R;
  29. }
  30. // TODO: ..._RATIO flags are 0, but would it not make a better case for 1.0 as default aka make this a 'multiplier'?
  31. // TODO: Also note that HLW8012 lib will happily accept 0.0 as multiplier, with no way to recover back through the WebUI as we only adjust 'expected' value
  32. constexpr double _hlw8012_default_current_multiplier() {
  33. return (HLW8012_CURRENT_RATIO != 0.0)
  34. ? (HLW8012_CURRENT_RATIO)
  35. : ( 1000000.0 * 512 * V_REF / _hlw8012_default_current_resistor() / 24.0 / F_OSC );
  36. }
  37. constexpr double _hlw8012_default_voltage_multiplier() {
  38. return (HLW8012_VOLTAGE_RATIO != 0.0)
  39. ? (HLW8012_VOLTAGE_RATIO)
  40. : ( 1000000.0 * 512 * V_REF * _hlw8012_default_voltage_resistor() / 2.0 / F_OSC );
  41. }
  42. constexpr double _hlw8012_default_power_multiplier() {
  43. return (HLW8012_POWER_RATIO != 0.0)
  44. ? (HLW8012_POWER_RATIO)
  45. : ( 1000000.0 * 128 * V_REF * V_REF * _hlw8012_default_voltage_resistor() / _hlw8012_default_current_resistor() / 48.0 / F_OSC );
  46. }
  47. } //namespace
  48. class HLW8012Sensor : public BaseEmonSensor {
  49. public:
  50. // ---------------------------------------------------------------------
  51. // Public
  52. // ---------------------------------------------------------------------
  53. HLW8012Sensor() {
  54. _count = 8;
  55. _sensor_id = SENSOR_HLW8012_ID;
  56. _hlw8012 = new HLW8012();
  57. }
  58. ~HLW8012Sensor() {
  59. _enableInterrupts(false);
  60. delete _hlw8012;
  61. }
  62. // ---------------------------------------------------------------------
  63. void setSEL(unsigned char sel) {
  64. if (_sel == sel) return;
  65. _sel = sel;
  66. _dirty = true;
  67. }
  68. void setCF(unsigned char cf) {
  69. if (_cf == cf) return;
  70. _cf = cf;
  71. _dirty = true;
  72. }
  73. void setCF1(unsigned char cf1) {
  74. if (_cf1 == cf1) return;
  75. _cf1 = cf1;
  76. _dirty = true;
  77. }
  78. void setSELCurrent(bool value) {
  79. _sel_current = value;
  80. }
  81. // ---------------------------------------------------------------------
  82. void expectedCurrent(double expected) override {
  83. _hlw8012->expectedCurrent(expected);
  84. }
  85. void expectedVoltage(unsigned int expected) override {
  86. _hlw8012->expectedVoltage(expected);
  87. }
  88. void expectedPower(unsigned int expected) override {
  89. _hlw8012->expectedActivePower(expected);
  90. }
  91. double defaultCurrentRatio() const override {
  92. return _hlw8012_default_current_multiplier();
  93. }
  94. double defaultVoltageRatio() const override {
  95. return _hlw8012_default_voltage_multiplier();
  96. }
  97. double defaultPowerRatio() const override {
  98. return _hlw8012_default_power_multiplier();
  99. }
  100. void resetRatios() override {
  101. _defaultRatios();
  102. }
  103. void setCurrentRatio(double value) override {
  104. if (value > 0.0) {
  105. _hlw8012->setCurrentMultiplier(value);
  106. }
  107. }
  108. void setVoltageRatio(double value) override {
  109. if (value > 0.0) {
  110. _hlw8012->setVoltageMultiplier(value);
  111. }
  112. }
  113. void setPowerRatio(double value) override {
  114. if (value > 0.0) {
  115. _hlw8012->setPowerMultiplier(value);
  116. }
  117. }
  118. double getCurrentRatio() override {
  119. return _hlw8012->getCurrentMultiplier();
  120. }
  121. double getVoltageRatio() override {
  122. return _hlw8012->getVoltageMultiplier();
  123. }
  124. double getPowerRatio() override {
  125. return _hlw8012->getPowerMultiplier();
  126. }
  127. // ---------------------------------------------------------------------
  128. unsigned char getSEL() {
  129. return _sel;
  130. }
  131. unsigned char getCF() {
  132. return _cf;
  133. }
  134. unsigned char getCF1() {
  135. return _cf1;
  136. }
  137. unsigned char getSELCurrent() {
  138. return _sel_current;
  139. }
  140. // ---------------------------------------------------------------------
  141. // Sensors API
  142. // ---------------------------------------------------------------------
  143. // Initialization method, must be idempotent
  144. // Defined outside the class body
  145. void begin() {
  146. // Initialize HLW8012
  147. // 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);
  148. // * cf_pin, cf1_pin and sel_pin are GPIOs to the HLW8012 IC
  149. // * currentWhen is the value in sel_pin to select current sampling
  150. // * set use_interrupts to true to use interrupts to monitor pulse widths
  151. // * leave pulse_timeout to the default value, recommended when using interrupts
  152. #if HLW8012_USE_INTERRUPTS
  153. _hlw8012->begin(_cf, _cf1, _sel, _sel_current, true);
  154. #else
  155. _hlw8012->begin(_cf, _cf1, _sel, _sel_current, false, 1000000);
  156. #endif
  157. // Note that HLW8012 does not initialize the multipliers (aka ratios) after begin(),
  158. // we need to manually set those based on either resistor values or RATIO flags
  159. // (see the defaults block at the top)
  160. _defaultRatios();
  161. // While we expect begin() to be called only once, try to detach before attaching again
  162. // (might be no-op on esp8266, since attachInterrupt will replace the existing func)
  163. #if HLW8012_USE_INTERRUPTS && (!HLW8012_WAIT_FOR_WIFI)
  164. _enableInterrupts(false);
  165. _enableInterrupts(true);
  166. #endif
  167. _ready = true;
  168. }
  169. // Descriptive name of the sensor
  170. String description() {
  171. char buffer[28];
  172. snprintf(buffer, sizeof(buffer), "HLW8012 @ GPIO(%u,%u,%u)", _sel, _cf, _cf1);
  173. return String(buffer);
  174. }
  175. // Descriptive name of the slot # index
  176. String description(unsigned char index) {
  177. return description();
  178. }
  179. // Address of the sensor (it could be the GPIO or I2C address)
  180. String address(unsigned char index) {
  181. char buffer[12];
  182. snprintf(buffer, sizeof(buffer), "%u:%u:%u", _sel, _cf, _cf1);
  183. return String(buffer);
  184. }
  185. // Type for slot # index
  186. unsigned char type(unsigned char index) {
  187. if (index == 0) return MAGNITUDE_CURRENT;
  188. if (index == 1) return MAGNITUDE_VOLTAGE;
  189. if (index == 2) return MAGNITUDE_POWER_ACTIVE;
  190. if (index == 3) return MAGNITUDE_POWER_REACTIVE;
  191. if (index == 4) return MAGNITUDE_POWER_APPARENT;
  192. if (index == 5) return MAGNITUDE_POWER_FACTOR;
  193. if (index == 6) return MAGNITUDE_ENERGY_DELTA;
  194. if (index == 7) return MAGNITUDE_ENERGY;
  195. return MAGNITUDE_NONE;
  196. }
  197. double getEnergyDelta() {
  198. return _energy_last;
  199. }
  200. // Current value for slot # index
  201. double value(unsigned char index) {
  202. if (index == 0) return _hlw8012->getCurrent();
  203. if (index == 1) return _hlw8012->getVoltage();
  204. if (index == 2) return _hlw8012->getActivePower();
  205. if (index == 3) return _hlw8012->getReactivePower();
  206. if (index == 4) return _hlw8012->getApparentPower();
  207. if (index == 5) return 100 * _hlw8012->getPowerFactor();
  208. if (index == 6) return getEnergyDelta();
  209. if (index == 7) return getEnergy();
  210. return 0.0;
  211. }
  212. // Pre-read hook (usually to populate registers with up-to-date data)
  213. void pre() {
  214. #if HLW8012_USE_INTERRUPTS && HLW8012_WAIT_FOR_WIFI
  215. _enableInterrupts(wifiConnected());
  216. #endif
  217. _energy_last = _hlw8012->getEnergy();
  218. _energy[0] += sensor::Ws { _energy_last };
  219. _hlw8012->resetEnergy();
  220. }
  221. #if !HLW8012_USE_INTERRUPTS
  222. // Toggle between current and voltage monitoring after reading
  223. void post() {
  224. _hlw8012->toggleMode();
  225. }
  226. #endif // HLW8012_USE_INTERRUPTS == 0
  227. // Handle interrupt calls
  228. void ICACHE_RAM_ATTR handleInterrupt(unsigned char gpio) {
  229. if (gpio == _cf) _hlw8012->cf_interrupt();
  230. if (gpio == _cf1) _hlw8012->cf1_interrupt();
  231. }
  232. protected:
  233. void _defaultRatios() {
  234. _hlw8012->setCurrentMultiplier(defaultCurrentRatio());
  235. _hlw8012->setVoltageMultiplier(defaultVoltageRatio());
  236. _hlw8012->setPowerMultiplier(defaultPowerRatio());
  237. }
  238. // ---------------------------------------------------------------------
  239. // Interrupt management
  240. // ---------------------------------------------------------------------
  241. void _attach(HLW8012Sensor * instance, unsigned char gpio, unsigned char mode);
  242. void _detach(unsigned char gpio);
  243. void _enableInterrupts(bool value) {
  244. static unsigned char _interrupt_cf = GPIO_NONE;
  245. static unsigned char _interrupt_cf1 = GPIO_NONE;
  246. if (value) {
  247. if (_interrupt_cf != _cf) {
  248. if (_interrupt_cf != GPIO_NONE) _detach(_interrupt_cf);
  249. _attach(this, _cf, HLW8012_INTERRUPT_ON);
  250. _interrupt_cf = _cf;
  251. }
  252. if (_interrupt_cf1 != _cf1) {
  253. if (_interrupt_cf1 != GPIO_NONE) _detach(_interrupt_cf1);
  254. _attach(this, _cf1, HLW8012_INTERRUPT_ON);
  255. _interrupt_cf1 = _cf1;
  256. }
  257. } else {
  258. if (GPIO_NONE != _interrupt_cf) {
  259. _detach(_interrupt_cf);
  260. _interrupt_cf = GPIO_NONE;
  261. }
  262. if (GPIO_NONE != _interrupt_cf1) {
  263. _detach(_interrupt_cf1);
  264. _interrupt_cf1 = GPIO_NONE;
  265. }
  266. }
  267. }
  268. // ---------------------------------------------------------------------
  269. double _initialRatioC;
  270. double _initialRatioV;
  271. double _initialRatioP;
  272. unsigned char _sel = GPIO_NONE;
  273. unsigned char _cf = GPIO_NONE;
  274. unsigned char _cf1 = GPIO_NONE;
  275. bool _sel_current = true;
  276. uint32_t _energy_last = 0;
  277. HLW8012 * _hlw8012 = NULL;
  278. };
  279. // -----------------------------------------------------------------------------
  280. // Interrupt helpers
  281. // -----------------------------------------------------------------------------
  282. HLW8012Sensor * _hlw8012_sensor_instance[10] = {NULL};
  283. void ICACHE_RAM_ATTR _hlw8012_sensor_isr(unsigned char gpio) {
  284. unsigned char index = gpio > 5 ? gpio-6 : gpio;
  285. if (_hlw8012_sensor_instance[index]) {
  286. _hlw8012_sensor_instance[index]->handleInterrupt(gpio);
  287. }
  288. }
  289. void ICACHE_RAM_ATTR _hlw8012_sensor_isr_0() { _hlw8012_sensor_isr(0); }
  290. void ICACHE_RAM_ATTR _hlw8012_sensor_isr_1() { _hlw8012_sensor_isr(1); }
  291. void ICACHE_RAM_ATTR _hlw8012_sensor_isr_2() { _hlw8012_sensor_isr(2); }
  292. void ICACHE_RAM_ATTR _hlw8012_sensor_isr_3() { _hlw8012_sensor_isr(3); }
  293. void ICACHE_RAM_ATTR _hlw8012_sensor_isr_4() { _hlw8012_sensor_isr(4); }
  294. void ICACHE_RAM_ATTR _hlw8012_sensor_isr_5() { _hlw8012_sensor_isr(5); }
  295. void ICACHE_RAM_ATTR _hlw8012_sensor_isr_12() { _hlw8012_sensor_isr(12); }
  296. void ICACHE_RAM_ATTR _hlw8012_sensor_isr_13() { _hlw8012_sensor_isr(13); }
  297. void ICACHE_RAM_ATTR _hlw8012_sensor_isr_14() { _hlw8012_sensor_isr(14); }
  298. void ICACHE_RAM_ATTR _hlw8012_sensor_isr_15() { _hlw8012_sensor_isr(15); }
  299. static void (*_hlw8012_sensor_isr_list[10])() = {
  300. _hlw8012_sensor_isr_0, _hlw8012_sensor_isr_1, _hlw8012_sensor_isr_2,
  301. _hlw8012_sensor_isr_3, _hlw8012_sensor_isr_4, _hlw8012_sensor_isr_5,
  302. _hlw8012_sensor_isr_12, _hlw8012_sensor_isr_13, _hlw8012_sensor_isr_14,
  303. _hlw8012_sensor_isr_15
  304. };
  305. void HLW8012Sensor::_attach(HLW8012Sensor * instance, unsigned char gpio, unsigned char mode) {
  306. if (!gpioValid(gpio)) return;
  307. _detach(gpio);
  308. unsigned char index = gpio > 5 ? gpio-6 : gpio;
  309. _hlw8012_sensor_instance[index] = instance;
  310. attachInterrupt(gpio, _hlw8012_sensor_isr_list[index], mode);
  311. #if SENSOR_DEBUG
  312. DEBUG_MSG_P(PSTR("[SENSOR] GPIO%u interrupt attached to %s\n"), gpio, instance->description().c_str());
  313. #endif
  314. }
  315. void HLW8012Sensor::_detach(unsigned char gpio) {
  316. if (!gpioValid(gpio)) return;
  317. unsigned char index = gpio > 5 ? gpio-6 : gpio;
  318. if (_hlw8012_sensor_instance[index]) {
  319. detachInterrupt(gpio);
  320. #if SENSOR_DEBUG
  321. DEBUG_MSG_P(PSTR("[SENSOR] GPIO%u interrupt detached from %s\n"), gpio, _hlw8012_sensor_instance[index]->description().c_str());
  322. #endif
  323. _hlw8012_sensor_instance[index] = NULL;
  324. }
  325. }
  326. #endif // SENSOR_SUPPORT && HLW8012_SUPPORT