-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpClient.cpp
More file actions
322 lines (299 loc) · 7.99 KB
/
HttpClient.cpp
File metadata and controls
322 lines (299 loc) · 7.99 KB
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
#include "Arduino.h"
#include "HttpClient.h"
HttpClient::HttpClient(Client& cl) : client(&cl){
status = HTTP_STATUS_IDLE;
timeout = HTTP_DEFAULT_TIMEOUT;
debug = false;
}
void HttpClient::setTimeout(int millis){
if(millis>0) timeout = millis;
}
void HttpClient::reset(){
close();
}
void HttpClient::close(){
if(debug) Serial.println(F("HttpClient.close()"));
//if(client->connected()){
client->stop();
//}
status = HTTP_STATUS_IDLE;
}
void HttpClient::setDebug(boolean d){
debug = d;
Serial.print("debug=");Serial.println(debug);
}
/**
* Envoi d'une requete GET
* @return 0 si la connexion a réussi
* HTTP_ERROR_CONNECTION_FAILED si la conexion a échoué
*/
int HttpClient::sendGet(char* server, int port, char* path, char* params){
if(debug){
Serial.print(F("HttpClient.sendGet http://"));
Serial.print(server);
Serial.print(":");
Serial.print(port,DEC);
Serial.print(path);
if(params[0]!='\0'){
Serial.print("?");
Serial.print(params);
}
Serial.println("");
}
if( !connect(server, port) ){
return error(HTTP_ERROR_CONNECTION_FAILED);
}
print("GET ");
print(path);
if(params[0]!='\0'){
print("?");
print(params);
}
print(" HTTP/1.1\nHost: ");
println(server);
println("Connection: close\n");
status = HTTP_STATUS_RESP_WAIT;
return 0;
}
int HttpClient::print(char* str){
//if(debug) Serial.print(str);
client->print(str);
}
int HttpClient::println(char* str){
//if(debug) Serial.println(str);
client->println(str);
}
/**
* Connection au serveur
*/
boolean HttpClient::connect(char* serv, int port){
if(debug){
Serial.print(F("HttpClient.connect to "));
Serial.print(serv);
Serial.print("...");
}
if(status != HTTP_STATUS_IDLE){
Serial.println(F("Connection deja en cours..."));
return false;
}
if( !client->connect(serv, port) ){
Serial.print(F("FAILED..."));
//KO
client->stop();
delay(500); //Don't know if necessary
if( !client->connect(serv, port) ){
Serial.println(F("FAILED"));
return false;
}
}
if(debug) Serial.println("OK");
lastConnected = true;
return true;
}
/**
* Attend le début de la réponse, lit la première ligne de la réponse, avec le code réponse
* Fait suite à l'envoi d'une requête.
* @return int code réponse
* HTTP_ERROR s'il y a eu une erreur
* HTTP_ERROR_TIMEOUT si le timeout a été dépassé
* HTTP_ERROR_STATUS status du client est anormal
*/
int HttpClient::readResponseCode(){
if(debug) Serial.print(F("HttpClient.readResponseCode..."));
if(status!=HTTP_STATUS_RESP_WAIT){
if(debug) Serial.println(F("Excepted status:WAIT"));
return error(HTTP_ERROR_STATUS);
}
char* intro = "HTTP/1.1 ";
int result = 0;
startMillis = millis();
for(int charIdx=0;;charIdx++){
char c = httpRead();
if(c<0) return c; //C'est une erreur
if(charIdx<=8){
if(debug) Serial.print(c);
//Vérification du "HTTP/1.1 "
if(c==intro[charIdx] || (charIdx==7 && c=='0')){
//OK
}
else{
if(debug) Serial.print(F(": HTTP/1.1 not verified"));
return error(HTTP_ERROR);
}
}
else if(charIdx<=11){
//Lecture du code réponse
if(c<'0' || c >'9'){
if(debug) Serial.print(F("Invalid char (")); Serial.print(charIdx); Serial.print("):"); Serial.print(c);
return error(HTTP_ERROR);
}
int tmp = 1;
for(uint8_t i=0;i<11-charIdx;i++) tmp = tmp*10;
tmp = (c-48)*tmp;
result += tmp;
//Serial.print("c=");Serial.print(c-48,DEC);Serial.print(" ");Serial.print(tmp);Serial.print(" idx=");Serial.print(charIdx,DEC);Serial.print(" ->");Serial.println(result,DEC);
//if(debug) Serial.println(result);
}
else{
//On passe le reste de la ligne, et on renvoie le résultat
if(int res=moveToEOL()<0) return error(res);
status = HTTP_STATUS_RESP_HEADER; //La ligne suivante est une en-tête
if(debug) Serial.println(result);
return result;
}
}
}
/**
* Lecture de la réponse jusqu'à un certain caractère (exclu) ou la fin de ligne
* Le caractère '\r' est ignoré
* @return int nb de caractères lus (0 signifie que le premier caractère était ce caractère ou une fin de ligne)
* HTTP_ERROR s'il y a eu une erreur
* HTTP_ERROR_TIMEOUT si le timeout a été dépassé
*/
int HttpClient::readLineToChar(char sep, char* key,int maxlen){
if(debug) Serial.println(F("HttpClient.readLineToChar"));
for(int nbChars=0;;){
char c = httpRead();
if(c==sep || c==0) return nbChars; //Séparateur ou fin de fichier
if(c<0) return c; //httpRead a renvoyé une erreur
if(c==10) continue; //on ignore le '\r'
if(c==13 && nbChars==0 && status!=HTTP_STATUS_RESP_BODY){
//C'est la fin des en-têtes
status = HTTP_STATUS_RESP_BODY;
return 0;
}
if(status==HTTP_STATUS_RESP_HEADER && !(c>='A' && c<='Z' || c>='a' && c<='z' || c>='0' && c<='9' || c=='_' || c=='-')){
//Caractère invalide
if(debug){
Serial.print(F("Caractere invalide:")); Serial.print(c); Serial.println(c,DEC);
}
return error(HTTP_ERROR);
}
nbChars++;
if(nbChars>maxlen) return error(HTTP_ERROR_BUFFER_OVERFLOW);
key[nbChars-1] = c;
key[nbChars] = '\0';
}
}
/**
* Passe la suites des en-têtes HTTP
* @return 0 si tout s'est bien passé
* HTTP_ERROR s'il y a eu une erreur
* HTTP_ERROR_TIMEOUT si le timeout a été dépassé
*/
int HttpClient::skipHeaders(){
if(debug) Serial.println(F("HttpClient.skipHeaders"));
if(status!=HTTP_STATUS_RESP_HEADER){
//On n'est pas dans les en-têtes
if(debug) Serial.println("Excepted status:RESP_HEADER");
return error(HTTP_ERROR_STATUS);
}
char prevChar;
char c = 0;
while(c!=13 || prevChar!=13) //tant qu'il n'y a pas deux caractères '\n' consécutifs
{
prevChar = c;
c = httpRead();
if(c<0) return error(c); //httpRead a renvoyé une erreur
if(c==10){
c = prevChar;
prevChar = 0;
continue;
}
}
status = HTTP_STATUS_RESP_BODY;
return 0;
}
int HttpClient::moveToEOL(){
if(status==HTTP_STATUS_IDLE){
//La réponse n'a pas commencé
if(debug) Serial.println("Error: Status not IDLE");
return error(HTTP_ERROR_STATUS);
}
for(int nbChars=0;;nbChars++){
int c = httpRead();
if(c<0) return c; //httpRead a renvoyé une erreur
if(c=='\n'){
return 0;
}
}
}
/**
* Indique si des données de réponse sont arrivées
*/
int HttpClient::available(){
return status!= HTTP_STATUS_ERROR && client->available();
}
/**
* Renvoie le caractère suivant de la réponse, en attendant si nécessaire
* @return caractère suivant dans la réponse
* O si la fin de fichier a été rencontrée
* HTTP_ERROR_TIMEOUT si le timeout a été dépassé
*/
int HttpClient::httpRead(){
//on attend tant qu'il n'y a rien à lire, qu'on n'est pas déconnecté, et que le timeout n'est pas dépassé
while(!client->available()){
if ( !client->connected() ){
status = HTTP_STATUS_EOF;
return 0;
}
if(millis()-startMillis > timeout){
status = HTTP_STATUS_ERROR;
return error(HTTP_ERROR_TIMEOUT);
}
}
char c = client->read();
if(c==EOF){
status = HTTP_STATUS_EOF;
return 0;
}
return c;
}
/**
* Ecrit un message d'erreur et renvoi le code en retour
*/
int HttpClient::error(int err){
Serial.print(F("HttpClient ERROR: "));
switch(err){
case HTTP_ERROR_BUFFER_OVERFLOW:
Serial.print(F("Buffer overflow"));
break;
case HTTP_ERROR_TIMEOUT:
Serial.print(F("timeout"));
break;
case HTTP_ERROR_CONNECTION_FAILED:
Serial.print(F("Connection failed"));
break;
case HTTP_ERROR_STATUS:
Serial.print(F("Invalid status: "));
Serial.print(status);
switch(status){
case HTTP_STATUS_IDLE:
Serial.print(F("IDLE"));
break;
case HTTP_STATUS_RESP_WAIT:
Serial.print(F("RESP_WAIT"));
break;
case HTTP_STATUS_RESP_BEGIN:
Serial.print(F("RESP_BEGIN"));
break;
case HTTP_STATUS_RESP_HEADER:
Serial.print(F("RESP_HEADER"));
break;
case HTTP_STATUS_RESP_BODY:
Serial.print(F("RESP_BODY"));
break;
case HTTP_STATUS_ERROR:
Serial.print(F("ERROR"));
break;
case HTTP_STATUS_EOF:
Serial.print(F("EOF"));
break;
default:
Serial.print(status);
}
break;
}
Serial.print('\n');
return err;
}