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.

1867 lines
61 KiB

6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. /*
  2. SENSOR MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if SENSOR_SUPPORT
  6. #include <vector>
  7. #include "filters/LastFilter.h"
  8. #include "filters/MaxFilter.h"
  9. #include "filters/MedianFilter.h"
  10. #include "filters/MovingAverageFilter.h"
  11. #include "sensors/BaseSensor.h"
  12. #include <float.h>
  13. struct sensor_magnitude_t {
  14. BaseSensor * sensor; // Sensor object
  15. BaseFilter * filter; // Filter object
  16. unsigned char local; // Local index in its provider
  17. unsigned char type; // Type of measurement
  18. unsigned char decimals; // Number of decimals in textual representation
  19. unsigned char global; // Global index in its type
  20. double last; // Last raw value from sensor (unfiltered)
  21. double reported; // Last reported value
  22. double min_change; // Minimum value change to report
  23. double max_change; // Maximum value change to report
  24. };
  25. std::vector<BaseSensor *> _sensors;
  26. std::vector<sensor_magnitude_t> _magnitudes;
  27. bool _sensors_ready = false;
  28. unsigned char _counts[MAGNITUDE_MAX];
  29. bool _sensor_realtime = API_REAL_TIME_VALUES;
  30. unsigned long _sensor_read_interval = 1000 * SENSOR_READ_INTERVAL;
  31. unsigned char _sensor_report_every = SENSOR_REPORT_EVERY;
  32. unsigned char _sensor_save_every = SENSOR_SAVE_EVERY;
  33. unsigned char _sensor_power_units = SENSOR_POWER_UNITS;
  34. unsigned char _sensor_energy_units = SENSOR_ENERGY_UNITS;
  35. unsigned char _sensor_temperature_units = SENSOR_TEMPERATURE_UNITS;
  36. double _sensor_temperature_correction = SENSOR_TEMPERATURE_CORRECTION;
  37. double _sensor_humidity_correction = SENSOR_HUMIDITY_CORRECTION;
  38. double _sensor_lux_correction = SENSOR_LUX_CORRECTION;
  39. #if PZEM004T_SUPPORT
  40. PZEM004TSensor *pzem004t_sensor;
  41. #endif
  42. String _sensor_energy_reset_ts = String();
  43. // -----------------------------------------------------------------------------
  44. // Private
  45. // -----------------------------------------------------------------------------
  46. unsigned char _magnitudeDecimals(unsigned char type) {
  47. // Hardcoded decimals (these should be linked to the unit, instead of the magnitude)
  48. if (type == MAGNITUDE_ANALOG) return ANALOG_DECIMALS;
  49. if (type == MAGNITUDE_ENERGY ||
  50. type == MAGNITUDE_ENERGY_DELTA) {
  51. _sensor_energy_units = getSetting("eneUnits", SENSOR_ENERGY_UNITS).toInt();
  52. if (_sensor_energy_units == ENERGY_KWH) return 3;
  53. }
  54. if (type == MAGNITUDE_POWER_ACTIVE ||
  55. type == MAGNITUDE_POWER_APPARENT ||
  56. type == MAGNITUDE_POWER_REACTIVE) {
  57. if (_sensor_power_units == POWER_KILOWATTS) return 3;
  58. }
  59. if (type < MAGNITUDE_MAX) return pgm_read_byte(magnitude_decimals + type);
  60. return 0;
  61. }
  62. double _magnitudeProcess(unsigned char type, unsigned char decimals, double value) {
  63. // Hardcoded conversions (these should be linked to the unit, instead of the magnitude)
  64. if (type == MAGNITUDE_TEMPERATURE) {
  65. if (_sensor_temperature_units == TMP_FAHRENHEIT) value = value * 1.8 + 32;
  66. value = value + _sensor_temperature_correction;
  67. }
  68. if (type == MAGNITUDE_HUMIDITY) {
  69. value = constrain(value + _sensor_humidity_correction, 0, 100);
  70. }
  71. if (type == MAGNITUDE_LUX) {
  72. value = value + _sensor_lux_correction;
  73. }
  74. if (type == MAGNITUDE_ENERGY ||
  75. type == MAGNITUDE_ENERGY_DELTA) {
  76. if (_sensor_energy_units == ENERGY_KWH) value = value / 3600000;
  77. }
  78. if (type == MAGNITUDE_POWER_ACTIVE ||
  79. type == MAGNITUDE_POWER_APPARENT ||
  80. type == MAGNITUDE_POWER_REACTIVE) {
  81. if (_sensor_power_units == POWER_KILOWATTS) value = value / 1000;
  82. }
  83. return roundTo(value, decimals);
  84. }
  85. // -----------------------------------------------------------------------------
  86. #if WEB_SUPPORT
  87. //void _sensorWebSocketMagnitudes(JsonObject& root, const String& ws_name, const String& conf_name) {
  88. template<typename T> void _sensorWebSocketMagnitudes(JsonObject& root, T prefix) {
  89. // ws produces flat list <prefix>Magnitudes
  90. const String ws_name = String(prefix) + "Magnitudes";
  91. // config uses <prefix>Magnitude<index> (cut 's')
  92. const String conf_name = ws_name.substring(0, ws_name.length() - 1);
  93. JsonObject& list = root.createNestedObject(ws_name);
  94. list["size"] = magnitudeCount();
  95. //JsonArray& name = list.createNestedArray("name");
  96. JsonArray& type = list.createNestedArray("type");
  97. JsonArray& index = list.createNestedArray("index");
  98. JsonArray& idx = list.createNestedArray("idx");
  99. for (unsigned char i=0; i<magnitudeCount(); ++i) {
  100. //name.add(magnitudeName(i));
  101. type.add(magnitudeType(i));
  102. index.add(magnitudeIndex(i));
  103. idx.add(getSetting(conf_name, i, 0).toInt());
  104. }
  105. }
  106. /*
  107. template<typename T> void _sensorWebSocketMagnitudes(JsonObject& root, T prefix) {
  108. // ws produces flat list <prefix>Magnitudes
  109. const String ws_name = String(prefix) + "Magnitudes";
  110. // config uses <prefix>Magnitude<index> (cut 's')
  111. const String conf_name = ws_name.substring(0, ws_name.length() - 1);
  112. _sensorWebSocketMagnitudes(root, ws_name, conf_name);
  113. }
  114. */
  115. bool _sensorWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  116. if (strncmp(key, "pwr", 3) == 0) return true;
  117. if (strncmp(key, "sns", 3) == 0) return true;
  118. if (strncmp(key, "tmp", 3) == 0) return true;
  119. if (strncmp(key, "hum", 3) == 0) return true;
  120. if (strncmp(key, "ene", 3) == 0) return true;
  121. if (strncmp(key, "lux", 3) == 0) return true;
  122. return false;
  123. }
  124. void _sensorWebSocketOnVisible(JsonObject& root) {
  125. root["snsVisible"] = 1;
  126. for (auto& magnitude : _magnitudes) {
  127. if (magnitude.type == MAGNITUDE_TEMPERATURE) root["temperatureVisible"] = 1;
  128. if (magnitude.type == MAGNITUDE_HUMIDITY) root["humidityVisible"] = 1;
  129. #if MICS2710_SUPPORT || MICS5525_SUPPORT
  130. if (magnitude.type == MAGNITUDE_CO || magnitude.type == MAGNITUDE_NO2) root["micsVisible"] = 1;
  131. #endif
  132. }
  133. }
  134. void _sensorWebSocketMagnitudesConfig(JsonObject& root) {
  135. JsonObject& magnitudes = root.createNestedObject("magnitudesConfig");
  136. uint8_t size = 0;
  137. JsonArray& index = magnitudes.createNestedArray("index");
  138. JsonArray& type = magnitudes.createNestedArray("type");
  139. JsonArray& units = magnitudes.createNestedArray("units");
  140. JsonArray& description = magnitudes.createNestedArray("description");
  141. for (unsigned char i=0; i<magnitudeCount(); i++) {
  142. sensor_magnitude_t magnitude = _magnitudes[i];
  143. if (magnitude.type == MAGNITUDE_EVENT) continue;
  144. ++size;
  145. index.add<uint8_t>(magnitude.global);
  146. type.add<uint8_t>(magnitude.type);
  147. units.add(magnitudeUnits(magnitude.type));
  148. if (magnitude.type == MAGNITUDE_ENERGY) {
  149. if (_sensor_energy_reset_ts.length() == 0) _sensorResetTS();
  150. description.add(magnitude.sensor->slot(magnitude.local) + String(" (since ") + _sensor_energy_reset_ts + String(")"));
  151. } else {
  152. description.add(magnitude.sensor->slot(magnitude.local));
  153. }
  154. }
  155. magnitudes["size"] = size;
  156. }
  157. void _sensorWebSocketSendData(JsonObject& root) {
  158. char buffer[64];
  159. JsonObject& magnitudes = root.createNestedObject("magnitudes");
  160. uint8_t size = 0;
  161. JsonArray& value = magnitudes.createNestedArray("value");
  162. JsonArray& error = magnitudes.createNestedArray("error");
  163. for (unsigned char i=0; i<magnitudeCount(); i++) {
  164. sensor_magnitude_t magnitude = _magnitudes[i];
  165. if (magnitude.type == MAGNITUDE_EVENT) continue;
  166. ++size;
  167. double value_show = _magnitudeProcess(magnitude.type, magnitude.decimals, magnitude.last);
  168. dtostrf(value_show, 1, magnitude.decimals, buffer);
  169. value.add(buffer);
  170. error.add(magnitude.sensor->error());
  171. }
  172. magnitudes["size"] = size;
  173. }
  174. void _sensorWebSocketOnConnected(JsonObject& root) {
  175. for (unsigned char i=0; i<_sensors.size(); i++) {
  176. BaseSensor * sensor = _sensors[i];
  177. UNUSED(sensor);
  178. #if EMON_ANALOG_SUPPORT
  179. if (sensor->getID() == SENSOR_EMON_ANALOG_ID) {
  180. root["emonVisible"] = 1;
  181. root["pwrVisible"] = 1;
  182. root["pwrVoltage"] = ((EmonAnalogSensor *) sensor)->getVoltage();
  183. }
  184. #endif
  185. #if HLW8012_SUPPORT
  186. if (sensor->getID() == SENSOR_HLW8012_ID) {
  187. root["hlwVisible"] = 1;
  188. root["pwrVisible"] = 1;
  189. }
  190. #endif
  191. #if CSE7766_SUPPORT
  192. if (sensor->getID() == SENSOR_CSE7766_ID) {
  193. root["cseVisible"] = 1;
  194. root["pwrVisible"] = 1;
  195. }
  196. #endif
  197. #if V9261F_SUPPORT
  198. if (sensor->getID() == SENSOR_V9261F_ID) {
  199. root["pwrVisible"] = 1;
  200. }
  201. #endif
  202. #if ECH1560_SUPPORT
  203. if (sensor->getID() == SENSOR_ECH1560_ID) {
  204. root["pwrVisible"] = 1;
  205. }
  206. #endif
  207. #if PZEM004T_SUPPORT
  208. if (sensor->getID() == SENSOR_PZEM004T_ID) {
  209. root["pzemVisible"] = 1;
  210. root["pwrVisible"] = 1;
  211. }
  212. #endif
  213. #if PULSEMETER_SUPPORT
  214. if (sensor->getID() == SENSOR_PULSEMETER_ID) {
  215. root["pmVisible"] = 1;
  216. root["pwrRatioE"] = ((PulseMeterSensor *) sensor)->getEnergyRatio();
  217. }
  218. #endif
  219. }
  220. if (magnitudeCount()) {
  221. //root["apiRealTime"] = _sensor_realtime;
  222. root["pwrUnits"] = _sensor_power_units;
  223. root["eneUnits"] = _sensor_energy_units;
  224. root["tmpUnits"] = _sensor_temperature_units;
  225. root["tmpCorrection"] = _sensor_temperature_correction;
  226. root["humCorrection"] = _sensor_humidity_correction;
  227. root["snsRead"] = _sensor_read_interval / 1000;
  228. root["snsReport"] = _sensor_report_every;
  229. root["snsSave"] = _sensor_save_every;
  230. _sensorWebSocketMagnitudesConfig(root);
  231. }
  232. /*
  233. // Sensors manifest
  234. JsonArray& manifest = root.createNestedArray("manifest");
  235. #if BMX280_SUPPORT
  236. BMX280Sensor::manifest(manifest);
  237. #endif
  238. // Sensors configuration
  239. JsonArray& sensors = root.createNestedArray("sensors");
  240. for (unsigned char i; i<_sensors.size(); i++) {
  241. JsonObject& sensor = sensors.createNestedObject();
  242. sensor["index"] = i;
  243. sensor["id"] = _sensors[i]->getID();
  244. _sensors[i]->getConfig(sensor);
  245. }
  246. */
  247. }
  248. #endif // WEB_SUPPORT
  249. #if API_SUPPORT
  250. void _sensorAPISetup() {
  251. for (unsigned char magnitude_id=0; magnitude_id<_magnitudes.size(); magnitude_id++) {
  252. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  253. String topic = magnitudeTopic(magnitude.type);
  254. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) topic = topic + "/" + String(magnitude.global);
  255. apiRegister(topic.c_str(), [magnitude_id](char * buffer, size_t len) {
  256. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  257. double value = _sensor_realtime ? magnitude.last : magnitude.reported;
  258. dtostrf(value, 1, magnitude.decimals, buffer);
  259. });
  260. }
  261. }
  262. #endif // API_SUPPORT
  263. #if TERMINAL_SUPPORT
  264. void _sensorInitCommands() {
  265. terminalRegisterCommand(F("MAGNITUDES"), [](Embedis* e) {
  266. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  267. sensor_magnitude_t magnitude = _magnitudes[i];
  268. DEBUG_MSG_P(PSTR("[SENSOR] * %2d: %s @ %s (%s/%d)\n"),
  269. i,
  270. magnitudeTopic(magnitude.type).c_str(),
  271. magnitude.sensor->slot(magnitude.local).c_str(),
  272. magnitudeTopic(magnitude.type).c_str(),
  273. magnitude.global
  274. );
  275. }
  276. terminalOK();
  277. });
  278. #if PZEM004T_SUPPORT
  279. terminalRegisterCommand(F("PZ.ADDRESS"), [](Embedis* e) {
  280. if (e->argc == 1) {
  281. DEBUG_MSG_P(PSTR("[SENSOR] PZEM004T\n"));
  282. unsigned char dev_count = pzem004t_sensor->getAddressesCount();
  283. for(unsigned char dev = 0; dev < dev_count; dev++) {
  284. DEBUG_MSG_P(PSTR("Device %d/%s\n"), dev, pzem004t_sensor->getAddress(dev).c_str());
  285. }
  286. terminalOK();
  287. } else if(e->argc == 2) {
  288. IPAddress addr;
  289. if (addr.fromString(String(e->argv[1]))) {
  290. if(pzem004t_sensor->setDeviceAddress(&addr)) {
  291. terminalOK();
  292. }
  293. } else {
  294. terminalError(F("Invalid address argument"));
  295. }
  296. } else {
  297. terminalError(F("Wrong arguments"));
  298. }
  299. });
  300. terminalRegisterCommand(F("PZ.RESET"), [](Embedis* e) {
  301. if(e->argc > 2) {
  302. terminalError(F("Wrong arguments"));
  303. } else {
  304. unsigned char init = e->argc == 2 ? String(e->argv[1]).toInt() : 0;
  305. unsigned char limit = e->argc == 2 ? init +1 : pzem004t_sensor->getAddressesCount();
  306. DEBUG_MSG_P(PSTR("[SENSOR] PZEM004T\n"));
  307. for(unsigned char dev = init; dev < limit; dev++) {
  308. float offset = pzem004t_sensor->resetEnergy(dev);
  309. _sensorEnergyTotal(dev, offset);
  310. DEBUG_MSG_P(PSTR("Device %d/%s - Offset: %s\n"), dev, pzem004t_sensor->getAddress(dev).c_str(), String(offset).c_str());
  311. }
  312. terminalOK();
  313. }
  314. });
  315. terminalRegisterCommand(F("PZ.VALUE"), [](Embedis* e) {
  316. if(e->argc > 2) {
  317. terminalError(F("Wrong arguments"));
  318. } else {
  319. unsigned char init = e->argc == 2 ? String(e->argv[1]).toInt() : 0;
  320. unsigned char limit = e->argc == 2 ? init +1 : pzem004t_sensor->getAddressesCount();
  321. DEBUG_MSG_P(PSTR("[SENSOR] PZEM004T\n"));
  322. for(unsigned char dev = init; dev < limit; dev++) {
  323. DEBUG_MSG_P(PSTR("Device %d/%s - Current: %s Voltage: %s Power: %s Energy: %s\n"), //
  324. dev,
  325. pzem004t_sensor->getAddress(dev).c_str(),
  326. String(pzem004t_sensor->value(dev * PZ_MAGNITUDE_CURRENT_INDEX)).c_str(),
  327. String(pzem004t_sensor->value(dev * PZ_MAGNITUDE_VOLTAGE_INDEX)).c_str(),
  328. String(pzem004t_sensor->value(dev * PZ_MAGNITUDE_POWER_ACTIVE_INDEX)).c_str(),
  329. String(pzem004t_sensor->value(dev * PZ_MAGNITUDE_ENERGY_INDEX)).c_str());
  330. }
  331. terminalOK();
  332. }
  333. });
  334. #endif
  335. }
  336. #endif
  337. void _sensorTick() {
  338. for (unsigned char i=0; i<_sensors.size(); i++) {
  339. _sensors[i]->tick();
  340. }
  341. }
  342. void _sensorPre() {
  343. for (unsigned char i=0; i<_sensors.size(); i++) {
  344. _sensors[i]->pre();
  345. if (!_sensors[i]->status()) {
  346. DEBUG_MSG_P(PSTR("[SENSOR] Error reading data from %s (error: %d)\n"),
  347. _sensors[i]->description().c_str(),
  348. _sensors[i]->error()
  349. );
  350. }
  351. }
  352. }
  353. void _sensorPost() {
  354. for (unsigned char i=0; i<_sensors.size(); i++) {
  355. _sensors[i]->post();
  356. }
  357. }
  358. void _sensorResetTS() {
  359. #if NTP_SUPPORT
  360. if (ntpSynced()) {
  361. if (_sensor_energy_reset_ts.length() == 0) {
  362. _sensor_energy_reset_ts = ntpDateTime(now() - millis() / 1000);
  363. } else {
  364. _sensor_energy_reset_ts = ntpDateTime(now());
  365. }
  366. } else {
  367. _sensor_energy_reset_ts = String();
  368. }
  369. setSetting("snsResetTS", _sensor_energy_reset_ts);
  370. #endif
  371. }
  372. double _sensorEnergyTotal(unsigned int index) {
  373. double value = 0;
  374. if (rtcmemStatus() && (index < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy)))) {
  375. value = Rtcmem->energy[index];
  376. } else {
  377. value = (_sensor_save_every > 0) ? getSetting("eneTotal", index, 0).toInt() : 0;
  378. }
  379. return value;
  380. }
  381. double _sensorEnergyTotal() {
  382. return _sensorEnergyTotal(0);
  383. }
  384. void _sensorEnergyTotal(unsigned int index, double value) {
  385. static unsigned long save_count = 0;
  386. // Save to EEPROM every '_sensor_save_every' readings
  387. if (_sensor_save_every > 0) {
  388. save_count = (save_count + 1) % _sensor_save_every;
  389. if (0 == save_count) {
  390. setSetting("eneTotal", index, value);
  391. saveSettings();
  392. }
  393. }
  394. // Always save to RTCMEM
  395. if (index < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy))) {
  396. Rtcmem->energy[index] = value;
  397. }
  398. }
  399. // -----------------------------------------------------------------------------
  400. // Sensor initialization
  401. // -----------------------------------------------------------------------------
  402. void _sensorLoad() {
  403. /*
  404. This is temporal, in the future sensors will be initialized based on
  405. soft configuration (data stored in EEPROM config) so you will be able
  406. to define and configure new sensors on the fly
  407. At the time being, only enabled sensors (those with *_SUPPORT to 1) are being
  408. loaded and initialized here. If you want to add new sensors of the same type
  409. just duplicate the block and change the arguments for the set* methods.
  410. Check the DHT block below for an example
  411. */
  412. #if AM2320_SUPPORT
  413. {
  414. AM2320Sensor * sensor = new AM2320Sensor();
  415. sensor->setAddress(AM2320_ADDRESS);
  416. _sensors.push_back(sensor);
  417. }
  418. #endif
  419. #if ANALOG_SUPPORT
  420. {
  421. AnalogSensor * sensor = new AnalogSensor();
  422. sensor->setSamples(ANALOG_SAMPLES);
  423. sensor->setDelay(ANALOG_DELAY);
  424. //CICM For analog scaling
  425. sensor->setFactor(ANALOG_FACTOR);
  426. sensor->setOffset(ANALOG_OFFSET);
  427. _sensors.push_back(sensor);
  428. }
  429. #endif
  430. #if BH1750_SUPPORT
  431. {
  432. BH1750Sensor * sensor = new BH1750Sensor();
  433. sensor->setAddress(BH1750_ADDRESS);
  434. sensor->setMode(BH1750_MODE);
  435. _sensors.push_back(sensor);
  436. }
  437. #endif
  438. #if BMP180_SUPPORT
  439. {
  440. BMP180Sensor * sensor = new BMP180Sensor();
  441. sensor->setAddress(BMP180_ADDRESS);
  442. _sensors.push_back(sensor);
  443. }
  444. #endif
  445. #if BMX280_SUPPORT
  446. {
  447. // Support up to two sensors with full auto-discovery.
  448. const unsigned char number = constrain(getSetting("bmx280Number", BMX280_NUMBER).toInt(), 1, 2);
  449. // For second sensor, if BMX280_ADDRESS is 0x00 then auto-discover
  450. // otherwise choose the other unnamed sensor address
  451. const unsigned char first = getSetting("bmx280Address", BMX280_ADDRESS).toInt();
  452. const unsigned char second = (first == 0x00) ? 0x00 : (0x76 + 0x77 - first);
  453. const unsigned char address_map[2] = { first, second };
  454. for (unsigned char n=0; n < number; ++n) {
  455. BMX280Sensor * sensor = new BMX280Sensor();
  456. sensor->setAddress(address_map[n]);
  457. _sensors.push_back(sensor);
  458. }
  459. }
  460. #endif
  461. #if CSE7766_SUPPORT
  462. {
  463. CSE7766Sensor * sensor = new CSE7766Sensor();
  464. sensor->setRX(CSE7766_PIN);
  465. _sensors.push_back(sensor);
  466. }
  467. #endif
  468. #if DALLAS_SUPPORT
  469. {
  470. DallasSensor * sensor = new DallasSensor();
  471. sensor->setGPIO(DALLAS_PIN);
  472. _sensors.push_back(sensor);
  473. }
  474. #endif
  475. #if DHT_SUPPORT
  476. {
  477. DHTSensor * sensor = new DHTSensor();
  478. sensor->setGPIO(DHT_PIN);
  479. sensor->setType(DHT_TYPE);
  480. _sensors.push_back(sensor);
  481. }
  482. #endif
  483. /*
  484. // Example on how to add a second DHT sensor
  485. // DHT2_PIN and DHT2_TYPE should be defined in sensors.h file
  486. #if DHT_SUPPORT
  487. {
  488. DHTSensor * sensor = new DHTSensor();
  489. sensor->setGPIO(DHT2_PIN);
  490. sensor->setType(DHT2_TYPE);
  491. _sensors.push_back(sensor);
  492. }
  493. #endif
  494. */
  495. #if DIGITAL_SUPPORT
  496. {
  497. #if (DIGITAL1_PIN != GPIO_NONE)
  498. {
  499. DigitalSensor * sensor = new DigitalSensor();
  500. sensor->setGPIO(DIGITAL1_PIN);
  501. sensor->setMode(DIGITAL1_PIN_MODE);
  502. sensor->setDefault(DIGITAL1_DEFAULT_STATE);
  503. _sensors.push_back(sensor);
  504. }
  505. #endif
  506. #if (DIGITAL2_PIN != GPIO_NONE)
  507. {
  508. DigitalSensor * sensor = new DigitalSensor();
  509. sensor->setGPIO(DIGITAL2_PIN);
  510. sensor->setMode(DIGITAL2_PIN_MODE);
  511. sensor->setDefault(DIGITAL2_DEFAULT_STATE);
  512. _sensors.push_back(sensor);
  513. }
  514. #endif
  515. #if (DIGITAL3_PIN != GPIO_NONE)
  516. {
  517. DigitalSensor * sensor = new DigitalSensor();
  518. sensor->setGPIO(DIGITAL3_PIN);
  519. sensor->setMode(DIGITAL3_PIN_MODE);
  520. sensor->setDefault(DIGITAL3_DEFAULT_STATE);
  521. _sensors.push_back(sensor);
  522. }
  523. #endif
  524. #if (DIGITAL4_PIN != GPIO_NONE)
  525. {
  526. DigitalSensor * sensor = new DigitalSensor();
  527. sensor->setGPIO(DIGITAL4_PIN);
  528. sensor->setMode(DIGITAL4_PIN_MODE);
  529. sensor->setDefault(DIGITAL4_DEFAULT_STATE);
  530. _sensors.push_back(sensor);
  531. }
  532. #endif
  533. #if (DIGITAL5_PIN != GPIO_NONE)
  534. {
  535. DigitalSensor * sensor = new DigitalSensor();
  536. sensor->setGPIO(DIGITAL5_PIN);
  537. sensor->setMode(DIGITAL5_PIN_MODE);
  538. sensor->setDefault(DIGITAL5_DEFAULT_STATE);
  539. _sensors.push_back(sensor);
  540. }
  541. #endif
  542. #if (DIGITAL6_PIN != GPIO_NONE)
  543. {
  544. DigitalSensor * sensor = new DigitalSensor();
  545. sensor->setGPIO(DIGITAL6_PIN);
  546. sensor->setMode(DIGITAL6_PIN_MODE);
  547. sensor->setDefault(DIGITAL6_DEFAULT_STATE);
  548. _sensors.push_back(sensor);
  549. }
  550. #endif
  551. #if (DIGITAL7_PIN != GPIO_NONE)
  552. {
  553. DigitalSensor * sensor = new DigitalSensor();
  554. sensor->setGPIO(DIGITAL7_PIN);
  555. sensor->setMode(DIGITAL7_PIN_MODE);
  556. sensor->setDefault(DIGITAL7_DEFAULT_STATE);
  557. _sensors.push_back(sensor);
  558. }
  559. #endif
  560. #if (DIGITAL8_PIN != GPIO_NONE)
  561. {
  562. DigitalSensor * sensor = new DigitalSensor();
  563. sensor->setGPIO(DIGITAL8_PIN);
  564. sensor->setMode(DIGITAL8_PIN_MODE);
  565. sensor->setDefault(DIGITAL8_DEFAULT_STATE);
  566. _sensors.push_back(sensor);
  567. }
  568. #endif
  569. }
  570. #endif
  571. #if ECH1560_SUPPORT
  572. {
  573. ECH1560Sensor * sensor = new ECH1560Sensor();
  574. sensor->setCLK(ECH1560_CLK_PIN);
  575. sensor->setMISO(ECH1560_MISO_PIN);
  576. sensor->setInverted(ECH1560_INVERTED);
  577. _sensors.push_back(sensor);
  578. }
  579. #endif
  580. #if EMON_ADC121_SUPPORT
  581. {
  582. EmonADC121Sensor * sensor = new EmonADC121Sensor();
  583. sensor->setAddress(EMON_ADC121_I2C_ADDRESS);
  584. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  585. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  586. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  587. _sensors.push_back(sensor);
  588. }
  589. #endif
  590. #if EMON_ADS1X15_SUPPORT
  591. {
  592. EmonADS1X15Sensor * sensor = new EmonADS1X15Sensor();
  593. sensor->setAddress(EMON_ADS1X15_I2C_ADDRESS);
  594. sensor->setType(EMON_ADS1X15_TYPE);
  595. sensor->setMask(EMON_ADS1X15_MASK);
  596. sensor->setGain(EMON_ADS1X15_GAIN);
  597. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  598. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  599. sensor->setCurrentRatio(1, EMON_CURRENT_RATIO);
  600. sensor->setCurrentRatio(2, EMON_CURRENT_RATIO);
  601. sensor->setCurrentRatio(3, EMON_CURRENT_RATIO);
  602. _sensors.push_back(sensor);
  603. }
  604. #endif
  605. #if EMON_ANALOG_SUPPORT
  606. {
  607. EmonAnalogSensor * sensor = new EmonAnalogSensor();
  608. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  609. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  610. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  611. _sensors.push_back(sensor);
  612. }
  613. #endif
  614. #if EVENTS_SUPPORT
  615. {
  616. #if (EVENTS1_PIN != GPIO_NONE)
  617. {
  618. EventSensor * sensor = new EventSensor();
  619. sensor->setGPIO(EVENTS1_PIN);
  620. sensor->setTrigger(EVENTS1_TRIGGER);
  621. sensor->setPinMode(EVENTS1_PIN_MODE);
  622. sensor->setDebounceTime(EVENTS1_DEBOUNCE);
  623. sensor->setInterruptMode(EVENTS1_INTERRUPT_MODE);
  624. _sensors.push_back(sensor);
  625. }
  626. #endif
  627. #if (EVENTS2_PIN != GPIO_NONE)
  628. {
  629. EventSensor * sensor = new EventSensor();
  630. sensor->setGPIO(EVENTS2_PIN);
  631. sensor->setTrigger(EVENTS2_TRIGGER);
  632. sensor->setPinMode(EVENTS2_PIN_MODE);
  633. sensor->setDebounceTime(EVENTS2_DEBOUNCE);
  634. sensor->setInterruptMode(EVENTS2_INTERRUPT_MODE);
  635. _sensors.push_back(sensor);
  636. }
  637. #endif
  638. #if (EVENTS3_PIN != GPIO_NONE)
  639. {
  640. EventSensor * sensor = new EventSensor();
  641. sensor->setGPIO(EVENTS3_PIN);
  642. sensor->setTrigger(EVENTS3_TRIGGER);
  643. sensor->setPinMode(EVENTS3_PIN_MODE);
  644. sensor->setDebounceTime(EVENTS3_DEBOUNCE);
  645. sensor->setInterruptMode(EVENTS3_INTERRUPT_MODE);
  646. _sensors.push_back(sensor);
  647. }
  648. #endif
  649. #if (EVENTS4_PIN != GPIO_NONE)
  650. {
  651. EventSensor * sensor = new EventSensor();
  652. sensor->setGPIO(EVENTS4_PIN);
  653. sensor->setTrigger(EVENTS4_TRIGGER);
  654. sensor->setPinMode(EVENTS4_PIN_MODE);
  655. sensor->setDebounceTime(EVENTS4_DEBOUNCE);
  656. sensor->setInterruptMode(EVENTS4_INTERRUPT_MODE);
  657. _sensors.push_back(sensor);
  658. }
  659. #endif
  660. #if (EVENTS5_PIN != GPIO_NONE)
  661. {
  662. EventSensor * sensor = new EventSensor();
  663. sensor->setGPIO(EVENTS5_PIN);
  664. sensor->setTrigger(EVENTS5_TRIGGER);
  665. sensor->setPinMode(EVENTS5_PIN_MODE);
  666. sensor->setDebounceTime(EVENTS5_DEBOUNCE);
  667. sensor->setInterruptMode(EVENTS5_INTERRUPT_MODE);
  668. _sensors.push_back(sensor);
  669. }
  670. #endif
  671. #if (EVENTS6_PIN != GPIO_NONE)
  672. {
  673. EventSensor * sensor = new EventSensor();
  674. sensor->setGPIO(EVENTS6_PIN);
  675. sensor->setTrigger(EVENTS6_TRIGGER);
  676. sensor->setPinMode(EVENTS6_PIN_MODE);
  677. sensor->setDebounceTime(EVENTS6_DEBOUNCE);
  678. sensor->setInterruptMode(EVENTS6_INTERRUPT_MODE);
  679. _sensors.push_back(sensor);
  680. }
  681. #endif
  682. #if (EVENTS7_PIN != GPIO_NONE)
  683. {
  684. EventSensor * sensor = new EventSensor();
  685. sensor->setGPIO(EVENTS7_PIN);
  686. sensor->setTrigger(EVENTS7_TRIGGER);
  687. sensor->setPinMode(EVENTS7_PIN_MODE);
  688. sensor->setDebounceTime(EVENTS7_DEBOUNCE);
  689. sensor->setInterruptMode(EVENTS7_INTERRUPT_MODE);
  690. _sensors.push_back(sensor);
  691. }
  692. #endif
  693. #if (EVENTS8_PIN != GPIO_NONE)
  694. {
  695. EventSensor * sensor = new EventSensor();
  696. sensor->setGPIO(EVENTS8_PIN);
  697. sensor->setTrigger(EVENTS8_TRIGGER);
  698. sensor->setPinMode(EVENTS8_PIN_MODE);
  699. sensor->setDebounceTime(EVENTS8_DEBOUNCE);
  700. sensor->setInterruptMode(EVENTS8_INTERRUPT_MODE);
  701. _sensors.push_back(sensor);
  702. }
  703. #endif
  704. }
  705. #endif
  706. #if GEIGER_SUPPORT
  707. {
  708. GeigerSensor * sensor = new GeigerSensor(); // Create instance of thr Geiger module.
  709. sensor->setGPIO(GEIGER_PIN); // Interrupt pin of the attached geiger counter board.
  710. sensor->setMode(GEIGER_PIN_MODE); // This pin is an input.
  711. sensor->setDebounceTime(GEIGER_DEBOUNCE); // Debounce time 25ms, because https://github.com/Trickx/espurna/wiki/Geiger-counter
  712. sensor->setInterruptMode(GEIGER_INTERRUPT_MODE); // Interrupt triggering: edge detection rising.
  713. sensor->setCPM2SievertFactor(GEIGER_CPM2SIEVERT); // Conversion factor from counts per minute to µSv/h
  714. _sensors.push_back(sensor);
  715. }
  716. #endif
  717. #if GUVAS12SD_SUPPORT
  718. {
  719. GUVAS12SDSensor * sensor = new GUVAS12SDSensor();
  720. sensor->setGPIO(GUVAS12SD_PIN);
  721. _sensors.push_back(sensor);
  722. }
  723. #endif
  724. #if SONAR_SUPPORT
  725. {
  726. SonarSensor * sensor = new SonarSensor();
  727. sensor->setEcho(SONAR_ECHO);
  728. sensor->setIterations(SONAR_ITERATIONS);
  729. sensor->setMaxDistance(SONAR_MAX_DISTANCE);
  730. sensor->setTrigger(SONAR_TRIGGER);
  731. _sensors.push_back(sensor);
  732. }
  733. #endif
  734. #if HLW8012_SUPPORT
  735. {
  736. HLW8012Sensor * sensor = new HLW8012Sensor();
  737. sensor->setSEL(HLW8012_SEL_PIN);
  738. sensor->setCF(HLW8012_CF_PIN);
  739. sensor->setCF1(HLW8012_CF1_PIN);
  740. sensor->setSELCurrent(HLW8012_SEL_CURRENT);
  741. _sensors.push_back(sensor);
  742. }
  743. #endif
  744. #if LDR_SUPPORT
  745. {
  746. LDRSensor * sensor = new LDRSensor();
  747. sensor->setSamples(LDR_SAMPLES);
  748. sensor->setDelay(LDR_DELAY);
  749. sensor->setType(LDR_TYPE);
  750. sensor->setPhotocellPositionOnGround(LDR_ON_GROUND);
  751. sensor->setResistor(LDR_RESISTOR);
  752. sensor->setPhotocellParameters(LDR_MULTIPLICATION, LDR_POWER);
  753. _sensors.push_back(sensor);
  754. }
  755. #endif
  756. #if MHZ19_SUPPORT
  757. {
  758. MHZ19Sensor * sensor = new MHZ19Sensor();
  759. sensor->setRX(MHZ19_RX_PIN);
  760. sensor->setTX(MHZ19_TX_PIN);
  761. if (getSetting("mhz19CalibrateAuto", 0).toInt() == 1)
  762. sensor->setCalibrateAuto(true);
  763. _sensors.push_back(sensor);
  764. }
  765. #endif
  766. #if MICS2710_SUPPORT
  767. {
  768. MICS2710Sensor * sensor = new MICS2710Sensor();
  769. sensor->setAnalogGPIO(MICS2710_NOX_PIN);
  770. sensor->setPreHeatGPIO(MICS2710_PRE_PIN);
  771. sensor->setRL(MICS2710_RL);
  772. _sensors.push_back(sensor);
  773. }
  774. #endif
  775. #if MICS5525_SUPPORT
  776. {
  777. MICS5525Sensor * sensor = new MICS5525Sensor();
  778. sensor->setAnalogGPIO(MICS5525_RED_PIN);
  779. sensor->setRL(MICS5525_RL);
  780. _sensors.push_back(sensor);
  781. }
  782. #endif
  783. #if NTC_SUPPORT
  784. {
  785. NTCSensor * sensor = new NTCSensor();
  786. sensor->setSamples(NTC_SAMPLES);
  787. sensor->setDelay(NTC_DELAY);
  788. sensor->setUpstreamResistor(NTC_R_UP);
  789. sensor->setDownstreamResistor(NTC_R_DOWN);
  790. sensor->setBeta(NTC_BETA);
  791. sensor->setR0(NTC_R0);
  792. sensor->setT0(NTC_T0);
  793. _sensors.push_back(sensor);
  794. }
  795. #endif
  796. #if PMSX003_SUPPORT
  797. {
  798. PMSX003Sensor * sensor = new PMSX003Sensor();
  799. #if PMS_USE_SOFT
  800. sensor->setRX(PMS_RX_PIN);
  801. sensor->setTX(PMS_TX_PIN);
  802. #else
  803. sensor->setSerial(& PMS_HW_PORT);
  804. #endif
  805. sensor->setType(PMS_TYPE);
  806. _sensors.push_back(sensor);
  807. }
  808. #endif
  809. #if PULSEMETER_SUPPORT
  810. {
  811. PulseMeterSensor * sensor = new PulseMeterSensor();
  812. sensor->setGPIO(PULSEMETER_PIN);
  813. sensor->setEnergyRatio(PULSEMETER_ENERGY_RATIO);
  814. sensor->setInterruptMode(PULSEMETER_INTERRUPT_ON);
  815. sensor->setDebounceTime(PULSEMETER_DEBOUNCE);
  816. _sensors.push_back(sensor);
  817. }
  818. #endif
  819. #if PZEM004T_SUPPORT
  820. {
  821. String addresses = getSetting("pzemAddr", PZEM004T_ADDRESSES);
  822. if (!addresses.length()) {
  823. DEBUG_MSG_P(PSTR("[SENSOR] PZEM004T Error: no addresses are configured\n"));
  824. return;
  825. }
  826. PZEM004TSensor * sensor = pzem004t_sensor = new PZEM004TSensor();
  827. sensor->setAddresses(addresses.c_str());
  828. if (getSetting("pzemSoft", PZEM004T_USE_SOFT).toInt() == 1) {
  829. sensor->setRX(getSetting("pzemRX", PZEM004T_RX_PIN).toInt());
  830. sensor->setTX(getSetting("pzemTX", PZEM004T_TX_PIN).toInt());
  831. } else {
  832. sensor->setSerial(& PZEM004T_HW_PORT);
  833. }
  834. // Read saved energy offset
  835. unsigned char dev_count = sensor->getAddressesCount();
  836. for(unsigned char dev = 0; dev < dev_count; dev++) {
  837. float value = _sensorEnergyTotal(dev);
  838. if (value > 0) sensor->resetEnergy(dev, value);
  839. }
  840. _sensors.push_back(sensor);
  841. }
  842. #endif
  843. #if SENSEAIR_SUPPORT
  844. {
  845. SenseAirSensor * sensor = new SenseAirSensor();
  846. sensor->setRX(SENSEAIR_RX_PIN);
  847. sensor->setTX(SENSEAIR_TX_PIN);
  848. _sensors.push_back(sensor);
  849. }
  850. #endif
  851. #if SDS011_SUPPORT
  852. {
  853. SDS011Sensor * sensor = new SDS011Sensor();
  854. sensor->setRX(SDS011_RX_PIN);
  855. sensor->setTX(SDS011_TX_PIN);
  856. _sensors.push_back(sensor);
  857. }
  858. #endif
  859. #if SHT3X_I2C_SUPPORT
  860. {
  861. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  862. sensor->setAddress(SHT3X_I2C_ADDRESS);
  863. _sensors.push_back(sensor);
  864. }
  865. #endif
  866. #if SI7021_SUPPORT
  867. {
  868. SI7021Sensor * sensor = new SI7021Sensor();
  869. sensor->setAddress(SI7021_ADDRESS);
  870. _sensors.push_back(sensor);
  871. }
  872. #endif
  873. #if T6613_SUPPORT
  874. {
  875. T6613Sensor * sensor = new T6613Sensor();
  876. sensor->setRX(T6613_RX_PIN);
  877. sensor->setTX(T6613_TX_PIN);
  878. _sensors.push_back(sensor);
  879. }
  880. #endif
  881. #if TMP3X_SUPPORT
  882. {
  883. TMP3XSensor * sensor = new TMP3XSensor();
  884. sensor->setType(TMP3X_TYPE);
  885. _sensors.push_back(sensor);
  886. }
  887. #endif
  888. #if V9261F_SUPPORT
  889. {
  890. V9261FSensor * sensor = new V9261FSensor();
  891. sensor->setRX(V9261F_PIN);
  892. sensor->setInverted(V9261F_PIN_INVERSE);
  893. _sensors.push_back(sensor);
  894. }
  895. #endif
  896. #if MAX6675_SUPPORT
  897. {
  898. MAX6675Sensor * sensor = new MAX6675Sensor();
  899. sensor->setCS(MAX6675_CS_PIN);
  900. sensor->setSO(MAX6675_SO_PIN);
  901. sensor->setSCK(MAX6675_SCK_PIN);
  902. _sensors.push_back(sensor);
  903. }
  904. #endif
  905. #if VEML6075_SUPPORT
  906. {
  907. VEML6075Sensor * sensor = new VEML6075Sensor();
  908. sensor->setIntegrationTime(VEML6075_INTEGRATION_TIME);
  909. sensor->setDynamicMode(VEML6075_DYNAMIC_MODE);
  910. _sensors.push_back(sensor);
  911. }
  912. #endif
  913. #if VL53L1X_SUPPORT
  914. {
  915. VL53L1XSensor * sensor = new VL53L1XSensor();
  916. sensor->setInterMeasurementPeriod(VL53L1X_INTER_MEASUREMENT_PERIOD);
  917. sensor->setDistanceMode(VL53L1X_DISTANCE_MODE);
  918. sensor->setMeasurementTimingBudget(VL53L1X_MEASUREMENT_TIMING_BUDGET);
  919. _sensors.push_back(sensor);
  920. }
  921. #endif
  922. #if EZOPH_SUPPORT
  923. {
  924. EZOPHSensor * sensor = new EZOPHSensor();
  925. sensor->setRX(EZOPH_RX_PIN);
  926. sensor->setTX(EZOPH_TX_PIN);
  927. _sensors.push_back(sensor);
  928. }
  929. #endif
  930. #if ADE7953_SUPPORT
  931. {
  932. ADE7953Sensor * sensor = new ADE7953Sensor();
  933. sensor->setAddress(ADE7953_ADDRESS);
  934. _sensors.push_back(sensor);
  935. }
  936. #endif
  937. }
  938. void _sensorCallback(unsigned char i, unsigned char type, double value) {
  939. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, String(value).c_str());
  940. for (unsigned char k=0; k<_magnitudes.size(); k++) {
  941. if ((_sensors[i] == _magnitudes[k].sensor) && (type == _magnitudes[k].type)) {
  942. _sensorReport(k, value);
  943. return;
  944. }
  945. }
  946. }
  947. void _sensorInit() {
  948. _sensors_ready = true;
  949. _sensor_save_every = getSetting("snsSave", 0).toInt();
  950. for (unsigned char i=0; i<_sensors.size(); i++) {
  951. // Do not process an already initialized sensor
  952. if (_sensors[i]->ready()) continue;
  953. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  954. // Force sensor to reload config
  955. _sensors[i]->begin();
  956. if (!_sensors[i]->ready()) {
  957. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  958. _sensors_ready = false;
  959. continue;
  960. }
  961. // Initialize magnitudes
  962. for (unsigned char k=0; k<_sensors[i]->count(); k++) {
  963. unsigned char type = _sensors[i]->type(k);
  964. signed char decimals = _sensors[i]->decimals(type);
  965. if (decimals < 0) decimals = _magnitudeDecimals(type);
  966. sensor_magnitude_t new_magnitude;
  967. new_magnitude.sensor = _sensors[i];
  968. new_magnitude.local = k;
  969. new_magnitude.type = type;
  970. new_magnitude.decimals = (unsigned char) decimals;
  971. new_magnitude.global = _counts[type];
  972. new_magnitude.last = 0;
  973. new_magnitude.reported = 0;
  974. new_magnitude.min_change = 0;
  975. new_magnitude.max_change = 0;
  976. // TODO: find a proper way to extend this to min/max of any magnitude
  977. if (MAGNITUDE_ENERGY == type) {
  978. new_magnitude.max_change = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE).toFloat();
  979. } else if (MAGNITUDE_TEMPERATURE == type) {
  980. new_magnitude.min_change = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE).toFloat();
  981. } else if (MAGNITUDE_HUMIDITY == type) {
  982. new_magnitude.min_change = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE).toFloat();
  983. }
  984. if (MAGNITUDE_ENERGY == type) {
  985. new_magnitude.filter = new LastFilter();
  986. } else if (MAGNITUDE_DIGITAL == type) {
  987. new_magnitude.filter = new MaxFilter();
  988. } else if (MAGNITUDE_COUNT == type || MAGNITUDE_GEIGER_CPM == type || MAGNITUDE_GEIGER_SIEVERT == type) { // For geiger counting moving average filter is the most appropriate if needed at all.
  989. new_magnitude.filter = new MovingAverageFilter();
  990. } else {
  991. new_magnitude.filter = new MedianFilter();
  992. }
  993. new_magnitude.filter->resize(_sensor_report_every);
  994. _magnitudes.push_back(new_magnitude);
  995. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  996. _counts[type] = _counts[type] + 1;
  997. }
  998. // Hook callback
  999. _sensors[i]->onEvent([i](unsigned char type, double value) {
  1000. _sensorCallback(i, type, value);
  1001. });
  1002. // Custom initializations
  1003. #if MICS2710_SUPPORT
  1004. if (_sensors[i]->getID() == SENSOR_MICS2710_ID) {
  1005. MICS2710Sensor * sensor = (MICS2710Sensor *) _sensors[i];
  1006. sensor->setR0(getSetting("snsR0", MICS2710_R0).toInt());
  1007. }
  1008. #endif // MICS2710_SUPPORT
  1009. #if MICS5525_SUPPORT
  1010. if (_sensors[i]->getID() == SENSOR_MICS5525_ID) {
  1011. MICS5525Sensor * sensor = (MICS5525Sensor *) _sensors[i];
  1012. sensor->setR0(getSetting("snsR0", MICS5525_R0).toInt());
  1013. }
  1014. #endif // MICS5525_SUPPORT
  1015. #if EMON_ANALOG_SUPPORT
  1016. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  1017. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  1018. sensor->setCurrentRatio(0, getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat());
  1019. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  1020. double value = _sensorEnergyTotal();
  1021. if (value > 0) sensor->resetEnergy(0, value);
  1022. }
  1023. #endif // EMON_ANALOG_SUPPORT
  1024. #if HLW8012_SUPPORT
  1025. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  1026. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  1027. double value;
  1028. value = getSetting("pwrRatioC", HLW8012_CURRENT_RATIO).toFloat();
  1029. if (value > 0) sensor->setCurrentRatio(value);
  1030. value = getSetting("pwrRatioV", HLW8012_VOLTAGE_RATIO).toFloat();
  1031. if (value > 0) sensor->setVoltageRatio(value);
  1032. value = getSetting("pwrRatioP", HLW8012_POWER_RATIO).toFloat();
  1033. if (value > 0) sensor->setPowerRatio(value);
  1034. value = _sensorEnergyTotal();
  1035. if (value > 0) sensor->resetEnergy(value);
  1036. }
  1037. #endif // HLW8012_SUPPORT
  1038. #if ADE7953_SUPPORT
  1039. if (_sensors[i]->getID() == SENSOR_ADE7953_ID) {
  1040. ADE7953Sensor * sensor = (ADE7953Sensor *) _sensors[i];
  1041. unsigned int dev_count = sensor->getTotalDevices();
  1042. for(unsigned char dev = 0; dev < dev_count; dev++) {
  1043. double value = _sensorEnergyTotal(dev);
  1044. if (value > 0) sensor->resetEnergy(dev, value);
  1045. }
  1046. }
  1047. #endif // ADE7953_SUPPORT
  1048. #if CSE7766_SUPPORT
  1049. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  1050. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  1051. double value;
  1052. value = getSetting("pwrRatioC", 0).toFloat();
  1053. if (value > 0) sensor->setCurrentRatio(value);
  1054. value = getSetting("pwrRatioV", 0).toFloat();
  1055. if (value > 0) sensor->setVoltageRatio(value);
  1056. value = getSetting("pwrRatioP", 0).toFloat();
  1057. if (value > 0) sensor->setPowerRatio(value);
  1058. value = _sensorEnergyTotal();
  1059. if (value > 0) sensor->resetEnergy(value);
  1060. }
  1061. #endif // CSE7766_SUPPORT
  1062. #if PULSEMETER_SUPPORT
  1063. if (_sensors[i]->getID() == SENSOR_PULSEMETER_ID) {
  1064. PulseMeterSensor * sensor = (PulseMeterSensor *) _sensors[i];
  1065. sensor->setEnergyRatio(getSetting("pwrRatioE", sensor->getEnergyRatio()).toInt());
  1066. }
  1067. #endif // PULSEMETER_SUPPORT
  1068. }
  1069. }
  1070. void _sensorConfigure() {
  1071. // General sensor settings
  1072. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  1073. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  1074. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY).toInt();
  1075. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  1076. _sensor_power_units = getSetting("pwrUnits", SENSOR_POWER_UNITS).toInt();
  1077. _sensor_energy_units = getSetting("eneUnits", SENSOR_ENERGY_UNITS).toInt();
  1078. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  1079. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  1080. _sensor_humidity_correction = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION).toFloat();
  1081. _sensor_energy_reset_ts = getSetting("snsResetTS", "");
  1082. _sensor_lux_correction = getSetting("luxCorrection", SENSOR_LUX_CORRECTION).toFloat();
  1083. // Specific sensor settings
  1084. for (unsigned char i=0; i<_sensors.size(); i++) {
  1085. #if MICS2710_SUPPORT
  1086. if (_sensors[i]->getID() == SENSOR_MICS2710_ID) {
  1087. if (getSetting("snsResetCalibration", 0).toInt() == 1) {
  1088. MICS2710Sensor * sensor = (MICS2710Sensor *) _sensors[i];
  1089. sensor->calibrate();
  1090. setSetting("snsR0", sensor->getR0());
  1091. }
  1092. }
  1093. #endif // MICS2710_SUPPORT
  1094. #if MICS5525_SUPPORT
  1095. if (_sensors[i]->getID() == SENSOR_MICS5525_ID) {
  1096. if (getSetting("snsResetCalibration", 0).toInt() == 1) {
  1097. MICS5525Sensor * sensor = (MICS5525Sensor *) _sensors[i];
  1098. sensor->calibrate();
  1099. setSetting("snsR0", sensor->getR0());
  1100. }
  1101. }
  1102. #endif // MICS5525_SUPPORT
  1103. #if EMON_ANALOG_SUPPORT
  1104. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  1105. double value;
  1106. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  1107. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  1108. sensor->expectedPower(0, value);
  1109. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  1110. }
  1111. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  1112. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  1113. delSetting("pwrRatioC");
  1114. }
  1115. if (getSetting("pwrResetE", 0).toInt() == 1) {
  1116. sensor->resetEnergy();
  1117. delSetting("eneTotal", 0);
  1118. _sensorResetTS();
  1119. }
  1120. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  1121. }
  1122. #endif // EMON_ANALOG_SUPPORT
  1123. #if EMON_ADC121_SUPPORT
  1124. if (_sensors[i]->getID() == SENSOR_EMON_ADC121_ID) {
  1125. EmonADC121Sensor * sensor = (EmonADC121Sensor *) _sensors[i];
  1126. if (getSetting("pwrResetE", 0).toInt() == 1) {
  1127. sensor->resetEnergy();
  1128. delSetting("eneTotal", 0);
  1129. _sensorResetTS();
  1130. }
  1131. }
  1132. #endif
  1133. #if EMON_ADS1X15_SUPPORT
  1134. if (_sensors[i]->getID() == SENSOR_EMON_ADS1X15_ID) {
  1135. EmonADS1X15Sensor * sensor = (EmonADS1X15Sensor *) _sensors[i];
  1136. if (getSetting("pwrResetE", 0).toInt() == 1) {
  1137. sensor->resetEnergy();
  1138. delSetting("eneTotal", 0);
  1139. _sensorResetTS();
  1140. }
  1141. }
  1142. #endif
  1143. #if HLW8012_SUPPORT
  1144. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  1145. double value;
  1146. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  1147. if ((value = getSetting("pwrExpectedC", 0).toFloat())) {
  1148. sensor->expectedCurrent(value);
  1149. setSetting("pwrRatioC", sensor->getCurrentRatio());
  1150. }
  1151. if ((value = getSetting("pwrExpectedV", 0).toInt())) {
  1152. sensor->expectedVoltage(value);
  1153. setSetting("pwrRatioV", sensor->getVoltageRatio());
  1154. }
  1155. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  1156. sensor->expectedPower(value);
  1157. setSetting("pwrRatioP", sensor->getPowerRatio());
  1158. }
  1159. if (getSetting("pwrResetE", 0).toInt() == 1) {
  1160. sensor->resetEnergy();
  1161. delSetting("eneTotal", 0);
  1162. _sensorResetTS();
  1163. }
  1164. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  1165. sensor->resetRatios();
  1166. delSetting("pwrRatioC");
  1167. delSetting("pwrRatioV");
  1168. delSetting("pwrRatioP");
  1169. }
  1170. }
  1171. #endif // HLW8012_SUPPORT
  1172. #if CSE7766_SUPPORT
  1173. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  1174. double value;
  1175. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  1176. if ((value = getSetting("pwrExpectedC", 0).toFloat())) {
  1177. sensor->expectedCurrent(value);
  1178. setSetting("pwrRatioC", sensor->getCurrentRatio());
  1179. }
  1180. if ((value = getSetting("pwrExpectedV", 0).toInt())) {
  1181. sensor->expectedVoltage(value);
  1182. setSetting("pwrRatioV", sensor->getVoltageRatio());
  1183. }
  1184. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  1185. sensor->expectedPower(value);
  1186. setSetting("pwrRatioP", sensor->getPowerRatio());
  1187. }
  1188. if (getSetting("pwrResetE", 0).toInt() == 1) {
  1189. sensor->resetEnergy();
  1190. delSetting("eneTotal", 0);
  1191. _sensorResetTS();
  1192. }
  1193. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  1194. sensor->resetRatios();
  1195. delSetting("pwrRatioC");
  1196. delSetting("pwrRatioV");
  1197. delSetting("pwrRatioP");
  1198. }
  1199. }
  1200. #endif // CSE7766_SUPPORT
  1201. #if PULSEMETER_SUPPORT
  1202. if (_sensors[i]->getID() == SENSOR_PULSEMETER_ID) {
  1203. PulseMeterSensor * sensor = (PulseMeterSensor *) _sensors[i];
  1204. if (getSetting("pwrResetE", 0).toInt() == 1) {
  1205. sensor->resetEnergy();
  1206. delSetting("eneTotal", 0);
  1207. _sensorResetTS();
  1208. }
  1209. sensor->setEnergyRatio(getSetting("pwrRatioE", sensor->getEnergyRatio()).toInt());
  1210. }
  1211. #endif // PULSEMETER_SUPPORT
  1212. #if PZEM004T_SUPPORT
  1213. if (_sensors[i]->getID() == SENSOR_PZEM004T_ID) {
  1214. PZEM004TSensor * sensor = (PZEM004TSensor *) _sensors[i];
  1215. if (getSetting("pwrResetE", 0).toInt() == 1) {
  1216. unsigned char dev_count = sensor->getAddressesCount();
  1217. for(unsigned char dev = 0; dev < dev_count; dev++) {
  1218. sensor->resetEnergy(dev, 0);
  1219. delSetting("eneTotal", dev);
  1220. }
  1221. _sensorResetTS();
  1222. }
  1223. }
  1224. #endif // PZEM004T_SUPPORT
  1225. #if ADE7953_SUPPORT
  1226. if (_sensors[i]->getID() == SENSOR_ADE7953_ID) {
  1227. ADE7953Sensor * sensor = (ADE7953Sensor *) _sensors[i];
  1228. if (getSetting("pwrResetE", 0).toInt() == 1) {
  1229. unsigned char dev_count = sensor->getTotalDevices();
  1230. for(unsigned char dev = 0; dev < dev_count; dev++) {
  1231. sensor->resetEnergy(dev);
  1232. delSetting("eneTotal", dev);
  1233. }
  1234. _sensorResetTS();
  1235. }
  1236. }
  1237. #endif // ADE7953_SUPPORT
  1238. }
  1239. // Update filter sizes and reset energy if needed
  1240. {
  1241. const bool reset_saved_energy = 0 == _sensor_save_every;
  1242. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  1243. _magnitudes[i].filter->resize(_sensor_report_every);
  1244. if ((_magnitudes[i].type == MAGNITUDE_ENERGY) && reset_saved_energy) {
  1245. delSetting("eneTotal", _magnitudes[i].global);
  1246. }
  1247. }
  1248. }
  1249. // Remove calibration values
  1250. // TODO: do not use settings for one-shot calibration
  1251. delSetting("snsResetCalibration");
  1252. delSetting("pwrExpectedP");
  1253. delSetting("pwrExpectedC");
  1254. delSetting("pwrExpectedV");
  1255. delSetting("pwrResetCalibration");
  1256. delSetting("pwrResetE");
  1257. saveSettings();
  1258. }
  1259. void _sensorReport(unsigned char index, double value) {
  1260. sensor_magnitude_t magnitude = _magnitudes[index];
  1261. unsigned char decimals = magnitude.decimals;
  1262. // XXX: ensure that the received 'value' will fit here
  1263. // dtostrf 2nd arg only controls leading zeroes and the
  1264. // 3rd is only for the part after the dot
  1265. char buffer[64];
  1266. dtostrf(value, 1, decimals, buffer);
  1267. #if BROKER_SUPPORT
  1268. brokerPublish(BROKER_MSG_TYPE_SENSOR ,magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  1269. #endif
  1270. #if MQTT_SUPPORT
  1271. mqttSend(magnitudeTopicIndex(index).c_str(), buffer);
  1272. #if SENSOR_PUBLISH_ADDRESSES
  1273. char topic[32];
  1274. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  1275. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  1276. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  1277. } else {
  1278. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  1279. }
  1280. #endif // SENSOR_PUBLISH_ADDRESSES
  1281. #endif // MQTT_SUPPORT
  1282. #if THINGSPEAK_SUPPORT
  1283. tspkEnqueueMeasurement(index, buffer);
  1284. #endif
  1285. #if DOMOTICZ_SUPPORT
  1286. {
  1287. char key[15];
  1288. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), index);
  1289. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  1290. int status;
  1291. if (value > 70) {
  1292. status = HUMIDITY_WET;
  1293. } else if (value > 45) {
  1294. status = HUMIDITY_COMFORTABLE;
  1295. } else if (value > 30) {
  1296. status = HUMIDITY_NORMAL;
  1297. } else {
  1298. status = HUMIDITY_DRY;
  1299. }
  1300. char status_buf[5];
  1301. itoa(status, status_buf, 10);
  1302. domoticzSend(key, buffer, status_buf);
  1303. } else {
  1304. domoticzSend(key, 0, buffer);
  1305. }
  1306. }
  1307. #endif // DOMOTICZ_SUPPORT
  1308. }
  1309. // -----------------------------------------------------------------------------
  1310. // Public
  1311. // -----------------------------------------------------------------------------
  1312. unsigned char sensorCount() {
  1313. return _sensors.size();
  1314. }
  1315. unsigned char magnitudeCount() {
  1316. return _magnitudes.size();
  1317. }
  1318. String magnitudeName(unsigned char index) {
  1319. if (index < _magnitudes.size()) {
  1320. sensor_magnitude_t magnitude = _magnitudes[index];
  1321. return magnitude.sensor->slot(magnitude.local);
  1322. }
  1323. return String();
  1324. }
  1325. unsigned char magnitudeType(unsigned char index) {
  1326. if (index < _magnitudes.size()) {
  1327. return int(_magnitudes[index].type);
  1328. }
  1329. return MAGNITUDE_NONE;
  1330. }
  1331. double magnitudeValue(unsigned char index) {
  1332. if (index < _magnitudes.size()) {
  1333. return _sensor_realtime ? _magnitudes[index].last : _magnitudes[index].reported;
  1334. }
  1335. return DBL_MIN;
  1336. }
  1337. unsigned char magnitudeIndex(unsigned char index) {
  1338. if (index < _magnitudes.size()) {
  1339. return int(_magnitudes[index].global);
  1340. }
  1341. return 0;
  1342. }
  1343. String magnitudeTopic(unsigned char type) {
  1344. char buffer[16] = {0};
  1345. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  1346. return String(buffer);
  1347. }
  1348. String magnitudeTopicIndex(unsigned char index) {
  1349. char topic[32] = {0};
  1350. if (index < _magnitudes.size()) {
  1351. sensor_magnitude_t magnitude = _magnitudes[index];
  1352. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  1353. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  1354. } else {
  1355. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  1356. }
  1357. }
  1358. return String(topic);
  1359. }
  1360. String magnitudeUnits(unsigned char type) {
  1361. char buffer[8] = {0};
  1362. if (type < MAGNITUDE_MAX) {
  1363. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  1364. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  1365. } else if (
  1366. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  1367. (_sensor_energy_units == ENERGY_KWH)) {
  1368. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  1369. } else if (
  1370. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  1371. (_sensor_power_units == POWER_KILOWATTS)) {
  1372. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  1373. } else {
  1374. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  1375. }
  1376. }
  1377. return String(buffer);
  1378. }
  1379. // -----------------------------------------------------------------------------
  1380. void sensorSetup() {
  1381. // Backwards compatibility
  1382. moveSetting("eneTotal", "eneTotal0");
  1383. moveSetting("powerUnits", "pwrUnits");
  1384. moveSetting("energyUnits", "eneUnits");
  1385. // Update PZEM004T energy total across multiple devices
  1386. moveSettings("pzEneTotal", "eneTotal");
  1387. // Load sensors
  1388. _sensorLoad();
  1389. _sensorInit();
  1390. // Configure stored values
  1391. _sensorConfigure();
  1392. // Websockets
  1393. #if WEB_SUPPORT
  1394. wsRegister()
  1395. .onVisible(_sensorWebSocketOnVisible)
  1396. .onConnected(_sensorWebSocketOnConnected)
  1397. .onData(_sensorWebSocketSendData)
  1398. .onKeyCheck(_sensorWebSocketOnKeyCheck);
  1399. #endif
  1400. // API
  1401. #if API_SUPPORT
  1402. _sensorAPISetup();
  1403. #endif
  1404. // Terminal
  1405. #if TERMINAL_SUPPORT
  1406. _sensorInitCommands();
  1407. #endif
  1408. // Main callbacks
  1409. espurnaRegisterLoop(sensorLoop);
  1410. espurnaRegisterReload(_sensorConfigure);
  1411. }
  1412. void sensorLoop() {
  1413. // Check if we still have uninitialized sensors
  1414. static unsigned long last_init = 0;
  1415. if (!_sensors_ready) {
  1416. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  1417. last_init = millis();
  1418. _sensorInit();
  1419. }
  1420. }
  1421. if (_magnitudes.size() == 0) return;
  1422. // Tick hook
  1423. _sensorTick();
  1424. // Check if we should read new data
  1425. static unsigned long last_update = 0;
  1426. static unsigned long report_count = 0;
  1427. if (millis() - last_update > _sensor_read_interval) {
  1428. last_update = millis();
  1429. report_count = (report_count + 1) % _sensor_report_every;
  1430. double value_raw; // holds the raw value as the sensor returns it
  1431. double value_show; // holds the processed value applying units and decimals
  1432. double value_filtered; // holds the processed value applying filters, and the units and decimals
  1433. // Pre-read hook
  1434. _sensorPre();
  1435. // Get the first relay state
  1436. #if SENSOR_POWER_CHECK_STATUS
  1437. bool relay_off = (relayCount() == 1) && (relayStatus(0) == 0);
  1438. #endif
  1439. // Get readings
  1440. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  1441. sensor_magnitude_t magnitude = _magnitudes[i];
  1442. if (magnitude.sensor->status()) {
  1443. // -------------------------------------------------------------
  1444. // Instant value
  1445. // -------------------------------------------------------------
  1446. value_raw = magnitude.sensor->value(magnitude.local);
  1447. // Completely remove spurious values if relay is OFF
  1448. #if SENSOR_POWER_CHECK_STATUS
  1449. if (relay_off) {
  1450. if (magnitude.type == MAGNITUDE_POWER_ACTIVE ||
  1451. magnitude.type == MAGNITUDE_POWER_REACTIVE ||
  1452. magnitude.type == MAGNITUDE_POWER_APPARENT ||
  1453. magnitude.type == MAGNITUDE_CURRENT ||
  1454. magnitude.type == MAGNITUDE_ENERGY_DELTA
  1455. ) {
  1456. value_raw = 0;
  1457. }
  1458. }
  1459. #endif
  1460. _magnitudes[i].last = value_raw;
  1461. // -------------------------------------------------------------
  1462. // Processing (filters)
  1463. // -------------------------------------------------------------
  1464. magnitude.filter->add(value_raw);
  1465. // Special case for MovingAverageFilter
  1466. if (MAGNITUDE_COUNT == magnitude.type ||
  1467. MAGNITUDE_GEIGER_CPM ==magnitude. type ||
  1468. MAGNITUDE_GEIGER_SIEVERT == magnitude.type) {
  1469. value_raw = magnitude.filter->result();
  1470. }
  1471. // -------------------------------------------------------------
  1472. // Procesing (units and decimals)
  1473. // -------------------------------------------------------------
  1474. value_show = _magnitudeProcess(magnitude.type, magnitude.decimals, value_raw);
  1475. // -------------------------------------------------------------
  1476. // Debug
  1477. // -------------------------------------------------------------
  1478. #if SENSOR_DEBUG
  1479. {
  1480. char buffer[64];
  1481. dtostrf(value_show, 1, magnitude.decimals, buffer);
  1482. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  1483. magnitude.sensor->slot(magnitude.local).c_str(),
  1484. magnitudeTopic(magnitude.type).c_str(),
  1485. buffer,
  1486. magnitudeUnits(magnitude.type).c_str()
  1487. );
  1488. }
  1489. #endif // SENSOR_DEBUG
  1490. // -------------------------------------------------------------
  1491. // Report
  1492. // (we do it every _sensor_report_every readings)
  1493. // -------------------------------------------------------------
  1494. bool report = (0 == report_count);
  1495. if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0)) {
  1496. // for MAGNITUDE_ENERGY, filtered value is last value
  1497. report = (fabs(value_show - magnitude.reported) >= magnitude.max_change);
  1498. } // if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0))
  1499. if (report) {
  1500. value_filtered = magnitude.filter->result();
  1501. value_filtered = _magnitudeProcess(magnitude.type, magnitude.decimals, value_filtered);
  1502. magnitude.filter->reset();
  1503. // Check if there is a minimum change threshold to report
  1504. if (fabs(value_filtered - magnitude.reported) >= magnitude.min_change) {
  1505. _magnitudes[i].reported = value_filtered;
  1506. _sensorReport(i, value_filtered);
  1507. } // if (fabs(value_filtered - magnitude.reported) >= magnitude.min_change)
  1508. // Persist total energy value
  1509. if (MAGNITUDE_ENERGY == magnitude.type) {
  1510. _sensorEnergyTotal(magnitude.global, value_raw);
  1511. }
  1512. } // if (report_count == 0)
  1513. } // if (magnitude.sensor->status())
  1514. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  1515. // Post-read hook
  1516. _sensorPost();
  1517. #if WEB_SUPPORT
  1518. wsPost(_sensorWebSocketSendData);
  1519. #endif
  1520. #if THINGSPEAK_SUPPORT
  1521. if (report_count == 0) tspkFlush();
  1522. #endif
  1523. }
  1524. }
  1525. #endif // SENSOR_SUPPORT