<file_sep><?php
include '/var/www/db_params.php';
$dv_id = array();
$dv_id_second=array();
$dv_time_on=array();
$dv_time_on_second=array();
$empty="";
$done=0;
//while(1){
	if(date("d")==1 && $done==0){
		//if(date("G")==17 && date("i")==26 && date("s")==1){
			$done=1;
			$conn = new mysqli($host, $username, $password, $dbname); //vruzka kum db
			if ($conn->connect_error) {
				die("Connection failed: " . $conn->connect_error);
			}
			if($stmt = $conn->prepare("DELETE FROM months_consumption"));
				$stmt->execute();
			if($stmt = $conn->prepare("SELECT id,id_second,time_on,time_on_second FROM devices WHERE id_second<>?")){//izbiram vsichko ot devices za da zapisha v druga tablica
				$stmt->bind_param("i",$empty);
				$stmt->execute();
				$stmt->bind_result($col_id,$col_id_second,$col_time_on,$col_time_second);
				$n=0;
				while ($stmt->fetch()) {//poluchavane na otgovor i podrejdane v masivi
					$dv_id[$n]=$col_id;
					$dv_id_second[$n]=$col_id_second;
					$dv_time_on[$n]=$col_time_on;
					$dv_time_on_second[$n]=$col_time_second;
					$n++;
				}
				//$stmt->close();
				//$conn->close();
			}
			if(!empty($dv_id)){
				for($r=0;$r<=count($dv_id)-1;$r++){
					if($stmt = $conn->prepare("INSERT INTO months_consumption (id_hs, id_second_hs,time_on,time_on_second) VALUES (?, ?, ?,?)")){ //zapisvam jivite danniti koito ustroistvoto e izpratilo
						$stmt->bind_param("iiii", $dv_id[$r], $dv_id_second[$r],$dv_time_on[$r],$dv_time_on_second[$r]);
						$stmt->execute();
						$stmt->close();
					}
				}
				if($stmt = $conn->prepare("UPDATE devices SET time_on=?,time_on_second=?")){//updeitvam vremeto i vatovete
					$stmt->bind_param("ii", $empty,$empty);
					$stmt->execute();
				}
				$conn->close();
			}
			
		//}
	}
	else if(date("d")!=1)
		$done=0;
//}
?><file_sep>var valid_name=0;
var jsonURL = [];
var patt = new RegExp(/^[a-z0-9]+$/i);
var name = document.getElementById("name");
var button=document.getElementById("send");
function check_name(){
	var name = document.getElementById("name");
	var status =document.getElementById("status");
	if(name.value.length<3){
		name.style.border = "solid #ff4d4d";
		status.innerHTML="Името е твърде късо!";		   
	}
	else if (name.value.length>40){
		name.style.border = "solid #ff4d4d";
		status.innerHTML="Името е твърде дълго!";
	}
	else if (!patt.test(name.value)){
		name.style.border = "solid #ff4d4d";
		status.innerHTML="Името съдържа забранени знаци!";
	}
	else{
	name.style.border = "solid #4dff4d";
	status.innerHTML="";	
	valid_name=1;
	}
}
function send(){	
var name = document.getElementById("name");
var pass = document.getElementById("pass");
var status =document.getElementById("status");
if(valid_name==1){	
    var oreg = new XMLHttpRequest();	
	oreg.onreadystatechange = function() {
		if (oreg.readyState == 4 && oreg.status == 200) { //poluchavam otgovor za tova kakvo deistvie e izvursheno
			jsonURL = JSON.parse(oreg.responseText);
			var msg=jsonURL[0].msg1+"<br>"+jsonURL[0].msg2;
			status.innerHTML=msg;
			if(jsonURL[0].url!="")
				window.location=jsonURL[0].url;
			switch(jsonURL[0].stat) {
				case 0:
					pass.style.border="solid #4dff4d";
					name.style.border="solid #4dff4d";
					break;
				case 1:
					pass.style.border="<PASSWORD>";
					name.style.border="solid #ff4d4d";
					break;
			} 
			return false;
		}
	};
	oreg.open("post", "user_login.php", true);
	oreg.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	oreg.send("name="+name.value+"&pass="+pass.value);	
}
else
name.style.border="solid #ff4d4d";	
}
document.getElementById("name").addEventListener("keyup", check_name);
button.addEventListener('click', send);<file_sep><?php
session_start();
include '/var/www/db_params.php';
$id=$_GET["id"];
$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
	die("Connection failed: " . $conn->connect_error);
}
$devices = array(
0 => "SELECT time_start,time_on,last_wats FROM devices WHERE id=?", 
1 => "SELECT time_start_second,time_on_second,last_wats_second FROM devices WHERE id_second=?");
$history = array(
0 => "SELECT time_on FROM months_consumption WHERE id_hs=?",
1 => "SELECT time_on_second FROM months_consumption WHERE id_second_hs=?");
for($i=0;$i<=1;$i++){
	if($stmt = $conn->prepare($devices[$i])){
		$stmt->bind_param("i", $id);
		$stmt->execute();
		$stmt->bind_result($col_dv_time_start,$col1_dv_time_on,$col2_dv_last_wats);
		$stmt->fetch();
		$stmt->close();
	}
}
for($i=0;$i<=1;$i++){
	if($stmt = $conn->prepare($history[$i])){
		$stmt->bind_param("i", $id);
		$stmt->execute();
		$stmt->bind_result($mn_time_on);
		$stmt->fetch();
		$stmt->close();
	}
}
$array=array(
					'time_start' => $col_dv_time_start, //slagam gi v masiv
					'time_on' => $col1_dv_time_on,
					'last_wats' => $col2_dv_last_wats,
					'history' => $mn_time_on
				);
				$return[]=$array;
echo json_encode($return); //encodvam i prashtam
$conn->close();
?><file_sep><?php
session_start();
include '/var/www/db_params.php';
if(isset($_POST["q"],$_POST["status"],$_POST["last_wats"])){
	if(!empty($_POST["q"] && !empty($_POST["status"]) && !empty($_POST["last_wats"]))){
		$in_id=$_POST["q"];
		$status=$_POST["status"];
		$last_wats=$_POST["last_wats"];
	}
}
elseif(isset($_POST["in_type"]) && !empty($_POST["in_type"])){
	$in_type=$_POST["in_type"];
	if($in_type=="mouse"){
		$datax=$_POST["datax"];
		$datay=$_POST["datay"];
		$command=$datax."&".$datay;
	}
	else if($in_type=="key"){
		$command=$_POST["command"];
	}
	else if($in_type=="mouse_click"){
		$command=$_POST["command"];
	}
	   $variable = array( 'type' => "$in_type", 
									'command' => "$command" );
	$msg=json_encode($variable);
}
if(isset($_SESSION["logged"])){
	$conn = new mysqli($host, $username, $password, $dbname);
	if(isset($_POST["q"])){
		if($stmt = $conn->prepare("SELECT ip,port,id_second,time_on,time_start,label FROM devices WHERE id=(?)")){ //vziamm informaciq ot sct1-kontakt purvi
			$stmt->bind_param("i", $in_id);
			$stmt->execute();
			$stmt->bind_result($col1,$col2,$col3,$col4,$col5,$col6);
			$stmt->fetch();
			$stmt->close();
		}
		if(($col1==0)&&($col3==0)){ //SCT nomer 2
			$stmt = $conn->prepare("SELECT ip,port,time_on_second,time_start_second,label1 FROM devices WHERE id_second=(?)"); //izbiram vsichko ot sct nomer 2
			$stmt->bind_param("i", $in_id);
			$stmt->execute();
			$stmt->bind_result($col1,$col2,$col3,$col4,$col5);
			$stmt->fetch();
			$stmt->close();
			$msg=2;
			if($status!="true"){ //status false
				$time_cmp = date("H:i"); //segashno vreme
				$currentTime = strtotime($time_cmp);
				$formatTime2= date("H:i", $currentTime); //tekusht chas
				$time_total= (strtotime($formatTime2) - strtotime($col4))/60; //razlika vuvu vremeto
				//$time_h=floor($time_h);
				//$time_m=$time_h%60;
				//$time_h=($time_h-$time_m)/60;
				//$time_total=$time_h.":".$time_m;
				//$time_ac=$formatTime2-$col4; //izminato vreme
				if($col5!="")
					$time_total=$time_total+$col3;
				else
					$time_total="";
				$formatTime="";
			}
			else{ //status true
				$time_cmp = date("H:i");
				$currentTime = strtotime($time_cmp);
				$formatTime= date("H:i", $currentTime);
				$time_total=$col3;
			}
			$stmt = $conn->prepare("UPDATE devices SET time_start_second=?, time_on_second=?, last_wats_second=? WHERE id_second=?"); //updeitvam vremeto i vatovete
			$stmt->bind_param("sisi", $formatTime,$time_total,$last_wats,$in_id);
			$stmt->execute();
			$stmt->close();
		}//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		else{
			$msg = 1;
			if($status!="true"){
				$time_cmp = date("H:i");
				$currentTime = strtotime($time_cmp);
				$formatTime2= date("H:i", $currentTime); //tekusht chas
				$time_total= (strtotime($formatTime2) - strtotime($col5))/60;
				if($col6!="")
					$time_total=$time_total+$col4;
				else
					$time_total="";
				$formatTime="";
			}
			else{
				$time_cmp = date("H:i");
				$currentTime = strtotime($time_cmp);
				$formatTime= date("H:i", $currentTime);
				$time_total=$col4;
			}
			if($col3!=0){
				$stmt = $conn->prepare("UPDATE devices SET time_start=?, time_on=?, last_wats=? WHERE id=?");
				$stmt->bind_param("sisi", $formatTime,$time_total,$last_wats,$in_id);
				$stmt->execute();
				$stmt->close();
			}
		}
		$conn->close();
}
	else{
		if($stmt = $conn->prepare("SELECT pc_ip,pc_port FROM settings")){ //vziamm informaciq ot sct1-kontakt purvi
			$stmt->execute();
			$stmt->bind_result($col1,$col2);
			$stmt->fetch();
			$stmt->close();
		}
	}
	$len = strlen($msg);
	$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
	socket_sendto($socket, $msg, $len, 0, $col1, $col2);
}
?><file_sep><?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
if(isset($_SESSION["logged"])){ //proverqvam dali sum lognat
function touch_pad(){ //touch pad za upravlenie na pc
	echo <<<EOT
	<div class="row">
	
		<div class="small-12 columns">
			<div class="panel">
				<div id="kb-buttons" class="pc-buttons buttons-container">
					<div id="esc">ESC</div>
					<div id="left" class="fi-arrow-left"></div>
					<div id="up" class="fi-arrow-up"></div>
					<div id="down" class="fi-arrow-down"></div>
					<div id="right" class="fi-arrow-right"></div>
					<div id="enter" >ENTER</div>
					<div id="vdown" class="fi-volume-none"></div>
					<div id="mute" class="fi-volume-strike"></div>
					<div id="vup" class="fi-volume"></div>
					<div id="space" >SPACE</div>
					<div id="f" class="fi-arrows-out"></div>
					<div id="exit" class="fi-x"></div>
				</div>
				<div class="row">
					<div class="small-12 columns">
						<div id="panel" class="touch_area"></div>
					</div>
				</div>
				<div  class="row">
					<div id="mouse_buttons">
						<div class="small-6 columns" style="padding-right: 0px;">
							<div id="left_mouse" class="left_button" ></div>
						</div>
						<div class="small-6 columns" style="padding-left: 0px;">
							<div id="right_mouse" class="right_button"></div> 
						</div>
					</div>
				</div>
			</div>
		</div>
		<div id=testing></div>
	</div>
EOT;
}
function sct_btn(&$sct_id ,&$sct_id_second,$br_sct){ //zarejdane na kontaktite s id-ta i imena
	for($q=0;$q<=$br_sct-1;$q++){
		echo <<<EOT
		<div class="row">
			<div class="small-6 columns">
				<div class="panel">
					<input type="text" class="wet_asphalt btn_stl" id="lb-$sct_id[$q]"  maxlength="10"  placeholder="Бутон" onfocusout="label_save(this)" />
					<div class="switch round large" >
						<input id="$sct_id[$q]" type='checkbox' onchange='UDP_send(this)'>
						<label for="$sct_id[$q]" style='margin: 0 auto; display: block;'></label>
					</div>
					<hr style="padding:0 0 0.5rem; margin:0;">
					<div class="row">
						<div class="small-6 columns">
							<div class="inf-w" id="info-$sct_id[$q]"></div>
						</div>
						<div class="small-6 columns">
							<i data-reveal-id="tbModal"  class="fi-info info-tb" id="info-tb-$sct_id[$q]" onclick="resp_hand(1,this)"></i>
						</div>
					</div>
				</div>
			</div>
			<div class="small-6 columns">
				<div class="panel">
					<input type="text" class="wet_asphalt btn_stl" id="sub-lb-$sct_id[$q]" maxlength="10" placeholder="Бутон" onfocusout="label_save(this)"/>
					<div class="switch round large">
						<input id="$sct_id_second[$q]" type="checkbox" onchange="UDP_send(this)">
						<label for="$sct_id_second[$q]" style="margin: 0 auto; display: block;" ></label>
					</div>
					<hr style="padding:0 0 0.5rem; margin:0;">
					<div class="row">
						<div class="small-6 columns">
							<div class="inf-w" id="info-$sct_id_second[$q]" ></div>
						</div>
						<div class="small-6 columns">
							<i data-reveal-id="tbModal" class="fi-info info-tb" id="info-tb-$sct_id_second[$q]" onclick="resp_hand(1,this)"></i>
						</div>
					</div>
				</div>
			</div>
		</div>
EOT;
	}
}
function lc_btn(&$lc_id,$br){ //zarejdane na kliuchovete za lampi s id-ta i nomera
	$tr=0;
	$br_lc=intval($br/2); 
	$br_second_lc=$br%2;
	if($br_lc>0){
		$br_lo=$br_lc-1;
		$br_li=1;
		$columns=6;
	}
	else if($br_second_lc==1){
		$br_lo=0;
		$br_li=0;
		$columns=12;
	}
	else{
		$br_lo=-2;
		$br_li=-2;
	}
	for($q=0;$q<=$br_lo;$q++){
		echo "<div class='row'>";
		for($i=0;$i<=$br_li;$i++){
			if($q>0)
			$v=$i+2*$q;
		else
			if($tr==1)
				$v=$br-1;
			else
				$v=$i;
		echo "<div class='small-$columns columns'>";
			echo <<<EOT
					<div class="panel">
						<input type='text' class="midnight_blue btn_stl" id="lb-$lc_id[$v]" maxlength='10' placeholder='Бутон' onfocusout="label_save(this)"/>
						<div class="switch round large" >
						<input id=$lc_id[$v] type = 'checkbox' onchange='UDP_send(this)'>
						<label for=$lc_id[$v] style='margin: 0 auto; display: block;'></label>
						</div>
					</div>
				</div>
EOT;
		}
		echo "</div>";
		if(($br_second_lc==1)&&($q==$br_lo)){
			if($br_lc==0)
			$br_lo=-1;
		else
			$br_lo=0;
			$br_li=0;
			$columns=12;
			$br_second_lc=0;
			$tr=1;
			$v=$v+1;
			$q=-1;
		}
	}
}
function video_panel(&$cam_ip,&$cam_label,&$cam_port,&$cam_id,$cam_br){ //video panel za kamerite
// echo <<<EOT
// <div class="row">
		 // <div class="small-12 columns">
// <ul class="example-orbit" data-orbit>
  // <li>
    // <img src="../assets/img/examples/satelite-orbit.jpg" alt="slide 1" />
    // <div class="orbit-caption">
      // Caption One.
    // </div>
  // </li>
  // <li class="active">
    // <img src="../assets/img/examples/andromeda-orbit.jpg" alt="slide 2" />
    // <div class="orbit-caption">
      // Caption Two.
    // </div>
  // </li>
  // <li>
    // <img src="../assets/img/examples/launch-orbit.jpg" alt="slide 3" />
    // <div class="orbit-caption">
      // Caption Three.
    // </div>
  // </li>
// </ul>
	// </div>
	// </div>
// EOT;
// <div class="video-panel">
				// <ul class="example-orbit" data-orbit>
				// <li>
					// <div class="orbit-caption">дз</div>
// </li>
echo <<<EOT
	
			
EOT;
for($t=0;$t<=$cam_br-1;$t++){
	$slide=$t+1;
	$stream="http://".$cam_ip[$t].":".$cam_port[$t]."/video";
echo <<<EOT
<div class="medium-12 columns">
	<div class="row">
		<div class="panel">	
			<img id="cam_$cam_id[$t]" src="$stream"/>
			<div id="cam_title">$cam_label[$t]</div>
		</div>
	</div>
</div>
EOT;
}
if($cam_br==0)
	echo "<h3 class='midnight_blue'>Няма охранителни камери</h3>";
}
function led_panel(){ //budeshta funkciq
	echo <<<EOT
	<div class="row">
		<div class="small-12  columns">
			<div class="led-panel"> 
				<div class="row">
					<div class="small-8 columns">
						<label class="midnight_blue">ЛЕД осветление</label>
					</div>
					<div class="small-2 small-offset-2 columns">
						<span id="sliderOutput3" ></span><span class="midnight_blue">%</span>
					</div>
				</div>
				<div class="row">
					<div class="small-12 medium-12 columns">
					  <div id="slider" class="range-slider round" data-slider data-options="display_selector: #sliderOutput3; step:2;">
						  <span id="switch" class="range-slider-handle" ontouchstart="doTimer()"></span>
						  <span class="range-slider-active-segment"></span>
						  <input type="hidden">
						</div>
					</div>
				</div>
				<div class="row">
					  <div class="silver medium">
						   <div class="small-2 medium-2 columns " ontouchend="iconLock()">
								<div class="right">
									<i id="icon" class="fi-unlock"></i>
								</div>
						   </div>
					  </div>
				</div>
			</div>
		</div>
	</div>
EOT;
}
}
?><file_sep><?php
session_start();
include '/var/www/db_params.php';
if(isset($_GET['day_price']))
	$day_price=$_GET["day_price"]; //vzimam informaciq za centa
if(isset($_SESSION["logged"])){
$conn = new mysqli($host, $username, $password, $dbname);
	$stmt = $conn->prepare("INSERT INTO electricity_price (day_price) VALUES (?) ON DUPLICATE KEY UPDATE day_price=?"); //zpisvam q v db
	$stmt->bind_param("ss", $day_price,$day_price);
	$stmt->execute();
$stmt->close();
$conn->close();
}
?>
<file_sep><?php
session_start();
include '/var/www/db_params.php';
if(isset($_GET['dvs_id'])){
	$label=$_GET["label"];
	$second_label=$_GET["label1"];
	$id=$_GET["dvs_id"];
}
if(isset($_SESSION["logged"])){
$conn = new mysqli($host, $username, $password, $dbname);
if($label==""){
	$stmt = $conn->prepare("UPDATE devices SET label1=(?) WHERE id=(?)"); //zapisvam label ot sct1 ili LC
	$stmt->bind_param("si", $second_label,$id);
	$stmt->execute();
}
else{
	$stmt = $conn->prepare("UPDATE devices SET label=(?) WHERE id=(?)");//zapisvam label ot SCT2 
	$stmt->bind_param("si", $label,$id);
	$stmt->execute();
}
$stmt->close();
$conn->close();
}
?><file_sep>#библиотеки нужни за програмата
import socket
import ctypes
from ctypes import windll, Structure, c_ulong, byref
import time
import os
import sys
import json
import re
from win32api import * #api за ос
SendInput = ctypes.windll.user32.SendInput # Начало на инициализация на ctypes библиотеката
PUL = ctypes.POINTER(ctypes.c_ulong)
class KeyBdInput(ctypes.Structure):
    _fields_ = [("wVk", ctypes.c_ushort),
                ("wScan", ctypes.c_ushort),
                ("dwFlags", ctypes.c_ulong),
                ("time", ctypes.c_ulong),
                ("dwExtraInfo", PUL)]

class HardwareInput(ctypes.Structure):
    _fields_ = [("uMsg", ctypes.c_ulong),
                ("wParamL", ctypes.c_short),
                ("wParamH", ctypes.c_ushort)]

class MouseInput(ctypes.Structure):
    _fields_ = [("dx", ctypes.c_long),
                ("dy", ctypes.c_long),
                ("mouseData", ctypes.c_ulong),
                ("dwFlags", ctypes.c_ulong),
                ("time",ctypes.c_ulong),
                ("dwExtraInfo", PUL)]

class Input_I(ctypes.Union):
    _fields_ = [("ki", KeyBdInput),
                 ("mi", MouseInput),
                 ("hi", HardwareInput)]

class Input(ctypes.Structure):
    _fields_ = [("type", ctypes.c_ulong),
                ("ii", Input_I)]
def PressKey(hexKeyCode):

    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    ii_.ki = KeyBdInput( hexKeyCode, 0x48, 0, 0, ctypes.pointer(extra) )
    x = Input( ctypes.c_ulong(1), ii_ )
    SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))

def ReleaseKey(hexKeyCode):

    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    ii_.ki = KeyBdInput( hexKeyCode, 0x48, 0x0002, 0, ctypes.pointer(extra) )
    x = Input( ctypes.c_ulong(1), ii_ )
    SendInput(1, ctypes.pointer(x), ctypes.sizeof(x)) #<Край
class POINT(Structure):
    _fields_ = [("x", c_ulong), ("y", c_ulong)]
try:
    with open('config.txt') as data_file:    
        data = json.load(data_file)
