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.

410 lines
13 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) {
  32. return String(SENSOR_TEMPERATURE_TOPIC);
  33. } else if (type == MAGNITUDE_HUMIDITY) {
  34. return String(SENSOR_HUMIDITY_TOPIC);
  35. } else if (type == MAGNITUDE_ANALOG) {
  36. return String(SENSOR_ANALOG_TOPIC);
  37. } else if (type == MAGNITUDE_EVENTS) {
  38. return String(SENSOR_EVENTS_TOPIC);
  39. }
  40. return String(SENSOR_UNKNOWN_TOPIC);
  41. }
  42. unsigned char _sensorDecimals(magnitude_t type) {
  43. if (type == MAGNITUDE_TEMPERATURE) {
  44. return SENSOR_TEMPERATURE_DECIMALS;
  45. } else if (type == MAGNITUDE_HUMIDITY) {
  46. return SENSOR_HUMIDITY_DECIMALS;
  47. } else if (type == MAGNITUDE_ANALOG) {
  48. return SENSOR_ANALOG_DECIMALS;
  49. } else if (type == MAGNITUDE_EVENTS) {
  50. return SENSOR_EVENTS_DECIMALS;
  51. }
  52. return 0;
  53. }
  54. String _sensorUnits(magnitude_t type) {
  55. if (type == MAGNITUDE_TEMPERATURE) {
  56. if (_sensor_temperature_units == TMP_CELSIUS) {
  57. return String("C");
  58. } else {
  59. return String("F");
  60. }
  61. } else if (type == MAGNITUDE_HUMIDITY) {
  62. return String("%");
  63. } else if (type == MAGNITUDE_EVENTS) {
  64. return String("/m");
  65. }
  66. return String();
  67. }
  68. double _sensorProcess(magnitude_t type, double value) {
  69. if (type == MAGNITUDE_TEMPERATURE) {
  70. if (_sensor_temperature_units == TMP_FAHRENHEIT) value = value * 1.8 + 32;
  71. value = value + _sensor_temperature_correction;
  72. }
  73. return roundTo(value, _sensorDecimals(type));
  74. }
  75. void _sensorConfigure() {
  76. _sensor_realtime = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  77. _sensor_temperature_units = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  78. _sensor_temperature_correction = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  79. }
  80. #if WEB_SUPPORT
  81. void _sensorWebSocketOnSend(JsonObject& root) {
  82. char buffer[10];
  83. bool hasTemperature = false;
  84. JsonArray& sensors = root.createNestedArray("sensors");
  85. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  86. sensor_magnitude_t magnitude = _magnitudes[i];
  87. unsigned char decimals = _sensorDecimals(magnitude.type);
  88. dtostrf(magnitude.current, 1-sizeof(buffer), decimals, buffer);
  89. JsonObject& sensor = sensors.createNestedObject();
  90. sensor["type"] = int(magnitude.type);
  91. sensor["value"] = String(buffer);
  92. sensor["units"] = _sensorUnits(magnitude.type);
  93. sensor["description"] = magnitude.sensor->slot(magnitude.local);
  94. if (magnitude.type == MAGNITUDE_TEMPERATURE) hasTemperature = true;
  95. }
  96. //root["apiRealTime"] = _sensor_realtime;
  97. root["tmpUnits"] = _sensor_temperature_units;
  98. root["tmpCorrection"] = _sensor_temperature_correction;
  99. if (hasTemperature) root["temperatureVisible"] = 1;
  100. }
  101. void _sensorAPISetup() {
  102. for (unsigned char magnitude_id=0; magnitude_id<_magnitudes.size(); magnitude_id++) {
  103. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  104. String topic = _sensorTopic(magnitude.type);
  105. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) topic = topic + "/" + String(magnitude.global);
  106. apiRegister(topic.c_str(), topic.c_str(), [magnitude_id](char * buffer, size_t len) {
  107. sensor_magnitude_t magnitude = _magnitudes[magnitude_id];
  108. unsigned char decimals = _sensorDecimals(magnitude.type);
  109. double value = _sensor_realtime ? magnitude.current : magnitude.filtered;
  110. dtostrf(value, 1-len, decimals, buffer);
  111. });
  112. }
  113. }
  114. #endif
  115. void _sensorTick() {
  116. for (unsigned char i=0; i<_sensors.size(); i++) {
  117. _sensors[i]->tick();
  118. }
  119. }
  120. void _sensorPre() {
  121. for (unsigned char i=0; i<_sensors.size(); i++) {
  122. _sensors[i]->pre();
  123. if (!_sensors[i]->status()) {
  124. DEBUG_MSG("[SENSOR] Error reading data from %s (error: %d)\n",
  125. _sensors[i]->name().c_str(),
  126. _sensors[i]->error()
  127. );
  128. }
  129. }
  130. }
  131. void _sensorPost() {
  132. for (unsigned char i=0; i<_sensors.size(); i++) {
  133. _sensors[i]->post();
  134. }
  135. }
  136. // -----------------------------------------------------------------------------
  137. // Values
  138. // -----------------------------------------------------------------------------
  139. void sensorISR() {
  140. _sensors[_sensor_isr]->InterruptHandler();
  141. }
  142. void sensorRegister(BaseSensor * sensor) {
  143. _sensors.push_back(sensor);
  144. }
  145. unsigned char sensorCount() {
  146. return _sensors.size();
  147. }
  148. unsigned char magnitudeCount() {
  149. return _magnitudes.size();
  150. }
  151. String magnitudeName(unsigned char index) {
  152. if (index < _magnitudes.size()) {
  153. sensor_magnitude_t magnitude = _magnitudes[index];
  154. return magnitude.sensor->slot(magnitude.local);
  155. }
  156. return String();
  157. }
  158. unsigned char magnitudeType(unsigned char index) {
  159. if (index < _magnitudes.size()) {
  160. return int(_magnitudes[index].type);
  161. }
  162. return MAGNITUDE_NONE;
  163. }
  164. void sensorInterrupt(unsigned char sensor_id, unsigned char gpio, int mode) {
  165. _sensor_isr = sensor_id;
  166. attachInterrupt(gpio, sensorISR, mode);
  167. }
  168. void sensorInit() {
  169. #if DHT_SUPPORT
  170. #include "sensors/DHTSensor.h"
  171. sensorRegister(new DHTSensor(DHT_PIN, DHT_TYPE, DHT_PULLUP));
  172. #endif
  173. #if DS18B20_SUPPORT
  174. #include "sensors/DallasSensor.h"
  175. sensorRegister(new DallasSensor(DS18B20_PIN, SENSOR_READ_INTERVAL, DS18B20_PULLUP));
  176. #endif
  177. #if ANALOG_SUPPORT
  178. #include "sensors/AnalogSensor.h"
  179. sensorRegister(new AnalogSensor(ANALOG_PIN));
  180. #endif
  181. #if COUNTER_SUPPORT
  182. if (_sensor_isr == 0xFF) {
  183. #include "sensors/EventSensor.h"
  184. sensorRegister(new EventSensor(COUNTER_PIN, COUNTER_PIN_MODE, COUNTER_DEBOUNCE));
  185. sensorInterrupt(sensorCount()-1, COUNTER_PIN, COUNTER_INTERRUPT_MODE);
  186. }
  187. #endif
  188. }
  189. void sensorSetup() {
  190. // Load sensors
  191. sensorInit();
  192. // Load magnitudes
  193. for (unsigned char i=0; i<_sensors.size(); i++) {
  194. BaseSensor * sensor = _sensors[i];
  195. DEBUG_MSG("[SENSOR] %s\n", sensor->name().c_str());
  196. for (unsigned char k=0; k<sensor->count(); k++) {
  197. magnitude_t type = sensor->type(k);
  198. sensor_magnitude_t new_magnitude;
  199. new_magnitude.sensor = sensor;
  200. new_magnitude.local = k;
  201. new_magnitude.type = type;
  202. new_magnitude.global = _counts[type];
  203. new_magnitude.current = 0;
  204. new_magnitude.filtered = 0;
  205. new_magnitude.reported = 0;
  206. new_magnitude.min_change = 0;
  207. if (type == MAGNITUDE_EVENTS) {
  208. new_magnitude.filter = new MovingAverageFilter(SENSOR_REPORT_EVERY);
  209. } else {
  210. new_magnitude.filter = new MedianFilter();
  211. }
  212. _magnitudes.push_back(new_magnitude);
  213. DEBUG_MSG("[SENSOR] -> %s:%d\n", _sensorTopic(type).c_str(), _counts[type]);
  214. _counts[type] = _counts[type] + 1;
  215. }
  216. }
  217. #if WEB_SUPPORT
  218. // Websockets
  219. wsOnSendRegister(_sensorWebSocketOnSend);
  220. wsOnAfterParseRegister(_sensorConfigure);
  221. // API
  222. _sensorAPISetup();
  223. #endif
  224. }
  225. void sensorLoop() {
  226. static unsigned long last_update = 0;
  227. static unsigned long report_count = 0;
  228. // Tick hook
  229. _sensorTick();
  230. // Check if we should read new data
  231. if ((millis() - last_update > SENSOR_READ_INTERVAL) || (last_update == 0)) {
  232. last_update = millis();
  233. report_count = (report_count + 1) % SENSOR_REPORT_EVERY;
  234. double current;
  235. double filtered;
  236. char buffer[64];
  237. // Pre-read hook
  238. _sensorPre();
  239. // Get readings
  240. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  241. sensor_magnitude_t magnitude = _magnitudes[i];
  242. if (magnitude.sensor->status()) {
  243. unsigned char decimals = _sensorDecimals(magnitude.type);
  244. current = magnitude.sensor->value(magnitude.local);
  245. magnitude.filter->add(current);
  246. // Special case
  247. if (magnitude.type == MAGNITUDE_EVENTS) current = magnitude.filter->result();
  248. current = _sensorProcess(magnitude.type, current);
  249. _magnitudes[i].current = current;
  250. // Debug
  251. #if true
  252. {
  253. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  254. DEBUG_MSG("[SENSOR] %s - %s: %s%s\n",
  255. magnitude.sensor->name().c_str(),
  256. _sensorTopic(magnitude.type).c_str(),
  257. buffer,
  258. _sensorUnits(magnitude.type).c_str()
  259. );
  260. }
  261. #endif
  262. // Time to report (we do it every SENSOR_REPORT_EVERY readings)
  263. if (report_count == 0) {
  264. filtered = magnitude.filter->result();
  265. magnitude.filter->reset();
  266. filtered = _sensorProcess(magnitude.type, filtered);
  267. _magnitudes[i].filtered = filtered;
  268. // Check if there is a minimum change threshold to report
  269. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  270. _magnitudes[i].reported = filtered;
  271. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  272. #if MQTT_SUPPORT
  273. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  274. mqttSend(_sensorTopic(magnitude.type).c_str(), magnitude.global, buffer);
  275. } else {
  276. mqttSend(_sensorTopic(magnitude.type).c_str(), buffer);
  277. }
  278. #endif
  279. #if INFLUXDB_SUPPORT
  280. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  281. idbSend(_sensorTopic(magnitude.type).c_str(), magnitude.global, buffer);
  282. } else {
  283. idbSend(_sensorTopic(magnitude.type).c_str(), buffer);
  284. }
  285. #endif
  286. #if DOMOTICZ_SUPPORT
  287. {
  288. char key[15];
  289. snprintf_P(key, sizeof(key), PSTR("dczSensor%d"), i);
  290. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  291. int status;
  292. if (filtered > 70) {
  293. status = HUMIDITY_WET;
  294. } else if (filtered > 45) {
  295. status = HUMIDITY_COMFORTABLE;
  296. } else if (filtered > 30) {
  297. status = HUMIDITY_NORMAL;
  298. } else {
  299. status = HUMIDITY_DRY;
  300. }
  301. char status_buf[5];
  302. itoa(status, status_buf, 10);
  303. domoticzSend(key, buffer, status_buf);
  304. } else {
  305. domoticzSend(key, 0, buffer);
  306. }
  307. }
  308. #endif
  309. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  310. } // if (report_count == 0)
  311. } // if (magnitude.sensor->status())
  312. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  313. // Post-read hook
  314. _sensorPost();
  315. #if WEB_SUPPORT
  316. wsSend(_sensorWebSocketOnSend);
  317. #endif
  318. }
  319. }