//https://navody.arduino-shop.cz/navody-k-produktum/komunikace-po-i2c-mezi-arduino-deskami.html
//https://forum.arduino.cc/index.php?topic=521697.0
#include <Wire.h>
#include <MQUnifiedsensor.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <EEPROM.h>
#include "GravityTDS.h"
//####################################

//Definitions
#define placa "Arduino NANO"
#define Voltage_Resolution 5
#define pin A0 //Analog input 0 of your arduino
#define type "MQ-135" //MQ135
#define ADC_Bit_Resolution 10 // For arduino UNO/MEGA/NANO
#define RatioMQ135CleanAir 3.6//RS / R0 = 3.6 ppm  
//#define calibration_button 13 //Pin to calibrate your sensor
// DS18B20 teplomery
const int pinCidlaDS = 10; // nastavení čísla vstupního pinu
OneWire oneWireDS(pinCidlaDS);
DallasTemperature senzoryDS(&oneWireDS);

// promenne pro odesilani dat I2C cestou
const char Start = '&';
const char Begin = '$';
const char endChar = '#';
const char Complete = '*';
char buffer[8] = {0};
float buff;
int dataLoops = 0;

//Declare Sensor
MQUnifiedsensor MQ135(placa, Voltage_Resolution, ADC_Bit_Resolution, pin, type);
// definice Gravity TDS senzoru
#define TdsSensorPin A1 //definice kde je zapojeny datovy vodic
GravityTDS gravityTds;
float temperature = 25,tdsValue = 0;
// opravit teplotu vody podle aktualni

void setup() {
  Serial.begin(115200);
  Wire.begin(0x01);
  
}

void loop() {
Wire.onReceive(prijempokynu);
  
delay(200);
}

//########################################################
void prijempokynu(){
  char inChar;
  
  while(Wire.available() > 0)
  {
    inChar = Wire.read();  
    
    if (inChar == 'S')
    {
      DS18B20();
      delay(200);
      TDSprobe();
      delay(200);
      senzorMQ135();
            
    }
  }
}

