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.

477 lines
17 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. unsigned char _sensor_isr = 0xFF;
  28. // -----------------------------------------------------------------------------
  29. // Private
  30. // -----------------------------------------------------------------------------
  31. String _sensorTopic(magnitude_t type) {
  32. if (type == MAGNITUDE_TEMPERATURE) return String(SENSOR_TEMPERATURE_TOPIC);
  33. if (type == MAGNITUDE_HUMIDITY) return String(SENSOR_HUMIDITY_TOPIC);
  34. if (type == MAGNITUDE_PRESSURE) return String(SENSOR_PRESSURE_TOPIC);
  35. if (type == MAGNITUDE_CURRENT) return String(SENSOR_CURRENT_TOPIC);
  36. if (type == MAGNITUDE_VOLTAGE) return String(SENSOR_VOLTAGE_TOPIC);
  37. if (type == MAGNITUDE_POWER_ACTIVE) return String(SENSOR_ACTIVE_POWER_TOPIC);
  38. if (type == MAGNITUDE_POWER_APPARENT) return String(SENSOR_APPARENT_POWER_TOPIC);
  39. if (type == MAGNITUDE_POWER_REACTIVE) return String(SENSOR_REACTIVE_POWER_TOPIC);
  40. if (type == MAGNITUDE_POWER_FACTOR) return String(SENSOR_POWER_FACTOR_TOPIC);
  41. if (type == MAGNITUDE_ENERGY) return String(SENSOR_ENERGY_TOPIC);
  42. if (type == MAGNITUDE_ENERGY_DELTA) return String(SENSOR_ENERGY_DELTA_TOPIC);
  43. if (type == MAGNITUDE_ANALOG) return String(SENSOR_ANALOG_TOPIC);
  44. if (type == MAGNITUDE_DIGITAL) return String(SENSOR_DIGITAL_TOPIC);
  45. if (type == MAGNITUDE_EVENTS) return String(SENSOR_EVENTS_TOPIC);
  46. if (type == MAGNITUDE_PM1dot0) return String(SENSOR_PM1dot0_TOPIC);
  47. if (type == MAGNITUDE_PM2dot5) return String(SENSOR_PM2dot5_TOPIC);
  48. if (type == MAGNITUDE_PM10) return String(SENSOR_PM10_TOPIC);
  49. if (type == MAGNITUDE_CO2) return String(SENSOR_CO2_TOPIC);
  50. return String(SENSOR_UNKNOWN_TOPIC);
  51. }
  52. unsigned char _sensorDecimals(magnitude_t type) {
  53. if (type == MAGNITUDE_TEMPERATURE) return SENSOR_TEMPERATURE_DECIMALS;
  54. if (type == MAGNITUDE_HUMIDITY) return SENSOR_HUMIDITY_DECIMALS;
  55. if (type == MAGNITUDE_PRESSURE) return SENSOR_PRESSURE_DECIMALS;
  56. if (type == MAGNITUDE_CURRENT) return SENSOR_CURRENT_DECIMALS;
  57. if (type == MAGNITUDE_VOLTAGE) return SENSOR_VOLTAGE_DECIMALS;
  58. if (type == MAGNITUDE_POWER_ACTIVE) return SENSOR_POWER_DECIMALS;
  59. if (type == MAGNITUDE_POWER_APPARENT) return SENSOR_POWER_DECIMALS;
  60. if (type == MAGNITUDE_POWER_REACTIVE) return SENSOR_POWER_DECIMALS;
  61. if (type == MAGNITUDE_POWER_FACTOR) return SENSOR_POWER_FACTOR_DECIMALS;
  62. if (type == MAGNITUDE_ENERGY) return SENSOR_ENERGY_DECIMALS;
  63. if (type == MAGNITUDE_ENERGY_DELTA) return SENSOR_ENERGY_DECIMALS;
  64. if (type == MAGNITUDE_ANALOG) return SENSOR_ANALOG_DECIMALS;
  65. if (type == MAGNITUDE_EVENTS) return SENSOR_EVENTS_DECIMALS;
  66. if (type == MAGNITUDE_PM1dot0) return SENSOR_PM1dot0_DECIMALS;
  67. if (type == MAGNITUDE_PM2dot5) return SENSOR_PM2dot5_DECIMALS;
  68. if (type == MAGNITUDE_PM10) return SENSOR_PM10_DECIMALS;
  69. if (type == MAGNITUDE_CO2) return SENSOR_CO2_DECIMALS;
  70. return 0;
  71. }
  72. String _sensorUnits(magnitude_t type) {
  73. if (type == MAGNITUDE_TEMPERATURE) return (_sensor_temperature_units == TMP_CELSIUS) ? String("C") : String("F");
  74. if (type == MAGNITUDE_HUMIDITY) return String("%");
  75. if (type == MAGNITUDE_PRESSURE) return String("hPa");
  76. if (type == MAGNITUDE_CURRENT) return String("A");
  77. if (type == MAGNITUDE_VOLTAGE) return String("V");
  78. if (type == MAGNITUDE_POWER_ACTIVE) return String("W");
  79. if (type == MAGNITUDE_POWER_APPARENT) return String("W");
  80. if (type == MAGNITUDE_POWER_REACTIVE) return String("W");
  81. if (type == MAGNITUDE_POWER_FACTOR) return String("%");
  82. if (type == MAGNITUDE_ENERGY) return String("J");
  83. if (type == MAGNITUDE_ENERGY_DELTA) return String("J");
  84. if (type == MAGNITUDE_EVENTS) return String("/min");
  85. if (type == MAGNITUDE_PM1dot0) return String("µg/m3");
  86. if (type == MAGNITUDE_PM2dot5) return String("µg/m3");
  87. if (type == MAGNITUDE_PM10) return String("µg/m3");
  88. if (type == MAGNITUDE_CO2) return String("ppm");
  89. return String();
  90. }
  91. double _sensorProcess(magnitude_t type, double value) {
  92. if (type == MAGNITUDE_TEMPERATURE) {
  93. if (_sensor_temperature_units == TMP_FAHRENHEIT) value = value * 1.8 + 32;
  94. value = value + _sensor_temperature_correction;
  95. }
  96. return roundTo(value, _sensorDecimals(type));
  97. }
  98. void _sensorConfigure() {
  99. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  100. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  101. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  102. }
  103. #if WEB_SUPPORT
  104. void _sensorWebSocketOnSend(JsonObject& root) {
  105. char buffer[10];
  106. bool hasTemperature = false;
  107. JsonArray& sensors = root.createNestedArray("sensors");
  108. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  109. sensor_magnitude_t magnitude = _magnitudes[i];
  110. unsigned char decimals = _sensorDecimals(magnitude.type);
  111. dtostrf(magnitude.current, 1-sizeof(buffer), decimals, buffer);
  112. JsonObject& sensor = sensors.createNestedObject();
  113. sensor["type"] = int(magnitude.type);
  114. sensor["value"] = String(buffer);
  115. sensor["units"] = _sensorUnits(magnitude.type);
  116. sensor["description"] = magnitude.sensor->slot(magnitude.local);
  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. // Interrupts
  161. // -----------------------------------------------------------------------------
  162. #if COUNTER_SUPPORT
  163. unsigned char _event_sensor_id = 0;
  164. void isrEventSensor() {
  165. _sensors[_event_sensor_id]->InterruptHandler();
  166. }
  167. #endif // COUNTER_SUPPORT
  168. // -----------------------------------------------------------------------------
  169. // Values
  170. // -----------------------------------------------------------------------------
  171. void sensorRegister(BaseSensor * sensor) {
  172. _sensors.push_back(sensor);
  173. }
  174. unsigned char sensorCount() {
  175. return _sensors.size();
  176. }
  177. unsigned char magnitudeCount() {
  178. return _magnitudes.size();
  179. }
  180. String magnitudeName(unsigned char index) {
  181. if (index < _magnitudes.size()) {
  182. sensor_magnitude_t magnitude = _magnitudes[index];
  183. return magnitude.sensor->slot(magnitude.local);
  184. }
  185. return String();
  186. }
  187. unsigned char magnitudeType(unsigned char index) {
  188. if (index < _magnitudes.size()) {
  189. return int(_magnitudes[index].type);
  190. }
  191. return MAGNITUDE_NONE;
  192. }
  193. void sensorInit() {
  194. #if DHT_SUPPORT
  195. #include "sensors/DHTSensor.h"
  196. sensorRegister(new DHTSensor(DHT_PIN, DHT_TYPE, DHT_PULLUP));
  197. #endif
  198. #if DS18B20_SUPPORT
  199. #include "sensors/DallasSensor.h"
  200. sensorRegister(new DallasSensor(DS18B20_PIN, SENSOR_READ_INTERVAL, DS18B20_PULLUP));
  201. #endif
  202. #if SI7021_SUPPORT
  203. #include "sensors/SI7021Sensor.h"
  204. sensorRegister(new SI7021Sensor(SI7021_ADDRESS));
  205. #endif
  206. #if BME280_SUPPORT
  207. #include "sensors/BME280Sensor.h"
  208. sensorRegister(new BME280Sensor(BME280_ADDRESS));
  209. #endif
  210. #if ANALOG_SUPPORT
  211. #include "sensors/AnalogSensor.h"
  212. sensorRegister(new AnalogSensor(ANALOG_PIN, ANALOG_PIN_MODE));
  213. #endif
  214. #if DIGITAL_SUPPORT
  215. #include "sensors/DigitalSensor.h"
  216. sensorRegister(new DigitalSensor(DIGITAL_PIN, DIGITAL_PIN_MODE, DIGITAL_DEFAULT_STATE));
  217. #endif
  218. #if EMON_ANALOG_SUPPORT
  219. #include "sensors/EmonAnalogSensor.h"
  220. sensorRegister(new EmonAnalogSensor(A0, EMON_MAINS_VOLTAGE, EMON_ANALOG_ADC_BITS, EMON_ANALOG_REFERENCE_VOLTAGE, EMON_ANALOG_CURRENT_RATIO));
  221. #endif
  222. #if EMON_ADC121_SUPPORT
  223. #include "sensors/EmonADC121Sensor.h"
  224. sensorRegister(new EmonADC121Sensor(EMON_ADC121_I2C_ADDRESS, EMON_MAINS_VOLTAGE, EMON_ADC121_ADC_BITS, EMON_ADC121_REFERENCE_VOLTAGE, EMON_ADC121_CURRENT_RATIO));
  225. #endif
  226. #if EMON_ADS1X15_SUPPORT
  227. #include "sensors/EmonADS1X15Sensor.h"
  228. sensorRegister(new EmonADS1X15Sensor(EMON_ADS1X15_I2C_ADDRESS, EMON_ADS1X15_ADS1115, EMON_ADS1X15_PORT_MASK, EMON_MAINS_VOLTAGE, EMON_ADS1X15_ADC_BITS, EMON_ADS1X15_REFERENCE_VOLTAGE, EMON_ADS1X15_CURRENT_RATIO));
  229. #endif
  230. #if PMSX003_SUPPORT
  231. #include "sensors/PMSX003Sensor.h"
  232. sensorRegister(new PMSX003Sensor(PMS_RX_PIN, PMS_TX_PIN));
  233. #endif
  234. #if MHZ19_SUPPORT
  235. #include "sensors/MHZ19Sensor.h"
  236. sensorRegister(new MHZ19Sensor(MHZ19_RX_PIN, MHZ19_TX_PIN));
  237. #endif
  238. #if COUNTER_SUPPORT
  239. #include "sensors/EventSensor.h"
  240. sensorRegister(new EventSensor(COUNTER_PIN, COUNTER_PIN_MODE, COUNTER_DEBOUNCE));
  241. _event_sensor_id = sensorCount() - 1;
  242. attachInterrupt(COUNTER_PIN, isrEventSensor, COUNTER_INTERRUPT_MODE);
  243. #endif
  244. }
  245. void sensorSetup() {
  246. // Load sensors
  247. sensorInit();
  248. // Load magnitudes
  249. for (unsigned char i=0; i<_sensors.size(); i++) {
  250. BaseSensor * sensor = _sensors[i];
  251. DEBUG_MSG("[SENSOR] %s\n", sensor->name().c_str());
  252. for (unsigned char k=0; k<sensor->count(); k++) {
  253. magnitude_t type = sensor->type(k);
  254. sensor_magnitude_t new_magnitude;
  255. new_magnitude.sensor = sensor;
  256. new_magnitude.local = k;
  257. new_magnitude.type = type;
  258. new_magnitude.global = _counts[type];
  259. new_magnitude.current = 0;
  260. new_magnitude.filtered = 0;
  261. new_magnitude.reported = 0;
  262. new_magnitude.min_change = 0;
  263. if (type == MAGNITUDE_DIGITAL) {
  264. new_magnitude.filter = new MaxFilter();
  265. } else if (type == MAGNITUDE_EVENTS) {
  266. new_magnitude.filter = new MovingAverageFilter(SENSOR_REPORT_EVERY);
  267. } else {
  268. new_magnitude.filter = new MedianFilter();
  269. }
  270. _magnitudes.push_back(new_magnitude);
  271. DEBUG_MSG("[SENSOR] -> %s:%d\n", _sensorTopic(type).c_str(), _counts[type]);
  272. _counts[type] = _counts[type] + 1;
  273. }
  274. }
  275. #if WEB_SUPPORT
  276. // Websockets
  277. wsOnSendRegister(_sensorWebSocketOnSend);
  278. wsOnAfterParseRegister(_sensorConfigure);
  279. // API
  280. _sensorAPISetup();
  281. #endif
  282. }
  283. void sensorLoop() {
  284. static unsigned long last_update = 0;
  285. static unsigned long report_count = 0;
  286. // Tick hook
  287. _sensorTick();
  288. // Check if we should read new data
  289. if (millis() - last_update > SENSOR_READ_INTERVAL) {
  290. last_update = millis();
  291. report_count = (report_count + 1) % SENSOR_REPORT_EVERY;
  292. double current;
  293. double filtered;
  294. char buffer[64];
  295. // Pre-read hook
  296. _sensorPre();
  297. // Get readings
  298. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  299. sensor_magnitude_t magnitude = _magnitudes[i];
  300. if (magnitude.sensor->status()) {
  301. unsigned char decimals = _sensorDecimals(magnitude.type);
  302. current = magnitude.sensor->value(magnitude.local);
  303. magnitude.filter->add(current);
  304. // Special case
  305. if (magnitude.type == MAGNITUDE_EVENTS) current = magnitude.filter->result();
  306. current = _sensorProcess(magnitude.type, current);
  307. _magnitudes[i].current = current;
  308. // Debug
  309. #if true
  310. {
  311. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  312. DEBUG_MSG("[SENSOR] %s - %s: %s%s\n",
  313. magnitude.sensor->slot(magnitude.local).c_str(),
  314. _sensorTopic(magnitude.type).c_str(),
  315. buffer,
  316. _sensorUnits(magnitude.type).c_str()
  317. );
  318. }
  319. #endif
  320. // Time to report (we do it every SENSOR_REPORT_EVERY readings)
  321. if (report_count == 0) {
  322. filtered = magnitude.filter->result();
  323. magnitude.filter->reset();
  324. filtered = _sensorProcess(magnitude.type, filtered);
  325. _magnitudes[i].filtered = filtered;
  326. // Check if there is a minimum change threshold to report
  327. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  328. _magnitudes[i].reported = filtered;
  329. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  330. #if MQTT_SUPPORT
  331. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  332. mqttSend(_sensorTopic(magnitude.type).c_str(), magnitude.global, buffer);
  333. } else {
  334. mqttSend(_sensorTopic(magnitude.type).c_str(), buffer);
  335. }
  336. #endif
  337. #if INFLUXDB_SUPPORT
  338. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  339. idbSend(_sensorTopic(magnitude.type).c_str(), magnitude.global, buffer);
  340. } else {
  341. idbSend(_sensorTopic(magnitude.type).c_str(), buffer);
  342. }
  343. #endif
  344. #if DOMOTICZ_SUPPORT
  345. {
  346. char key[15];
  347. snprintf_P(key, sizeof(key), PSTR("dczSensor%d"), i);
  348. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  349. int status;
  350. if (filtered > 70) {
  351. status = HUMIDITY_WET;
  352. } else if (filtered > 45) {
  353. status = HUMIDITY_COMFORTABLE;
  354. } else if (filtered > 30) {
  355. status = HUMIDITY_NORMAL;
  356. } else {
  357. status = HUMIDITY_DRY;
  358. }
  359. char status_buf[5];
  360. itoa(status, status_buf, 10);
  361. domoticzSend(key, buffer, status_buf);
  362. } else {
  363. domoticzSend(key, 0, buffer);
  364. }
  365. }
  366. #endif
  367. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  368. } // if (report_count == 0)
  369. } // if (magnitude.sensor->status())
  370. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  371. // Post-read hook
  372. _sensorPost();
  373. #if WEB_SUPPORT
  374. wsSend(_sensorWebSocketOnSend);
  375. #endif
  376. }
  377. }