Class properties:
Class methods:
Class objects:
// это однократный будильник, выключем его sg("AlarmOne.AlarmOn",0); // все проснулись setGlobal("SleepAllMode.active",0); $add_word=getGlobal('AlarmOne.AlarmText'); if ($add_word<>"") {say($add_word,5); } if (gg("AlarmOne.AlarmSound")) { playSound('alarm_num7'); //playSound('alarm_num7'); }
if (isWeekDay()) { // сегодня рабочий день // все проснулись setGlobal("SleepAllMode.active",0); $add_word=getGlobal('AlarmWeekDay.AlarmText'); say(timeNow()); say($add_word); sleep(2); runScript("sayTodayAgenda"); }
if (isWeekEnd()){ // сегодня выходной день // все проснулись setGlobal("SleepAllMode.active",0); say('Пора вставать!'); // включим радио // callMethod("Radio.RadioPlay"); // запланируем выключить радио через 25 минут // SetTimeOut("AlarmWeekEnd_RadioStop",'callMethod("Radio.RadioStop");', 60*25); // запланируем напоминание о точном времени и доклад погоды // SetTimeOut("AlarmWeekEnd_timeNow1",'callMethod("сколько время.action");', 60*30); // SetTimeOut("AlarmWeekEnd_Pogoda", 'callMethod("погода на улице.action");', 60*35); // SetTimeOut("AlarmWeekEnd_timeNow2",'callMethod("сколько время.action");', 60*40); // SetTimeOut("AlarmWeekEnd_timeNow3",'callMethod("сколько время.action");', 60*50); // если на улице темно // if(timeBetween(gg("Yandex.SunSet"),gg("Yandex.SunRise"))){ // плавное включение Бра в спальне // runScript("nl_lowOn_SpalnyaBra"); // Запланируем выключить его через полчаса // SetTimeOut("AlarmWeekEnd_BraOff",'callMethod("NooLiteD_SpalnyBra.turnOff");', 30*60); // } }
Class properties:
Class methods:
$volume=round(65535*$params['VALUE']/100); $this->setProperty('volumeLevel',$params['VALUE']); safe_exec('..\\apps\\nircmd\\nircmdc setsysvolume '.$volume); say("Изменилась громкость до ".$params['VALUE']." процентов");
Class objects:
say("Отключено питание");
$command=$params['command']; $short_command=''; $dt=recognizeTime($command,$short_command); if (preg_match('/скажи сколько врем/is',$command)) { if ($dt>0) { addScheduledJob("command".$dt,"processCommand('".$short_command."');",$dt); say('Задача принята',2); return; } global $voicemode; $voicemode='on'; say('Сейчас '.timeNow(),2); } elseif (preg_match('/сколько время/is',$command)) { if ($dt>0) { addScheduledJob("command".$dt,"processCommand('".$short_command."');",$dt); say('Задача принята'); echo $short_command; return; } say('Сейчас '.timeNow()); } elseif (preg_match('/повтори (.+)/is',$command,$m) || preg_match('/скажи (.+)/is',$command,$m)) { if ($dt>0) { addScheduledJob("command".$dt,"processCommand('".$short_command."');",$dt); say('Задача принята',2); return; } global $voicemode; $voicemode='on'; say($m[1],2); } else { say('Неизвестная команда...',2); }
Class properties:
Class methods:
//$params['t'] $this->setProperty("updated",time()); $this->setProperty("updatedTime",date("H:i",time())); $this->setProperty("alive",1); $ot=$this->object_title; $alive_timeout=(int)$this->getProperty("aliveTimeOut"); if (!$alive_timeout) { $alive_timeout=30*60; } clearTimeOut($ot."_alive"); setTimeOut($ot."_alive","sg('".$ot.".alive',0);",$alive_timeout); if (!isset($params['h'])) { return; } $old_temp=$this->getProperty('humidity'); $t=round($params['h'],1); if ($t>100) return; $this->setProperty('humidity',$t); if ($params['uptime']) { $this->setProperty('uptime',$params['uptime']); } if ($t>$old_temp) { $d=1; } elseif ($t<$old_temp) { $d=-1; } else { $d=0; } $this->setProperty('direction',$d); $linked_room=$this->getProperty("LinkedRoom"); if ($linked_room) { setGlobal($linked_room.'.Humidity',$t); }
Class objects:
Class properties:
Class methods:
$this->setProperty("updated", time()); $this->setProperty("updatedTime", date("H:i")); $this->setProperty("message", $params["message"]);
Class objects:
Class properties:
Class methods:
if ($params['status']) { $this->setProperty('status',$params['status']); } $this->setProperty('updatedTimestamp',time()); $this->setProperty("alive",1); $ot=$this->object_title; $alive_timeout=(int)$this->getProperty("aliveTimeOut"); if (!$alive_timeout) { $alive_timeout=12*60*60; } clearTimeOut($ot."_alive"); setTimeOut($ot."_alive","sg('".$ot.".alive',0);",$alive_timeout);
Class properties:
Class methods:
$this->setProperty('status',$params['status']); // выставляем статус сенсора $this->setProperty('updatedTimestamp',time()); // выставляем время срабатывания сенсора $this->setProperty('alive',1); $ot=$this->object_title; $alive_timeout=(int)$this->getProperty("aliveTimeOut"); if (!$alive_timeout) { $alive_timeout=24*60*60; } clearTimeOut($ot."_alive"); setTimeOut($ot."_alive","sg('".$ot.".alive',0);",$alive_timeout); if ($params['status']) { $this->setProperty('motionDetected',1); clearTimeOut($this->object_title.'_detected'); setTimeOut($this->object_title.'_detected',"setGlobal('".$this->object_title.".motionDetected',0);",30); $linked_room=$this->getProperty('LinkedRoom'); if ($linked_room!='') { callMethod($linked_room.'.onActivity'); } if ($this->object_title=='sensorMovement3' || $this->object_title=='sensorMovementRemote1' || $this->object_title=='sensorMovementRemote2') { //|| $this->object_title=='sensorMovement5' return; // не реагируем на движение в спальне, по ip-сенсорам и по сенсору на втром этаже } ClearTimeOut("nobodyHome"); SetTimeOut("nobodyHome","callMethod('NobodyHomeMode.activate');", 1*60*60); // выполняем если целый час никого не было if (getGlobal('NobodyHomeMode.active')) { callMethod('NobodyHomeMode.deactivate'); } $last_register=registeredEventTime('inhouseMovement'); // проверяем когда в последний раз срабатывало событие "движение внутри дома" registerEvent('inhouseMovement',$this->name,2); // регистрируем событие "движение внутри дома" if (timeBetween('05:00', '12:00') && ((time()-$last_register)>2*60*60)) { runScript('Greeting'); // запускаем скрипт "доброе утро" } }
Class objects:
Class properties:
Class methods:
Class objects:
$sayMetUSD = gg ("Sets.sayMetUSD"); if ($sayMetUSD) { say ("Читаю курсы валюты с ЦБ РФ",($sayMetUSD-2)); } $file = simplexml_load_file("http://www.cbr.ru/scripts/XML_daily.asp?date_req=".date("d/m/Y")); if (!$file){ DebMes("CBR error"); return; } // USD $xml = $file->xpath("//Valute[@ID='R01235']"); $valute = strval($xml[0]->Value); $this->setProperty('USD', round(str_replace(",",".",$valute)*100)/100); // EURO $xml = $file->xpath("//Valute[@ID='R01239']"); $valute = strval($xml[0]->Value); $this->setProperty('EURO', round(str_replace(",",".",$valute)*100)/100); // CZK (10 крон превращаем в 1 крону) $xml = $file->xpath("//Valute[@ID='R01760']"); $valute = strval($xml[0]->Value); $this->setProperty('CZK', round(str_replace(",",".",$valute)*10)/100); $this->setProperty("uptime",date("d.m.Y - H:i:s",time())); $this->setProperty("updatedTimestamp",time());
Class objects:
Class properties:
Class methods:
$this->setProperty('active',1);
$this->setProperty('active',0);
$this->setProperty("updated",time()); $this->setProperty("updatedTime",date('H:i')); if ($this->getProperty('active')) { say("Режим ".$this->getProperty('title')." активирован."); } else { say("Режим ".$this->getProperty('title')." выключен."); }
Class objects:
setGlobal('minMsgLevel','2');
setGlobal('minMsgLevel','1');
Class methods:
include_once(DIR_MODULES.'app_radio/app_radio.class.php'); $app_radio=new app_radio(); if(is_array($params)) { if(isset($params['sta'])) $app_radio->change_station($params['sta'],$app_radio); if(isset($params['cmd'])) $app_radio->control($params['cmd']); if(isset($params['vol'])) $app_radio->set_volume($params['vol'],$app_radio); } else { if($params=='play' || $params=='stop') $app_radio->control($params); else if(strpos($params, "vol")===0) $app_radio->set_volume((int)substr($params,3),$app_radio); else if(strpos($params, "sta:")===0) $app_radio->change_station(substr($params,4),$app_radio); }
Class objects:
include_once(DIR_MODULES.'app_radio/app_radio.class.php'); $app_radio=new app_radio(); if(is_array($params)) { if(isset($params['sta'])) $app_radio->change_station($params['sta'],$app_radio); if(isset($params['cmd'])) $app_radio->control($params['cmd']); if(isset($params['vol'])) $app_radio->set_volume($params['vol'],$app_radio); } else { if($params=='play' || $params=='stop') $app_radio->control($params); else if(strpos($params, "vol")===0) $app_radio->set_volume((int)substr($params,3),$app_radio); else if(strpos($params, "sta:")===0) $app_radio->change_station(substr($params,4),$app_radio); }
Class properties:
Class methods:
$status=$this->getProperty("status"); if ($status) { $this->callMethod('turnOn'); } else { $this->callMethod('turnOff'); }
$status=$this->getProperty("status"); if ($status) { $this->callMethod('turnOff'); } else { $this->callMethod('turnOn'); }
$this->setProperty("status",0);
$this->setProperty("status",1);
Class objects:
Class properties:
Class methods:
$cmdline='"c:\Program Files\nooLite\nooLite.exe" -api '.$params['command']; $last_called=gg('NoolightCommandSend'); $min_delay=3; $now=time(); if (($now-$last_called)>$min_delay) { //safe_exec($cmdline); $last_callled=$now; sg('NoolightCommandSend',$last_called); DebMes("Noolite instant exec: ".$cmdline); system($cmdline); //exec($cmdline); } else { if ($last_callled<$now) { $last_callled=$now; } $last_called+=$min_delay; sg('NoolightCommandSend',$last_called); DebMes("Noolite scheduled job for ".date('H:i:s',$last_called)); AddScheduledJob("noolight".md5($cmdline),"safe_exec('".$cmdline."');",$last_called); }
$this->setProperty("status",0); //safe_exec('"c:\Program Files\nooLite\noolite.exe" -api -off_ch'.$this->getProperty("channel")); $this->callMethod("sendCommand",array('command'=>'-off_ch'.$this->getProperty("channel")));
$this->setProperty("status",1); $this->callMethod("sendCommand",array('command'=>'-on_ch'.$this->getProperty("channel")));
Class properties:
Class methods:
$code1=$this->getProperty('Code1'); $code2=$this->getProperty('Code2'); safe_exec("c:\_majordomo\apps\arduino_gw\arduino_gw.exe rcon$code1:$code2;"); $this->setProperty("status",1);
$code1=$this->getProperty('Code1'); $code2=$this->getProperty('Code2'); safe_exec("c:\_majordomo\apps\arduino_gw\arduino_gw.exe rcoff$code1:$code2;"); $this->setProperty("status",0);
Class properties:
Class methods:
$rooms=getObjectsByClass("Rooms"); $total=count($rooms); for($i=0;$i<$total;$i++) { $rooms[$i]['room']=getGlobal($rooms[$i]['TITLE'].'.Title'); if (!$rooms[$i]['room']) { $rooms[$i]['room']=$rooms[$i]['TITLE']; } $rooms[$i]['active']=getGlobal($rooms[$i]['TITLE'].'.SomebodyHere'); $rooms[$i]['time']=getGlobal($rooms[$i]['TITLE'].'.LatestActivity'); $rooms[$i]['diff']=time()-$rooms[$i]['time']; } function cmp($a, $b) { if ($a['diff'] == $b['diff']) { return 0; } return ($a['diff'] < $b['diff']) ? -1 : 1; } usort($rooms,"cmp"); if (!$rooms[0]['active']) { $somebodyHomeText="Никого нет дома. Были в ".date('H:i',$rooms[0]['time'])." (".$rooms[0]['room'].")"; } else { $res_rooms=array(); for($i=0;$i<$total;$i++) { if ($rooms[$i]['active']) { $res_rooms[]=$rooms[$i]['room']; } } $somebodyHomeText="Кто-то дома: ".implode(", ",$res_rooms); } setGlobal('somebodyHomeText',$somebodyHomeText); //echo "Updated";
$this->setProperty('SomebodyHere',0);
$latestActivity=$this->getProperty('LatestActivity'); $this->setProperty('LatestActivity',time()); $this->setProperty('LatestActivityTime',date('H:i')); $this->setProperty('SomebodyHere',1); $ot=$this->object_title; if ($this->getProperty("IdleDelay")) { $activity_timeout=(int)$this->getProperty("IdleDelay"); } else { $activity_timeout=10*60; } clearTimeOut($ot."_activity_timeout"); setTimeOut($ot."_activity_timeout","callMethod('".$ot.".onIdle');",$activity_timeout); $this->callMethod("updateActivityStatus");
Class objects:
Class methods:
Class objects:
echo "status received: ".$params['status'];
global $voicemode; $voicemode='off'; processCommand($params['message']);
Class properties:
Class methods:
Class objects:
$details=array(); $red_state=0; $yellow_state=0; if (!isOnline('Internet')) { $yellow_state=1; $details[]=LANG_GENERAL_NO_INTERNET_ACCESS; } if ($red_state) { $state='red'; $state_title=LANG_GENERAL_RED; } elseif ($yellow_state) { $state='yellow'; $state_title=LANG_GENERAL_YELLOW; } else { $state='green'; $state_title=LANG_GENERAL_GREEN; } $new_details=implode(". ",$details); if ($this->getProperty("stateDetails")!=$new_details) { $this->setProperty('stateDetails',$new_details); } if ($this->getProperty('stateColor')!=$state) { $this->setProperty('stateColor',$state); $this->setProperty('stateTitle',$state_title); if ($state!='green') { say(LANG_GENERAL_COMMUNICATION_STATE." ".LANG_GENERAL_CHANGED_TO." ".$state_title."."); say(implode(". ",$details)); } else { say(LANG_GENERAL_COMMUNICATION_STATE." ".LANG_GENERAL_RESTORED_TO." ".$state_title); } $this->callMethod('stateChanged'); }
$details=array(); $red_state=0; $yellow_state=0; $cycles=array('states'=>'states','main'=>'main','execs'=>'exec','scheduler'=>'scheduler'); foreach($cycles as $k=>$v) { $tm=getGlobal('ThisComputer.cycle_'.$k.'Run'); if (time()-$tm>5*60) { $red_state=1; $details[]=$v." ".LANG_GENERAL_CYCLE." ".LANG_GENERAL_STOPPED."."; } } $cycles=array('ping'=>'ping','webvars'=>'webvars'); foreach($cycles as $k=>$v) { $tm=getGlobal('ThisComputer.cycle_'.$k.'Run'); if (time()-$tm>10*60) { $yellow_state=1; $details[]=$v." ".LANG_GENERAL_CYCLE." ".LANG_GENERAL_STOPPED."."; } } if ($red_state) { $state='red'; $state_title=LANG_GENERAL_RED; } elseif ($yellow_state) { $state='yellow'; $state_title=LANG_GENERAL_YELLOW; } else { $state='green'; $state_title=LANG_GENERAL_GREEN; } $new_details=implode(". ",$details); if ($this->getProperty("stateDetails")!=$new_details) { $this->setProperty('stateDetails',$new_details); } if ($this->getProperty('stateColor')!=$state) { $this->setProperty('stateColor',$state); $this->setProperty('stateTitle',$state_title); if ($state!='green') { say(LANG_GENERAL_SYSTEM_STATE." ".LANG_GENERAL_CHANGED_TO." ".$state_title."."); say(implode(". ",$details)); } else { say(LANG_GENERAL_SYSTEM_STATE." ".LANG_GENERAL_RESTORED_TO." ".$state_title); } $this->callMethod('stateChanged'); }
$details=array(); $red_state=0; $yellow_state=0; if ($red_state) { $state='red'; $state_title=LANG_GENERAL_RED; } elseif ($yellow_state) { $state='yellow'; $state_title=LANG_GENERAL_YELLOW; } else { $state='green'; $state_title=LANG_GENERAL_GREEN; } $new_details=implode(". ",$details); if ($this->getProperty("stateDetails")!=$new_details) { $this->setProperty('stateDetails',$new_details); } if ($this->getProperty('stateColor')!=$state) { $this->setProperty('stateColor',$state); $this->setProperty('stateTitle',$state_title); if ($state!='green') { say(LANG_GENERAL_SECURITY_STATE." ".LANG_GENERAL_CHANGED_TO." ".$state_title."."); say(implode(". ",$details)); } else { say(LANG_GENERAL_SECURITY_STATE." ".LANG_GENERAL_RESTORED_TO." ".$state_title); } $this->callMethod('stateChanged'); }
Class properties:
Class methods:
//$params['t'] $this->setProperty("updated",time()); $this->setProperty("updatedTime",date("H:i",time())); $this->setProperty("alive",1); $ot=$this->object_title; $alive_timeout=(int)$this->getProperty("aliveTimeOut"); if (!$alive_timeout) { $alive_timeout=30*60; } clearTimeOut($ot."_alive"); setTimeOut($ot."_alive","sg('".$ot.".alive',0);",$alive_timeout); if (!isset($params['t'])) { return; } $old_temp=$this->getProperty('temp'); $t=round($params['t'],1); if ($t>110) return; $this->setProperty('temp',$t); if ($params['uptime']) { $this->setProperty('uptime',$params['uptime']); } if ($t>$old_temp) { $d=1; } elseif ($t<$old_temp) { $d=-1; } else { $d=0; } $this->setProperty('direction',$d); $linked_room=$this->getProperty("LinkedRoom"); if ($linked_room) { setGlobal($linked_room.'.Temperature',$t); }
Class objects:
Class properties:
Class methods:
//START openweather module $updateTime = gg('ow_setting.updateTime'); if($updateTime > 0) { $count = gg('ow_setting.countTime'); if($count >= $updateTime) { include_once(DIR_MODULES . 'app_openweather/app_openweather.class.php'); $app_openweather = new app_openweather(); $app_openweather->get_weather(gg('ow_city.id')); sg('ow_setting.countTime', 1); } else { $count++; sg('ow_setting.countTime', $count); } } // END openweather module//START openweather module $updateTime = gg('ow_setting.updateTime'); if($updateTime > 0) { $count = gg('ow_setting.countTime'); if($count >= $updateTime) { include_once(DIR_MODULES . 'app_openweather/app_openweather.class.php'); $app_openweather = new app_openweather(); $app_openweather->get_weather(gg('ow_city.id')); sg('ow_setting.countTime', 1); } else { $count++; sg('ow_setting.countTime', $count); } } // END openweather module//START openweather module $updateTime = gg('ow_setting.updateTime'); if($updateTime > 0) { $count = gg('ow_setting.countTime'); if($count >= $updateTime) { include_once(DIR_MODULES . 'app_openweather/app_openweather.class.php'); $app_openweather = new app_openweather(); $app_openweather->get_weather(gg('ow_city.id')); sg('ow_setting.countTime', 1); } else { $count++; sg('ow_setting.countTime', $count); } } // END openweather module//START openweather module $updateTime = gg('ow_setting.updateTime'); if($updateTime > 0) { $count = gg('ow_setting.countTime'); if($count >= $updateTime) { include_once(DIR_MODULES . 'app_openweather/app_openweather.class.php'); $app_openweather = new app_openweather(); $app_openweather->get_weather(gg('ow_city.id')); sg('ow_setting.countTime', 1); } else { $count++; sg('ow_setting.countTime', $count); } } // END openweather module//START openweather module $updateTime = gg('ow_setting.updateTime'); if($updateTime > 0) { $count = gg('ow_setting.countTime'); if($count >= $updateTime) { include_once(DIR_MODULES . 'app_openweather/app_openweather.class.php'); $app_openweather = new app_openweather(); $app_openweather->get_weather(gg('ow_city.id')); sg('ow_setting.countTime', 1); } else { $count++; sg('ow_setting.countTime', $count); } } // END openweather module//START openweather module $updateTime = gg('ow_setting.updateTime'); if($updateTime > 0) { $count = gg('ow_setting.countTime'); if($count >= $updateTime) { include_once(DIR_MODULES . 'app_openweather/app_openweather.class.php'); $app_openweather = new app_openweather(); $app_openweather->get_weather(gg('ow_city.id')); sg('ow_setting.countTime', 1); } else { $count++; sg('ow_setting.countTime', $count); } } // END openweather module//START openweather module $updateTime = gg('ow_setting.updateTime'); if($updateTime > 0) { $count = gg('ow_setting.countTime'); if($count >= $updateTime) { include_once(DIR_MODULES . 'app_openweather/app_openweather.class.php'); $app_openweather = new app_openweather(); $app_openweather->get_weather(gg('ow_city.id')); sg('ow_setting.countTime', 1); } else { $count++; sg('ow_setting.countTime', $count); } } // END openweather module//START openweather module $updateTime = gg('ow_setting.updateTime'); if($updateTime > 0) { $count = gg('ow_setting.countTime'); if($count >= $updateTime) { include_once(DIR_MODULES . 'app_openweather/app_openweather.class.php'); $app_openweather = new app_openweather(); $app_openweather->get_weather(gg('ow_city.id')); sg('ow_setting.countTime', 1); } else { $count++; sg('ow_setting.countTime', $count); } } // END openweather module//START openweather module $updateTime = gg('ow_setting.updateTime'); if($updateTime > 0) { $count = gg('ow_setting.countTime'); if($count >= $updateTime) { include_once(DIR_MODULES . 'app_openweather/app_openweather.class.php'); $app_openweather = new app_openweather(); $app_openweather->get_weather(gg('ow_city.id')); sg('ow_setting.countTime', 1); } else { $count++; sg('ow_setting.countTime', $count); } } // END openweather module//START openweather module $updateTime = gg('ow_setting.updateTime'); if($updateTime > 0) { $count = gg('ow_setting.countTime'); if($count >= $updateTime) { include_once(DIR_MODULES . 'app_openweather/app_openweather.class.php'); $app_openweather = new app_openweather(); $app_openweather->get_weather(gg('ow_city.id')); sg('ow_setting.countTime', 1); } else { $count++; sg('ow_setting.countTime', $count); } } // END openweather module/* START yaWeather module*/ $updateTime = gg('yw_setting.updateTime'); if($updateTime > 0){ $count = gg('yw_setting.countTime'); if($count >= $updateTime){ include_once(DIR_MODULES.'app_yaweather/app_yaweather.class.php'); $app_yaweather=new app_yaweather(); $app_yaweather->get_weather(gg('yw_setting.city_id')); sg('yw_setting.countTime',1); } else { $count++; sg('yw_setting.countTime',$count); } }/* END yaWeather*/
Class objects:
$h=(int)date('G',time()); $m=date('i',time()); //Записываем текущее время sg("ThisComputer.timeNow",date( "H:i", time())); // получем ЧАСЫ и МИНУТЫ отдельно $timeH=date("H", time()); $timeM=date("i", time()); sg("ThisComputer.timeH",$timeH); sg("ThisComputer.timeM",$timeM); // выделяем десятки и единицы часов и минут, если изминились, то присваиваем if (gg("ThisComputer.timeH1")!=$timeH[0]) {sg("ThisComputer.timeH1",$timeH[0]);} if (gg("ThisComputer.timeH2")!=$timeH[1]) {sg("ThisComputer.timeH2",$timeH[1]);} if (gg("ThisComputer.timeM1")!=$timeM[0]) {sg("ThisComputer.timeM1",$timeM[0]);} if (gg("ThisComputer.timeM2")!=$timeM[1]) {sg("ThisComputer.timeM2",$timeM[1]);} // готовим минимальный уровень проговаривания в соответствии с настройками для проговаривания времени $saytime = gg('Sets.saytime'); // сообщение о восходе и закате и установка режима темного времени суток if (timeIs(gg("Izhevsk.SunRise"))) { if ($saytime) { say ("Восход солнца.",($saytime-2)); } callMethod('DarknessMode.deactivate'); } if (timeIs(gg("Izhevsk.SunSet"))) { if ($saytime) { say ("Солнце уже заходит.",($saytime-2)); } callMethod('DarknessMode.activate'); } // установка ночного режима if (timeIs("23:30")) { callMethod("NightMode.activate"); } else if (timeIs("06:00")) { callMethod("NightMode.deactivate"); } // произносить или писать время каждый час, если НЕ ночной режим if ((!(gg("NightMode.active")))&&($m=="00")) { if ($saytime) { say((timeNow()." ровно"),($saytime-2)); } } // Флуктуации каждую минуту 1 - 0 - 1 - 0 ... if (gg("ThisComputer.fluctuations")) { sg("ThisComputer.fluctuations",0); } else { sg("ThisComputer.fluctuations",1); } // для разных задумок в дальнейшем, а также для тестирования может пригодиться if (gg("ThisComputer.fluctuations")) { sg("ThisComputer.StreamingCode1","."); } else { sg("ThisComputer.StreamingCode1",gg("ThisComputer.StreamingCode0")); } // переберем пользователей для проверки включенно ли слежение GPS $objects=getObjectsByClass("Users"); foreach($objects as $obj) { $user=$obj['TITLE']; // Если нужно следить за User через GPS по iCloud if (gg($user.'.monitor')) { $AppleDevNum=(gg($user.'.AppleDevNum')=='') ? 0 : gg($user.'.AppleDevNum'); switch (gg($user.'.atHome')) { case 0: // если не дома то через X минут if (!($m%2)) { findMyiPhone(gg($user.'.AppleID'), dsCrypt(gg($user.'.ApplePass'),true)); } break; case 1: // если дома то через Y минут if (!($m%3)) { findMyiPhone(gg($user.'.AppleID'), dsCrypt(gg($user.'.ApplePass'),true)); } break; } } } //будильники $objects=getObjectsByClass("AlarmClock"); foreach($objects as $obj) { // переберем все будильники в системе if (gg($obj['TITLE'].".AlarmOn") && timeIs(gg($obj['TITLE'].".AlarmTime"))) { //если будильник включен и время совпало callMethod($obj['TITLE'].".AlarmRun"); // выполним метод будильника } } // обновляем данные о компе runScript("Данные_OHM"); //callMethod("Izhevsk.sensors");
// раскидываем дату и время если изменилось в Windows $h=(int)date('G',time()); if (gg('ThisComputer.DateD')!=date("d", time())) { $day[0]="воскресенье"; $day[1]="понедельник"; $day[2]="вторник"; $day[3]="среда"; $day[4]="четверг"; $day[5]="пятница"; $day[6]="суббота"; $month[1]="января"; $monthAlt[1]="ЯНВАРЬ"; $month[2]="февраля"; $monthAlt[2]="ФЕВРАЛЬ"; $month[3]="марта"; $monthAlt[3]="МАРТ"; $month[4]="апреля"; $monthAlt[4]="АПРЕЛЬ"; $month[5]="мая"; $monthAlt[5]="МАЙ"; $month[6]="июня"; $monthAlt[6]="ИЮНЬ"; $month[7]="июля"; $monthAlt[7]="ИЮЛЬ"; $month[8]="августа"; $monthAlt[8]="АВГУСТ"; $month[9]="сентября"; $monthAlt[9]="СЕНТЯБРЬ"; $month[10]="октября"; $monthAlt[10]="ОКТЯБРЬ"; $month[11]="ноября"; $monthAlt[11]="НОЯБРЬ"; $month[12]="декабря"; $monthAlt[12]="ДЕКАБРЬ"; sg("ThisComputer.DateD",date( "d", time())); sg("ThisComputer.DateM",date( "m", time())); sg("ThisComputer.DateY",date( "Y", time())); sg("ThisComputer.Date",date( "d.m.Y", time())); sg("ThisComputer.Day",$day[date("w")]); sg("ThisComputer.Month",$month[date("n")]); sg("ThisComputer.MonthAlt",$monthAlt[date("n")]); } //дни рождения, проверять при условии разрешения в установках и в 9-00 if ((gg("Sets.checkBirthday"))&&($h=="09")) { runScript("birthday"); } if (isOnline("Интернет")) { // обновим прогноз погоды setTimeOut('IzhevskSensor','callMethod("Izhevsk.sensors");',1); //callMethod("Izhevsk.sensors"); // обновим курс валюты каждые 4 часа if (!($h%4)) {callMethod("cbr.update");} } else { say ("Проверить погоду и курсы валют пока не могу, так как нет доступа в интеренет. Попробую сделать это через один час. ",-1); }
Class properties:
Class methods:
// МЕТОД new if (isset($params["task"])) { $todo = $this->getProperty("todo"); $mytask = "-".$params["task"]; // строка задачи $sayTodo = gg("Sets.sayTodo"); if ($sayTodo) { say ("В лист todo добавлена задача: "".$params["task"].""",($sayTodo-2)); } $todo = $todo."|".$mytask; // добавляем с разделителем $this->setProperty("todo", $todo); }
// МЕТОД delete $todo = $this->getProperty("todo"); $dt = $params["task"]; // получаем номер строки на удаление $td = explode("|", $todo); // Считываем всё в массив for($i = 0; $i < sizeof($td); $i++) { if($i == $dt) { $sayTodo = gg("Sets.sayTodo"); if ($sayTodo) { say ("Из листа todo удалена задача: "".mb_substr($td[$i], 1).""",($sayTodo-2)); } unset($td[$i]); } } $todo = implode("|", $td); $this->setProperty("todo", $todo); // выполним подготовку для отображения // callMethod("TodoList.view");
// МЕТОД check $todo = $this->getProperty("todo"); // установим внутреннюю кодировку символов mb_internal_encoding("UTF-8"); $td = explode("|", $todo); if (isset($params["task"])) { $ct = $params["task"]; for($i = 0; ($i < sizeof($td)); $i++) { // выделим и сохраним первый символ $check = mb_substr($td[$i], 0, 1); // обрежем строку, не будем отображать первый символ + или - $task = mb_substr($td[$i], 1); // если совпадает номер строки if ($i == $ct) { // инвентируем check $check = ($check == "+") ? "-" : "+"; $tcheck = ($check == "+") ? ""выполненно"" : ""не выполнено""; $sayTodo = gg("Sets.sayTodo"); if ($sayTodo) { say ("Todo задача: "".$task."" - отмечена как ".$tcheck,($sayTodo-2)); } } $td[$i] = $check.$task; } $todo = implode("|", $td); $this->setProperty("todo", $todo); } // выполним подготовку для отображения // callMethod("TodoList.view");
// МЕТОД view - подготовка кода для отображения $todo = $this->getProperty("todo"); // установим внутреннюю кодировку символов mb_internal_encoding("UTF-8"); $td = explode("|", $todo); $str_cod = '<div id="list"> <div class="new"> <input id="newtask" placeholder="New Item" type="text"> <button onClick="btnRunClicked();" class="fa fa-plus"></button> </div> <div class="list">'; for($i = 1; $i < sizeof($td); $i++) { // выделим и сохраним первый символ $check = mb_substr($td[$i], 0, 1); // обрежем строку, не будем отображать первый символ + или - $task = mb_substr($td[$i], 1); // начинаем формировать код hsl(196,'.(73-24*(($i-1)%2)).'%,50%) $str_cod = $str_cod.' <div class="item" id="taskbox_'.$i.'" style ="background: hsl('.(190+$i*6).',73%,50%);"> <span id="task_'.$i.'"'; // если певый символ "+" то значит задание "выполнено" if ($check == "+") { $str_cod = $str_cod.' class="checked"'; } $str_cod = $str_cod.'>'.$task.'</span>'; $str_cod = $str_cod.' <div class="rightblock"> <button id="check_'.$i.'" class="check fa fa-check" onClick="checkClicked('.$i.');"></button> <button id="delete_'.$i.'" class="delete fa fa-times" onClick="deleteClicked('.$i.');"></button> </div> </div>'; } $str_cod = $str_cod.' </div> </div>'; // записываем получившийся код $this->setProperty("StreamingCodeScene",$str_cod); $str_cod_css = "<style>".$this->getProperty("menuCSS")."</style>"; $str_cod_js = "<script type='text/javascript'>".$this->getProperty("JS")."</script>"; $str_cod = $str_cod_css.$str_cod_js.$str_cod; $this->setProperty("StreamingCodeMenu",$str_cod);
Class objects:
// ****************************************************************** // * TO DO app - by Vovix - 30.11.2015 г. - v 3.1 * // ****************************************************************** // создадим класс и объекты addClass('ToDo'); addClassObject('ToDo','TodoList'); addClassProperty('ToDo','StreamingCodeMenu'); // HTML для меню addClassProperty('ToDo','StreamingCodeScene'); // HTML для сцен addClassProperty('ToDo','menuCSS'); // CSS для меню addClassProperty('ToDo','sceneCSS'); // CSS для сцены addClassProperty('ToDo','JS'); // общий код javascript addClassProperty('ToDo','todo'); // сам лист to do // $this->setProperty('todo', '- to do list by Vovix -'); $menuCSS=' @import url("https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"); #item194 { /* здесь item194 - это номер ID пункта меню в котором он размещен */ padding: 0; } #list { position: relative; /* width: calc(100% + 40px); */ /* margin: 0 -20px 0 -20px; */ width: 100%; margin: 0; } #list .new { width: 100%; height: 50px; padding: 0; margin: 0; } #list .new #newtask { float: left; width: calc(100% - 76px); height: 50px; padding: 0; margin: 0; background: #333333; text-indent: 8px; } #list .new input { font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif; font-size: 14px; color: #FFF; text-align: justify; line-height: normal; outline: 0; border: 0; border-radius: 0px; text-shadow: none; } #list .new #newtask::-webkit-input-placeholder { color: rgba(255, 255, 255, 0.5); } #list .new button { cursor: pointer; float: right; width: 76px; height: 50px; padding: 0; outline: 0; border: 0; border-radius: 0px; margin: -9px 0 0 0; background: #111111; font-size: 24px; color: #FFF; } #list .list .item { clear: both; width: 100%; height: 38px; margin: 0; } #list .list .item span { cursor: default; float: left; width: calc(100% - 76px); height: 20px; padding: 9px 0 0 0; margin: 0; outline: 0; border: 0; background: transparent; text-indent: 8px; font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif; font-size: 14px; color: #FFF; text-align: justify; text-shadow: none; } #list .list .item span.checked { opacity: .5; text-decoration: line-through; } #list .list .item .rightblock { float: right; width: 76px; height: 38px; padding: 0; margin: 0; } #list .list .item .rightblock button { cursor: pointer; float: left; width: 38px; height: 38px; padding: 0px; margin: 0; outline: 0; border: 0; border-radius: 0px; background: rgba(0,0,0,0.1); font-size: 20px; color: #FFF; } '; $this->setProperty('menuCSS', $menuCSS); $sceneCSS=' #list { position: relative; width: 100%; max-height: 528px; overflow: auto; margin: 0; } #list .new #newtask { float: left; width: calc(100% - 100px); height: 100px; padding: 0; margin: 0; outline: 0; border: 0; background: #333333; line-height: 50px; text-indent: 25px; } #list .new input { font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif; font-size: 28px; color: #FFF; text-align: justify; line-height: normal; outline: 0; border: 0; border-radius: 0px; text-shadow: 0px; } #list .new #newtask::-webkit-input-placeholder { color: rgba(255, 255, 255, 0.5); } #list .new button { cursor: pointer; float: right; width: 100px; height: 100px; padding: 0; margin: 0; outline: 0; border: 0; border-radius: 0px; background: #111111; font-size: 84px; color: #FFF; } #list .list .item { clear: both; width: 100%; height: 50px; margin: 0; padding: 5px 0 0 0; } #list .list .item span { cursor: default; float: left; width: calc(100% - 150px); height: 50px; padding: 0; margin: 0; outline: 0; border: 0; background: transparent; text-indent: 25px; font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif; font-size: 28px; color: #FFF; text-align: justify; line-height: normal; } #list .list .item span.checked { opacity: .5; text-decoration: line-through; } #list .list .item .rightblock { float: right; padding: 0; margin: -2px 0 0 0; } #list .list .item button{ cursor: pointer; float: left; width: 50px; height: 50px; padding: 0; margin: 0; outline: 0; border: 0; box-shadow: 0 0 3px rgba(0,0,0,0.2); background: rgba(0,0,0,0.1); font-size: 32px; color: #FFF; } '; $this->setProperty('sceneCSS', $sceneCSS); $JS=' function btnRunClicked() { var newtask = $("#newtask").val(), ni = $("div.item").length + 1; $("#newtask").val(""); if (newtask) { var task1 = String(newtask); var codItem1 = \'<div class="item" id="taskbox_\' + ni + \'" style ="background: hsl(\' + (190+ni*6) + \',73%,50%);">\'; var codItem2 = \'<span id="task_\' + ni + \'">\' + task1 + \'</span>\'; var codItem3 = \'<div class="rightblock"><button id="check_\' + ni + \'" class="check fa fa-check ui-btn ui-shadow ui-corner-all" onClick="checkClicked(\' + ni +\');"></button>\'; var codItem4 = \'<button id="delete_\' + ni + \'" class="delete fa fa-times ui-btn ui-shadow ui-corner-all" onClick="deleteClicked(\' + ni + \');"></button></div></div>\'; $.get( "/objects/", { object:"TodoList", op:"m", m:"new", task:newtask } ); setTimeout(function() { $.get( "/objects/", { object:"TodoList", op:"m", m:"view" } ) }, 100); $(codItem1 + codItem2 + codItem3 + codItem4).appendTo("div.list"); return false; } } function checkClicked(ctask) { if (ctask) { $.get( "/objects/", { object:"TodoList", op:"m",m:"check", task:ctask } ); $("#task_"+ctask).toggleClass("checked"); setTimeout(function() { $.get( "/objects/", { object:"TodoList", op:"m", m:"view" } ) }, 100); return false; } } function deleteClicked(dtask) { if (dtask) { $.get( "/objects/", { object:"TodoList", op:"m", m:"delete", task:dtask } ); $("#taskbox_"+dtask).remove(); setTimeout(function() { $.get( "/objects/", { object:"TodoList", op:"m", m:"view" } ) }, 100); return false; } } '; $this->setProperty('JS', $JS); $view=' // МЕТОД view - подготовка кода для отображения $todo = $this->getProperty("todo"); // установим внутреннюю кодировку символов mb_internal_encoding("UTF-8"); $td = explode("|", $todo); $str_cod = \'<div id="list"> <div class="new"> <input id="newtask" placeholder="New Item" type="text"> <button onClick="btnRunClicked();" class="fa fa-plus"></button> </div> <div class="list">\'; for($i = 1; $i < sizeof($td); $i++) { // выделим и сохраним первый символ $check = mb_substr($td[$i], 0, 1); // обрежем строку, не будем отображать первый символ + или - $task = mb_substr($td[$i], 1); // начинаем формировать код hsl(196,\'.(73-24*(($i-1)%2)).\'%,50%) $str_cod = $str_cod.\' <div class="item" id="taskbox_\'.$i.\'" style ="background: hsl(\'.(190+$i*6).\',73%,50%);"> <span id="task_\'.$i.\'"\'; // если певый символ "+" то значит задание "выполнено" if ($check == "+") { $str_cod = $str_cod.\' class="checked"\'; } $str_cod = $str_cod.\'>\'.$task.\'</span>\'; $str_cod = $str_cod.\' <div class="rightblock"> <button id="check_\'.$i.\'" class="check fa fa-check" onClick="checkClicked(\'.$i.\');"></button> <button id="delete_\'.$i.\'" class="delete fa fa-times" onClick="deleteClicked(\'.$i.\');"></button> </div> </div>\'; } $str_cod = $str_cod.\' </div> </div>\'; // записываем получившийся код $this->setProperty("StreamingCodeScene",$str_cod); $str_cod_css = "<style>".$this->getProperty("menuCSS")."</style>"; $str_cod_js = "<script type=\'text/javascript\'>".$this->getProperty("JS")."</script>"; $str_cod = $str_cod_css.$str_cod_js.$str_cod; $this->setProperty("StreamingCodeMenu",$str_cod); '; addClassMethod('ToDo', 'view', $view); $check=' // МЕТОД check $todo = $this->getProperty("todo"); // установим внутреннюю кодировку символов mb_internal_encoding("UTF-8"); $td = explode("|", $todo); if (isset($params["task"])) { $ct = $params["task"]; for($i = 0; ($i < sizeof($td)); $i++) { // выделим и сохраним первый символ $check = mb_substr($td[$i], 0, 1); // обрежем строку, не будем отображать первый символ + или - $task = mb_substr($td[$i], 1); // если совпадает номер строки if ($i == $ct) { // инвентируем check $check = ($check == "+") ? "-" : "+"; $tcheck = ($check == "+") ? ""выполненно"" : ""не выполнено""; $sayTodo = gg("Sets.sayTodo"); if ($sayTodo) { say ("Todo задача: "".$task."" - отмечена как ".$tcheck,($sayTodo-2)); } } $td[$i] = $check.$task; } $todo = implode("|", $td); $this->setProperty("todo", $todo); } // выполним подготовку для отображения // callMethod("TodoList.view"); '; addClassMethod('ToDo', 'check', $check); $delete = ' // МЕТОД delete $todo = $this->getProperty("todo"); $dt = $params["task"]; // получаем номер строки на удаление $td = explode("|", $todo); // Считываем всё в массив for($i = 0; $i < sizeof($td); $i++) { if($i == $dt) { $sayTodo = gg("Sets.sayTodo"); if ($sayTodo) { say ("Из листа todo удалена задача: "".mb_substr($td[$i], 1).""",($sayTodo-2)); } unset($td[$i]); } } $todo = implode("|", $td); $this->setProperty("todo", $todo); // выполним подготовку для отображения // callMethod("TodoList.view"); '; addClassMethod('ToDo', 'delete', $delete); $new = ' // МЕТОД new if (isset($params["task"])) { $todo = $this->getProperty("todo"); $mytask = "-".$params["task"]; // строка задачи $sayTodo = gg("Sets.sayTodo"); if ($sayTodo) { say ("В лист todo добавлена задача: "".$params["task"].""",($sayTodo-2)); } $todo = $todo."|".$mytask; // добавляем с разделителем $this->setProperty("todo", $todo); } '; addClassMethod('ToDo', 'new', $new); callMethod("TodoList.view");
Class methods:
Class objects:
if ($params['serial']=='' && $params['devname']!='') { $params['serial']=$params['devname']; } $device=SQLSelectOne("SELECT * FROM usbdevices WHERE SERIAL LIKE '".$params['serial']."'"); if (!$device['ID']) { // new device connected //say("Подключено новое устройство",1); $device=array(); $device['SERIAL']=$params['serial']; $device['TITLE']='устройство '.$params['devname']; $device['FIRST_FOUND']=date('Y-m-d H:i:s'); $device['LAST_FOUND']=date('Y-m-d H:i:s'); $device['LOG'].=$device['FIRST_FOUND'].' подключено (впервые)'."\n"; $device['ID']=SQLInsert('usbdevices',$device); } else { // device already in our database //say("Подключено ".$device['TITLE'],1); if ($device['USER_ID']) { $user=SQLSelectOne("SELECT * FROM users WHERE ID='".$device['USER_ID']."'"); if ($user['ID']) { //$user['NAME']; // теперь мы знаем имя пользователя, связанного с этим устройством } } $device['LAST_FOUND']=date('Y-m-d H:i:s'); $device['LOG']=$device['LAST_FOUND'].' подключено'."\n".$device['LOG']; SQLUpdate('usbdevices',$device); if ($device['SCRIPT_ID']!='') { runScript($device['SCRIPT_ID'],$params); } elseif ($device['SCRIPT']!='') { eval($device['SCRIPT']); } }
Class properties:
Class methods:
Class objects:
// ****************************** // Vovix, 16.11.2015 г. v.1.1 // ****************************** $city_id=gg("37864"); //ID города узнаем тут: https://pogoda.yandex.ru/static/cities.xml $data_file="http://export.yandex.ru/weather-ng/forecasts/$city_id.xml?".rand(); // адрес xml файла - 37864 //say($data_file); $xml = simplexml_load_file($data_file); // раскладываем xml на массив // температура вчера в это же время $temp_yesterday=$xml->yesterday->temperature; // Если значение температуры положительно, для наглядности добавляем "+" $temp_yesterday = getTempSign($temp_yesterday); sg("Izhevsk.TempYesterday",$temp_yesterday); // температура сейчас $temp=$xml->fact->temperature; if (date('G')==13) {sg("Izhevsk.Temp13h",$temp);} if (date('G')==21) {sg("Izhevsk.Temp21h",$temp);} $temp = getTempSign($temp); // Если значение температуры положительно, для наглядности добавляем "+" // достаем из XML-файла время его чтения $XMLuptime = $xml->fact->uptime; $XMLuptime = explode("T", $XMLuptime); $XMLuptimeTo = ($XMLuptime[0].' '.$XMLuptime[1]); // addClassProperty('Weather','XMLuptime'); sg("Izhevsk.XMLuptime",$XMLuptimeTo); // сохраняем основные параметры текущей погоды sg("Izhevsk.Temp",$temp); sg("ThisComputer.TempOutside",$temp); sg("Izhevsk.Type",$xml->fact->weather_type); sg("Izhevsk.Pressure",$xml->fact->pressure); sg("Izhevsk.Humidity",$xml->fact->humidity); sg("Izhevsk.WindSpeed",$xml->fact->wind_speed); sg("Izhevsk.Image",$xml->fact->{'image-v3'}); // определение вероятности дождя 0 или 1 $rain1=gg("Izhevsk.Type"); $rain2=$xml->day[0]->day_part[0]->weather_type; $rain3=$xml->day[0]->day_part[1]->weather_type; $rain4=$xml->day[0]->day_part[2]->weather_type; $rain5=$xml->day[0]->day_part[3]->weather_type; $rain=($rain1. $rain2. $rain3. $rain4. $rain5); $pos = strpos($rain, "дожд"); if ($pos === false) { sg("Izhevsk.Rain",0); } else { sg("Izhevsk.Rain",1); // say("Возможен дождь",2); } // Направление ветра $dir = $xml->fact->wind_direction; // Функция возвращает массив, поэтому записываем в переменные значения, полученные в функции list ($dir, $dirtext) = getWindDirection($dir); sg("Izhevsk.WindDir",$dir); sg("Izhevsk.WindDirText",$dirtext); // Солнце: восход/закат sg("Izhevsk.SunRise",$xml->day[0]->sunrise); sg("Izhevsk.SunSet",$xml->day[0]->sunset); // Луна sg("Izhevsk.Moon_phase",$xml->day[0]->moon_phase); sg("Izhevsk.MoonRise",$xml->day[0]->moonrise); sg("Izhevsk.MoonSet",$xml->day[0]->moonset); // длинный текстовый прогноз погоды // $metcast=""; $metcast="На улице ".gg("Izhevsk.Type")."."; // ветер $WindSpeed=(float)gg("Izhevsk.WindSpeed"); if ($WindSpeed<1) { $metcast.=' Ветра, скорее всего, нет.'; } elseif ($WindSpeed<3) { $metcast.=' Возможен слабый ветер.'; } elseif ($WindSpeed<6) { $metcast.=' Возможен сильный ветер.'; } elseif ($WindSpeed<9) { $metcast.=' Возможен довольно сильный ветер.'; } else { $metcast.=' Возможен очень сильный ветер.'; } $w=round(strip_tags(gg("Izhevsk.Temp"))); $tempw=$w; if($w < "0"){ $tempw=abs($w); } if($w > "0"){ $templus=" плюс "; } if($tempw >= 11 and $tempw <= 14){ $tempcels=" градусов";} else{ while ($tempw > 9){ $tempw=$tempw-10; } if($tempw == 0 or $tempw >= 5 and $tempw <= 9){ $tempcels=" градусов"; } if($tempw == 1){ $tempcels=" градус"; } if($tempw >= 2 and $tempw <= 4){ $tempcels=" градуса"; } } $metcast.=' Температура '.gg("Izhevsk.Temp").' '.$tempcels.'.'; $tm=(float)gg("Izhevsk.Temp"); if ($tm<-40) { $metcast.=' Мы морозов не боимся!'; } elseif ($tm<-30) { $metcast.=' Очень холодно, оденьтесь теплее.'; } elseif ($tm<-20) { $metcast.=' Самое время есть мороженое.'; } elseif ($tm<-10) { $metcast.=' Холодновато.'; } elseif ($tm<-3) { $metcast.=' Не особо холодно.'; } elseif ($tm<3) { $metcast.=' Значит, возможно, гололёд.'; } elseif ($tm<10) { $metcast.=' Тепловато.'; } elseif ($tm<25) { $metcast.=' Тепло.'; } elseif ($tm<30) { $metcast.=' Жарко.'; } elseif ($tm>30) { $metcast.=' Ташкент.'; } // $metcast.=' Восход солнца сегодня в '.gg("Izhevsk.SunRise").','; // $metcast.=' закат в '.gg("Izhevsk.SunSet").'.'; sg("Izhevsk.metcast",$metcast); // прогноз на 3 дня $w3days="Сегодня ночью будет "; $temp=$xml->day[0]->day_part[3]->temperature_from; if ($temp>0) {$temp='+'.$temp;} $w3days.=$temp; $w3days.="°, "; $w3days.=$xml->day[0]->day_part[3]->weather_type; $w3days.=".\r\nЗавтра днём будет "; $temp=$xml->day[1]->day_part[1]->temperature_from; if ($temp>0) {$temp='+'.$temp;} $w3days.=$temp; $w3days.="°, "; $w3days.=$xml->day[1]->day_part[1]->weather_type; $w3days.=". Послезавтра ночью "; $temp=$xml->day[1]->day_part[3]->temperature_from; if ($temp>0) {$temp='+'.$temp;} $w3days.=$temp; $w3days.="°, "; $w3days.=$xml->day[1]->day_part[3]->weather_type; $w3days.="."; sg("Izhevsk.forecast",$w3days); // Определяем время года $season = $xml->fact->season; switch ($season){ case 'winter': $season="зима"; break; case 'summer': $season="лето"; break; case 'autumn': $season="осень"; break; case 'spring': $season="весна"; break; } sg("Izhevsk.season",$season); //время года // Запишем прогноз погоды на 10 дней $nDay=0; foreach($xml->day as $day) { // записываем дату с днем недели на каждый день sg("Izhevsk.mcD".$nDay."_Day",getDayDate($day['date'])); // нам нужны только 4 части дня по 6+1 параметров в каждом for($i = 0;$i < 4;$i++) { $prop_Temp = 'mcD'.$nDay.'_Temp_'.$i; //addClassProperty('Weather',$prop_Temp); $prop_Image = 'mcD'.$nDay.'_Image_'.$i; //addClassProperty('Weather',$prop_Image); $prop_WindDir = 'mcD'.$nDay.'_WindDir_'.$i; //addClassProperty('Weather',$prop_WindDir); $prop_WindDirText = 'mcD'.$nDay.'_WindDirText_'.$i; //addClassProperty('Weather',$prop_WindDirText); $prop_WindSpeed = 'mcD'.$nDay.'_WindSpeed_'.$i; //addClassProperty('Weather',$prop_WindSpeed); $prop_Humidity = 'mcD'.$nDay.'_Humidity_'.$i; //addClassProperty('Weather',$prop_Humidity); $prop_Pressure = 'mcD'.$nDay.'_Pressure_'.$i; //addClassProperty('Weather',$prop_Pressure); // 1 температура sg("Izhevsk.".$prop_Temp, getTempSign($day->day_part[$i]->{'temperature-data'}->avg)); // 2 Картинка sg("Izhevsk.".$prop_Image,$day->day_part[$i]->{'image-v3'}); // 3 Направление ветра $dir = $day->day_part[$i]->wind_direction; // Функция возвращает массив, поэтому записываем в переменные значения, полученные в функции list ($dir, $dirtext) = getWindDirection($dir); sg("Izhevsk.".$prop_WindDir, $dir); sg("Izhevsk.".$prop_WindDirText, $dirtext); // 4 Скорость ветра sg("Izhevsk.".$prop_WindSpeed,$day->day_part[$i]->wind_speed); // 5 Влажность sg("Izhevsk.".$prop_Humidity,$day->day_part[$i]->humidity); // 6 Атмосферное давление sg("Izhevsk.".$prop_Pressure,$day->day_part[$i]->pressure); } $nDay++; } // Обновляем показатели жизни объекта sg("Izhevsk.updatedTimestamp", time()); sg("Izhevsk.updatedTime", date( "H:i - d.m.Y", time())); // Проговариваем, при необходимости $sayMetUSD = gg ("Sets.sayMetUSD"); if ($sayMetUSD) { say("Читаю прогноз погоды с Yandex",($sayMetUSD-2)); } // ******************************************************** // КОНЕЦ ОСНОВНОГО БЛОКА // Функция - добавления "+" к положительной температуре function getTempSign($temp) { $temp = (int)$temp; return $temp > 0 ? '+'.$temp : $temp; } // Функция - получить направления ветра в МАССИВ function getWindDirection($wind) { $wind = (string)$wind; $wind_direction = array('s'=>'↑ ю', 'n'=>'↓ с', 'w'=>'→ з', 'e'=>'← в', 'sw'=>'↗ юз', 'se'=>'↖ юв', 'nw'=>'↘ сз', 'ne'=>'↙ св'); $wind_dirtxt = array('s'=>'южный', 'n'=>'северный', 'w'=>'западный', 'e'=>'восточный', 'sw'=>'юго-западный', 'se'=>'юго-восточный', 'nw'=>'северо-западный', 'ne'=>'северо-восточный'); return array ($wind_direction[$wind], $wind_dirtxt[$wind]); } // Функция - получить локализованный день недели function getDayDate($date) { $date = strtotime($date); // $months = array('','января','февраля','марта','апреля','мая','июня','июля','августа','сентября','октября','ноября','декабря'); $days = array('ВС','ПН', 'ВТ', 'СР', 'ЧТ', 'ПТ', 'СБ'); // return $days[date('w', $date)].', '.(int)date('d',$date).' '.$months[date('n', $date)].' '.date('y',$date).' г.'; return $days[date('w', $date)]; }
Class properties:
Class methods:
$updateTime = gg("yt_settings.updateTime"); if($updateTime > 0){ $count = gg("yt_settings.countTime"); if($count >= $updateTime){ include_once(DIR_MODULES."app_yatraffic/app_yatraffic.class.php"); $app_yatraffic=new app_yatraffic(); $app_yatraffic->get_traffic(gg("yt_settings.reg_id")); sg("yt_settings.countTime",1); } else { $count++; sg("yt_settings.countTime",$count); } }
include_once(DIR_MODULES."app_yatraffic/app_yatraffic.class.php"); $app_yatraffic=new app_yatraffic(); $app_yatraffic->get_traffic(gg("yt_settings.reg_id"));
Class objects:
Class objects:
, Азербайджан
© 2024 - Site Built By SergeJey | Реквизиты: Курицын С. С. ИНН 762001394609 | Контакты | Public agreement
SmartLiving