except:
    ctypes.windll.user32.MessageBoxW(0,"Липсва конфигурационен файл!", "Данни за свързване", 0)
    sys.exit()
x_old=0
y_old=0
conf_port=data["settings"]["port"]
conf_mouse_x=data["settings"]["mouse_sens_x"]
conf_mouse_y=data["settings"]["mouse_sens_y"]
conf_mouse_x=re.sub(r'[^\d]+','',conf_mouse_x)
conf_mouse_y=re.sub(r'[^\d]+','',conf_mouse_y)
conf_port=re.sub(r'[^\d]+','',conf_port)
conf_port=int(conf_port)
conf_mouse_x=int(conf_mouse_x)
conf_mouse_y=int(conf_mouse_y)
UDP_IP = socket.gethostbyname(socket.getfqdn()) #адрес на хост-а
if conf_port !=0 and conf_port <= 65535 and conf_port>0:
    UDP_PORT = conf_port #Порт
    ctypes.windll.user32.MessageBoxW(0,"Адрес:"+UDP_IP+'\n'
                                     +"Порт:"+str(UDP_PORT)+'\n'
                                     +"X офсет:"+str(conf_mouse_x)+'\n'
                                     +"У офсет:"+str(conf_mouse_y), "Данни за свързване", 0)
elif conf_port<0:
    conf_port=abs(conf_port)
    if conf_port > 65535:
        UDP_PORT = 65535 #Порт
    else:
        UDP_PORT=conf_port
    ctypes.windll.user32.MessageBoxW(0,"Адрес:"+UDP_IP+'\n'+"Порт:"+str(UDP_PORT), "Данни за свързване", 0)
elif conf_port>65535:
    UDP_PORT = 65535 #Порт
    ctypes.windll.user32.MessageBoxW(0,"Адрес:"+UDP_IP+'\n'+"Порт:"+str(UDP_PORT), "Данни за свързване", 0)
else:
    ctypes.windll.user32.MessageBoxW(0,"Проблем с порта!", "Данни за свързване", 0)
    sys.exit()
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #Създаване на сокет и bind-ване
sock.bind((UDP_IP, UDP_PORT))
#x=int(GetSystemMetrics(0)/2) # половината от широчината на екрана в пиксели
#y=int(GetSystemMetrics(1)/2) # половината от височината на екрана в пиксели
while True:
    try:
        data, addr = sock.recvfrom(1024) #Задаване размер на буфер за получените данни
        line=data.decode("ascii")#декодиранена данните
        loaded = json.loads(line)  
        dv_type=loaded["type"]
        dv_command=loaded["command"]
        line="@"+dv_type+":"+dv_command
        print(line)
        if line=='@key:up':
            PressKey(0x26)    #стрелка нагоре
            ReleaseKey(0x26)
        elif line=='@key:down':
            PressKey(0x28)#стрелка надолу
            ReleaseKey(0x28)
        elif line=='@key:left':
            PressKey(0x25)# лява стрелка
            ReleaseKey(0x25)   
        elif line=='@key:right':
            PressKey(0x27)# дясна стрелка
            ReleaseKey(0x27)
        elif line=='@key:esc':
            PressKey(0x1B)# esc
            ReleaseKey(0x1B)
        elif line=='@key:space':          
            PressKey(0x20)
            ReleaseKey(0x20)
        elif line=='@key:mute':          
            PressKey(0xAD)
            ReleaseKey(0xAD)
        elif line=='@key:exit':
            PressKey(0x12)
            PressKey(0x73)
            ReleaseKey(0x12)
            ReleaseKey(0x73)
        elif line=='@key:menu':
            PressKey(0x5C)# старт бутон
            ReleaseKey(0x5C)      
        elif line=='@key:enter':
            PressKey(0x0D)
            ReleaseKey(0x0D)#ентър
        elif line=='@key:vup':
            PressKey(0xAF)
            ReleaseKey(0xAF)# увеличаване на звука
        elif line=='@key:vdown':
            PressKey(0xAE)
            ReleaseKey(0xAE)# намаляне на звука
        elif line=='@key:f':
            PressKey(0x46)
            ReleaseKey(0x46)#  f бутон   
        elif line=='@key:pc_restart':
            os.system('shutdown /r /t 0')# рестартиране на машината
        elif line=='@key:pc_shutdown':
            os.system('shutdown /s /t 0')# рестартиране на машината
        elif line=='@key:pc_sleep':
            os.system('rundll32.exe powrprof.dll,SetSuspendState 0,1,0')# вкарване на машината в спящ режим
        elif line=='@mouse_click:left':
            ctypes.windll.user32.mouse_event(2, 0, 0, 0,0)# ляв бутон на мишката
            ctypes.windll.user32.mouse_event(4, 0, 0, 0,0)
        elif line=='@mouse_click:right':
            ctypes.windll.user32.mouse_event(8, 0, 0, 0,0)# десен бутон на мишката
            ctypes.windll.user32.mouse_event(16, 0, 0, 0,0)
        elif '@mouse:' in line:
            aft_line=line.replace("@mouse:", "")
            x2,y2=aft_line.split("&")
            x2=int(x2)
            y2=int(y2)
            x2=x2/conf_mouse_x #offset x
            y2=y2/conf_mouse_y# offset y
            pt = POINT()
            windll.user32.GetCursorPos(byref(pt))
            x=pt.x+((pt.x+int(x2))-x_old)#-conf_mouse_x
            y=pt.y+(pt.y+int(y2)-y_old)#-conf_mouse_y
            x_old=x
            y_old=y
            ctypes.windll.user32.SetCursorPos(x,y)
    except:
        pass
    
