camImagesProcess
|
Сортировка изображений с веб-камеры
DebMes("camImagesProcess");
$src=SERVER_ROOT.'/media/webcam'; // откуда брать фотографии
clearTimeout('camImagesTimer');
$base_path=SERVER_ROOT.'/dvr/unsorted';
$dst=SERVER_ROOT.'/dvr/sorted';
safe_exec('chown pi:pi -Rf '.$base_path.'/*');
safe_exec('chmod 0777 -f '.$base_path.'/*');
setTimeout('camImagesTimer','runScript("camImagesProcess");',10*60);
if (is_dir($base_path)) {
if ($dir = @opendir($base_path)) {
while (($file = readdir($dir)) !== false) {
if ($file!='.' && $file!='..' && is_dir($base_path.'/'.$file)) {
$src=$base_path.'/'.$file;
echo $src.'<br/>';
processLine($src." -> ".$dst."/%Y/%m - %F/%d/".$file);
}
}
closedir($dir);
}
} else {
echo "Cannot open $base_path";
}
processLine("CLEAR ".$dst." 30 DAYS OLD");
|
checkFreeSpace
|
Проверка свободного места на диске
DebMes("checkFreeSpace");
$max_usage=90; //%
$output=array();
exec('df',$output);
//var_dump($output);
$problems=0;
$problems_details='';
foreach($output as $line) {
if (preg_match('/(\d+)% (\/.+)/',$line,$m))
$proc=$m[1];
$path=$m[2];
if ($proc>$max_usage) {
$problems++;
$problems_details.="$path: $proc; ";
}
//echo "$path: $proc%<br/>";
}
sg("ThisComputer.SpaceProblems",$problems);
sg("ThisComputer.SpaceProblems_Details",$problems_details);
setTimeOut('checkFreeSpace','runScript("checkFreeSpace");',5*60);
|
rebootSystem
|
Перезапуск системы
DebMes("rebootSystem");
$filename = ROOT . '/database_backup/db.sql';
$mysqlDumpPath = "/usr/bin/mysqldump";
$mysqlDumpParam = " --user=" . DB_USER . " --password=" . DB_PASSWORD;
$mysqlDumpParam .= " --no-create-db --add-drop-table --databases " . DB_NAME;
if (file_exists($filename)) rename($filename, $filename . '.prev');
exec($mysqlDumpPath . $mysqlDumpParam . " > " . $filename);
say("Подготовка к перезагрузке",2);
setTimeout("shutdownTimer","safe_exec('shutdown -r now');",15);
|
shutDown
|
Выключение системы
DebMes("shutDown");
$filename = ROOT . '/database_backup/db.sql';
$mysqlDumpPath = "/usr/bin/mysqldump";
$mysqlDumpParam = " --user=" . DB_USER . " --password=" . DB_PASSWORD;
$mysqlDumpParam .= " --no-create-db --add-drop-table --databases " . DB_NAME;
if (file_exists($filename)) rename($filename, $filename . '.prev');
exec($mysqlDumpPath . $mysqlDumpParam . " > " . $filename);
say("Подготовка к выключению",2);
setTimeout("shutdownTimer","safe_exec('shutdown -h now');",15);
|
Выключить кнопку потопа
|
DebMes("Выключить кнопку потопа");
|
LightThiefGame
|
DebMes("LightThiefGame");
$curent_status = gg('ThisComputer.thiefStatus');
if (!$curent_status) return;
$maxLightOnCounts = 3;
$Lights = array();
$objects=getObjectsByClass("SRelays");
foreach($objects as $obj) {
if (gg($obj['TITLE'].".thief") == 1) {
$Lights[$obj['TITLE']] = $obj;
}
}
if (!$Lights) return;
$Params = gg('ThisComputer.theifParams');
if (!$Params) $Params = array();
else $Params = unserialize($Params);
if (!$Params) {
foreach($Lights as $k=>$obj) {
if (gg($obj['TITLE'].".status") == 1) {
cm($obj['TITLE'].".switch");
}
}
}
$currentLightOn = array();
foreach ($Params as $k=>$item) {
if ($item['stime'] > time()) {
$currentLightOn[$item['title']] = true;
unset($Lights[$item['title']]);
cm($item['title'].'.turnOn');
} else {
cm($item['title'].'.turnOff');
unset($Params[$k]);
}
}
$currentLightOnCount = count($currentLightOn);
$currentHour = (int)date('G',time());
$maxTimeOn = 50;
$rand_roll = 0;
if (time() >= gg("ow_fact.sunrise") && time() <= gg("ow_fact.sunset")-30*60) {
$rand_roll = 0;
$maxTimeOn = 0;
} elseif ($currentHour > 2 && $currentHour < 8) {
$rand_roll = ($currentLightOnCount == 0 ? 0.1 : ($currentLightOnCount == 1 ? 0.05 : ($currentLightOnCount == 2 ? 0.01 : 0) ) );
$maxTimeOn = 600;
} else {
$rand_roll = ($currentLightOnCount == 0 ? 0.4 : ($currentLightOnCount == 1 ? 0.2 : ($currentLightOnCount == 2 ? 0.05 : 0.05) ) );
$maxTimeOn = 3600;
}
$RandLight = '';
$RandSec = 0;
if (rand(0,100000)/100000 <= $rand_roll && $currentLightOnCount < $maxLightOnCounts) {
$RandLight = array_rand($Lights);
$RandSec = rand(50,$maxTimeOn);
$Params[] = array(
'title' => $RandLight,
'stime' => time()+$RandSec,
);
cm($RandLight.'.turnOn');
unset($Lights[$RandLight]);
}
sg('ThisComputer.theifParams',serialize($Params));
|
manageConnectService
|
Включение/выключение сервиса синхронизации через облако
DebMes("manageConnectService");
include_once(DIR_MODULES.'connect/connect.class.php');
$cn=new connect();
$cn->getConfig();
if ($params['start']) {
$cn->config['CONNECT_SYNC']='1';
$cn->saveConfig();
}
if ($params['stop']) {
$cn->config['CONNECT_SYNC']='0';
$cn->saveConfig();
}
echo $cn->config['CONNECT_SYNC'];
|
manageWebCamMotion
|
Включение/выключение детектора движений на камере
DebMes("manageWebCamMotion");
if ($params['start']) {
DebMes("Starting web-cam motion detection");
if ( gg("ThisComputer.WebCamMotionAuto") == 1) {
sg("ThisComputer.WebCamMotion","1");
}
//getURL('http://localhost:8080/0/detection/start',0);
}
if ($params['stop']) {
DebMes("Stopping web-cam motion detection");
sg("ThisComputer.camera1_file","");
if ( gg("ThisComputer.WebCamMotionAuto") == 1) {
sg("ThisComputer.WebCamMotion","0");
}
//getURL('http://localhost:8080/0/detection/pause',0);
}
|
manageWebCamService
|
Включение/выключение вебкамеры
DebMes("manageWebCamService");
if ($params['start']) {
//safe_exec('cp /etc/motion/motion_enabled /etc/default/motion');
//safe_exec('service motion start');
}
if ($params['stop']) {
//safe_exec('cp /etc/motion/motion_disabled /etc/default/motion');
//safe_exec('service motion stop');
}
|
MotionFromCamera
|
DebMes("MotionFromCamera");
include_once(DIR_MODULES . 'telegram/telegram.class.php');
$telegram_module = new telegram();
if (!gg("ThisComputer.WebCamMotion") && gg("ThisComputer.TelegramMotionDetected_".$_GET['cam'])) {
sg("ThisComputer.TelegramMotionDetected_".$_GET['cam'],0);
}
if ($_GET['Motion'] && gg("ThisComputer.WebCamMotion")) {
if (gg("ThisComputer.TelegramMotionDetected_".$_GET['cam']) < (time()-3600)) {
sg("ThisComputer.TelegramMotionDetected_".$_GET['cam'],time());
$telegram_module->sendMessageToAdmin("Обнаружено движение на камере ".$_GET['cam']."!");
if ($_GET['file']) {
$file_data = file_get_contents('http://192.168.1.201'.$_GET['file']);
if ($file_data) {
file_put_contents(SERVER_ROOT.'/tmp/'.basename($_GET['file']),$file_data);
$telegram_module->sendFileToAdmin(SERVER_ROOT.'/tmp/'.basename($_GET['file']));
}
}
}
}
if (gg("ThisComputer.WebCamMotion") && $_GET['Storage'] && $_GET['file']) {
$file_data = file_get_contents('http://192.168.1.201'.$_GET['file']);
if ($file_data) {
file_put_contents(SERVER_ROOT.'/tmp/'.basename($_GET['file']),$file_data);
$telegram_module->sendFileToAdmin(SERVER_ROOT.'/tmp/'.basename($_GET['file']));
}
}
|
NobodyHomeCheck
|
DebMes("NobodyHomeCheck");
if (gg('ThisComputer.NobodyHome') == 0) return;
if (gg("NobodyHomeMode.active") == 1) return;
//say('Никого нети дома. Проверяем выключатели!',2);
$objects=getObjectsByClass("SRelays");
foreach($objects as $obj) {
if (gg($obj['TITLE'].".status") == 1) {
sg('ThisComputer.NobodyHomeCheckCron',time());
break;
}
}
$currentHour = (int)date("G",time());
if ($currentHour >= min(21,(int)date("G",gg("ow_fact.sunset"))) && $currentHour <=21) {
if (gg('ThisComputer.NobodyHomeCheckCron') < time()-3600) {
cm('NobodyHomeMode.activate');
}
}
|
ElectroCounter
|
DebMes("ElectroCounter");
$t1 = gg('ThisComputer.ElectroT1');
$t2 = gg('ThisComputer.ElectroT2');
//$t3 = gg('ThisComputer.ElectroT3');
$H = date('G',time());
if ($H>=7 && $H<23) $t1++;
elseif ($H>=23 || $H<7) $t2++;
/*
if (($H>=7 && $H<10) || ($H>=17 && $H<21)) $t1++;
elseif (($H>=10 && $H<17) || ($H>=21 && $H<23)) $t3++;
elseif ($H>=23 || $H<7) $t2++;
*/
sg('ThisComputer.ElectroT1',$t1);
sg('ThisComputer.ElectroT2',$t2);
//sg('ThisComputer.ElectroT3',$t3);
sg('ThisComputer.ElectroT1_show',round($t1/2000,3));
sg('ThisComputer.ElectroT2_show',round($t2/2000,3));
//sg('ThisComputer.ElectroT3_show',round($t3/2000,3));
|
Hourly
|
Выполняется каждый час
DebMes("Hourly");
echo "OK";
/*
if (gg("Sensor_humidity03.updated") < time()-30*60 || gg("Sensor_temp04.updated") < time()-30*60 ) {
include_once(DIR_MODULES . 'telegram/telegram.class.php');
$telegram_module = new telegram();
$telegram_module->sendMessageToAll("На переноске села батарейка. Последнее обновление: ".date("Y-m-d H:i:s",max(gg("Sensor_temp04.updated"),gg("Sensor_humidity03.updated"))));
}
*/
// оптимизируем историю GPS
getURL(BASE_URL.'/panel/popup/app_gpstrack.html?optimize_log=1', 0);
|
iPhoneBatteryCheck
|
DebMes("iPhoneBatteryCheck");
$iphones = array(
5 => 11,
6 => 13,
7 => 19
);
foreach($iphones as $userId=>$iPhoneId) {
$iPhone = SQLSelectOne('SELECT * FROM idevices WHERE ID='.$iPhoneId);
if (!$iPhone) continue;
$text = false;
if ($iPhone['BATTERY_LEVEL'] >= 30 || $iPhone['BATTERY_STATUS']) {
sg('ThisComputer.iBattery_'.$iPhoneId, "{}");
continue;
}
$status = gg('ThisComputer.iBattery_'.$iPhoneId);
if (!$status) $status = "{}";
$status = json_decode($status,1);
if ($iPhone['BATTERY_LEVEL'] < 30 && !$status['b30']) {
$status['b30'] = 1;
$text = true;
}
if ($iPhone['BATTERY_LEVEL'] < 20 && !$status['b20']) {
$status['b20'] = 1;
$text = true;
}
if ($iPhone['BATTERY_LEVEL'] < 10 && !$status['b10']) {
$status['b10'] = 1;
$text = true;
}
if ($iPhone['BATTERY_LEVEL'] < 5 && !$status['b5']) {
$status['b5'] = 1;
$text = true;
}
if ($text) {
$text = 'Уровень зарадки устройства "'.$iPhone['NAME'].'" меньше '.$iPhone['BATTERY_LEVEL'].'% Нужно поставить на зарядку!';
say($text, 2);
}
sg('ThisComputer.iBattery_'.$iPhoneId, json_encode($status));
}
|
iPhoneOnlineCheck
|
DebMes("iPhoneOnlineCheck");
$anybodyHome = false;
$locationName = 'Дом';
$devices = array(
'iPhone_AKEB' => array(
'macAddress' => '48:4B:AA:0F:E8:7C',
'ipAddress' => '192.168.1.3',
'userObject' => 'AKEB',
'bluetoothObjects' => 'iPhone_AKEB',
),
'iPhone_Tikovka' => array(
'macAddress' => 'B8:53:AC:A1:65:71',
'ipAddress' => '192.168.1.4',
'userObject' => 'Marianna',
'bluetoothObjects' => 'iPhone_Tikovka',
),
'iPhone_Polina' => array(
'macAddress' => '0C:51:01:25:A8:74',
'ipAddress' => '192.168.1.5',
'userObject' => 'Polina',
'bluetoothObjects' => 'iPhone_Polina',
),
);
foreach($devices as $device) {
$offline = true;
$old_status = cm($device['userObject'].'.atHome');
if ($device['bluetoothObjects']) {
$bluetooths = explode(',',$device['bluetoothObjects']);
foreach($bluetooths as $bluetooth) {
$on = gg($bluetooth.'.online');
$up = gg($bluetooth.'.lastTimestamp');
if ($on && $up+60 > time()) $offline = false;
}
}
if ($offline) {
$loc = gg($device['userObject'].'.seenAt');
list($h,$i) = explode(':',gg($device['userObject'].'.CoordinatesUpdated'));
$sec = $h*60 + $i;
$now = date('H')*60+date('i');
if ($loc == $locationName && $sec+5*60 > $now) $offline = false;
}
if ($offline && $device['ipAddress']) {
$ips = explode(',',$device['ipAddress']);
foreach($ips as $ip) {
$res=exec('sudo arping -c 2 -i eth0 '.$ip.' -D');
if (strpos($res,'!') !== false) $offline = false;
}
}
if ($offline && $device['macAddress']) {
$macs = explode(',',$device['macAddress']);
foreach($macs as $mac) {
$res=exec('sudo arping -c 2 -i eth0 '.$mac.' -D');
if (strpos($res,'!') !== false) $offline = false;
}
}
if (!$offline) {
$anybodyHome = true;
cm($device['userObject'].'.gotHome');
} else {
cm($device['userObject'].'.outOfHome');
}
}
if ($anybodyHome) {
DebMes("Кто-то дома из устройств");
setGlobal('ThisComputer.NobodyHomeCheckCron', time());
if (gg('ThisComputer.nobodyHome') != 0) {
say('Кто-то дома из устройств. Ставлю статус nobodyHome=0',2);
setGlobal('ThisComputer.nobodyHome',0);
}
$status = gg('NobodyHomeMode.active');
if ($status) {
say('Отключаю режим никого нет дома. Так как какое-то устройтсво дома',2);
DebMes("Отключаю режим никого нет дома. Так как какое-то устройтсво дома");
cm('NobodyHomeMode.deactivate');
}
} else {
DebMes("Никого нет дома из устройств");
if (gg('ThisComputer.nobodyHome') != 1) {
say('Никого нет дома из устройств. Ставлю статус nobodyHome=1',2);
setGlobal('ThisComputer.nobodyHome',1);
}
}
|
loadavg
|
DebMes("loadavg");
$data=trim(exec("cat /proc/loadavg"));
$data = explode(" ",$data);
setGlobal("ThisComputer.loadavg0",$data[0]);
setGlobal("ThisComputer.loadavg1",$data[1]);
setGlobal("ThisComputer.loadavg2",$data[2]);
setGlobal("ThisComputer.loadavg3",$data[3]);
$data=trim(exec("cat /sys/class/thermal/thermal_zone0/temp"));
setGlobal("ThisComputer.TempCpu",round($data/1000,2));
|
Minutes
|
DebMes("Minutes");
runScript("Samsung_refresh_status");
//runScript("PlayXiRadio");
runScript("NobodyHomeCheck");
runScript("LightThiefGame");
runScript("loadavg");
runScript("weatherReceived");
runScript("motionDetected");
runScript("iPhoneBatteryCheck");
runScript("iPhoneOnlineCheck");
|
motionDetected
|
Проверка датчика движения на камере
DebMes("motionDetected");
//DebMes("Motion detected: ".serialize($params));
//callMethod('MotionSensorCam.motionDetected');
//setTimeOut('motionDetectedTimer','runScript("camImagesProcess");',10);
//if (getGlobal('ThisComputer'.'.'.'WebCamMotionAuto')) {
// setTimeOut('stopWebCamDetection', " runScript('manageWebCamMotion', array('stop'=>'1'));", (int)('60'));
//}
include_once(DIR_MODULES . 'telegram/telegram.class.php');
$telegram_module = new telegram();
if (!gg("ThisComputer.WebCamMotion")) {
sg("ThisComputer.TelegramMotionDetected",0);
}
$file_name = gg("ThisComputer.camera1_file");
if ($file_name && gg("ThisComputer.WebCamMotion")) {
$file_data = file_get_contents('http://camera1.akeb.ru/'.$file_name);
if ($file_data) {
sg("ThisComputer.camera1_file","");
file_put_contents(SERVER_ROOT.'/tmp/motion.mp4',$file_data);
$telegram_module->sendFileToAdmin(SERVER_ROOT.'/tmp/motion.mp4');
sg("ThisComputer.camera1_lastfile",$file_name);
//cm("NobodyHomeMode.deactivate");
$file_name = null;
}
}
if (!$file_name) {
$data = file_get_contents("http://camera1.akeb.ru/motion");
//$data = "record/2017Y07M31D02H/15M00S.mp4";
$data = trim($data);
if ($data) {
DebMes("Motion detected: ".$data);
}
if ($data && gg("ThisComputer.WebCamMotion")) {
$last_file_name = gg("ThisComputer.camera1_lastfile");
if ($last_file_name != $data) {
if (gg("ThisComputer.TelegramMotionDetected") < (time()-3600)) {
sg("ThisComputer.TelegramMotionDetected",time());
$telegram_module->sendMessageToAdmin("Обнаружено движение!");
}
sg("ThisComputer.camera1_file",$data);
}
}
}
|
NobodyHome
|
Срабатывает, когда никого дома нет
DebMes("NobodyHome");
say('Включаю режим экономии', 2);
cm("EconomMode.activate");
if (gg("ThisComputer.WebCamMotionAuto")) {
runScript('manageWebCamMotion', array('start'=>'1'));
}
runScript('Обман для воров', array('start'=>'1'));
|
PlayXiRadio
|
DebMes("PlayXiRadio");
/*
$lastUpdate = gg("Xiaomigateway.lastUpdateRadio");
if ($lastUpdate+5*60 < time()) {
sg('Xiaomigateway.status', "pause");
$res = file_get_contents('http://192.168.1.200/ajax/xiaomimiio.html?op=test_api_cmd&dip=192.168.1.18&dtoken=17ce80fed0b42f279d533ff3de787966&dcmd=play_specify_fm&dopt={"id":10005,"type":0,"url":"http://192.168.1.200/hls/live1.m3u8"}');
DebMes('PlayXiRadio '.$res);
sg("Xiaomigateway.lastUpdateRadio", time());
$volume = 0;
$h = date('H');
if ($h >= 0 && $h < 8) $volume = 0;
elseif ($h >= 8 && $h < 10) $volume = 50;
elseif ($h >= 10 && $h < 21) $volume = 100;
elseif ($h >= 21 && $h < 22) $volume = 50;
elseif ($h >= 22 && $h < 23) $volume = 30;
elseif ($h >= 23 && $h < 0) $volume = 0;
sg('Xiaomigateway.volume',$volume);
}
*/
|
Samsung_refresh_status
|
DebMes("Samsung_refresh_status");
$objects=getObjectsByClass("SamsungTV");
foreach($objects as $obj) {
callMethod($obj['TITLE'].".refresh_status");
}
|
SomebodyHome
|
Срабатывает в том случае, когда кто-то появился дома
DebMes("SomebodyHome");
callMethod("EconomMode.deactivate");
say('Здравствуйте!', 2);
runScript('reportStatus', array());
if (getGlobal("ThisComputer.WebCamMotionAuto")) {
runScript('manageWebCamMotion', array('stop'=>'1'));
}
runScript('Обман для воров', array('stop'=>'1'));
setGlobal("ThisComputer.NobodyHomeCheckCron", time());
|
startUp
|
Система загружена
DebMes("startUp");
say('Система загружена', 2);
runScript('tellIPAddress', array());
|
turnOffEverything
|
Выключить все приборы
DebMes("turnOffEverything");
$objects=array(
'Light_01','Light_02','Light_03','Light_04',
'Light_05','Light_06','Light_07','Light_08',
'Light_09','Light_10','Light_11','Light_12',
'Light_13','Light_14'
);
foreach($objects as $o) {
$obj = getObject($o);
// if($obj->getProperty('status')) {
$obj->callMethod('turnoff');
// }
}
|
Кто-то дома по Событию
|
DebMes("Кто-то дома по Событию");
$status = gg('NobodyHomeMode.active');
if ($status) {
cm('NobodyHomeMode.deactivate');
}
|
Обман для воров
|
Включать и выключать рандомно свет
DebMes("Обман для воров");
$Lights = array();
$objects=getObjectsByClass("SRelays");
foreach($objects as $obj) {
if (gg($obj['TITLE'].".thief") == 1) {
$Lights[$obj['TITLE']] = $obj;
}
}
$curent_status = gg('ThisComputer.thiefStatus');
if ($params['start'] && count($Lights) > 0 && $curent_status < 1) {
$old_status = array();
foreach ($Lights as $obj) {
$old_status[$obj['TITLE']] = gg($obj['TITLE'].".status");
}
sg('ThisComputer.thiefOldLightStatus',serialize($old_status));
sg('ThisComputer.thiefStatus',1);
}
if ($params['stop'] && count($Lights) > 0 && $curent_status > 0) {
$old_status = unserialize(gg('ThisComputer.thiefOldLightStatus'));
foreach ($Lights as $obj) {
if (gg($obj['TITLE'].".status") != $old_status[$obj['TITLE']]) {
cm($obj['TITLE'].".switch");
}
}
sg('ThisComputer.thiefOldLightStatus',serialize(array()));
sg('ThisComputer.thiefStatus',0);
sg('ThisComputer.theifParams','');
}
|
Резервное копирование
|
DebMes("Резервное копирование");
$state=$params['STATE'];
$desc=$params['DESCRIPTION'];
include_once(DIR_MODULES . 'telegram/telegram.class.php');
$telegram_module = new telegram();
$message = "Резервное копирование\nСтатус: <b>".$state."</b>";
if ($desc) $message .= "\nОписание:".$desc;
$telegram_module->sendMessageToAdmin($message);
|