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.

67 lines
1.8 KiB

  1. /*
  2. PROMETHEUS METRICS MODULE
  3. Copyright (C) 2020 by Maxim Prokhorov <prokhorov dot max at outlook dot com>
  4. */
  5. #include "espurna.h"
  6. #if WEB_SUPPORT && PROMETHEUS_SUPPORT
  7. #include "prometheus.h"
  8. #include "api.h"
  9. #include "relay.h"
  10. #include "sensor.h"
  11. #include "web.h"
  12. void _prometheusRequestHandler(AsyncWebServerRequest* request) {
  13. static_assert(RELAY_SUPPORT || SENSOR_SUPPORT, "");
  14. // TODO: Add more stuff?
  15. // Note: Response 'stream' backing buffer is customizable. Default is 1460 bytes (see ESPAsyncWebServer.h)
  16. // In case printf overflows, memory of CurrentSize+N{overflow} will be allocated to replace
  17. // the existing buffer. Previous buffer will be copied into the new and destroyed after that.
  18. AsyncResponseStream *response = request->beginResponseStream("text/plain");
  19. #if RELAY_SUPPORT
  20. for (unsigned char index = 0; index < relayCount(); ++index) {
  21. response->printf("relay%u %d\n", index, static_cast<int>(relayStatus(index)));
  22. }
  23. #endif
  24. #if SENSOR_SUPPORT
  25. char buffer[64] { 0 };
  26. for (unsigned char index = 0; index < magnitudeCount(); ++index) {
  27. String topic(magnitudeTopicIndex(index));
  28. topic.replace("/", "");
  29. magnitudeFormat(magnitudeValue(index), buffer, sizeof(buffer));
  30. response->printf("%s %s\n", topic.c_str(), buffer);
  31. }
  32. #endif
  33. response->write('\n');
  34. request->send(response);
  35. }
  36. bool _prometheusRequestCallback(AsyncWebServerRequest* request) {
  37. if (request->url().equals(F("/api/metrics"))) {
  38. webLog(request);
  39. if (apiAuthenticate(request)) {
  40. _prometheusRequestHandler(request);
  41. }
  42. return true;
  43. }
  44. return false;
  45. }
  46. void prometheusSetup() {
  47. webRequestRegister(_prometheusRequestCallback);
  48. }
  49. #endif // PROMETHEUS_SUPPORT