BeforeSay
|
Выполнить пере тем как say
// Пригдлушаем радио
//cm("RadioSetting.Mute");
// Возобновляем радио после 10 сек
//setTimeOut("afterSayTimer", 'cm("RadioSetting.UnMute");', 10);
|
iiiBot
|
iii
define('BOT_TOKEN', '8a5526de-f601-4f35-ba33-70ce385fffcb'); //Идентификатор бота с iii.ru
class Bot {
protected $key = null;
protected $session = null;
private $salt = 'some very-very long string without any non-latin characters due to different string representations inside of variable programming languages';
/**
* @param $key - Ключ из урла после создания инфа
*/
public function __construct($key) {
$this->key = $key;
}
/**
* @param null $session - Идентификатор сессии существуюющей, если нет то создается новая
* @return string Идентификатор текущей сессии
*/
public function session($session = null) {
if ($session === null) {
$response = file_get_contents('http://iii.ru/api/2.0/json/Chat.init/' . $this->key . '/');
$this->session = $this->decode($response)->result->cuid;
} else {
$this->session = $session;
}
return $this->session;
}
/**
* ОТправить сообщение боту
* @param string $message Сообщение
* @return string Ответ
*/
public function say($message) {
$request = '["' . $this->session . '","' . $message . '"]';
$myCurl = curl_init();
curl_setopt_array($myCurl, array(
CURLOPT_URL => 'http://iii.ru/api/2.0/json/Chat.request',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $this->encode($request)
));
$response = curl_exec($myCurl);
curl_close($myCurl);
return $this->decode($response)->result->text->tts;
}
/**
* Кодирование сообщения
* @param $message
* @return string
*/
private function encode($message) {
$message = base64_encode($message);
$ml = strlen($message);
$kl = strlen($this->salt);
$encoded = "";
for ($i = 0; $i < $ml; $i++) {
$encoded = $encoded . ($message[$i] ^ $this->salt[$i % $kl]);
}
return base64_encode($encoded);
}
/**
* Декодирование сообщения
* @param $message
* @return mixed|null
*/
private function decode($message) {
$msg = base64_decode($message);
$ml = strlen($msg);
$kl = strlen($this->salt);
$decoded = "";
for ($i = 0; $i < $ml; $i++) {
$decoded.= ($msg[$i] ^ $this->salt[$i % $kl]);
}
return json_decode(base64_decode($decoded));
}
}
if ($params['message']) {
$sessionId = gg('ThisComputer.iiiBotSessionId');
$message = $params['message'];
$bot = new Bot(BOT_TOKEN);
if ($sessionId == '') {
$session = $bot->session();
sg('ThisComputer.iiiBotSessionId', $session);
} else {
$session = $bot->session($sessionId);
}
$response = $bot->say($message);
say($response);
}
|
Moon
|
include_once("./MoonPhase.php");
// create an instance of the class, and use the current time
$moon = new MoonPhase();
//$age = round( $moon->age(), 1 );
$age = round( $moon->age(), 0 );
$stage = $moon->phase() < 0.5 ? 'растущая' : 'убывающая';
$distance = round( $moon->distance(), 2 );
$nextnewtime = gmdate( 'G:i:s', $moon->next_new_moon() );
$nextnewdate = gmdate( 'd.m.Y', $moon->next_new_moon() );
$nextfulltime = gmdate( 'G:i:s', $moon->next_full_moon() );
$nextfulldate = gmdate( 'd.m.Y', $moon->next_full_moon() );
$phasename = $moon->phase_name();
sg('Moon.Age',$age); //Возраст луны (лунный день)
sg('Moon.Stage',$stage); //Стадия луны
sg('Moon.Distance',$distance); //Дистанция до луны
sg('Moon.NextNewTime',$nextnewtime); //Время следующего полнолуния
sg('Moon.NextNewDate',$nextnewdate); //Новолуние
sg('Moon.NextFullTime',$nextfulltime); //Длительность лунного дня
sg('Moon.NextFullDate',$nextfulldate); //Дата следующего полнолуния
sg('Moon.PhaseName',$phasename); //Фаза луны
$illumination = round( $moon->illumination()*100, 2 );
sg('Moon.Phase',$illumination); //Фаза луны %
|
RadioHi
|
Радио громче на 10%
$vol = gg("RadioSetting.VolumeLevel");
if ($vol < 100){
cm('RadioSetting.Control',array('vol'=> $vol+10 ));
} else {
cm('RadioSetting.Control',array('vol'=> 100 ));
}
|
RadioLow
|
Радио тише
$vol = gg("RadioSetting.VolumeLevel");
if ($vol > 10){
cm('RadioSetting.Control',array('vol'=> $vol-10 ));
} else {
cm('RadioSetting.Control',array('vol'=> 0 ));
}
|
RadioOff
|
Выключить радио
cm('RadioSetting.Control',array('cmd'=>'stop'));
|
RadioOn
|
Включение радио
//say("Вы просили включить радио.");
cm('RadioSetting.Control',array('cmd'=>'play'));
|
ReadNews
|
Проговаривает последние новости
$last_id=getGlobal('ThisComputer.LastNewsId');
$values=SQLSelect("SELECT * FROM `rss_items` WHERE ID >".$last_id);
if($values) {
$total=count($values);
$maxnews = 30;
$startfrom = 0;
if ($total > $maxnews){
$startfrom = $total - $maxnews;
say("Новостей больше $maxnews");
} else {
say("Новости");
}
for($i=$startfrom;$i<$total;$i++){
$sql="SELECT * FROM `rss_items` WHERE ID =".$values[$i]['ID'];
$value=SQLSelectOne($sql);
say($value['TITLE'].".");
};
$last_id=$value['ID'];
setGlobal('ThisComputer.LastNewsId',$last_id);
} else {
say("Нет новых новостей");
};
|
StopMedia
|
Останавливает все проигрывания звуков и выключает телики
// Выключить радио
cm('RadioSetting.Control',array('cmd'=>'stop'));
// Телек у тони
include_once(DIR_MODULES.'app_smarttv/app_smarttv.class.php');
$smartTv=new app_smarttv();
$smartTv->control('TonjaTv','sendCode', 1);
|
VkMusic
|
Прослушивание музыки Вконтакте
$token = 'e68c144006a1d3757ddaba6e85020c5610c178fe60920c722d222fc4949f3f55a0061faa7e10ee60ea8eb';
if ($params['VALUE']) {
getURL('http://127.0.0.1/rc/?command=vlc_close', 0);
if (isset($params['COUNT'])) {
$trackCount = $params['COUNT'];
} else {
$trackCount = 1;
}
if ($params['MODE'] == 0) {
$uid = $params['VALUE'];
$link = 'https://api.vk.com/method/audio.get.xml?owner_id=' . urlencode($uid) . '&access_token=' . $token;
} elseif ($params['MODE'] == 1) {
$trackName = $params['VALUE'];
$link = 'https://api.vk.com/method/audio.search.xml?q=' . urlencode($trackName) . '&count=' . $trackCount . '&auto_complete=1&sort=2&access_token=' . $token;
} elseif ($params['MODE'] == 2) {
$performerName = $params['VALUE'];
$link = 'https://api.vk.com/method/audio.search.xml?q=' . urlencode($performerName) . '&count=' . $trackCount . '&auto_complete=1&performer_only=1&sort=2&access_token=' . $token;
} else {
if (isset($params['ALBUM'])) {
$uid = $params['VALUE'];
$link = 'https://api.vk.com/method/audio.getAlbums.xml?owner_id=' . urlencode($uid) . '&access_token=' . $token;
$res = getURL($link,0);
$xml = new SimpleXMLElement($res);
foreach ($xml->album as $item) {
if ($item->title == $params['ALBUM']) {
$albumId = $item->album_id;
break;
}
}
$link = 'https://api.vk.com/method/audio.get.xml?owner_id=' . urlencode($uid) . '&access_token=' . $token . '&album_id=' . $albumId;
}
}
//DebMes($link);
$res = getURL($link,0);
$xml = new SimpleXMLElement($res);
$tempPlaylist = sys_get_temp_dir() .DIRECTORY_SEPARATOR. "playlist.m3u";
$fp = fopen($tempPlaylist, "w");
fwrite($fp, '#EXTM3U' . "\r\n");
foreach ($xml->audio as $item) {
fwrite($fp, '#EXTINF:' . $item->duration . ', ' . $item->artist . ' - ' . $item->title . "\r\n");
fwrite($fp, $item->url . "\r\n");
fwrite($fp, "\r\n");
}
fclose($fp);
$play_terminal = "MAIN";
$url=BASE_URL.ROOTHTML.'popup/app_player.html?ajax=1&play_terminal='.$play_terminal.'&command=refresh&play=';
getURL($url.$tempPlaylist, 0);
//getURL('http://10.9.0.2/rc/?command=vlc_play¶m='.$tempPlaylist, 0);
}
|
kodi
|
Kodi info
$req='{"jsonrpc":"2.0","method":"GUI.ShowNotification","params":{"title":"'.$params["title"].'","message":"'.$params["message"].'"},"id":1}';
getURL("http://10.9.0.6/jsonrpc?request=".urlencode($req));
|
kodi_copy
|
Kodi info
$req='{"jsonrpc":"2.0","method":"System.OnSleep","params":{}';
getURL("http://10.9.0.6/jsonrpc?request=".urlencode($req));
|
Test34
|
|
test_0
|
//getURL('http://10.9.0.2/popup/app_101ru.html?&ajax=1&op=playstation&id=1224',0);
//setGlobal('PoolFilter.state', 0);
|
test_1
|
Тест функция истории
$dn = date("N");
// Среда и Воскресенье
if (($dn == 3) || ($dn == 7)) {
echo "ops";
say("Напоминаю: Нужно выбросить мусор");
}
|
timeNow
|
|
TonjaTVOn
|
magicPacket('10:08:C1:56:D7:3E');
function magicPacket($mac,$addr='255.255.255.255',$socket_number=7) {
//split up the mac address based upon the colons in the string
$addr_byte = explode(':', $mac);
$hw_addr = '';
for ($a=0; $a <6; $a++)
$hw_addr .=chr(hexdec($addr_byte[$a])); //convert the hex to its decimal equivalent, encode as a character, and repeat 16 times
$msg = str_repeat(chr(255),6); //FF in decimal is 255, which is then encoded as a char as with our mac address
for ($a = 1; $a <= 16; $a++)
$msg .= $hw_addr;
$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); //create our socket
if ($s == false) {
echo "Error creating socket!\n";
echo "Error code is '".socket_last_error($s)."'- " . socket_strerror(socket_last_error($s));
return false;
} else {
// setting a broadcast option to socket:
//$opt_ret = socket_set_option($s, 1, 6, TRUE);
$opt_ret = socket_set_option($s,SOL_SOCKET,SO_BROADCAST,true);
if($opt_ret <0) {
echo "setsockopt() failed, error: " . strerror($opt_ret) ."\n";
return false;
}
if(socket_sendto($s, $msg, strlen($msg), 0, $addr,$socket_number)) {
socket_close($s);
return true;
} else {
return false;
}
}
}
|
CheckOnline
|
Проверяет какие юзеры онлайн
// Проверка пользователей
$objects=getObjectsByClass("Users");
// переберем все объекты в класе
foreach($objects as $obj) {
$devices = getGlobal($obj['TITLE'].".deviceip");
$devarr = explode(";", $devices);
foreach ($devarr as $device) {
if (isOnline($device)){
callMethod($obj['TITLE'].".atHome");
break;
}
}
}
|
CheckTrack
|
Проверка треков почты
getURL('http://10.9.0.2/modules/app_postoffice/check_post.php', 0);
|
restart_md
|
Перезапуск циклов
echo shell_exec( 'sudo /var/www/md/restart.sh' );
|
sayTodayAgenda
|
Cкрипт, который по утрам может говорить запланированные на сегодня дела и события, используя данные из модуля Календарь
if (file_exists('./modules/app_calendar/app_calendar.class.php')) {
include_once('./modules/app_calendar/app_calendar.class.php');
$calendar=new app_calendar();
$calendar->usual($out);
$events=$out['EVENTS_TODAY'];
$say_phrase='';
if (is_array($events)) {
$total=count($events);
$tasks=array();
$cals=array();
for($i=0;$i<$total;$i++) {
if ($events[$i]['IS_TASK']=='1' && $events[$i]['IS_DONE']!='1') {
$tasks[]=$events[$i]['TITLE'];
} elseif ($events[$i]['IS_TASK'] !='1') {
$cals[]=$events[$i]['TITLE'];
}
}
// Tasks
$total_tasks=count($tasks);
if ($total_tasks) {
$say_phrase.="У вас на сегодня запланированы задачи. ";
for($i=0;$i<$total_tasks;$i++) {
$say_phrase.=($i+1).". ".$tasks[$i].". ";
}
} else {
say("Никаких дел не запланировано.");
}
// Events
$total_cals=count($cals);
if ($total_cals) {
$say_phrase.=("Сегодняшние события. ");
for($i=0;$i<$total_cals;$i++) {
$say_phrase.=$cals[$i].'. ';
}
}
}
$events=$out['EVENTS_PAST'];
if ($events[0]['TITLE']) {
$say_phrase.=" Так же напоминаю о пропущенных задачах. ";
$total_tasks=count($events);
for($i=0;$i<$total_tasks;$i++) {
$say_phrase.=($i+1).". ".$events[$i]['TITLE'].". ";
}
}
}
if ($say_phrase) {
say($say_phrase);
}
|
StartInit
|
Сбрасывет статусы датчиков при старте
// Reset rooms
$objects=getObjectsByClass("Rooms");
foreach($objects as $obj) {
clearTimeOut($obj['TITLE']."_activity_timeout");
callMethod($obj['TITLE'].".onIdle");
//setGlobal($obj['TITLE'].".SomebodyHere", 0);
}
// Reset movments sensors
$objects=getObjectsByClass("inhouseMovementSensors");
foreach($objects as $obj) {
setGlobal($obj['TITLE'].".status", 0);
setGlobal($obj['TITLE'].".statusText", "");
}
setGlobal("sensorMovementSUM.status", 0);
// Reset user has
$objects=getObjectsByClass("Users");
foreach($objects as $obj) {
clearTimeOut($obj['TITLE']."_inHome");
setGlobal($obj['TITLE'].".isHome", 0);
}
|
SysInfo
|
Чтение параметров системы
//CPU temp
exec( "sensors | grep 'Core' | cut -b15-23", $asensors );
$val = "";
foreach ($asensors as $itm){
if ($val != ""){ $val .= "/"; }
$val .= $itm;
}
setGlobal( "ThisComputer.CPU_temp", $val );
//$cpu_temp=shell_exec('cat /sys/class/thermal/thermal_zone0/temp') / 1000;
//$cpu_temp=round($cpu_temp,1);
//setGlobal("ThisComputer.CPU_temp",$cpu_temp);
//CPU usage
$cpu_usage=exec("top -bn 1 | awk '{print $9}' | tail -n +8 | awk '{s+=$1} END {print s}'");
setGlobal("ThisComputer.CPU_usage",$cpu_usage);
//System uptime
$sys_uptime=shell_exec("uptime");
$sys_uptime = explode(" up ", $sys_uptime);
$sys_uptime = explode(",", $sys_uptime[1]);
$sys_uptime = $sys_uptime[0].", ".$sys_uptime[1];
setGlobal("ThisComputer.System_uptime",$sys_uptime);
//Memory usage/total
$mem_total=exec("cat /proc/meminfo | grep MemTotal | awk '{print $2}'");
$mem_usage=$mem_total - exec("cat /proc/meminfo | grep MemFree | awk '{print $2}'");
$sys_memory=round($mem_usage * 100 / $mem_total, 1);
setGlobal("ThisComputer.System_memory",$sys_memory);
//Disk
$bytes = disk_free_space(".");
$si_prefix = array( 'B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB' );
$base = 1024;
$class = min((int)log($bytes , $base) , count($si_prefix) - 1);
$temp = round($bytes / pow($base,$class)) . ' ' . $si_prefix[$class];
sg('System_freespace',$temp);
|
systemMaintenance
|
Обслуживание системы
// Оптимизация новостей
SQLExec("DELETE FROM rss_items WHERE TO_DAYS(NOW())-TO_DAYS(ADDED)>3");
// Обслуживание базы и бекап
require(ROOT.'scripts/startup_maintenance.php');
|
TestUsers
|
Проверяет пользователи онлайн, пингами
$users = "";
$objects=getObjectsByClass("Users");
foreach($objects as $obj) {
$host = getGlobal($obj['TITLE'].".deviceip");
$fullname = getGlobal($obj['TITLE'].".fullName");
if ($host != ''){
$rec = SQLSelectOne("SELECT * FROM pinghosts WHERE HOSTNAME LIKE '".DBSafe($host)."' OR TITLE LIKE '".DBSafe($host)."'");
$hostname = $rec['HOSTNAME'];
$online=ping( $hostname );
//DebMes("TU: ".$host."-".$hostnam."=".$online);
if ($online){
if ($users != ""){ $users .= ", "; }
$users .= $fullname;
}
}
}
if ($users != ""){
say($users);
DebMes('Users:'.$users);
}
|
TorrentEvent
|
Сообщает о скаченном новом фильме на MediaCentr
Используется BASH скрипт для обнаружения новых фильмов на LostFilmTV
say('Скачен новый фильм:'.$params['file'], 2);
|
WOL
|
отправка "магического" пакета Wake-On-LAN (включение ноутбука)
magicPacket('E0:69:95:DD:C9:7E');
function magicPacket($mac,$addr='255.255.255.255',$socket_number=7) {
//split up the mac address based upon the colons in the string
$addr_byte = explode(':', $mac);
$hw_addr = '';
for ($a=0; $a <6; $a++)
$hw_addr .=chr(hexdec($addr_byte[$a])); //convert the hex to its decimal equivalent, encode as a character, and repeat 16 times
$msg = str_repeat(chr(255),6); //FF in decimal is 255, which is then encoded as a char as with our mac address
for ($a = 1; $a <= 16; $a++)
$msg .= $hw_addr;
$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); //create our socket
if ($s == false) {
echo "Error creating socket!\n";
echo "Error code is '".socket_last_error($s)."'- " . socket_strerror(socket_last_error($s));
return false;
} else {
// setting a broadcast option to socket:
//$opt_ret = socket_set_option($s, 1, 6, TRUE);
$opt_ret = socket_set_option($s,SOL_SOCKET,SO_BROADCAST,true);
if($opt_ret <0) {
echo "setsockopt() failed, error: " . strerror($opt_ret) ."\n";
return false;
}
if(socket_sendto($s, $msg, strlen($msg), 0, $addr,$socket_number)) {
socket_close($s);
return true;
} else {
return false;
}
}
}
|
WOL_test
|
отправка "магического" пакета Wake-On-LAN (включение ноутбука)
magicPacket('A8-F9-4B-24-5F-AF');
function magicPacket($mac,$addr='255.255.255.255',$socket_number=7) {
//split up the mac address based upon the colons in the string
$addr_byte = explode(':', $mac);
$hw_addr = '';
for ($a=0; $a <6; $a++)
$hw_addr .=chr(hexdec($addr_byte[$a])); //convert the hex to its decimal equivalent, encode as a character, and repeat 16 times
$msg = str_repeat(chr(255),6); //FF in decimal is 255, which is then encoded as a char as with our mac address
for ($a = 1; $a <= 16; $a++)
$msg .= $hw_addr;
$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); //create our socket
if ($s == false) {
echo "Error creating socket!\n";
echo "Error code is '".socket_last_error($s)."'- " . socket_strerror(socket_last_error($s));
return false;
} else {
// setting a broadcast option to socket:
//$opt_ret = socket_set_option($s, 1, 6, TRUE);
$opt_ret = socket_set_option($s,SOL_SOCKET,SO_BROADCAST,true);
if($opt_ret <0) {
echo "setsockopt() failed, error: " . strerror($opt_ret) ."\n";
return false;
}
if(socket_sendto($s, $msg, strlen($msg), 0, $addr,$socket_number)) {
socket_close($s);
return true;
} else {
return false;
}
}
}
|
WOL_work
|
отправка "магического" пакета Wake-On-LAN (включение ноутбука)
magicPacket('00:1E:8C:F1:3C:7F');
function magicPacket($mac,$addr='255.255.255.255',$socket_number=7) {
//split up the mac address based upon the colons in the string
$addr_byte = explode(':', $mac);
$hw_addr = '';
for ($a=0; $a <6; $a++)
$hw_addr .=chr(hexdec($addr_byte[$a])); //convert the hex to its decimal equivalent, encode as a character, and repeat 16 times
$msg = str_repeat(chr(255),6); //FF in decimal is 255, which is then encoded as a char as with our mac address
for ($a = 1; $a <= 16; $a++)
$msg .= $hw_addr;
$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); //create our socket
if ($s == false) {
echo "Error creating socket!\n";
echo "Error code is '".socket_last_error($s)."'- " . socket_strerror(socket_last_error($s));
return false;
} else {
// setting a broadcast option to socket:
//$opt_ret = socket_set_option($s, 1, 6, TRUE);
$opt_ret = socket_set_option($s,SOL_SOCKET,SO_BROADCAST,true);
if($opt_ret <0) {
echo "setsockopt() failed, error: " . strerror($opt_ret) ."\n";
return false;
}
if(socket_sendto($s, $msg, strlen($msg), 0, $addr,$socket_number)) {
socket_close($s);
return true;
} else {
return false;
}
}
}
|