<file_sep><?php
session_start();
include '/var/www/db_params.php';
if(isset($_POST['pc_ip'],$_POST['pc_port'],$_POST['update'])){
	if($_POST['update']==0){
	$pc_ip=$_POST['pc_ip'];
	$pc_port=$_POST['pc_port'];
		if(isset($_SESSION["logged"])){
			$conn = new mysqli($host, $username, $password, $dbname);
			$stmt = $conn->prepare("DELETE FROM settings");
			$stmt->execute();
			$stmt = $conn->prepare("INSERT INTO settings (pc_ip,pc_port) VALUES (?,?)"); //zpisvam q v db
			$stmt->bind_param("si", $pc_ip,$pc_port);
			$stmt->execute();
			$stmt->close();
			$conn->close();
			get_info($host, $username, $password, $dbname);
		}
	}
	else if($_POST['update']==1)
		get_info($host, $username, $password, $dbname);
}
function get_info($host, $username, $password, $dbname){
	$conn = new mysqli($host, $username, $password, $dbname);
	if($stmt = $conn->prepare("SELECT pc_ip,pc_port FROM settings")){ //vzimam vsicko kakvoto e zapisano v db
	$stmt->execute();
	$stmt->bind_result($col,$col1);
	$stmt->fetch();
	$array=array( 
				'ip' => $col,
				'port' => $col1
			);
			$return[]=$array;
	$stmt->close();
	if(!empty($return))
		echo json_encode($return); //encodvam i prashtam
	}
}
?>
<file_sep><?php
$command="/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'";
$localIP = exec ($command); //vziamm localnoto ip ot linux mashinata
include '/var/www/db_params.php'; //zarejdam danni za db
include 'items_types.php';
$head   = 'DV-INFORMATION'; //tursq tozi fragment
$cl   = ':';
$match=0;
$from = '';
$port = 0;
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); //suzdavam UDO soket
socket_bind($socket,$localIP, 5113); //i go bind-vam na localnoto ip i port
while(1){	
	socket_recvfrom($socket, $buf, 50, 0, $from, $port);
	if($buf!=null){ //proverqm za informaciq
		$match=0;
		$pos_h = strpos($buf, $head); //sravnqvam po gorniq fragment
		if ($pos_h=== false) {
			$pos_tp = strpos($buf, $dv_type1); //tursq tipa na ustroistvoto
			if($pos_tp===false){
				$int=2;
				$pos_tp = strpos($buf, $dv_type0);
			}
			else{
				$int=3;
				
			}
			$dv_type = substr($buf,$pos_tp,$int);
			$data = substr($buf,$int,50);
			$conn = new mysqli($host, $username, $password, $dbname);
			$stmt = $conn->prepare("INSERT INTO incoming_data (ip, device,data) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE data=?"); //zapisvam jivite danniti koito ustroistvoto e izpratilo
			$stmt->bind_param("ssss", $from, $dv_type,$data,$data);
			$stmt->execute();
			$stmt->close();
			$conn->close();
		}
		else{
			$pos_tp = strpos($buf, $dv_type1);
			if($pos_tp==false){
				$int=2;
				$pos_tp = strpos($buf, $dv_type0);
			}
			else
				$int=3;
            $pos_port = strripos($buf, $cl);
			$dv_ip= substr($buf, $pos_tp+$int, $pos_port-($pos_tp+$int));
			$dv_port = substr($buf,$pos_port+1,4);
			$dv_type = substr($buf,$pos_tp,$int);
			if (!filter_var($dv_ip, FILTER_VALIDATE_IP) === false) {
				$conn = new mysqli($host, $username, $password, $dbname);
				 if($stmt = $conn->prepare("SELECT ip,id,id_second FROM devices")){
					$stmt->execute();
					$stmt->bind_result($col,$col1,$col2);
					while ($stmt->fetch()) {
						if($col==$dv_ip){
							$match=1;
						}
						$lst_id_second=$col2;
						$lst_id=$col1;
					}
						$stmt->close();
				 }
				if($match==0){
					if($lst_id_second>$lst_id)
						$dv_id=$lst_id_second+1;
					else
						$dv_id=$lst_id+1;
					if($dv_type==$dv_type1)
						$dv_id_second=$dv_id+1;
					else
						$dv_id_second=0;
					if($stmt = $conn->prepare("INSERT INTO devices (ip,port,type,id,id_second) VALUES (?,?,?,?,?)")){ //zapisvam v db dannite za ustroistvoto
						$stmt->bind_param("sisii", $dv_ip, $dv_port,$dv_type,$dv_id,$dv_id_second);
						$stmt->execute();
						$stmt->close();
					}
				}
				$conn->close();
			}
			
		}
	}
}
?>
<file_sep><?php
session_start();
include '/var/www/db_params.php';
if(isset($_SESSION["logged"])){
$command="/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'";
$localIP = exec ($command); //vziamm localnoto ip 
$port=5113;
$conn = new mysqli($host, $username, $password, $dbname);
if($stmt = $conn->prepare("SELECT day_price FROM electricity_price")){ //vzimam cenata ot db
	$stmt->execute();
	$stmt->bind_result($col);
	$stmt->fetch();
	$stmt->close();
}
$array=array(
					'host_ip' => $localIP, //slagam gi v masivi
					'host_port' => $port,
					'el_price'=> $col
				);
				$return[]=$array;
echo json_encode($return); //encodvam v json i prashtam
}
?><file_sep><?php
//$command="/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'";
//$localIP = exec ($command); //vziamm localnoto ip ot linux mashinata
$from = '';
$port = 0;
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); //suzdavam UDO soket
socket_bind($socket,'192.168.1.166', 5150); //i go bind-vam na localnoto ip i port
	socket_recvfrom($socket, $buf, 150, 0, $from, $port);
	//if($buf!=null){ //proverqm za informaciq
	//	$match=0;	
	echo $buf;
	$obj = json_decode($buf);
	echo $obj->{'head'}; // 12345
?><file_sep><?php
	echo <<<EOT
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" /> 
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<link rel="stylesheet" href="css/foundation.css" />
	<link rel="stylesheet" href="css/ui_colors.css" />
	<link rel="stylesheet" href="icon_pack/foundation-icons.css" />
</head>
<body>
<div class="off-canvas-wrap" data-offcanvas>
  <div class="inner-wrap">

    <a class="left-off-canvas-toggle" href="#" >Menu</a>

    <!-- Off Canvas Menu -->
    <aside class="left-off-canvas-menu">
        <!-- whatever you want goes here -->
        <ul>
          <li><a href="#">Item 1</a></li>
        ...
        </ul>
    </aside>

    <!-- main content goes here -->
    <p>Set in the year 0 F.E. ("Foundation Era"), The Psychohistorians opens on Trantor, the capital of the 12,000-year-old Galactic Empire. Though the empire appears stable and powerful, it is slowly decaying in ways that parallel the decline of the Western Roman Empire. <NAME>, a mathematician and psychologist, has developed psychohistory, a new field of science and psychology that equates all possibilities in large societies to mathematics, allowing for the prediction of future events.</p>

  <!-- close the off-canvas menu -->
  <a class="exit-off-canvas"></a>

  </div>
</div>
  <script src="js/vendor/jquery.js"></script>
  <script src="js/foundation.min.js"></script>
  <script src="js/functionality.js"></script>
  <script>
    $(document).foundation();
  </script>
