<?php
require_once "../Parameters.php";
require_once "../auth/func.php";
require_once '../class.OPC_Soft.inc';

//設定資料庫連線資訊
$dsn = sprintf("sqlsrv:Server=%s; Database=%s;", $DataSource, $DataBase_Alarm);
$pdo_mssql = new PDO($dsn, $UserID, $Password);

//撈取設定為自動的設備清單
$sql = sprintf(
    "SELECT 
        _dl.id
        ,_dl.schedule_start_time
        ,_dl.schedule_end_time
        ,_dil.soft_alarm_tag 
    FROM 
        [%s].[dbo].[device_list] AS _dl
        LEFT JOIN [%s].[dbo].[device_item_list] AS _dil ON _dil.device_id = _dl.id 
    WHERE
        _dl.schedule_mode = 1
    ",
    $DataBase_Alarm,
    $DataBase_Alarm
);
$sth = $pdo_mssql->prepare($sql);
$sth->execute();
$a_store_data = $sth->fetchAll(PDO::FETCH_ASSOC);
$arr = [];
$now_time = new DateTime(date("H:i:s"));
foreach ($a_store_data as $k => $v) {
    //當時間欄位都有設定、點位都有設定時才執行自動化
    if (
        !empty(trim($v["schedule_start_time"])) &&
        !empty(trim($v["schedule_end_time"])) &&
        !empty(trim($v["soft_alarm_tag"]))
    ) {
        $schedule_start_time = new DateTime($v["schedule_start_time"]);
        $schedule_end_time = new DateTime($v["schedule_end_time"]);
        if ($schedule_start_time > $schedule_end_time) {
            //當在時間區間內 將警報點全部設為開啟
            if ($now_time >= $schedule_start_time || $now_time <= $schedule_end_time) {
                $soft_val = 1;
            }
            //當不再時間區間內 將警報點全部設為關閉
            else {
                $soft_val = 0;
            }
        } else {
            //當在時間區間內 將警報點全部設為開啟
            if ($now_time >= $schedule_start_time && $now_time <= $schedule_end_time) {
                $soft_val = 1;
            }
            //當不再時間區間內 將警報點全部設為關閉
            else {
                $soft_val = 0;
            }
        }

        //點位通訊值設定
        $arr[$v["id"]][trim($v["soft_alarm_tag"])] = [
            "decimal" => 0,
            "value" => $soft_val
        ];
    }
}

//點位控制 
foreach ($arr as $k => $v) {
    $err = "";
    //先建立soft socket通訊
    $OPC = new OPC_Soft($Socket_Host, $Socket_Port, true);
    //讀取要控制的點位 先判斷是否已經為要設定的數值了
    $s_read_point_str = $OPC->Stringify(array_merge(array("Action_Type" => "R"), $v));
    $rtn_read = $OPC->Commend($s_read_point_str);
    if ($rtn_read == "") {
        $err = '機台通訊異常';
    }
    //解析soft回傳資料為陣列
    $arr_read = $OPC->Parser($rtn_read);
    foreach ($v as $k_2 => $v_2) {
        //檢查要控制的點位 目前數值 並移除數值與要設定的數值為相同的點位(防止重複呼叫)
        if (isset($arr_read[$k_2])) {
            if ($arr_read[$k_2]["value"] == $v_2["value"]) {
                unset($v[$k_2]);
            }
        }
    }
    //當點位陣列不為空 再進行修改呼叫
    if (!empty($v)) {
        $s_clear_point_str = $OPC->Stringify(array_merge(array("Action_Type" => "W"), $v), true);
        $rtn = $OPC->Commend($s_clear_point_str);
        if ($rtn != $s_clear_point_str) {
            $err = '機台通訊異常';
        }
        // 呼叫紀錄
        base_class::WriteLog("batfile_log", "device_alarm_ctrl", array(
            "post_str" => $s_clear_point_str,
            "rtn" =>  $rtn,
            "error" => $err
        ));
    }
}
