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.

1880 lines
61 KiB

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