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.

1536 lines
50 KiB

7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
  1. /*
  2. SENSOR MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if SENSOR_SUPPORT
  6. #include <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 decimals; // Number of decimals in textual representation
  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, unsigned char decimals, 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, decimals);
  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 = magnitude.decimals;
  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 = magnitude.decimals;
  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. signed char decimals = _sensors[i]->decimals(type);
  723. if (decimals < 0) decimals = _magnitudeDecimals(type);
  724. sensor_magnitude_t new_magnitude;
  725. new_magnitude.sensor = _sensors[i];
  726. new_magnitude.local = k;
  727. new_magnitude.type = type;
  728. new_magnitude.decimals = (unsigned char) decimals;
  729. new_magnitude.global = _counts[type];
  730. new_magnitude.current = 0;
  731. new_magnitude.reported = 0;
  732. new_magnitude.min_change = 0;
  733. new_magnitude.max_change = 0;
  734. // TODO: find a proper way to extend this to min/max of any magnitude
  735. if (MAGNITUDE_ENERGY == type) {
  736. new_magnitude.max_change = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE).toFloat();
  737. } else if (MAGNITUDE_TEMPERATURE == type) {
  738. new_magnitude.min_change = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE).toFloat();
  739. } else if (MAGNITUDE_HUMIDITY == type) {
  740. new_magnitude.min_change = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE).toFloat();
  741. }
  742. if (MAGNITUDE_ENERGY == type) {
  743. new_magnitude.filter = new LastFilter();
  744. } else if (MAGNITUDE_DIGITAL == type) {
  745. new_magnitude.filter = new MaxFilter();
  746. } 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.
  747. new_magnitude.filter = new MovingAverageFilter();
  748. } else {
  749. new_magnitude.filter = new MedianFilter();
  750. }
  751. new_magnitude.filter->resize(_sensor_report_every);
  752. _magnitudes.push_back(new_magnitude);
  753. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  754. _counts[type] = _counts[type] + 1;
  755. }
  756. // Hook callback
  757. _sensors[i]->onEvent([i](unsigned char type, double value) {
  758. _sensorCallback(i, type, value);
  759. });
  760. // Custom initializations
  761. #if MICS2710_SUPPORT
  762. if (_sensors[i]->getID() == SENSOR_MICS2710_ID) {
  763. MICS2710Sensor * sensor = (MICS2710Sensor *) _sensors[i];
  764. sensor->setR0(getSetting("snsR0", MICS2710_R0).toInt());
  765. }
  766. #endif // MICS2710_SUPPORT
  767. #if MICS5525_SUPPORT
  768. if (_sensors[i]->getID() == SENSOR_MICS5525_ID) {
  769. MICS5525Sensor * sensor = (MICS5525Sensor *) _sensors[i];
  770. sensor->setR0(getSetting("snsR0", MICS5525_R0).toInt());
  771. }
  772. #endif // MICS5525_SUPPORT
  773. #if EMON_ANALOG_SUPPORT
  774. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  775. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  776. sensor->setCurrentRatio(0, getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat());
  777. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  778. double value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  779. if (value > 0) sensor->resetEnergy(0, value);
  780. }
  781. #endif // EMON_ANALOG_SUPPORT
  782. #if HLW8012_SUPPORT
  783. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  784. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  785. double value;
  786. value = getSetting("pwrRatioC", HLW8012_CURRENT_RATIO).toFloat();
  787. if (value > 0) sensor->setCurrentRatio(value);
  788. value = getSetting("pwrRatioV", HLW8012_VOLTAGE_RATIO).toFloat();
  789. if (value > 0) sensor->setVoltageRatio(value);
  790. value = getSetting("pwrRatioP", HLW8012_POWER_RATIO).toFloat();
  791. if (value > 0) sensor->setPowerRatio(value);
  792. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  793. if (value > 0) sensor->resetEnergy(value);
  794. }
  795. #endif // HLW8012_SUPPORT
  796. #if CSE7766_SUPPORT
  797. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  798. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  799. double value;
  800. value = getSetting("pwrRatioC", 0).toFloat();
  801. if (value > 0) sensor->setCurrentRatio(value);
  802. value = getSetting("pwrRatioV", 0).toFloat();
  803. if (value > 0) sensor->setVoltageRatio(value);
  804. value = getSetting("pwrRatioP", 0).toFloat();
  805. if (value > 0) sensor->setPowerRatio(value);
  806. value = (_sensor_save_every > 0) ? getSetting("eneTotal", 0).toInt() : 0;
  807. if (value > 0) sensor->resetEnergy(value);
  808. }
  809. #endif // CSE7766_SUPPORT
  810. #if PULSEMETER_SUPPORT
  811. if (_sensors[i]->getID() == SENSOR_PULSEMETER_ID) {
  812. PulseMeterSensor * sensor = (PulseMeterSensor *) _sensors[i];
  813. sensor->setEnergyRatio(getSetting("pwrRatioE", PULSEMETER_ENERGY_RATIO).toInt());
  814. }
  815. #endif // PULSEMETER_SUPPORT
  816. }
  817. }
  818. void _sensorConfigure() {
  819. // General sensor settings
  820. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  821. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  822. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY).toInt();
  823. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  824. _sensor_power_units = getSetting("pwrUnits", SENSOR_POWER_UNITS).toInt();
  825. _sensor_energy_units = getSetting("eneUnits", SENSOR_ENERGY_UNITS).toInt();
  826. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  827. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  828. _sensor_humidity_correction = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION).toFloat();
  829. _sensor_energy_reset_ts = getSetting("snsResetTS", "");
  830. // Specific sensor settings
  831. for (unsigned char i=0; i<_sensors.size(); i++) {
  832. #if MICS2710_SUPPORT
  833. if (_sensors[i]->getID() == SENSOR_MICS2710_ID) {
  834. if (getSetting("snsResetCalibration", 0).toInt() == 1) {
  835. MICS2710Sensor * sensor = (MICS2710Sensor *) _sensors[i];
  836. sensor->calibrate();
  837. setSetting("snsR0", sensor->getR0());
  838. }
  839. }
  840. #endif // MICS2710_SUPPORT
  841. #if MICS5525_SUPPORT
  842. if (_sensors[i]->getID() == SENSOR_MICS5525_ID) {
  843. if (getSetting("snsResetCalibration", 0).toInt() == 1) {
  844. MICS5525Sensor * sensor = (MICS5525Sensor *) _sensors[i];
  845. sensor->calibrate();
  846. setSetting("snsR0", sensor->getR0());
  847. }
  848. }
  849. #endif // MICS5525_SUPPORT
  850. #if EMON_ANALOG_SUPPORT
  851. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  852. double value;
  853. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  854. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  855. sensor->expectedPower(0, value);
  856. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  857. }
  858. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  859. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  860. delSetting("pwrRatioC");
  861. }
  862. if (getSetting("pwrResetE", 0).toInt() == 1) {
  863. sensor->resetEnergy();
  864. delSetting("eneTotal");
  865. _sensorResetTS();
  866. }
  867. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  868. }
  869. #endif // EMON_ANALOG_SUPPORT
  870. #if EMON_ADC121_SUPPORT
  871. if (_sensors[i]->getID() == SENSOR_EMON_ADC121_ID) {
  872. EmonADC121Sensor * sensor = (EmonADC121Sensor *) _sensors[i];
  873. if (getSetting("pwrResetE", 0).toInt() == 1) {
  874. sensor->resetEnergy();
  875. delSetting("eneTotal");
  876. _sensorResetTS();
  877. }
  878. }
  879. #endif
  880. #if EMON_ADS1X15_SUPPORT
  881. if (_sensors[i]->getID() == SENSOR_EMON_ADS1X15_ID) {
  882. EmonADS1X15Sensor * sensor = (EmonADS1X15Sensor *) _sensors[i];
  883. if (getSetting("pwrResetE", 0).toInt() == 1) {
  884. sensor->resetEnergy();
  885. delSetting("eneTotal");
  886. _sensorResetTS();
  887. }
  888. }
  889. #endif
  890. #if HLW8012_SUPPORT
  891. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  892. double value;
  893. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  894. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  895. sensor->expectedCurrent(value);
  896. setSetting("pwrRatioC", sensor->getCurrentRatio());
  897. }
  898. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  899. sensor->expectedVoltage(value);
  900. setSetting("pwrRatioV", sensor->getVoltageRatio());
  901. }
  902. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  903. sensor->expectedPower(value);
  904. setSetting("pwrRatioP", sensor->getPowerRatio());
  905. }
  906. if (getSetting("pwrResetE", 0).toInt() == 1) {
  907. sensor->resetEnergy();
  908. delSetting("eneTotal");
  909. _sensorResetTS();
  910. }
  911. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  912. sensor->resetRatios();
  913. delSetting("pwrRatioC");
  914. delSetting("pwrRatioV");
  915. delSetting("pwrRatioP");
  916. }
  917. }
  918. #endif // HLW8012_SUPPORT
  919. #if CSE7766_SUPPORT
  920. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  921. double value;
  922. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  923. if ((value = getSetting("pwrExpectedC", 0).toFloat())) {
  924. sensor->expectedCurrent(value);
  925. setSetting("pwrRatioC", sensor->getCurrentRatio());
  926. }
  927. if ((value = getSetting("pwrExpectedV", 0).toInt())) {
  928. sensor->expectedVoltage(value);
  929. setSetting("pwrRatioV", sensor->getVoltageRatio());
  930. }
  931. if ((value = getSetting("pwrExpectedP", 0).toInt())) {
  932. sensor->expectedPower(value);
  933. setSetting("pwrRatioP", sensor->getPowerRatio());
  934. }
  935. if (getSetting("pwrResetE", 0).toInt() == 1) {
  936. sensor->resetEnergy();
  937. delSetting("eneTotal");
  938. _sensorResetTS();
  939. }
  940. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  941. sensor->resetRatios();
  942. delSetting("pwrRatioC");
  943. delSetting("pwrRatioV");
  944. delSetting("pwrRatioP");
  945. }
  946. }
  947. #endif // CSE7766_SUPPORT
  948. #if PULSEMETER_SUPPORT
  949. if (_sensors[i]->getID() == SENSOR_PULSEMETER_ID) {
  950. PulseMeterSensor * sensor = (PulseMeterSensor *) _sensors[i];
  951. if (getSetting("pwrResetE", 0).toInt() == 1) {
  952. sensor->resetEnergy();
  953. delSetting("eneTotal");
  954. _sensorResetTS();
  955. }
  956. sensor->setEnergyRatio(getSetting("pwrRatioE", PULSEMETER_ENERGY_RATIO).toInt());
  957. }
  958. #endif // PULSEMETER_SUPPORT
  959. #if PZEM004T_SUPPORT
  960. if (_sensors[i]->getID() == SENSOR_PZEM004T_ID) {
  961. PZEM004TSensor * sensor = (PZEM004TSensor *) _sensors[i];
  962. if (getSetting("pwrResetE", 0).toInt() == 1) {
  963. unsigned char dev_count = sensor->getAddressesCount();
  964. for(unsigned char dev = 0; dev < dev_count; dev++) {
  965. sensor->resetEnergy(dev, 0);
  966. delSetting("pzEneTotal", dev);
  967. }
  968. _sensorResetTS();
  969. }
  970. }
  971. #endif // PZEM004T_SUPPORT
  972. }
  973. // Update filter sizes
  974. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  975. _magnitudes[i].filter->resize(_sensor_report_every);
  976. }
  977. // General processing
  978. if (0 == _sensor_save_every) {
  979. delSetting("eneTotal");
  980. }
  981. // Save settings
  982. delSetting("snsResetCalibration");
  983. delSetting("pwrExpectedP");
  984. delSetting("pwrExpectedC");
  985. delSetting("pwrExpectedV");
  986. delSetting("pwrResetCalibration");
  987. delSetting("pwrResetE");
  988. saveSettings();
  989. }
  990. void _sensorReport(unsigned char index, double value) {
  991. sensor_magnitude_t magnitude = _magnitudes[index];
  992. unsigned char decimals = magnitude.decimals;
  993. char buffer[10];
  994. dtostrf(value, 1-sizeof(buffer), decimals, buffer);
  995. #if BROKER_SUPPORT
  996. brokerPublish(BROKER_MSG_TYPE_SENSOR ,magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  997. #endif
  998. #if MQTT_SUPPORT
  999. mqttSend(magnitudeTopicIndex(index).c_str(), buffer);
  1000. #if SENSOR_PUBLISH_ADDRESSES
  1001. char topic[32];
  1002. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  1003. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  1004. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  1005. } else {
  1006. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  1007. }
  1008. #endif // SENSOR_PUBLISH_ADDRESSES
  1009. #endif // MQTT_SUPPORT
  1010. #if THINGSPEAK_SUPPORT
  1011. tspkEnqueueMeasurement(index, buffer);
  1012. #endif
  1013. #if DOMOTICZ_SUPPORT
  1014. {
  1015. char key[15];
  1016. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), index);
  1017. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  1018. int status;
  1019. if (value > 70) {
  1020. status = HUMIDITY_WET;
  1021. } else if (value > 45) {
  1022. status = HUMIDITY_COMFORTABLE;
  1023. } else if (value > 30) {
  1024. status = HUMIDITY_NORMAL;
  1025. } else {
  1026. status = HUMIDITY_DRY;
  1027. }
  1028. char status_buf[5];
  1029. itoa(status, status_buf, 10);
  1030. domoticzSend(key, buffer, status_buf);
  1031. } else {
  1032. domoticzSend(key, 0, buffer);
  1033. }
  1034. }
  1035. #endif // DOMOTICZ_SUPPORT
  1036. }
  1037. // -----------------------------------------------------------------------------
  1038. // Public
  1039. // -----------------------------------------------------------------------------
  1040. unsigned char sensorCount() {
  1041. return _sensors.size();
  1042. }
  1043. unsigned char magnitudeCount() {
  1044. return _magnitudes.size();
  1045. }
  1046. String magnitudeName(unsigned char index) {
  1047. if (index < _magnitudes.size()) {
  1048. sensor_magnitude_t magnitude = _magnitudes[index];
  1049. return magnitude.sensor->slot(magnitude.local);
  1050. }
  1051. return String();
  1052. }
  1053. unsigned char magnitudeType(unsigned char index) {
  1054. if (index < _magnitudes.size()) {
  1055. return int(_magnitudes[index].type);
  1056. }
  1057. return MAGNITUDE_NONE;
  1058. }
  1059. unsigned char magnitudeIndex(unsigned char index) {
  1060. if (index < _magnitudes.size()) {
  1061. return int(_magnitudes[index].global);
  1062. }
  1063. return 0;
  1064. }
  1065. String magnitudeTopic(unsigned char type) {
  1066. char buffer[16] = {0};
  1067. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  1068. return String(buffer);
  1069. }
  1070. String magnitudeTopicIndex(unsigned char index) {
  1071. char topic[32] = {0};
  1072. if (index < _magnitudes.size()) {
  1073. sensor_magnitude_t magnitude = _magnitudes[index];
  1074. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  1075. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  1076. } else {
  1077. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  1078. }
  1079. }
  1080. return String(topic);
  1081. }
  1082. String magnitudeUnits(unsigned char type) {
  1083. char buffer[8] = {0};
  1084. if (type < MAGNITUDE_MAX) {
  1085. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  1086. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  1087. } else if (
  1088. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  1089. (_sensor_energy_units == ENERGY_KWH)) {
  1090. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  1091. } else if (
  1092. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  1093. (_sensor_power_units == POWER_KILOWATTS)) {
  1094. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  1095. } else {
  1096. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  1097. }
  1098. }
  1099. return String(buffer);
  1100. }
  1101. // -----------------------------------------------------------------------------
  1102. void sensorSetup() {
  1103. // Backwards compatibility
  1104. moveSetting("powerUnits", "pwrUnits");
  1105. moveSetting("energyUnits", "eneUnits");
  1106. // Load sensors
  1107. _sensorLoad();
  1108. _sensorInit();
  1109. // Configure stored values
  1110. _sensorConfigure();
  1111. // Websockets
  1112. #if WEB_SUPPORT
  1113. wsOnSendRegister(_sensorWebSocketStart);
  1114. wsOnReceiveRegister(_sensorWebSocketOnReceive);
  1115. wsOnSendRegister(_sensorWebSocketSendData);
  1116. #endif
  1117. // API
  1118. #if API_SUPPORT
  1119. _sensorAPISetup();
  1120. #endif
  1121. // Terminal
  1122. #if TERMINAL_SUPPORT
  1123. _sensorInitCommands();
  1124. #endif
  1125. // Main callbacks
  1126. espurnaRegisterLoop(sensorLoop);
  1127. espurnaRegisterReload(_sensorConfigure);
  1128. }
  1129. void sensorLoop() {
  1130. // Check if we still have uninitialized sensors
  1131. static unsigned long last_init = 0;
  1132. if (!_sensors_ready) {
  1133. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  1134. last_init = millis();
  1135. _sensorInit();
  1136. }
  1137. }
  1138. if (_magnitudes.size() == 0) return;
  1139. // Tick hook
  1140. _sensorTick();
  1141. // Check if we should read new data
  1142. static unsigned long last_update = 0;
  1143. static unsigned long report_count = 0;
  1144. static unsigned long save_count = 0;
  1145. if (millis() - last_update > _sensor_read_interval) {
  1146. last_update = millis();
  1147. report_count = (report_count + 1) % _sensor_report_every;
  1148. double current;
  1149. double filtered;
  1150. // Pre-read hook
  1151. _sensorPre();
  1152. // Get the first relay state
  1153. #if SENSOR_POWER_CHECK_STATUS
  1154. bool relay_off = (relayCount() == 1) && (relayStatus(0) == 0);
  1155. #endif
  1156. // Get readings
  1157. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  1158. sensor_magnitude_t magnitude = _magnitudes[i];
  1159. if (magnitude.sensor->status()) {
  1160. // -------------------------------------------------------------
  1161. // Instant value
  1162. // -------------------------------------------------------------
  1163. current = magnitude.sensor->value(magnitude.local);
  1164. // Completely remove spurious values if relay is OFF
  1165. #if SENSOR_POWER_CHECK_STATUS
  1166. if (relay_off) {
  1167. if (magnitude.type == MAGNITUDE_POWER_ACTIVE ||
  1168. magnitude.type == MAGNITUDE_POWER_REACTIVE ||
  1169. magnitude.type == MAGNITUDE_POWER_APPARENT ||
  1170. magnitude.type == MAGNITUDE_CURRENT ||
  1171. magnitude.type == MAGNITUDE_ENERGY_DELTA
  1172. ) {
  1173. current = 0;
  1174. }
  1175. }
  1176. #endif
  1177. // -------------------------------------------------------------
  1178. // Processing (filters)
  1179. // -------------------------------------------------------------
  1180. magnitude.filter->add(current);
  1181. // Special case for MovingAvergaeFilter
  1182. if (MAGNITUDE_COUNT == magnitude.type ||
  1183. MAGNITUDE_GEIGER_CPM ==magnitude. type ||
  1184. MAGNITUDE_GEIGER_SIEVERT == magnitude.type) {
  1185. current = magnitude.filter->result();
  1186. }
  1187. current = _magnitudeProcess(magnitude.type, magnitude.decimals, current);
  1188. _magnitudes[i].current = current;
  1189. // -------------------------------------------------------------
  1190. // Debug
  1191. // -------------------------------------------------------------
  1192. #if SENSOR_DEBUG
  1193. {
  1194. char buffer[64];
  1195. dtostrf(current, 1-sizeof(buffer), magnitude.decimals, buffer);
  1196. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  1197. magnitude.sensor->slot(magnitude.local).c_str(),
  1198. magnitudeTopic(magnitude.type).c_str(),
  1199. buffer,
  1200. magnitudeUnits(magnitude.type).c_str()
  1201. );
  1202. }
  1203. #endif // SENSOR_DEBUG
  1204. // -------------------------------------------------------------
  1205. // Report
  1206. // (we do it every _sensor_report_every readings)
  1207. // -------------------------------------------------------------
  1208. bool report = (0 == report_count);
  1209. if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0)) {
  1210. // for MAGNITUDE_ENERGY, filtered value is last value
  1211. double value = _magnitudeProcess(magnitude.type, magnitude.decimals, current);
  1212. report = (fabs(value - magnitude.reported) >= magnitude.max_change);
  1213. } // if ((MAGNITUDE_ENERGY == magnitude.type) && (magnitude.max_change > 0))
  1214. if (report) {
  1215. filtered = magnitude.filter->result();
  1216. filtered = _magnitudeProcess(magnitude.type, magnitude.decimals, filtered);
  1217. magnitude.filter->reset();
  1218. // Check if there is a minimum change threshold to report
  1219. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  1220. _magnitudes[i].reported = filtered;
  1221. _sensorReport(i, filtered);
  1222. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  1223. // -------------------------------------------------------------
  1224. // Saving to EEPROM
  1225. // (we do it every _sensor_save_every readings)
  1226. // -------------------------------------------------------------
  1227. if (_sensor_save_every > 0) {
  1228. save_count = (save_count + 1) % _sensor_save_every;
  1229. if (0 == save_count) {
  1230. if (MAGNITUDE_ENERGY == magnitude.type) {
  1231. setSetting("eneTotal", current);
  1232. saveSettings();
  1233. }
  1234. } // if (0 == save_count)
  1235. } // if (_sensor_save_every > 0)
  1236. } // if (report_count == 0)
  1237. } // if (magnitude.sensor->status())
  1238. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  1239. // Post-read hook
  1240. _sensorPost();
  1241. #if WEB_SUPPORT
  1242. wsSend(_sensorWebSocketSendData);
  1243. #endif
  1244. #if THINGSPEAK_SUPPORT
  1245. if (report_count == 0) tspkFlush();
  1246. #endif
  1247. }
  1248. }
  1249. #endif // SENSOR_SUPPORT