-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEspHelper.cpp
101 lines (93 loc) · 2.41 KB
/
EspHelper.cpp
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
/*
* EspHelper.cpp - Library for the ESP8266 Module
* Created by Shane Jansen, September 3 2015
*/
#include "Arduino.h"
#include "EspHelper.h"
EspHelper::EspHelper (int RX, int TX, String SSID, String PASSWORD, bool DEBUG) {
espSerial = new SoftwareSerial(RX, TX);
espSerial->begin(9600);
_RX = RX;
_TX = TX;
_SSID = SSID;
_PASSWORD = PASSWORD;
_DEBUG = DEBUG;
}
/**
* Checks the ESP's WiFi connection and
* makes one if necessary.
*/
void EspHelper::makeConnection() {
String ipAddress = sendData("AT+CIFSR\r\n", 5000);
if (ipAddress.indexOf("0.0.0.0") == -1) {
serialPrint("ESP is already connected.");
sendData("AT+CIFSR\r\n", 2000);
}
else {
serialPrint("ESP is not connected; making connection.");
sendData("AT+RST\r\n", 5000);
sendData("AT+CWMODE=1\r\n", 2000);
String creds = "AT+CWJAP=\"" +_SSID + "\",\"" + _PASSWORD + "\"\r\n";
sendData(creds, 10000);
sendData("AT+CIFSR\r\n", 2000);
}
}
/**
* Sends data to the ESP and captures
* the response in a single string. The
* timeout is how long to wait for the response.
* EspHelper::makeConnection should be called before
* this to ensure a connection is made.
*/
String EspHelper::sendData(String command, int timeout) {
String response = "";
espSerial->print(command);
long int time = millis();
while((time + timeout) > millis()) {
while(espSerial->available()) {
char c = espSerial->read();
response += c;
}
}
serialPrint(response);
return response;
}
/**
* Makes a GET request which, in turn,
* sends a push notification using the
* Parse API.
*/
void EspHelper::motionDetected() {
sendData("AT+CIPSTART=\"TCP\",\"sjjapps.com\",80\r\n", 2000);
String request = "GET http://www.sjjapps.com/house-control/path-checker\r\n";
String cipSend = "AT+CIPSEND=";
cipSend += request.length() - 1;
sendData(cipSend += "\r\n", 2000);
sendData(request, 5000);
}
/**
* Sends an AT Command
*/
void EspHelper::sendAtCommand(String command) {
espSerial->println(command);
}
/**
* Logs all of the ESP's output
* to the Serial. Should be called
* from Arduino loop.
*/
void EspHelper::logOutput() {
if(_DEBUG && espSerial->available()) {
while(espSerial->available()) {
char c = espSerial->read();
Serial.write(c);
}
}
}
/**
* Print to the Serial if we
* are in DEBUG mode.
*/
void EspHelper::serialPrint(String data) {
if (_DEBUG) Serial.println(data);
}