Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
9.4 kB
0
Indexable
Never
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_BMP085.h>
#include <DHT.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Firebase_ESP_Client.h>
#include <time.h>
#include <WiFi.h>


//firebase stuff
// Provide the token generation process info.
#include "addons/TokenHelper.h"
// Provide the RTDB payload printing info and other helper functions.
#include "addons/RTDBHelper.h"
// Insert your network credentials
// const char* ssid = "besp";
// const char* passphrase = "Spring!234";

// Insert Firebase project API Key
#define API_KEY "AIzaSyCr-IzETOZIeZ37PehtgIck1qhpOqnAtYE"

// Insert Authorized Email and Corresponding Password
#define USER_EMAIL "info@besp.ca"
#define USER_PASSWORD "nB7NAGZTUmiAj_R"

// Insert RTDB URLefine the RTDB URL
#define DATABASE_URL "https://home-sensors-e4137-default-rtdb.firebaseio.com/"

// Define Firebase objects
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;

// Variable to save USER UID
String uid;

// Database main path (to be updated in setup with the user UID)
String databasePath;
// Database child nodes
String tempPath = "/temperature";
String humPath = "/humidity";
String presPath = "/pressure";
String timePath = "/timestamp";

// Parent Node (to be updated in every loop)
String parentPath;

int timestamp;
FirebaseJson json;

const char* ntpServer = "pool.ntp.org";

// Timer variables (send new readings every three minutes)
unsigned long sendDataPrevMillis = 0;
unsigned long timerDelay = 180000;

// Load the BMP Library
Adafruit_BMP085 bmp;

// Data wire is plugged into pin 6 on the Arduino
const int ONE_WIRE_BUS = 4;
OneWire oneWire(ONE_WIRE_BUS);
 
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

// Load the DHT library for the humidity sensor
#define DHTTYPE DHT11   // DHT 11
#define DHTPIN 0    // what pin we're connected to(DHT10 and DHT20 don't need define it)
DHT dht(DHTPIN, DHTTYPE);   //   DHT11 DHT21 DHT22
 
//###############################
//### Debug Mode ###############
//##############################

//Change between Serial and display output
//Enter 1 for Debug, 0 for normal display output
#define DEBUG 1

#if DEBUG == 1
#define output Serial
#else
#define output tft
#endif

//###############################
//### End Debug Mode ###############
//##############################

// get current temperature from temp probe
// double tempProbe() {
//   double result;
//   if (!sensors.getTempCByIndex(0) ) {
//     output.print("N/A");
//   } else {
//     sensors.requestTemperatures();
//     output.print(sensors.getTempCByIndex(0) * .98);
//     output.println("*C");
//   }
//   return result;
// }

// //get current humidity
// float getHumidity() {
//   float temp_hum_val[2] = {0};
//   // Reading temperature or humidity takes about 250 milliseconds!
//   // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)

//   if (!dht.readTempAndHumidity(temp_hum_val)) {
//     output.print(temp_hum_val[0] * 1.055);
//     output.print("%");
//   } else {
//     output.println("Failed to get humidity value.");
//   }
//   return temp_hum_val[0];
// }

//initialize message
void initialize(){
  output.print("Initializing");
  delay(800);
  output.print(".");
  delay(800);
  output.print(".");
  delay(800);
  output.println(".");
  delay(800);

  configTime(0, 0, ntpServer);
     // Assign the api key (required)
  config.api_key = API_KEY;

  // Assign the user sign in credentials
  auth.user.email = USER_EMAIL;
  auth.user.password = USER_PASSWORD;

  // Assign the RTDB URL (required)
  config.database_url = DATABASE_URL;

  Firebase.reconnectWiFi(true);
  fbdo.setResponseSize(4096);

  // Assign the callback function for the long running token generation task */
  config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h

  // Assign the maximum retry of token generation
  config.max_token_generation_retry = 5;

  // Initialize the library with the Firebase authen and config
  Firebase.begin(&config, &auth);

  // Getting the user UID might take a few seconds
  Serial.println("Getting User UID");
  while ((auth.token.uid) == "") {
    Serial.print('.');
    delay(1000);
  }
  // Print user UID
  uid = auth.token.uid.c_str();
  Serial.print("User UID: ");
  Serial.println(uid);

  // Update database path
  databasePath = "/UsersData/" + uid + "/readings";
  output.println("Initialization Done!");
  delay(1000);
}

unsigned long previousTime = 0;
const long interval = 1000;

class sensorData{
  public:
    int temp;
    int humidity;
    int press;
    int probe;
  private:
};
sensorData data;

int ledPin = 2;

// Initialize WiFi
// Insert your network credentials
      char ssid[] = "bespiot";
      char passphrase[] = "Spring234";
