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.

90 lines
2.4 KiB

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. unsigned long getCounter() {
  21. return _counterValue;
  22. }
  23. void counterSetup() {
  24. pinMode(COUNTER_PIN, COUNTER_PIN_MODE);
  25. attachInterrupt(COUNTER_PIN, _counterISR, COUNTER_INTERRUPT_MODE);
  26. #if WEB_SUPPORT
  27. apiRegister(COUNTER_TOPIC, COUNTER_TOPIC, [](char * buffer, size_t len) {
  28. snprintf_P(buffer, len, PSTR("%d"), getCounter());
  29. });
  30. #endif
  31. DEBUG_MSG_P(PSTR("[COUNTER] Counter on GPIO %d\n"), COUNTER_PIN);
  32. }
  33. void counterLoop() {
  34. // Check if we should read new data
  35. static unsigned long last_update = 0;
  36. if ((millis() - last_update) < COUNTER_UPDATE_INTERVAL) return;
  37. last_update = millis();
  38. // Update buffer counts
  39. _counterValue = _counterValue - _counterBuffer[_counterBufferPointer] + _counterCurrent;
  40. _counterBuffer[_counterBufferPointer] = _counterCurrent;
  41. _counterCurrent = 0;
  42. _counterBufferPointer = (_counterBufferPointer + 1) % COUNTER_REPORT_EVERY;
  43. DEBUG_MSG_P(PSTR("[COUNTER] Value: %d\n"), _counterValue);
  44. // Update websocket clients
  45. #if WEB_SUPPORT
  46. char buffer[100];
  47. snprintf_P(buffer, sizeof(buffer), PSTR("{\"counterVisible\": 1, \"counterValue\": %d}"), _counterValue);
  48. wsSend(buffer);
  49. #endif
  50. // Do we have to report?
  51. if (_counterBufferPointer == 0) {
  52. // Send MQTT messages
  53. mqttSend(getSetting("counterTopic", COUNTER_TOPIC).c_str(), String(_counterValue).c_str());
  54. // Send to Domoticz
  55. #if DOMOTICZ_SUPPORT
  56. domoticzSend("dczCountIdx", 0, String(_counterValue).c_str());
  57. #endif
  58. // Send to InfluxDB
  59. #if INFLUXDB_SUPPORT
  60. influxDBSend(COUNTER_TOPIC, _counterValue);
  61. #endif
  62. }
  63. }
  64. #endif // COUNTER_SUPPORT