aboutsummaryrefslogtreecommitdiff
path: root/main/param/color_int.c
blob: 0b8b00262181b236150b740c88e263dbfdea456c (plain) (blame)
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
#include "param.h"
#include "http_server.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

void cmd_handle(color_int_t)(
    const char* attr, sockbuf_t* sockbuf, color_int_t* ptr)
{
  char buf_[32];
  char* value = read_token(sockbuf, buf_, sizeof(buf_));

  if (!value) {
    sockbuf_write(sockbuf, "Missing color value\n");
    return;
  }

  char* p = value;
  if (*p == '#') {
    p++;
  } else if (!strncasecmp(p, "0x", 2)) {
    p += 2;
  }

  char* end = NULL;
  unsigned long parsed = strtoul(p, &end, 16);
  if (end == p || *end != '\0' || parsed > 0xFFFFFFUL) {
    sockbuf_write(sockbuf, "Invalid color; expected hex like RRGGBB\n");
    return;
  }

  *ptr = (color_int_t)parsed;
  snprintf(buf_, sizeof(buf_), "%s = 0x%06lx\n", attr, parsed);
  sockbuf_write(sockbuf, buf_);
}

size_t serialize_to_json(color_int_t)(
    char** out, size_t len, const char* attr, const char* dn, color_int_t value)
{
  size_t newlen = snprintf(
      *out,
      len,
      "\"%s\":{\"type\":\"color\",\"value\":\"#%06lx\",\"disp\":\"%s\"}",
      attr,
      (unsigned long)(value & 0xFFFFFF),
      dn);
  *out += newlen;
  return len - newlen;
}

#define TAG "param_color"
void http_handle(color_int_t)(httpd_req_t* req, color_int_t* val)
{
  char buf[128];
  int buf_len = httpd_req_get_url_query_len(req) + 1;

  if (buf_len > 1) {
    if (buf_len > sizeof(buf)) {
      ESP_LOGI(TAG, "Invalid request. Query string too long.");
      httpd_resp_set_status(req, HTTPD_400);
      return;
    }

    if (httpd_req_get_url_query_str(req, buf, buf_len) == ESP_OK) {
      char param[32];
      if (httpd_query_key_value(buf, "set", param, sizeof(param)) == ESP_OK) {
        char* p = param;
        if (*p == '#') {
          p++;
        } else if (!strncasecmp(p, "0x", 2)) {
          p += 2;
        }
        char* end = NULL;
        unsigned long parsed = strtoul(p, &end, 16);
        if (end == p || *end != '\0' || parsed > 0xFFFFFFUL) {
          ESP_LOGI(TAG, "Invalid request. Invalid color value.");
          httpd_resp_set_status(req, HTTPD_400);
          return;
        }
        *val = (color_int_t)parsed;
      }
    }
  }

  httpd_resp_set_status(req, HTTPD_204);
}

void print(color_int_t)(
    sockbuf_t* sockbuf, const char* attr, color_int_t val)
{
  char buf[128];
  snprintf(buf, sizeof(buf), "%s: 0x%06lx :: color\n", attr, (unsigned long)val);
  sockbuf_write(sockbuf, buf);
}