Переглянути джерело

api: Handle empty objects to allow for disabling a day

Helmut Pozimski 1 рік тому
батько
коміт
7659c20cc5
1 змінених файлів з 21 додано та 10 видалено
  1. 21 10
      main/api.c

+ 21 - 10
main/api.c

@@ -53,8 +53,10 @@ static esp_err_t wakeup_get_handler(httpd_req_t *req) {
 	if (ret == ESP_OK) {
 		httpd_resp_set_type(req, "application/json");
 		cJSON *root = cJSON_CreateObject();
-		cJSON_AddNumberToObject(root, "hour", wakeup_minutes / 60);
-		cJSON_AddNumberToObject(root, "minute", wakeup_minutes % 60);
+		if (wakeup_minutes >= 0) {
+			cJSON_AddNumberToObject(root, "hour", wakeup_minutes / 60);
+			cJSON_AddNumberToObject(root, "minute", wakeup_minutes % 60);
+		}
 		const char *response = cJSON_Print(root);
 		httpd_resp_sendstr(req, response);
 	} else if (ret == ESP_ERR_NVS_NOT_FOUND) {
@@ -106,18 +108,27 @@ static esp_err_t wakeup_put_handler(httpd_req_t *req) {
 		return ESP_OK;
 	}
 	
-	int hour = cJSON_GetObjectItem(root, "hour")->valueint;
-	int minute = cJSON_GetObjectItem(root, "minute")->valueint;
+	int16_t minute_of_day;
 	
-	if (validate_time(hour, minute)) {
-		esp_err_t ret = write_wakeup_time_str(wakeup_str, hour * 60 + minute);
-		if (ret == ESP_OK) {
-			httpd_resp_sendstr(req, "");
+	if (cJSON_GetArraySize(root) == 0) {
+		minute_of_day = -1;
+	} else {
+		int16_t hour = cJSON_GetObjectItem(root, "hour")->valueint;
+		int16_t minute = cJSON_GetObjectItem(root, "minute")->valueint;
+		if (validate_time(hour, minute)) {
+			minute_of_day = hour * 60 + minute;
 		} else {
-			httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Error while writing data");		
+			httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Time values outside allowed range");
+			cJSON_Delete(root);
+			return ESP_OK;
 		}
+	}
+
+	esp_err_t ret = write_wakeup_time_str(wakeup_str, minute_of_day);
+	if (ret == ESP_OK) {
+		httpd_resp_sendstr(req, "");
 	} else {
-		httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Time values outside allowed range");
+		httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Error while writing data");		
 	}
 	cJSON_Delete(root);
 	return ESP_OK;