4.溫溼度站升級版

網路遙控

Google Apps Script

ESP8266 端

Google 重指向 函式庫下載

DHT 函式庫

#include <ESP8266WiFi.h>

#include "HTTPSRedirect.h"

#include <DHT.h>

#define DHTPIN 2

#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

WiFiServer server(80);

const int httpPort = 80;

////////////////////////////////////////////////////////////////////////////////

const char* ssid = "tomorrows";

const char* password = "----";

const char* thingspeak_host = "api.thingspeak.com";

const char* writeAPIKey = "VLGNCOYLSQHRG6RW";

const char *GScriptId = "AKfycbz_mRNgVDlfM3m8JylUIb27Kk1JfE-1ww0Y_8F__K7Msxmrbv0=";

const int dataPostDelay = 60000; // 1 minutes

///////////////////////////////////////////////////////////////////////////////

unsigned long t1,t2;

String humidity,temperature;

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

const char* googleRedirHost = "script.googleusercontent.com";

const int httpsPort = 443;

HTTPSRedirect client(httpsPort);

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

const char* fingerprint = "F0 5C 74 77 3F 6B 25 D7 3B 66 4D 43 2F 7E BC 5B E9 28 86 AD";

void data_to_html(String data1, String data2){

WiFiClient client = server.available();

client.println("HTTP/1.1 200 OK");

client.println("Content-Type: text/html");

client.println("Connection: close");

client.println();

client.println("<!DOCTYPE html>");

client.println("<head>\n<meta charset='UTF-8'>");

client.println("<title>ESP8266 Temperature & Humidity DHT22 Sensor</title>");

client.println("</head>\n<body>");

client.println("<H2>ESP8266 & DHT22 Sensor</H2>");

client.println("<H3>Maker Lab</H3>");

client.println("<pre>");

client.print("Humidity (%) : ");

client.println(data1);

client.print("Temperature (°C) : ");

client.println(data2);

client.println("</pre>");

client.print("</body>\n</html>");

}

void data_to_tingspeak(String data3, String data4){

WiFiClient client = server.available();

if (!client.connect(thingspeak_host, httpPort)) {

return;

}

String url_1 = "/update?key=";

url_1+=writeAPIKey;

url_1+="&field1=";

url_1+=data3;

url_1+="&field2=";

url_1+=data4;

url_1+="\r\n";

// This will send the request to the server

client.print(String("GET ") + url_1 + " HTTP/1.1\r\n" +

"Host: " + thingspeak_host + "\r\n" +

"Connection: close\r\n\r\n");

}

void postData(String tag, String temp, String humi){

if (!client.connected()){

Serial.println("Connecting to client again...");

client.connect(host, httpsPort);

}

String urlFinal = url + "tag=" + tag + "&temp=" + temp + "&humi=" + humi ;

client.printRedir(urlFinal, host, googleRedirHost);

}

void setup() {

Serial.begin(115200);

WiFi.mode(WIFI_STA);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {

delay(500);

}

server.begin();

Serial.println(" IP address: ");

Serial.println(WiFi.localIP());

Serial.print(String("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("Connection failed. Retrying...");

}

// Connection Status, 1 = Connected, 0 is not.

Serial.println("Connection Status: " + String(client.connected()));

Serial.flush();

if (!flag){

Serial.print("Could not connect to server: ");

Serial.println(host);

Serial.println("Exiting...");

Serial.flush();

return;

}

// Data will still be pushed even certification don't match.

if (client.verify(fingerprint, host)) {

Serial.println("Certificate match.");

} else {

Serial.println("Certificate mis-match");

}

t1=millis();

}

void loop() {

t2=millis();

if(t2>t1+60000){

Serial.println(WiFi.localIP());

humidity = String(dht.readHumidity());

temperature = String(dht.readTemperature());

data_to_tingspeak(temperature, humidity);

postData("Home", temperature, humidity);

t1=t2;

}

data_to_html(humidity,temperature);

}

function doGet(e){

Logger.log("--- doGet ---");

var tag = "",

temp = "",

humi = "";

try {

// this helps during debuggin

if (e == null){e={}; e.parameters = {tag:"test",temp:"-1",humi:"-1"};}

tag = e.parameters.tag;

temp = e.parameters.temp;

humi = e.parameters.humi;

// save the data to spreadsheet

save_data(tag, temp, humi);

return ContentService.createTextOutput("Wrote:\n tag: " + tag + "\n temp: " + temp + "\n humi: " + humi);

} catch(error) {

Logger.log(error);

return ContentService.createTextOutput("oops...." + error.message

+ "\n" + new Date()

+ "\ntag: " + tag +

+ "\ntemp: " + temp +

+ "\nhumi: " + humi );

}

}

// Method to save given data to a sheet

function save_data(tag, temp, humi){

Logger.log("--- save_data ---");

try {

var dateTime = new Date();

// Paste the URL of the Google Sheets starting from https thru /edit

// For e.g.: https://docs.google.com/..../edit

var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1QMC8Wt-hGzDQ7AEkfRNOH8sHu_4f2RP-pBWb-FOlNB4/edit");

var summarySheet = ss.getSheetByName("Summary");

var dataLoggerSheet = ss.getSheetByName("DataLogger");

// Get last edited row from DataLogger sheet

var row = dataLoggerSheet.getLastRow() + 1;

// Start Populating the data

dataLoggerSheet.getRange("A" + row).setValue(row -1); // ID

dataLoggerSheet.getRange("B" + row).setValue(dateTime); // dateTime

dataLoggerSheet.getRange("C" + row).setValue(tag); // tag

dataLoggerSheet.getRange("D" + row).setValue(temp); // temp

dataLoggerSheet.getRange("E" + row).setValue(humi); // humi

// Update summary sheet

summarySheet.getRange("B1").setValue(dateTime); // Last modified date

// summarySheet.getRange("B2").setValue(row - 1); // Count

}

catch(error) {

Logger.log(JSON.stringify(error));

}

Logger.log("--- save_data end---");

}