/
ThingspeakClient.cpp
129 lines (93 loc) · 2.48 KB
/
ThingspeakClient.cpp
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include "ThingspeakClient.h"
ThingspeakClient::ThingspeakClient() {
}
void ThingspeakClient::getLastChannelItem(String channelId, String readApiKey) {
JsonStreamingParser parser;
parser.setListener(this);
WiFiClient client;
// http://api.thingspeak.com/channels/CHANNEL_ID/feeds.json?results=2&api_key=API_KEY
const char host[] = "api.thingspeak.com";
String path = "/channels/" + channelId +"/feeds.json?results=1&api_key=" + readApiKey;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
Serial.print("Requesting path: ");
Serial.println(path);
// This will send the request to the server
client.print(String("GET ") + path + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
int retryCounter = 0;
while(!client.available()) {
Serial.println(".");
delay(1000);
retryCounter++;
if (retryCounter > 10) {
return;
}
}
boolean isBody = false;
char c;
client.setNoDelay(false);
while (client.connected() || client.available()) {
if (client.available()) {
c = client.read();
if (c == '{' || c == '[') {
isBody = true;
}
if (isBody) {
parser.parse(c);
}
}
// give WiFi and TCP/IP libraries a chance to handle pending events
yield();
}
client.stop();
}
void ThingspeakClient::whitespace(char c) {
}
void ThingspeakClient::startDocument() {
}
void ThingspeakClient::key(String key) {
if (key == "channel") {
isHeader = true;
} else if (key == "feeds") {
isHeader = false;
}
currentKey = key;
}
void ThingspeakClient::value(String value) {
//Serial.println(currentKey +": " + value);
for (int i = 1; i < 9; i++) {
String fieldKey = "field" + String(i);
if (currentKey == fieldKey) {
if (isHeader) {
fieldLabels[i-1] = value;
} else {
lastFields[i-1] = value;
Serial.println(fieldKey + ": " + value);
}
}
}
}
String ThingspeakClient::getFieldLabel(int index) {
return fieldLabels[index];
}
String ThingspeakClient::getFieldValue(int index) {
return lastFields[index];
}
String ThingspeakClient::getCreatedAt() {
return createdAt;
}
void ThingspeakClient::endArray() {
}
void ThingspeakClient::endObject() {
}
void ThingspeakClient::endDocument() {
}
void ThingspeakClient::startArray() {
}
void ThingspeakClient::startObject() {
}