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.

1879 lines
61 KiB

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