-
Notifications
You must be signed in to change notification settings - Fork 4
/
HubTemperature.ino
361 lines (302 loc) · 9.05 KB
/
HubTemperature.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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
// Will work only with ESP8266 firmware 0.9.2.2 or higher
// Some particulars of this sketch are for the Cactus Micro board,
// but it can be adapted for any Arduino
// Special thanks to David Reeves for his help
// Include the DHT library for reading from the Temp/Hum Sensor
#include "DHT.h"
////////////////////////////
////// Temp/Hum Sensor /////
////////////////////////////
// The pin OUT is connected to
#define DHTPIN 7
// The type of DHT sensor
#define DHTTYPE DHT22
// Tell the library which pin and type
DHT dht(DHTPIN, DHTTYPE);
////////////////////////////
// Initial State Streamer //
////////////////////////////
// Your hub's IP address to configure the direct connection
String hubIP = "Hub_IP";
int port = 8080;
// Bucket key - using the hub, this will be the name of your bucket
String bucketKey = "Hub_Temp";
///////////////////////////
// Event Signal Settings //
///////////////////////////
// How many signals are in your stream? You can have as few or as many as you want
const int NUM_SIGNALS = 3;
// What are the names of your signals (i.e. "Temperature", "Humidity", etc.)
// CANNOT CONTAIN SPACES
String signalName[NUM_SIGNALS] = {"Temperature","Humidity","Heat_Index"};
// This array is to store our signal data later
String signalData[NUM_SIGNALS];
////////////////////////////
///// WiFi Credentials /////
////////////////////////////
// WiFi SSID
#define SSID "WiFi_SSID"
// WiFi password
#define PASS "WiFi_Password"
////////////////////////////
/// Cactus Micro Settings //
////////////////////////////
// CH_PD pin - Used by Cactus Micro to enable ESP8266
#define RESET 13
// GPIO0
#define GPIO0 5
// RST pin - ESP8266 reset pin
#define RST 5
////////////////////////////
//// AT Command Setting ////
////////////////////////////
// Timeout in milliseconds
#define TIMEOUT 5000
#define CONTINUE false
#define HALT true
// This only runs once at the very beginning
void setup() {
// Start the Serial monitor
Serial.begin(9600);
// Communication with ESP8266
Serial1.begin(9600);
// Enable RST pin
digitalWrite(RST, 1);
// Enable GPIO1 pin to prevent bootloader mode
digitalWrite(GPIO0, 1);
// Enable CH_PD pin
pinMode(RESET, OUTPUT);
digitalWrite(RESET, 1);
// Wait for chip enable
delay(2000);
Serial.println("ESP8266 A0 Monitor");
reset();
// Wait for reset to complete
delay(5000);
// Reset & test if the module is ready
echoCommand("AT+RST", "Ready", HALT);
delay(5000);
echoCommand("AT+CSYSWDTENABLE", "WDT Enabled", HALT);
delay(500);
Serial.println("Module is ready.");
// Set up connection modes
// Retrieves the firmware ID (version number) of the module.
// Trying to hide SSID
echoCommand("AT+CWSAP?", "", HALT);
echoCommand("AT+GMR", "OK", CONTINUE);
// Station mode - MODE 1 = Station; Mode 2 = AP; Mode 3 = Both
echoCommand("AT+CWMODE=1", "", HALT);
// Allow one connection
echoCommand("AT+CIPMUX=1", "", HALT);
// Connect to the wifi
boolean connection_established = false;
for(int i=0;i<5;i++)
{
if(connectWiFi())
{
connection_established = true;
delay(5000);
break;
}
}
if (!connection_established) errorHalt("Connection failed");
delay(5000);
// Echo IP address.
echoCommand("AT+CIFSR", "", HALT);
// Start the DHT library reading
dht.begin();
}
// This repeats
void loop()
{
// Reset ESP8266 each time around
reset();
delay(2000);
// The takeTempHum() function reads from the sensor
takeTempHum();
// The toHub() function streams our events
while(!toHub());
}
// Here are the data bucket creation, event data posting, error handling,
// and WiFi connection functions
// They do not need to be edited - everything you would need to change for
// your project can be found above
// Read from the sensor
void takeTempHum()
{
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
h = 0;
t = 0;
f = 0;
return;
}
// Compute heat index in Fahrenheit
float hif = dht.computeHeatIndex(f, h);
// Store our readings in the signalData array to be streamed
signalData[0] = String(f);
signalData[1] = String(h);
signalData[2] = String(hif);
}
// Stream events to the hub
boolean toHub ()
{
for (int i=0; i<NUM_SIGNALS; i++)
{
// Must be connected to your destination URL
while(!connectService(hubIP,port)) {};
// Get connection status
while(!echoCommand("AT+CIPSTATUS", "STATUS:3", CONTINUE))
{
echoCommand("AT+CIPCLOSE", "OK", CONTINUE);
while(!connectService(hubIP,port)) {};
};
// Build HTTP request.
String toSend = "POST http://" + hubIP + "/" + bucketKey + "/" + signalName[i] + "\r\n";
String payload = signalData[i];
toSend += "Content-Type: text/plain\r\n";
toSend += "Content-Length: "+String(payload.length())+"\r\n";
toSend += "\r\n";
toSend += payload;
Serial.println(toSend);
// Ready the module to receive raw data
if (!echoCommand("AT+CIPSEND="+String(toSend.length()), ">", CONTINUE))
{
echoCommand("AT+CIPCLOSE", "", CONTINUE);
Serial.println("Connection timeout.");
return false;
}
// Send the raw HTTP request
// POST
if(!echoCommand(toSend,"20", CONTINUE)) return false;
String toPrint = "Request ";
toPrint += (i + 1);
toPrint += " sent!";
Serial.println(toPrint);
echoCommand("AT+CIPCLOSE", "OK", CONTINUE);
delay(2000);
}
return true;
}
// Print error message and loop stop.
void errorHalt(String msg)
{
Serial.println(msg);
Serial.println("HALT");
while(true){};
}
// Read characters from WiFi module and echo to serial until keyword occurs or timeout.
boolean echoFind(String keyword)
{
byte current_char = 0;
byte keyword_length = keyword.length();
// Fail if the target string has not been sent by deadline.
unsigned long deadline = millis() + TIMEOUT;
while(millis() < deadline)
{
if (Serial1.available())
{
char ch = Serial1.read();
Serial.write(ch);
if (ch == keyword[current_char])
if (++current_char == keyword_length)
{
Serial.println();
return true;
}
}
}
// Timed out
return false;
}
// Read and echo all available module output.
// (Used when we're indifferent to "OK" vs. "no change" responses or to get around firmware bugs.)
void echoFlush()
{while(Serial1.available()) Serial.write(Serial1.read());}
// Echo module output until 3 newlines encountered.
// (Used when we're indifferent to "OK" vs. "no change" responses.)
void echoSkip()
{
echoFind("\n"); // Search for nl at end of command echo
echoFind("\n"); // Search for 2nd nl at end of response.
echoFind("\n"); // Search for 3rd nl at end of blank line.
}
// Send a command to the module and wait for acknowledgement string
// (or flush module output if no ack specified).
// Echoes all data received to the serial monitor.
boolean echoCommand(String cmd, String ack, boolean halt_on_fail)
{
Serial1.println(cmd);
#ifdef ECHO_COMMANDS
Serial.print("--"); Serial.println(cmd);
#endif
// If no ack response specified, skip all available module output.
if (ack == "")
echoSkip();
else
// Otherwise wait for ack.
// Timed out waiting for ack string
if (!echoFind(ack))
if (halt_on_fail)
// Critical failure halt.
errorHalt(cmd+" failed");
else
// Let the caller handle it.
return false;
// Ack blank or ack found
return true;
}
// Connect to the specified wireless network.
boolean connectWiFi()
{
String cmd = "AT+CWJAP=\"" SSID "\",\"" PASS "\"";
// Join Access Point
if (echoCommand(cmd, "OK", CONTINUE))
{
Serial.println("Connected to WiFi.");
return true;
}
else
{
Serial.println("Connection to WiFi failed.");
return false;
}
}
// Connect to a service; in our case, the hub at IP address on Port
boolean connectService(String service, int port)
{
String serviceConnect = "AT+CIPSTART=\"TCP\",\"" + service + "\"," + port;
// Handle connection errors
if (!echoCommand(serviceConnect, "Linked", CONTINUE)) {
if (echoCommand(serviceConnect, "ALREADY CONNECTED", CONTINUE)){
return true;
}
if (echoCommand(serviceConnect, "busy p...", CONTINUE)) {
reset();
delay(5000);
}
if (echoCommand(serviceConnect, "ERROR", CONTINUE)) {
reset();
delay(5000);
}
delay(2000);
return false;
}
delay(2000);
return true;
}
// Reset the ESP8266 Chip
void reset()
{
digitalWrite(RESET,LOW);
delay(1000);
digitalWrite(RESET,HIGH);
delay(1000);
}