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.

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