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.

1532 lines
50 KiB

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