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.

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