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.

434 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(new EmonAnalogSensor(A0, EMON_ANALOG_MAINS_VOLTAGE, EMON_ANALOG_ADC_BITS, EMON_ANALOG_REFERENCE_VOLTAGE, EMON_ANALOG_CURRENT_RATIO));
  197. #endif
  198. #if EMON_ADC121_SUPPORT
  199. #include "sensors/EmonADC121Sensor.h"
  200. sensorRegister(new EmonADC121Sensor(EMON_ADC121_I2C_ADDRESS, EMON_ANALOG_MAINS_VOLTAGE, EMON_ANALOG_ADC_BITS, EMON_ANALOG_REFERENCE_VOLTAGE, EMON_ANALOG_CURRENT_RATIO));
  201. #endif
  202. #if COUNTER_SUPPORT
  203. if (_sensor_isr == 0xFF) {
  204. #include "sensors/EventSensor.h"
  205. sensorRegister(new EventSensor(COUNTER_PIN, COUNTER_PIN_MODE, COUNTER_DEBOUNCE));
  206. sensorInterrupt(sensorCount()-1, COUNTER_PIN, COUNTER_INTERRUPT_MODE);
  207. }
  208. #endif
  209. }
  210. void sensorSetup() {
  211. // Load sensors
  212. sensorInit();
  213. // Load magnitudes
  214. for (unsigned char i=0; i<_sensors.size(); i++) {
  215. BaseSensor * sensor = _sensors[i];
  216. DEBUG_MSG("[SENSOR] %s\n", sensor->name().c_str());
  217. for (unsigned char k=0; k<sensor->count(); k++) {
  218. magnitude_t type = sensor->type(k);
  219. sensor_magnitude_t new_magnitude;
  220. new_magnitude.sensor = sensor;
  221. new_magnitude.local = k;
  222. new_magnitude.type = type;
  223. new_magnitude.global = _counts[type];
  224. new_magnitude.current = 0;
  225. new_magnitude.filtered = 0;
  226. new_magnitude.reported = 0;
  227. new_magnitude.min_change = 0;
  228. if (type == MAGNITUDE_EVENTS) {
  229. new_magnitude.filter = new MovingAverageFilter(SENSOR_REPORT_EVERY);
  230. } else {
  231. new_magnitude.filter = new MedianFilter();
  232. }
  233. _magnitudes.push_back(new_magnitude);
  234. DEBUG_MSG("[SENSOR] -> %s:%d\n", _sensorTopic(type).c_str(), _counts[type]);
  235. _counts[type] = _counts[type] + 1;
  236. }
  237. }
  238. #if WEB_SUPPORT
  239. // Websockets
  240. wsOnSendRegister(_sensorWebSocketOnSend);
  241. wsOnAfterParseRegister(_sensorConfigure);
  242. // API
  243. _sensorAPISetup();
  244. #endif
  245. }
  246. void sensorLoop() {
  247. static unsigned long last_update = 0;
  248. static unsigned long report_count = 0;
  249. // Tick hook
  250. _sensorTick();
  251. // Check if we should read new data
  252. if (millis() - last_update > SENSOR_READ_INTERVAL) {
  253. last_update = millis();
  254. report_count = (report_count + 1) % SENSOR_REPORT_EVERY;
  255. double current;
  256. double filtered;
  257. char buffer[64];
  258. // Pre-read hook
  259. _sensorPre();
  260. // Get readings
  261. for (unsigned char i=0; i<_magnitudes.size(); i++) {
  262. sensor_magnitude_t magnitude = _magnitudes[i];
  263. if (magnitude.sensor->status()) {
  264. unsigned char decimals = _sensorDecimals(magnitude.type);
  265. current = magnitude.sensor->value(magnitude.local);
  266. magnitude.filter->add(current);
  267. // Special case
  268. if (magnitude.type == MAGNITUDE_EVENTS) current = magnitude.filter->result();
  269. current = _sensorProcess(magnitude.type, current);
  270. _magnitudes[i].current = current;
  271. // Debug
  272. #if true
  273. {
  274. dtostrf(current, 1-sizeof(buffer), decimals, buffer);
  275. DEBUG_MSG("[SENSOR] %s - %s: %s%s\n",
  276. magnitude.sensor->name().c_str(),
  277. _sensorTopic(magnitude.type).c_str(),
  278. buffer,
  279. _sensorUnits(magnitude.type).c_str()
  280. );
  281. }
  282. #endif
  283. // Time to report (we do it every SENSOR_REPORT_EVERY readings)
  284. if (report_count == 0) {
  285. filtered = magnitude.filter->result();
  286. magnitude.filter->reset();
  287. filtered = _sensorProcess(magnitude.type, filtered);
  288. _magnitudes[i].filtered = filtered;
  289. // Check if there is a minimum change threshold to report
  290. if (fabs(filtered - magnitude.reported) >= magnitude.min_change) {
  291. _magnitudes[i].reported = filtered;
  292. dtostrf(filtered, 1-sizeof(buffer), decimals, buffer);
  293. #if MQTT_SUPPORT
  294. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  295. mqttSend(_sensorTopic(magnitude.type).c_str(), magnitude.global, buffer);
  296. } else {
  297. mqttSend(_sensorTopic(magnitude.type).c_str(), buffer);
  298. }
  299. #endif
  300. #if INFLUXDB_SUPPORT
  301. if (SENSOR_USE_INDEX || (_counts[magnitude.type] > 1)) {
  302. idbSend(_sensorTopic(magnitude.type).c_str(), magnitude.global, buffer);
  303. } else {
  304. idbSend(_sensorTopic(magnitude.type).c_str(), buffer);
  305. }
  306. #endif
  307. #if DOMOTICZ_SUPPORT
  308. {
  309. char key[15];
  310. snprintf_P(key, sizeof(key), PSTR("dczSensor%d"), i);
  311. if (magnitude.type == MAGNITUDE_HUMIDITY) {
  312. int status;
  313. if (filtered > 70) {
  314. status = HUMIDITY_WET;
  315. } else if (filtered > 45) {
  316. status = HUMIDITY_COMFORTABLE;
  317. } else if (filtered > 30) {
  318. status = HUMIDITY_NORMAL;
  319. } else {
  320. status = HUMIDITY_DRY;
  321. }
  322. char status_buf[5];
  323. itoa(status, status_buf, 10);
  324. domoticzSend(key, buffer, status_buf);
  325. } else {
  326. domoticzSend(key, 0, buffer);
  327. }
  328. }
  329. #endif
  330. } // if (fabs(filtered - magnitude.reported) >= magnitude.min_change)
  331. } // if (report_count == 0)
  332. } // if (magnitude.sensor->status())
  333. } // for (unsigned char i=0; i<_magnitudes.size(); i++)
  334. // Post-read hook
  335. _sensorPost();
  336. #if WEB_SUPPORT
  337. wsSend(_sensorWebSocketOnSend);
  338. #endif
  339. }
  340. }