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.

1878 lines
61 KiB

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