#include "aero_doc.h"
#include "dht21.h"
#include "MainWindow.h"
#include "pid.h"
#include <ui_MainWindow.h>
#include <QMessageBox>
#include <QTimer>
#include <wiringPi.h>
#include <wiringSerial.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <typeinfo>

using namespace std;

//double map(double val, double low1, double high1, double low2, double high2);

static int a(0);

static int period_ms = 6000;
static int graph_maxvalues = 600;
static int graph_timerange = 60 * 75;
static int y_offset = 10;
static PID pid = PID(5, 100, 0, 3.12, 0.005155, 299.1);/// ( double dt, double max, double min, double Kp, double Kd, double Ki )
static sensor s1, s2;

static int fd;

static QQueue<QCPGraphData> q_intemp;
static QQueue<QCPGraphData> q_inhum;
static QQueue<QCPGraphData> q_outemp;
static QQueue<QCPGraphData> q_outhum;
static QQueue<QCPGraphData> q_ec;
static QQueue<QCPGraphData> q_ph;
static QQueue<QCPGraphData> q_soltemp;
static int pump_p,pump_s,fogger,fan1,fan2,ev_p1,ev_p2,ev_s1,ls_pmax, ls_pmin, ls_smax, temp_out = 0;
static double c_pump1, c_pump2, c_pump3,EC,pH,soltemp = 0;
static double s_hum, s_temp, s_EC, s_pH,s_mix,s_spray,pid_out = 0;
static int temp_reg, hum_reg, ec_reg, ph_reg, mix_state, spray_state = 0;
static QTimer *timer;
static QTimer *measurment;
static QTimer *t_regulation;
static QTimer *t_spray;
static QTimer *t_mix;

MainWindow::MainWindow(QWidget *parent)
	: QMainWindow(parent)
	, ui(new Ui::MainWindow)
{
	ui->setupUi(this);
	//connect(ui->doubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(valueUpdate()));
	//connect(ui->horizontalSlider, SIGNAL(valueChanged(int)), this, SLOT(valueUpdate1()));
	//connect(ui->verticalSlider, SIGNAL(valueChanged(int)), this, SLOT(valueUpdate2()));
	//connect(ui->dial, SIGNAL(valueChanged(int)), this, SLOT(valueUpdate3()));
	//connect(, SIGNAL(clicked()), this, SLOT(Page2()));
	connect(ui->start, SIGNAL(clicked()), this, SLOT(temp()));
	connect(ui->btn_systate_back, SIGNAL(clicked()), this, SLOT(menu()));
	connect(ui->btn_graph_back, SIGNAL(clicked()), this, SLOT(menu()));
	connect(ui->btn_sett_back, SIGNAL(clicked()), this, SLOT(menu()));
	connect(ui->btn_menu1, SIGNAL(clicked()), this, SLOT(menu1()));
	connect(ui->btn_menu2, SIGNAL(clicked()), this, SLOT(menu2()));
	connect(ui->btn_menu4, SIGNAL(clicked()), this, SLOT(menu4()));
	connect(ui->btn_exit, SIGNAL(clicked()), this, SLOT(exit()));
	
	connect(ui->btn_graph_temp, SIGNAL(clicked()), this, SLOT(graph_temp()));
	connect(ui->btn_graph_hum, SIGNAL(clicked()), this, SLOT(graph_hum()));
	connect(ui->btn_graph_ph, SIGNAL(clicked()), this, SLOT(graph_ph()));
	connect(ui->btn_graph_ec, SIGNAL(clicked()), this, SLOT(graph_ec()));
	connect(ui->btn_graph_soltemp, SIGNAL(clicked()), this, SLOT(graph_soltemp()));
	//connect(ui->btn_menu7, SIGNAL(clicked()), this, SLOT(menu7()));

	connect(ui->btn_mix, SIGNAL(clicked()), this, SLOT(click_mix()));
	connect(ui->btn_spray, SIGNAL(clicked()), this, SLOT(click_spray()));
	connect(ui->btn_ec, SIGNAL(clicked()), this, SLOT(click_ec()));
	connect(ui->btn_ph, SIGNAL(clicked()), this, SLOT(click_ph()));
	connect(ui->btn_temp, SIGNAL(clicked()), this, SLOT(click_temp()));
	connect(ui->btn_hum, SIGNAL(clicked()), this, SLOT(click_hum()));
	connect(ui->btn_heater, SIGNAL(clicked()), this, SLOT(click_heater()));
	connect(ui->btn_fogger, SIGNAL(clicked()), this, SLOT(click_fogger()));
	connect(ui->btn_fan, SIGNAL(clicked()), this, SLOT(click_fan()));
	connect(ui->btn_pHcal, SIGNAL(clicked()), this, SLOT(click_pHcal()));
	connect(ui->btn_ECcal, SIGNAL(clicked()), this, SLOT(click_ECcal()));
	connect(ui->doubleSpinBox_ph, SIGNAL(valueChanged(double)), this, SLOT(vu_ph()));
	connect(ui->doubleSpinBox_ec, SIGNAL(valueChanged(double)), this, SLOT(vu_ec()));
	connect(ui->doubleSpinBox_temp, SIGNAL(valueChanged(double)), this, SLOT(vu_temp()));
	connect(ui->doubleSpinBox_hum, SIGNAL(valueChanged(double)), this, SLOT(vu_hum()));
	connect(ui->doubleSpinBox_phon, SIGNAL(valueChanged(double)), this, SLOT(vu_phon()));
	connect(ui->doubleSpinBox_econ, SIGNAL(valueChanged(double)), this, SLOT(vu_econ()));
	connect(ui->doubleSpinBox_settle, SIGNAL(valueChanged(double)), this, SLOT(vu_settle()));
	
	
	timer = new QTimer(this);
	t_regulation = new QTimer(this);
	t_mix = new QTimer(this);
	t_spray = new QTimer(this);
	measurment = new QTimer(this);
	connect(t_regulation, SIGNAL(timeout()), this, SLOT(temp_regulation()));
	connect(t_mix, SIGNAL(timeout()), this, SLOT(solution_mix()));
	connect(t_spray, SIGNAL(timeout()), this, SLOT(solution_spray()));
	connect(measurment, SIGNAL(timeout()), this, SLOT(SensorRead()));
	QTimer::singleShot(0, this, SLOT(init()));
}

