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.

528 lines
18 KiB

7 years ago
  1. /*
  2. SENSOR MODULE
  3. Copyright (C) 2016-2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include <vector>
  6. #include "filters/MaxFilter.h"
  7. #include "filters/MedianFilter.h"
  8. #include "filters/MovingAverageFilter.h"
  9. #include "sensors/BaseSensor.h"
  10. typedef struct {
  11. BaseSensor * sensor;
  12. unsigned char local; // Local index in its provider
  13. magnitude_t type; // Type of measurement
  14. unsigned char global; // Global index in its type
  15. double current; // Current (last) value, unfiltered
  16. double filtered; // Filtered (averaged) value
  17. double reported; // Last reported value
  18. double min_change; // Minimum value change to report
  19. BaseFilter * filter; // Filter object
  20. } sensor_magnitude_t;
  21. std::vector<BaseSensor *> _sensors;
  22. std::vector<sensor_magnitude_t> _magnitudes;
  23. unsigned char _counts[MAGNITUDE_MAX];
  24. bool _sensor_realtime = API_REAL_TIME_VALUES;
  25. unsigned char _sensor_temperature_units = SENSOR_TEMPERATURE_UNITS;
  26. double _sensor_temperature_correction = SENSOR_TEMPERATURE_CORRECTION;
  27. // -----------------------------------------------------------------------------
  28. // Private
  29. // -----------------------------------------------------------------------------
  30. String _sensorTopic(magnitude_t type) {
  31. if (type == MAGNITUDE_TEMPERATURE) return String(SENSOR_TEMPERATURE_TOPIC);
  32. if (type == MAGNITUDE_HUMIDITY) return String(SENSOR_HUMIDITY_TOPIC);
  33. if (type == MAGNITUDE_PRESSURE) return String(SENSOR_PRESSURE_TOPIC);
  34. if (type == MAGNITUDE_CURRENT) return String(SENSOR_CURRENT_TOPIC);
  35. if (type == MAGNITUDE_VOLTAGE) return String(SENSOR_VOLTAGE_TOPIC);
  36. if (type == MAGNITUDE_POWER_ACTIVE) return String(SENSOR_ACTIVE_POWER_TOPIC);
  37. if (type == MAGNITUDE_POWER_APPARENT) return String(SENSOR_APPARENT_POWER_TOPIC);
  38. if (type == MAGNITUDE_POWER_REACTIVE) return String(SENSOR_REACTIVE_POWER_TOPIC);
  39. if (type == MAGNITUDE_POWER_FACTOR) return String(SENSOR_POWER_FACTOR_TOPIC);
  40. if (type == MAGNITUDE_ENERGY) return String(SENSOR_ENERGY_TOPIC);
  41. if (type == MAGNITUDE_ENERGY_DELTA) return String(SENSOR_ENERGY_DELTA_TOPIC);
  42. if (type == MAGNITUDE_ANALOG) return String(SENSOR_ANALOG_TOPIC);
  43. if (type == MAGNITUDE_DIGITAL) return String(SENSOR_DIGITAL_TOPIC);
  44. if (type == MAGNITUDE_EVENTS) return String(SENSOR_EVENTS_TOPIC);
  45. if (type == MAGNITUDE_PM1dot0) return String(SENSOR_PM1dot0_TOPIC);
  46. if (type == MAGNITUDE_PM2dot5) return String(SENSOR_PM2dot5_TOPIC);
  47. if (type == MAGNITUDE_PM10) return String(SENSOR_PM10_TOPIC);
  48. if (type == MAGNITUDE_CO2) return String(SENSOR_CO2_TOPIC);
  49. return String(SENSOR_UNKNOWN_TOPIC);
  50. }
  51. unsigned char _sensorDecimals(magnitude_t type) {
  52. if (type == MAGNITUDE_TEMPERATURE) return SENSOR_TEMPERATURE_DECIMALS;
  53. if (type == MAGNITUDE_HUMIDITY) return SENSOR_HUMIDITY_DECIMALS;
  54. if (type == MAGNITUDE_PRESSURE) return SENSOR_PRESSURE_DECIMALS;
  55. if (type == MAGNITUDE_CURRENT) return SENSOR_CURRENT_DECIMALS;
  56. if (type == MAGNITUDE_VOLTAGE) return SENSOR_VOLTAGE_DECIMALS;
  57. if (type == MAGNITUDE_POWER_ACTIVE) return SENSOR_POWER_DECIMALS;
  58. if (type == MAGNITUDE_POWER_APPARENT) return SENSOR_POWER_DECIMALS;
  59. if (type == MAGNITUDE_POWER_REACTIVE) return SENSOR_POWER_DECIMALS;
  60. if (type == MAGNITUDE_POWER_FACTOR) return SENSOR_POWER_FACTOR_DECIMALS;
  61. if (type == MAGNITUDE_ENERGY) return SENSOR_ENERGY_DECIMALS;
  62. if (type == MAGNITUDE_ENERGY_DELTA) return SENSOR_ENERGY_DECIMALS;
  63. if (type == MAGNITUDE_ANALOG) return SENSOR_ANALOG_DECIMALS;
  64. if (type == MAGNITUDE_EVENTS) return SENSOR_EVENTS_DECIMALS;
  65. if (type == MAGNITUDE_PM1dot0) return SENSOR_PM1dot0_DECIMALS;
  66. if (type == MAGNITUDE_PM2dot5) return SENSOR_PM2dot5_DECIMALS;
  67. if (type == MAGNITUDE_PM10) return SENSOR_PM10_DECIMALS;
  68. if (type == MAGNITUDE_CO2) return SENSOR_CO2_DECIMALS;
  69. return 0;
  70. }
  71. String _sensorUnits(magnitude_t type) {
  72. if (type == MAGNITUDE_TEMPERATURE) return (_sensor_temperature_units == TMP_CELSIUS) ? String("C") : String("F");
  73. if (type == MAGNITUDE_HUMIDITY) return String("%");
  74. if (type == MAGNITUDE_PRESSURE) return String("hPa");
  75. if (type == MAGNITUDE_CURRENT) return String("A");
  76. if (type == MAGNITUDE_VOLTAGE) return String("V");
  77. if (type == MAGNITUDE_POWER_ACTIVE) return String("W");
  78. if (type == MAGNITUDE_POWER_APPARENT) return String("W");
  79. if (type == MAGNITUDE_POWER_REACTIVE) return String("W");
  80. if (type == MAGNITUDE_POWER_FACTOR) return String("%");
  81. if (type == MAGNITUDE_ENERGY) return String("J");
  82. if (type == MAGNITUDE_ENERGY_DELTA) return String("J");
  83. if (type == MAGNITUDE_EVENTS) return String("/min");
  84. if (type == MAGNITUDE_PM1dot0) return String("µg/m3");
  85. if (type == MAGNITUDE_PM2dot5) return String("µg/m3");
  86. if (type == MAGNITUDE_PM10) return String("µg/m3");
  87. if (type == MAGNITUDE_CO2) return String("ppm");
  88. return String();
  89. }
  90. double _sensorProcess(magnitude_t type, double value) {
  91. if (type == MAGNITUDE_TEMPERATURE) {
  92. if (_sensor_temperature_units == TMP_FAHRENHEIT) value = value * 1.8 + 32;
  93. value = value + _sensor_temperature_correction;
  94. }
  95. return roundTo(value, _sensorDecimals(type));
  96. }
  97. void _sensorConfigure() {
  98. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  99. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  100. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  101. }
  102. #if WEB_SUPPORT
  103. void _sensorWebSocketOnSend(JsonObject& root) {
  104. char buffer[10];
  105. bool hasTemperature = false;
  106. JsonArray& list = root.createNestedArray("magnitudes");
  107. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  108. sensor_magnitude_t magnitude = _magnitudes[i];
  109. unsigned char decimals = _sensorDecimals(magnitude.type);
  110. dtostrf(magnitude.current, 1-sizeof(buffer), decimals, buffer);
  111. JsonObject& element = list.createNestedObject();
  112. element["type"] = int(magnitude.type);
  113. element["value"] = String(buffer);
  114. element["units"] = _sensorUnits(magnitude.type);
  115. element["description"] = magnitude.sensor->slot(magnitude.local);
  116. element["error"] = magnitude.sensor->error();
  117. if (magnitude.type == MAGNITUDE_TEMPERATURE) hasTemperature = true;
  118. }
  119. //root["apiRealTime"] = _sensor_realtime;
  120. root["tmpUnits"] = _sensor_temperature_units;
  121. root["tmpCorrection"] = _sensor_temperature_correction;
  122. if (hasTemperature) root["temperatureVisible"] = 1;
  123. }
  124. void _sensorAPISetup() {
  125. for (unsigned char magnitude_id=0; magnitude_id<_magnitudes.size(); magnitude_id++) {
  126. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  127. String topic = _sensorTopic(magnitude.type);
  128. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) topic = topic + "/" + String(magnitude.global);
  129. apiRegister(topic.c_str(), topic.c_str(), [magnitude_id](char * buffer, size_t len) {
  130. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  131. unsigned char decimals = _sensorDecimals(magnitude.type);
  132. double value = _sensor_realtime ? magnitude.current : magnitude.filtered;
  133. dtostrf(value, 1-len, decimals, buffer);
  134. });
  135. }
  136. }
  137. #endif
  138. void _sensorTick() {
  139. for (unsigned char i=0; i<_sensors.size(); i++) {
  140. _sensors[i]->tick();
  141. }
  142. }
  143. void _sensorPre() {
  144. for (unsigned char i=0; i<_sensors.size(); i++) {
  145. _sensors[i]->pre();
  146. if (!_sensors[i]->status()) {
  147. DEBUG_MSG("[SENSOR] Error reading data from %s (error: %d)\n",
  148. _sensors[i]->name().c_str(),
  149. _sensors[i]->error()
  150. );
  151. }
  152. }
  153. }
  154. void _sensorPost() {
  155. for (unsigned char i=0; i<_sensors.size(); i++) {
  156. _sensors[i]->post();
  157. }
  158. }
  159. // -----------------------------------------------------------------------------
  160. // Sensor initialization
  161. // -----------------------------------------------------------------------------
  162. void _sensorRegister(BaseSensor * sensor) {
  163. sensor->begin();
  164. _sensors.push_back(sensor);
  165. }
  166. void _sensorInit() {
  167. #if ANALOG_SUPPORT
  168. {
  169. AnalogSensor * sensor = new AnalogSensor();
  170. sensor->setGPIO(ANALOG_PIN, ANALOG_PIN_MODE);
  171. _sensorRegister(sensor);
  172. }
  173. #endif
  174. #if BMX280_SUPPORT
  175. {
  176. BMX280Sensor * sensor = new BMX280Sensor();
  177. sensor->setAddress(BMX280_ADDRESS);
  178. _sensorRegister(sensor);
  179. }
  180. #endif
  181. #if DALLAS_SUPPORT
  182. {
  183. DallasSensor * sensor = new DallasSensor();
  184. sensor->setGPIO(DALLAS_PIN);
  185. sensor->setPullUp(DALLAS_PULLUP);
  186. _sensorRegister(sensor);
  187. }
  188. #endif
  189. #if DHT_SUPPORT
  190. {
  191. DHTSensor * sensor = new DHTSensor();
  192. sensor->setGPIO(DHT_PIN);
  193. sensor->setType(DHT_TYPE);
  194. _sensorRegister(sensor);
  195. }
  196. #endif
  197. #if DIGITAL_SUPPORT
  198. {
  199. DigitalSensor * sensor = new DigitalSensor();
  200. sensor->setGPIO(DIGITAL_PIN);
  201. sensor->setMode(DIGITAL_PIN_MODE);
  202. sensor->setDefault(DIGITAL_DEFAULT_STATE);
  203. _sensorRegister(sensor);
  204. }
  205. #endif
  206. #if EMON_ADC121_SUPPORT
  207. {
  208. EmonADC121Sensor * sensor = new EmonADC121Sensor();
  209. sensor->setAddress(EMON_ADC121_I2C_ADDRESS);
  210. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  211. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  212. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  213. _sensorRegister(sensor);
  214. }
  215. #endif
  216. #if EMON_ADS1X15_SUPPORT
  217. {
  218. EmonADS1X15Sensor * sensor = new EmonADS1X15Sensor();
  219. sensor->setAddress(EMON_ADS1X15_I2C_ADDRESS);
  220. sensor->setType(EMON_ADS1X15_TYPE);
  221. sensor->setMask(EMON_ADS1X15_MASK);
  222. sensor->setGain(EMON_ADS1X15_GAIN);
  223. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  224. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  225. sensor->setCurrentRatio(1, EMON_CURRENT_RATIO);
  226. sensor->setCurrentRatio(2, EMON_CURRENT_RATIO);
  227. sensor->setCurrentRatio(3, EMON_CURRENT_RATIO);
  228. _sensorRegister(sensor);
  229. }
  230. #endif
  231. #if EMON_ANALOG_SUPPORT
  232. {
  233. EmonAnalogSensor * sensor = new EmonAnalogSensor();
  234. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  235. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  236. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  237. _sensorRegister(sensor);
  238. }
  239. #endif
  240. #if EVENTS_SUPPORT
  241. {
  242. EventSensor * sensor = new EventSensor();
  243. sensor->setGPIO(EVENTS_PIN);
  244. sensor->setMode(EVENTS_PIN_MODE);
  245. sensor->setDebounceTime(EVENTS_DEBOUNCE);
  246. sensor->setInterruptMode(EVENTS_INTERRUPT_MODE);
  247. _sensorRegister(sensor);
  248. }
  249. #endif
  250. #if MHZ19_SUPPORT
  251. {
  252. MHZ19Sensor * sensor = new MHZ19Sensor();
  253. sensor->setRX(MHZ19_RX_PIN);
  254. sensor->setTX(MHZ19_TX_PIN);
  255. _sensorRegister(sensor);
  256. }
  257. #endif
  258. #if PMSX003_SUPPORT
  259. {
  260. PMSX003Sensor * sensor = new PMSX003Sensor();
  261. sensor->setRX(PMS_RX_PIN);
  262. sensor->setTX(PMS_TX_PIN);
  263. _sensorRegister(sensor);
  264. }
  265. #endif
  266. #if SI7021_SUPPORT
  267. {
  268. SI7021Sensor * sensor = new SI7021Sensor();
  269. sensor->setAddress(SI7021_ADDRESS);
  270. _sensorRegister(sensor);
  271. }
  272. #endif
  273. }
  274. // -----------------------------------------------------------------------------
  275. // Values
  276. // -----------------------------------------------------------------------------
  277. unsigned char sensorCount() {
  278. return _sensors.size();
  279. }
  280. unsigned char magnitudeCount() {
  281. return _magnitudes.size();
  282. }
  283. String magnitudeName(unsigned char index) {
  284. if (index < _magnitudes.size()) {
  285. sensor_magnitude_t magnitude = _magnitudes[index];
  286. return magnitude.sensor->slot(magnitude.local);
  287. }
  288. return String();
  289. }
  290. unsigned char magnitudeType(unsigned char index) {
  291. if (index < _magnitudes.size()) {
  292. return int(_magnitudes[index].type);
  293. }
  294. return MAGNITUDE_NONE;
  295. }
  296. // -----------------------------------------------------------------------------
  297. void sensorSetup() {
  298. // Load sensors
  299. _sensorInit();
  300. // Load magnitudes
  301. for (unsigned char i=0; i<_sensors.size(); i++) {
  302. BaseSensor * sensor = _sensors[i];
  303. DEBUG_MSG("[SENSOR] %s\n", sensor->name().c_str());
  304. if (sensor->count() == 0) DEBUG_MSG("[SENSOR] -> NOTHING FOUND\n");
  305. for (unsigned char k=0; k<sensor->count(); k++) {
  306. magnitude_t type = sensor->type(k);
  307. sensor_magnitude_t new_magnitude;
  308. new_magnitude.sensor = sensor;
  309. new_magnitude.local = k;
  310. new_magnitude.type = type;
  311. new_magnitude.global = _counts[type];
  312. new_magnitude.current = 0;
  313. new_magnitude.filtered = 0;
  314. new_magnitude.reported = 0;
  315. new_magnitude.min_change = 0;
  316. if (type == MAGNITUDE_DIGITAL) {
  317. new_magnitude.filter = new MaxFilter();
  318. } else if (type == MAGNITUDE_EVENTS) {
  319. new_magnitude.filter = new MovingAverageFilter(SENSOR_REPORT_EVERY);
  320. } else {
  321. new_magnitude.filter = new MedianFilter();
  322. }
  323. _magnitudes.push_back(new_magnitude);
  324. DEBUG_MSG("[SENSOR] -> %s:%d\n", _sensorTopic(type).c_str(), _counts[type]);
  325. _counts[type] = _counts[type] + 1;
  326. }
  327. }
  328. #if WEB_SUPPORT
  329. // Websockets
  330. wsOnSendRegister(_sensorWebSocketOnSend);
  331. wsOnAfterParseRegister(_sensorConfigure);
  332. // API
  333. _sensorAPISetup();
  334. #endif
  335. }
  336. void sensorLoop() {
  337. static unsigned long last_update = 0;
  338. static unsigned long report_count = 0;
  339. // Tick hook
  340. _sensorTick();
  341. // Check if we should read new data
  342. if (millis() - last_update > SENSOR_READ_INTERVAL) {
  343. last_update = millis();
  344. report_count = (report_count + 1) % SENSOR_REPORT_EVERY;
  345. double current;
  346. double filtered;
  347. char buffer[64];
  348. // Pre-read hook
  349. _sensorPre();
  350. // Get readings
  351. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  352. sensor_magnitude_t magnitude = _magnitudes[i];
  353. if (magnitude.sensor->status()) {
  354. unsigned char decimals = _sensorDecimals(magnitude.type);
  355. current = magnitude.sensor->value(magnitude.local);
  356. magnitude.filter->add(current);
  357. // Special case
  358. if (magnitude.type == MAGNITUDE_EVENTS) current = magnitude.filter->result();
  359. current = _sensorProcess(magnitude.type, current);
  360. _magnitudes[i].current = current;
  361. // Debug
  362. #if SENSOR_DEBUG
  363. {
  364. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  365. DEBUG_MSG("[SENSOR] %s - %s: %s%s\n",
  366. magnitude.sensor->slot(magnitude.local).c_str(),
  367. _sensorTopic(magnitude.type).c_str(),
  368. buffer,
  369. _sensorUnits(magnitude.type).c_str()
  370. );
  371. }
  372. #endif
  373. // Time to report (we do it every SENSOR_REPORT_EVERY readings)
  374. if (report_count == 0) {
  375. filtered = magnitude.filter->result();
  376. magnitude.filter->reset();
  377. filtered = _sensorProcess(magnitude.type, filtered);
  378. _magnitudes[i].filtered = filtered;
  379. // Check if there is a minimum change threshold to report
  380. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  381. _magnitudes[i].reported = filtered;
  382. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  383. #if MQTT_SUPPORT
  384. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  385. mqttSend(_sensorTopic(magnitude.type).c_str(), magnitude.global, buffer);
  386. } else {
  387. mqttSend(_sensorTopic(magnitude.type).c_str(), buffer);
  388. }
  389. #endif
  390. #if INFLUXDB_SUPPORT
  391. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  392. idbSend(_sensorTopic(magnitude.type).c_str(), magnitude.global, buffer);
  393. } else {
  394. idbSend(_sensorTopic(magnitude.type).c_str(), buffer);
  395. }
  396. #endif
  397. #if DOMOTICZ_SUPPORT
  398. {
  399. char key[15];
  400. snprintf_P(key, sizeof(key), PSTR("dczSensor%d"), i);
  401. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  402. int status;
  403. if (filtered > 70) {
  404. status = HUMIDITY_WET;
  405. } else if (filtered > 45) {
  406. status = HUMIDITY_COMFORTABLE;
  407. } else if (filtered > 30) {
  408. status = HUMIDITY_NORMAL;
  409. } else {
  410. status = HUMIDITY_DRY;
  411. }
  412. char status_buf[5];
  413. itoa(status, status_buf, 10);
  414. domoticzSend(key, buffer, status_buf);
  415. } else {
  416. domoticzSend(key, 0, buffer);
  417. }
  418. }
  419. #endif
  420. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  421. } // if (report_count == 0)
  422. } // if (magnitude.sensor->status())
  423. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  424. // Post-read hook
  425. _sensorPost();
  426. #if WEB_SUPPORT
  427. wsSend(_sensorWebSocketOnSend);
  428. #endif
  429. }
  430. }