Свойства класса:
Методы класса:
$volume=round(65535*$params['VALUE']/100); $this->setProperty('volumeLevel',$params['VALUE']); safe_exec('..\\apps\\nircmd\\nircmdc setsysvolume '.$volume); say("Изменилась громкость до ".$params['VALUE']." процентов");
Объекты класса:
//Записываем текущее время setGlobal('timeNow',date( "H:i", time())); // получим ЧАСЫ и МИНУТЫ отдельно $timeH=date("H", time()); $timeM=date("i", time()); sg("ThisComputer.timeH",$timeH); sg("ThisComputer.timeM",$timeM);
$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); }
say("Отключено питание");
Свойства класса:
Методы класса:
$this->setProperty('LastRun',date('Y-m-d H:i:s'));
$name='Cron_'.$this->object_title; SQLExec("DELETE FROM jobs WHERE title='".$name."'");
Свойства класса:
Методы класса:
//$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); }
Объекты класса:
Свойства класса:
Методы класса:
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);
Свойства класса:
Методы класса:
$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'); // запускаем скрипт "доброе утро" } }
Объекты класса:
Объекты класса:
Методы класса:
Объекты класса:
if (getGlobal('TempSensor01.temp') <= getGlobal('temp_sel.min_t')) { setGlobal('air_v.open','0'); setGlobal('fan.fan_1','0'); } else { if (getGlobal('TempSensor01.temp') >= getGlobal('temp_sel.t')) { setGlobal('air_v.open','0'); setGlobal('fan.fan_1','0'); } else { setGlobal('air_v.open','1'); setGlobal('fan.fan_1','1'); } }
Объекты класса:
Свойства класса:
Методы класса:
$this->setProperty("updated",time()); $this->setProperty("updatedTime",date('H:i')); if ($this->getProperty('active')) { say("Режим ".$this->getProperty('title')." активирован."); } else { say("Режим ".$this->getProperty('title')." выключен."); }
$this->setProperty('active',1);
$this->setProperty('active',0);
Объекты класса:
setGlobal('minMsgLevel','2');
setGlobal('minMsgLevel','1');
Свойства класса:
Методы класса:
$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);
Свойства класса:
Методы класса:
$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")));
Свойства класса:
Методы класса:
$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);
Свойства класса:
Методы класса:
$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");
$this->setProperty('SomebodyHere',0);
$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";
Объекты класса:
Методы класса:
Объекты класса:
echo "status received: ".$params['status'];
global $voicemode; $voicemode='off'; processCommand($params['message']);
Свойства класса:
Методы класса:
Объекты класса:
$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','watchfolders'=>'watch folders','rss'=>'RSS'); 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 (!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; 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'); }
Свойства класса:
Методы класса:
//$params['t'] $this->setProperty("updated",time()); $this->setProperty("updatedTime",date("H:i",time())); $this->setProperty("alive",1); callMethod("TempSensorN.tempChanged"); //вызов метода "средняя температура жилых помещений" $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); }
Объекты класса:
$a = gg('TempSensor03.temp'); $b = gg('TempSensor04.temp'); $temp = ($a + $b) / 2; sg("TempSensorN.temp",$temp);
Методы класса:
Объекты класса:
if (getGlobal('Check1.chek')=="1"); //проверка, что включен режим работы по заходу солнца { if (getGlobal('DarknessMode.active')=="1"); // проверка, что включен режим "Темное время суток" { SetTimeOut("lightOnTimer","callMethod('Rele6.Rele_ON');",10); } // устанавливаем таймер 25 мин.(1500/60), включаем Прожектор1 }
Свойства класса:
Методы класса:
//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*///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
Объекты класса:
$h=(int)date('G',time()); $m=date('i',time()); if (isWeekDay()) { } if (($h>=8) && getGlobal('clockChimeEnabled')) { if ($m=="00") { say(timeNow(),1); } } setGlobal('timeNow',date('H:i')); // получим ЧАСЫ и МИНУТЫ отдельно $timeH=date("H", time()); $timeM=date("i", time()); sg("ThisComputer.timeH",$timeH); sg("ThisComputer.timeM",$timeM); $homeStatus=date('H:i'); if (getGlobal('NobodyHomeMode.active')) { $homeStatus.=' Дома никого'; } else { $homeStatus.=' Дома кто-то есть'; } $homeStatus.=' '.getGlobal('Security.stateDetails'); $homeStatus.=' '.getGlobal('System.stateDetails'); $homeStatus.=' '.getGlobal('Communication.stateDetails'); setGlobal('HomeStatus',$homeStatus); if (timeBetween(getGlobal('Izhevsk.SunRise'),getGlobal('Izhevsk.SunSet')) && getGlobal('isDark')=="1") { setGlobal("isDark",0); callMethod('DarknessMode.deactivate'); } elseif (!timeBetween(getGlobal('Izhevsk.SunRise'),getGlobal('Izhevsk.SunSet')) && getGlobal('isDark')!="1") { setGlobal("isDark",1); callMethod('DarknessMode.activate'); callMethod('Check1.Chek_on'); // вызывем метод включения уличного освещения } //e/ callMethod('temp_ctrl.temp_ctrl'); if (timeIs(getGlobal('Izhevsk.SunRise'))) { say('Всходит солнце'); if (getGlobal('Rele6.chek')==1) {callMethod('Check1.Chek_off');} } if (timeIs(getGlobal('Izhevsk.SunSet'))) { say('Солнце заходит',2); } if (timeIs("23:30") && (gg("EconomMode.active")!="1") && (gg("NobodyHomeMode.active")=="1")) { say("Похоже никого нет сегодня, можно сэкономить немного."); callMethod('EconomMode.activate'); } if (timeIs('23:30')) { callMethod('NightMode.activate'); setGlobal('Rele5.chek',0); if (getGlobal('Check1.chek')==1) {callMethod('Check1.Chek_off');} // выключаем уличное освещение } elseif (timeIs('08:00')) { callMethod('NightMode.deactivate'); setGlobal('Rele5.chek',1); if (getGlobal('Rele6.chek')==1) {callMethod('Check1.Chek_off');} } if (timeIs("03:00")) { runScript("systemMaintenance"); } if (gg('ThisComputer.AlarmStatus') && timeIs(gg('ThisComputer.AlarmTime'))) { runScript('MorningAlarm'); } //вызываем метод вычисления значений виртуальног датчика "Средняя температура жилых помещений" callMethod("TempSensorN.tempChanged"); //вызываем метод обновления погоды.Яндекс каждые 20 минут //if ($m=="00") { // callMethod('Izhevsk.sensors'); //} //if ($m=="20") { // callMethod('Izhevsk.sensors'); //} //if ($m=="40") { // callMethod('Izhevsk.sensors'); //}
Методы класса:
Объекты класса:
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']); } }
Методы класса:
Объекты класса:
callMethod('Rele6.Rele_OFF'); say('Уличное освещение выключено');
$chek=getGlobal('Check1.chek'); if ($chek==1) { SetTimeOut("lightOnTimer","callMethod('Rele6.Rele_ON'); say('Уличное освещение включено');",1500); // устанавливаем таймер }
Методы класса:
// ****************************** // Vovix, 16.11.2015 г. v.1.1 // ****************************** $city_id=gg("Izhevsk.city_id"); //ID города узнаем тут: https://pogoda.yandex.ru/static/cities.xml $data_file="http://export.yandex.ru/weather-ng/forecasts/$city_id.xml?".rand(); // адрес xml файла - 28411 //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)]; }
Объекты класса:
// ****************************** // Vovix, 16.11.2015 г. v.1.1 // ****************************** $city_id=gg("28679"); //ID города узнаем тут: https://pogoda.yandex.ru/static/cities.xml $data_file="http://export.yandex.ru/weather-ng/forecasts/28679.xml?".rand(); // адрес xml файла - 28679 //say($data_file); $xml = simplexml_load_file($data_file); // раскладываем xml на массив // температура вчера в это же время $temp_yesterday=$xml->yesterday->temperature; // Если значение температуры положительно, для наглядности добавляем "+" $temp_yesterday = getTempSign($temp_yesterday); sg("Petro.TempYesterday",$temp_yesterday); // температура сейчас $temp=$xml->fact->temperature; if (date('G')==13) {sg("Petro.Temp13h",$temp);} if (date('G')==21) {sg("Petro.Temp21h",$temp);} $temp = getTempSign($temp); // Если значение температуры положительно, для наглядности добавляем "+" // достаем из XML-файла время его чтения $XMLuptime = $xml->fact->uptime; $XMLuptime = explode("T", $XMLuptime); $XMLuptimeTo = ($XMLuptime[0].' '.$XMLuptime[1]); // addClassProperty('Weather','XMLuptime'); sg("Petro.XMLuptime",$XMLuptimeTo); // сохраняем основные параметры текущей погоды sg("Petro.Temp",$temp); sg("ThisComputer.TempOutside",$temp); sg("Petro.Type",$xml->fact->weather_type); sg("Petro.Pressure",$xml->fact->pressure); sg("Petro.Humidity",$xml->fact->humidity); sg("Petro.WindSpeed",$xml->fact->wind_speed); sg("Petro.Image",$xml->fact->{'image-v3'}); // Определяем время года $season = $xml->fact->season; switch ($season){ case 'winter': $season="зима"; break; case 'summer': $season="лето"; break; case 'autumn': $season="осень"; break; case 'spring': $season="весна"; break; } // определение вероятности дождя 0 или 1 $rain1=gg("Petro.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("Petro.Rain",0); } else { sg("Petro.Rain",1); // say("Возможен дождь",2); } // Направление ветра $dir = $xml->fact->wind_direction; // Функция возвращает массив, поэтому записываем в переменные значения, полученные в функции list ($dir, $dirtext) = getWindDirection($dir); sg("Petro.WindDir",$dir); sg("Petro.WindDirText",$dirtext); // Солнце: восход/закат sg("Petro.SunRise",$xml->day[0]->sunrise); sg("Petro.SunSet",$xml->day[0]->sunset); // Луна sg("Petro.Moon_phase",$xml->day[0]->moon_phase); sg("Petro.MoonRise",$xml->day[0]->moonrise); sg("Petro.MoonSet",$xml->day[0]->moonset); // длинный текстовый прогноз погоды // $metcast=""; $metcast="На улице ".gg("Petro.Type")."."; // ветер $WindSpeed=(float)gg("Petro.WindSpeed"); if ($WindSpeed<1) { $metcast.=' Ветра, скорее всего, нет.'; } elseif ($WindSpeed<3) { $metcast.=' Возможен слабый ветер.'; } elseif ($WindSpeed<6) { $metcast.=' Возможен сильный ветер.'; } elseif ($WindSpeed<9) { $metcast.=' Возможен довольно сильный ветер.'; } else { $metcast.=' Возможен очень сильный ветер.'; } $w=round(strip_tags(gg("Petro.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("Petro.Temp").' '.$tempcels.'.'; $tm=(float)gg("Petro.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("Petro.SunRise").','; // $metcast.=' закат в '.gg("Petro.SunSet").'.'; sg("Petro.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("Petro.forecast",$w3days);
// ****************************** // Vovix, 16.11.2015 г. v.1.1 // ****************************** //$city_id=gg("28679"); //ID города узнаем тут: https://pogoda.yandex.ru/static/cities.xml// //$data_file="http://export.yandex.ru/weather-ng/forecasts/$city_id.xml?".rand(); // адрес xml файла - 28679 //say($data_file); //$xml = simplexml_load_file($data_file); // раскладываем xml на массив $city_id=gg("28679"); //ID города узнаем тут: https://pogoda.yandex.ru/static/cities.xml $data_file="http://export.yandex.ru/weather-ng/forecasts/$city_id.xml?".rand(); // адрес xml файла - 28411 //say($data_file); $xml = simplexml_load_file($data_file); // раскладываем xml на массив if($xml === false ) { return; } // температура вчера в это же время $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); //время года // Обновляем показатели жизни объекта sg("Izhevsk.updatedTimestamp", time()); sg("Izhevsk.updatedTime", date( "H:i - d.m.Y", time())); // Проговариваем, при необходимости $sayMetUSD = gg ("Sets.sayMetUSD"); if ($sayMetUSD) { say("Читаю прогноз погоды на 3 дня с 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]); }
Свойства класса:
Объекты класса:
Объекты класса:
, Казахстан
© 2024 - Site Built By SergeJey | Реквизиты: Курицын С. С. ИНН 762001394609 | Контакты | Публичный договор
SmartLiving