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.

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