MainWindow::~MainWindow()
{
	pwmWrite(PWM, 0);
	delete ui;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///User functions
double mapper(double val, double low1, double high1, double low2, double high2) {
	return low2 + (val - low1) * (high2 - low2) / (high1 - low1);
}

int  serialGets(int fd, int maxlen, char * str) {
	int i = 0;
	int c = -1;
	if (maxlen < 0) maxlen = 0;
	do { 
		if (i >= maxlen) {
			str[maxlen] = '\0';
			i = maxlen;
			c = '\0';
			break;
		}
		c = serialDataAvail(fd);
		if (c != -1) {
			c = serialGetchar(fd);
			if (c == -1)  {break;}         
			if (c == EOF)  {c = '\0'; break;} 
			else str[i++] = c;
			if (c == '\n')  {str[i] = '\0'; break;}
		}
	} while ((c != '\0') && (c != -1) && (c != '\n')  && (c != EOF)) ; 
	if (c == -1) return c;
	else return i;
}

int digital_toggle(int pin, int s = -1)
{
	if (s == -1)
	{
		digitalWrite(pin, digitalRead(pin) == HIGH ? LOW : HIGH);
	}
	else if (s == 0)
	{
		digitalWrite(pin, HIGH);      // RELAY IS OFF
	}
	else if (s == 1)
	{
		digitalWrite(pin, LOW);    //RELAY IS ON
	}
	return digitalRead(pin); 
}

///InOut functions
void water_fill()
{
	int count = 0;
	while (digitalRead(LS3) == 1)
	{
		digital_toggle(RL5,1);
		delay(1000);
		count++;
		if (count >= 60)
			break;
	}
	digital_toggle(RL5, 0);
}

int solution_fill()
{
	int count = 0;
	if (digitalRead(LS2))
	{
		if (digitalRead(LS1) != 1)
		{
			return -1; /// Error
		}
		while (digitalRead(LS1) == 1)
		{
			digital_toggle(RL2, 1);
			delay(1000);
			count++;
			if (count >= 60)
				break;
		}
		digital_toggle(RL2, 0);
		return 0;
	}
}




void MainWindow::solution_mix(unsigned int on_time=120) /// time in seconds
{
	mix_state = 1;
	digital_toggle(RL4, 1);
	delay(1000);
	digital_toggle(RL8, 1);
	delay(on_time * 1000);
	mix_state = 0;
	if (spray_state = 1){
		digital_toggle(RL4, 0);
	}
	else {
		digital_toggle(RL4, 0);
		delay(500);
		digital_toggle(RL8, 0);

	}
}

void MainWindow::solution_spray(unsigned int on_time = 5)
{
	spray_state = 1;
	digital_toggle(RL3, 1);
	delay(1000);
	digital_toggle(RL8, 1);
	delay(on_time * 1000);
	spray_state = 0;
	if (mix_state = 1) {
		digital_toggle(RL3, 0);
	}
	else {
		digital_toggle(RL3, 0);
		delay(500);
		digital_toggle(RL8, 0);

	}
}

void MainWindow::temp_regulation()
{
	pid_out = pid.calculate(s_temp, dht21(4).temp);
	double val = mapper(pid_out, 0, 100, 0, 1024);
	pwmWrite(PWM, val);
}

void hum_regulation(double set_hum,double hum, double hys = 5)
{
	if (set_hum > 99)
		set_hum = 99;
	else if (set_hum < 1)
		set_hum = 1;
	if (hys < 0 || hys > 30)
		hys = 5;
	if (set_hum + hys > 99)
		set_hum = 99 - hys;
	else if (set_hum - hys < 1)
		set_hum = 1 + hys;
	if (hum < (set_hum - hys)) { digital_toggle(RL6, 1); digital_toggle(RL1, 1);}
	if (hum > (set_hum + hys)) { digital_toggle(RL6, 0); digital_toggle(RL1, 0);}
}

void setEC(double set_ec)
{
	string msg = "EC;" + to_string(set_ec)+"\n";
	serialPuts(fd,msg.c_str());
}

void EC_on(unsigned int ec_on = 2000)///default 2 s  
{
	string msg = "ECon;" + to_string(ec_on) + "\n";
	serialPuts(fd, msg.c_str());
}

void EC_settle(unsigned int settle = 20000) ///default 20 s to settle
{
	string msg = "ECsettle;" + to_string(settle) + "\n";
	serialPuts(fd, msg.c_str());
}

void EC_cal(double cal= 1.413) 
{
	string msg = "ECcal;" + to_string(cal) + "\n";
	serialPuts(fd, msg.c_str());
}

void setpH(double set_pH)
{
	string msg = "pH;" + to_string(set_pH) + "\n";
	serialPuts(fd, msg.c_str());
}

void pH_on(unsigned int pH_on = 2000)///default 2 s  
{
	string msg = "pHon;" + to_string(pH_on) + "\n";
	serialPuts(fd, msg.c_str());
}

void pH_settle(unsigned int settle = 20000) ///default 20 s to settle
{
	string msg = "pHsettle;" + to_string(settle) + "\n";
	serialPuts(fd, msg.c_str());
}

void pH_cal(double cal = 4.01) 
{
	string msg = "pHcal;" + to_string(cal) + "\n";
	serialPuts(fd, msg.c_str());
}

void MainWindow::Automatic()
{
	s_mix = 1;
	s_spray = 1;
	hum_reg = 1;
	temp_reg = 1;
	s_temp = 20;
	s_hum = 95;
	s_EC = 1.1;
	s_pH = 6;

	water_fill();
	solution_fill();

	if(s_mix==1)
	{
		if(!t_mix->isActive()){
		t_mix->start();
		t_mix->setInterval(1000*60*20);
		}
	}
	else {
		t_mix->stop();
	}

	if (s_spray == 1)
	{
		if (!t_spray->isActive()) {
			t_spray->start();
			t_spray->setInterval(1000 * 60 * 5);
		}
	} else {
		t_spray->stop();
	}

	if (hum_reg == 1)
	{
		if (q_inhum.size()>1){
		hum_regulation(90, q_inhum.last().value);
		}
	}
	else
	{
		digital_toggle(RL6, 0); digital_toggle(RL1, 0);
	}

	if (temp_reg == 1)
	{
		if (!t_regulation->isActive()) {
			digital_toggle(RL2, 1);
			t_regulation->start();
			t_regulation->setInterval(1000 * 5);
		}
	}
	else 
	{
		t_regulation->stop();
		pwmWrite(PWM, 0);
		digital_toggle(RL2, 0);
	}
}

void MainWindow::Manual()
{
	water_fill();
	solution_fill();

	if (s_mix == 1)
	{
		if (!t_mix->isActive()) {
			t_mix->start();
			t_mix->setInterval(1000 * 60 * 20);
		}
	}
	else {
		t_mix->stop();
	}

	if (s_spray == 1)
	{
		if (!t_spray->isActive()) {
			t_spray->start();
			t_spray->setInterval(1000 * 60 * 4);
		}
	}
	else {
		t_spray->stop();
	}

	if (hum_reg == 1)
	{
		if (q_inhum.size() > 1) {
			hum_regulation(s_hum, q_inhum.last().value);
		}
	}
	else
	{
		digital_toggle(RL6, 0); digital_toggle(RL1, 0);
	}

	if (temp_reg == 1)
	{
		if (!t_regulation->isActive()) {
			digital_toggle(RL2, 1);
			t_regulation->start();
			t_regulation->setInterval(1000 * 5);
		}
	}
	else
	{
		t_regulation->stop();
		pwmWrite(PWM, 0);
		digital_toggle(RL2, 0);
	}
}

void MainWindow::Maintenance()
{
	hum_reg = 0;
	temp_reg = 0;
	s_spray= 0;
	s_mix= 0;
	measurment->stop();
	t_regulation->stop();
	t_spray->stop();
	t_mix->stop();
	digitalWrite(RL1, HIGH);
	digitalWrite(RL2, HIGH);
	digitalWrite(RL3, HIGH);
	digitalWrite(RL4, HIGH);
	digitalWrite(RL5, HIGH);
	digitalWrite(RL6, HIGH);
	digitalWrite(RL7, HIGH);
	digitalWrite(RL8, HIGH);
	pwmWrite(PWM, 0);
}

void MainWindow::State() {
	if (ui->radioButton->isChecked())
	{
		if(!measurment->isActive()){
		measurment->start();
		measurment->setInterval(1000 * 15);
		}
		ui->groupBox_2->setEnabled(false);
		Automatic();
		QTimer::singleShot(20, this, SLOT(State()));
	}
	else if (ui->radioButton_2->isChecked())
	{
		if (!measurment->isActive()) {
			measurment->start();
			measurment->setInterval(1000 * 15);
		}
		ui->groupBox_2->setEnabled(true);
		Manual();
		QTimer::singleShot(20, this, SLOT(State()));
	}
	else if (ui->radioButton_3->isChecked())
	{
		ui->groupBox_2->setEnabled(false);
		Maintenance();
		QTimer::singleShot(20, this, SLOT(State()));
	}
}

void MainWindow::init()
{
	if ((fd = serialOpen("/dev/ttyUSB0", 9600)) < 0)
	{
		fprintf(stderr, "Unable to open serial device: %s\n", strerror(errno));
	}
	
	////DATA
	/*
	char file_path[] = "settings.txt";
	fstream fs;
	fs.open(file_path, std::fstream::in | std::fstream::out | std::fstream::app);
		if(!fs) {
			fs.open(file_path, fstream::in | fstream::out | fstream::trunc);
		} 
	fs << "ON";
	fs.close();
	*/
	////GRAPHS
	QSharedPointer<QCPAxisTickerDateTime> dateTicker(new QCPAxisTickerDateTime);
	ui->widget->setLocale(QLocale(QLocale::Czech, QLocale::CzechRepublic));
	ui->widget->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectAxes |QCP::iSelectLegend);
	ui->widget->addGraph();
	ui->widget->graph(0)->setName(QLatin1String("Teplota v systému"));
	ui->widget->graph(0)->setPen(QPen(QColor(255, 110, 40)));
	ui->widget->addGraph();
	ui->widget->graph(1)->setName(QLatin1String("Venkovní teplota"));
	ui->widget->graph(1)->setPen(QPen(QColor(40, 110, 255)));
	dateTicker->setDateTimeFormat("dd.mm\nhh:mm:ss");
	ui->widget->xAxis->setTicker(dateTicker);
	ui->widget->yAxis->setLabel(QLatin1String("Teplota [°C]"));
	ui->widget->legend->setVisible(true);
	ui->widget->yAxis->setRange(0, 40);
	
	ui->widget_3->setLocale(QLocale(QLocale::Czech, QLocale::CzechRepublic));
	ui->widget_3->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectAxes | QCP::iSelectLegend);
	ui->widget_3->addGraph();
	ui->widget_3->graph(0)->setName(QLatin1String("Vlhkost v systému"));
	ui->widget_3->graph(0)->setPen(QPen(QColor(255, 110, 40)));
	ui->widget_3->addGraph();
	ui->widget_3->graph(1)->setName(QLatin1String("Venkovní vhlkost"));
	ui->widget_3->graph(1)->setPen(QPen(QColor(40, 110, 255)));
	ui->widget_3->xAxis->setTicker(dateTicker);
	ui->widget_3->yAxis->setLabel("Vlhkost [%]");
	ui->widget_3->legend->setVisible(true);
	ui->widget_3->yAxis->setRange(0, 100);
	
	ui->widget_5->setLocale(QLocale(QLocale::Czech, QLocale::CzechRepublic));
	ui->widget_5->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectAxes | QCP::iSelectLegend);
	ui->widget_5->addGraph();
	ui->widget_5->graph(0)->setName(QLatin1String("pH"));
	ui->widget_5->graph(0)->setPen(QPen(QColor(255, 110, 40)));
	ui->widget_5->xAxis->setTicker(dateTicker);
	ui->widget_5->yAxis->setLabel(QLatin1String("pH"));
	ui->widget_5->yAxis->setRange(0, 8);
	
	ui->widget_7->setLocale(QLocale(QLocale::Czech, QLocale::CzechRepublic));
	ui->widget_7->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectAxes | QCP::iSelectLegend);
	ui->widget_7->addGraph();
	ui->widget_7->graph(0)->setName(QLatin1String("EC"));
	ui->widget_7->graph(0)->setPen(QPen(QColor(255, 110, 40)));
	ui->widget_7->xAxis->setTicker(dateTicker);
	ui->widget_7->yAxis->setLabel(QLatin1String("EC [mS/cm]"));
	ui->widget_7->yAxis->setRange(0, 3);
	
	ui->widget_9->setLocale(QLocale(QLocale::Czech, QLocale::CzechRepublic));
	ui->widget_9->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectAxes | QCP::iSelectLegend);
	ui->widget_9->addGraph();
	ui->widget_9->graph(0)->setName(QLatin1String("Teplota roztoku"));
	ui->widget_9->graph(0)->setPen(QPen(QColor(255, 110, 40)));
	ui->widget_9->xAxis->setTicker(dateTicker);
	ui->widget_9->yAxis->setLabel(QLatin1String("Teplota [°C]"));
	ui->widget_9->yAxis->setRange(0, 40);

  //////Init values
	temp_reg = 1;
	hum_reg = 1;
	s_temp = 20;
	s_hum = 95;
	s_EC = 1.1;
	s_pH = 6;
	ph_reg = 1;
	ec_reg = 1;
	string msg = "pHstate;" + to_string(1) + "\n";
	serialPuts(fd, msg.c_str());
	msg = "ECstate;" + to_string(1) + "\n";
	serialPuts(fd, msg.c_str());
	ui->doubleSpinBox_ph->setValue(s_pH);
    ui->doubleSpinBox_ec->setValue(s_EC);		
    ui->doubleSpinBox_temp->setValue(s_temp);
	ui->doubleSpinBox_hum->setValue(s_hum);
	ui->doubleSpinBox_phon->setValue(1);
	ui->doubleSpinBox_econ->setValue(1);
	ui->doubleSpinBox_settle->setValue(20);
	QTimer::singleShot(10, this, SLOT(State()));

}