</body>
</html>
EOT;
?><file_sep><?php 
session_start();
if(isset($_SESSION["logged"])){ //proverka dali si lognat
	if(isset($_GET["load"])){ //proverka i vzima na stoinosti ot zaqvkata
		$load_n=$_GET["load"];
	}
	else
		$load_n="";
include 'items.php';
include 'items_types.php';
include '/var/www/db_params.php';
$ip_dvs = array(); //deklarirane na mnogo masivi 
$id_dvs = array();
$id_dvs_second = array();
$id_dvs_second_sub = array();
$dv_status=array();
$tp_dvs = array();
$label_id=array();
$label_id_lc=array();
$label_id_sct=array();
$label_id_sct_second=array();
$label=array();
$id_dvs_lc=array();
$cam_ip=array();
$cam_label=array();
$cam_id=array();
$cam_port=array();
$lc_cnt=0;
$sct_cnt=0;
$match=0;
$conn = new mysqli($host, $username, $password, $dbname); //vruzka kum db
if ($conn->connect_error) {
	die("Connection failed: " . $conn->connect_error);
}
$ip_cam = array();
$cam_label = array();
$n=0;
$conn = new mysqli($host, $username, $password, $dbname);
$stmt = $conn->prepare("SELECT ip,label,id,port FROM cameras"); //izprashtane na zaqvka
$stmt->execute();
$stmt->bind_result($col_ip,$col_label,$col_ids,$col_ports); 
$z=0;
while ($stmt->fetch()) { //poluchavane na otgovor
	$cam_ip[$z]=$col_ip;
	$cam_label[$z]=$col_label;
	$cam_id[$z]=$col_ids;
	$cam_port[$z]=$col_ports;
	$z++;
}
$stmt->close();
$z=$z-1;
if(count($cam_ip)>0){ //proverqvam kolko sa kamerite
		for($q=0;$q<=$z;$q++){		//slagam gi v masivi
				$array=array(
					'cam_ip'=> $cam_ip[$q],
					'cam_port' => $cam_port[$q],
					'cam_id'=>$cam_id[$q],
					'cam_label'=>$cam_label[$q],
				);
				$return_cams[]=$array;
			}
	}
//echo json_encode($return);
if($stmt = $conn->prepare("SELECT type,id,ip,label,id_second,label1 FROM devices")){//izprashtane na zaqvka
	$stmt->execute();
	$stmt->bind_result($col1,$col2,$col3,$col4,$col5,$col6);
	$n=0;
	$r=0;
	while ($stmt->fetch()) {//poluchavane na otgovor
		$tp_dvs[$n]=$col1;
		$id_dvs[$n]=$col2;
		$ip_dvs[$n]=$col3;
		$label[$n]=$col4;
		$id_dvs_second[$n]=$col5;
		$label_id_sct_second[$n]=$col6;
		if($id_dvs_second[$n]>0){
			$id_dvs_second_sub[$r]=$id_dvs_second[$n];
			$r++;
		}
		$label_id[$n]=0;
		$n++;
	}
	$n=$n-1;
	$stmt->close();
	$conn->close();
	if(count($ip_dvs)>0){ //proverqvam kolko sa ustroistvata
		for($j=0;$j<=$n;$j++){		//slagam gi v masivi
				$array=array(
					'ip'=> $ip_dvs[$j],
					'id' => $id_dvs[$j],
					'second_id'=>$id_dvs_second[$j],
					'type'=>$tp_dvs[$j],
					'label' => $label[$j],
					'second_label' => $label_id_sct_second[$j],
				);
				$return[]=$array;
			}
		//}
		for($k=0;$k<=$n;$k++){
			if($tp_dvs[$k]==$dv_type0){
				$id_dvs_lc[$lc_cnt]=$id_dvs[$k]; //pravq malko magii za vseki ot elementite
				$lc_cnt++;
			}
			if($tp_dvs[$k]==$dv_type1){
					$id_dvs_sct[$sct_cnt]=$id_dvs[$k]; //sushtoto
					$sct_cnt++;
			}
		}
	}
}
if(!empty($return)){
		echo "<div id='id-info' style='display:none;'>";
		echo json_encode($return); //encodvam gi v json
		echo "</div>";
	}
switch ($load_n) { //proverka na zaqvenite elementi
    case 1: //lampi i razklonitel
        $fn_type1($id_dvs_sct,$id_dvs_second_sub,$sct_cnt);
		$fn_type0($id_dvs_lc,$lc_cnt);
		
        break;
    case 2:
        $fn_type2($cam_ip,$cam_label,$cam_port,$cam_id,$z+1); //kameri
		if(!empty($return)){
			echo "<div id='id-info-cams' style='display:none;'>";
			echo json_encode($return_cams); //encodvam gi v json i gi izkarvam
			echo "</div>";
		}
        break;
    case 3:
        $fn_type0($id_dvs_lc,$lc_cnt); //samo lampi
        break;
	case 4:
        //echo "REMOTES"; //budeshta funkciq
		$fn_type4();
        break;
	default:
		$fn_type1($id_dvs_sct,$id_dvs_second_sub,$sct_cnt); //defaultnite kakto pri 1
		$fn_type0($id_dvs_lc,$lc_cnt);
		//$fn_type2($cam_ip,$cam_label,$z);
}
}
?><file_sep>var c = 0;
var t;
var tr = 0;
var drop_stat = 1;
var timer_is_on = 0;
var lock_stat = 1;
var i = 0; //loops
var buffer = 0;
var ip = 0;
var ssid = 0;
var pass = 0;
var jsonData = [];
var jsonIpPort = [];
var jsonModals = [];
var jsonData3 = [];
var ids = [];
var label_ids = [];
var labels = [];
var labels_second = [];
var id_sd = 0;
var second_label;
var raw;
var stats;
var stats_n;
var inx;
var tg=0;
var b;
var data_js=[];
var frst=[];
var scnd=[];
var dt_scnd=[];
var dt_frst=[];
var wts_1=[];
var wts_2=[];
var each_info=[[],[]];
var inf_arrs=0;
var ip_ch = new RegExp(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/);
var table = document.getElementsByTagName("TABLE")[0];
var rows=table.getElementsByTagName("TR");
var cell=table.getElementsByTagName("TD");
//===>Intervals
setInterval(outReq, 1000);
//===>Functions
function get_crn_d(id_tb){
	tg=1;
	var numb = id_tb.id.match(/\d/g);
	numb = numb.join("");
	for(var t=0;t<=jsonData.length-1;t++){
		if(jsonData[t].id==numb)
			document.getElementById("title-tb").innerHTML =jsonData[t].label;
		else if(jsonData[t].second_id==numb)
			document.getElementById("title-tb").innerHTML =jsonData[t].second_label;
	}
}
function resp_hand(a) {
	if(a!=undefined)
		b=a
	for (var j = 0; j <= jsonData3.length - 1; j++) {
		for (var q = 0; q <= jsonData3.length - 1; q++) {
			if (jsonData3[j].ip == jsonData[q].ip) {
				if (jsonData[q].type == "LC") {
					inx = jsonData3[j].data.indexOf(":TMP:");
					stats_n = jsonData3[j].data.substring(inx - 1, inx)
					if (stats_n == 0)
						stats = false;
					else
						stats = true;
					document.getElementById(jsonData[q].id).checked = stats;
					//alert(stats);
				} else {
					data_js[inf_arrs]=jsonData3[j].data;
					frst[inf_arrs]=data_js[inf_arrs].indexOf("N");
					scnd[inf_arrs]=data_js[inf_arrs].indexOf("k1");
					dt_frst[inf_arrs]=data_js[inf_arrs].substring(frst[inf_arrs]+1, scnd[inf_arrs]);
					dt_scnd[inf_arrs]=data_js[inf_arrs].substring(0, frst[inf_arrs]);
					wts_1[inf_arrs]=dt_frst[inf_arrs]*228;
					wts_2[inf_arrs]=dt_scnd[inf_arrs]*228;
					//for (var l = 0; l <= 1; l++) {		
					//	if (l == 0) {
					for(var t=0;t<=1;t++)
						each_info[inf_arrs][t]=;
					}
							inx = data_js.lastIndexOf(":"); 
							stats_n = data_js.substring(inx + 1, inx + 2)
							var id_inf="info-"+jsonData[q].id;
							if(b==1)
								rows[1].getElementsByTagName("TD")[1].innerHTML = wts_1.toFixed(2)+"W";
							if (stats_n == 0){
								stats = false;
								wts_1=0;
							}
							else
								stats = true;
							document.getElementById(id_inf).innerHTML=wts_1.toFixed(2)+"W";
							document.getElementById(jsonData[q].id).checked = stats;
					//	} else {
							inx = data_js.indexOf(":");
							stats_n = data_js.substring(inx + 1, inx + 2)
							id_inf="info-"+jsonData[q].second_id;
							if(b==2)
								rows[1].getElementsByTagName("TD")[1].innerHTML = wts_2.toFixed(2)+"W";
							if (stats_n == 0){
								stats = false;
								wts_2=0;
							}
							else
								stats = true;
							document.getElementById(id_inf).innerHTML=wts_2.toFixed(2)+"W";
							document.getElementById(jsonData[q].second_id).checked = stats;
					//	}
					//}
					inf_arrs=inf_arrs+1;
				}
			}
		}
	}
	inf_arrs=0;
}

