Skip to content

Instantly share code, notes, and snippets.

@meub
Last active August 29, 2020 04:59
Show Gist options
  • Save meub/f13b98c9f40cc83e46175c7ed20f56d0 to your computer and use it in GitHub Desktop.
Save meub/f13b98c9f40cc83e46175c7ed20f56d0 to your computer and use it in GitHub Desktop.
/*
This Arduino sketch sends a GET request to the specified
domain and appends a unique DEVICE_ID as a query parameter
on the request. After sending the device will go into Deep
Sleep mode to conserve power.
*/
#include <ESP8266WiFi.h>
const char* ssid = "SSID_NAME_HERE";
const char* password = "SSID_PASSWORD_HERE";
const char* device_id = "DEVICE_ID_HERE";
// no protocol here, assuming HTTP
const char* host = "DOMAIN_HERE";
const uint16_t port = 80;
void setup() {
Serial.begin(115200);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
// Explicitly set the ESP8266 to be a WiFi-client
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("connecting to ");
Serial.print(host);
Serial.print(':');
Serial.println(port);
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("connection failed");
delay(5000);
return;
}
// Make GET Request with Headers (CloudFront requires this)
if (client.connected() ) {
client.println((String)"GET /?device_id=" + device_id + " HTTP/1.0");
client.println((String)"Host: " + host);
client.println("Connection: keep-alive");
client.println("Cache-Control: max-age=0");
client.println("User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)");
client.println("Accept-Language: en-US,en;q=0.9");
client.println();
}
// wait for data to be available
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 20000) {
Serial.println(">>> Client Timeout !");
client.stop();
delay(5000);
return;
}
}
// Read all the lines of the reply from server and print them to Serial
Serial.println("receiving from remote server");
// not testing 'client.connected()' since we do not need to send data here
while (client.available()) {
char ch = static_cast<char>(client.read());
Serial.print(ch);
}
// Close the connection
Serial.println();
Serial.println("closing connection");
client.stop();
// Wait 1 second and then initiate Deep Sleep to conserve battery
delay(1000);
ESP.deepSleep(0);
}
void loop(){}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment