//----------------------------------------Include the NodeMCU ESP8266 Library
//----------------------------------------see here: https://www.youtube.com/watch?v=8jMr94B8iN0 to add NodeMCU ESP12E ESP8266 library and board (ESP8266 Core SDK)
#include <ArduinoJson.h>
#include <ArduinoUniqueID.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include "globals.h"
// Define the device ID for this device, updated on boot
String device_id = "unkown-default";
//----------------------------------------Host & httpsPort
const char* host = "script.google.com";
const int httpsPort = 443;
//----------------------------------------
WiFiClientSecure client; //--> Create a WiFiClientSecure object.
// String GAS_ID = "AKfycbxv-9an4ZeYfB5YuCQkFDUoSkzYUbkgc7vwnNXZ3AJFnMQArMqPr1QSeOxkavDow8HZ"; //--> spreadsheet script ID
int smoke_pin = 34;/* MQ2 O/P pin */
int flame_pin = 14;/* IR flame sensor D6*/
int buzzer = 19; /*Connected to D2 pin of NodeMCU*/
int smokeThres = 200;
int flameThres = 1;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
delay(500);
// Generate the unique ID for the board
device_id = generateUniqueID();
Serial.print("UniqueID: " + device_id);
// Connect to the WiFi access point
WiFi.begin(WIFI_SSID, WIFI_PASSWORD); //--> Connect to your WiFi router
Serial.println("");
//----------------------------------------Wait for connection
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
//----------------------------------------Make the On Board Flashing LED on the process of connecting to the wifi router.
}
Serial.println("");
Serial.print("Successfully connected to : ");
Serial.println(WIFI_SSID);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
//----------------------------------------
// Set the GPIO pin mode for input
pinMode(smoke_pin, INPUT);
pinMode(flame_pin, INPUT);
// To skip the CA cert for SSL (HTTPS) connection
client.setInsecure();
// Register the device in the database
registerDevice();
}
void loop() {
// Reading smoke or flame takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
/* Read from IR flame */
float flameRead = digitalRead(flame_pin);
float flame_val = flameRead;
/* Read from MQ2 smoke sensor */
float smokeRead = analogRead(smoke_pin) >> 2;
float smoke_val = smokeRead;
// Check if any reads failed and exit early (to try again).
if (isnan(flame_val) || isnan(smoke_val)) {
Serial.println("Failed to read from sensor!");
delay(DATA_INVALID_DELAY);
return;
}
if (smoke_val >= smokeThres && flame_val >= flameThres) {
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
}
String Smoke = "smoke : " + String(smoke_val);
String Flame = "flame : " + String(flame_val);
Serial.println(Smoke);
Serial.println(Flame);
sendData((int)smoke_val, flame_val); //--> Calls the sendData Subroutine
delay(DATA_TELEMETRY_INTERVAL);
}
//==============================================================================
//============================================================================== void sendData
// Subroutine for sending data to Firebase Firestore
void sendData(float smoke, float flame) {
Serial.println("==========");
Serial.println("sending data ...");
Serial.print("connecting to ");
Serial.println(host);
//----------------------------------------Connect to Google host
if (!client.connect(host, httpsPort)) {
Serial.println("connection failed");
delay(CONNECTION_FAIL_DELAY);
return;
}
//----------------------------------------
//----------------------------------------Processing data and sending data
StaticJsonDocument<64> jsonData;
jsonData["smoke"] = smoke;
jsonData["flame"] = flame;
// Serialize the JSON object into string
// to send to the Android app
String data;
serializeJson(jsonData, data);
String url = "/macros/s/" + GAS_ID + "/exec?method=push_data&device_id=" + device_id + "&data=" + data;
Serial.print("requesting URL: ");
Serial.println(url);
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: FireAlarm/ESP8266Board\r\n" +
"Connection: keep-alive\r\n\r\n");
Serial.println("request sent");
//----------------------------------------
// //----------------------------------------Checking whether the data was sent successfully or not
while (client.connected()) {
String line = client.readStringUntil('\n');
Serial.println(line);
if (line == "\r") {
Serial.println("headers received");
break;
}
}
// There is a HTTP 302 redirect from Google Apps Script
// read the redirected HTTP response headers too
while (client.connected()) {
String line = client.readStringUntil('\n');
Serial.println(line);
if (line == "\r") {
Serial.println("headers received");
break;
}
}
String line = client.readStringUntil('\n');
Serial.print("received: ");
Serial.println(line);
Serial.println("closing connection");
Serial.println("==========");
Serial.println();
}
//==============================================================================
//============================================================================== void registerDevice
// Subroutine to register the device in the Firebase Firestore database
void registerDevice() {
Serial.println("==========");
Serial.println("registering device ...");
Serial.print("connecting to ");
Serial.println(host);
//----------------------------------------Connect to Google host
if (!client.connect(host, httpsPort)) {
Serial.println("connection failed");
delay(CONNECTION_FAIL_DELAY);
return;
}
//----------------------------------------
String url = "/macros/s/" + GAS_ID + "/exec?method=register_device&device_id=" + device_id;
Serial.print("requesting URL: ");
Serial.println(url);
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: FireAlarm/ESP8266Board\r\n" +
"Connection: close\r\n\r\n");
Serial.println("request sent");
//----------------------------------------
// //----------------------------------------Checking whether the data was sent successfully or not
while (client.connected()) {
String line = client.readStringUntil('\n');
Serial.println(line);
if (line == "\r") {
Serial.println("headers received");
break;
}
}
// There is a HTTP 302 redirect from Google Apps Script
// read the redirected HTTP response headers too
while (client.connected()) {
String line = client.readStringUntil('\n');
Serial.println(line);
if (line == "\r") {
Serial.println("headers received");
break;
}
}
String line = client.readStringUntil('\n');
Serial.print("received: ");
Serial.println(line);
Serial.println("closing connection");
Serial.println("==========");
Serial.println();
}
//==============================================================================
//============================================================================== String generateUniqueID
// Subroutine to generate the unique ID for the microcontroller board
String generateUniqueID() {
Serial.println("==========");
Serial.println("generating unique ID for board ...");
String id = "";
for (int i = 0; i < UniqueIDsize; i++) {
id += String(UniqueID[i], HEX);
}
Serial.println("==========");
Serial.println();
return id;
}