void MainWindow::SensorRead()
{
	////Humidity and temperature readings
	int read_i = 0;
	int read_i2 = 0;
	double time_stamp = QDateTime::currentDateTime().toTime_t();	
	s1 = dht21(4);
	while ((s1.temp < 1) && (s1.hum < 1)) {
		s1 = dht21(4);
		read_i++;
		delay(400);
		if (read_i >= 5)
			break;
	}
	delay(1000);
	s2 = dht21(15);
	while ((s2.temp < 1) && (s2.hum < 1)) {
		s2 = dht21(15);
		read_i2++;
		delay(400);
		if (read_i2 >= 5)
			break;
	}
	
	//Water level sensors readings
	ls_pmax = digitalRead(LS1);
	ls_pmin = digitalRead(LS2);
	ls_smax = digitalRead(LS3);

	///Reading data from pH&EC regulator
	char msg[] = "hodnoty";
	serialPuts(fd, msg);
	char buff[200];
	char dumm;
	serialGets(fd, serialDataAvail(fd), buff);
	string data(buff);
	istringstream is(data);
	is >> pH >> dumm >> EC >> dumm >> soltemp >> dumm >> c_pump1 >> dumm >> c_pump2 >> dumm >> c_pump3 >> dumm ;
	///Saving variables
	q_intemp.enqueue(QCPGraphData(time_stamp, s1.temp));
	q_inhum.enqueue(QCPGraphData(time_stamp, s1.hum));
	q_outemp.enqueue(QCPGraphData(time_stamp, s2.temp));
	q_outhum.enqueue(QCPGraphData(time_stamp, s2.hum));
	q_ph.enqueue(QCPGraphData(time_stamp, pH));
	q_ec.enqueue(QCPGraphData(time_stamp, EC));
	q_soltemp.enqueue(QCPGraphData(time_stamp, soltemp));
	///Show variables
	QTimer::singleShot(10,this, SLOT(updateValues()));
}

