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.

101 lines
2.4 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. /*
  2. COUNTER MODULE
  3. Copyright (C) 2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if COUNTER_SUPPORT
  6. volatile unsigned long _counterCurrent = 0;
  7. volatile unsigned long _counterLast = 0;
  8. unsigned long _counterBuffer[COUNTER_REPORT_EVERY] = {0};
  9. unsigned char _counterBufferPointer = 0;
  10. unsigned long _counterValue = 0;
  11. // -----------------------------------------------------------------------------
  12. // COUNTER
  13. // -----------------------------------------------------------------------------
  14. void ICACHE_RAM_ATTR _counterISR() {
  15. if (millis() - _counterLast > COUNTER_DEBOUNCE) {
  16. ++_counterCurrent;
  17. _counterLast = millis();
  18. }
  19. }
  20. #if WEB_SUPPORT
  21. void _counterWSSend(JsonObject& root) {
  22. root["counterVisible"] = 1;
  23. root["counterValue"] = getCounter();
  24. }
  25. #endif
  26. unsigned long getCounter() {
  27. return _counterValue;
  28. }
  29. void counterSetup() {
  30. pinMode(COUNTER_PIN, COUNTER_PIN_MODE);
  31. attachInterrupt(COUNTER_PIN, _counterISR, COUNTER_INTERRUPT_MODE);
  32. #if WEB_SUPPORT
  33. // Websockets
  34. wsRegister(_counterWSSend);
  35. // API
  36. apiRegister(COUNTER_TOPIC, COUNTER_TOPIC, [](char * buffer, size_t len) {
  37. snprintf_P(buffer, len, PSTR("%d"), getCounter());
  38. });
  39. #endif
  40. DEBUG_MSG_P(PSTR("[COUNTER] Counter on GPIO %d\n"), COUNTER_PIN);
  41. }
  42. void counterLoop() {
  43. // Check if we should read new data
  44. static unsigned long last_update = 0;
  45. if ((millis() - last_update) < COUNTER_UPDATE_INTERVAL) return;
  46. last_update = millis();
  47. // Update buffer counts
  48. _counterValue = _counterValue - _counterBuffer[_counterBufferPointer] + _counterCurrent;
  49. _counterBuffer[_counterBufferPointer] = _counterCurrent;
  50. _counterCurrent = 0;
  51. _counterBufferPointer = (_counterBufferPointer + 1) % COUNTER_REPORT_EVERY;
  52. DEBUG_MSG_P(PSTR("[COUNTER] Value: %d\n"), _counterValue);
  53. // Update websocket clients
  54. #if WEB_SUPPORT
  55. wsSend(_counterWSSend);
  56. #endif
  57. // Do we have to report?
  58. if (_counterBufferPointer == 0) {
  59. // Send MQTT messages
  60. mqttSend(getSetting("counterTopic", COUNTER_TOPIC).c_str(), String(_counterValue).c_str());
  61. // Send to Domoticz
  62. #if DOMOTICZ_SUPPORT
  63. domoticzSend("dczCountIdx", 0, String(_counterValue).c_str());
  64. #endif
  65. // Send to InfluxDB
  66. #if INFLUXDB_SUPPORT
  67. idbSend(COUNTER_TOPIC, _counterValue);
  68. #endif
  69. }
  70. }
  71. #endif // COUNTER_SUPPORT