//########################################################
void senzorMQ135(){

  //Set math model to calculate the PPM concentration and the value of constants
  MQ135.setRegressionMethod(1); //_PPM =  a*ratio^b
  //Remarks: Configure the pin of arduino as input.
  /************************************************************************************/ 
  MQ135.init();
  /* 
    //If the RL value is different from 10K please assign your RL value with the following method:
    MQ135.setRL(10);
  */
  /*****************************  MQ CAlibration ********************************************/ 
  // Explanation: 
  // In this routine the sensor will measure the resistance of the sensor supposing before was pre-heated
  // and now is on clean air (Calibration conditions), and it will setup R0 value.
  // We recomend execute this routine only on setup or on the laboratory and save on the eeprom of your arduino
  // This routine not need to execute to every restart, you can load your R0 if you know the value
  // Acknowledgements: https://jayconsystems.com/blog/understanding-a-gas-sensor
  float calcR0 = 0;
  for(int i = 1; i<=10; i ++)
  {
    MQ135.update(); // Update data, the arduino will be read the voltage on the analog pin
    calcR0 += MQ135.calibrate(RatioMQ135CleanAir);
    
  }
  MQ135.setR0(calcR0/10);
  MQ135.update(); // Update data, the arduino will be read the voltage on the analog pin

  MQ135.setA(605.18); MQ135.setB(-3.937); // Configurate the ecuation values to get CO concentration
  int CO = MQ135.readSensor(); // Sensor will read PPM concentration using the model and a and b values setted before or in the setup

  MQ135.setA(77.255); MQ135.setB(-3.18); // Configurate the ecuation values to get Alcohol concentration
  int Alkohol = MQ135.readSensor(); // Sensor will read PPM concentration using the model and a and b values setted before or in the setup

  MQ135.setA(110.47); MQ135.setB(-2.862); // Configurate the ecuation values to get CO2 concentration
  int CO2 = MQ135.readSensor(); // Sensor will read PPM concentration using the model and a and b values setted before or in the setup

  MQ135.setA(44.947); MQ135.setB(-3.445); // Configurate the ecuation values to get Tolueno concentration
  int Toluen = MQ135.readSensor(); // Sensor will read PPM concentration using the model and a and b values setted before or in the setup

  MQ135.setA(102.2 ); MQ135.setB(-2.473); // Configurate the ecuation values to get NH4 concentration
  int NH4 = MQ135.readSensor(); // Sensor will read PPM concentration using the model and a and b values setted before or in the setup

  MQ135.setA(34.668); MQ135.setB(-3.369); // Configurate the ecuation values to get Acetona concentration
  int Aceton = MQ135.readSensor(); // Sensor will read PPM concentration using the model and a and b values setted before or in the setup
//odeslani dat do NodeMCU
Wire.beginTransmission(0x02);
  Wire.write(Start);
  Wire.endTransmission();
  for (int y = 0; y < 8; y++) {
    // send recive variable cmd
    Wire.beginTransmission(0x02);
    Wire.write(Begin);
    Wire.endTransmission();
    // clears char array
    for (int i = 0; i < 8; i++) {
      buffer[i] = 0;
    }
    // convert variables to chars
    if (dataLoops == 0) {
      buff = CO;
      dtostrf(buff, 5, 2, buffer);
    }
    else if (dataLoops == 1) {
      buff = Alkohol;
      dtostrf(buff, 5, 2, buffer);
    }
    else if (dataLoops == 2) {
      buff = CO2;
      dtostrf(buff, 5, 2, buffer);
    }
    else if (dataLoops == 3) {
      buff = Toluen;
      dtostrf(buff, 5, 2, buffer);
    }
    else if (dataLoops == 4) {
      buff = NH4;
      dtostrf(buff, 5, 2, buffer);
    }
    else if (dataLoops == 5) {
      buff = Aceton;
      dtostrf(buff, 5, 2, buffer);
    }
    else if (dataLoops == 6) {
      buff = senzoryDS.getTempCByIndex(0);
      dtostrf(buff, 5, 2, buffer);
    }
    else if (dataLoops == 7) {
      buff = tdsValue;
      dtostrf(buff, 5, 2, buffer);
    }
    // send the char value
    for (int i = 0; i < 10; i++) {
    Wire.beginTransmission(0x02);
    Wire.write(buffer[i]);
    Wire.endTransmission();
    }
    // send stop reciving cmd
    Wire.beginTransmission(0x02);
    Wire.write(endChar);
    Wire.endTransmission();
    dataLoops++;
  }
  dataLoops = 0; // reset loops count
  // send transmission complete cmd
  Wire.beginTransmission(0x02);
  Wire.write(Complete);
  Wire.endTransmission();
}
//#########################################
void DS18B20(){
 senzoryDS.begin();// zapnutí komunikace knihovny s teplotním čidlem
 senzoryDS.requestTemperatures();// načtení informací ze všech připojených čidel na daném pinu
 Serial.print("Teplota cidla DS18B20: ");
  Serial.print(senzoryDS.getTempCByIndex(0));
  //int teplotaDS18B20 = senzoryDS.getTempCByIndex(0);
  Serial.println(" stupnu Celsia");
  
}
//############################################
void TDSprobe(){ //https://www.freshwater.cz/user/documents/upload/gallery/TDS_picture.png
  gravityTds.setPin(TdsSensorPin);
  gravityTds.setAref(5.0);  //reference voltage on ADC, default 5.0V on Arduino UNO
  gravityTds.setAdcRange(1024);  //1024 for 10bit ADC;4096 for 12bit ADC
  gravityTds.begin();  //initialization
  gravityTds.setTemperature(senzoryDS.getTempCByIndex(0));  // set the temperature and execute temperature compensation
  gravityTds.update();  //sample and calculate 
  tdsValue = gravityTds.getTdsValue();  // then get the value
  Serial.print(tdsValue,0);
  Serial.println("ppm");
 }