void MainWindow::updateValues()
{		
	static int count = 0;

	///Saving data to txt
	QDateTime qdate;
	qdate.setTime_t(q_intemp.last().key);
		string date;
		date = to_string(qdate.date().year()) + "y_" + to_string(qdate.date().month()) + "m_" + to_string(qdate.date().day()) + "d"; 
		string file_path = date + ".txt";
		fstream fs;
		fs.open(file_path, std::fstream::in | std::fstream::out | std::fstream::app);
		if (!fs) {
			fs.open(file_path, fstream::in | fstream::out | fstream::trunc);
			fs << "Date;Time;InTemperature;InHumidity;OutTemperature;OutHumidity;pH;EC;SolutionTemperature;LS1;LS2;LS3;C1;C2;C3" << endl;
		} 
		fs << qdate.date().day() << "." << qdate.date().month() << "." << qdate.date().year() <<  ";"
		   << qdate.time().hour() << ":" << qdate.time().minute() << ":" << qdate.time().second()  << ";"
		   << q_intemp.last().value << ";" 
		   << q_inhum.last().value  << ";" 
		   << q_outemp.last().value << ";" 
		   << q_outhum.last().value << ";" 
			<< q_ph.last().value << ";" 
			<< q_ec.last().value << ";" 
			<< q_soltemp.last().value << ";" 
			<<ls_pmax << ";" 
			<< ls_pmin << ";"
			<< ls_smax << ";"
			<< c_pump1 << ";"
			<< c_pump2 << ";"
			<< c_pump3 << ";" << endl;
		fs.close();
		count = 0;
	
	///Show data in lcd boxes	
	ui->lcdnumber_outemp->display(q_outemp.last().value);
	ui->lcdNumber_outhum->display(q_outhum.last().value);
	ui->lcdNumber_intemp->display(q_intemp.last().value);
	ui->lcdNumber_inhum->display(q_inhum.last().value);
	ui->lcdNumber_ec->display(q_ec.last().value);
	ui->lcdNumber_ph->display(q_ph.last().value);
	ui->lcdNumber_soltemp->display(q_soltemp.last().value);

	///Update systate
	if (!digitalRead(RL8)) { ///PUMP
		ui->label_65->setText("ON");
	} 
	else {
		ui->label_65->setText("OFF");
	}

	if (!digitalRead(RL3)) { ///EV2
		ui->label_66->setText("ON");
	}
	else {
		ui->label_66->setText("OFF");
	}

	if (!digitalRead(RL4)) { ///EV3
		ui->label_69->setText("ON");
	}
	else {
		ui->label_69->setText("OFF");
	}

	if (digitalRead(LS1)) {
		ui->label_71->setText("ON");
	}
	else {
		ui->label_71->setText("OFF");
	}

	if (digitalRead(LS2)) {
		ui->label_73->setText("ON");
	}
	else {
		ui->label_73->setText("OFF");
	}

	if (!digitalRead(RL7)) {
		ui->label_19->setText("ON");
	}
	else {
		ui->label_19->setText("OFF");
	}

	if (!digitalRead(RL5)) {
		ui->label_21->setText("ON");
	}
	else {
		ui->label_21->setText("OFF");
	}

	if (digitalRead(LS3)) {
		ui->label_23->setText("ON");
	}
	else {
		ui->label_23->setText("OFF");
	}

	if (ph_reg) {
		ui->label_76->setText("ON");
	}
	else {
		ui->label_76->setText("OFF");
	}

	if (ec_reg) {
		ui->label_74->setText("ON");
	}
	else {
		ui->label_74->setText("OFF");
	}

	ui->label_79->setText(QString("%1").arg(c_pump1));
	ui->label_81->setText( QString("%1").arg(c_pump2));
	ui->label_83->setText( QString("%1").arg(c_pump3));
	ui->label_95->setText( QString("%1").arg(s_pH));
	ui->label_62->setText( QString("%1").arg(s_EC));
	ui->label_93->setText( QString("%1").arg(pH));
	ui->label_63->setText( QString("%1").arg(EC));
	ui->label_94->setText( QString("%1").arg(soltemp));

	if (temp_reg) {
		ui->label_27->setText("ON");
	}
	else {
		ui->label_27->setText("OFF");
	}

	if (hum_reg) {
		ui->label_29->setText("ON");
	}
	else {
		ui->label_29->setText("OFF");
	}

	if (!digitalRead(RL1)) {
		ui->label_34->setText("ON");
	}
	else {
		ui->label_34->setText("OFF");
	}

	if (!digitalRead(RL2)) {
		ui->label_36->setText("ON");
	}
	else {
		ui->label_36->setText("OFF");
	}

	if (!digitalRead(RL6)) {
		ui->label_38->setText("ON");
	}
	else {
		ui->label_38->setText("OFF");
	}
	ui->label_41->setText( QString("%1").arg(pid_out));
	ui->label_45->setText( QString("%1").arg(s_temp));
	ui->label_48->setText( QString("%1").arg(s_hum));
	ui->label_60->setText( QString("%1").arg(q_intemp.last().value));
	ui->label_56->setText( QString("%1").arg(q_inhum.last().value));
	ui->label_54->setText(QString("%1").arg(q_outemp.last().value));
	ui->label_50->setText( QString("%1").arg(q_intemp.last().value));
	///Continuos measurment
	if (q_intemp.size() >= graph_maxvalues){
		q_intemp.pop_front();
	}
	if (q_inhum.size() >= graph_maxvalues){
		q_inhum.pop_front();
	}
	if (q_outemp.size() >= graph_maxvalues){
		q_outemp.pop_front();
	}
	if (q_outhum.size() >= graph_maxvalues){
		q_outhum.pop_front();
	}	
	if (q_ph.size() >= graph_maxvalues){
		q_ph.pop_front();	
	}	
	if (q_ec.size() >= graph_maxvalues){
		q_ec.pop_front();	
	}	
	if (q_soltemp.size() >= graph_maxvalues){
		q_soltemp.pop_front();				
	}
	///Temperature graphs
	ui->widget->graph(0)->data()->set(q_intemp.toVector());
	ui->widget->graph(1)->data()->set(q_outemp.toVector());
	ui->widget->xAxis->setRange(q_intemp.toVector()[0].key, q_intemp.toVector()[0].key + graph_timerange);
	ui->widget->yAxis->setRange(12,28);
	ui->widget->replot();
	///Humidity graphs
	ui->widget_3->graph(0)->data()->set(q_inhum.toVector());
	ui->widget_3->graph(1)->data()->set(q_outhum.toVector());
	ui->widget_3->xAxis->setRange(q_inhum.toVector()[0].key, q_inhum.toVector()[0].key + graph_timerange);
	ui->widget_3->yAxis->setRange(0, 100);
	ui->widget_3->replot();
	///pH
    ui->widget_5->graph(0)->data()->set(q_ph.toVector());
	ui->widget_5->xAxis->setRange(q_ph.toVector()[0].key, q_ph.toVector()[0].key + graph_timerange);
	ui->widget_5->yAxis->setRange(0, 8);
	ui->widget_5->replot();
	///EC
	ui->widget_7->graph(0)->data()->set(q_ec.toVector());
	ui->widget_7->xAxis->setRange(q_ec.toVector()[0].key, q_ec.toVector()[0].key + graph_timerange);
	ui->widget_7->yAxis->setRange(0, 3);
	ui->widget_7->replot();
	///Soltemp
    ui->widget_9->graph(0)->data()->set(q_soltemp.toVector());
	ui->widget_9->xAxis->setRange(q_soltemp.toVector()[0].key, q_soltemp.toVector()[0].key + graph_timerange);
	ui->widget_9->yAxis->setRange(5, 30);
	ui->widget_9->replot();


}

