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
98
99
100
101
102
103
104
105
106
|
#include "esp_mac.h"
#include "esp_log.h"
#include "esp_check.h"
#include "esp_wifi.h"
#include "relay.h"
#include "settings.h"
#include "utils.h"
#include "routes.h"
static const char *TAG = "routes/settings";
/**
* Handles requests for the `/settings` endpoint
*/
esp_err_t settings_handler(httpd_req_t *req)
{
ESP_LOGD(TAG, "settings_handler %s", req->uri);
char *resp = settings_json();
ESP_RETURN_ON_FALSE(resp, ESP_ERR_NO_MEM, TAG, "buffer alloc failed");
httpd_resp_set_type(req, "application/json");
httpd_resp_sendstr(req, resp);
return ESP_OK;
}
/**
* Handles requests for the `/settings/cloud` endpoint
*/
esp_err_t settings_cloud_handler(httpd_req_t *req)
{
ESP_LOGD(TAG, "settings_cloud_handler %s", req->uri);
httpd_resp_set_type(req, "application/json");
httpd_resp_sendstr(req, "{\"enabled\":false}");
return ESP_OK;
}
/**
* Handles requests for the `/settings/sta` endpoint
*/
esp_err_t settings_sta_handler(httpd_req_t *req)
{
ESP_LOGD(TAG, "settings_sta_handler %s", req->uri);
size_t query_len = httpd_req_get_url_query_len(req) + 1;
if (query_len > 1)
{
char* buf = (char*)malloc(query_len);
ESP_RETURN_ON_FALSE(buf, ESP_ERR_NO_MEM, TAG, "buffer alloc failed");
if (httpd_req_get_url_query_str(req, buf, query_len) == ESP_OK)
{
char param[64];
wifi_config_t wifi_cfg;
ESP_ERROR_CHECK(esp_wifi_get_config(WIFI_IF_STA, &wifi_cfg));
if (httpd_query_key_value(buf, "ssid", param, sizeof(param)) == ESP_OK)
{
ESP_LOGI(TAG, "Found URL query parameter => ssid=%s", param);
ESP_LOGD(TAG, "Configured ssid %s", param);
size_t s = sizeof(wifi_cfg.sta.ssid);
strncpy((char*)wifi_cfg.sta.ssid, param, s);
wifi_cfg.sta.ssid[s] = '\0';
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_cfg));
}
if (httpd_query_key_value(buf, "key", param, sizeof(param)) == ESP_OK) {
ESP_LOGD(TAG, "Configured psk");
size_t s = sizeof(wifi_cfg.sta.password) - 1;
strncpy((char*)wifi_cfg.sta.password, param, s);
wifi_cfg.sta.password[s] = '\0';
wifi_cfg.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_cfg));
}
}
free(buf);
}
char* resp = settings_sta_json();
ESP_RETURN_ON_FALSE(resp, ESP_ERR_NO_MEM, TAG, "buffer alloc failed");
httpd_resp_set_type(req, "application/json");
httpd_resp_sendstr(req, resp);
return ESP_OK;
}
/**
* Handles requests for the `/settings/relay/0` endpoint
*/
esp_err_t settings_relay_handler(httpd_req_t *req)
{
char *resp = settings_relay_json();
ESP_RETURN_ON_FALSE(resp, ESP_ERR_NO_MEM, TAG, "buffer alloc failed");
httpd_resp_set_type(req, "application/json");
httpd_resp_sendstr(req, resp);
return ESP_OK;
}
|