function outReq() {
	var oReq = new XMLHttpRequest();
	oReq.onreadystatechange = function() {
		if (oReq.readyState == 4 && oReq.status == 200) {
			if (oReq.responseText.length == 0) {
				for (var t = 0; t <= jsonData.length - 1; t++) {
					document.getElementById(jsonData[t].id).disabled = true;
					if (jsonData[t].second_id != 0)
						document.getElementById(jsonData[t].second_id).disabled = true;
				}
			} else {
				for (var t = 0; t <= jsonData.length - 1; t++) {
					document.getElementById(jsonData[t].id).disabled = false;
					if (jsonData[t].second_id != 0)
						document.getElementById(jsonData[t].second_id).disabled = false;
				}
				jsonData3 = JSON.parse(oReq.responseText);
				resp_hand();
			}
		}
	};
	oReq.open("get", "get-data.php", true);
	oReq.send();
}
var cpReq = new XMLHttpRequest();
cpReq.onreadystatechange = function() {
	if (cpReq.readyState == 4 && cpReq.status == 200) {
		jsonIpPort = JSON.parse(cpReq.responseText);
	}
};
cpReq.open("GET", "get-ip-port.php", true);
cpReq.send();

function label_save(val) {
	var plc_holder = document.getElementById(val.id).value;
	var p = val.id.search("sub-");
	if (p >= 0) {
		var numb = val.id.match(/\d/g);
		numb = numb.join("");
		for (var n = 0; n <= jsonData.length - 1; n++) {
			if (numb == jsonData[n].label_id) {
				id_sd = jsonData[n].id;
				second_label = plc_holder;
				plc_holder = "";
			}
		}
	} else {
		for (var n = 0; n <= jsonData.length - 1; n++) {
			if (val.id == jsonData[n].label_id)
				id_sd = jsonData[n].id;
			second_label = "";
		}
	}
	var lblReq = new XMLHttpRequest();
	lblReq.open("GET", "label_save.php?label=" + plc_holder + "&label1=" + second_label + "&dvs_id=" + id_sd, true);
	lblReq.send();
}
var coReq = new XMLHttpRequest();
coReq.onreadystatechange = function() {
	if (coReq.readyState == 4 && coReq.status == 200) {
		document.getElementById("main-container").innerHTML = coReq.responseText;
		get_el();
	}
};
coReq.open("GET", "items_boot.php", true);
coReq.send();

function get_el() {
	raw = document.getElementById("id-info").innerHTML;
	jsonData = JSON.parse(raw);
	for (var k = 0; k <= jsonData.length - 1; k++) {
		ids[k] = jsonData[k].id;
		label_ids[k] = jsonData[k].label_id;
		labels[k] = jsonData[k].label;
		labels_second[k] = jsonData[k].second_label;
		if (labels_second[k] != "") {
			var id_mrg = "sub-" + label_ids[k];
			document.getElementById(id_mrg).value = labels_second[k];
		}
		if (labels[k] != "")
			document.getElementById(label_ids[k]).value = labels[k];
	}
	//alert(jsonData[0].id);
}
document.getElementById("wifi-data").style.display = "none";

function dvSearch() {
	ip = document.getElementById("ip-holder").value;
	if (ip_ch.test(ip)) {
		document.getElementById("ip-data").style.display = "none";
		document.getElementById("wifi-data").style.display = "block";
	} else
		document.getElementById("ip-holder").style.border = "solid #ff0000";
}

function dvSave() {
	ssid = document.getElementById("ssid-holder").value;
	pass = document.getElementById("pass-holder").value;
	xmlhttp = new XMLHttpRequest();
	xmlhttp.open("POST", "http://" + ip, true);
	xmlhttp.send("ssid=" + ssid + "&" + "pass=" + pass + "&target=" +jsonIpPort[0].host_ip + "&port=" + jsonIpPort[0].host_port + "end");
}

function Defaults() {
	ip = "";
	document.getElementById("ip-holder").style.border = "";
	document.getElementById("ip-holder").value = "";
	document.getElementById("ssid-holder").value = "";
	document.getElementById("pass-holder").value = "";
	document.getElementById("wifi-data").style.display = "none";
	document.getElementById("ip-data").style.display = "block";
}

function UDP_send(elt) {
	var sReq = new XMLHttpRequest();
	sReq.open("get", "UDP_send.php?q=" + elt.id, true);
	sReq.send();
}

function doTimer() {
	if (!timer_is_on) {
		timer_is_on = 1;
		timedCount();
	}
}

function stopCount() {
	clearTimeout(t);
	timer_is_on = 0;
}

function timedCount() {
	if (lock_stat == 1) {
		document.getElementById("slider").onchange = function() {
			var value = document.getElementById('slider').getAttribute('data-slider');
			document.getElementById('qj').innerHTML = value;
			if (value > 80)
				document.getElementById('qj').style.backgroundColor = 'red';
			else
				document.getElementById('qj').style.backgroundColor = 'green';
			if (c > 0) {
				stopCount()
				c = 0;
			}
		};
		c = c + 10;
		if (c == 500) {
			if (tr == 0) {
				vibrate();
				document.getElementById("switch").style.background = "silver";
				tr = 1;
			} else {
				vibrate();
				document.getElementById("switch").style.background = "#16A085";
				tr = 0;
			}
		} else {
			document.addEventListener("touchend", function() {
				stopCount()
				c = 0;
			});
		}
		t = setTimeout(function() {
			timedCount()
		}, 10);
	} else
		document.addEventListener("touchend", function() {
			stopCount()
			c = 0;
		});
}

function vibrate() {
	window.navigator.vibrate(500);
}

function iconLock() {
	var check = document.getElementById('icon').className;
	if (check == 'fi-unlock') {
		if (drop_stat == 0)
			menuUp()
		document.getElementById('icon').className = "fi-lock";
		document.getElementById('slider').className += " disabled";
		document.getElementById("switch").style.background = 'red';
		lock_stat = 0;
	} else {
		document.getElementById('icon').className = "fi-unlock";
		document.getElementById("slider").className =
			document.getElementById("slider").className.replace(/(?:^|\s)disabled(?!\S)/g, '')
		document.getElementById("switch").style.background = '#16A085';
		lock_stat = 1;
	}
}
// document.getElementById("panel").addEventListener("touchmove", function(p){
// p.preventDefault()
// window.navigator.vibrate(15);
// });
// document.getElementById("left").addEventListener("touchstart", function(){
// document.getElementById("qj").innerHTML="levo";
// document.getElementById("left").style.background = "grey";
// window.navigator.vibrate(150);
// });
// document.getElementById("left").addEventListener("touchend", function(){
// document.getElementById("left").style.background = "#DDDDDD";
// });
// document.getElementById("right").addEventListener("touchstart", function(){
// document.getElementById("right").style.background = "grey";
// window.navigator.vibrate(150);
// document.getElementById("qj").innerHTML="desno";

