Skip to content

Merge of customheader methods for tago.io api keys #95

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@

/**
* Example for reading temperature and humidity
* using the DHT22 and ESP8266
*
* Copyright (c) 2016 Losant IoT. All rights reserved.
* https://www.losant.com
*/

#define DHTPIN 4
// what digital pin the DHT22 is conected to
#define DHTTYPE DHT22 // there are multiple kinds of DHT sensors
//#define DEBUG

#include "DHT.h"
#include <DebugMacros.h>
#include <ESP8266WiFi.h>
#include <HTTPSRedirect.h>
#include <PubSubClient.h>

const char* mqttServer = "192.168.20.18";
const int mqttPort = 1883;
const char* mqttUser = "XXX";
const char* mqttPassword = "XXX";

// your wifi ap info
const char* ssid = "XXX";
const char* password = "XXX";

//your gsscript sheet id

const char *GScriptId = "XXX";
const char* host = "script.google.com";

const int dataPostDelay = 900000; // 15 minutes = 15 * 60 * 1000
const int httpsPort = 443;

String url = String("/macros/s/") + GScriptId + "/exec?";


HTTPSRedirect client(httpsPort);
PubSubClient mqclient;

DHT dht(DHTPIN, DHTTYPE);

void setup() {
Serial.begin(9600);
Serial.setTimeout(2000);
// Wait for serial to initialize.
while(!Serial) { }

Serial.println("setup: Device Started");
Serial.println("setup: -------------------------------------");
Serial.println("setup: Running DHT!");
Serial.println("setup: -------------------------------------");
Serial.println(ssid);
Serial.flush();
dht.begin();
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("setup:IP address: ");
Serial.println(WiFi.localIP());

//Insecure for TLS cert checking
client.setInsecure();
client.setContentTypeHeader("application/json");

Serial.print("setup: Connecting to ");
Serial.println(host);

bool flag = false;

for (int i=0; i<5; i++){
int retval = client.connect(host, httpsPort);
if (retval == 1) {
flag = true;
break;
}
else
Serial.println("setup: Initial https Connection failed. Retrying...");
}

if (!flag){
Serial.print("setup: Could not connect to server: ");
Serial.println(host);
Serial.println("setup: Exiting...");
return;
}
Serial.println("setup: Before MQTT");
mqclient.setServer(mqttServer, mqttPort);
mqclient.setCallback(callback);
while (!mqclient.connected()) {
Serial.println("setup: Connecting to MQTT...");

if (mqclient.connect("ESP8266Client", mqttUser, mqttPassword )) {

Serial.println("connected");

} else {

Serial.print("failed with state ");
Serial.print(mqclient.state());
delay(2000);

}
}

mqclient.publish("esp/test", "hello"); //Topic name
mqclient.subscribe("esp/test");
}
void postData(String tag, float value){
// this method is cruft and exist in case there is a desire for a Post payload, it was cloned from the Get fucntion, and never taken further
if (!client.connected()){
Serial.println("postData: Connecting to client again…");
client.connect(host, httpsPort);
}
String payload = "tag=" + tag + "&value=" + String(value);
Serial.print("url");
//Serial.print(url);
Serial.print(" host ");
//Serial.print(host);
Serial.print("payload ");
//Serial.print(payload);
client.POST(url, host, payload);
Serial.print("getStatusCode: ");
Serial.print(client.getStatusCode());
//Serial.print("getReasonPhrase");
//Serial.print(client.getReasonPhrase());
Serial.print(client.getResponseBody());
}

//void getData(String tag, float value){
void getData(String Sensorname, float Humidity, float Temperature){
if (!client.connected()){
Serial.println("getData:Connecting to client again…");
client.connect(host, httpsPort);
}
//String payload = "tag=" + tag + "&value=" + String(value);
String payload = "Sensorname=" + Sensorname + "&Humidity=" + String(Humidity)+ "&Temperature=" + String(Temperature);
String url2 = url + payload;
//Serial.print("GetData: url2\n");
//Serial.print(url2);
//Serial.print(" host ");
//Serial.print(host);
//Serial.print("payload ");
//Serial.print(payload);
client.GET(url2, host);
Serial.print("getData: getStatusCode: ");
Serial.print(client.getStatusCode());
//Serial.print("getReasonPhrase");
//Serial.print(client.getReasonPhrase());
//Serial.print(client.getResponseBody());
}

void callback(char* topic, byte* payload, unsigned int length) {

Serial.print("Message arrived in topic: ");
Serial.println(topic);

Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}

Serial.println();
Serial.println("-----------------------");

}

void loop() {
// Wait a few seconds between measurements.


// 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)) {
Serial.println(F("loop: Failed to read from DHT sensor!"));
return;
}

// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);

Serial.print(F("loop: Humidity: "));
Serial.print(h);
Serial.print(F("% Temperature: "));
Serial.print(t);
Serial.print(F("°C "));
Serial.print(f);
Serial.print(F("°F Heat index: "));
Serial.print(hic);
Serial.print(F("°C "));
Serial.print(hif);
Serial.println(F("°F"));
getData("1710Office01" ,h, f);
// postData("Humidity" ,h);
// #postData("TempC",t);
// #postData("TempF",f);
delay(300000);


}
56 changes: 53 additions & 3 deletions HTTPSRedirect/HTTPSRedirect.cpp
Original file line number Diff line number Diff line change
@@ -155,6 +155,25 @@ void HTTPSRedirect::createPostRequest(const String& url, const char* host, const
return;
}

void HTTPSRedirect::createPostRequestcustomHeader(const String& url, const char* host, const String& customHeader, const String& payload){
// Content-Length is mandatory in POST requests
// Body content will include payload and a newline character
unsigned int len = payload.length() + 1;

_Request = String("POST ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: ESP8266\r\n" +
(_keepAlive ? "" : "Connection: close\r\n") +
"Content-Type: " + _contentTypeHeader + "\r\n" +
customHeader + "\r\n" +
"Content-Length: " + len + "\r\n" +
"\r\n" +
payload +
"\r\n\r\n";

return;
}


bool HTTPSRedirect::getLocationURL(void){

@@ -377,9 +396,12 @@ bool HTTPSRedirect::POST(const String& url, const char* host, const String& payl
return POST(url, host, payload, _printResponseBody);
}

bool HTTPSRedirect::POST(const String& url, const char* host, const String& payload, const bool& disp){


bool HTTPSRedirect::POST(const String& url, const char* host, const String& payload, const bool& disp){
bool retval;
bool oldval;


// set _printResponseBody temporarily to argument passed
oldval = _printResponseBody;
@@ -390,12 +412,41 @@ bool HTTPSRedirect::POST(const String& url, const char* host, const String& payl
// which did not have redirection
_redirHost = host;
_redirUrl = url;

InitResponse();

// Create request packet
//createPostRequest(url, host, payload);
createPostRequest(url, host, payload);
// Call request handler
retval = printRedir();

_printResponseBody = oldval;
return retval;
}

bool HTTPSRedirect::POSTcustomHeader(const String& url, const char* host, const String& customHeader, const String& payload){
return POSTcustomHeader(url, host, customHeader, payload, _printResponseBody);
}


bool HTTPSRedirect::POSTcustomHeader(const String& url, const char* host, const String& customHeader, const String& payload, const bool& disp){
bool retval;
bool oldval;

// set _printResponseBody temporarily to argument passed
oldval = _printResponseBody;
_printResponseBody = disp;

// redirected Host and Url need to be initialized in case a
// reConnectFinalEndpoint() request is made after an initial request
// which did not have redirection
_redirHost = host;
_redirUrl = url;
InitResponse();

// Create request packet
//createPostRequest(url, host, payload);
createPostRequestcustomHeader(url, host, customHeader, payload);
// Call request handler
retval = printRedir();

@@ -484,4 +535,3 @@ void HTTPSRedirect::printHeaderFields(void){
DPRINTLN(_hF.contentType);
}
#endif

1 change: 1 addition & 0 deletions HTTPSRedirect/HTTPSRedirect.h
Original file line number Diff line number Diff line change
@@ -54,6 +54,7 @@ class HTTPSRedirect : public WiFiClientSecure {
void InitResponse(void);
void createGetRequest(const String&, const char*);
void createPostRequest(const String&, const char*, const String&);
void createPostRequestcustomHeader(const String&, const char*, const String& , const String&);

#ifdef EXTRA_FNS
void fetchBodyRaw(void);
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
# ESP8266

Stuff I do with this tiny wireless wonder
@peril99 added a post method to this fork for usa in the arduino projects which need an https / post method. My use case was IOT projects based on arduino clones like esp8266 / esp32. These are the key sensors / affectors which sit outside and controls pumps teeny pumps (affectors) and ph sensors (atlas ezo).

These have all been tied together in a rudimentary dashboard for visualization @ https://admin.tago.io/public/dashboard/5f35d9868411cc00274b6a8a/e155a708-01a8-4fbc-8227-74e2b4e79855


to use this library with the arduino ide

1) clone a copy of this repo in a spot where you arduino ide can reference the libaries folder for me that was C:\Users\xxx\Documents\Arduino\libraries\HTTPSRedirect
2) include this library in the project you are including with a "#include <HTTPSRedirect.h>"