-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathHttpClient.cpp
More file actions
141 lines (104 loc) · 2.72 KB
/
Copy pathHttpClient.cpp
File metadata and controls
141 lines (104 loc) · 2.72 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
/*
* "Drinks" RFID Terminal
* Buy sodas with your company badge!
*
* Benoit Blanchon 2014 - MIT License
* https://github.com/bblanchon/DrinksRfidTerminal
*/
#include <Arduino.h>
#include <SPI.h>
#include <Ethernet.h>
#include <Dns.h>
#include "Configuration.h"
#include "HttpClient.h"
#define xstr(s) str(s)
#define str(s) #s
#define NOT_EMPTY(s) (s[0]!=0 && s[0]!='\r' && s[0]!='\n')
void HttpClient::begin()
{
delay(100);
byte mac[6] = MAC_ADDRESS;
Serial.println("DHCP...");
// start the Ethernet connection:
while (0 == Ethernet.begin(mac))
{
Serial.println("Failed. Retry...");
}
Serial.print("Address=");
Serial.println(Ethernet.localIP());
Serial.print("Subnet=");
Serial.println(Ethernet.subnetMask());
Serial.print("DNS=");
Serial.println(Ethernet.dnsServerIP());
Serial.println("Resolve " SERVER_NAME "...");
DNSClient dns;
dns.begin(Ethernet.dnsServerIP());
while (1 != dns.getHostByName(SERVER_NAME, serverIp))
{
Serial.println("Failed. Retry...");
}
Serial.print("Address=");
Serial.println(serverIp);
}
void HttpClient::readln(char* buffer, int size)
{
int i = 0;
bool connected = true;
while (i < size - 1)
{
if (client.available()>0)
{
char c = client.read();
//Serial.print(c);
if (c == '\n') break;
buffer[i++] = c;
}
else if (!connected)
{
Serial.println("interrupted");
break;
}
connected = client.connected();
}
buffer[i] = 0;
}
bool HttpClient::query(const char* request, char* content, int maxContentSize)
{
/*
* 1. SEND REQUEST
*/
Serial.println(request);
if (!client.connect(serverIp, SERVER_PORT))
{
Serial.println("Connect failed");
return false;
}
client.print(request);
client.println(" HTTP/1.1");
client.println("Host: " SERVER_NAME ":" xstr(SERVER_PORT));
client.println("Accept: application/json");
client.println("Connection: close");
if (content[0])
{
client.println("Content-Type: application/json");
client.print("Content-Length: ");
client.println(strlen(content));
client.println();
Serial.println(content);
client.println(content);
}
else
{
client.println();
}
/*
* 2. READ RESPONSE
*/
// skip HTTP headers
while (readln(content, maxContentSize), NOT_EMPTY(content));
// read content
readln(content, maxContentSize);
Serial.println(content);
client.stop();
return content[0] != 0;
}