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.

870 lines
27 KiB

7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 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. unsigned char _counts[MAGNITUDE_MAX];
  25. bool _sensor_realtime = API_REAL_TIME_VALUES;
  26. unsigned long _sensor_read_interval = 1000 * SENSOR_READ_INTERVAL;
  27. unsigned char _sensor_report_every = SENSOR_REPORT_EVERY;
  28. unsigned char _sensor_power_units = SENSOR_POWER_UNITS;
  29. unsigned char _sensor_energy_units = SENSOR_ENERGY_UNITS;
  30. unsigned char _sensor_temperature_units = SENSOR_TEMPERATURE_UNITS;
  31. double _sensor_temperature_correction = SENSOR_TEMPERATURE_CORRECTION;
  32. // -----------------------------------------------------------------------------
  33. // Private
  34. // -----------------------------------------------------------------------------
  35. unsigned char _magnitudeDecimals(unsigned char type) {
  36. // Hardcoded decimals (these should be linked to the unit, instead of the magnitude)
  37. if (type == MAGNITUDE_ENERGY ||
  38. type == MAGNITUDE_ENERGY_DELTA) {
  39. if (_sensor_energy_units == ENERGY_KWH) return 3;
  40. }
  41. if (type == MAGNITUDE_POWER_ACTIVE ||
  42. type == MAGNITUDE_POWER_APPARENT ||
  43. type == MAGNITUDE_POWER_REACTIVE) {
  44. if (_sensor_power_units == POWER_KILOWATTS) return 3;
  45. }
  46. if (type < MAGNITUDE_MAX) return pgm_read_byte(magnitude_decimals + type);
  47. return 0;
  48. }
  49. double _magnitudeProcess(unsigned char type, double value) {
  50. // Hardcoded conversions (these should be linked to the unit, instead of the magnitude)
  51. if (type == MAGNITUDE_TEMPERATURE) {
  52. if (_sensor_temperature_units == TMP_FAHRENHEIT) value = value * 1.8 + 32;
  53. value = value + _sensor_temperature_correction;
  54. }
  55. if (type == MAGNITUDE_ENERGY ||
  56. type == MAGNITUDE_ENERGY_DELTA) {
  57. if (_sensor_energy_units == ENERGY_KWH) value = value / 3600000;
  58. }
  59. if (type == MAGNITUDE_POWER_ACTIVE ||
  60. type == MAGNITUDE_POWER_APPARENT ||
  61. type == MAGNITUDE_POWER_REACTIVE) {
  62. if (_sensor_power_units == POWER_KILOWATTS) value = value / 1000;
  63. }
  64. return roundTo(value, _magnitudeDecimals(type));
  65. }
  66. // -----------------------------------------------------------------------------
  67. #if WEB_SUPPORT
  68. void _sensorWebSocketSendData(JsonObject& root) {
  69. char buffer[10];
  70. bool hasTemperature = false;
  71. JsonArray& list = root.createNestedArray("magnitudes");
  72. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  73. sensor_magnitude_t magnitude = _magnitudes[i];
  74. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  75. dtostrf(magnitude.current, 1-sizeof(buffer), decimals, buffer);
  76. JsonObject& element = list.createNestedObject();
  77. element["index"] = int(magnitude.global);
  78. element["type"] = int(magnitude.type);
  79. element["value"] = String(buffer);
  80. element["units"] = magnitudeUnits(magnitude.type);
  81. element["description"] = magnitude.sensor->slot(magnitude.local);
  82. element["error"] = magnitude.sensor->error();
  83. if (magnitude.type == MAGNITUDE_TEMPERATURE) hasTemperature = true;
  84. }
  85. if (hasTemperature) root["temperatureVisible"] = 1;
  86. }
  87. void _sensorWebSocketStart(JsonObject& root) {
  88. for (unsigned char i=0; i<_sensors.size(); i++) {
  89. BaseSensor * sensor = _sensors[i];
  90. #if EMON_ANALOG_SUPPORT
  91. if (sensor->getID() == SENSOR_EMON_ANALOG_ID) {
  92. root["emonVisible"] = 1;
  93. root["pwrVisible"] = 1;
  94. root["pwrVoltage"] = ((EmonAnalogSensor *) sensor)->getVoltage();
  95. }
  96. #endif
  97. #if HLW8012_SUPPORT
  98. if (sensor->getID() == SENSOR_HLW8012_ID) {
  99. root["hlwVisible"] = 1;
  100. root["pwrVisible"] = 1;
  101. }
  102. #endif
  103. #if V9261F_SUPPORT
  104. if (sensor->getID() == SENSOR_V9261F_ID) {
  105. root["pwrVisible"] = 1;
  106. }
  107. #endif
  108. #if ECH1560_SUPPORT
  109. if (sensor->getID() == SENSOR_ECH1560_ID) {
  110. root["pwrVisible"] = 1;
  111. }
  112. #endif
  113. #if PZEM004T_SUPPORT
  114. if (sensor->getID() == SENSOR_PZEM004T_ID) {
  115. root["pwrVisible"] = 1;
  116. }
  117. #endif
  118. }
  119. if (_magnitudes.size() > 0) {
  120. root["sensorsVisible"] = 1;
  121. //root["apiRealTime"] = _sensor_realtime;
  122. root["powerUnits"] = _sensor_power_units;
  123. root["energyUnits"] = _sensor_energy_units;
  124. root["tmpUnits"] = _sensor_temperature_units;
  125. root["tmpCorrection"] = _sensor_temperature_correction;
  126. root["snsRead"] = _sensor_read_interval / 1000;
  127. root["snsReport"] = _sensor_report_every;
  128. }
  129. /*
  130. // Sensors manifest
  131. JsonArray& manifest = root.createNestedArray("manifest");
  132. #if BMX280_SUPPORT
  133. BMX280Sensor::manifest(manifest);
  134. #endif
  135. // Sensors configuration
  136. JsonArray& sensors = root.createNestedArray("sensors");
  137. for (unsigned char i; i<_sensors.size(); i++) {
  138. JsonObject& sensor = sensors.createNestedObject();
  139. sensor["index"] = i;
  140. sensor["id"] = _sensors[i]->getID();
  141. _sensors[i]->getConfig(sensor);
  142. }
  143. */
  144. }
  145. void _sensorAPISetup() {
  146. for (unsigned char magnitude_id=0; magnitude_id<_magnitudes.size(); magnitude_id++) {
  147. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  148. String topic = magnitudeTopic(magnitude.type);
  149. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) topic = topic + "/" + String(magnitude.global);
  150. apiRegister(topic.c_str(), [magnitude_id](char * buffer, size_t len) {
  151. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  152. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  153. double value = _sensor_realtime ? magnitude.current : magnitude.filtered;
  154. dtostrf(value, 1-len, decimals, buffer);
  155. });
  156. }
  157. }
  158. #endif
  159. #if TERMINAL_SUPPORT
  160. void _sensorInitCommands() {
  161. settingsRegisterCommand(F("MAGNITUDES"), [](Embedis* e) {
  162. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  163. sensor_magnitude_t magnitude = _magnitudes[i];
  164. DEBUG_MSG_P(PSTR("[SENSOR] * %2d: %s @ %s (%s/%d)\n"),
  165. i,
  166. magnitudeTopic(magnitude.type).c_str(),
  167. magnitude.sensor->slot(magnitude.local).c_str(),
  168. magnitudeTopic(magnitude.type).c_str(),
  169. magnitude.global
  170. );
  171. }
  172. DEBUG_MSG_P(PSTR("+OK\n"));
  173. });
  174. }
  175. #endif
  176. void _sensorTick() {
  177. for (unsigned char i=0; i<_sensors.size(); i++) {
  178. _sensors[i]->tick();
  179. }
  180. }
  181. void _sensorPre() {
  182. for (unsigned char i=0; i<_sensors.size(); i++) {
  183. _sensors[i]->pre();
  184. if (!_sensors[i]->status()) {
  185. DEBUG_MSG_P(PSTR("[SENSOR] Error reading data from %s (error: %d)\n"),
  186. _sensors[i]->description().c_str(),
  187. _sensors[i]->error()
  188. );
  189. }
  190. }
  191. }
  192. void _sensorPost() {
  193. for (unsigned char i=0; i<_sensors.size(); i++) {
  194. _sensors[i]->post();
  195. }
  196. }
  197. // -----------------------------------------------------------------------------
  198. // Sensor initialization
  199. // -----------------------------------------------------------------------------
  200. void _sensorInit() {
  201. /*
  202. This is temporal, in the future sensors will be initialized based on
  203. soft configuration (data stored in EEPROM config) so you will be able
  204. to define and configure new sensors on the fly
  205. At the time being, only enabled sensors (those with *_SUPPORT to 1) are being
  206. loaded and initialized here. If you want to add new sensors of the same type
  207. just duplicate the block and change the arguments for the set* methods.
  208. Check the DHT block below for an example
  209. */
  210. #if ANALOG_SUPPORT
  211. {
  212. AnalogSensor * sensor = new AnalogSensor();
  213. _sensors.push_back(sensor);
  214. }
  215. #endif
  216. #if BH1750_SUPPORT
  217. {
  218. BH1750Sensor * sensor = new BH1750Sensor();
  219. sensor->setAddress(BH1750_ADDRESS);
  220. sensor->setMode(BH1750_MODE);
  221. _sensors.push_back(sensor);
  222. }
  223. #endif
  224. #if BMX280_SUPPORT
  225. {
  226. BMX280Sensor * sensor = new BMX280Sensor();
  227. sensor->setAddress(BMX280_ADDRESS);
  228. _sensors.push_back(sensor);
  229. }
  230. #endif
  231. #if DALLAS_SUPPORT
  232. {
  233. DallasSensor * sensor = new DallasSensor();
  234. sensor->setGPIO(DALLAS_PIN);
  235. _sensors.push_back(sensor);
  236. }
  237. #endif
  238. #if DHT_SUPPORT
  239. {
  240. DHTSensor * sensor = new DHTSensor();
  241. sensor->setGPIO(DHT_PIN);
  242. sensor->setType(DHT_TYPE);
  243. _sensors.push_back(sensor);
  244. }
  245. #endif
  246. /*
  247. // Example on how to add a second DHT sensor
  248. // DHT2_PIN and DHT2_TYPE should be defined in sensors.h file
  249. #if DHT_SUPPORT
  250. {
  251. DHTSensor * sensor = new DHTSensor();
  252. sensor->setGPIO(DHT2_PIN);
  253. sensor->setType(DHT2_TYPE);
  254. _sensors.push_back(sensor);
  255. }
  256. #endif
  257. */
  258. #if DIGITAL_SUPPORT
  259. {
  260. DigitalSensor * sensor = new DigitalSensor();
  261. sensor->setGPIO(DIGITAL_PIN);
  262. sensor->setMode(DIGITAL_PIN_MODE);
  263. sensor->setDefault(DIGITAL_DEFAULT_STATE);
  264. _sensors.push_back(sensor);
  265. }
  266. #endif
  267. #if ECH1560_SUPPORT
  268. {
  269. ECH1560Sensor * sensor = new ECH1560Sensor();
  270. sensor->setCLK(ECH1560_CLK_PIN);
  271. sensor->setMISO(ECH1560_MISO_PIN);
  272. sensor->setInverted(ECH1560_INVERTED);
  273. _sensors.push_back(sensor);
  274. }
  275. #endif
  276. #if EMON_ADC121_SUPPORT
  277. {
  278. EmonADC121Sensor * sensor = new EmonADC121Sensor();
  279. sensor->setAddress(EMON_ADC121_I2C_ADDRESS);
  280. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  281. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  282. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  283. _sensors.push_back(sensor);
  284. }
  285. #endif
  286. #if EMON_ADS1X15_SUPPORT
  287. {
  288. EmonADS1X15Sensor * sensor = new EmonADS1X15Sensor();
  289. sensor->setAddress(EMON_ADS1X15_I2C_ADDRESS);
  290. sensor->setType(EMON_ADS1X15_TYPE);
  291. sensor->setMask(EMON_ADS1X15_MASK);
  292. sensor->setGain(EMON_ADS1X15_GAIN);
  293. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  294. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  295. sensor->setCurrentRatio(1, EMON_CURRENT_RATIO);
  296. sensor->setCurrentRatio(2, EMON_CURRENT_RATIO);
  297. sensor->setCurrentRatio(3, EMON_CURRENT_RATIO);
  298. _sensors.push_back(sensor);
  299. }
  300. #endif
  301. #if EMON_ANALOG_SUPPORT
  302. {
  303. EmonAnalogSensor * sensor = new EmonAnalogSensor();
  304. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  305. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  306. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  307. _sensors.push_back(sensor);
  308. }
  309. #endif
  310. #if EVENTS_SUPPORT
  311. {
  312. EventSensor * sensor = new EventSensor();
  313. sensor->setGPIO(EVENTS_PIN);
  314. sensor->setMode(EVENTS_PIN_MODE);
  315. sensor->setDebounceTime(EVENTS_DEBOUNCE);
  316. sensor->setInterruptMode(EVENTS_INTERRUPT_MODE);
  317. _sensors.push_back(sensor);
  318. }
  319. #endif
  320. #if HLW8012_SUPPORT
  321. {
  322. HLW8012Sensor * sensor = new HLW8012Sensor();
  323. sensor->setSEL(HLW8012_SEL_PIN);
  324. sensor->setCF(HLW8012_CF_PIN);
  325. sensor->setCF1(HLW8012_CF1_PIN);
  326. sensor->setSELCurrent(HLW8012_SEL_CURRENT);
  327. _sensors.push_back(sensor);
  328. }
  329. #endif
  330. #if MHZ19_SUPPORT
  331. {
  332. MHZ19Sensor * sensor = new MHZ19Sensor();
  333. sensor->setRX(MHZ19_RX_PIN);
  334. sensor->setTX(MHZ19_TX_PIN);
  335. _sensors.push_back(sensor);
  336. }
  337. #endif
  338. #if PMSX003_SUPPORT
  339. {
  340. PMSX003Sensor * sensor = new PMSX003Sensor();
  341. sensor->setRX(PMS_RX_PIN);
  342. sensor->setTX(PMS_TX_PIN);
  343. _sensors.push_back(sensor);
  344. }
  345. #endif
  346. #if PZEM004T_SUPPORT
  347. {
  348. PZEM004TSensor * sensor = new PZEM004TSensor();
  349. #if PZEM004T_USE_SOFT
  350. sensor->setRX(PZEM004T_RX_PIN);
  351. sensor->setTX(PZEM004T_TX_PIN);
  352. #else
  353. sensor->setSerial(& PZEM004T_HW_PORT);
  354. #endif
  355. _sensors.push_back(sensor);
  356. }
  357. #endif
  358. #if SHT3X_I2C_SUPPORT
  359. {
  360. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  361. sensor->setAddress(SHT3X_I2C_ADDRESS);
  362. _sensors.push_back(sensor);
  363. }
  364. #endif
  365. #if SI7021_SUPPORT
  366. {
  367. SI7021Sensor * sensor = new SI7021Sensor();
  368. sensor->setAddress(SI7021_ADDRESS);
  369. _sensors.push_back(sensor);
  370. }
  371. #endif
  372. #if V9261F_SUPPORT
  373. {
  374. V9261FSensor * sensor = new V9261FSensor();
  375. sensor->setRX(V9261F_PIN);
  376. sensor->setInverted(V9261F_PIN_INVERSE);
  377. _sensors.push_back(sensor);
  378. }
  379. #endif
  380. }
  381. void _sensorCallback(unsigned char i, unsigned char type, const char * payload) {
  382. DEBUG_MSG_P(PSTR("[SENSOR] Sensor #%u callback, type %u, payload: '%s'\n"), i, type, payload);
  383. }
  384. void _sensorConfigure() {
  385. for (unsigned char i=0; i<_sensors.size(); i++) {
  386. #if EMON_ANALOG_SUPPORT
  387. if (_sensors[i]->getID() == SENSOR_EMON_ANALOG_ID) {
  388. double value;
  389. EmonAnalogSensor * sensor = (EmonAnalogSensor *) _sensors[i];
  390. if (value = (getSetting("pwrExpectedP", 0).toInt() == 0)) {
  391. value = getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat();
  392. if (value > 0) sensor->setCurrentRatio(0, value);
  393. } else {
  394. sensor->expectedPower(0, value);
  395. setSetting("pwrRatioC", sensor->getCurrentRatio(0));
  396. }
  397. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  398. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  399. delSetting("pwrRatioC");
  400. }
  401. sensor->setVoltage(getSetting("pwrVoltage", EMON_MAINS_VOLTAGE).toInt());
  402. }
  403. #endif // EMON_ANALOG_SUPPORT
  404. // Force sensor to reload config
  405. _sensors[i]->begin();
  406. // Hook callback
  407. _sensors[i]->onEvent([i](unsigned char type, const char * payload) {
  408. _sensorCallback(i, type, payload);
  409. });
  410. #if HLW8012_SUPPORT
  411. if (_sensors[i]->getID() == SENSOR_HLW8012_ID) {
  412. double value;
  413. HLW8012Sensor * sensor = (HLW8012Sensor *) _sensors[i];
  414. if (value = getSetting("pwrExpectedC", 0).toFloat()) {
  415. sensor->expectedCurrent(value);
  416. setSetting("pwrRatioC", sensor->getCurrentRatio());
  417. } else {
  418. value = getSetting("pwrRatioC", 0).toFloat();
  419. if (value > 0) sensor->setCurrentRatio(value);
  420. }
  421. if (value = getSetting("pwrExpectedV", 0).toInt()) {
  422. sensor->expectedVoltage(value);
  423. setSetting("pwrRatioV", sensor->getVoltageRatio());
  424. } else {
  425. value = getSetting("pwrRatioV", 0).toFloat();
  426. if (value > 0) sensor->setVoltageRatio(value);
  427. }
  428. if (value = getSetting("pwrExpectedP", 0).toInt()) {
  429. sensor->expectedPower(value);
  430. setSetting("pwrRatioP", sensor->getPowerRatio());
  431. } else {
  432. value = getSetting("pwrRatioP", 0).toFloat();
  433. if (value > 0) sensor->setPowerRatio(value);
  434. }
  435. if (getSetting("pwrResetCalibration", 0).toInt() == 1) {
  436. sensor->resetRatios();
  437. delSetting("pwrRatioC");
  438. delSetting("pwrRatioV");
  439. delSetting("pwrRatioP");
  440. }
  441. }
  442. #endif // HLW8012_SUPPORT
  443. }
  444. // General sensor settings
  445. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL).toInt(), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  446. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY).toInt(), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  447. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  448. _sensor_power_units = getSetting("powerUnits", SENSOR_POWER_UNITS).toInt();
  449. _sensor_energy_units = getSetting("energyUnits", SENSOR_ENERGY_UNITS).toInt();
  450. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  451. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  452. // Update filter sizes
  453. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  454. _magnitudes[i].filter->resize(_sensor_report_every);
  455. }
  456. // Save settings
  457. delSetting("pwrExpectedP");
  458. delSetting("pwrExpectedC");
  459. delSetting("pwrExpectedV");
  460. delSetting("pwrResetCalibration");
  461. //saveSettings();
  462. }
  463. void _magnitudesInit() {
  464. for (unsigned char i=0; i<_sensors.size(); i++) {
  465. BaseSensor * sensor = _sensors[i];
  466. DEBUG_MSG_P(PSTR("[SENSOR] %s\n"), sensor->description().c_str());
  467. if (sensor->error() != 0) DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), sensor->error());
  468. for (unsigned char k=0; k<sensor->count(); k++) {
  469. unsigned char type = sensor->type(k);
  470. sensor_magnitude_t new_magnitude;
  471. new_magnitude.sensor = sensor;
  472. new_magnitude.local = k;
  473. new_magnitude.type = type;
  474. new_magnitude.global = _counts[type];
  475. new_magnitude.current = 0;
  476. new_magnitude.filtered = 0;
  477. new_magnitude.reported = 0;
  478. new_magnitude.min_change = 0;
  479. if (type == MAGNITUDE_DIGITAL) {
  480. new_magnitude.filter = new MaxFilter();
  481. } else if (type == MAGNITUDE_EVENTS) {
  482. new_magnitude.filter = new MovingAverageFilter();
  483. } else {
  484. new_magnitude.filter = new MedianFilter();
  485. }
  486. new_magnitude.filter->resize(_sensor_report_every);
  487. _magnitudes.push_back(new_magnitude);
  488. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%d\n"), magnitudeTopic(type).c_str(), _counts[type]);
  489. _counts[type] = _counts[type] + 1;
  490. }
  491. }
  492. }
  493. // -----------------------------------------------------------------------------
  494. // Public
  495. // -----------------------------------------------------------------------------
  496. unsigned char sensorCount() {
  497. return _sensors.size();
  498. }
  499. unsigned char magnitudeCount() {
  500. return _magnitudes.size();
  501. }
  502. String magnitudeName(unsigned char index) {
  503. if (index < _magnitudes.size()) {
  504. sensor_magnitude_t magnitude = _magnitudes[index];
  505. return magnitude.sensor->slot(magnitude.local);
  506. }
  507. return String();
  508. }
  509. unsigned char magnitudeType(unsigned char index) {
  510. if (index < _magnitudes.size()) {
  511. return int(_magnitudes[index].type);
  512. }
  513. return MAGNITUDE_NONE;
  514. }
  515. unsigned char magnitudeIndex(unsigned char index) {
  516. if (index < _magnitudes.size()) {
  517. return int(_magnitudes[index].global);
  518. }
  519. return 0;
  520. }
  521. String magnitudeTopic(unsigned char type) {
  522. char buffer[16] = {0};
  523. if (type < MAGNITUDE_MAX) strncpy_P(buffer, magnitude_topics[type], sizeof(buffer));
  524. return String(buffer);
  525. }
  526. String magnitudeTopicIndex(unsigned char index) {
  527. char topic[32] = {0};
  528. if (index < _magnitudes.size()) {
  529. sensor_magnitude_t magnitude = _magnitudes[index];
  530. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  531. snprintf(topic, sizeof(topic), "%s/%u", magnitudeTopic(magnitude.type).c_str(), magnitude.global);
  532. } else {
  533. snprintf(topic, sizeof(topic), "%s", magnitudeTopic(magnitude.type).c_str());
  534. }
  535. }
  536. return String(topic);
  537. }
  538. String magnitudeUnits(unsigned char type) {
  539. char buffer[8] = {0};
  540. if (type < MAGNITUDE_MAX) {
  541. if ((type == MAGNITUDE_TEMPERATURE) && (_sensor_temperature_units == TMP_FAHRENHEIT)) {
  542. strncpy_P(buffer, magnitude_fahrenheit, sizeof(buffer));
  543. } else if (
  544. (type == MAGNITUDE_ENERGY || type == MAGNITUDE_ENERGY_DELTA) &&
  545. (_sensor_energy_units == ENERGY_KWH)) {
  546. strncpy_P(buffer, magnitude_kwh, sizeof(buffer));
  547. } else if (
  548. (type == MAGNITUDE_POWER_ACTIVE || type == MAGNITUDE_POWER_APPARENT || type == MAGNITUDE_POWER_REACTIVE) &&
  549. (_sensor_power_units == POWER_KILOWATTS)) {
  550. strncpy_P(buffer, magnitude_kw, sizeof(buffer));
  551. } else {
  552. strncpy_P(buffer, magnitude_units[type], sizeof(buffer));
  553. }
  554. }
  555. return String(buffer);
  556. }
  557. // -----------------------------------------------------------------------------
  558. void sensorSetup() {
  559. // Load sensors
  560. _sensorInit();
  561. // Configure stored values
  562. _sensorConfigure();
  563. // Load magnitudes
  564. _magnitudesInit();
  565. #if WEB_SUPPORT
  566. // Websockets
  567. wsOnSendRegister(_sensorWebSocketStart);
  568. wsOnSendRegister(_sensorWebSocketSendData);
  569. wsOnAfterParseRegister(_sensorConfigure);
  570. // API
  571. _sensorAPISetup();
  572. #endif
  573. #if TERMINAL_SUPPORT
  574. _sensorInitCommands();
  575. #endif
  576. // Register loop
  577. espurnaRegisterLoop(sensorLoop);
  578. }
  579. void sensorLoop() {
  580. static unsigned long last_update = 0;
  581. static unsigned long report_count = 0;
  582. if (_magnitudes.size() == 0) return;
  583. // Tick hook
  584. _sensorTick();
  585. // Check if we should read new data
  586. if (millis() - last_update > _sensor_read_interval) {
  587. last_update = millis();
  588. report_count = (report_count + 1) % _sensor_report_every;
  589. double current;
  590. double filtered;
  591. char buffer[64];
  592. // Pre-read hook
  593. _sensorPre();
  594. // Get readings
  595. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  596. sensor_magnitude_t magnitude = _magnitudes[i];
  597. if (magnitude.sensor->status()) {
  598. unsigned char decimals = _magnitudeDecimals(magnitude.type);
  599. current = magnitude.sensor->value(magnitude.local);
  600. magnitude.filter->add(current);
  601. // Special case
  602. if (magnitude.type == MAGNITUDE_EVENTS) current = magnitude.filter->result();
  603. current = _magnitudeProcess(magnitude.type, current);
  604. _magnitudes[i].current = current;
  605. // Debug
  606. #if SENSOR_DEBUG
  607. {
  608. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  609. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  610. magnitude.sensor->slot(magnitude.local).c_str(),
  611. magnitudeTopic(magnitude.type).c_str(),
  612. buffer,
  613. magnitudeUnits(magnitude.type).c_str()
  614. );
  615. }
  616. #endif // SENSOR_DEBUG
  617. // Time to report (we do it every _sensor_report_every readings)
  618. if (report_count == 0) {
  619. filtered = magnitude.filter->result();
  620. magnitude.filter->reset();
  621. filtered = _magnitudeProcess(magnitude.type, filtered);
  622. _magnitudes[i].filtered = filtered;
  623. // Check if there is a minimum change threshold to report
  624. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  625. _magnitudes[i].reported = filtered;
  626. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  627. #if BROKER_SUPPORT
  628. brokerPublish(magnitudeTopic(magnitude.type).c_str(), magnitude.local, buffer);
  629. #endif
  630. #if MQTT_SUPPORT
  631. mqttSend(magnitudeTopicIndex(i).c_str(), buffer);
  632. #if SENSOR_PUBLISH_ADDRESSES
  633. char topic[32];
  634. snprintf(topic, sizeof(topic), "%s/%s", SENSOR_ADDRESS_TOPIC, magnitudeTopic(magnitude.type).c_str());
  635. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  636. mqttSend(topic, magnitude.global, magnitude.sensor->address(magnitude.local).c_str());
  637. } else {
  638. mqttSend(topic, magnitude.sensor->address(magnitude.local).c_str());
  639. }
  640. #endif // SENSOR_PUBLISH_ADDRESSES
  641. #endif // MQTT_SUPPORT
  642. #if INFLUXDB_SUPPORT
  643. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  644. idbSend(magnitudeTopic(magnitude.type).c_str(), magnitude.global, buffer);
  645. } else {
  646. idbSend(magnitudeTopic(magnitude.type).c_str(), buffer);
  647. }
  648. #endif // INFLUXDB_SUPPORT
  649. #if THINGSPEAK_SUPPORT
  650. tspkEnqueueMeasurement(i, buffer);
  651. #endif
  652. #if DOMOTICZ_SUPPORT
  653. {
  654. char key[15];
  655. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), i);
  656. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  657. int status;
  658. if (filtered > 70) {
  659. status = HUMIDITY_WET;
  660. } else if (filtered > 45) {
  661. status = HUMIDITY_COMFORTABLE;
  662. } else if (filtered > 30) {
  663. status = HUMIDITY_NORMAL;
  664. } else {
  665. status = HUMIDITY_DRY;
  666. }
  667. char status_buf[5];
  668. itoa(status, status_buf, 10);
  669. domoticzSend(key, buffer, status_buf);
  670. } else {
  671. domoticzSend(key, 0, buffer);
  672. }
  673. }
  674. #endif // DOMOTICZ_SUPPORT
  675. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  676. } // if (report_count == 0)
  677. } // if (magnitude.sensor->status())
  678. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  679. // Post-read hook
  680. _sensorPost();
  681. #if WEB_SUPPORT
  682. wsSend(_sensorWebSocketSendData);
  683. #endif
  684. #if THINGSPEAK_SUPPORT
  685. if (report_count == 0) tspkFlush();
  686. #endif
  687. }
  688. }
  689. #endif // SENSOR_SUPPORT