interface_webhook.cpp 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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 (Img == NULL || Img->size == 0 || Img->size > MAX_JPG_SIZE) {
  93. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "WebhookUploadPic aborted: JPEG image buffer is unavailable or invalid");
  94. return;
  95. }
  96. if (_webhookURI.empty())
  97. {
  98. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "WebhookUploadPic aborted: no Uri configured");
  99. return;
  100. }
  101. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Starting WebhookUploadPic");
  102. std::string fullURI = _webhookURI + "?timestamp=" + std::to_string(_lastTimestamp);
  103. char response_buffer[MAX_HTTP_OUTPUT_BUFFER] = {0};
  104. esp_http_client_config_t http_config = {
  105. .url = fullURI.c_str(),
  106. .user_agent = "ESP32 Meter reader",
  107. .method = HTTP_METHOD_PUT,
  108. .event_handler = http_event_handler,
  109. .buffer_size = MAX_HTTP_OUTPUT_BUFFER,
  110. .user_data = response_buffer
  111. };
  112. esp_http_client_handle_t http_client = esp_http_client_init(&http_config);
  113. if (!http_client)
  114. {
  115. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "WebhookUploadPic: failed to initialize HTTP client for Uri " + fullURI);
  116. return;
  117. }
  118. esp_http_client_set_header(http_client, "Content-Type", "image/jpeg");
  119. esp_http_client_set_header(http_client, "APIKEY", _webhookApiKey.c_str());
  120. esp_err_t err = ESP_ERROR_CHECK_WITHOUT_ABORT(esp_http_client_set_post_field(http_client, (const char *)Img->data, Img->size));
  121. err = ESP_ERROR_CHECK_WITHOUT_ABORT(esp_http_client_perform(http_client));
  122. if (err == ESP_OK) {
  123. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP PUT request was performed successfully");
  124. int status_code = esp_http_client_get_status_code(http_client);
  125. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP status code: " + std::to_string(status_code));
  126. } else {
  127. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "HTTP PUT request failed");
  128. }
  129. esp_http_client_cleanup(http_client);
  130. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "WebhookUploadPic finished");
  131. }
  132. static esp_err_t http_event_handler(esp_http_client_event_t *evt)
  133. {
  134. switch(evt->event_id)
  135. {
  136. case HTTP_EVENT_ERROR:
  137. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client Error encountered");
  138. break;
  139. case HTTP_EVENT_ON_CONNECTED:
  140. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client connected");
  141. ESP_LOGI(TAG, "HTTP Client Connected");
  142. break;
  143. case HTTP_EVENT_HEADERS_SENT:
  144. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client sent all request headers");
  145. break;
  146. case HTTP_EVENT_ON_HEADER:
  147. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Header: key=" + std::string(evt->header_key) + ", value=" + std::string(evt->header_value));
  148. break;
  149. case HTTP_EVENT_ON_DATA:
  150. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client data recevied: len=" + std::to_string(evt->data_len));
  151. break;
  152. case HTTP_EVENT_ON_FINISH:
  153. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client finished");
  154. break;
  155. case HTTP_EVENT_DISCONNECTED:
  156. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client Disconnected");
  157. break;
  158. case HTTP_EVENT_REDIRECT:
  159. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Redirect");
  160. break;
  161. }
  162. return ESP_OK;
  163. }
  164. #endif //ENABLE_WEBHOOK