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.

74 lines
2.0 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. #include <cmath>
  13. void _prometheusRequestHandler(AsyncWebServerRequest* request) {
  14. static_assert(RELAY_SUPPORT || SENSOR_SUPPORT, "");
  15. // TODO: Add more stuff?
  16. // Note: Response 'stream' backing buffer is customizable. Default is 1460 bytes (see ESPAsyncWebServer.h)
  17. // In case printf overflows, memory of CurrentSize+N{overflow} will be allocated to replace
  18. // the existing buffer. Previous buffer will be copied into the new and destroyed after that.
  19. AsyncResponseStream *response = request->beginResponseStream("text/plain");
  20. #if RELAY_SUPPORT
  21. for (unsigned char index = 0; index < relayCount(); ++index) {
  22. response->printf("relay%u %d\n", index, static_cast<int>(relayStatus(index)));
  23. }
  24. #endif
  25. #if SENSOR_SUPPORT
  26. char buffer[64] { 0 };
  27. for (unsigned char index = 0; index < magnitudeCount(); ++index) {
  28. auto value = magnitudeValue(index);
  29. if (std::isnan(value.get()) || std::isinf(value.get())) {
  30. continue;
  31. }
  32. String topic(magnitudeTopicIndex(index));
  33. topic.replace("/", "");
  34. magnitudeFormat(value, buffer, sizeof(buffer));
  35. response->printf("%s %s\n", topic.c_str(), buffer);
  36. }
  37. #endif
  38. response->write('\n');
  39. request->send(response);
  40. }
  41. bool _prometheusRequestCallback(AsyncWebServerRequest* request) {
  42. if (request->url().equals(F("/api/metrics"))) {
  43. webLog(request);
  44. if (apiAuthenticate(request)) {
  45. _prometheusRequestHandler(request);
  46. }
  47. return true;
  48. }
  49. return false;
  50. }
  51. void prometheusSetup() {
  52. webRequestRegister(_prometheusRequestCallback);
  53. }
  54. #endif // PROMETHEUS_SUPPORT