///Events handle
void MainWindow::menu()
{
	ui->stackedWidget->setCurrentIndex(0);
}
void MainWindow::menu1()
{
	ui->stackedWidget->setCurrentIndex(1);
}

void MainWindow::menu2()
{
	ui->stackedWidget->setCurrentIndex(2);
}

void MainWindow::menu4()
{
	ui->stackedWidget->setCurrentIndex(4);
}

void MainWindow::click_mix() {
	if (s_mix == 1) {
		s_mix = 0;
		ui->btn_mix->setText("OFF");
	}
	else {
		s_mix = 1;
		ui->btn_mix->setText("ON");
	}
}
void MainWindow::click_spray() {
	if (s_spray == 1) {
		s_spray = 0;
		ui->btn_spray->setText("OFF");
	}
	else {
		s_spray = 1;
		ui->btn_spray->setText("ON");
	}
}
void MainWindow::click_ec() {
	if (ec_reg == 1) {
		string msg = "ECstate;" + to_string(0) + "\n";
		serialPuts(fd, msg.c_str());
		ec_reg = 0;
		ui->btn_ec->setText("OFF");
	}
	else {
		string msg = "ECstate;" + to_string(1) + "\n";
		serialPuts(fd, msg.c_str());
		ec_reg = 1;
		ui->btn_ec->setText("ON");
	}
}
void MainWindow::click_ph() {
	if (ph_reg == 1) {
		string msg = "pHstate;" + to_string(0) + "\n";
		serialPuts(fd, msg.c_str());
		ph_reg = 0;
		ui->btn_ph->setText("OFF");
	}
	else {
		string msg = "pHstate;" + to_string(1) + "\n";
		serialPuts(fd, msg.c_str());
		ph_reg = 1;
		ui->btn_ph->setText("ON");
	}
}

void MainWindow::click_pHcal() {
	pH_cal();
}

void MainWindow::click_ECcal() {
	EC_cal();
}


void MainWindow::click_temp() {
	if (temp_reg == 1) {
		temp_reg = 0;
		ui->btn_temp->setText("OFF");
	}
	else {
		temp_reg = 1;
		ui->btn_temp->setText("ON");
	}
}
void MainWindow::click_hum() {
	if (hum_reg == 1) {
		hum_reg = 0;
		ui->btn_hum->setText("OFF");
	}
	else {
		hum_reg = 1;
		ui->btn_hum->setText("ON");
	}
}
void MainWindow::click_heater() {
	static int prev;
	if (prev == 1) {
		prev = 0;
		digital_toggle(RL2, 0);
		pwmWrite(PWM, 0);
		ui->btn_heater->setText("OFF");
	}
	else {
		digital_toggle(RL2, 1);
		pwmWrite(PWM, 1024);
		prev = 1;
		ui->btn_heater->setText("ON");
	}

}
void MainWindow::click_fogger() {
	static int prev;
	if (prev == 1) {
		prev = 0;
		digital_toggle(RL1, 0);
		digital_toggle(RL6, 0);
		ui->btn_fogger->setText("OFF");
	}
	else {
		digital_toggle(RL1, 1);
		digital_toggle(RL6, 1);
		prev = 1;
		ui->btn_fogger->setText("ON");
	}
}

