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.

1531 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. typedef struct {
  13. BaseSensor * sensor; // Sensor object
  14. BaseFilter * filter; // Filter object
  15. unsigned char local; // Local index in its provider
  16. unsigned char type; // Type of measurement
  17. unsigned char global; // Global index in its type
  18. double current; // Current (last) value, unfiltered
  19. double reported; // Last reported value
  20. double min_change; // Minimum value change to report
  21. double max_change; // Maximum value change to report
  22. } sensor_magnitude_t;
  23. std::vector<BaseSensor *> _sensors;
  24. std::vector<sensor_magnitude_t> _magnitudes;
  25. bool _sensors_ready = false;
  26. unsigned char _counts[MAGNITUDE_MAX];
  27. bool _sensor_realtime = API_REAL_TIME_VALUES;
  28. unsigned long _sensor_read_interval = 1000 * SENSOR_READ_INTERVAL;
  29. unsigned char _sensor_report_every = SENSOR_REPORT_EVERY;
  30. unsigned char _sensor_save_every = SENSOR_SAVE_EVERY;
  31. unsigned char _sensor_power_units = SENSOR_POWER_UNITS;
  32. unsigned char _sensor_energy_units = SENSOR_ENERGY_UNITS;
  33. unsigned char _sensor_temperature_units = SENSOR_TEMPERATURE_UNITS;
  34. double _sensor_temperature_correction = SENSOR_TEMPERATURE_CORRECTION;
  35. double _sensor_humidity_correction = SENSOR_HUMIDITY_CORRECTION;
  36. #if PZEM004T_SUPPORT
  37. PZEM004TSensor *pzem004t_sensor;
  38. #endif
  39. String _sensor_energy_reset_ts = String();
  40. // -----------------------------------------------------------------------------
  41. // Private
  42. // -----------------------------------------------------------------------------
  43. unsigned char _magnitudeDecimals(unsigned char type) {
  44. // Hardcoded decimals (these should be linked to the unit, instead of the magnitude)
  45. if (type == MAGNITUDE_ANALOG) return ANALOG_DECIMALS;
  46. if (type == MAGNITUDE_ENERGY ||
  47. type == MAGNITUDE_ENERGY_DELTA) {
  48. if (_sensor_energy_units == ENERGY_KWH) return 3;
  49. }
  50. if (type == MAGNITUDE_POWER_ACTIVE ||
  51. type == MAGNITUDE_POWER_APPARENT ||
  52. type == MAGNITUDE_POWER_REACTIVE) {
  53. if (_sensor_power_units == POWER_KILOWATTS) return 3;
  54. }
  55. if (type < MAGNITUDE_MAX) return pgm_read_byte(magnitude_decimals + type);
  56. return 0;
  57. }
  58. double _magnitudeProcess(unsigned char type, double value) {
  59. // Hardcoded conversions (these should be linked to the unit, instead of the magnitude)
  60. if (type == MAGNITUDE_TEMPERATURE) {
  61. if (_sensor_temperature_units == TMP_FAHRENHEIT) value = value * 1.8 + 32;
  62. value = value + _sensor_temperature_correction;
  63. }
  64. if (type == MAGNITUDE_HUMIDITY) {
  65. value = constrain(value + _sensor_humidity_correction, 0, 100);
  66. }
  67. if (type == MAGNITUDE_ENERGY ||
  68. type == MAGNITUDE_ENERGY_DELTA) {
  69. if (_sensor_energy_units == ENERGY_KWH) value = value / 3600000;
  70. }
  71. if (type == MAGNITUDE_POWER_ACTIVE ||
  72. type == MAGNITUDE_POWER_APPARENT ||
  73. type == MAGNITUDE_POWER_REACTIVE) {
  74. if (_sensor_power_units == POWER_KILOWATTS) value = value / 1000;
  75. }
  76. return roundTo(value, _magnitudeDecimals(type));
  77. }
  78. // -----------------------------------------------------------------------------
  79. #if WEB_SUPPORT
  80. template<typename T>
  81. 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. _sensors.push_back(sensor);
  541. }
  542. #endif
  543. #if MICS2710_SUPPORT
  544. {
  545. MICS2710Sensor * sensor = new MICS2710Sensor();
  546. sensor->setAnalogGPIO(MICS2710_NOX_PIN);
  547. sensor->setPreHeatGPIO(MICS2710_PRE_PIN);
  548. sensor->setRL(MICS2710_RL);
  549. _sensors.push_back(sensor);
  550. }
  551. #endif
  552. #if MICS5525_SUPPORT
  553. {
  554. MICS5525Sensor * sensor = new MICS5525Sensor();
  555. sensor->setAnalogGPIO(MICS5525_RED_PIN);
  556. sensor->setRL(MICS5525_RL);
  557. _sensors.push_back(sensor);
  558. }
  559. #endif
  560. #if NTC_SUPPORT
  561. {
  562. NTCSensor * sensor = new NTCSensor();
  563. sensor->setSamples(NTC_SAMPLES);
  564. sensor->setDelay(NTC_DELAY);
  565. sensor->setUpstreamResistor(NTC_R_UP);
  566. sensor->setDownstreamResistor(NTC_R_DOWN);
  567. sensor->setBeta(NTC_BETA);
  568. sensor->setR0(NTC_R0);
  569. sensor->setT0(NTC_T0);
  570. _sensors.push_back(sensor);
  571. }
  572. #endif
  573. #if PMSX003_SUPPORT
  574. {
  575. PMSX003Sensor * sensor = new PMSX003Sensor();
  576. #if PMS_USE_SOFT
  577. sensor->setRX(PMS_RX_PIN);
  578. sensor->setTX(PMS_TX_PIN);
  579. #else
  580. sensor->setSerial(& PMS_HW_PORT);
  581. #endif
  582. sensor->setType(PMS_TYPE);
  583. _sensors.push_back(sensor);
  584. }
  585. #endif
  586. #if PULSEMETER_SUPPORT
  587. {
  588. PulseMeterSensor * sensor = new PulseMeterSensor();
  589. sensor->setGPIO(PULSEMETER_PIN);
  590. sensor->setEnergyRatio(PULSEMETER_ENERGY_RATIO);
  591. sensor->setDebounceTime(PULSEMETER_DEBOUNCE);
  592. _sensors.push_back(sensor);
  593. }
  594. #endif
  595. #if PZEM004T_SUPPORT
  596. {
  597. PZEM004TSensor * sensor = pzem004t_sensor = new PZEM004TSensor();
  598. #if PZEM004T_USE_SOFT
  599. sensor->setRX(PZEM004T_RX_PIN);
  600. sensor->setTX(PZEM004T_TX_PIN);
  601. #else
  602. sensor->setSerial(& PZEM004T_HW_PORT);
  603. #endif
  604. sensor->setAddresses(PZEM004T_ADDRESSES);
  605. // Read saved energy offset
  606. unsigned char dev_count = sensor->getAddressesCount();
  607. for(unsigned char dev = 0; dev < dev_count; dev++) {
  608. float value = getSetting("pzEneTotal", dev, 0).toFloat();
  609. if (value > 0) sensor->resetEnergy(dev, value);
  610. }
  611. _sensors.push_back(sensor);
  612. }
  613. #endif
  614. #if SENSEAIR_SUPPORT
  615. {
  616. SenseAirSensor * sensor = new SenseAirSensor();
  617. sensor->setRX(SENSEAIR_RX_PIN);
  618. sensor->setTX(SENSEAIR_TX_PIN);
  619. _sensors.push_back(sensor);
  620. }
  621. #endif
  622. #if SDS011_SUPPORT
  623. {
  624. SDS011Sensor * sensor = new SDS011Sensor();
  625. sensor->setRX(SDS011_RX_PIN);
  626. sensor->setTX(SDS011_TX_PIN);
  627. _sensors.push_back(sensor);
  628. }
  629. #endif
  630. #if SHT3X_I2C_SUPPORT
  631. {
  632. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  633. sensor->setAddress(SHT3X_I2C_ADDRESS);
  634. _sensors.push_back(sensor);
  635. }
  636. #endif
  637. #if SI7021_SUPPORT
  638. {
  639. SI7021Sensor * sensor = new SI7021Sensor();
  640. sensor->setAddress(SI7021_ADDRESS);
  641. _sensors.push_back(sensor);
  642. }
  643. #endif
  644. #if TMP3X_SUPPORT
  645. {
  646. TMP3XSensor * sensor = new TMP3XSensor();
  647. sensor->setType(TMP3X_TYPE);
  648. _sensors.push_back(sensor);
  649. }
  650. #endif
  651. #if V9261F_SUPPORT
  652. {
  653. V9261FSensor * sensor = new V9261FSensor();
  654. sensor->setRX(V9261F_PIN);
  655. sensor->setInverted(V9261F_PIN_INVERSE);
  656. _sensors.push_back(sensor);
  657. }
  658. #endif
  659. #if MAX6675_SUPPORT
  660. {
  661. MAX6675Sensor * sensor = new MAX6675Sensor();
  662. sensor->setCS(MAX6675_CS_PIN);
  663. sensor->setSO(MAX6675_SO_PIN);
  664. sensor->setSCK(MAX6675_SCK_PIN);
  665. _sensors.push_back(sensor);
  666. }
  667. #endif
  668. #if VEML6075_SUPPORT
  669. {
  670. VEML6075Sensor * sensor = new VEML6075Sensor();
  671. sensor->setIntegrationTime(VEML6075_INTEGRATION_TIME);
  672. sensor->setDynamicMode(VEML6075_DYNAMIC_MODE);
  673. _sensors.push_back(sensor);
  674. }
  675. #endif
  676. #if VL53L1X_SUPPORT
  677. {
  678. VL53L1XSensor * sensor = new VL53L1XSensor();
  679. sensor->setInterMeasurementPeriod(VL53L1X_INTER_MEASUREMENT_PERIOD);
  680. sensor->setDistanceMode(VL53L1X_DISTANCE_MODE);
  681. sensor->setMeasurementTimingBudget(VL53L1X_MEASUREMENT_TIMING_BUDGET);
  682. _sensors.push_back(sensor);
  683. }
  684. #endif
  685. #if EZOPH_SUPPORT
  686. {
  687. EZOPHSensor * sensor = new EZOPHSensor();
  688. sensor->setRX(EZOPH_RX_PIN);
  689. sensor->setTX(EZOPH_TX_PIN);
  690. _sensors.push_back(sensor);
  691. }
  692. #endif
  693. }
  694. void _sensorCallback(unsigned char i, unsigned char type, double value) {
  695. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, String(value).c_str());
  696. for (unsigned char k=0; k<_magnitudes.size(); k++) {
  697. if ((_sensors[i] == _magnitudes[k].sensor) && (type == _magnitudes[k].type)) {
  698. _sensorReport(k, value);
  699. return;
  700. }
  701. }
  702. }
  703. void _sensorInit() {
  704. _sensors_ready = true;
  705. _sensor_save_every = getSetting("snsSave", 0).toInt();
  706. for (unsigned char i=0; i<_sensors.size(); i++) {
  707. // Do not process an already initialized sensor
  708. if (_sensors[i]->ready()) continue;
  709. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  710. // Force sensor to reload config
  711. _sensors[i]->begin();
  712. if (!_sensors[i]->ready()) {
  713. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  714. _sensors_ready = false;
  715. continue;
  716. }
  717. // Initialize magnitudes
  718. for (unsigned char k=0; k<_sensors[i]->count(); k++) {
  719. unsigned char type = _sensors[i]->type(k);
  720. sensor_magnitude_t new_magnitude;
  721. new_magnitude.sensor = _sensors[i];
  722. new_magnitude.local = k;
  723. new_magnitude.type = type;
  724. new_magnitude.global = _counts[type];
  725. new_magnitude.current = 0;
  726. new_magnitude.reported = 0;
  727. new_magnitude.min_change = 0;
  728. new_magnitude.max_change = 0;
  729. // TODO: find a proper way to extend this to min/max of any magnitude
  730. if (MAGNITUDE_ENERGY == type) {
  731. new_magnitude.max_change = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE).toFloat();
  732. } else if (MAGNITUDE_TEMPERATURE == type) {
  733. new_magnitude.min_change = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE).toFloat();
  734. } else if (MAGNITUDE_HUMIDITY == type) {
  735. new_magnitude.min_change = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE).toFloat();
  736. }
  737. if (MAGNITUDE_ENERGY == type) {
  738. new_magnitude.filter = new LastFilter();
  739. } else if (MAGNITUDE_DIGITAL == type) {
  740. new_magnitude.filter = new MaxFilter();
  741. } 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.
  742. new_magnitude.filter = new MovingAverageFilter();
  743. } else {
  744. new_magnitude.filter = new MedianFilter();
  745. }
  746. new_magnitude.filter->resize(_sensor_report_every);
  747. _magnitudes.push_back(new_magnitude);
  748. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  749. _counts[type] = _counts[type] + 1;
  750. }
  751. // Hook callback
  752. _sensors[i]->onEvent([i](unsigned char type, double value) {
  753. _sensorCallback(i, type, value);
  754. });
  755. // Custom initializations
  756. #if MICS2710_SUPPORT
  757. if (_sensors[i]->getID() == SENSOR_MICS2710_ID) {
  758. MICS2710Sensor * sensor = (MICS2710Sensor *) _sensors[i];
  759. sensor->setR0(getSetting("snsR0", MICS2710_R0).toInt());
  760. }
  761. #endif // MICS2710_SUPPORT
  762. #if MICS5525_SUPPORT
  763. if (_sensors[i]->getID() == SENSOR_MICS5525_ID) {
  764. MICS5525Sensor * sensor = (MICS5525Sensor *) _sensors[i];
  765. sensor->setR0(getSetting("snsR0", MICS5525_R0).toInt());
  766. }
  767. #endif // MICS5525_SUPPORT
  768. #if EMON_ANALOG_SUPPORT
  769. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  770. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  771. sensor->setCurrentRatio(0, getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat());
  772. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  773. double value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  774. if (value > 0) sensor->resetEnergy(0, value);
  775. }
  776. #endif // EMON_ANALOG_SUPPORT
  777. #if HLW8012_SUPPORT
  778. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  779. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  780. double value;
  781. value = getSetting("pwrRatioC", HLW8012_CURRENT_RATIO).toFloat();
  782. if (value > 0) sensor->setCurrentRatio(value);
  783. value = getSetting("pwrRatioV", HLW8012_VOLTAGE_RATIO).toFloat();
  784. if (value > 0) sensor->setVoltageRatio(value);
  785. value = getSetting("pwrRatioP", HLW8012_POWER_RATIO).toFloat();
  786. if (value > 0) sensor->setPowerRatio(value);
  787. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  788. if (value > 0) sensor->resetEnergy(value);
  789. }
  790. #endif // HLW8012_SUPPORT
  791. #if CSE7766_SUPPORT
  792. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  793. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  794. double value;
  795. value = getSetting("pwrRatioC", 0).toFloat();
  796. if (value > 0) sensor->setCurrentRatio(value);
  797. value = getSetting("pwrRatioV", 0).toFloat();
  798. if (value > 0) sensor->setVoltageRatio(value);
  799. value = getSetting("pwrRatioP", 0).toFloat();
  800. if (value > 0) sensor->setPowerRatio(value);
  801. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  802. if (value > 0) sensor->resetEnergy(value);
  803. }
  804. #endif // CSE7766_SUPPORT
  805. #if PULSEMETER_SUPPORT
  806. if (_sensors[i]->getID() == SENSOR_PULSEMETER_ID) {
  807. PulseMeterSensor * sensor = (PulseMeterSensor *) _sensors[i];
  808. sensor->setEnergyRatio(getSetting("pwrRatioE", PULSEMETER_ENERGY_RATIO).toInt());
  809. }
  810. #endif // PULSEMETER_SUPPORT
  811. }
  812. }
  813. void _sensorConfigure() {
  814. // General sensor settings
  815. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  816. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  817. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY).toInt();
  818. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  819. _sensor_power_units = getSetting("pwrUnits", SENSOR_POWER_UNITS).toInt();
  820. _sensor_energy_units = getSetting("eneUnits", SENSOR_ENERGY_UNITS).toInt();
  821. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  822. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  823. _sensor_humidity_correction = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION).toFloat();
  824. _sensor_energy_reset_ts = getSetting("snsResetTS", "");
  825. // Specific sensor settings
  826. for (unsigned char i=0; i<_sensors.size(); i++) {
  827. #if MICS2710_SUPPORT
  828. if (_sensors[i]->getID() == SENSOR_MICS2710_ID) {
  829. if (getSetting("snsResetCalibration", 0).toInt() == 1) {
  830. MICS2710Sensor * sensor = (MICS2710Sensor *) _sensors[i];
  831. sensor->calibrate();
  832. setSetting("snsR0", sensor->getR0());
  833. }
  834. }
  835. #endif // MICS2710_SUPPORT
  836. #if MICS5525_SUPPORT
  837. if (_sensors[i]->getID() == SENSOR_MICS5525_ID) {
  838. if (getSetting("snsResetCalibration", 0).toInt() == 1) {
  839. MICS5525Sensor * sensor = (MICS5525Sensor *) _sensors[i];
  840. sensor->calibrate();
  841. setSetting("snsR0", sensor->getR0());
  842. }
  843. }
  844. #endif // MICS5525_SUPPORT
  845. #if EMON_ANALOG_SUPPORT
  846. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  847. double value;
  848. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  849. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  850. sensor->expectedPower(0, value);
  851. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  852. }
  853. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  854. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  855. delSetting("pwrRatioC");
  856. }
  857. if (getSetting("pwrResetE", 0).toInt() == 1) {
  858. sensor->resetEnergy();
  859. delSetting("eneTotal");
  860. _sensorResetTS();
  861. }
  862. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  863. }
  864. #endif // EMON_ANALOG_SUPPORT
  865. #if EMON_ADC121_SUPPORT
  866. if (_sensors[i]->getID() == SENSOR_EMON_ADC121_ID) {
  867. EmonADC121Sensor * sensor = (EmonADC121Sensor *) _sensors[i];
  868. if (getSetting("pwrResetE", 0).toInt() == 1) {
  869. sensor->resetEnergy();
  870. delSetting("eneTotal");
  871. _sensorResetTS();
  872. }
  873. }
  874. #endif
  875. #if EMON_ADS1X15_SUPPORT
  876. if (_sensors[i]->getID() == SENSOR_EMON_ADS1X15_ID) {
  877. EmonADS1X15Sensor * sensor = (EmonADS1X15Sensor *) _sensors[i];
  878. if (getSetting("pwrResetE", 0).toInt() == 1) {
  879. sensor->resetEnergy();
  880. delSetting("eneTotal");
  881. _sensorResetTS();
  882. }
  883. }
  884. #endif
  885. #if HLW8012_SUPPORT
  886. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  887. double value;
  888. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  889. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  890. sensor->expectedCurrent(value);
  891. setSetting("pwrRatioC", sensor->getCurrentRatio());
  892. }
  893. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  894. sensor->expectedVoltage(value);
  895. setSetting("pwrRatioV", sensor->getVoltageRatio());
  896. }
  897. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  898. sensor->expectedPower(value);
  899. setSetting("pwrRatioP", sensor->getPowerRatio());
  900. }
  901. if (getSetting("pwrResetE", 0).toInt() == 1) {
  902. sensor->resetEnergy();
  903. delSetting("eneTotal");
  904. _sensorResetTS();
  905. }
  906. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  907. sensor->resetRatios();
  908. delSetting("pwrRatioC");
  909. delSetting("pwrRatioV");
  910. delSetting("pwrRatioP");
  911. }
  912. }
  913. #endif // HLW8012_SUPPORT
  914. #if CSE7766_SUPPORT
  915. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  916. double value;
  917. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  918. if ((value = getSetting("pwrExpectedC", 0).toFloat())) {
  919. sensor->expectedCurrent(value);
  920. setSetting("pwrRatioC", sensor->getCurrentRatio());
  921. }
  922. if ((value = getSetting("pwrExpectedV", 0).toInt())) {
  923. sensor->expectedVoltage(value);
  924. setSetting("pwrRatioV", sensor->getVoltageRatio());
  925. }
  926. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  927. sensor->expectedPower(value);
  928. setSetting("pwrRatioP", sensor->getPowerRatio());
  929. }
  930. if (getSetting("pwrResetE", 0).toInt() == 1) {
  931. sensor->resetEnergy();
  932. delSetting("eneTotal");
  933. _sensorResetTS();
  934. }
  935. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  936. sensor->resetRatios();
  937. delSetting("pwrRatioC");
  938. delSetting("pwrRatioV");
  939. delSetting("pwrRatioP");
  940. }
  941. }
  942. #endif // CSE7766_SUPPORT
  943. #if PULSEMETER_SUPPORT
  944. if (_sensors[i]->getID() == SENSOR_PULSEMETER_ID) {
  945. PulseMeterSensor * sensor = (PulseMeterSensor *) _sensors[i];
  946. if (getSetting("pwrResetE", 0).toInt() == 1) {
  947. sensor->resetEnergy();
  948. delSetting("eneTotal");
  949. _sensorResetTS();
  950. }
  951. sensor->setEnergyRatio(getSetting("pwrRatioE", PULSEMETER_ENERGY_RATIO).toInt());
  952. }
  953. #endif // PULSEMETER_SUPPORT
  954. #if PZEM004T_SUPPORT
  955. if (_sensors[i]->getID() == SENSOR_PZEM004T_ID) {
  956. PZEM004TSensor * sensor = (PZEM004TSensor *) _sensors[i];
  957. if (getSetting("pwrResetE", 0).toInt() == 1) {
  958. unsigned char dev_count = sensor->getAddressesCount();
  959. for(unsigned char dev = 0; dev < dev_count; dev++) {
  960. sensor->resetEnergy(dev, 0);
  961. delSetting("pzEneTotal", dev);
  962. }
  963. _sensorResetTS();
  964. }
  965. }
  966. #endif // PZEM004T_SUPPORT
  967. }
  968. // Update filter sizes
  969. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  970. _magnitudes[i].filter->resize(_sensor_report_every);
  971. }
  972. // General processing
  973. if (0 == _sensor_save_every) {
  974. delSetting("eneTotal");
  975. }
  976. // Save settings
  977. delSetting("snsResetCalibration");
  978. delSetting("pwrExpectedP");
  979. delSetting("pwrExpectedC");
  980. delSetting("pwrExpectedV");
  981. delSetting("pwrResetCalibration");
  982. delSetting("pwrResetE");
  983. saveSettings();
  984. }
  985. void _sensorReport(unsigned char index, double value) {
  986. sensor_magnitude_t magnitude = _magnitudes[index];
  987. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  988. char buffer[10];
  989. dtostrf(value, 1-sizeof(buffer), decimals, buffer);
  990. #if BROKER_SUPPORT
  991. brokerPublish(BROKER_MSG_TYPE_SENSOR ,magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  992. #endif
  993. #if MQTT_SUPPORT
  994. mqttSend(magnitudeTopicIndex(index).c_str(), buffer);
  995. #if SENSOR_PUBLISH_ADDRESSES
  996. char topic[32];
  997. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  998. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  999. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  1000. } else {
  1001. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  1002. }
  1003. #endif // SENSOR_PUBLISH_ADDRESSES
  1004. #endif // MQTT_SUPPORT
  1005. #if THINGSPEAK_SUPPORT
  1006. tspkEnqueueMeasurement(index, buffer);
  1007. #endif
  1008. #if DOMOTICZ_SUPPORT
  1009. {
  1010. char key[15];
  1011. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), index);
  1012. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  1013. int status;
  1014. if (value > 70) {
  1015. status = HUMIDITY_WET;
  1016. } else if (value > 45) {
  1017. status = HUMIDITY_COMFORTABLE;
  1018. } else if (value > 30) {
  1019. status = HUMIDITY_NORMAL;
  1020. } else {
  1021. status = HUMIDITY_DRY;
  1022. }
  1023. char status_buf[5];
  1024. itoa(status, status_buf, 10);
  1025. domoticzSend(key, buffer, status_buf);
  1026. } else {
  1027. domoticzSend(key, 0, buffer);
  1028. }
  1029. }
  1030. #endif // DOMOTICZ_SUPPORT
  1031. }
  1032. // -----------------------------------------------------------------------------
  1033. // Public
  1034. // -----------------------------------------------------------------------------
  1035. unsigned char sensorCount() {
  1036. return _sensors.size();
  1037. }
  1038. unsigned char magnitudeCount() {
  1039. return _magnitudes.size();
  1040. }
  1041. String magnitudeName(unsigned char index) {
  1042. if (index < _magnitudes.size()) {
  1043. sensor_magnitude_t magnitude = _magnitudes[index];
  1044. return magnitude.sensor->slot(magnitude.local);
  1045. }
  1046. return String();
  1047. }
  1048. unsigned char magnitudeType(unsigned char index) {
  1049. if (index < _magnitudes.size()) {
  1050. return int(_magnitudes[index].type);
  1051. }
  1052. return MAGNITUDE_NONE;
  1053. }
  1054. unsigned char magnitudeIndex(unsigned char index) {
  1055. if (index < _magnitudes.size()) {
  1056. return int(_magnitudes[index].global);
  1057. }
  1058. return 0;
  1059. }
  1060. String magnitudeTopic(unsigned char type) {
  1061. char buffer[16] = {0};
  1062. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  1063. return String(buffer);
  1064. }
  1065. String magnitudeTopicIndex(unsigned char index) {
  1066. char topic[32] = {0};
  1067. if (index < _magnitudes.size()) {
  1068. sensor_magnitude_t magnitude = _magnitudes[index];
  1069. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  1070. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  1071. } else {
  1072. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  1073. }
  1074. }
  1075. return String(topic);
  1076. }
  1077. String magnitudeUnits(unsigned char type) {
  1078. char buffer[8] = {0};
  1079. if (type < MAGNITUDE_MAX) {
  1080. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  1081. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  1082. } else if (
  1083. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  1084. (_sensor_energy_units == ENERGY_KWH)) {
  1085. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  1086. } else if (
  1087. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  1088. (_sensor_power_units == POWER_KILOWATTS)) {
  1089. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  1090. } else {
  1091. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  1092. }
  1093. }
  1094. return String(buffer);
  1095. }
  1096. // -----------------------------------------------------------------------------
  1097. void sensorSetup() {
  1098. // Backwards compatibility
  1099. moveSetting("powerUnits", "pwrUnits");
  1100. moveSetting("energyUnits", "eneUnits");
  1101. // Load sensors
  1102. _sensorLoad();
  1103. _sensorInit();
  1104. // Configure stored values
  1105. _sensorConfigure();
  1106. // Websockets
  1107. #if WEB_SUPPORT
  1108. wsOnSendRegister(_sensorWebSocketStart);
  1109. wsOnReceiveRegister(_sensorWebSocketOnReceive);
  1110. wsOnSendRegister(_sensorWebSocketSendData);
  1111. #endif
  1112. // API
  1113. #if API_SUPPORT
  1114. _sensorAPISetup();
  1115. #endif
  1116. // Terminal
  1117. #if TERMINAL_SUPPORT
  1118. _sensorInitCommands();
  1119. #endif
  1120. // Main callbacks
  1121. espurnaRegisterLoop(sensorLoop);
  1122. espurnaRegisterReload(_sensorConfigure);
  1123. }
  1124. void sensorLoop() {
  1125. // Check if we still have uninitialized sensors
  1126. static unsigned long last_init = 0;
  1127. if (!_sensors_ready) {
  1128. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  1129. last_init = millis();
  1130. _sensorInit();
  1131. }
  1132. }
  1133. if (_magnitudes.size() == 0) return;
  1134. // Tick hook
  1135. _sensorTick();
  1136. // Check if we should read new data
  1137. static unsigned long last_update = 0;
  1138. static unsigned long report_count = 0;
  1139. static unsigned long save_count = 0;
  1140. if (millis() - last_update > _sensor_read_interval) {
  1141. last_update = millis();
  1142. report_count = (report_count + 1) % _sensor_report_every;
  1143. double current;
  1144. double filtered;
  1145. // Pre-read hook
  1146. _sensorPre();
  1147. // Get the first relay state
  1148. #if SENSOR_POWER_CHECK_STATUS
  1149. bool relay_off = (relayCount() > 0) && (relayStatus(0) == 0);
  1150. #endif
  1151. // Get readings
  1152. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  1153. sensor_magnitude_t magnitude = _magnitudes[i];
  1154. if (magnitude.sensor->status()) {
  1155. // -------------------------------------------------------------
  1156. // Instant value
  1157. // -------------------------------------------------------------
  1158. current = magnitude.sensor->value(magnitude.local);
  1159. // Completely remove spurious values if relay is OFF
  1160. #if SENSOR_POWER_CHECK_STATUS
  1161. if (relay_off) {
  1162. if (magnitude.type == MAGNITUDE_POWER_ACTIVE ||
  1163. magnitude.type == MAGNITUDE_POWER_REACTIVE ||
  1164. magnitude.type == MAGNITUDE_POWER_APPARENT ||
  1165. magnitude.type == MAGNITUDE_CURRENT ||
  1166. magnitude.type == MAGNITUDE_ENERGY_DELTA
  1167. ) {
  1168. current = 0;
  1169. }
  1170. }
  1171. #endif
  1172. // -------------------------------------------------------------
  1173. // Processing (filters)
  1174. // -------------------------------------------------------------
  1175. magnitude.filter->add(current);
  1176. // Special case for MovingAvergaeFilter
  1177. if (MAGNITUDE_COUNT == magnitude.type ||
  1178. MAGNITUDE_GEIGER_CPM ==magnitude. type ||
  1179. MAGNITUDE_GEIGER_SIEVERT == magnitude.type) {
  1180. current = magnitude.filter->result();
  1181. }
  1182. current = _magnitudeProcess(magnitude.type, current);
  1183. _magnitudes[i].current = current;
  1184. // -------------------------------------------------------------
  1185. // Debug
  1186. // -------------------------------------------------------------
  1187. #if SENSOR_DEBUG
  1188. {
  1189. char buffer[64];
  1190. dtostrf(current, 1-sizeof(buffer), _magnitudeDecimals(magnitude.type), buffer);
  1191. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  1192. magnitude.sensor->slot(magnitude.local).c_str(),
  1193. magnitudeTopic(magnitude.type).c_str(),
  1194. buffer,
  1195. magnitudeUnits(magnitude.type).c_str()
  1196. );
  1197. }
  1198. #endif // SENSOR_DEBUG
  1199. // -------------------------------------------------------------
  1200. // Report
  1201. // (we do it every _sensor_report_every readings)
  1202. // -------------------------------------------------------------
  1203. bool report = (0 == report_count);
  1204. if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0)) {
  1205. // for MAGNITUDE_ENERGY, filtered value is last value
  1206. double value = _magnitudeProcess(magnitude.type, current);
  1207. report = (fabs(value - magnitude.reported) >= magnitude.max_change);
  1208. } // if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0))
  1209. if (report) {
  1210. filtered = magnitude.filter->result();
  1211. filtered = _magnitudeProcess(magnitude.type, filtered);
  1212. magnitude.filter->reset();
  1213. // Check if there is a minimum change threshold to report
  1214. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  1215. _magnitudes[i].reported = filtered;
  1216. _sensorReport(i, filtered);
  1217. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  1218. // -------------------------------------------------------------
  1219. // Saving to EEPROM
  1220. // (we do it every _sensor_save_every readings)
  1221. // -------------------------------------------------------------
  1222. if (_sensor_save_every > 0) {
  1223. save_count = (save_count + 1) % _sensor_save_every;
  1224. if (0 == save_count) {
  1225. if (MAGNITUDE_ENERGY == magnitude.type) {
  1226. setSetting("eneTotal", current);
  1227. saveSettings();
  1228. }
  1229. } // if (0 == save_count)
  1230. } // if (_sensor_save_every > 0)
  1231. } // if (report_count == 0)
  1232. } // if (magnitude.sensor->status())
  1233. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  1234. // Post-read hook
  1235. _sensorPost();
  1236. #if WEB_SUPPORT
  1237. wsSend(_sensorWebSocketSendData);
  1238. #endif
  1239. #if THINGSPEAK_SUPPORT
  1240. if (report_count == 0) tspkFlush();
  1241. #endif
  1242. }
  1243. }
  1244. #endif // SENSOR_SUPPORT