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.

1142 lines
36 KiB

7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
  1. /*
  2. SENSOR MODULE
  3. Copyright (C) 2016-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if SENSOR_SUPPORT
  6. #include <vector>
  7. #include "filters/MaxFilter.h"
  8. #include "filters/MedianFilter.h"
  9. #include "filters/MovingAverageFilter.h"
  10. #include "sensors/BaseSensor.h"
  11. typedef struct {
  12. BaseSensor * sensor; // Sensor object
  13. BaseFilter * filter; // Filter object
  14. unsigned char local; // Local index in its provider
  15. unsigned char type; // Type of measurement
  16. unsigned char global; // Global index in its type
  17. double current; // Current (last) value, unfiltered
  18. double filtered; // Filtered (averaged) value
  19. double reported; // Last reported value
  20. double min_change; // Minimum value change to report
  21. } sensor_magnitude_t;
  22. std::vector<BaseSensor *> _sensors;
  23. std::vector<sensor_magnitude_t> _magnitudes;
  24. bool _sensors_ready = false;
  25. unsigned char _counts[MAGNITUDE_MAX];
  26. bool _sensor_realtime = API_REAL_TIME_VALUES;
  27. unsigned long _sensor_read_interval = 1000 * SENSOR_READ_INTERVAL;
  28. unsigned char _sensor_report_every = SENSOR_REPORT_EVERY;
  29. unsigned char _sensor_power_units = SENSOR_POWER_UNITS;
  30. unsigned char _sensor_energy_units = SENSOR_ENERGY_UNITS;
  31. unsigned char _sensor_temperature_units = SENSOR_TEMPERATURE_UNITS;
  32. double _sensor_temperature_correction = SENSOR_TEMPERATURE_CORRECTION;
  33. double _sensor_humidity_correction = SENSOR_HUMIDITY_CORRECTION;
  34. String _sensor_energy_reset_ts = String();
  35. // -----------------------------------------------------------------------------
  36. // Private
  37. // -----------------------------------------------------------------------------
  38. unsigned char _magnitudeDecimals(unsigned char type) {
  39. // Hardcoded decimals (these should be linked to the unit, instead of the magnitude)
  40. if (type == MAGNITUDE_ENERGY ||
  41. type == MAGNITUDE_ENERGY_DELTA) {
  42. if (_sensor_energy_units == ENERGY_KWH) return 3;
  43. }
  44. if (type == MAGNITUDE_POWER_ACTIVE ||
  45. type == MAGNITUDE_POWER_APPARENT ||
  46. type == MAGNITUDE_POWER_REACTIVE) {
  47. if (_sensor_power_units == POWER_KILOWATTS) return 3;
  48. }
  49. if (type < MAGNITUDE_MAX) return pgm_read_byte(magnitude_decimals + type);
  50. return 0;
  51. }
  52. double _magnitudeProcess(unsigned char type, double value) {
  53. // Hardcoded conversions (these should be linked to the unit, instead of the magnitude)
  54. if (type == MAGNITUDE_TEMPERATURE) {
  55. if (_sensor_temperature_units == TMP_FAHRENHEIT) value = value * 1.8 + 32;
  56. value = value + _sensor_temperature_correction;
  57. }
  58. if (type == MAGNITUDE_HUMIDITY) {
  59. value = constrain(value + _sensor_humidity_correction, 0, 100);
  60. }
  61. if (type == MAGNITUDE_ENERGY ||
  62. type == MAGNITUDE_ENERGY_DELTA) {
  63. if (_sensor_energy_units == ENERGY_KWH) value = value / 3600000;
  64. }
  65. if (type == MAGNITUDE_POWER_ACTIVE ||
  66. type == MAGNITUDE_POWER_APPARENT ||
  67. type == MAGNITUDE_POWER_REACTIVE) {
  68. if (_sensor_power_units == POWER_KILOWATTS) value = value / 1000;
  69. }
  70. return roundTo(value, _magnitudeDecimals(type));
  71. }
  72. // -----------------------------------------------------------------------------
  73. #if WEB_SUPPORT
  74. bool _sensorWebSocketOnReceive(const char * key, JsonVariant& value) {
  75. if (strncmp(key, "pwr", 3) == 0) return true;
  76. if (strncmp(key, "sns", 3) == 0) return true;
  77. if (strncmp(key, "tmp", 3) == 0) return true;
  78. if (strncmp(key, "hum", 3) == 0) return true;
  79. if (strncmp(key, "energy", 6) == 0) return true;
  80. return false;
  81. }
  82. void _sensorWebSocketSendData(JsonObject& root) {
  83. char buffer[10];
  84. bool hasTemperature = false;
  85. bool hasHumidity = false;
  86. JsonArray& list = root.createNestedArray("magnitudes");
  87. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  88. sensor_magnitude_t magnitude = _magnitudes[i];
  89. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  90. dtostrf(magnitude.current, 1-sizeof(buffer), decimals, buffer);
  91. JsonObject& element = list.createNestedObject();
  92. element["index"] = int(magnitude.global);
  93. element["type"] = int(magnitude.type);
  94. element["value"] = String(buffer);
  95. element["units"] = magnitudeUnits(magnitude.type);
  96. element["error"] = magnitude.sensor->error();
  97. if (magnitude.type == MAGNITUDE_ENERGY) {
  98. if (_sensor_energy_reset_ts.length() == 0) _sensorReset();
  99. element["description"] = magnitude.sensor->slot(magnitude.local) + _sensor_energy_reset_ts;
  100. } else {
  101. element["description"] = magnitude.sensor->slot(magnitude.local);
  102. }
  103. if (magnitude.type == MAGNITUDE_TEMPERATURE) hasTemperature = true;
  104. if (magnitude.type == MAGNITUDE_HUMIDITY) hasHumidity = true;
  105. }
  106. if (hasTemperature) root["temperatureVisible"] = 1;
  107. if (hasHumidity) root["humidityVisible"] = 1;
  108. }
  109. void _sensorWebSocketStart(JsonObject& root) {
  110. for (unsigned char i=0; i<_sensors.size(); i++) {
  111. BaseSensor * sensor = _sensors[i];
  112. #if EMON_ANALOG_SUPPORT
  113. if (sensor->getID() == SENSOR_EMON_ANALOG_ID) {
  114. root["emonVisible"] = 1;
  115. root["pwrVisible"] = 1;
  116. root["pwrVoltage"] = ((EmonAnalogSensor *) sensor)->getVoltage();
  117. }
  118. #endif
  119. #if HLW8012_SUPPORT
  120. if (sensor->getID() == SENSOR_HLW8012_ID) {
  121. root["hlwVisible"] = 1;
  122. root["pwrVisible"] = 1;
  123. }
  124. #endif
  125. #if CSE7766_SUPPORT
  126. if (sensor->getID() == SENSOR_CSE7766_ID) {
  127. root["cseVisible"] = 1;
  128. root["pwrVisible"] = 1;
  129. }
  130. #endif
  131. #if V9261F_SUPPORT
  132. if (sensor->getID() == SENSOR_V9261F_ID) {
  133. root["pwrVisible"] = 1;
  134. }
  135. #endif
  136. #if ECH1560_SUPPORT
  137. if (sensor->getID() == SENSOR_ECH1560_ID) {
  138. root["pwrVisible"] = 1;
  139. }
  140. #endif
  141. #if PZEM004T_SUPPORT
  142. if (sensor->getID() == SENSOR_PZEM004T_ID) {
  143. root["pzemVisible"] = 1;
  144. root["pwrVisible"] = 1;
  145. }
  146. #endif
  147. }
  148. if (_magnitudes.size() > 0) {
  149. root["sensorsVisible"] = 1;
  150. //root["apiRealTime"] = _sensor_realtime;
  151. root["pwrUnits"] = _sensor_power_units;
  152. root["energyUnits"] = _sensor_energy_units;
  153. root["tmpUnits"] = _sensor_temperature_units;
  154. root["tmpCorrection"] = _sensor_temperature_correction;
  155. root["humCorrection"] = _sensor_humidity_correction;
  156. root["snsRead"] = _sensor_read_interval / 1000;
  157. root["snsReport"] = _sensor_report_every;
  158. }
  159. /*
  160. // Sensors manifest
  161. JsonArray& manifest = root.createNestedArray("manifest");
  162. #if BMX280_SUPPORT
  163. BMX280Sensor::manifest(manifest);
  164. #endif
  165. // Sensors configuration
  166. JsonArray& sensors = root.createNestedArray("sensors");
  167. for (unsigned char i; i<_sensors.size(); i++) {
  168. JsonObject& sensor = sensors.createNestedObject();
  169. sensor["index"] = i;
  170. sensor["id"] = _sensors[i]->getID();
  171. _sensors[i]->getConfig(sensor);
  172. }
  173. */
  174. }
  175. void _sensorAPISetup() {
  176. for (unsigned char magnitude_id=0; magnitude_id<_magnitudes.size(); magnitude_id++) {
  177. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  178. String topic = magnitudeTopic(magnitude.type);
  179. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) topic = topic + "/" + String(magnitude.global);
  180. apiRegister(topic.c_str(), [magnitude_id](char * buffer, size_t len) {
  181. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  182. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  183. double value = _sensor_realtime ? magnitude.current : magnitude.filtered;
  184. dtostrf(value, 1-len, decimals, buffer);
  185. });
  186. }
  187. }
  188. #endif
  189. #if TERMINAL_SUPPORT
  190. void _sensorInitCommands() {
  191. settingsRegisterCommand(F("MAGNITUDES"), [](Embedis* e) {
  192. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  193. sensor_magnitude_t magnitude = _magnitudes[i];
  194. DEBUG_MSG_P(PSTR("[SENSOR] * %2d: %s @ %s (%s/%d)\n"),
  195. i,
  196. magnitudeTopic(magnitude.type).c_str(),
  197. magnitude.sensor->slot(magnitude.local).c_str(),
  198. magnitudeTopic(magnitude.type).c_str(),
  199. magnitude.global
  200. );
  201. }
  202. DEBUG_MSG_P(PSTR("+OK\n"));
  203. });
  204. }
  205. #endif
  206. void _sensorTick() {
  207. for (unsigned char i=0; i<_sensors.size(); i++) {
  208. _sensors[i]->tick();
  209. }
  210. }
  211. void _sensorPre() {
  212. for (unsigned char i=0; i<_sensors.size(); i++) {
  213. _sensors[i]->pre();
  214. if (!_sensors[i]->status()) {
  215. DEBUG_MSG_P(PSTR("[SENSOR] Error reading data from %s (error: %d)\n"),
  216. _sensors[i]->description().c_str(),
  217. _sensors[i]->error()
  218. );
  219. }
  220. }
  221. }
  222. void _sensorPost() {
  223. for (unsigned char i=0; i<_sensors.size(); i++) {
  224. _sensors[i]->post();
  225. }
  226. }
  227. void _sensorReset() {
  228. #if NTP_SUPPORT
  229. if (ntpSynced()) {
  230. _sensor_energy_reset_ts = String(" (since ") + ntpDateTime() + String(")");
  231. }
  232. #endif
  233. }
  234. // -----------------------------------------------------------------------------
  235. // Sensor initialization
  236. // -----------------------------------------------------------------------------
  237. void _sensorLoad() {
  238. /*
  239. This is temporal, in the future sensors will be initialized based on
  240. soft configuration (data stored in EEPROM config) so you will be able
  241. to define and configure new sensors on the fly
  242. At the time being, only enabled sensors (those with *_SUPPORT to 1) are being
  243. loaded and initialized here. If you want to add new sensors of the same type
  244. just duplicate the block and change the arguments for the set* methods.
  245. Check the DHT block below for an example
  246. */
  247. #if AM2320_SUPPORT
  248. {
  249. AM2320Sensor * sensor = new AM2320Sensor();
  250. sensor->setAddress(AM2320_ADDRESS);
  251. _sensors.push_back(sensor);
  252. }
  253. #endif
  254. #if ANALOG_SUPPORT
  255. {
  256. AnalogSensor * sensor = new AnalogSensor();
  257. sensor->setSamples(ANALOG_SAMPLES);
  258. sensor->setDelay(ANALOG_DELAY);
  259. _sensors.push_back(sensor);
  260. }
  261. #endif
  262. #if BH1750_SUPPORT
  263. {
  264. BH1750Sensor * sensor = new BH1750Sensor();
  265. sensor->setAddress(BH1750_ADDRESS);
  266. sensor->setMode(BH1750_MODE);
  267. _sensors.push_back(sensor);
  268. }
  269. #endif
  270. #if BMX280_SUPPORT
  271. {
  272. BMX280Sensor * sensor = new BMX280Sensor();
  273. sensor->setAddress(BMX280_ADDRESS);
  274. _sensors.push_back(sensor);
  275. }
  276. #endif
  277. #if CSE7766_SUPPORT
  278. {
  279. CSE7766Sensor * sensor = new CSE7766Sensor();
  280. sensor->setRX(CSE7766_PIN);
  281. _sensors.push_back(sensor);
  282. }
  283. #endif
  284. #if DALLAS_SUPPORT
  285. {
  286. DallasSensor * sensor = new DallasSensor();
  287. sensor->setGPIO(DALLAS_PIN);
  288. _sensors.push_back(sensor);
  289. }
  290. #endif
  291. #if DHT_SUPPORT
  292. {
  293. DHTSensor * sensor = new DHTSensor();
  294. sensor->setGPIO(DHT_PIN);
  295. sensor->setType(DHT_TYPE);
  296. _sensors.push_back(sensor);
  297. }
  298. #endif
  299. /*
  300. // Example on how to add a second DHT sensor
  301. // DHT2_PIN and DHT2_TYPE should be defined in sensors.h file
  302. #if DHT_SUPPORT
  303. {
  304. DHTSensor * sensor = new DHTSensor();
  305. sensor->setGPIO(DHT2_PIN);
  306. sensor->setType(DHT2_TYPE);
  307. _sensors.push_back(sensor);
  308. }
  309. #endif
  310. */
  311. #if DIGITAL_SUPPORT
  312. {
  313. DigitalSensor * sensor = new DigitalSensor();
  314. sensor->setGPIO(DIGITAL_PIN);
  315. sensor->setMode(DIGITAL_PIN_MODE);
  316. sensor->setDefault(DIGITAL_DEFAULT_STATE);
  317. _sensors.push_back(sensor);
  318. }
  319. #endif
  320. #if ECH1560_SUPPORT
  321. {
  322. ECH1560Sensor * sensor = new ECH1560Sensor();
  323. sensor->setCLK(ECH1560_CLK_PIN);
  324. sensor->setMISO(ECH1560_MISO_PIN);
  325. sensor->setInverted(ECH1560_INVERTED);
  326. _sensors.push_back(sensor);
  327. }
  328. #endif
  329. #if EMON_ADC121_SUPPORT
  330. {
  331. EmonADC121Sensor * sensor = new EmonADC121Sensor();
  332. sensor->setAddress(EMON_ADC121_I2C_ADDRESS);
  333. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  334. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  335. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  336. _sensors.push_back(sensor);
  337. }
  338. #endif
  339. #if EMON_ADS1X15_SUPPORT
  340. {
  341. EmonADS1X15Sensor * sensor = new EmonADS1X15Sensor();
  342. sensor->setAddress(EMON_ADS1X15_I2C_ADDRESS);
  343. sensor->setType(EMON_ADS1X15_TYPE);
  344. sensor->setMask(EMON_ADS1X15_MASK);
  345. sensor->setGain(EMON_ADS1X15_GAIN);
  346. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  347. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  348. sensor->setCurrentRatio(1, EMON_CURRENT_RATIO);
  349. sensor->setCurrentRatio(2, EMON_CURRENT_RATIO);
  350. sensor->setCurrentRatio(3, EMON_CURRENT_RATIO);
  351. _sensors.push_back(sensor);
  352. }
  353. #endif
  354. #if EMON_ANALOG_SUPPORT
  355. {
  356. EmonAnalogSensor * sensor = new EmonAnalogSensor();
  357. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  358. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  359. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  360. _sensors.push_back(sensor);
  361. }
  362. #endif
  363. #if EVENTS_SUPPORT
  364. {
  365. EventSensor * sensor = new EventSensor();
  366. sensor->setGPIO(EVENTS_PIN);
  367. sensor->setMode(EVENTS_PIN_MODE);
  368. sensor->setDebounceTime(EVENTS_DEBOUNCE);
  369. sensor->setInterruptMode(EVENTS_INTERRUPT_MODE);
  370. _sensors.push_back(sensor);
  371. }
  372. #endif
  373. #if GEIGER_SUPPORT
  374. {
  375. GeigerSensor * sensor = new GeigerSensor(); // Create instance of thr Geiger module.
  376. sensor->setGPIO(GEIGER_PIN); // Interrupt pin of the attached geiger counter board.
  377. sensor->setMode(GEIGER_PIN_MODE); // This pin is an input.
  378. sensor->setDebounceTime(GEIGER_DEBOUNCE); // Debounce time 25ms, because https://github.com/Trickx/espurna/wiki/Geiger-counter
  379. sensor->setInterruptMode(GEIGER_INTERRUPT_MODE); // Interrupt triggering: edge detection rising.
  380. sensor->setCPM2SievertFactor(GEIGER_CPM2SIEVERT); // Conversion factor from counts per minute to µSv/h
  381. _sensors.push_back(sensor);
  382. }
  383. #endif
  384. #if GUVAS12SD_SUPPORT
  385. {
  386. GUVAS12SDSensor * sensor = new GUVAS12SDSensor();
  387. sensor->setGPIO(GUVAS12SD_PIN);
  388. _sensors.push_back(sensor);
  389. }
  390. #endif
  391. #if HCSR04_SUPPORT
  392. {
  393. HCSR04Sensor * sensor = new HCSR04Sensor();
  394. sensor->setTrigger(HCSR04_TRIGGER);
  395. sensor->setEcho(HCSR04_ECHO);
  396. _sensors.push_back(sensor);
  397. }
  398. #endif
  399. #if HLW8012_SUPPORT
  400. {
  401. HLW8012Sensor * sensor = new HLW8012Sensor();
  402. sensor->setSEL(HLW8012_SEL_PIN);
  403. sensor->setCF(HLW8012_CF_PIN);
  404. sensor->setCF1(HLW8012_CF1_PIN);
  405. sensor->setSELCurrent(HLW8012_SEL_CURRENT);
  406. _sensors.push_back(sensor);
  407. }
  408. #endif
  409. #if MHZ19_SUPPORT
  410. {
  411. MHZ19Sensor * sensor = new MHZ19Sensor();
  412. sensor->setRX(MHZ19_RX_PIN);
  413. sensor->setTX(MHZ19_TX_PIN);
  414. _sensors.push_back(sensor);
  415. }
  416. #endif
  417. #if NTC_SUPPORT
  418. {
  419. NTCSensor * sensor = new NTCSensor();
  420. sensor->setSamples(NTC_SAMPLES);
  421. sensor->setDelay(NTC_DELAY);
  422. sensor->setUpstreamResistor(NTC_R_UP);
  423. sensor->setDownstreamResistor(NTC_R_DOWN);
  424. sensor->setBeta(NTC_BETA);
  425. sensor->setR0(NTC_R0);
  426. sensor->setT0(NTC_T0);
  427. _sensors.push_back(sensor);
  428. }
  429. #endif
  430. #if SENSEAIR_SUPPORT
  431. {
  432. SenseAirSensor * sensor = new SenseAirSensor();
  433. sensor->setRX(SENSEAIR_RX_PIN);
  434. sensor->setTX(SENSEAIR_TX_PIN);
  435. _sensors.push_back(sensor);
  436. }
  437. #endif
  438. #if PMSX003_SUPPORT
  439. {
  440. PMSX003Sensor * sensor = new PMSX003Sensor();
  441. sensor->setRX(PMS_RX_PIN);
  442. sensor->setTX(PMS_TX_PIN);
  443. sensor->setType(PMS_TYPE);
  444. _sensors.push_back(sensor);
  445. }
  446. #endif
  447. #if PZEM004T_SUPPORT
  448. {
  449. PZEM004TSensor * sensor = new PZEM004TSensor();
  450. #if PZEM004T_USE_SOFT
  451. sensor->setRX(PZEM004T_RX_PIN);
  452. sensor->setTX(PZEM004T_TX_PIN);
  453. #else
  454. sensor->setSerial(& PZEM004T_HW_PORT);
  455. #endif
  456. _sensors.push_back(sensor);
  457. }
  458. #endif
  459. #if SHT3X_I2C_SUPPORT
  460. {
  461. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  462. sensor->setAddress(SHT3X_I2C_ADDRESS);
  463. _sensors.push_back(sensor);
  464. }
  465. #endif
  466. #if SI7021_SUPPORT
  467. {
  468. SI7021Sensor * sensor = new SI7021Sensor();
  469. sensor->setAddress(SI7021_ADDRESS);
  470. _sensors.push_back(sensor);
  471. }
  472. #endif
  473. #if TMP3X_SUPPORT
  474. {
  475. TMP3XSensor * sensor = new TMP3XSensor();
  476. sensor->setType(TMP3X_TYPE);
  477. _sensors.push_back(sensor);
  478. }
  479. #endif
  480. #if V9261F_SUPPORT
  481. {
  482. V9261FSensor * sensor = new V9261FSensor();
  483. sensor->setRX(V9261F_PIN);
  484. sensor->setInverted(V9261F_PIN_INVERSE);
  485. _sensors.push_back(sensor);
  486. }
  487. #endif
  488. }
  489. void _sensorCallback(unsigned char i, unsigned char type, const char * payload) {
  490. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, payload);
  491. }
  492. void _sensorInit() {
  493. _sensors_ready = true;
  494. for (unsigned char i=0; i<_sensors.size(); i++) {
  495. // Do not process an already initialized sensor
  496. if (_sensors[i]->ready()) continue;
  497. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), _sensors[i]->description().c_str());
  498. // Force sensor to reload config
  499. _sensors[i]->begin();
  500. if (!_sensors[i]->ready()) {
  501. if (_sensors[i]->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), _sensors[i]->error());
  502. _sensors_ready = false;
  503. continue;
  504. }
  505. // Initialize magnitudes
  506. for (unsigned char k=0; k<_sensors[i]->count(); k++) {
  507. unsigned char type = _sensors[i]->type(k);
  508. sensor_magnitude_t new_magnitude;
  509. new_magnitude.sensor = _sensors[i];
  510. new_magnitude.local = k;
  511. new_magnitude.type = type;
  512. new_magnitude.global = _counts[type];
  513. new_magnitude.current = 0;
  514. new_magnitude.filtered = 0;
  515. new_magnitude.reported = 0;
  516. new_magnitude.min_change = 0;
  517. if (type == MAGNITUDE_DIGITAL) {
  518. new_magnitude.filter = new MaxFilter();
  519. } else if (type == MAGNITUDE_EVENTS || type == MAGNITUDE_GEIGER_CPM|| type == MAGNITUDE_GEIGER_SIEVERT) { // For geiger counting moving average filter is the most appropriate if needed at all.
  520. new_magnitude.filter = new MovingAverageFilter();
  521. } else {
  522. new_magnitude.filter = new MedianFilter();
  523. }
  524. new_magnitude.filter->resize(_sensor_report_every);
  525. _magnitudes.push_back(new_magnitude);
  526. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  527. _counts[type] = _counts[type] + 1;
  528. }
  529. // Hook callback
  530. _sensors[i]->onEvent([i](unsigned char type, const char * payload) {
  531. _sensorCallback(i, type, payload);
  532. });
  533. // Custom initializations
  534. #if EMON_ANALOG_SUPPORT
  535. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  536. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  537. sensor->setCurrentRatio(0, getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat());
  538. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  539. }
  540. #endif // EMON_ANALOG_SUPPORT
  541. #if HLW8012_SUPPORT
  542. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  543. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  544. double value;
  545. value = getSetting("pwrRatioC", HLW8012_CURRENT_RATIO).toFloat();
  546. if (value > 0) sensor->setCurrentRatio(value);
  547. value = getSetting("pwrRatioV", HLW8012_VOLTAGE_RATIO).toFloat();
  548. if (value > 0) sensor->setVoltageRatio(value);
  549. value = getSetting("pwrRatioP", HLW8012_POWER_RATIO).toFloat();
  550. if (value > 0) sensor->setPowerRatio(value);
  551. }
  552. #endif // HLW8012_SUPPORT
  553. #if CSE7766_SUPPORT
  554. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  555. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  556. double value;
  557. value = getSetting("pwrRatioC", 0).toFloat();
  558. if (value > 0) sensor->setCurrentRatio(value);
  559. value = getSetting("pwrRatioV", 0).toFloat();
  560. if (value > 0) sensor->setVoltageRatio(value);
  561. value = getSetting("pwrRatioP", 0).toFloat();
  562. if (value > 0) sensor->setPowerRatio(value);
  563. }
  564. #endif // CSE7766_SUPPORT
  565. }
  566. }
  567. void _sensorConfigure() {
  568. // General sensor settings
  569. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  570. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  571. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  572. _sensor_power_units = getSetting("pwrUnits", SENSOR_POWER_UNITS).toInt();
  573. _sensor_energy_units = getSetting("energyUnits", SENSOR_ENERGY_UNITS).toInt();
  574. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  575. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  576. _sensor_humidity_correction = getSetting("humCorrection", SENSOR_HUMIDITY_CORRECTION).toFloat();
  577. // Specific sensor settings
  578. for (unsigned char i=0; i<_sensors.size(); i++) {
  579. #if EMON_ANALOG_SUPPORT
  580. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  581. double value;
  582. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  583. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  584. sensor->expectedPower(0, value);
  585. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  586. }
  587. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  588. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  589. delSetting("pwrRatioC");
  590. }
  591. if (getSetting("pwrResetE", 0).toInt() == 1) {
  592. sensor->resetEnergy();
  593. _sensorReset();
  594. }
  595. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  596. }
  597. #endif // EMON_ANALOG_SUPPORT
  598. #if EMON_ADC121_SUPPORT
  599. if (_sensors[i]->getID() == SENSOR_EMON_ADC121_ID) {
  600. EmonADC121Sensor * sensor = (EmonADC121Sensor *) _sensors[i];
  601. if (getSetting("pwrResetE", 0).toInt() == 1) {
  602. sensor->resetEnergy();
  603. _sensorReset();
  604. }
  605. }
  606. #endif
  607. #if EMON_ADS1X15_SUPPORT
  608. if (_sensors[i]->getID() == SENSOR_EMON_ADS1X15_ID) {
  609. EmonADS1X15Sensor * sensor = (EmonADS1X15Sensor *) _sensors[i];
  610. if (getSetting("pwrResetE", 0).toInt() == 1) {
  611. sensor->resetEnergy();
  612. _sensorReset();
  613. }
  614. }
  615. #endif
  616. #if HLW8012_SUPPORT
  617. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  618. double value;
  619. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  620. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  621. sensor->expectedCurrent(value);
  622. setSetting("pwrRatioC", sensor->getCurrentRatio());
  623. }
  624. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  625. sensor->expectedVoltage(value);
  626. setSetting("pwrRatioV", sensor->getVoltageRatio());
  627. }
  628. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  629. sensor->expectedPower(value);
  630. setSetting("pwrRatioP", sensor->getPowerRatio());
  631. }
  632. if (getSetting("pwrResetE", 0).toInt() == 1) {
  633. sensor->resetEnergy();
  634. _sensorReset();
  635. }
  636. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  637. sensor->resetRatios();
  638. delSetting("pwrRatioC");
  639. delSetting("pwrRatioV");
  640. delSetting("pwrRatioP");
  641. }
  642. }
  643. #endif // HLW8012_SUPPORT
  644. #if CSE7766_SUPPORT
  645. if (_sensors[i]->getID() == SENSOR_CSE7766_ID) {
  646. double value;
  647. CSE7766Sensor * sensor = (CSE7766Sensor *) _sensors[i];
  648. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  649. sensor->expectedCurrent(value);
  650. setSetting("pwrRatioC", sensor->getCurrentRatio());
  651. }
  652. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  653. sensor->expectedVoltage(value);
  654. setSetting("pwrRatioV", sensor->getVoltageRatio());
  655. }
  656. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  657. sensor->expectedPower(value);
  658. setSetting("pwrRatioP", sensor->getPowerRatio());
  659. }
  660. if (getSetting("pwrResetE", 0).toInt() == 1) {
  661. sensor->resetEnergy();
  662. _sensorReset();
  663. }
  664. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  665. sensor->resetRatios();
  666. delSetting("pwrRatioC");
  667. delSetting("pwrRatioV");
  668. delSetting("pwrRatioP");
  669. }
  670. }
  671. #endif // CSE7766_SUPPORT
  672. }
  673. // Update filter sizes
  674. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  675. _magnitudes[i].filter->resize(_sensor_report_every);
  676. }
  677. // Save settings
  678. delSetting("pwrExpectedP");
  679. delSetting("pwrExpectedC");
  680. delSetting("pwrExpectedV");
  681. delSetting("pwrResetCalibration");
  682. delSetting("pwrResetE");
  683. saveSettings();
  684. }
  685. // -----------------------------------------------------------------------------
  686. // Public
  687. // -----------------------------------------------------------------------------
  688. unsigned char sensorCount() {
  689. return _sensors.size();
  690. }
  691. unsigned char magnitudeCount() {
  692. return _magnitudes.size();
  693. }
  694. String magnitudeName(unsigned char index) {
  695. if (index < _magnitudes.size()) {
  696. sensor_magnitude_t magnitude = _magnitudes[index];
  697. return magnitude.sensor->slot(magnitude.local);
  698. }
  699. return String();
  700. }
  701. unsigned char magnitudeType(unsigned char index) {
  702. if (index < _magnitudes.size()) {
  703. return int(_magnitudes[index].type);
  704. }
  705. return MAGNITUDE_NONE;
  706. }
  707. unsigned char magnitudeIndex(unsigned char index) {
  708. if (index < _magnitudes.size()) {
  709. return int(_magnitudes[index].global);
  710. }
  711. return 0;
  712. }
  713. String magnitudeTopic(unsigned char type) {
  714. char buffer[16] = {0};
  715. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  716. return String(buffer);
  717. }
  718. String magnitudeTopicIndex(unsigned char index) {
  719. char topic[32] = {0};
  720. if (index < _magnitudes.size()) {
  721. sensor_magnitude_t magnitude = _magnitudes[index];
  722. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  723. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  724. } else {
  725. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  726. }
  727. }
  728. return String(topic);
  729. }
  730. String magnitudeUnits(unsigned char type) {
  731. char buffer[8] = {0};
  732. if (type < MAGNITUDE_MAX) {
  733. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  734. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  735. } else if (
  736. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  737. (_sensor_energy_units == ENERGY_KWH)) {
  738. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  739. } else if (
  740. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  741. (_sensor_power_units == POWER_KILOWATTS)) {
  742. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  743. } else {
  744. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  745. }
  746. }
  747. return String(buffer);
  748. }
  749. // -----------------------------------------------------------------------------
  750. void sensorSetup() {
  751. // Backwards compatibility
  752. moveSetting("powerUnits", "pwrUnits");
  753. // Load sensors
  754. _sensorLoad();
  755. _sensorInit();
  756. // Configure stored values
  757. _sensorConfigure();
  758. #if WEB_SUPPORT
  759. // Websockets
  760. wsOnSendRegister(_sensorWebSocketStart);
  761. wsOnReceiveRegister(_sensorWebSocketOnReceive);
  762. wsOnSendRegister(_sensorWebSocketSendData);
  763. wsOnAfterParseRegister(_sensorConfigure);
  764. // API
  765. _sensorAPISetup();
  766. #endif
  767. #if TERMINAL_SUPPORT
  768. _sensorInitCommands();
  769. #endif
  770. // Register loop
  771. espurnaRegisterLoop(sensorLoop);
  772. }
  773. void sensorLoop() {
  774. // Check if we still have uninitialized sensors
  775. static unsigned long last_init = 0;
  776. if (!_sensors_ready) {
  777. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  778. last_init = millis();
  779. _sensorInit();
  780. }
  781. }
  782. if (_magnitudes.size() == 0) return;
  783. // Tick hook
  784. _sensorTick();
  785. // Check if we should read new data
  786. static unsigned long last_update = 0;
  787. static unsigned long report_count = 0;
  788. if (millis() - last_update > _sensor_read_interval) {
  789. last_update = millis();
  790. report_count = (report_count + 1) % _sensor_report_every;
  791. double current;
  792. double filtered;
  793. char buffer[64];
  794. // Pre-read hook
  795. _sensorPre();
  796. // Get the first relay state
  797. #if SENSOR_POWER_CHECK_STATUS
  798. bool relay_off = (relayCount() > 0) && (relayStatus(0) == 0);
  799. #endif
  800. // Get readings
  801. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  802. sensor_magnitude_t magnitude = _magnitudes[i];
  803. if (magnitude.sensor->status()) {
  804. current = magnitude.sensor->value(magnitude.local);
  805. // Completely remove spurious values if relay is OFF
  806. #if SENSOR_POWER_CHECK_STATUS
  807. if (relay_off) {
  808. if (magnitude.type == MAGNITUDE_POWER_ACTIVE ||
  809. magnitude.type == MAGNITUDE_POWER_REACTIVE ||
  810. magnitude.type == MAGNITUDE_POWER_APPARENT ||
  811. magnitude.type == MAGNITUDE_CURRENT ||
  812. magnitude.type == MAGNITUDE_ENERGY_DELTA
  813. ) {
  814. current = 0;
  815. }
  816. }
  817. #endif
  818. magnitude.filter->add(current);
  819. // Special case
  820. if (magnitude.type == MAGNITUDE_EVENTS) {
  821. current = magnitude.filter->result();
  822. }
  823. current = _magnitudeProcess(magnitude.type, current);
  824. _magnitudes[i].current = current;
  825. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  826. // Debug
  827. #if SENSOR_DEBUG
  828. {
  829. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  830. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  831. magnitude.sensor->slot(magnitude.local).c_str(),
  832. magnitudeTopic(magnitude.type).c_str(),
  833. buffer,
  834. magnitudeUnits(magnitude.type).c_str()
  835. );
  836. }
  837. #endif // SENSOR_DEBUG
  838. // Time to report (we do it every _sensor_report_every readings)
  839. if (report_count == 0) {
  840. filtered = magnitude.filter->result();
  841. magnitude.filter->reset();
  842. filtered = _magnitudeProcess(magnitude.type, filtered);
  843. _magnitudes[i].filtered = filtered;
  844. // Check if there is a minimum change threshold to report
  845. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  846. _magnitudes[i].reported = filtered;
  847. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  848. #if BROKER_SUPPORT
  849. brokerPublish(magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  850. #endif
  851. #if MQTT_SUPPORT
  852. mqttSend(magnitudeTopicIndex(i).c_str(), buffer);
  853. #if SENSOR_PUBLISH_ADDRESSES
  854. char topic[32];
  855. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  856. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  857. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  858. } else {
  859. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  860. }
  861. #endif // SENSOR_PUBLISH_ADDRESSES
  862. #endif // MQTT_SUPPORT
  863. #if INFLUXDB_SUPPORT
  864. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  865. idbSend(magnitudeTopic(magnitude.type).c_str(), magnitude.global, buffer);
  866. } else {
  867. idbSend(magnitudeTopic(magnitude.type).c_str(), buffer);
  868. }
  869. #endif // INFLUXDB_SUPPORT
  870. #if THINGSPEAK_SUPPORT
  871. tspkEnqueueMeasurement(i, buffer);
  872. #endif
  873. #if DOMOTICZ_SUPPORT
  874. {
  875. char key[15];
  876. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), i);
  877. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  878. int status;
  879. if (filtered > 70) {
  880. status = HUMIDITY_WET;
  881. } else if (filtered > 45) {
  882. status = HUMIDITY_COMFORTABLE;
  883. } else if (filtered > 30) {
  884. status = HUMIDITY_NORMAL;
  885. } else {
  886. status = HUMIDITY_DRY;
  887. }
  888. char status_buf[5];
  889. itoa(status, status_buf, 10);
  890. domoticzSend(key, buffer, status_buf);
  891. } else {
  892. domoticzSend(key, 0, buffer);
  893. }
  894. }
  895. #endif // DOMOTICZ_SUPPORT
  896. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  897. } // if (report_count == 0)
  898. } // if (magnitude.sensor->status())
  899. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  900. // Post-read hook
  901. _sensorPost();
  902. #if WEB_SUPPORT
  903. wsSend(_sensorWebSocketSendData);
  904. #endif
  905. #if THINGSPEAK_SUPPORT
  906. if (report_count == 0) tspkFlush();
  907. #endif
  908. }
  909. }
  910. #endif // SENSOR_SUPPORT