<?php
error_reporting(E_ALL & ~(E_NOTICE | E_WARNING)); // 關閉警示及錯誤訊息
session_write_close();
// 讀取設定檔
$json_file = dirname(dirname(__FILE__)) . "\\cfg\\JSON_MachinesInfo.js";
if (!is_file($json_file)) {
	exec_end("json file does not exist.");
}

$setting = substr(trim(file_get_contents($json_file)), strlen("var Machines_Info = "), -1);
$setting = json_decode(str_replace(array("\r\n", "\n"), "", $setting), true, JSON_UNESCAPED_UNICODE);

if (!$setting) {
	exec_end("setting is empty (".json_last_error().").");
}

$mArr = array();
foreach ($setting as $m) {
	$mArr[$m["mid"]] = $m["updater"];
}

require_once "Parameters.php";
require_once "class.OPC_Soft.inc";

$dsn = sprintf("sqlsrv:Server=%s; Database=%s;", $SP_DataSource, $SP_DataBase_Trend);
$sp_conn = new PDO($dsn, $SP_UserID, $SP_Password); 
$softs = array();

// 寫入機台開工資料
$sql = "select * from fn_iot_eqpt_item_in_process()";
$st = $sp_conn->prepare($sql);
$st->execute(); 
$res = $st->fetchAll(PDO::FETCH_ASSOC);
foreach ($res as $one) {
	if (isset($mArr[$one["eqpt_id"]])) {
		$softs = array_merge($softs, soft_array($one, $mArr[$one["eqpt_id"]]));
	}
}
// 寫入時間 故障 保養 待料
$today = date("Y-m-d");
$sql = "select * from fn_iot_eqpt_idle_minutes(:start_time, :end_time)";
$st = $sp_conn->prepare($sql);
$st->execute(array("start_time" => $today, "end_time" => $today)); 
$res = $st->fetchAll(PDO::FETCH_ASSOC);
foreach ($res as $one) {
	if (isset($mArr[$one["eqpt_id"]])) {
		$softs = array_merge($softs, soft_array($one, $mArr[$one["eqpt_id"]]));
	}
}

if (!$softs) {
	exec_end("Softs is empty");
}

try {
	$OPC = new OPC_Soft("localhost", $Socket_Port);
	$softs = array_merge($softs, array("Action_Type" => "W"));
	$cmd = $OPC->Stringify($softs);
	$rtn = $OPC->Commend($cmd);
	if ($rtn != $cmd) {
		throw new Exception("update fail :: ".$rtn." :: ".$cmd);
	}
} catch (Exception $e) {
	exec_end($e->getMessage());
}

exec_end();

function soft_array ($row, $tran) {
	$rtn = array();
	$decimal = array("D" => 2, "R" => 0, "S" => 0);
	foreach ($row as $col => $val) {
		if (isset($tran[$col]) && isset($decimal[substr($tran[$col], 0, 1)])) {
			if ($col == "start_time") {
				$val = substr($val, 0, 19);
			}
			$rtn[$tran[$col]] = array("decimal" => $decimal[substr($tran[$col], 0, 1)], "value" => $val);
		}
	}
	return $rtn;
}

function exec_end ($msg="Done.") {
	die(sprintf("[%s] %s", date("Y-m-d H:i:s"), $msg));
}
?>