<?php
// กำหนดข้อมูลสำหรับการเชื่อมต่อ MySQL
$host = "localhost";
/*
$username = "dufoon";
$password = "Tech0015";
*/
$username = "root";
$password = "";
$db = "dufoon";

error_reporting( error_reporting() & ~E_NOTICE );
global $connect; //เพิ่ม
$connect= mysqli_connect($host,$username,$password,$db) or die("Error: " . mysqli_error($connect));
if (!$connect) {
    die('Connect Error : (' . mysqli_connect_errno() . ')<hr/>'. mysqli_connect_error());
}
mysqli_query($connect, "SET NAMES 'utf8' ");

//=============== select ================== 
function select($table,$condition)
{
global $connect;		
$sql = "select * from $table $condition";
$dbquery = mysqli_query($connect,$sql);
$result= mysqli_fetch_array($dbquery);
return $result;
}

//=============== select  all ================== 
function selectall($table)
{
global $connect;		
$sql = "select * from $table ";
$dbquery = mysqli_query($connect,$sql);
$result= mysqli_fetch_array($dbquery);
return $result;
}


//=============== Numrow ================== 
function num_record($table,$condition)
{
global $connect;	
$sql = "select * from $table $condition";
$dbquery = mysqli_query($connect,$sql);
$num_rows = mysqli_num_rows($dbquery);
return $num_rows;
}

//=============== update ==================
function update($table,$command,$condition)
{
global $connect;		
$sql = "UPDATE $table SET $command $condition";
$result = mysqli_query($connect,$sql);
return $result;
}

$alert=0;
while(1){
    //ดึงข้อมูลค่า pm2.5
    $result=select("weather_location1","where 1 order by id DESC");
    $pm25=$result["weather1_pm25"];
    //ดึงค่าสถานะการแจ้งเตือน
    $result_alert=select("alert","where id='1'");
    $alert=$result_alert["alert"];
    echo "pm25=$pm25 alert=$alert \n";
    if($pm25>51 and $alert=='N' ){
        echo "alert \n";
        //shell_exec("LineTimeNotify.php 2>/dev/null >/dev/null &");
        include("LineTimeNotify.php"); 
        update("alert","alert='Y'","where id='1'");
        
    }
    if($pm25<=51 and $alert=='Y'){
        echo "normal \n";
        update("alert","alert='N'","where id='1'");
        
    }
    
    sleep(1);

}
?>
