-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsonclient.h
64 lines (50 loc) · 1.36 KB
/
jsonclient.h
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
#pragma once
class JsonClient {
public:
JsonClient(WiFiClient &client, const __FlashStringHelper *host):
JsonClient(client, host, 80) {}
JsonClient(WiFiClient &client, const __FlashStringHelper *host, unsigned port):
_client(client), _host(host), _port(port) {}
bool get(const char *path) {
return get([path](Stream &s) { s.print(path); });
}
bool get(std::function<void(Stream &)> add_path) {
if (!_client.connect(_host, _port)) {
ERR(print(F("Failed to connect: ")));
ERR(print(_host));
ERR(print(':'));
ERR(print(_port));
return false;
}
_client.print(F("GET "));
add_path(_client);
_client.println(F(" HTTP/1.1"));
_client.print(F("Host: "));
_client.println(_host);
_client.println(F("Connection: close"));
_client.println(F("Accept: application/json"));
_client.println();
if (!_client.connected()) {
ERR(print(F("Not connected")));
return false;
}
unsigned long now = millis();
while (!_client.available())
if (millis() - now > 5000) {
ERR(println(F("Timeout waiting for server!")));
return false;
}
while (_client.available()) {
int c = _client.peek();
if (c == '{' || c == '[')
return true;
_client.read();
}
ERR(println(F("Unexpected EOF reading server response!")));
return false;
}
private:
WiFiClient &_client;
const __FlashStringHelper *_host;
const unsigned _port;
};