-
Notifications
You must be signed in to change notification settings - Fork 0
/
support_functions.ino
61 lines (59 loc) · 2.45 KB
/
support_functions.ino
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
/*----------------------------------
* char_append Function:
* Arguments:
* char* buff: pointer to character array which we will append a
* char c:
* uint16_t buff_size: size of buffer buff
*
* Return value:
* boolean: True if character appended, False if not appended (indicating buffer full)
*/
uint8_t char_append(char* buff, char c, uint16_t buff_size) {
int len = strlen(buff);
if (len>buff_size) return false;
buff[len] = c;
buff[len+1] = '\0';
return true;
}
/*----------------------------------
* do_http_request Function:
* Arguments:
* char* host: null-terminated char-array containing host to connect to
* char* request: null-terminated char-arry containing properly formatted HTTP request
* char* response: char-array used as output for function to contain response
* uint16_t response_size: size of response buffer (in bytes)
* uint16_t response_timeout: duration we'll wait (in ms) for a response from server
* uint8_t serial: used for printing debug information to terminal (true prints, false doesn't)
* Return value:
* void (none)
*/
void do_http_request(char* host, char* request, char* response, uint16_t response_size, uint16_t response_timeout, uint8_t serial){
WiFiClient client; //instantiate a client object
if (client.connect(host, 80)) { //try to connect to host on port 80
if (serial) Serial.print(request);//Can do one-line if statements in C without curly braces
client.print(request);
memset(response, 0, response_size); //Null out (0 is the value of the null terminator '\0') entire buffer
uint32_t count = millis();
while (client.connected()) { //while we remain connected read out data coming back
client.readBytesUntil('\n',response,response_size);
if (serial) Serial.println(response);
if (strcmp(response,"\r")==0) { //found a blank line!
break;
}
memset(response, 0, response_size);
if (millis()-count>response_timeout) break;
}
memset(response, 0, response_size);
count = millis();
while (client.available()) { //read out remaining text (body of response)
char_append(response,client.read(),OUT_BUFFER_SIZE);
}
if (serial) Serial.println(response);
client.stop();
if (serial) Serial.println("-----------");
}else{
if (serial) Serial.println("connection failed :/");
if (serial) Serial.println("wait 0.5 sec...");
client.stop();
}
}