<?php
//include_once '/var/www/html/www.clickhome.ro/inc/session.php';
$db = @mysql_connect("localhost", "iot", "Clickiotdbhome8219", TRUE, 128) or die ("Nu ma pot conecta la serverul mysql!");
mysql_select_db("clickhome", $db) or die ("Nu pot selecta baza de date!");

//$coeficient=0.25;
$ora=date('H:i:s');
$dayofweek = date('w');
if ($dayofweek==0) $dayofweek=7;
$q=mysql_query("SELECT * from centrala where day='$dayofweek'");
// citesc datale din tabela centrala
while ($c=mysql_fetch_array($q)){
    $coeficient=$c['delta'];
    $offline=0;
    $user=$c['user'];
    $senzor=$c['senzor'];
    $releu=$c['releu'];
    // verific ca toti senzorii sa fie ONLINE ca sa pot continua
    $q1=mysql_query("select valoare from getdevinfo where devid in ($senzor, $releu) and user='$user' and camp='LWT'");
    if (mysql_num_rows($q1)<2){
    	$offline=1;
    }
    else{
        while ($c1=mysql_fetch_array($q1)){
             if ($c1[0]=='Offline'){
                 $offline=1;
	     }	
        }
    }
    if (!$offline){
        echo "User:$user | senzor:$senzor | releu: $releu\n";
        $flag=$c['flag'];
        // verific sa nu fiu in modul manual
        if ($flag=='stop'){
            echo "Centrala e pe modul manual. Fara actiune!\n";
        }
        else{
    	    $topic_senzor=$user."-".$senzor;
    	    $topic_releu=$user."-".$releu;
    	    $realTemp=getRealTemp($topic_senzor);
    	    if (time()<strtotime($c['i2'])){    
                $configTemp=$c['t1'];
                }
            elseif (time()<strtotime($c['i3'])){
                $configTemp=$c['t2'];
            }
            elseif (time()<strtotime($c['i4'])){
                $configTemp=$c['t3'];
            }
            elseif (time()<strtotime($c['i5'])){
                $configTemp=$c['t4'];
            }	
            else {
    	        $configTemp=$c['t5'];
            }
            $min=$configTemp;
            $max=$configTemp+$coeficient;
            if (isset($realTemp)){
                if (($min<=$realTemp)&&($realTemp<=$max)){
    	            echo "Temperatura $realTemp este in intervalul $min - $max; Fara actiune!\n";
                }
                elseif (($realTemp<$min)&&($flag=="min")){
    	            echo "Temperatura $realTemp este sub pragul minim de $min insa centrala e deja pornita; Fara actiune!\n";  
                }
                elseif (($realTemp>$max)&&($flag=="max")){
    	            echo "Temperatura $realTemp este peste pragul maxim de $max insa centrala e deja oprita; Fara actiune!\n";
                }
                elseif (($realTemp>$max)&&($flag!="max")){
    	            echo "Temperatura $realTemp este peste pragul maxim de $max; Opresc centrala!\n";
    	            if (isSonoffRelay($user,$releu)){
    	                pub_mqtt_topic("cmnd/$topic_releu/POWER","OFF");
    	            }
    	            else {
    	                pub_mqtt_topic("cmnd/$topic_releu/ESP","OFF");
    	            }    
    	            @mysql_query("insert into log_centrala values (DEFAULT, '$user', '$senzor', '$releu', 'OFF', '$realTemp', '$configTemp',now(), 'AUTO')");
    	            @mysql_query("update centrala set flag='max' where user='$user' and senzor='$senzor' and releu='$releu'");    
                }
                elseif (($realTemp<$min)&&($flag!="min")){
    	            echo "Temperatura $realTemp este sub pragul minim de $min; Pornesc centrala!\n";
                    if (isSonoffRelay($user,$releu)){
                        pub_mqtt_topic("cmnd/$topic_releu/POWER","ON");
                    }
                    else {
       	            	pub_mqtt_topic("cmnd/$topic_releu/ESP","ON");
    	            }
		    @mysql_query("insert into log_centrala values (DEFAULT, '$user', '$senzor', '$releu', 'ON', '$realTemp', '$configTemp', now(), 'AUTO')");                                                    
    	            @mysql_query("update centrala set flag='min' where user='$user' and senzor='$senzor' and releu='$releu'");
                }
                else {
    	            echo "N-ar fi trebuit sa mai ajung aici!\n";
                }
            }	
            else {
                echo "N-am putut citi temperatura reala. Fara actiune!\n";
            }
    	}
    }
    else {
        echo "User:$user | senzor:$senzor | releu: $releu\n";
    	echo "Centrala offline. Fara actiune!\n";
    }
}
function isSonoffRelay ($u, $d){
    $q=mysql_query("SELECT tip from devices where user='$u' and devid='$d'");
    while ($c=mysql_fetch_array($q)){
        if ($c['tip']=='12'){
            return true;
        }
        else {
            return false;
        }
    }
}

function getRealTemp($topic){
    $mqtt=sub_mqtt_topic("cmnd/$topic/ESP","temp","stat/$topic/TEMP");
    $j=json_decode($mqtt,true);
    return $j['Temp'];
}

function sub_mqtt_topic($pub_channel,$pub_msg,$sub_channel){
    $timeout=3; //  daca nu primeste raspuns in 3 secunde sa renunte
    $data_initiala=time();
    $client = new \Mosquitto\Client(uniqid());
    $client->onMessage('message');
    $client->setCredentials('admin', 'Clickmqhome8219');
    $client->connect("localhost", 1883, 5);
    $client->setTlsCertificates('/etc/ssl/certs/ca-bundle.crt');
    $client->subscribe($sub_channel, 1);
    usleep(100000); //100 ms 
    $client->publish($pub_channel, $pub_msg);

    $GLOBALS['mqtt_message'] = '';
    while (true) {
        $client->loop();
        usleep(100000); //100 ms de asteptare sa apuce sa execute comenzile
        $data_acum = time();
        if (($data_acum - $data_initiala) > $timeout) break;
        if(!empty($GLOBALS['mqtt_message'])) break;
    }
    $client->disconnect();
    unset($client);
    return ($GLOBALS['mqtt_message']);
}

function message($message){
    $GLOBALS['mqtt_message'] =  $message->payload;
}

function pub_mqtt_topic($topic,$msg){
    $client = new \Mosquitto\Client("phpMQTT-pub-centrala");
    $client->setCredentials('admin', 'Clickmqhome8219');
    $client->connect("localhost", 1883, 5); //Change Accordingly. TCP/IP connection is supported by mqtt.
    $client->setTlsCertificates('/etc/ssl/certs/ca-bundle.crt');
    $client->publish($topic, $msg);
    $client->disconnect();
    unset($client);
}
?>
