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.

453 lines
16 KiB

  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("/m");
  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. // Values
  156. // -----------------------------------------------------------------------------
  157. void sensorISR() {
  158. _sensors[_sensor_isr]->InterruptHandler();
  159. }
  160. void sensorRegister(BaseSensor * sensor) {
  161. _sensors.push_back(sensor);
  162. }
  163. unsigned char sensorCount() {
  164. return _sensors.size();
  165. }
  166. unsigned char magnitudeCount() {
  167. return _magnitudes.size();
  168. }
  169. String magnitudeName(unsigned char index) {
  170. if (index < _magnitudes.size()) {
  171. sensor_magnitude_t magnitude = _magnitudes[index];
  172. return magnitude.sensor->slot(magnitude.local);
  173. }
  174. return String();
  175. }
  176. unsigned char magnitudeType(unsigned char index) {
  177. if (index < _magnitudes.size()) {
  178. return int(_magnitudes[index].type);
  179. }
  180. return MAGNITUDE_NONE;
  181. }
  182. void sensorInterrupt(unsigned char sensor_id, unsigned char gpio, int mode) {
  183. _sensor_isr = sensor_id;
  184. attachInterrupt(gpio, sensorISR, mode);
  185. }
  186. void sensorInit() {
  187. #if DHT_SUPPORT
  188. #include "sensors/DHTSensor.h"
  189. sensorRegister(new DHTSensor(DHT_PIN, DHT_TYPE, DHT_PULLUP));
  190. #endif
  191. #if DS18B20_SUPPORT
  192. #include "sensors/DallasSensor.h"
  193. sensorRegister(new DallasSensor(DS18B20_PIN, SENSOR_READ_INTERVAL, DS18B20_PULLUP));
  194. #endif
  195. #if SI7021_SUPPORT
  196. #include "sensors/SI7021Sensor.h"
  197. sensorRegister(new SI7021Sensor(SI7021_ADDRESS));
  198. #endif
  199. #if ANALOG_SUPPORT
  200. #include "sensors/AnalogSensor.h"
  201. sensorRegister(new AnalogSensor(ANALOG_PIN));
  202. #endif
  203. #if EMON_ANALOG_SUPPORT
  204. #include "sensors/EmonAnalogSensor.h"
  205. sensorRegister(new EmonAnalogSensor(A0, EMON_MAINS_VOLTAGE, EMON_ANALOG_ADC_BITS, EMON_ANALOG_REFERENCE_VOLTAGE, EMON_ANALOG_CURRENT_RATIO));
  206. #endif
  207. #if EMON_ADC121_SUPPORT
  208. #include "sensors/EmonADC121Sensor.h"
  209. sensorRegister(new EmonADC121Sensor(EMON_ADC121_I2C_ADDRESS, EMON_MAINS_VOLTAGE, EMON_ADC121_ADC_BITS, EMON_ADC121_REFERENCE_VOLTAGE, EMON_ADC121_CURRENT_RATIO));
  210. #endif
  211. #if EMON_ADS1115_SUPPORT
  212. #include "sensors/EmonADS1115Sensor.h"
  213. sensorRegister(new EmonADS1115Sensor(EMON_ADS1115_I2C_ADDRESS, EMON_ADS1115_PORT_MASK, EMON_MAINS_VOLTAGE, EMON_ADS1115_ADC_BITS, EMON_ADS1115_REFERENCE_VOLTAGE, EMON_ADS1115_CURRENT_RATIO));
  214. #endif
  215. #if PMSX003_SUPPORT
  216. #include "sensors/PMSX003Sensor.h"
  217. sensorRegister(new PMSX003Sensor(PMS_RX_PIN, PMS_TX_PIN));
  218. #endif
  219. #if COUNTER_SUPPORT
  220. if (_sensor_isr == 0xFF) {
  221. #include "sensors/EventSensor.h"
  222. sensorRegister(new EventSensor(COUNTER_PIN, COUNTER_PIN_MODE, COUNTER_DEBOUNCE));
  223. sensorInterrupt(sensorCount()-1, COUNTER_PIN, COUNTER_INTERRUPT_MODE);
  224. }
  225. #endif
  226. }
  227. void sensorSetup() {
  228. // Load sensors
  229. sensorInit();
  230. // Load magnitudes
  231. for (unsigned char i=0; i<_sensors.size(); i++) {
  232. BaseSensor * sensor = _sensors[i];
  233. DEBUG_MSG("[SENSOR] %s\n", sensor->name().c_str());
  234. for (unsigned char k=0; k<sensor->count(); k++) {
  235. magnitude_t type = sensor->type(k);
  236. sensor_magnitude_t new_magnitude;
  237. new_magnitude.sensor = sensor;
  238. new_magnitude.local = k;
  239. new_magnitude.type = type;
  240. new_magnitude.global = _counts[type];
  241. new_magnitude.current = 0;
  242. new_magnitude.filtered = 0;
  243. new_magnitude.reported = 0;
  244. new_magnitude.min_change = 0;
  245. if (type == MAGNITUDE_EVENTS) {
  246. new_magnitude.filter = new MovingAverageFilter(SENSOR_REPORT_EVERY);
  247. } else {
  248. new_magnitude.filter = new MedianFilter();
  249. }
  250. _magnitudes.push_back(new_magnitude);
  251. DEBUG_MSG("[SENSOR] -> %s:%d\n", _sensorTopic(type).c_str(), _counts[type]);
  252. _counts[type] = _counts[type] + 1;
  253. }
  254. }
  255. #if WEB_SUPPORT
  256. // Websockets
  257. wsOnSendRegister(_sensorWebSocketOnSend);
  258. wsOnAfterParseRegister(_sensorConfigure);
  259. // API
  260. _sensorAPISetup();
  261. #endif
  262. }
  263. void sensorLoop() {
  264. static unsigned long last_update = 0;
  265. static unsigned long report_count = 0;
  266. // Tick hook
  267. _sensorTick();
  268. // Check if we should read new data
  269. if (millis() - last_update > SENSOR_READ_INTERVAL) {
  270. last_update = millis();
  271. report_count = (report_count + 1) % SENSOR_REPORT_EVERY;
  272. double current;
  273. double filtered;
  274. char buffer[64];
  275. // Pre-read hook
  276. _sensorPre();
  277. // Get readings
  278. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  279. sensor_magnitude_t magnitude = _magnitudes[i];
  280. if (magnitude.sensor->status()) {
  281. unsigned char decimals = _sensorDecimals(magnitude.type);
  282. current = magnitude.sensor->value(magnitude.local);
  283. magnitude.filter->add(current);
  284. // Special case
  285. if (magnitude.type == MAGNITUDE_EVENTS) current = magnitude.filter->result();
  286. current = _sensorProcess(magnitude.type, current);
  287. _magnitudes[i].current = current;
  288. // Debug
  289. #if true
  290. {
  291. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  292. DEBUG_MSG("[SENSOR] %s - %s: %s%s\n",
  293. magnitude.sensor->slot(magnitude.local).c_str(),
  294. _sensorTopic(magnitude.type).c_str(),
  295. buffer,
  296. _sensorUnits(magnitude.type).c_str()
  297. );
  298. }
  299. #endif
  300. // Time to report (we do it every SENSOR_REPORT_EVERY readings)
  301. if (report_count == 0) {
  302. filtered = magnitude.filter->result();
  303. magnitude.filter->reset();
  304. filtered = _sensorProcess(magnitude.type, filtered);
  305. _magnitudes[i].filtered = filtered;
  306. // Check if there is a minimum change threshold to report
  307. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  308. _magnitudes[i].reported = filtered;
  309. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  310. #if MQTT_SUPPORT
  311. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  312. mqttSend(_sensorTopic(magnitude.type).c_str(), magnitude.global, buffer);
  313. } else {
  314. mqttSend(_sensorTopic(magnitude.type).c_str(), buffer);
  315. }
  316. #endif
  317. #if INFLUXDB_SUPPORT
  318. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  319. idbSend(_sensorTopic(magnitude.type).c_str(), magnitude.global, buffer);
  320. } else {
  321. idbSend(_sensorTopic(magnitude.type).c_str(), buffer);
  322. }
  323. #endif
  324. #if DOMOTICZ_SUPPORT
  325. {
  326. char key[15];
  327. snprintf_P(key, sizeof(key), PSTR("dczSensor%d"), i);
  328. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  329. int status;
  330. if (filtered > 70) {
  331. status = HUMIDITY_WET;
  332. } else if (filtered > 45) {
  333. status = HUMIDITY_COMFORTABLE;
  334. } else if (filtered > 30) {
  335. status = HUMIDITY_NORMAL;
  336. } else {
  337. status = HUMIDITY_DRY;
  338. }
  339. char status_buf[5];
  340. itoa(status, status_buf, 10);
  341. domoticzSend(key, buffer, status_buf);
  342. } else {
  343. domoticzSend(key, 0, buffer);
  344. }
  345. }
  346. #endif
  347. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  348. } // if (report_count == 0)
  349. } // if (magnitude.sensor->status())
  350. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  351. // Post-read hook
  352. _sensorPost();
  353. #if WEB_SUPPORT
  354. wsSend(_sensorWebSocketOnSend);
  355. #endif
  356. }
  357. }