-
Notifications
You must be signed in to change notification settings - Fork 5
/
ESP8266-json-server.ino
271 lines (221 loc) · 6.18 KB
/
ESP8266-json-server.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
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
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define HELLO_MESSAGE "ESP8266 json server"
//Real Access Point configuration
const char
*ssid = "AAAAA",
*password = "BBBB";
//Software Access Point configuration
const char
*APssid = "ESP6288",
*APpassword = "dupadupa"; //MINIMUM 8 chars or softAP will use default name and pass
//--web server
#define webServerPort 80
ESP8266WebServer server(webServerPort);
//--udp ticker
WiFiUDP g_udp;
#define g_port 6666
const unsigned long int t_waitTimeMS = 30000;//30sec (not exact)
unsigned long int t_memory=0;
//--DS18B20
#define ONE_WIRE_BUS 2 // DS18B20 pin
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
//the value to publish
String VALUE="";
// ThingSpeak Settings
char thingSpeakAddress[] = "api.thingspeak.com";
String thingSpeakWriteAPIKey = "<INSERT-KEY-HERE>";
void handleRoot() {
server.send(200, "text/plain", "hello from esp8266!\n\n go to /json or /get to request value.");
}
void handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void handleGetValueJSON() {
String message = "{ ";
message += " value=";
message += VALUE;
message += " }";
server.send(200, "application/json", message);
}
void handleGetValueRAW() {
server.send(200, "text/plain", VALUE);
}
boolean connectedToAP=false;
void setup(void) {
//Serial
Serial.begin(115200);
Serial.println(HELLO_MESSAGE);
//Ticker
Serial.print("ticker: ");
Serial.print(t_waitTimeMS/1000.0);
Serial.println("sec");
//DS18B20
DS18B20.begin();//->find all devices
Serial.print("DS18B20 Found: ");
Serial.print(String(DS18B20.getDeviceCount()));
Serial.println(" devices");
//soft AP
Serial.print("Softrawre AP ");
if(!WiFi.softAP(APssid, APpassword)){
Serial.println("failed");
}else{
Serial.println("started");
}
//connect to AP
WiFi.begin(ssid, password);
//Multicast DNS
if (MDNS.begin("esp8266")) {
MDNS.addService("http", "tcp", webServerPort);
MDNS.addService("esp", "udp", g_port);
Serial.println("MDNS responder started");
}
//UDP server
g_udp.begin(g_port);
// web server
server.on("/", handleRoot);
server.on("/json", handleGetValueJSON);
server.on("/get", handleGetValueRAW);
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void udpBrodcast(){
IPAddress ip = WiFi.localIP();
ip[3] = 255;
// transmit broadcast package
g_udp.beginPacket(ip, g_port);
g_udp.write(VALUE.c_str());
g_udp.write("\n");
g_udp.endPacket();
}
void SerialPrintWiFiStatus(){
Serial.print("WIFI: ");
if(WiFi.status() == WL_CONNECTED){
Serial.print("Connected to: ");
Serial.print(ssid);
Serial.print(" IP address: ");
Serial.println(WiFi.localIP());
}else{
Serial.print("Disconnected from: ");
Serial.println(ssid);
}
}
void tick() {
Serial.println("tick!");
SerialPrintWiFiStatus();//print WIFI status
updateVALUE();//update the value
udpBrodcast();//brodcast value using UDP
}
void updateThingSpeak(String tsData)
{
WiFiClient client;
if (client.connect(thingSpeakAddress, 80))
{
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+thingSpeakWriteAPIKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(tsData.length());
client.print("\n\n");
client.print(tsData);
if (client.connected())
{
Serial.print("Connected to ThingSpeak, sent: ");
Serial.println(tsData);
return;
}
}
Serial.print("Connection to ThingSpeak Failed!");
Serial.println(tsData);
}
String DeviceAddressToString(const DeviceAddress &deviceAddress) {
String ret="0x";
for (uint8_t i = 0; i < 8; i++)
{
if (deviceAddress[i] < 16) ret=ret+"0";
ret=ret+String(deviceAddress[i], HEX);
}
return ret;
}
void updateVALUE(){
uint8_t DS18B20num = DS18B20.getDeviceCount();
DeviceAddress deviceAddress;
if(DS18B20num==0)
{
VALUE="error-no-devices";
}else{
DS18B20.requestTemperatures(); /// sends command for all devices on the bus to perform a temperature conversion
VALUE="";//values will be concatenated
String ThingSpeak="";
for(uint8_t index=0; index<DS18B20num; index++)
{
delay(20);//miliseconds
VALUE=VALUE+String(index)+":";
if(!DS18B20.getAddress(deviceAddress,index))
{
VALUE=VALUE+"0x00=??*C;";
}else{
VALUE=VALUE+DeviceAddressToString(deviceAddress)+"=";
float temp= DS18B20.getTempCByIndex(index);
if(temp == 85.0 || temp == (-127.0)) {
VALUE=VALUE+"error";
}else{
VALUE=VALUE+String(temp)+"*C";
ThingSpeak+="field";
ThingSpeak+=String(index+1);
ThingSpeak+="=";
ThingSpeak+=String(temp);
ThingSpeak+="&";
}
VALUE=VALUE+";";
}
}
if(ThingSpeak!="")
{
updateThingSpeak(ThingSpeak);
}
}
Serial.print("TEMP: ");
Serial.println(VALUE);
}
void loop(void) {
//webserver
server.handleClient();
//ticker
int d = (int)millis()-t_memory;
if(d<0) { d=-d; }//millis can overflow
if(d>t_waitTimeMS) {
t_memory=millis();
tick();
}
//check if connection status has changed
boolean isConnectedToAP=(WiFi.status() == WL_CONNECTED);
if(connectedToAP != isConnectedToAP) {
connectedToAP = isConnectedToAP;
Serial.print("INFO: ");
if(connectedToAP) { Serial.println("WIFI connected"); }
else { Serial.println("WIFI disconnected"); }
}
//ms - give esp8266 time to breathe
delay(100);
}