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.

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