16#if DETWS_ENABLE_GPIO_MAP
22const char *detws_gpio_dir_name(DetwsGpioDir dir)
26 case DetwsGpioDir::DETWS_GPIO_IN:
28 case DetwsGpioDir::DETWS_GPIO_IN_PULLUP:
30 case DetwsGpioDir::DETWS_GPIO_IN_PULLDOWN:
32 case DetwsGpioDir::DETWS_GPIO_OUT:
39static int json_append(
char *out,
size_t cap,
size_t *pos,
const char *fmt, ...)
45 int w = vsnprintf(out + *pos, cap - *pos, fmt, ap);
47 if (w < 0 || (
size_t)w >= cap - *pos)
53int detws_gpio_json(
const DetwsGpioPin *pins, uint8_t count,
char *out,
size_t cap)
61 if (json_append(out, cap, &pos,
"{\"pins\":[") != 0)
63 for (uint8_t i = 0; i < count; i++)
65 const DetwsGpioPin *p = &pins[i];
66 if (json_append(out, cap, &pos,
"%s{\"pin\":%u,\"label\":\"%s\",\"dir\":\"%s\",\"level\":%u}", i ?
"," :
"",
67 (unsigned)p->pin, p->label ? p->label :
"", detws_gpio_dir_name(p->dir),
68 p->level ? 1u : 0u) != 0)
71 if (json_append(out, cap, &pos,
"]}") != 0)
78static bool form_field_uint(
const char *body,
size_t len,
const char *name,
unsigned *out)
80 size_t nlen = strnlen(name, len + 1);
81 for (
size_t i = 0; i + nlen + 1 <= len; i++)
83 bool at_field = (i == 0) || body[i - 1] ==
'&';
84 if (!at_field || memcmp(body + i, name, nlen) != 0 || body[i + nlen] !=
'=')
86 size_t j = i + nlen + 1;
87 if (j >= len || body[j] <
'0' || body[j] >
'9')
90 for (; j < len && body[j] >=
'0' && body[j] <=
'9'; j++)
91 v = v * 10 + (
unsigned)(body[j] -
'0');
98bool detws_gpio_parse_set(
const char *body,
size_t len, uint8_t *pin, uint8_t *level)
100 if (!body || !pin || !level)
104 if (!form_field_uint(body, len,
"pin", &p) || !form_field_uint(body, len,
"level", &l))
111bool detws_gpio_is_output(
const DetwsGpioPin *pins, uint8_t count, uint8_t pin)
115 for (uint8_t i = 0; i < count; i++)
116 if (pins[i].pin == pin && pins[i].dir == DetwsGpioDir::DETWS_GPIO_OUT)
125void detws_gpio_begin_pins(
const DetwsGpioPin *pins, uint8_t count)
129 for (uint8_t i = 0; i < count; i++)
133 case DetwsGpioDir::DETWS_GPIO_OUT:
134 pinMode(pins[i].pin, OUTPUT);
136 case DetwsGpioDir::DETWS_GPIO_IN_PULLUP:
137 pinMode(pins[i].pin, INPUT_PULLUP);
139 case DetwsGpioDir::DETWS_GPIO_IN_PULLDOWN:
140 pinMode(pins[i].pin, INPUT_PULLDOWN);
143 pinMode(pins[i].pin, INPUT);
149void detws_gpio_read(DetwsGpioPin *pins, uint8_t count)
153 for (uint8_t i = 0; i < count; i++)
154 pins[i].level = (uint8_t)(digitalRead(pins[i].pin) ? 1 : 0);
157void detws_gpio_write(uint8_t pin, uint8_t level)
159 digitalWrite(pin, level ? HIGH : LOW);
164void detws_gpio_begin_pins(
const DetwsGpioPin *, uint8_t)
168void detws_gpio_read(DetwsGpioPin *, uint8_t)
172void detws_gpio_write(uint8_t, uint8_t)
Browser GPIO pin-mapper / diagnostics (DETWS_ENABLE_GPIO_MAP).