void initWiFi() {  
    // WiFi.mode(WIFI_STA); //Optional
  
    WiFi.begin(ssid, passphrase);
    WiFi.disconnect();
    delay(100);
    Serial.println("\nConnecting");
    
    int timeout_counter = 0;

    while(WiFi.status() != WL_CONNECTED){
        Serial.println(WiFi.status());
        delay(1000);
        timeout_counter++;
        if(timeout_counter >= 20){
        ESP.restart();
        }
    }

    Serial.println("\nConnected to the WiFi network");
    Serial.print("Local ESP32 IP: ");
    Serial.println(WiFi.localIP());
    digitalWrite(ledPin, HIGH);
}

void setup() {

  Serial.begin(115200);
  Wire.begin();
  delay(1000);
  initWiFi();

  //display initialization message
  initialize();
  // //Start Temp/Humidity Sensor
  // bool success1 = dht.begin();
  // if (success1) {
  //   output.println("DHT Sensor init success");
  //   delay(1000);
  // }   else if (!dht.begin()) {
  //   output.println("Could not find a valid DHT sensor, check wiring!");
  // }

  // //Start external Temp Probe Sensor
  sensors.begin();
  // bool success2 = sensors.begin();
  // if (success2) {
  //   output.println("Temperature Probe Sensor init success");
  //   delay(1000);
  // }   else if (!sensors.begin()) {
  //   output.println("Could not find a valid Temperature Probe sensor, check wiring!");
  // }

  //initialize the bmp180 temperature sensor
  bool success = bmp.begin();
  if (success) {
    output.println("BMP180 init success");
    delay(1000);
  }   else if (!bmp.begin()) {
    output.println("Could not find a valid BMP180 sensor, check wiring!");
    delay(1000);
  }
  //output to Serial that setup completed
  Serial.println("Initialization Complete!");
 
  //this is mostly for Serial output
  output.println();
}

void loop() {
// Send new readings to database
  if (Firebase.ready() && (millis() - sendDataPrevMillis > timerDelay || sendDataPrevMillis == 0)){
    sendDataPrevMillis = millis();

    //Get current timestamp
    timestamp = getTime();
    Serial.print ("time: ");
    Serial.println (timestamp);

    parentPath= databasePath + "/" + String(timestamp);

    json.set(tempPath.c_str(), String(getTemp()));
    json.set(humPath.c_str(), String(getHumidity()));
    json.set(presPath.c_str(), String(getPress()/100.0F));
    json.set(timePath, String(timestamp));
    Serial.printf("Set json... %s\n", Firebase.RTDB.setJSON(&fbdo, parentPath.c_str(), &json) ? "ok" : fbdo.errorReason().c_str());
  }


unsigned long currentTime = millis();
    if(millis() - previousTime >= 5000){
        data.temp = getTemp();
        data.press = getPress();
        data.humidity = getHumidity();
        data.probe = tempProbe();

      previousTime = currentTime;

          data.temp;
          data.press;
          data.humidity;
          data.probe;

      Serial.println();
      }
} 

//get current temperature
float getTemp() {
  float readTemp;
  float t = bmp.readTemperature();
  //read temperature sensor
  if (bmp.readTemperature()) {
    Serial.print("Temperature:");
    output.print(bmp.readTemperature() / 1.032);
    output.println("*C");
  } else if (!bmp.readTemperature()){
    Serial.print("Temperature:");
    output.print(t);
    output.println("*C");
  }  else  {
    output.println ("Unav");
  }
  return readTemp;
}

// //get current pressure
double getPress() {
  double readPress;
  //read pressure sensor
  if (bmp.readPressure()) {
    Serial.print("Pressure:");
    output.print(bmp.readPressure() / 1000);
    output.println("KPA");
  } else  {
      output.println ("Press Unavail");
    }
  return readPress;
}

// get current temperature from temp probe
double tempProbe() {
  double result;
  if (!sensors.getTempCByIndex(0) ) {
    output.print("Probe: ");
    output.println("N/A");
  } else {
    output.print("Probe: ");
    sensors.requestTemperatures();
    output.print(sensors.getTempCByIndex(0) * .98);
    output.println("*C");
  }
  return result;
}

//get current humidity
float getHumidity() {
  float temp_hum_val[2] = {0};
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)

  if (!dht.readTempAndHumidity(temp_hum_val)) {
    output.print("Humidity: ");
    output.print(temp_hum_val[0] * 1.055);
    output.println("%");
  } else {
    output.println("Failed to get humidity value.");
  }
  return temp_hum_val[0];
}

// Function that gets current epoch time
unsigned long getTime() {
  time_t now;
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    //Serial.println("Failed to obtain time");
    return(0);
  }
  time(&now);
  return now;
}