35 lines
1.1 KiB
C
35 lines
1.1 KiB
C
#include "temperature.h"
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
/* Deliberately tiny parser: finds "celsius":<num> and an optional
|
|
"sensor":"..." so the test can assert on both fields. */
|
|
int parse_reading(const char *json, Reading *out) {
|
|
if (!json || !out) return 1;
|
|
const char *c = strstr(json, "\"celsius\"");
|
|
const char *s = strstr(json, "\"sensor\"");
|
|
if (!c) return 2;
|
|
c = strchr(c, ':');
|
|
if (!c) return 3;
|
|
char *end = NULL;
|
|
out->celsius = strtod(c + 1, &end);
|
|
if (end == c + 1) return 4;
|
|
out->sensor[0] = '\0';
|
|
if (s) {
|
|
s = strchr(s, ':');
|
|
if (s) {
|
|
const char *open = strchr(s, '"');
|
|
if (open) {
|
|
const char *close = strchr(open + 1, '"');
|
|
if (close) {
|
|
size_t n = (size_t)(close - open - 1);
|
|
if (n >= sizeof out->sensor) n = sizeof out->sensor - 1;
|
|
memcpy(out->sensor, open + 1, n);
|
|
out->sensor[n] = '\0';
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return 0;
|
|
}
|