void MainWindow::click_fan() {
	static int prev;
	if (prev == 1) {
		prev = 0;
		digital_toggle(RL1, 0);
		digital_toggle(RL2, 0);
		ui->btn_fan->setText("OFF");
	}
	else {
		digital_toggle(RL1, 1);
		digital_toggle(RL2, 1);
		prev = 1;
		ui->btn_fan->setText("ON");
	}
}

void MainWindow::vu_ph() {
	s_pH=ui->doubleSpinBox_ph->value();
	setpH(ui->doubleSpinBox_ph->value());
}
void MainWindow::vu_ec() {
	s_EC = ui->doubleSpinBox_ph->value();
	setEC(ui->doubleSpinBox_ec->value());
}
void MainWindow::vu_temp() {
	s_temp = ui->doubleSpinBox_temp->value();
}
void MainWindow::vu_hum() {
	s_hum = ui->doubleSpinBox_hum->value();
}
void MainWindow::vu_phon() {
	pH_on(ui->doubleSpinBox_phon->value()*1000);
}
void MainWindow::vu_econ() {
	EC_on(ui->doubleSpinBox_econ->value()*1000);
}
void MainWindow::vu_settle() {
	pH_settle(ui->doubleSpinBox_settle->value() * 1000);
	EC_settle(ui->doubleSpinBox_settle->value() * 1000);
}

