Snippets
Created by
Grant Young
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 | // NOTE: save this as a .ino file for use in the Arduino IDE
//
// This was a "first principles" attempt at getting AT commands working with an
// Arduino Uno + Nano, using the ESP8266 chip.
// It works, sorta. It's very unstable, and it's very convoluted as I've not
// split things out into reasonable methods etc. (this the "flat" in the file name)
// It is not robust and has limited error handling. It doesn't provide the ability
// to do multiple retries for failed messages etc.
// I'm indebted to the author of the WeeESP8266 library, upon which a lot of my
// understanding is based.
//
// SEE COMMENTS IN CLASSES IMPLEMENTATION FOR A MORE DETAILED/BETTER DESCRIPTION
// OF WHAT'S GOING ON...
#include <SoftwareSerial.h>
#define API_KEY "<your-api-key>"
#define HOST_NAME "api.thingspeak.com"
#define HOST_PORT (80)
#define END_POINT "/update"
#define SSID "<your-wifi-network>"
#define PSK "<your-wifi-password>"
SoftwareSerial espSerial = SoftwareSerial(8,9);
void setup() {
Serial.begin(9600);
wifiInit();
wifiRequest();
}
unsigned interval = 30000; // millis
long pMillis = millis();
void loop() {
// put your main code here, to run repeatedly:
if (millis() - pMillis >= interval) {
pMillis = millis();
wifiRequest();
}
}
// Utility functions
void printResponse()
{
char a;
unsigned long start = millis();
while (millis() - start < 5000) {
while(espSerial.available() > 0) {
a = espSerial.read();
if(a == '\0') continue;
Serial.print(a);
}
}
}
bool containsString(char *searchIn, char *searchFor) {
return (strstr(searchIn, searchFor) != NULL);
}
bool containsString(String searchIn, String searchFor) {
return (strstr(searchIn.c_str(), searchFor.c_str()) != NULL);
}
String getResponseToString(String target, uint32_t timeout = 5000)
{
String data;
char a;
unsigned long start = millis();
while (millis() - start < timeout) {
while(espSerial.available() > 0) {
a = espSerial.read();
if(a == '\0') continue;
data += a;
}
if (containsString(data, target)) {
break;
}
}
return data;
}
String getResponse(uint32_t timeout = 5000)
{
String data;
char a;
unsigned long start = millis();
while (millis() - start < timeout) {
while(espSerial.available() > 0) {
a = espSerial.read();
if(a == '\0') continue;
data += a;
}
}
return data;
}
bool responseContainsString(String target, uint32_t timeout = 5000)
{
String data_tmp;
data_tmp = getResponseToString(target, timeout);
if (containsString(data_tmp, target)) {
return true;
}
return false;
}
void emptySerialBuffer()
{
while(espSerial.available() > 0) {
espSerial.read();
}
}
bool getResponseSubstring(String target, String begin, String end, String &data, uint32_t timeout = 5000)
{
String data_tmp;
data_tmp = getResponseToString(target, timeout);
if (containsString(data_tmp, target)) {
int offset = begin.length();
int32_t index1 = data_tmp.indexOf(begin);
int32_t index2 = data_tmp.indexOf(end, index1+offset);
if (index1 != -1 && index2 != -1) {
index1 += begin.length();
data = data_tmp.substring(index1, index2);
return true;
}
}
data = "";
return false;
}
bool wifiInit()
{
Serial.println("wifiInit()");
espSerial.begin(9600);
emptySerialBuffer();
espSerial.println("AT");
if (!responseContainsString("OK")) {
Serial.println("Error communicating with ESP826\n");
return false;
}
emptySerialBuffer();
espSerial.println("AT+CWMODE=1");
if (!responseContainsString("OK")) {
Serial.println("Error switching to station mode");
return false;
}
emptySerialBuffer();
espSerial.println("AT+CWJAP?");
// returns:
//AT+CWJAP?
//
//+CWJAP:"<ssid>"
//
//OK
String d;
getResponseSubstring("OK", ":\"", "\"", d);
if (d == SSID) {
Serial.print("Already connected to ");
Serial.println(SSID);
} else {
// AT+CWJAP="<ssid>","<pass>"
char cmd[64];
snprintf(cmd, sizeof(cmd), "AT+CWJAP=\"%s\",\"%s\"", SSID, PSK);
emptySerialBuffer();
Serial.println(cmd);
espSerial.println(cmd);
printResponse();
return true;
if (responseContainsString("OK")) {
Serial.print("Connected to ");
Serial.println(SSID);
} else {
Serial.print("Error connecting to SSID ");
Serial.println(SSID);
return false;
}
}
emptySerialBuffer();
espSerial.println("AT+CIPMUX=0");
if (!responseContainsString("OK")) {
Serial.println("Error setting MUX to single");
return false; // as command syntax is dependent on this, need to fail
}
return true;
}
bool wifiRequest()
{
Serial.print("\n\nwifiRequest()--");
Serial.print((millis()/1000));
Serial.println("s");
// make sure we haven't lost comms
emptySerialBuffer();
espSerial.println("AT");
if (!responseContainsString("OK")) {
Serial.println("Error communicating with ESP826");
espSerial.println("AT+RST"); // attempt reset
delay(5000); // TODO: be more graceful
return false;
}
char cmd[64]; // this accommodates the requirements of this demo
snprintf(cmd, sizeof(cmd), "AT+CIPSTART=\"TCP\",\"%s\",%i", HOST_NAME, HOST_PORT);
// AT+CIPSTART="TCP","api.thingspeak.com",80
//Serial.println(cmd);
emptySerialBuffer();
espSerial.println(cmd);
String r = getResponse();
// Serial.print("Response:\n");
// Serial.print(r);
if (containsString(r, "OK") || containsString(r, "ALREAY CONNECT")) {
// Yes... the current version of the firmware responds with this typo?!
// But, if we get this response, we're ok to continue
// do nothing
} else if (containsString(r, "ERROR")) {
Serial.print("Error connecting to ");
Serial.print(HOST_NAME);
Serial.print(":");
Serial.print(HOST_PORT);
Serial.print("Response:\n");
Serial.print(r);
return false;
}
// either OK or ALREADY CONNECTED, so good to continue
// create the request string
// setup some dummy data (to come from sensors/EEPROM etc.)
char siteID[] = "001";
char monitorID[] = "001";
char sensorType[] = "elec";
float f_curr = 0.23f;
float f_volt = 240.0f;
char c_curr[6];
dtostrf(f_curr, 4, 2, c_curr);
char c_volt[7];
dtostrf(f_volt, 4, 2, c_volt);
char payload[64]; // 60 is expected max
snprintf(payload, sizeof(payload), "field1=%s&field2=%s&field3=%s&field4=%s&field5=%s", siteID, monitorID, sensorType, c_curr, c_volt);
//Serial.println(payload);
int payloadLength = static_cast<int>(strlen(payload)); // strlen returns size_t
// could also build using strcat
char requestTemplate[152] = "POST %s HTTP/1.1\n"
"Host: %s\n"
"Connection: keep-alive\n" // had issues with this being set to "close"
"X-THINGSPEAKAPIKEY: %s\n"
"Content-Type: application/x-www-form-urlencoded\n"
"Content-Length: %i"
"\n\n%s";
char request[256];
snprintf(request, sizeof(request), requestTemplate, END_POINT, HOST_NAME, API_KEY, payloadLength, payload);
// send the request
// the CIPSEND command occurs in two parts
// the first sends the length
// a prompt is returned
// then the HTTP request is sent
int requestLength = static_cast<int>(strlen(request));
//AT+CIPSEND=<length>
snprintf(cmd, sizeof(cmd), "AT+CIPSEND=%i", requestLength);
//Serial.println(cmd);
emptySerialBuffer();
espSerial.println(cmd);
if (responseContainsString(">")) {
//Serial.print(request);
// send the payload
emptySerialBuffer(); // just in case there's any remaining cruft
espSerial.print(request);
} else {
Serial.println("Error sending request. Response:");
Serial.print(r);
Serial.print("\n");
}
//char response[256]{0};
Serial.println("Waiting for response... ");
// get the response
// this is running in a stable fashion presently
// but doesn't allow for testing status/response
// it also, by necessity, requires 5+ secs to execute
// you would need to check the response to see if the +IPD: value and then read
// to number of bytes specified to not wait the full 10 seconds
unsigned long start = millis();
// String resp = "";
// char statusResp[128]{0};
// int c = 0;
// int idx = 0;
// int maxIdx = 128;
char a;
while (millis() - start < 5000) {
if(espSerial.available()) {
// c = espSerial.read();
// a = (char) c;
// if (idx < maxIdx) {
// statusResp[idx] = c;
// idx++;
// }
//resp += a; // building a string fails—gets truncated
a = (char) espSerial.read();
Serial.print(a);
}
}
// if (strstr(statusResp, "200 OK") != NULL) {
// Serial.println("RESPONSE: OK");
// } else {
// Serial.println("RESPONSE: ERROR");
// }
// close the connection
emptySerialBuffer();
//Serial.println("AT+CIPCLOSE");
//espSerial.println("AT+CIPCLOSE");
// the above was causing errors
// following this thread https://github.com/adafruit/Adafruit_ESP8266/issues/2
// suggests following two techniques, the second of which appears to be working
//espSerial.println("AT+CIPSERVER=0");
espSerial.println("AT+CIPSTATUS");
espSerial.println("AT+CIPSTATUS");
espSerial.println("AT+CIPCLOSE"); // closes the TCP connection
return true;
}
|
Comments (0)
You can clone a snippet to your computer for local editing. Learn more.