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.

476 lines
17 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
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& sensors = root.createNestedArray("sensors");
  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& sensor = sensors.createNestedObject();
  112. sensor["type"] = int(magnitude.type);
  113. sensor["value"] = String(buffer);
  114. sensor["units"] = _sensorUnits(magnitude.type);
  115. sensor["description"] = magnitude.sensor->slot(magnitude.local);
  116. if (magnitude.type == MAGNITUDE_TEMPERATURE) hasTemperature = true;
  117. }
  118. //root["apiRealTime"] = _sensor_realtime;
  119. root["tmpUnits"] = _sensor_temperature_units;
  120. root["tmpCorrection"] = _sensor_temperature_correction;
  121. if (hasTemperature) root["temperatureVisible"] = 1;
  122. }
  123. void _sensorAPISetup() {
  124. for (unsigned char magnitude_id=0; magnitude_id<_magnitudes.size(); magnitude_id++) {
  125. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  126. String topic = _sensorTopic(magnitude.type);
  127. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) topic = topic + "/" + String(magnitude.global);
  128. apiRegister(topic.c_str(), topic.c_str(), [magnitude_id](char * buffer, size_t len) {
  129. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  130. unsigned char decimals = _sensorDecimals(magnitude.type);
  131. double value = _sensor_realtime ? magnitude.current : magnitude.filtered;
  132. dtostrf(value, 1-len, decimals, buffer);
  133. });
  134. }
  135. }
  136. #endif
  137. void _sensorTick() {
  138. for (unsigned char i=0; i<_sensors.size(); i++) {
  139. _sensors[i]->tick();
  140. }
  141. }
  142. void _sensorPre() {
  143. for (unsigned char i=0; i<_sensors.size(); i++) {
  144. _sensors[i]->pre();
  145. if (!_sensors[i]->status()) {
  146. DEBUG_MSG("[SENSOR] Error reading data from %s (error: %d)\n",
  147. _sensors[i]->name().c_str(),
  148. _sensors[i]->error()
  149. );
  150. }
  151. }
  152. }
  153. void _sensorPost() {
  154. for (unsigned char i=0; i<_sensors.size(); i++) {
  155. _sensors[i]->post();
  156. }
  157. }
  158. // -----------------------------------------------------------------------------
  159. // Interrupts
  160. // -----------------------------------------------------------------------------
  161. #if EVENTS_SUPPORT
  162. unsigned char _event_sensor_id = 0;
  163. void isrEventSensor() {
  164. _sensors[_event_sensor_id]->InterruptHandler();
  165. }
  166. #endif // EVENTS_SUPPORT
  167. // -----------------------------------------------------------------------------
  168. // Values
  169. // -----------------------------------------------------------------------------
  170. void sensorRegister(BaseSensor * sensor) {
  171. _sensors.push_back(sensor);
  172. }
  173. unsigned char sensorCount() {
  174. return _sensors.size();
  175. }
  176. unsigned char magnitudeCount() {
  177. return _magnitudes.size();
  178. }
  179. String magnitudeName(unsigned char index) {
  180. if (index < _magnitudes.size()) {
  181. sensor_magnitude_t magnitude = _magnitudes[index];
  182. return magnitude.sensor->slot(magnitude.local);
  183. }
  184. return String();
  185. }
  186. unsigned char magnitudeType(unsigned char index) {
  187. if (index < _magnitudes.size()) {
  188. return int(_magnitudes[index].type);
  189. }
  190. return MAGNITUDE_NONE;
  191. }
  192. void sensorInit() {
  193. #if DHT_SUPPORT
  194. #include "sensors/DHTSensor.h"
  195. sensorRegister(new DHTSensor(DHT_PIN, DHT_TYPE, DHT_PULLUP));
  196. #endif
  197. #if DALLAS_SUPPORT
  198. #include "sensors/DallasSensor.h"
  199. sensorRegister(new DallasSensor(DALLAS_PIN, SENSOR_READ_INTERVAL, DALLAS_PULLUP));
  200. #endif
  201. #if SI7021_SUPPORT
  202. #include "sensors/SI7021Sensor.h"
  203. sensorRegister(new SI7021Sensor(SI7021_ADDRESS));
  204. #endif
  205. #if BMX280_SUPPORT
  206. #include "sensors/BMX280Sensor.h"
  207. sensorRegister(new BMX280Sensor(BMX280_ADDRESS));
  208. #endif
  209. #if ANALOG_SUPPORT
  210. #include "sensors/AnalogSensor.h"
  211. sensorRegister(new AnalogSensor(ANALOG_PIN, ANALOG_PIN_MODE));
  212. #endif
  213. #if DIGITAL_SUPPORT
  214. #include "sensors/DigitalSensor.h"
  215. sensorRegister(new DigitalSensor(DIGITAL_PIN, DIGITAL_PIN_MODE, DIGITAL_DEFAULT_STATE));
  216. #endif
  217. #if EMON_ANALOG_SUPPORT
  218. #include "sensors/EmonAnalogSensor.h"
  219. sensorRegister(new EmonAnalogSensor(A0, EMON_MAINS_VOLTAGE, EMON_ANALOG_ADC_BITS, EMON_ANALOG_REFERENCE_VOLTAGE, EMON_ANALOG_CURRENT_RATIO));
  220. #endif
  221. #if EMON_ADC121_SUPPORT
  222. #include "sensors/EmonADC121Sensor.h"
  223. sensorRegister(new EmonADC121Sensor(EMON_ADC121_I2C_ADDRESS, EMON_MAINS_VOLTAGE, EMON_ADC121_ADC_BITS, EMON_ADC121_REFERENCE_VOLTAGE, EMON_ADC121_CURRENT_RATIO));
  224. #endif
  225. #if EMON_ADS1X15_SUPPORT
  226. #include "sensors/EmonADS1X15Sensor.h"
  227. 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));
  228. #endif
  229. #if PMSX003_SUPPORT
  230. #include "sensors/PMSX003Sensor.h"
  231. sensorRegister(new PMSX003Sensor(PMS_RX_PIN, PMS_TX_PIN));
  232. #endif
  233. #if MHZ19_SUPPORT
  234. #include "sensors/MHZ19Sensor.h"
  235. sensorRegister(new MHZ19Sensor(MHZ19_RX_PIN, MHZ19_TX_PIN));
  236. #endif
  237. #if EVENTS_SUPPORT
  238. #include "sensors/EventSensor.h"
  239. sensorRegister(new EventSensor(EVENTS_PIN, EVENTS_PIN_MODE, EVENTS_DEBOUNCE));
  240. _event_sensor_id = sensorCount() - 1;
  241. attachInterrupt(EVENTS_PIN, isrEventSensor, EVENTS_INTERRUPT_MODE);
  242. #endif
  243. }
  244. void sensorSetup() {
  245. // Load sensors
  246. sensorInit();
  247. // Load magnitudes
  248. for (unsigned char i=0; i<_sensors.size(); i++) {
  249. BaseSensor * sensor = _sensors[i];
  250. DEBUG_MSG("[SENSOR] %s\n", sensor->name().c_str());
  251. for (unsigned char k=0; k<sensor->count(); k++) {
  252. magnitude_t type = sensor->type(k);
  253. sensor_magnitude_t new_magnitude;
  254. new_magnitude.sensor = sensor;
  255. new_magnitude.local = k;
  256. new_magnitude.type = type;
  257. new_magnitude.global = _counts[type];
  258. new_magnitude.current = 0;
  259. new_magnitude.filtered = 0;
  260. new_magnitude.reported = 0;
  261. new_magnitude.min_change = 0;
  262. if (type == MAGNITUDE_DIGITAL) {
  263. new_magnitude.filter = new MaxFilter();
  264. } else if (type == MAGNITUDE_EVENTS) {
  265. new_magnitude.filter = new MovingAverageFilter(SENSOR_REPORT_EVERY);
  266. } else {
  267. new_magnitude.filter = new MedianFilter();
  268. }
  269. _magnitudes.push_back(new_magnitude);
  270. DEBUG_MSG("[SENSOR] -> %s:%d\n", _sensorTopic(type).c_str(), _counts[type]);
  271. _counts[type] = _counts[type] + 1;
  272. }
  273. }
  274. #if WEB_SUPPORT
  275. // Websockets
  276. wsOnSendRegister(_sensorWebSocketOnSend);
  277. wsOnAfterParseRegister(_sensorConfigure);
  278. // API
  279. _sensorAPISetup();
  280. #endif
  281. }
  282. void sensorLoop() {
  283. static unsigned long last_update = 0;
  284. static unsigned long report_count = 0;
  285. // Tick hook
  286. _sensorTick();
  287. // Check if we should read new data
  288. if (millis() - last_update > SENSOR_READ_INTERVAL) {
  289. last_update = millis();
  290. report_count = (report_count + 1) % SENSOR_REPORT_EVERY;
  291. double current;
  292. double filtered;
  293. char buffer[64];
  294. // Pre-read hook
  295. _sensorPre();
  296. // Get readings
  297. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  298. sensor_magnitude_t magnitude = _magnitudes[i];
  299. if (magnitude.sensor->status()) {
  300. unsigned char decimals = _sensorDecimals(magnitude.type);
  301. current = magnitude.sensor->value(magnitude.local);
  302. magnitude.filter->add(current);
  303. // Special case
  304. if (magnitude.type == MAGNITUDE_EVENTS) current = magnitude.filter->result();
  305. current = _sensorProcess(magnitude.type, current);
  306. _magnitudes[i].current = current;
  307. // Debug
  308. #if true
  309. {
  310. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  311. DEBUG_MSG("[SENSOR] %s - %s: %s%s\n",
  312. magnitude.sensor->slot(magnitude.local).c_str(),
  313. _sensorTopic(magnitude.type).c_str(),
  314. buffer,
  315. _sensorUnits(magnitude.type).c_str()
  316. );
  317. }
  318. #endif
  319. // Time to report (we do it every SENSOR_REPORT_EVERY readings)
  320. if (report_count == 0) {
  321. filtered = magnitude.filter->result();
  322. magnitude.filter->reset();
  323. filtered = _sensorProcess(magnitude.type, filtered);
  324. _magnitudes[i].filtered = filtered;
  325. // Check if there is a minimum change threshold to report
  326. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  327. _magnitudes[i].reported = filtered;
  328. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  329. #if MQTT_SUPPORT
  330. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  331. mqttSend(_sensorTopic(magnitude.type).c_str(), magnitude.global, buffer);
  332. } else {
  333. mqttSend(_sensorTopic(magnitude.type).c_str(), buffer);
  334. }
  335. #endif
  336. #if INFLUXDB_SUPPORT
  337. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  338. idbSend(_sensorTopic(magnitude.type).c_str(), magnitude.global, buffer);
  339. } else {
  340. idbSend(_sensorTopic(magnitude.type).c_str(), buffer);
  341. }
  342. #endif
  343. #if DOMOTICZ_SUPPORT
  344. {
  345. char key[15];
  346. snprintf_P(key, sizeof(key), PSTR("dczSensor%d"), i);
  347. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  348. int status;
  349. if (filtered > 70) {
  350. status = HUMIDITY_WET;
  351. } else if (filtered > 45) {
  352. status = HUMIDITY_COMFORTABLE;
  353. } else if (filtered > 30) {
  354. status = HUMIDITY_NORMAL;
  355. } else {
  356. status = HUMIDITY_DRY;
  357. }
  358. char status_buf[5];
  359. itoa(status, status_buf, 10);
  360. domoticzSend(key, buffer, status_buf);
  361. } else {
  362. domoticzSend(key, 0, buffer);
  363. }
  364. }
  365. #endif
  366. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  367. } // if (report_count == 0)
  368. } // if (magnitude.sensor->status())
  369. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  370. // Post-read hook
  371. _sensorPost();
  372. #if WEB_SUPPORT
  373. wsSend(_sensorWebSocketOnSend);
  374. #endif
  375. }
  376. }