void MainWindow::exit()
{
	QApplication::quit();
}

void MainWindow::graph_temp()
{
	ui->stackedWidget_2->setCurrentIndex(0);
}

void MainWindow::graph_hum()
{
	ui->stackedWidget_2->setCurrentIndex(1);
}
void MainWindow::graph_ph()
{
	ui->stackedWidget_2->setCurrentIndex(2);
}
void MainWindow::graph_ec()
{
	ui->stackedWidget_2->setCurrentIndex(3);
}
void MainWindow::graph_soltemp()
{
	ui->stackedWidget_2->setCurrentIndex(4);
}


/*
void MainWindow::menu7()
{
	ui->stackedWidget->setCurrentIndex(7);
}

void MainWindow::menu8()
{
	ui->stackedWidget->setCurrentIndex(8);
}
*/



void MainWindow::valueUpdate1()
{
	//int outputblink = map(ui->horizontalSlider->value(), 0, 100, 4000, 10);
	//ui->progressBar->setValue(ui->horizontalSlider->value());
	//timer->setInterval(outputblink);
}

void MainWindow::valueUpdate2()
{
	//int outputblink = map(ui->verticalSlider->value(), 0, 100, 4000, 10);
	//ui->progressBar->setValue(ui->verticalSlider->value());
	//timer->setInterval(outputblink);
}

void MainWindow::valueUpdate3()
{
	//int outputblink = map(ui->dial->value(), 0, 100, 4000, 10);
	//ui->progressBar->setValue(ui->dial->value());
	//timer->setInterval(outputblink);
}