// });
// document.getElementById("right").addEventListener("touchend", function(){
// document.getElementById("right").style.background = "#DDDDDD";
// });
document.getElementById("settings").addEventListener("touchend", function() {
	document.body.scrollTop = 0;
});
document.getElementById("off-canvas-prevent").addEventListener("touchmove", function(e) {
	e.preventDefault()
});<file_sep><?php
session_start();
include '/var/www/db_params.php';
//if(isset($_SESSION["logged"])){
while(1){
	$all_ip= array();
	$death_ip=array();
	$conn = new mysqli($host, $username, $password, $dbname);
	if($stmt = $conn->prepare("SELECT ip FROM incoming_data")){ //vzimam cenata ot db
		$stmt->execute();
		$stmt->bind_result($col);
		$n=0;
		while ($stmt->fetch()) {
			$all_ip[$n]=$col;
			$n++;
			}
		$stmt->close();
	}
	$allIp = implode(' ', $all_ip);
	exec("fping  -u -i 100 $allIp" , $death_ip);
	//echo print_r($death_ip);
	 /* for($i=0;$i<=$n-1;$i++){
		if($stmt = $conn->prepare("DELETE FROM incoming_data WHERE ip=?")){ //vzimam cenata ot db
			$stmt->bind_param("s",$death_ip[$i]);
			$stmt->execute();
			$stmt->close();
		}
		if($stmt = $conn->prepare("DELETE FROM devices WHERE ip=?")){ //vzimam cenata ot db
			$stmt->bind_param("s",$death_ip[$i]);
			$stmt->execute();
			$stmt->close();
		}
	}  */
	 $conn->close();
	 sleep(1);
}
//}
?><file_sep># open-automation
Piece of software that provides full control and monitoring over power appliances from around the world over internet
___
![Alt text](2.jpg?raw=true "Title")
<file_sep><?php
session_start();  
include '/var/www/db_params.php'; //proverka i vzima na stoinosti ot zaqvkata
$pos=$_GET["pos"];
$id=$_GET["id"];
if(isset($_SESSION["logged"])){ 
$value="";
$conn = new mysqli($host, $username, $password, $dbname);
if($pos==1){
if($stmt = $conn->prepare("UPDATE devices SET time_on=(?) WHERE id=(?)")){
	$stmt->bind_param("ii",$value,$id);
	$stmt->execute();
}
if($stmt = $conn->prepare("UPDATE months_consumption SET time_on=(?) WHERE id_hs=(?)")){
	$stmt->bind_param("ii",$value,$id);
	$stmt->execute();
}
$conn->close();
}
else if($pos==2){
if($stmt = $conn->prepare("UPDATE devices SET time_on_second=(?) WHERE id_second=(?)")){
	$stmt->bind_param("ii",$value,$id);
	$stmt->execute();
}
if($stmt = $conn->prepare("UPDATE months_consumption SET time_on_second=(?) WHERE id_second_hs=(?)")){
	$stmt->bind_param("ii",$value,$id);
	$stmt->execute();
}
$conn->close();
}
}
?><file_sep><?php
$fn_type0="lc_btn"; //ime na funkciq za kliuch za lampa
$fn_type1="sct_btn";//za razklonitelq
$fn_type2="video_panel";//kameri
$fn_type3="led_panel";//led panel
$fn_type4="touch_pad";//touch pad
//=======================
$dv_type0="LC";//kratki naimenovaniq
$dv_type1="SCT";
$dv_type2="VIDEO";
$dv_type3="LED";
$dv_type4="TOUCH";
?><file_sep><?php
session_start();
include '/var/www/db_params.php';
if(isset($_SESSION["logged"])){
$ip_cam = array();
$cam_label = array();
$n=0;
$conn = new mysqli($host, $username, $password, $dbname);
$stmt = $conn->prepare("SELECT ip,label FROM cameras"); //vziamm infoto ot db za kamerite
$stmt->execute();
$stmt->bind_result($col,$col1);
while ($stmt->fetch()) {
	$array=array(
				'cam_ip' => $col, //slagam v masiv
				'label' => $col1,
			);
$return[]=$array;
}
$stmt->close();
echo json_encode($return); //encodvam v json i prashtam
}
?><file_sep><?php
session_start();//startiram sesiq
include '/var/www/db_params.php';
if(isset($_GET['ip'],$_GET["name"],$_GET["port"],$_GET["stat"])){ //proverqvam za zadadeni stoinosti
	$name=$_GET["name"];
	$ip=$_GET["ip"];
	$port=$_GET["port"];
	$stat=$_GET["stat"];
	$ip_cam= array();
	$port_cam= array();
	$label_cam= array();
	if(isset($_SESSION["logged"])){ //proverqm dali si lognat
		$conn = new mysqli($host, $username, $password, $dbname);
		if($stat==0){
			$stmt = $conn->prepare("INSERT INTO cameras (ip,label,port) VALUES (?,?,?) ON DUPLICATE KEY UPDATE label=?"); //zapisvam  informaciqta
			$stmt->bind_param("ssis", $ip,$name,$port,$name);
			$stmt->execute();
		//	echo "Камерата е добавена!";
		}
		else if($stat==1){
			$stmt = $conn->prepare("DELETE FROM cameras WHERE ip=? AND port=?"); //triq informaciq
			$stmt->bind_param("si", $ip,$port);
			$stmt->execute();	
			//echo "Камерата е премахната!";
		}
		$stmt = $conn->prepare("SELECT ip,port,label FROM cameras");
		$stmt->execute();	
		$stmt->bind_result($col,$col1,$col2);
		$n=0;
		while ($stmt->fetch()) {
			$ip_cam[$n]=$col;
			$port_cam[$n]=$col1;
			$label_cam[$n]=$col2;
			$n++;
		}
		if(array_filter($ip_cam)){
echo <<<EOT
	<table style=width:100%>
		<tr>
			<td>Адрес</td>
			<td>Порт</td>		
			<td>Име</td>	
	</tr>
EOT;
for($u=0;$u<=$n-1;$u++){
	echo <<<EOT
	<tr>
		<td>$ip_cam[$u]</td>
		<td>$port_cam[$u]</td>	
		<td>$label_cam[$u]</td>		
	</tr>
EOT;
}
echo "</table>";
		}
		else
			echo "Няма добавени камери!";
$stmt->close();
$conn->close();
}
}
?><file_sep><?php
session_start();
if(isset($_SESSION["logged"])){ //proverka koi e lognat
include '/var/www/db_params.php';
$conn = new mysqli($host, $username, $password, $dbname); //vruzka kum db
if ($conn->connect_error) {
	die("Connection failed: " . $conn->connect_error);
}
//header("Access-Control-Allow-Origin:*");
if($stmt = $conn->prepare("SELECT ip,data,k1,k2 FROM incoming_data")){ //vzimam vsicko kakvoto e zapisano v db
	$stmt->execute();
	$stmt->bind_result($col,$col1,$col2,$col3);
	while ($stmt->fetch()) {
		$array=array( //slagom go v masiv
					'ip' => $col,
					'data' => $col1,
					'k1' => $col2,
					'k2' => $col3,
				);
				$return[]=$array;
	}
	$stmt->close();
}
$conn->close();
if(!empty($return))
echo json_encode($return); //encodvam i prashtam
}
?>
