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.

562 lines
19 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(MAGNITUDE_TEMPERATURE_TOPIC);
  32. if (type == MAGNITUDE_HUMIDITY) return String(MAGNITUDE_HUMIDITY_TOPIC);
  33. if (type == MAGNITUDE_PRESSURE) return String(MAGNITUDE_PRESSURE_TOPIC);
  34. if (type == MAGNITUDE_CURRENT) return String(MAGNITUDE_CURRENT_TOPIC);
  35. if (type == MAGNITUDE_VOLTAGE) return String(MAGNITUDE_VOLTAGE_TOPIC);
  36. if (type == MAGNITUDE_POWER_ACTIVE) return String(MAGNITUDE_ACTIVE_POWER_TOPIC);
  37. if (type == MAGNITUDE_POWER_APPARENT) return String(MAGNITUDE_APPARENT_POWER_TOPIC);
  38. if (type == MAGNITUDE_POWER_REACTIVE) return String(MAGNITUDE_REACTIVE_POWER_TOPIC);
  39. if (type == MAGNITUDE_POWER_FACTOR) return String(MAGNITUDE_POWER_FACTOR_TOPIC);
  40. if (type == MAGNITUDE_ENERGY) return String(MAGNITUDE_ENERGY_TOPIC);
  41. if (type == MAGNITUDE_ENERGY_DELTA) return String(MAGNITUDE_ENERGY_DELTA_TOPIC);
  42. if (type == MAGNITUDE_ANALOG) return String(MAGNITUDE_ANALOG_TOPIC);
  43. if (type == MAGNITUDE_DIGITAL) return String(MAGNITUDE_DIGITAL_TOPIC);
  44. if (type == MAGNITUDE_EVENTS) return String(MAGNITUDE_EVENTS_TOPIC);
  45. if (type == MAGNITUDE_PM1dot0) return String(MAGNITUDE_PM1dot0_TOPIC);
  46. if (type == MAGNITUDE_PM2dot5) return String(MAGNITUDE_PM2dot5_TOPIC);
  47. if (type == MAGNITUDE_PM10) return String(MAGNITUDE_PM10_TOPIC);
  48. if (type == MAGNITUDE_CO2) return String(MAGNITUDE_CO2_TOPIC);
  49. return String(MAGNITUDE_UNKNOWN_TOPIC);
  50. }
  51. unsigned char _sensorDecimals(magnitude_t type) {
  52. if (type == MAGNITUDE_TEMPERATURE) return MAGNITUDE_TEMPERATURE_DECIMALS;
  53. if (type == MAGNITUDE_HUMIDITY) return MAGNITUDE_HUMIDITY_DECIMALS;
  54. if (type == MAGNITUDE_PRESSURE) return MAGNITUDE_PRESSURE_DECIMALS;
  55. if (type == MAGNITUDE_CURRENT) return MAGNITUDE_CURRENT_DECIMALS;
  56. if (type == MAGNITUDE_VOLTAGE) return MAGNITUDE_VOLTAGE_DECIMALS;
  57. if (type == MAGNITUDE_POWER_ACTIVE) return MAGNITUDE_POWER_DECIMALS;
  58. if (type == MAGNITUDE_POWER_APPARENT) return MAGNITUDE_POWER_DECIMALS;
  59. if (type == MAGNITUDE_POWER_REACTIVE) return MAGNITUDE_POWER_DECIMALS;
  60. if (type == MAGNITUDE_POWER_FACTOR) return MAGNITUDE_POWER_FACTOR_DECIMALS;
  61. if (type == MAGNITUDE_ENERGY) return MAGNITUDE_ENERGY_DECIMALS;
  62. if (type == MAGNITUDE_ENERGY_DELTA) return MAGNITUDE_ENERGY_DECIMALS;
  63. if (type == MAGNITUDE_ANALOG) return MAGNITUDE_ANALOG_DECIMALS;
  64. if (type == MAGNITUDE_EVENTS) return MAGNITUDE_EVENTS_DECIMALS;
  65. if (type == MAGNITUDE_PM1dot0) return MAGNITUDE_PM1dot0_DECIMALS;
  66. if (type == MAGNITUDE_PM2dot5) return MAGNITUDE_PM2dot5_DECIMALS;
  67. if (type == MAGNITUDE_PM10) return MAGNITUDE_PM10_DECIMALS;
  68. if (type == MAGNITUDE_CO2) return MAGNITUDE_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 _sensorWebSocketSendData(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 _sensorWebSocketStart(JsonObject& root) {
  125. /*
  126. // Sensors manifest
  127. JsonArray& manifest = root.createNestedArray("manifest");
  128. #if BMX280_SUPPORT
  129. BMX280Sensor::manifest(manifest);
  130. #endif
  131. // Sensors configuration
  132. JsonArray& sensors = root.createNestedArray("sensors");
  133. for (unsigned char i; i<_sensors.size(); i++) {
  134. JsonObject& sensor = sensors.createNestedObject();
  135. sensor["index"] = i;
  136. sensor["id"] = _sensors[i]->getID();
  137. _sensors[i]->getConfig(sensor);
  138. }
  139. */
  140. }
  141. void _sensorWebSocketReceiveData() {
  142. //_emon.setCurrentRatio(getSetting("pwrRatioC", EMON_CURRENT_RATIO).toFloat());
  143. //_power_voltage = getSetting("pwrVoltage", POWER_VOLTAGE).toFloat();
  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 = _sensorTopic(magnitude.type);
  149. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) topic = topic + "/" + String(magnitude.global);
  150. apiRegister(topic.c_str(), topic.c_str(), [magnitude_id](char * buffer, size_t len) {
  151. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  152. unsigned char decimals = _sensorDecimals(magnitude.type);
  153. double value = _sensor_realtime ? magnitude.current : magnitude.filtered;
  154. dtostrf(value, 1-len, decimals, buffer);
  155. });
  156. }
  157. }
  158. #endif
  159. void _sensorTick() {
  160. for (unsigned char i=0; i<_sensors.size(); i++) {
  161. _sensors[i]->tick();
  162. }
  163. }
  164. void _sensorPre() {
  165. for (unsigned char i=0; i<_sensors.size(); i++) {
  166. _sensors[i]->pre();
  167. if (!_sensors[i]->status()) {
  168. DEBUG_MSG("[SENSOR] Error reading data from %s (error: %d)\n",
  169. _sensors[i]->description().c_str(),
  170. _sensors[i]->error()
  171. );
  172. }
  173. }
  174. }
  175. void _sensorPost() {
  176. for (unsigned char i=0; i<_sensors.size(); i++) {
  177. _sensors[i]->post();
  178. }
  179. }
  180. // -----------------------------------------------------------------------------
  181. // Sensor initialization
  182. // -----------------------------------------------------------------------------
  183. void _sensorRegister(BaseSensor * sensor) {
  184. sensor->begin();
  185. _sensors.push_back(sensor);
  186. }
  187. void _sensorInit() {
  188. #if ANALOG_SUPPORT
  189. {
  190. AnalogSensor * sensor = new AnalogSensor();
  191. _sensorRegister(sensor);
  192. }
  193. #endif
  194. #if BMX280_SUPPORT
  195. {
  196. BMX280Sensor * sensor = new BMX280Sensor();
  197. sensor->setAddress(BMX280_ADDRESS);
  198. _sensorRegister(sensor);
  199. }
  200. #endif
  201. #if DALLAS_SUPPORT
  202. {
  203. DallasSensor * sensor = new DallasSensor();
  204. sensor->setGPIO(DALLAS_PIN);
  205. _sensorRegister(sensor);
  206. }
  207. #endif
  208. #if DHT_SUPPORT
  209. {
  210. DHTSensor * sensor = new DHTSensor();
  211. sensor->setGPIO(DHT_PIN);
  212. sensor->setType(DHT_TYPE);
  213. _sensorRegister(sensor);
  214. }
  215. #endif
  216. #if DIGITAL_SUPPORT
  217. {
  218. DigitalSensor * sensor = new DigitalSensor();
  219. sensor->setGPIO(DIGITAL_PIN);
  220. sensor->setMode(DIGITAL_PIN_MODE);
  221. sensor->setDefault(DIGITAL_DEFAULT_STATE);
  222. _sensorRegister(sensor);
  223. }
  224. #endif
  225. #if EMON_ADC121_SUPPORT
  226. {
  227. EmonADC121Sensor * sensor = new EmonADC121Sensor();
  228. sensor->setAddress(EMON_ADC121_I2C_ADDRESS);
  229. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  230. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  231. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  232. _sensorRegister(sensor);
  233. }
  234. #endif
  235. #if EMON_ADS1X15_SUPPORT
  236. {
  237. EmonADS1X15Sensor * sensor = new EmonADS1X15Sensor();
  238. sensor->setAddress(EMON_ADS1X15_I2C_ADDRESS);
  239. sensor->setType(EMON_ADS1X15_TYPE);
  240. sensor->setMask(EMON_ADS1X15_MASK);
  241. sensor->setGain(EMON_ADS1X15_GAIN);
  242. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  243. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  244. sensor->setCurrentRatio(1, EMON_CURRENT_RATIO);
  245. sensor->setCurrentRatio(2, EMON_CURRENT_RATIO);
  246. sensor->setCurrentRatio(3, EMON_CURRENT_RATIO);
  247. _sensorRegister(sensor);
  248. }
  249. #endif
  250. #if EMON_ANALOG_SUPPORT
  251. {
  252. EmonAnalogSensor * sensor = new EmonAnalogSensor();
  253. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  254. sensor->setReference(EMON_REFERENCE_VOLTAGE);
  255. sensor->setCurrentRatio(0, EMON_CURRENT_RATIO);
  256. _sensorRegister(sensor);
  257. }
  258. #endif
  259. #if EVENTS_SUPPORT
  260. {
  261. EventSensor * sensor = new EventSensor();
  262. sensor->setGPIO(EVENTS_PIN);
  263. sensor->setMode(EVENTS_PIN_MODE);
  264. sensor->setDebounceTime(EVENTS_DEBOUNCE);
  265. sensor->setInterruptMode(EVENTS_INTERRUPT_MODE);
  266. _sensorRegister(sensor);
  267. }
  268. #endif
  269. #if MHZ19_SUPPORT
  270. {
  271. MHZ19Sensor * sensor = new MHZ19Sensor();
  272. sensor->setRX(MHZ19_RX_PIN);
  273. sensor->setTX(MHZ19_TX_PIN);
  274. _sensorRegister(sensor);
  275. }
  276. #endif
  277. #if PMSX003_SUPPORT
  278. {
  279. PMSX003Sensor * sensor = new PMSX003Sensor();
  280. sensor->setRX(PMS_RX_PIN);
  281. sensor->setTX(PMS_TX_PIN);
  282. _sensorRegister(sensor);
  283. }
  284. #endif
  285. #if SI7021_SUPPORT
  286. {
  287. SI7021Sensor * sensor = new SI7021Sensor();
  288. sensor->setAddress(SI7021_ADDRESS);
  289. _sensorRegister(sensor);
  290. }
  291. #endif
  292. }
  293. void _magnitudesInit() {
  294. for (unsigned char i=0; i<_sensors.size(); i++) {
  295. BaseSensor * sensor = _sensors[i];
  296. DEBUG_MSG("[SENSOR] %s\n", sensor->description().c_str());
  297. if (sensor->error() != 0) DEBUG_MSG("[SENSOR] -> ERROR %d\n", sensor->error());
  298. for (unsigned char k=0; k<sensor->count(); k++) {
  299. magnitude_t type = sensor->type(k);
  300. sensor_magnitude_t new_magnitude;
  301. new_magnitude.sensor = sensor;
  302. new_magnitude.local = k;
  303. new_magnitude.type = type;
  304. new_magnitude.global = _counts[type];
  305. new_magnitude.current = 0;
  306. new_magnitude.filtered = 0;
  307. new_magnitude.reported = 0;
  308. new_magnitude.min_change = 0;
  309. if (type == MAGNITUDE_DIGITAL) {
  310. new_magnitude.filter = new MaxFilter();
  311. } else if (type == MAGNITUDE_EVENTS) {
  312. new_magnitude.filter = new MovingAverageFilter(SENSOR_REPORT_EVERY);
  313. } else {
  314. new_magnitude.filter = new MedianFilter();
  315. }
  316. _magnitudes.push_back(new_magnitude);
  317. DEBUG_MSG("[SENSOR] -> %s:%d\n", _sensorTopic(type).c_str(), _counts[type]);
  318. _counts[type] = _counts[type] + 1;
  319. }
  320. }
  321. }
  322. // -----------------------------------------------------------------------------
  323. // Public
  324. // -----------------------------------------------------------------------------
  325. unsigned char sensorCount() {
  326. return _sensors.size();
  327. }
  328. unsigned char magnitudeCount() {
  329. return _magnitudes.size();
  330. }
  331. String magnitudeName(unsigned char index) {
  332. if (index < _magnitudes.size()) {
  333. sensor_magnitude_t magnitude = _magnitudes[index];
  334. return magnitude.sensor->slot(magnitude.local);
  335. }
  336. return String();
  337. }
  338. unsigned char magnitudeType(unsigned char index) {
  339. if (index < _magnitudes.size()) {
  340. return int(_magnitudes[index].type);
  341. }
  342. return MAGNITUDE_NONE;
  343. }
  344. // -----------------------------------------------------------------------------
  345. void sensorSetup() {
  346. // Load sensors
  347. _sensorInit();
  348. // Load magnitudes
  349. _magnitudesInit();
  350. #if WEB_SUPPORT
  351. // Websockets
  352. wsOnSendRegister(_sensorWebSocketStart);
  353. wsOnSendRegister(_sensorWebSocketSendData);
  354. wsOnAfterParseRegister(_sensorConfigure);
  355. // API
  356. _sensorAPISetup();
  357. #endif
  358. }
  359. void sensorLoop() {
  360. static unsigned long last_update = 0;
  361. static unsigned long report_count = 0;
  362. // Tick hook
  363. _sensorTick();
  364. // Check if we should read new data
  365. if (millis() - last_update > SENSOR_READ_INTERVAL) {
  366. last_update = millis();
  367. report_count = (report_count + 1) % SENSOR_REPORT_EVERY;
  368. double current;
  369. double filtered;
  370. char buffer[64];
  371. // Pre-read hook
  372. _sensorPre();
  373. // Get readings
  374. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  375. sensor_magnitude_t magnitude = _magnitudes[i];
  376. if (magnitude.sensor->status()) {
  377. unsigned char decimals = _sensorDecimals(magnitude.type);
  378. current = magnitude.sensor->value(magnitude.local);
  379. magnitude.filter->add(current);
  380. // Special case
  381. if (magnitude.type == MAGNITUDE_EVENTS) current = magnitude.filter->result();
  382. current = _sensorProcess(magnitude.type, current);
  383. _magnitudes[i].current = current;
  384. // Debug
  385. #if SENSOR_DEBUG
  386. {
  387. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  388. DEBUG_MSG("[SENSOR] %s - %s: %s%s\n",
  389. magnitude.sensor->slot(magnitude.local).c_str(),
  390. _sensorTopic(magnitude.type).c_str(),
  391. buffer,
  392. _sensorUnits(magnitude.type).c_str()
  393. );
  394. }
  395. #endif
  396. // Time to report (we do it every SENSOR_REPORT_EVERY readings)
  397. if (report_count == 0) {
  398. filtered = magnitude.filter->result();
  399. magnitude.filter->reset();
  400. filtered = _sensorProcess(magnitude.type, filtered);
  401. _magnitudes[i].filtered = filtered;
  402. // Check if there is a minimum change threshold to report
  403. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  404. _magnitudes[i].reported = filtered;
  405. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  406. #if MQTT_SUPPORT
  407. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  408. mqttSend(_sensorTopic(magnitude.type).c_str(), magnitude.global, buffer);
  409. } else {
  410. mqttSend(_sensorTopic(magnitude.type).c_str(), buffer);
  411. }
  412. #endif
  413. #if INFLUXDB_SUPPORT
  414. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  415. idbSend(_sensorTopic(magnitude.type).c_str(), magnitude.global, buffer);
  416. } else {
  417. idbSend(_sensorTopic(magnitude.type).c_str(), buffer);
  418. }
  419. #endif
  420. #if DOMOTICZ_SUPPORT
  421. {
  422. char key[15];
  423. snprintf_P(key, sizeof(key), PSTR("dczSensor%d"), i);
  424. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  425. int status;
  426. if (filtered > 70) {
  427. status = HUMIDITY_WET;
  428. } else if (filtered > 45) {
  429. status = HUMIDITY_COMFORTABLE;
  430. } else if (filtered > 30) {
  431. status = HUMIDITY_NORMAL;
  432. } else {
  433. status = HUMIDITY_DRY;
  434. }
  435. char status_buf[5];
  436. itoa(status, status_buf, 10);
  437. domoticzSend(key, buffer, status_buf);
  438. } else {
  439. domoticzSend(key, 0, buffer);
  440. }
  441. }
  442. #endif
  443. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  444. } // if (report_count == 0)
  445. } // if (magnitude.sensor->status())
  446. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  447. // Post-read hook
  448. _sensorPost();
  449. #if WEB_SUPPORT
  450. wsSend(_sensorWebSocketSendData);
  451. #endif
  452. }
  453. }