forked from valdanylchuk/breezybox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbreezy_http.c
More file actions
97 lines (81 loc) · 2.18 KB
/
Copy pathbreezy_http.c
File metadata and controls
97 lines (81 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
* breezy_http.c - HTTP helper functions for ELF apps
*
* Provides simple wrappers that hide ESP-IDF struct complexity.
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "esp_http_client.h"
#include "esp_crt_bundle.h"
#include "esp_netif.h"
#include "breezybox.h"
/* Check if we have network connectivity */
static int check_network(void)
{
esp_netif_t *netif = esp_netif_get_default_netif();
if (!netif) {
return 0;
}
esp_netif_ip_info_t ip_info;
if (esp_netif_get_ip_info(netif, &ip_info) != ESP_OK) {
return 0;
}
return ip_info.ip.addr != 0;
}
/* Download context */
typedef struct {
FILE *file;
size_t total;
} dl_ctx_t;
static esp_err_t download_handler(esp_http_client_event_t *evt)
{
dl_ctx_t *ctx = (dl_ctx_t *)evt->user_data;
if (evt->event_id == HTTP_EVENT_ON_DATA) {
if (ctx->file && evt->data_len > 0) {
size_t written = fwrite(evt->data, 1, evt->data_len, ctx->file);
ctx->total += written;
}
}
return ESP_OK;
}
int breezy_http_download(const char *url, const char *dest_path)
{
if (!url || !dest_path) {
return -1;
}
if (!check_network()) {
return -2; /* No network */
}
FILE *f = fopen(dest_path, "wb");
if (!f) {
return -1;
}
dl_ctx_t ctx = { .file = f, .total = 0 };
esp_http_client_config_t config = {
.url = url,
.event_handler = download_handler,
.user_data = &ctx,
.crt_bundle_attach = esp_crt_bundle_attach,
.timeout_ms = 30000,
.max_redirection_count = 5,
.buffer_size = 4096,
.buffer_size_tx = 2048,
};
esp_http_client_handle_t client = esp_http_client_init(&config);
if (!client) {
fclose(f);
unlink(dest_path);
return -1;
}
esp_http_client_set_header(client, "User-Agent", "ESP32-BreezyBox");
esp_err_t err = esp_http_client_perform(client);
int status = esp_http_client_get_status_code(client);
esp_http_client_cleanup(client);
fclose(f);
if (err != ESP_OK || (status != 200 && status != 0)) {
unlink(dest_path);
return -1;
}
return 0;
}