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.

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