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.

460 lines
16 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/MedianFilter.h"
  7. #include "filters/MovingAverageFilter.h"
  8. #include "sensors/BaseSensor.h"
  9. typedef struct {
  10. BaseSensor * sensor;
  11. unsigned char local; // Local index in its provider
  12. magnitude_t type; // Type of measurement
  13. unsigned char global; // Global index in its type
  14. double current; // Current (last) value, unfiltered
  15. double filtered; // Filtered (averaged) value
  16. double reported; // Last reported value
  17. double min_change; // Minimum value change to report
  18. BaseFilter * filter; // Filter object
  19. } sensor_magnitude_t;
  20. std::vector<BaseSensor *> _sensors;
  21. std::vector<sensor_magnitude_t> _magnitudes;
  22. unsigned char _counts[MAGNITUDE_MAX];
  23. bool _sensor_realtime = API_REAL_TIME_VALUES;
  24. unsigned char _sensor_temperature_units = SENSOR_TEMPERATURE_UNITS;
  25. double _sensor_temperature_correction = SENSOR_TEMPERATURE_CORRECTION;
  26. unsigned char _sensor_isr = 0xFF;
  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_EVENTS) return String(SENSOR_EVENTS_TOPIC);
  44. if (type == MAGNITUDE_PM1dot0) return String(SENSOR_PM1dot0_TOPIC);
  45. if (type == MAGNITUDE_PM2dot5) return String(SENSOR_PM2dot5_TOPIC);
  46. if (type == MAGNITUDE_PM10) return String(SENSOR_PM10_TOPIC);
  47. return String(SENSOR_UNKNOWN_TOPIC);
  48. }
  49. unsigned char _sensorDecimals(magnitude_t type) {
  50. if (type == MAGNITUDE_TEMPERATURE) return SENSOR_TEMPERATURE_DECIMALS;
  51. if (type == MAGNITUDE_HUMIDITY) return SENSOR_HUMIDITY_DECIMALS;
  52. if (type == MAGNITUDE_PRESSURE) return SENSOR_PRESSURE_DECIMALS;
  53. if (type == MAGNITUDE_CURRENT) return SENSOR_CURRENT_DECIMALS;
  54. if (type == MAGNITUDE_VOLTAGE) return SENSOR_VOLTAGE_DECIMALS;
  55. if (type == MAGNITUDE_POWER_ACTIVE) return SENSOR_POWER_DECIMALS;
  56. if (type == MAGNITUDE_POWER_APPARENT) return SENSOR_POWER_DECIMALS;
  57. if (type == MAGNITUDE_POWER_REACTIVE) return SENSOR_POWER_DECIMALS;
  58. if (type == MAGNITUDE_POWER_FACTOR) return SENSOR_POWER_FACTOR_DECIMALS;
  59. if (type == MAGNITUDE_ENERGY) return SENSOR_ENERGY_DECIMALS;
  60. if (type == MAGNITUDE_ENERGY_DELTA) return SENSOR_ENERGY_DECIMALS;
  61. if (type == MAGNITUDE_ANALOG) return SENSOR_ANALOG_DECIMALS;
  62. if (type == MAGNITUDE_EVENTS) return SENSOR_EVENTS_DECIMALS;
  63. if (type == MAGNITUDE_PM1dot0) return SENSOR_PM1dot0_DECIMALS;
  64. if (type == MAGNITUDE_PM2dot5) return SENSOR_PM2dot5_DECIMALS;
  65. if (type == MAGNITUDE_PM10) return SENSOR_PM10_DECIMALS;
  66. return 0;
  67. }
  68. String _sensorUnits(magnitude_t type) {
  69. if (type == MAGNITUDE_TEMPERATURE) return (_sensor_temperature_units == TMP_CELSIUS) ? String("C") : String("F");
  70. if (type == MAGNITUDE_HUMIDITY) return String("%");
  71. if (type == MAGNITUDE_PRESSURE) return String("hPa");
  72. if (type == MAGNITUDE_CURRENT) return String("A");
  73. if (type == MAGNITUDE_VOLTAGE) return String("V");
  74. if (type == MAGNITUDE_POWER_ACTIVE) return String("W");
  75. if (type == MAGNITUDE_POWER_APPARENT) return String("W");
  76. if (type == MAGNITUDE_POWER_REACTIVE) return String("W");
  77. if (type == MAGNITUDE_POWER_FACTOR) return String("%");
  78. if (type == MAGNITUDE_ENERGY) return String("J");
  79. if (type == MAGNITUDE_ENERGY_DELTA) return String("J");
  80. if (type == MAGNITUDE_EVENTS) return String("/min");
  81. if (type == MAGNITUDE_PM1dot0) return String("µg/m3");
  82. if (type == MAGNITUDE_PM2dot5) return String("µg/m3");
  83. if (type == MAGNITUDE_PM10) return String("µg/m3");
  84. return String();
  85. }
  86. double _sensorProcess(magnitude_t type, double value) {
  87. if (type == MAGNITUDE_TEMPERATURE) {
  88. if (_sensor_temperature_units == TMP_FAHRENHEIT) value = value * 1.8 + 32;
  89. value = value + _sensor_temperature_correction;
  90. }
  91. return roundTo(value, _sensorDecimals(type));
  92. }
  93. void _sensorConfigure() {
  94. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  95. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  96. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  97. }
  98. #if WEB_SUPPORT
  99. void _sensorWebSocketOnSend(JsonObject& root) {
  100. char buffer[10];
  101. bool hasTemperature = false;
  102. JsonArray& sensors = root.createNestedArray("sensors");
  103. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  104. sensor_magnitude_t magnitude = _magnitudes[i];
  105. unsigned char decimals = _sensorDecimals(magnitude.type);
  106. dtostrf(magnitude.current, 1-sizeof(buffer), decimals, buffer);
  107. JsonObject& sensor = sensors.createNestedObject();
  108. sensor["type"] = int(magnitude.type);
  109. sensor["value"] = String(buffer);
  110. sensor["units"] = _sensorUnits(magnitude.type);
  111. sensor["description"] = magnitude.sensor->slot(magnitude.local);
  112. if (magnitude.type == MAGNITUDE_TEMPERATURE) hasTemperature = true;
  113. }
  114. //root["apiRealTime"] = _sensor_realtime;
  115. root["tmpUnits"] = _sensor_temperature_units;
  116. root["tmpCorrection"] = _sensor_temperature_correction;
  117. if (hasTemperature) root["temperatureVisible"] = 1;
  118. }
  119. void _sensorAPISetup() {
  120. for (unsigned char magnitude_id=0; magnitude_id<_magnitudes.size(); magnitude_id++) {
  121. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  122. String topic = _sensorTopic(magnitude.type);
  123. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) topic = topic + "/" + String(magnitude.global);
  124. apiRegister(topic.c_str(), topic.c_str(), [magnitude_id](char * buffer, size_t len) {
  125. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  126. unsigned char decimals = _sensorDecimals(magnitude.type);
  127. double value = _sensor_realtime ? magnitude.current : magnitude.filtered;
  128. dtostrf(value, 1-len, decimals, buffer);
  129. });
  130. }
  131. }
  132. #endif
  133. void _sensorTick() {
  134. for (unsigned char i=0; i<_sensors.size(); i++) {
  135. _sensors[i]->tick();
  136. }
  137. }
  138. void _sensorPre() {
  139. for (unsigned char i=0; i<_sensors.size(); i++) {
  140. _sensors[i]->pre();
  141. if (!_sensors[i]->status()) {
  142. DEBUG_MSG("[SENSOR] Error reading data from %s (error: %d)\n",
  143. _sensors[i]->name().c_str(),
  144. _sensors[i]->error()
  145. );
  146. }
  147. }
  148. }
  149. void _sensorPost() {
  150. for (unsigned char i=0; i<_sensors.size(); i++) {
  151. _sensors[i]->post();
  152. }
  153. }
  154. // -----------------------------------------------------------------------------
  155. // Interrupts
  156. // -----------------------------------------------------------------------------
  157. #if COUNTER_SUPPORT
  158. unsigned char _event_sensor_id = 0;
  159. void isrEventSensor() {
  160. _sensors[_event_sensor_id]->InterruptHandler();
  161. }
  162. #endif // COUNTER_SUPPORT
  163. // -----------------------------------------------------------------------------
  164. // Values
  165. // -----------------------------------------------------------------------------
  166. void sensorRegister(BaseSensor * sensor) {
  167. _sensors.push_back(sensor);
  168. }
  169. unsigned char sensorCount() {
  170. return _sensors.size();
  171. }
  172. unsigned char magnitudeCount() {
  173. return _magnitudes.size();
  174. }
  175. String magnitudeName(unsigned char index) {
  176. if (index < _magnitudes.size()) {
  177. sensor_magnitude_t magnitude = _magnitudes[index];
  178. return magnitude.sensor->slot(magnitude.local);
  179. }
  180. return String();
  181. }
  182. unsigned char magnitudeType(unsigned char index) {
  183. if (index < _magnitudes.size()) {
  184. return int(_magnitudes[index].type);
  185. }
  186. return MAGNITUDE_NONE;
  187. }
  188. void sensorInit() {
  189. #if DHT_SUPPORT
  190. #include "sensors/DHTSensor.h"
  191. sensorRegister(new DHTSensor(DHT_PIN, DHT_TYPE, DHT_PULLUP));
  192. #endif
  193. #if DS18B20_SUPPORT
  194. #include "sensors/DallasSensor.h"
  195. sensorRegister(new DallasSensor(DS18B20_PIN, SENSOR_READ_INTERVAL, DS18B20_PULLUP));
  196. #endif
  197. #if SI7021_SUPPORT
  198. #include "sensors/SI7021Sensor.h"
  199. sensorRegister(new SI7021Sensor(SI7021_ADDRESS));
  200. #endif
  201. #if BME280_SUPPORT
  202. #include "sensors/BME280Sensor.h"
  203. sensorRegister(new BME280Sensor(BME280_ADDRESS));
  204. #endif
  205. #if ANALOG_SUPPORT
  206. #include "sensors/AnalogSensor.h"
  207. sensorRegister(new AnalogSensor(ANALOG_PIN));
  208. #endif
  209. #if EMON_ANALOG_SUPPORT
  210. #include "sensors/EmonAnalogSensor.h"
  211. sensorRegister(new EmonAnalogSensor(A0, EMON_MAINS_VOLTAGE, EMON_ANALOG_ADC_BITS, EMON_ANALOG_REFERENCE_VOLTAGE, EMON_ANALOG_CURRENT_RATIO));
  212. #endif
  213. #if EMON_ADC121_SUPPORT
  214. #include "sensors/EmonADC121Sensor.h"
  215. sensorRegister(new EmonADC121Sensor(EMON_ADC121_I2C_ADDRESS, EMON_MAINS_VOLTAGE, EMON_ADC121_ADC_BITS, EMON_ADC121_REFERENCE_VOLTAGE, EMON_ADC121_CURRENT_RATIO));
  216. #endif
  217. #if EMON_ADS1X15_SUPPORT
  218. #include "sensors/EmonADS1X15Sensor.h"
  219. 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));
  220. #endif
  221. #if PMSX003_SUPPORT
  222. #include "sensors/PMSX003Sensor.h"
  223. sensorRegister(new PMSX003Sensor(PMS_RX_PIN, PMS_TX_PIN));
  224. #endif
  225. #if COUNTER_SUPPORT
  226. #include "sensors/EventSensor.h"
  227. sensorRegister(new EventSensor(COUNTER_PIN, COUNTER_PIN_MODE, COUNTER_DEBOUNCE));
  228. _event_sensor_id = sensorCount() - 1;
  229. attachInterrupt(COUNTER_PIN, isrEventSensor, COUNTER_INTERRUPT_MODE);
  230. #endif
  231. }
  232. void sensorSetup() {
  233. // Load sensors
  234. sensorInit();
  235. // Load magnitudes
  236. for (unsigned char i=0; i<_sensors.size(); i++) {
  237. BaseSensor * sensor = _sensors[i];
  238. DEBUG_MSG("[SENSOR] %s\n", sensor->name().c_str());
  239. for (unsigned char k=0; k<sensor->count(); k++) {
  240. magnitude_t type = sensor->type(k);
  241. sensor_magnitude_t new_magnitude;
  242. new_magnitude.sensor = sensor;
  243. new_magnitude.local = k;
  244. new_magnitude.type = type;
  245. new_magnitude.global = _counts[type];
  246. new_magnitude.current = 0;
  247. new_magnitude.filtered = 0;
  248. new_magnitude.reported = 0;
  249. new_magnitude.min_change = 0;
  250. if (type == MAGNITUDE_EVENTS) {
  251. new_magnitude.filter = new MovingAverageFilter(SENSOR_REPORT_EVERY);
  252. } else {
  253. new_magnitude.filter = new MedianFilter();
  254. }
  255. _magnitudes.push_back(new_magnitude);
  256. DEBUG_MSG("[SENSOR] -> %s:%d\n", _sensorTopic(type).c_str(), _counts[type]);
  257. _counts[type] = _counts[type] + 1;
  258. }
  259. }
  260. #if WEB_SUPPORT
  261. // Websockets
  262. wsOnSendRegister(_sensorWebSocketOnSend);
  263. wsOnAfterParseRegister(_sensorConfigure);
  264. // API
  265. _sensorAPISetup();
  266. #endif
  267. }
  268. void sensorLoop() {
  269. static unsigned long last_update = 0;
  270. static unsigned long report_count = 0;
  271. // Tick hook
  272. _sensorTick();
  273. // Check if we should read new data
  274. if (millis() - last_update > SENSOR_READ_INTERVAL) {
  275. last_update = millis();
  276. report_count = (report_count + 1) % SENSOR_REPORT_EVERY;
  277. double current;
  278. double filtered;
  279. char buffer[64];
  280. // Pre-read hook
  281. _sensorPre();
  282. // Get readings
  283. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  284. sensor_magnitude_t magnitude = _magnitudes[i];
  285. if (magnitude.sensor->status()) {
  286. unsigned char decimals = _sensorDecimals(magnitude.type);
  287. current = magnitude.sensor->value(magnitude.local);
  288. magnitude.filter->add(current);
  289. // Special case
  290. if (magnitude.type == MAGNITUDE_EVENTS) current = magnitude.filter->result();
  291. current = _sensorProcess(magnitude.type, current);
  292. _magnitudes[i].current = current;
  293. // Debug
  294. #if true
  295. {
  296. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  297. DEBUG_MSG("[SENSOR] %s - %s: %s%s\n",
  298. magnitude.sensor->slot(magnitude.local).c_str(),
  299. _sensorTopic(magnitude.type).c_str(),
  300. buffer,
  301. _sensorUnits(magnitude.type).c_str()
  302. );
  303. }
  304. #endif
  305. // Time to report (we do it every SENSOR_REPORT_EVERY readings)
  306. if (report_count == 0) {
  307. filtered = magnitude.filter->result();
  308. magnitude.filter->reset();
  309. filtered = _sensorProcess(magnitude.type, filtered);
  310. _magnitudes[i].filtered = filtered;
  311. // Check if there is a minimum change threshold to report
  312. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  313. _magnitudes[i].reported = filtered;
  314. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  315. #if MQTT_SUPPORT
  316. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  317. mqttSend(_sensorTopic(magnitude.type).c_str(), magnitude.global, buffer);
  318. } else {
  319. mqttSend(_sensorTopic(magnitude.type).c_str(), buffer);
  320. }
  321. #endif
  322. #if INFLUXDB_SUPPORT
  323. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  324. idbSend(_sensorTopic(magnitude.type).c_str(), magnitude.global, buffer);
  325. } else {
  326. idbSend(_sensorTopic(magnitude.type).c_str(), buffer);
  327. }
  328. #endif
  329. #if DOMOTICZ_SUPPORT
  330. {
  331. char key[15];
  332. snprintf_P(key, sizeof(key), PSTR("dczSensor%d"), i);
  333. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  334. int status;
  335. if (filtered > 70) {
  336. status = HUMIDITY_WET;
  337. } else if (filtered > 45) {
  338. status = HUMIDITY_COMFORTABLE;
  339. } else if (filtered > 30) {
  340. status = HUMIDITY_NORMAL;
  341. } else {
  342. status = HUMIDITY_DRY;
  343. }
  344. char status_buf[5];
  345. itoa(status, status_buf, 10);
  346. domoticzSend(key, buffer, status_buf);
  347. } else {
  348. domoticzSend(key, 0, buffer);
  349. }
  350. }
  351. #endif
  352. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  353. } // if (report_count == 0)
  354. } // if (magnitude.sensor->status())
  355. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  356. // Post-read hook
  357. _sensorPost();
  358. #if WEB_SUPPORT
  359. wsSend(_sensorWebSocketOnSend);
  360. #endif
  361. }
  362. }