interface_webhook.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. #ifdef ENABLE_WEBHOOK
  2. #include "interface_webhook.h"
  3. #include "esp_log.h"
  4. #include <time.h>
  5. #include "ClassLogFile.h"
  6. #include "esp_http_client.h"
  7. #include "time_sntp.h"
  8. #include "../../include/defines.h"
  9. #include <cJSON.h>
  10. #include <ClassFlowDefineTypes.h>
  11. static const char *TAG = "WEBHOOK";
  12. std::string _webhookURI;
  13. std::string _webhookApiKey;
  14. long _lastTimestamp;
  15. static esp_err_t http_event_handler(esp_http_client_event_t *evt);
  16. void WebhookInit(std::string _uri, std::string _apiKey)
  17. {
  18. _webhookURI = _uri;
  19. _webhookApiKey = _apiKey;
  20. _lastTimestamp = 0L;
  21. }
  22. bool WebhookPublish(std::vector<NumberPost*>* numbers)
  23. {
  24. if (_webhookURI.empty())
  25. {
  26. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "WebhookPublish aborted: no Uri configured");
  27. return false;
  28. }
  29. bool numbersWithError = false;
  30. cJSON *jsonArray = cJSON_CreateArray();
  31. for (int i = 0; i < (*numbers).size(); ++i)
  32. {
  33. string timezw = "";
  34. char buffer[80];
  35. time_t &lastPreValue = (*numbers)[i]->timeStampLastPreValue;
  36. struct tm* timeinfo = localtime(&lastPreValue);
  37. _lastTimestamp = static_cast<long>(lastPreValue);
  38. strftime(buffer, 80, PREVALUE_TIME_FORMAT_OUTPUT, timeinfo);
  39. timezw = std::string(buffer);
  40. cJSON *json = cJSON_CreateObject();
  41. cJSON_AddStringToObject(json, "timestamp", timezw.c_str());
  42. cJSON_AddStringToObject(json, "timestampLong", std::to_string(_lastTimestamp).c_str());
  43. cJSON_AddStringToObject(json, "name", (*numbers)[i]->name.c_str());
  44. cJSON_AddStringToObject(json, "rawValue", (*numbers)[i]->ReturnRawValue.c_str());
  45. cJSON_AddStringToObject(json, "value", (*numbers)[i]->ReturnValue.c_str());
  46. cJSON_AddStringToObject(json, "preValue", (*numbers)[i]->ReturnPreValue.c_str());
  47. cJSON_AddStringToObject(json, "rate", (*numbers)[i]->ReturnRateValue.c_str());
  48. cJSON_AddStringToObject(json, "changeAbsolute", (*numbers)[i]->ReturnChangeAbsolute.c_str());
  49. cJSON_AddStringToObject(json, "error", (*numbers)[i]->ErrorMessageText.c_str());
  50. cJSON_AddItemToArray(jsonArray, json);
  51. if ((*numbers)[i]->ErrorMessage) {
  52. numbersWithError = true;
  53. }
  54. }
  55. char *jsonString = cJSON_PrintUnformatted(jsonArray);
  56. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "sending webhook");
  57. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "sending JSON: " + std::string(jsonString));
  58. char response_buffer[MAX_HTTP_OUTPUT_BUFFER] = {0};
  59. esp_http_client_config_t http_config = {
  60. .url = _webhookURI.c_str(),
  61. .user_agent = "ESP32 Meter reader",
  62. .method = HTTP_METHOD_POST,
  63. .event_handler = http_event_handler,
  64. .buffer_size = MAX_HTTP_OUTPUT_BUFFER,
  65. .user_data = response_buffer
  66. };
  67. esp_http_client_handle_t http_client = esp_http_client_init(&http_config);
  68. if (!http_client)
  69. {
  70. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "WebhookPublish: failed to initialize HTTP client for Uri " + _webhookURI);
  71. cJSON_Delete(jsonArray);
  72. free(jsonString);
  73. return numbersWithError;
  74. }
  75. esp_http_client_set_header(http_client, "Content-Type", "application/json");
  76. esp_http_client_set_header(http_client, "APIKEY", _webhookApiKey.c_str());
  77. ESP_ERROR_CHECK(esp_http_client_set_post_field(http_client, jsonString, strlen(jsonString)));
  78. esp_err_t err = ESP_ERROR_CHECK_WITHOUT_ABORT(esp_http_client_perform(http_client));
  79. if(err == ESP_OK) {
  80. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP request was performed");
  81. int status_code = esp_http_client_get_status_code(http_client);
  82. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP status code: " + std::to_string(status_code));
  83. } else {
  84. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "HTTP request failed");
  85. }
  86. esp_http_client_cleanup(http_client);
  87. cJSON_Delete(jsonArray);
  88. free(jsonString);
  89. return numbersWithError;
  90. }
  91. void WebhookUploadPic(ImageData *Img) {
  92. if (_webhookURI.empty())
  93. {
  94. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "WebhookUploadPic aborted: no Uri configured");
  95. return;
  96. }
  97. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Starting WebhookUploadPic");
  98. std::string fullURI = _webhookURI + "?timestamp=" + std::to_string(_lastTimestamp);
  99. char response_buffer[MAX_HTTP_OUTPUT_BUFFER] = {0};
  100. esp_http_client_config_t http_config = {
  101. .url = fullURI.c_str(),
  102. .user_agent = "ESP32 Meter reader",
  103. .method = HTTP_METHOD_PUT,
  104. .event_handler = http_event_handler,
  105. .buffer_size = MAX_HTTP_OUTPUT_BUFFER,
  106. .user_data = response_buffer
  107. };
  108. esp_http_client_handle_t http_client = esp_http_client_init(&http_config);
  109. if (!http_client)
  110. {
  111. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "WebhookUploadPic: failed to initialize HTTP client for Uri " + fullURI);
  112. return;
  113. }
  114. esp_http_client_set_header(http_client, "Content-Type", "image/jpeg");
  115. esp_http_client_set_header(http_client, "APIKEY", _webhookApiKey.c_str());
  116. esp_err_t err = ESP_ERROR_CHECK_WITHOUT_ABORT(esp_http_client_set_post_field(http_client, (const char *)Img->data, Img->size));
  117. err = ESP_ERROR_CHECK_WITHOUT_ABORT(esp_http_client_perform(http_client));
  118. if (err == ESP_OK) {
  119. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP PUT request was performed successfully");
  120. int status_code = esp_http_client_get_status_code(http_client);
  121. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP status code: " + std::to_string(status_code));
  122. } else {
  123. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "HTTP PUT request failed");
  124. }
  125. esp_http_client_cleanup(http_client);
  126. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "WebhookUploadPic finished");
  127. }
  128. static esp_err_t http_event_handler(esp_http_client_event_t *evt)
  129. {
  130. switch(evt->event_id)
  131. {
  132. case HTTP_EVENT_ERROR:
  133. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client Error encountered");
  134. break;
  135. case HTTP_EVENT_ON_CONNECTED:
  136. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client connected");
  137. ESP_LOGI(TAG, "HTTP Client Connected");
  138. break;
  139. case HTTP_EVENT_HEADERS_SENT:
  140. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client sent all request headers");
  141. break;
  142. case HTTP_EVENT_ON_HEADER:
  143. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Header: key=" + std::string(evt->header_key) + ", value=" + std::string(evt->header_value));
  144. break;
  145. case HTTP_EVENT_ON_DATA:
  146. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client data recevied: len=" + std::to_string(evt->data_len));
  147. break;
  148. case HTTP_EVENT_ON_FINISH:
  149. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client finished");
  150. break;
  151. case HTTP_EVENT_DISCONNECTED:
  152. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client Disconnected");
  153. break;
  154. case HTTP_EVENT_REDIRECT:
  155. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Redirect");
  156. break;
  157. }
  158. return ESP_OK;
  159. }
  160. #endif //ENABLE_WEBHOOK