-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwledapi.c
109 lines (84 loc) · 2.59 KB
/
wledapi.c
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
107
108
109
#include <stddef.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include "matelight.h"
#include <curl/curl.h>
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t write_memory_callback(void *contents, size_t size, size_t nmemb, void *userp)
{
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
char *ptr;
if (! mem->memory) {
ptr = malloc(realsize + 1);
} else {
ptr = realloc(mem->memory, mem->size + realsize + 1);
}
if (! ptr) {
return 0;
}
mem->memory = ptr;
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
void wled_api_init(void)
{
curl_global_init(CURL_GLOBAL_ALL);
//curl_global_cleanup();
}
bool wled_xml_check(struct MemoryStruct *chunk)
{
char *s = chunk->memory;
/* XML parsing for dummies */
if (strncmp(s, "<?xml", 5))
return false;
s = strstr(s, "<ds>");
if (! s)
return false;
s += 4;
if (strncmp(s, wled_ds, strlen(wled_ds)) != 0)
return false;
s += strlen(wled_ds);
if (strncmp(s, " (live)", 7) == 0)
s += 7;
if (strncmp(s, "</ds>", 5) != 0)
return false;
return true;
}
bool wled_api_check(const char *addr)
{
char url[7 + MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 4 + 1];
CURL *curl_handle;
struct MemoryStruct chunk = { NULL, 0 };
CURLcode res;
bool xmlok = false;
snprintf(url, sizeof(url), "http://%s/win", addr);
//fprintf(stderr, "curl: %s\n", url);
curl_handle = curl_easy_init();
curl_easy_setopt(curl_handle, CURLOPT_URL, url);
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_memory_callback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, 10);
curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 0L);
curl_easy_setopt(curl_handle, CURLOPT_MAXFILESIZE_LARGE, (off_t)(1024L*1024L));
res = curl_easy_perform(curl_handle);
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
} else {
//fprintf(stderr, "%zu bytes retrieved\n", chunk.size);
//fprintf(stderr, "%.*s\n", (int)chunk.size, chunk.memory);
xmlok = wled_xml_check(&chunk);
fprintf(stderr, "wledapi: address: %s, %s-WLED: %s\n", addr, wled_ds, (xmlok ? "yes" : "no"));
}
curl_easy_cleanup(curl_handle);
if (chunk.memory) {
free(chunk.memory);
}
return xmlok;
}