Пример #1
0
 private function __construct()
 {
     $this->processedReportsModel = new ScheduleTypeReportProcessed();
     $this->synchronization = new Synchronization();
     $this->_logger = LoggerFactory::getFileLogger('ExchangeODSS');
     TimezoneWork::set('UTC');
 }
 public function init()
 {
     parent::init();
     ini_set('memory_limit', '-1');
     set_time_limit(0);
     // All reports are generated basing on data in UTC time.
     TimezoneWork::set('UTC');
 }
Пример #3
0
 public function init()
 {
     parent::init();
     ini_set('memory_limit', '-1');
     set_time_limit(0);
     self::$_logger = LoggerFactory::getFileLogger('reports');
     // All reports are generated basing on data in UTC time.
     TimezoneWork::set('UTC');
 }
Пример #4
0
 public function beforeSave()
 {
     if (!$this->getUseLong() && $this->beforeSave) {
         if ($this->isNewRecord) {
             $this->created = new CDbExpression('NOW()');
         }
         $this->timezone_offset = TimezoneWork::getOffsetFromUTC($this->timezone_id, 1);
         $this->updated = new CDbExpression('NOW()');
     }
     return parent::beforeSave();
 }
Пример #5
0
 public function getTZOffset($unit = 's')
 {
     $tz = $this->getTZ();
     $offset = TimezoneWork::getOffsetFromUTC($tz);
     if ($unit == 'm') {
         return $offset / 60;
     } else {
         if ($unit == 'h') {
             return $offset / 3600;
         }
     }
     return $offset;
 }
 public function actionIndex()
 {
     // return maintenance to framework
     //Listener::checkPreparingProcess();
     $route = Yii::app()->getUrlManager()->parseUrl(Yii::app()->getRequest());
     if (strtolower($route) != strtolower('update/CheckExtraUpdate')) {
         if (isset($_POST['change_timezone_id'])) {
             Yii::app()->user->setTZ($_POST['change_timezone_id']);
         }
         $tz = Yii::app()->user->getTZ();
         // Set timezone in either case, because mysql timezone settings can differ from php
         //				if ($tz != date_default_timezone_get())
         //				{
         TimezoneWork::set($tz);
         //				}
     }
     Yii::app()->runController($route);
 }
Пример #7
0
 protected function _init()
 {
     $this->_logger->log(__METHOD__);
     $current_user_timezone = date_default_timezone_get();
     $timezone_id = 'UTC';
     if ($timezone_id != $current_user_timezone) {
         TimezoneWork::set($timezone_id);
     }
     $this->_prepareScheduleInfo();
     $this->_prepareListenerLogInfo();
     $this->_prepareStationInfo();
     if ($timezone_id != $current_user_timezone) {
         TimezoneWork::set($current_user_timezone);
     }
     if ($this->errors) {
         return false;
     }
     return true;
 }
Пример #8
0
 public function generate()
 {
     $this->_logger->log(__METHOD__);
     if ($this->errors) {
         $this->_logger->log(__METHOD__, array('errors' => $this->errors));
         return false;
     }
     $current_user_timezone = date_default_timezone_get();
     $timezone_id = 'UTC';
     if ($timezone_id != $current_user_timezone) {
         TimezoneWork::set($timezone_id);
     }
     $this->report_parts = array();
     $this->explanations = array();
     // get sensors' values for all messages received in reporting period
     $sql = "SELECT `t5`.`listener_log_id`,\r\n                       `t5`.`measuring_timestamp`,\r\n                       `t1`.`station_sensor_id`, `t1`.`sensor_id_code`, \r\n                       \r\n                       `t3`.`feature_code`, `t3`.`feature_constant_value`,\r\n                       `t4`.`code` AS `metric_code`, \r\n                       `t5`.`sensor_feature_value`, \r\n                       `t5`.`is_m`,\r\n                       `t5`.`period` AS `sensor_feature_period`,\r\n                       `t6`.`code` AS `value_metric_code`,\r\n                       `t7`.`handler_id_code`\r\n\r\n                FROM `" . SensorData::model()->tableName() . "`  `t5`\r\n                LEFT JOIN `" . StationSensor::model()->tableName() . "`        `t1` ON t1.station_sensor_id = t5.sensor_id\r\n                LEFT JOIN `" . StationSensorFeature::model()->tableName() . "` `t3` ON (`t3`.`sensor_feature_id` = `t5`.`sensor_feature_id`)\r\n                LEFT JOIN `" . RefbookMetric::model()->tableName() . "`        `t4` ON `t4`.`metric_id` = `t3`.`metric_id`\r\n                LEFT JOIN `" . RefbookMetric::model()->tableName() . "`        `t6` ON `t6`.`metric_id` = `t5`.`metric_id`\r\n                LEFT JOIN `" . SensorDBHandler::model()->tableName() . "`      `t7` ON t7.handler_id = t1.handler_id\r\n                WHERE `t5`.`station_id` = '" . $this->station_info->station_id . "' AND `t5`.`listener_log_id` IN (" . $this->schedule_process_info->listener_log_ids . ")\r\n                ORDER BY `t5`.`measuring_timestamp` DESC, `t1`.`sensor_id_code` ASC, `t3`.`feature_code` ASC";
     $sensor_data = Yii::app()->db->createCommand($sql)->queryAll();
     $data = array();
     if ($sensor_data) {
         // get calculation values for all messages received in reporting period
         $sql = "SELECT `t1`.`listener_log_id`,\r\n                           `t1`.`value`,\r\n                           `t3`.`handler_id_code`\r\n                    FROM `" . StationCalculationData::model()->tableName() . "`    `t1`\r\n                    LEFT JOIN `" . StationCalculation::model()->tableName() . "`   `t2` ON t2.calculation_id = t1.calculation_id\r\n                    LEFT JOIN `" . CalculationDBHandler::model()->tableName() . "` `t3` ON `t3`.`handler_id` = `t2`.`handler_id`\r\n                    WHERE `t2`.`station_id` = '" . $this->station_info->station_id . "' AND `t1`.`listener_log_id` IN (" . $this->schedule_process_info->listener_log_ids . ")\r\n                    ORDER BY `t3`.`handler_id_code`";
         $res2 = Yii::app()->db->createCommand($sql)->queryAll();
         if ($res2) {
             foreach ($res2 as $key => $value) {
                 $calculations[$value['listener_log_id']][] = $value;
             }
         }
         foreach ($sensor_data as $key => $value) {
             $data[$value['listener_log_id']][] = $value;
         }
         // prepare $result_item array, where each line represents line in report.
         foreach ($data as $key => $value) {
             $result_item = array('StationId', $this->station_info->station_id_code, 'WMO AWS #', $this->station_info->wmo_block_number . $this->station_info->station_number, 'National AWS #', $this->station_info->national_aws_number, 'Tx DateTime', date('m/d/Y H:i', strtotime($value[0]['measuring_timestamp'])));
             foreach ($value as $key2 => $value2) {
                 $handler_obj = SensorHandler::create($value2['handler_id_code']);
                 if (in_array($value2['handler_id_code'], array('BatteryVoltage', 'Humidity', 'Pressure', 'Temperature'))) {
                     $sensor_id_code = $value2['sensor_id_code'];
                 } else {
                     $sensor_id_code = $value2['sensor_id_code'] . ' (' . $handler_obj->getFeatureName($value2['feature_code']) . ')';
                 }
                 $result_item[] = $sensor_id_code;
                 if ($value2['is_m']) {
                     $result_item[] = '-';
                 } else {
                     $value2['sensor_feature_value'] = $handler_obj->applyOffset($value2['sensor_feature_value'], $this->station_info->magnetic_north_offset);
                     $result_item[] = str_replace(',', ' ', $handler_obj->formatValue($value2['sensor_feature_value'], $value2['feature_code']));
                 }
             }
             if (isset($calculations[$key])) {
                 foreach ($calculations[$key] as $key2 => $value2) {
                     if ($value2['handler_id_code'] === 'DewPoint') {
                         $result_item[] = 'DP';
                     } else {
                         if ($value2['handler_id_code'] === 'PressureSeaLevel') {
                             $result_item[] = 'MSL';
                         } else {
                             $result_item[] = 'Unknown calculation';
                         }
                     }
                     $result_item[] = str_replace(',', ' ', number_format(round($value2['value'], 1), 1));
                 }
             }
             $this->report_parts[] = $result_item;
         }
     }
     if ($timezone_id != $current_user_timezone) {
         TimezoneWork::set($current_user_timezone);
     }
     $this->_logger->log(__METHOD__ . ' Export generation completed.');
     return true;
 }
Пример #9
0
</a></li>
                    <?php 
}
?>
                </ul>
                <br/><br/>
                <div id="header_time">
                    <form action="<?php 
echo $this->createUrl($cur_route);
?>
" method="post" id="TZChangeForm">
                        <div class="time text"><?php 
echo Yii::app()->user->getTZ();
?>
 (<?php 
echo TimezoneWork::getOffsetFromUTC(Yii::app()->user->getTZ(), 1);
?>
)</div>
                        <div class="text">
                            <?php 
echo date('M d');
?>
,
                            <span id="jclock2"></span>
                        </div>
                        <div class="delimiter time text">UTC (GMT +00:00)</div> 
                        <div class="text">
                            <?php 
echo gmdate('M d');
?>
,
Пример #10
0
 public function generate()
 {
     $this->_logger->log(__METHOD__);
     $current_user_timezone = date_default_timezone_get();
     $timezone_id = 'UTC';
     if ($timezone_id != $current_user_timezone) {
         TimezoneWork::set($timezone_id);
     }
     if (is_null($this->listener_log_info)) {
         return false;
     }
     $this->_logger->log(__METHOD__ . "this->listener_log_info->log_id " . $this->listener_log_info->log_id);
     $this->sensors = $this->prepareSensorsInfo($this->listener_log_info->log_id);
     $this->calculations = $this->_prepareCalculationsInfo($this->listener_log_info->log_id);
     if ($timezone_id != $current_user_timezone) {
         TimezoneWork::set($current_user_timezone);
     }
     if ($this->errors) {
         $this->_logger->log(__METHOD__, array('errors' => $this->errors));
         return false;
     }
     $this->report_parts = array();
     $this->explanations = array();
     $measuring_timestamp = strtotime($this->listener_log_info->measuring_timestamp);
     $measuring_day = gmdate('d', $measuring_timestamp);
     $measuring_hour = gmdate('H', $measuring_timestamp);
     $measuring_minute = gmdate('i', $measuring_timestamp);
     $section = 0;
     $i = 0;
     // Section #0 - #0
     // CONSTANT
     $this->report_parts[$section][$i] = 'AAXX';
     $this->explanations[$section][$i][] = '<span>AAXX</span>: Fixed';
     $i++;
     $this->explanations[$section][$i][] = ' ';
     // Section #0 - #1
     // Day of the month (UTC), with 01 indicating the first day, 02 the second day,
     // etc.: @DTKY01111229 => 29
     $this->report_parts[$section][$i] = $measuring_day;
     $this->explanations[$section][$i][] = "<span>" . $this->report_parts[$section][$i] . "</span>: Day of the month. Measurement timestamp = '" . $this->listener_log_info->measuring_timestamp . " UTC'";
     // Section #0 - #2
     // Actual time of observation, to the nearest whole hour UTC (Barometer reading time)
     // (round up or down to nearest hour):
     // @DTKY011112290653 => 0653 => 07
     $this->report_parts[$section][$i] .= $measuring_minute >= 30 ? $measuring_hour + 1 : $measuring_hour;
     $this->explanations[$section][$i][] = "<span>" . $measuring_hour . "</span>: Actual time of observation, to the nearest whole hour UTC." . ($measuring_minute >= 30 ? ' +1 = ' . ($measuring_hour + 1) . '. Because minutes >= 30' : '');
     // Section #0 - #3
     // Indicator for source and units of wind speed (1 = m/s) => taken from table 1855
     if (isset($this->sensors['wind_speed_10'])) {
         if ($this->sensors['wind_speed_10']['metric_code'] === 'meter_per_second') {
             $this->report_parts[$section][$i] .= '1';
             $this->explanations[$section][$i][] = "<span>1</span>: Indicator for source and units of wind speed. Sensor " . $this->sensors['wind_speed_10']['sensor_id_code'] . " metric is 'meter_per_second' (see table 1855)";
         } else {
             if ($this->sensors['wind_speed_10']['metric_code'] === 'knot') {
                 $this->report_parts[$section][$i] .= '4';
                 $this->explanations[$section][$i][] = "<span>4</span>: Indicator for source and units of wind speed. Sensor " . $this->sensors['wind_speed_10']['sensor_id_code'] . " metric is 'knot' (see table 1855)";
             } else {
                 $this->report_parts[$section][$i] .= '/';
                 $this->explanations[$section][$i][] = "<span>/</span>: Indicator for source and units of wind speed. Sensor " . $this->sensors['wind_speed_10']['sensor_id_code'] . " metric is '" . $this->sensors['wind_speed_10']['metric_code'] . "' wich has not association in Table 1855";
             }
         }
     } else {
         $this->report_parts[$section][$i] .= '/';
         $this->explanations[$section][$i][] = "<span>/</span>: Indicator for source and units of wind speed. Station has not Wind Speed sensor";
     }
     $i++;
     $this->explanations[$section][$i][] = ' ';
     // Section #0 - #4
     // WMO Block# (take from the station setup) => admin > stations > tky01 = 08 (make sure to add the 0's)
     $this->report_parts[$section][$i] = str_pad($this->station_info['wmo_block_number'], 2, '0', STR_PAD_LEFT);
     $this->explanations[$section][$i][] = '<span>' . $this->station_info['wmo_block_number'] . '</span>: WMO Block#.';
     // Section #0 - #5
     // WMO Station # (take from the station setup) => admin > stations > tky01 = 007
     $this->report_parts[$section][$i] .= str_pad($this->station_info['station_number'], 3, '0', STR_PAD_LEFT);
     $this->explanations[$section][$i][] = '<span>' . $this->station_info['station_number'] . '</span>: WMO Station#.';
     $i++;
     $section = 1;
     // SECTION #1
     // Section #1 - #0
     // Indicator for inclusion or omission of precipitation data (Table 1819):
     // RN1038003018114366: there was rain, we only include in section 1
     $this->report_parts[$section][$i] = isset($this->sensors['rain_in_period']) ? '1' : '0';
     $this->explanations[$section][$i][] = "<span>" . (isset($this->sensors['rain_in_period']) ? '1' : '0') . "</span>: Indicator for RAIN inclusion. The station has rain sensor " . $this->sensors['rain_in_period']['sensor_id_code'];
     // Section #1 - #1
     // Indicator for type of station operation (manned or automatic) and for present and past weather data (1860):
     // 6 (if automatic) or 3 (if manned)..
     $this->report_parts[$section][$i] .= '6';
     $this->explanations[$section][$i][] = "<span>6</span>: Automatic station. Because all stations in this software are automatic.";
     // If Cloud Amount Height is present then take it, otherwise - Cloud Depth Height
     $cloudHeightSensor = isset($this->sensors['cloud_amount_height_1']) ? $this->sensors['cloud_amount_height_1'] : (isset($this->sensors['cloud_height_height_1']) ? $this->sensors['cloud_height_height_1'] : null);
     // Section #1 - #2
     // Height above surface of the base of the lowest cloud seen
     if (!is_null($cloudHeightSensor)) {
         if ($cloudHeightSensor['is_m'] == 1) {
             $this->report_parts[$section][$i] .= '/';
             $this->explanations[$section][$i][] = "<span>/</span>: Height above surface of the base of the lowest cloud seen. Because Cloud Sensor height#1 value is unavailable";
         } else {
             $tmp_data = It::convertMetric($cloudHeightSensor['sensor_feature_value'], $cloudHeightSensor['metric_code'], 'meter');
             $tmp_data2 = $this->_get_cloud_height_code($tmp_data);
             $this->report_parts[$section][$i] .= $tmp_data2;
             $this->explanations[$section][$i][] = "<span>" . $tmp_data2 . "</span>: Height above surface of the base of the lowest cloud seen. (Cloud Height #1 = " . round($cloudHeightSensor['sensor_feature_value'], 1) . " " . $cloudHeightSensor['metric_code'] . " = " . round($tmp_data, 1) . " meter, see table 1600.)";
         }
     } else {
         $this->report_parts[$section][$i] .= '/';
         $this->explanations[$section][$i][] = "<span>/</span>: Height above surface of the base of the lowest cloud seen. Because no Cloud Sensor";
     }
     // Section #1 - #3
     // Horizontal visibility at surface
     if (isset($this->sensors['visibility_1'])) {
         if ($this->sensors['visibility_1']['is_m']) {
             $this->report_parts[$section][$i] .= '//';
             $this->explanations[$section][$i][] = "<span>//</span>: Horizontal visibility at surface. Because value of Visibility Sensor is unavailable.";
         } else {
             $tmp_data = It::convertMetric($this->sensors['visibility_1']['sensor_feature_value'], $this->sensors['visibility_1']['metric_code'], 'kilometer');
             $tmp_data2 = $this->_get_visibility_code($tmp_data);
             $this->report_parts[$section][$i] .= $tmp_data2;
             $this->explanations[$section][$i][] = "<span>" . $tmp_data2 . "</span>: Horizontal visibility at surface. (Visibility = " . round($this->sensors['visibility_1']['sensor_feature_value'], 1) . " " . $this->sensors['visibility_1']['metric_code'] . " = " . round($tmp_data, 1) . " km, See table 4377) ";
         }
     } else {
         $this->report_parts[$section][$i] .= '//';
         $this->explanations[$section][$i][] = "<span>//</span>: Horizontal visibility at surface. Because no Visibility Sensor";
     }
     $i++;
     $this->explanations[$section][$i][] = ' ';
     // Section #1 - #4
     // Cloud cover (2700)
     if (isset($this->sensors['cloud_amount_amount_total'])) {
         if ($this->sensors['cloud_amount_amount_total']['is_m']) {
             $this->report_parts[$section][$i] = '/';
             $this->explanations[$section][$i][] = "<span>/</span>: Cloud cover. Because value of Cloud Sensor is unavailable";
         } else {
             $tmp_data = $this->_get_cloud_cover_code(round($this->sensors['cloud_amount_amount_total']['sensor_feature_value'], 1));
             $this->report_parts[$section][$i] = $tmp_data;
             $this->explanations[$section][$i][] = "<span>" . $tmp_data . "</span>: Cloud cover. (Cloud Amount #1 = " . round($this->sensors['cloud_amount_amount_total']['sensor_feature_value']) . "/8. See code table 2700)";
         }
     } else {
         $this->report_parts[$section][$i] = '/';
         $this->explanations[$section][$i][] = "<span>/</span>: Cloud cover. Because no info about Cloud Amount";
     }
     // Section #1 - #5
     // True Wind Direction (Table 0877)
     // Example: WD11245 => 245 degrees => table 0877 => 25
     if (isset($this->sensors['wind_direction_10'])) {
         if ($this->sensors['wind_direction_10']['is_m']) {
             $this->report_parts[$section][$i] .= '//';
             $this->explanations[$section][$i][] = "<span>//</span>: True Wind Direction. Because value of Wind Direction sensor is unavailable.";
         } else {
             $handler_obj = SensorHandler::create($this->sensors['wind_direction_10']['handler_id_code']);
             $value = $handler_obj->applyOffset($this->sensors['wind_direction_10']['sensor_feature_value'], $this->station_info['magnetic_north_offset']);
             $value = It::convertMetric($value, $this->sensors['wind_direction_10']['metric_code'], 'degree');
             $tmp_val = $this->_get_wind_direction_code($value);
             $this->report_parts[$section][$i] .= $tmp_val;
             $this->explanations[$section][$i][] = "<span>" . $tmp_val . "</span>: True Wind Direction. Because value of " . $this->sensors['wind_direction_10']['sensor_id_code'] . ' = ' . $value . ' degree. See table 0877.';
         }
     } else {
         $this->report_parts[$section][$i] .= '//';
         $this->explanations[$section][$i][] = "<span>//</span>: True Wind Direction. Because no Wind Direction sensor";
     }
     // Section #1 - #6
     // Wind Speed in Units (rounded meter per second )
     // Example: WS23069006540632 => instantaneous = 0690
     if (isset($this->sensors['wind_speed_10'])) {
         if ($this->sensors['wind_speed_10']['is_m']) {
             $this->report_parts[$section][$i] .= '//';
             $this->explanations[$section][$i][] = "<span>//</span>: Because value of Wind Speed sensor is unavailable.";
         } else {
             $value = It::convertMetric($this->sensors['wind_speed_10']['sensor_feature_value'], $this->sensors['wind_speed_10']['metric_code'], 'meter_per_second');
             $tmp_val = round($value);
             $tmp_val = substr($tmp_val, -2);
             $tmp_val = str_pad($tmp_val, 2, '0', STR_PAD_LEFT);
             $this->report_parts[$section][$i] .= $tmp_val;
             $this->explanations[$section][$i][] = "<span>" . $tmp_val . "</span> m/s: Wind Speed in Units. Because value of " . $this->sensors['wind_speed_10']['sensor_id_code'] . " = " . $this->sensors['wind_speed_10']['sensor_feature_value'] . " " . $this->sensors['wind_speed_10']['metric_code'];
         }
     } else {
         $this->report_parts[$section][$i] .= '//';
         $this->explanations[$section][$i][] = "<span>//</span>: Wind Speed in Units. Because no Wind Speed sensor.";
     }
     $i++;
     $this->explanations[$section][$i][] = ' ';
     // Section #1 - #7
     // FIXED
     $this->report_parts[$section][$i] = '1';
     $this->explanations[$section][$i][] = '<span>1</span>: Fixed.';
     // Section #1 - #8 - Sign of the data (Code table 3845), in this case relative to temperature (Celsius): TP11772
     // Section #1 - #9 - Air temperature, in tenths of a degree Celsius (observed): TP11772
     if (isset($this->sensors['temperature'])) {
         if ($this->sensors['temperature']['is_m']) {
             $this->report_parts[$section][$i] .= '/';
             $this->explanations[$section][$i][] = "<span>/</span>: Sign of the temperature data (Celsius). Because value of Temperature Sensor is unavailable.";
             $this->report_parts[$section][$i] .= '///';
             $this->explanations[$section][$i][] = "<span>///</span>: Air temperature, in tenths of a degree Celsius. Because value Temperature Sensor is unavailable.";
         } else {
             $value = It::convertMetric($this->sensors['temperature']['sensor_feature_value'], $this->sensors['temperature']['metric_code'], 'celsius');
             $tmp_val = $value >= 0 ? '0' : '1';
             $this->report_parts[$section][$i] .= $tmp_val;
             $this->explanations[$section][$i][] = "<span>" . $tmp_val . "</span>: Sign of the temperature data (Celsius). Because value of " . $this->sensors['temperature']['sensor_id_code'] . " = " . $value . " Celsius degree" . ($this->sensors['temperature']['metric_code'] != 'celsius' ? ' (' . $this->sensors['temperature']['sensor_feature_value'] . ' ' . $this->sensors['temperature']['metric_code'] . ')' : '') . ". See table 3845.";
             $tmp_val = abs(round($value * 10));
             $tmp_val = substr($tmp_val, -3);
             $tmp_val = str_pad($tmp_val, 3, '0', STR_PAD_LEFT);
             $this->report_parts[$section][$i] .= $tmp_val;
             $this->explanations[$section][$i][] = "<span>" . $tmp_val . "</span>: Air temperature, in tenths of a degree Celsius. Because value of " . $this->sensors['temperature']['sensor_id_code'] . " = " . $value . " Celsius degree" . ($this->sensors['temperature']['metric_code'] != 'celsius' ? ' (' . $this->sensors['temperature']['sensor_feature_value'] . ' ' . $this->sensors['temperature']['metric_code'] . ')' : '') . "";
         }
     } else {
         $this->report_parts[$section][$i] .= '/';
         $this->explanations[$section][$i][] = "<span>/</span>: Sign of the temperature data (Celsius). Because no Temperature Sensor.";
         $this->report_parts[$section][$i] .= '///';
         $this->explanations[$section][$i][] = "<span>///</span>: Air temperature, in tenths of a degree Celsius. Because no Temperature Sensor.";
     }
     $i++;
     $this->explanations[$section][$i][] = " ";
     // Section #1 - #10 FIXED
     $this->report_parts[$section][$i] = '2';
     $this->explanations[$section][$i][] = "<span>2</span>: Fixed.";
     // Section #1 - #11 - Sign of the data (Code table 3845), in this case relative to DewPoint or Humidity (if there is now DewPoint)
     // Section #1 - #12 - Dew Point (include if calculated), else Humidity (HU in case sn =9) (observed) => no DewPoint or Humidity.. Can we exclude it? Have to add '///'? Can we exclude 'Sn' as well?
     if (isset($this->calculations['DewPoint'])) {
         $tmp_val = $this->calculations['DewPoint']['value'] >= 0 ? '0' : '1';
         $this->report_parts[$section][$i] .= $tmp_val;
         $this->explanations[$section][$i][] = "<span>" . $tmp_val . "</span>: Sign of the data (Code table 3845), in this case relative to DewPoint or Humidity (if there is no DewPoint). Because 1) we have DewPoint; 2) DewPoint value is = " . $this->calculations['DewPoint']['value'];
         $tmp_val = round(abs($this->calculations['DewPoint']['value'] * 10));
         $tmp_val = substr($tmp_val, -3);
         $tmp_val = str_pad($tmp_val, 3, '0', STR_PAD_LEFT);
         $this->report_parts[$section][$i] .= $tmp_val;
         $this->explanations[$section][$i][] = "<span>" . $tmp_val . "</span>: Dew Point (include if calculated), else Humidity (HU in case sn=9). Because we have Dew Point calculation and its vaue = " . $this->calculations['DewPoint']['value'];
     } else {
         if (isset($this->sensors['humidity']) && !$this->sensors['humidity']['is_m']) {
             $this->report_parts[$section][$i] .= '9';
             $this->explanations[$section][$i][] = "<span>" . $tmp_val . "</span>: Sign of the data (Code table 3845), in this case relative to DewPoint or Humidity (if there is no DewPoint). Because 1) we have don't have DewPoint, but we have Humidity; 2) result is 9 according to table 3845.";
             $tmp_val = round($this->sensors['humidity']['sensor_feature_value']);
             $tmp_val = substr($tmp_val, -3);
             $tmp_val = str_pad($tmp_val, 3, '0', STR_PAD_LEFT);
             $this->report_parts[$section][$i] .= $tmp_val;
             $this->explanations[$section][$i][] = "<span>" . $tmp_val . "</span>: Dew Point (include if calculated), else Humidity (HU in case sn=9). Because we don't have DewPoint calculation, but we have Humidity Sensor " . $this->sensors['humidity']['sensor_id_code'] . ' with value = ' . $this->sensors['humidity']['sensor_feature_value'] . '%';
         } else {
             $this->report_parts[$section][$i] .= '/';
             $this->explanations[$section][$i][] = "<span>/</span>: Sign of the data (Code table 3845), in this case relative to DewPoint or Humidity (if there is no DewPoint). Because Station has not DewPoint Calculation, Humidity Sensor";
             $this->report_parts[$section][$i] .= '///';
             $this->explanations[$section][$i][] = "<span>///</span>: Dew Point (include if calculated), else Humidity (HU in case sn=9). Because Station has not DewPoint Calculation, Humidity Sensor";
         }
     }
     $i++;
     $this->explanations[$section][$i][] = " ";
     // Section #1 - #13
     // FIXED
     $this->report_parts[$section][$i] = '3';
     $this->explanations[$section][$i][] = "<span>3</span>: Fixed.";
     // Section #1 - #14
     // Pressure at station level, in tenths of a hectopascal, omitting thousands
     // digit of hectopascals of the pressure value. (observed)
     // Example: PR105090
     if (isset($this->sensors['pressure'])) {
         if ($this->sensors['pressure']['is_m']) {
             $this->report_parts[$section][$i] .= '////';
             $this->explanations[$section][$i][] = "<span>////</span>: Pressure at station level, in tenths of a hectopascal, omitting thousands digit of hectopascals of the pressure value. Because value of Pressure Sensor is unavailable.";
         } else {
             $value = It::convertMetric($this->sensors['pressure']['sensor_feature_value'], $this->sensors['pressure']['metric_code'], 'hpascal');
             $tmp_val = round($value * 10);
             $tmp_val = substr($tmp_val, -4);
             $tmp_val = str_pad($tmp_val, 4, '0', STR_PAD_LEFT);
             $this->report_parts[$section][$i] .= $tmp_val;
             $this->explanations[$section][$i][] = "<span>" . $tmp_val . "</span>: Pressure at station level, in tenths of a hectopascal, omitting thousands digit of hectopascals of the pressure value. Because value of Pressure Sensor " . $this->sensors['pressure']['sensor_id_code'] . ' = ' . $this->sensors['pressure']['sensor_feature_value'] . ' ' . $this->sensors['pressure']['metric_code'] . ($this->sensors['pressure']['metric_code'] != 'hpascal' ? ' (' . $value . ' hPa)' : '');
         }
     } else {
         $this->report_parts[$section][$i] .= '////';
         $this->explanations[$section][$i][] = "<span>////</span>: Pressure at station level, in tenths of a hectopascal, omitting thousands digit of hectopascals of the pressure value. Because no Pressure Sensor.";
     }
     $i++;
     $this->explanations[$section][$i][] = " ";
     // Section #1 - #15 FIXED
     $this->report_parts[$section][$i] = '4';
     $this->explanations[$section][$i][] = "<span>4</span>: Fixed.";
     // Section #1 - #16 - Pressure at mean sea level, in tenths of a hectopascal, omitting thousands digit of hectopascals of the pressure value. (assuming accurate adjustment to sea level in possible) (Calculated)
     if (isset($this->calculations['PressureSeaLevel'])) {
         $tmp_val = round(abs($this->calculations['PressureSeaLevel']['value'] * 10));
         $tmp_val = substr($tmp_val, -4);
         $tmp_val = str_pad($tmp_val, 4, '0', STR_PAD_LEFT);
         $this->report_parts[$section][$i] .= $tmp_val;
         $this->explanations[$section][$i][] = "<span>" . $tmp_val . "</span>: Pressure at mean sea level, in tenths of a hectopascal, omitting thousands digit of hectopascals of the pressure value. Because Pressure MSL=" . $this->calculations['PressureSeaLevel']['value'];
     } else {
         $this->report_parts[$section][$i] .= '////';
         $this->explanations[$section][$i][] = "<span>////</span>: Pressure at mean sea level, in tenths of a hectopascal, omitting thousands digit of hectopascals of the pressure value. Because no calculation Pressure MSL";
     }
     $i++;
     $this->explanations[$section][$i][] = " ";
     // Section #1 - #17 - FIXED
     $this->report_parts[$section][$i] = '6';
     $this->explanations[$section][$i][] = "<span>6</span>: Fixed.";
     // Section #1 - #18
     // Amount of precipitation which has fallen during the period preceding the time of observation, as indicated by tR (Table 3590)
     if (isset($this->sensors['rain_in_period'])) {
         if ($this->sensors['rain_in_period']['is_m']) {
             $this->report_parts[$section][$i] .= '///';
             $this->explanations[$section][$i][] = '<span>///</span>: Amount of precipitation which has fallen during the period preceding the time of observation. Because value of Rain Sensor is unavailable.';
         } else {
             $value = It::convertMetric($this->sensors['rain_in_period']['sensor_feature_value'], $this->sensors['rain_in_period']['metric_code'], 'millimeter');
             $tmp_val = $this->_get_rain_code($value);
             $this->report_parts[$section][$i] .= $tmp_val;
             $this->explanations[$section][$i][] = "<span>" . $tmp_val . "</span>: Amount of precipitation which has fallen during the period preceding the time of observation. Because value of Rain Sensor " . $this->sensors['rain_in_period']['sensor_id_code'] . " = " . $this->sensors['rain_in_period']['sensor_feature_value'] . ' ' . $this->sensors['rain_in_period']['metric_code'] . ', see table 3590 to understand result.';
         }
     } else {
         $this->report_parts[$section][$i] .= '///';
         $this->explanations[$section][$i][] = '<span>///</span>: Amount of precipitation which has fallen during the period preceding the time of observation. Because no Rain sensor';
     }
     // Section #1 - #19
     // Duration of period of reference for amount of precipitation (Table 4019);
     // This depends upon the period of transmission of SYNOP. If hourly transmission then the data should be for 1 hour.
     $tmp_val = $this->_get_duration_of_synop_transmission($this->schedule_info->period);
     $this->report_parts[$section][$i] .= $tmp_val;
     $this->explanations[$section][$i][] = "<span>" . $tmp_val . "</span>: Duration of period of reference for amount of precipitation. Because period of SYNOP transmission is " . $this->schedule_info->period . ' minutes, see table 4019 to understand result';
     $i++;
     // Section #2 is not included
     // Section #3 - #20 - FIXED
     $section = 3;
     $this->report_parts[$section][$i] = '333';
     $this->explanations[$section][$i][] = '<span>333</span>: Fixed.';
     $i++;
     $this->explanations[$section][$i][] = " ";
     $this->report_parts[$section][$i] = '5';
     $this->explanations[$section][$i][] = "<span>5</span>: Fixed.";
     //$i++;
     if ((!isset($this->sensors['solar_radiation_in_period']) || $this->sensors['solar_radiation_in_period']['is_m']) && (!isset($this->sensors['sun_duration_in_period']) || $this->sensors['sun_duration_in_period']['is_m'])) {
         $this->report_parts[$section][$i] = '/////////';
         $this->explanations[$section][$i][] = "<span>/////////</span>: No Solar Radiation, no Sun Duration sensor.";
     } else {
         $this->report_parts[$section][$i] = '53';
         $this->explanations[$section][$i][] = "<span>53</span>: Is fixed.";
         if (isset($this->sensors['solar_radiation_in_period'])) {
             $tmp_val = ceil($this->sensors['solar_radiation_in_period']['sensor_feature_period'] / 6);
             $tmp_val = substr($tmp_val, -2);
             $tmp_val = str_pad($tmp_val, 2, '0', STR_PAD_LEFT);
             $this->report_parts[$section][$i] .= $tmp_val;
             $this->explanations[$section][$i][] = "<span>" . $tmp_val . "</span>: Duration of period for Solar Radiation " . $this->sensors['solar_radiation_in_period']['sensor_id_code'] . " (" . $this->sensors['solar_radiation_in_period']['sensor_feature_period'] . " / 6). Highest whole figure was taken.";
             $this->report_parts[$section][$i] .= '2';
             $this->explanations[$section][$i][] = "<span>2</span>: Fixed and = 2, because period of Solar Radiation " . $this->sensors['solar_radiation_in_period']['sensor_id_code'] . " was taken (Not period of Sun Duration). Period for Solar Radiation (" . $this->sensors['solar_radiation_in_period']['sensor_feature_period'] . " / 6). Highest whole figure was taken.";
             $value = It::convertMetric($this->sensors['solar_radiation_in_period']['sensor_feature_value'], $this->sensors['solar_radiation_in_period']['metric_code'], 'kjoule_per_sq_meter');
             $tmp_val = substr(round($value), -4);
             $tmp_val = str_pad($tmp_val, 4, '0', STR_PAD_LEFT);
             $this->report_parts[$section][$i] .= $tmp_val;
             $this->explanations[$section][$i][] = "<span>" . $tmp_val . "</span>: Value of Solar Radiation Sensor " . $this->sensors['solar_radiation_in_period']['sensor_id_code'] . " = " . $this->sensors['solar_radiation_in_period']['sensor_feature_value'] . ' ' . $this->sensors['solar_radiation_in_period']['metric_code'] . ($this->sensors['solar_radiation_in_period']['metric_code'] != 'kjoule_per_sq_meter' ? ' ( = ' . $value . ' kjoule_per_sq_meter)' : '');
         } else {
             $tmp_val = ceil($this->sensors['sun_duration_in_period']['sensor_feature_period'] / 6);
             $tmp_val = substr($tmp_val, -2);
             $tmp_val = str_pad($tmp_val, 2, '0', STR_PAD_LEFT);
             $this->report_parts[$section][$i] .= $tmp_val;
             $this->explanations[$section][$i][] = "<span>" . $tmp_val . "</span>: Duration of period for Sun Duration " . $this->sensors['sun_duration_in_period']['sensor_id_code'] . " measurememt (" . $this->sensors['sun_duration_in_period']['sensor_feature_period'] . " / 6). Highest whole figure was taken.";
             $this->report_parts[$section][$i] .= '3';
             $this->explanations[$section][$i][] = "<span>3</span>: Fixed and = 3, because period of Sun Duration " . $this->sensors['sun_duration_in_period']['sensor_id_code'] . " was taken (Not period of Solar Radiation). Period for Sun Duration (" . $this->sensors['sun_duration_in_period']['sensor_feature_period'] . " / 6). Highest whole figure was taken.";
             $tmp_val = round($this->sensors['sun_duration_in_period']['sensor_feature_value']);
             $tmp_val = substr($tmp_val, -4);
             $tmp_val = str_pad($tmp_val, 4, '0', STR_PAD_LEFT);
             $this->report_parts[$section][$i] .= $tmp_val;
             $this->explanations[$section][$i][] = "<span>" . $tmp_val . "</span>: Value of Sun Duration Sensor " . $this->sensors['sun_duration_in_period']['sensor_id_code'] . " = " . $this->sensors['sun_duration_in_period']['sensor_feature_value'] . ' ' . $this->sensors['sun_duration_in_period']['metric_code'] . ' minutes';
         }
     }
     return true;
 }
 /**
  * @var $stationForm configForm
  * **/
 public function run($args)
 {
     //        error_reporting(null);
     ini_set('display_errors', 1);
     $this->_logger = LoggerFactory::getFileLogger('GenerateMessageCommand');
     //        $this->_logger = LoggerFactory::getConsoleLogger();
     $this->_logger->log('start');
     //       $args:
     //       $args[0] AWS01
     //       $args[1] "sensors:TS1;TS2;"
     $station_id_code = false;
     if (preg_match('/^([A-Z,a-z,0-9]{4,5})$/', $args[0], $matchesStations)) {
         $station_id_code = $matchesStations[1];
     } else {
         $this->_logger->log(' Station ID can contain only Letters (A-Z) and Figures (1-9), and must be of 4(rain) or 5(AWS) chars length.');
     }
     $sensor_id_codes = array();
     if (isset($args[1])) {
         if (preg_match("/^sensors:([A-Za-z1-9;]+)/", $args[1], $matchesSensors)) {
             $sensor_id_code = explode(';', $matchesSensors[1]);
             $sensor_id_codes = array_values($sensor_id_code);
             $sensor_id_codes_count = count($sensor_id_codes);
             for ($i = 0; $i < $sensor_id_codes_count; $i++) {
                 if (!preg_match('/^([A-Z,a-z]{2})([1-9]{1})$/', $sensor_id_codes[$i], $matches)) {
                     unset($sensor_id_codes[$i]);
                     $this->_logger->log('Sensor ID should contain two letters and 1 digit. Ex.: TP1');
                 }
             }
             $sensor_id_codes = array_values($sensor_id_codes);
         }
     }
     $station = Station::getStationByCode($station_id_code, array('sensors.handler', 'sensors.features.metric'));
     //            $sql = "SELECT `t1`.`station_sensor_id`, `t1`.`sensor_id_code`,  `t2`.`handler_id_code`, `t3`.`feature_code`, `t4`.`code` AS `metric_code`
     //                            FROM `".StationSensor::model()->tableName()."` `t1`
     //                            LEFT JOIN `".SensorDBHandler::model()->tableName()."`      `t2` ON `t2`.`handler_id` = `t1`.`handler_id`
     //                            LEFT JOIN `".StationSensorFeature::model()->tableName()."` `t3` ON `t3`.`sensor_id`  = `t1`.`station_sensor_id`
     //                            LEFT JOIN `".RefbookMetric::model()->tableName()."`        `t4` ON `t4`.`metric_id`  = `t3`.`metric_id`
     //                            WHERE `t1`.`station_id` = '".$station_id."' AND `t1`.`station_sensor_id` IN (".implode(',',$sensor_id).")";
     //            $res = Yii::app()->db->createCommand($sql)->queryAll();
     if ($station) {
         TimezoneWork::set($station->timezone_id);
         $sensors = array();
         foreach ($station->sensors as $key => $sensor) {
             if (in_array($sensor->sensor_id_code, $sensor_id_codes) || count($sensor_id_codes) == 0) {
                 if (!isset($sensors[$sensor->station_sensor_id])) {
                     $sensors[$sensor->station_sensor_id] = array('station_sensor_id' => $sensor->station_sensor_id, 'sensor_id_code' => $sensor->sensor_id_code, 'handler_id_code' => $sensor->handler->handler_id_code);
                 }
                 foreach ($sensor->features as $feature) {
                     if (is_object($feature->metric)) {
                         $sensors[$sensor->station_sensor_id]['features'][$feature->feature_code] = $feature->metric->code;
                     }
                 }
             }
         }
         $i = time();
         $messages[$i]['timestamp'] = $i;
         $this->_logger->log(__METHOD__ . ': sensors ' . print_r($sensors['sensor_id_code'], 1));
         foreach ($messages as $key => $value) {
             if ($station->station_type === 'rain') {
                 $messages[$key]['parts'][] = 'D';
                 $messages[$key]['parts'][] = $station->station_id_code;
                 $messages[$key]['parts'][] = date('ymd', $key);
                 $messages[$key]['parts'][] = date('Hi', $key);
                 $messages[$key]['parts'][] = str_pad(rand(100, 135), 3, "0", STR_PAD_LEFT);
                 $messages[$key]['parts'][] = '00';
             } else {
                 $messages[$key]['parts'][] = 'D';
                 $messages[$key]['parts'][] = $station->station_id_code;
                 $messages[$key]['parts'][] = date('ymd', $key);
                 $messages[$key]['parts'][] = date('Hi', $key);
                 $messages[$key]['parts'][] = '00';
             }
             $sensors_values = array();
             if ($sensors) {
                 foreach ($sensors as $k1 => $v1) {
                     $handler = SensorHandler::create($v1['handler_id_code']);
                     $random_value = $handler->getRandomValue($v1['features']);
                     $sensors_values[] = $v1['sensor_id_code'] . $random_value;
                 }
                 shuffle($sensors_values);
                 foreach ($sensors_values as $k1 => $v1) {
                     $messages[$key]['parts'][] = $v1;
                 }
             }
             $crc = It::prepareCRC(implode('', $messages[$key]['parts']));
             $messages[$key]['parts'][] = $crc;
             array_push($messages[$key]['parts'], '$');
             array_unshift($messages[$key]['parts'], '@');
         }
         $messages_display = array();
         $messages_copy = array();
         foreach ($messages as $key => $value) {
             $messages_display[] = implode(' ', $value['parts']);
             $messages_copy[] = implode('', $value['parts']);
         }
         $this->_logger->log(__METHOD__ . ': $messages_copy ' . print_r($messages_copy, 1));
         foreach ($messages_copy as $msg) {
             ListenerLogTemp::addNew($msg, 0, 1, 'import', 0);
         }
     } else {
         $this->_logger->log(__METHOD__ . ': has no stations like ' . $args[0]);
     }
 }
Пример #12
0
    public function createExport()
    {
        TimezoneWork::set('UTC');
        $tablesArray = array();
        $settingsArray = array();
        $settingsArray['user_settings'] = false;
        $settingsArray['common_settings'] = false;
        // users and access tables
        if ($this->user_settings) {
            $userTable = Yii::app()->db->createCommand()->select('
                                            u.user_id,
                                            u.email,
                                            u.username,
                                            u.password,
                                            u.role,
                                            u.timezone_id,
                                            u.created,
                                            u.updated
                                        ')->from('user u')->queryAll();
            $tablesArray['user'] = $userTable;
            $access_userTable = Yii::app()->db->createCommand()->select('
                                            au.id,
                                            au.user_id,
                                            au.action_id,

                                        ')->from('access_user au')->queryAll();
            $tablesArray['access_user'] = $access_userTable;
            $access_globalTable = Yii::app()->db->createCommand()->select('
                                            ag.id,
                                            ag.controller,
                                            ag.action,
                                            ag.enable,
                                            ag.description,

                                        ')->from('access_global ag')->queryAll();
            $tablesArray['access_global'] = $access_globalTable;
            $settingsArray['user_settings'] = true;
        }
        $settingsTable = Settings::model()->findAll();
        $tablesArray['settings'] = self::modelDataToArray($settingsTable);
        //        $configTable = Yii::app()->db->createCommand()
        //            ->select('c.config_id, c.key, c.label, c.value, c.default, c.type')
        //            ->from('config c')
        //            ->queryAll();
        //        $tablesArray['config'] = $configTable;
        $station = Yii::app()->db->createCommand()->select('
                                                            s.station_id,
                                                            s.display_name,
                                                            s.station_id_code,
                                                            s.station_number,
                                                            s.station_type,
                                                            s.logger_type,
                                                            s.communication_type,
                                                            s.communication_port,
                                                            s.communication_esp_ip,
                                                            s.communication_esp_port,
                                                            s.details,
                                                            s.status_message_period,
                                                            s.event_message_period,
                                                            s.timezone_id,
                                                            s.timezone_offset,
                                                            s.wmo_block_number,
                                                            s.wmo_member_state_id,
                                                            s.wmo_station_number,
                                                            s.wmo_originating_centre,
                                                            s.national_aws_number,
                                                            s.lat,
                                                            s.lng,
                                                            s.altitude,
                                                            s.magnetic_north_offset,
                                                            s.country_id,
                                                            s.city_id,
                                                            s.awos_msg_source_folder,
                                                            s.icao_code,
                                                            s.phone_number,
                                                            s.sms_message,
                                                            s.station_gravity,
                                                            s.created,
                                                            s.updated
                                                            ')->from('station  s')->queryAll();
        $tablesArray['station'] = $station;
        $station_groupTable = Yii::app()->db->createCommand()->select('
                                                                        sg.group_id,
                                                                        sg.name
                                                            ')->from('station_group sg')->queryAll();
        $tablesArray['station_group'] = $station_groupTable;
        $station_group_destinationTable = Yii::app()->db->createCommand()->select('
                                                                        sgd.group_destination_id,
                                                                        sgd.group_id,
                                                                        sgd.station_id
                                                            ')->from('station_group_destination sgd')->queryAll();
        $tablesArray['station_group_destination'] = $station_group_destinationTable;
        $station_calculationTable = Yii::app()->db->createCommand()->select('
                                                                        sc.calculation_id,
                                                                        sc.station_id,
                                                                        sc.handler_id,
                                                                        sc.formula,
                                                                        sc.created,
                                                                        sc.updated
                                                            ')->from('station_calculation sc')->queryAll();
        $tablesArray['station_calculation'] = $station_calculationTable;
        $station_calculation_variableTable = Yii::app()->db->createCommand()->select('
                                                                        scv.calculation_variable_id,
                                                                        scv.calculation_id,
                                                                        scv.variable_name,
                                                                        scv.sensor_feature_id,
                                                                        scv.created,
                                                                        scv.updated
                                                            ')->from('station_calculation_variable scv')->queryAll();
        $tablesArray['station_calculation_variable'] = $station_calculation_variableTable;
        $station_sensorTable = Yii::app()->db->createCommand()->select('
                                                                        ss.station_sensor_id,
                                                                        ss.station_id,
                                                                        ss.sensor_id_code,
                                                                        ss.display_name,
                                                                        ss.created,
                                                                        ss.updated,
                                                                        ss.handler_id
                                                            ')->from('station_sensor ss')->queryAll();
        $tablesArray['station_sensor'] = $station_sensorTable;
        $station_sensor_featureTable = Yii::app()->db->createCommand()->select('
                                                                      ssf.sensor_feature_id,
                                                                      ssf.sensor_id,
                                                                      ssf.feature_code,
                                                                      ssf.feature_display_name,
                                                                      ssf.feature_constant_value,
                                                                      ssf.measurement_type_code,
                                                                      ssf.metric_id,
                                                                      ssf.is_main,
                                                                      ssf.filter_max,
                                                                      ssf.filter_min,
                                                                      ssf.filter_diff,
                                                                      ssf.has_filters,
                                                                      ssf.has_filter_min,
                                                                      ssf.has_filter_max,
                                                                      ssf.has_filter_diff,
                                                                      ssf.is_constant,
                                                                      ssf.is_cumulative,
                                                                      ssf.created,
                                                                      ssf.updated
                                                            ')->from('station_sensor_feature ssf')->queryAll();
        $tablesArray['station_sensor_feature'] = $station_sensor_featureTable;
        $sensor_handler_defaultTable = Yii::app()->db->createCommand()->select('
                                                                      sh.handler_id,
                                                                      sh.handler_id_code,
                                                                      sh.display_name,
                                                                      sh.handler_default_display_name,
                                                                      sh.default_prefix,
                                                                      sh.aws_panel_display_position,
                                                                      sh.aws_panel_show,
                                                                      sh.aws_single_display_position,
                                                                      sh.aws_single_group,
                                                                      sh.aws_station_uses,
                                                                      sh.rain_station_uses,
                                                                      sh.awa_station_uses,
                                                                      sh.flags,
                                                                      sh.start_time,
                                                                      sh.created,
                                                                      sh.updated
                                                            ')->from('sensor_handler sh')->queryAll();
        $tablesArray['sensor_handler'] = $sensor_handler_defaultTable;
        $sensor_handler_default_featureTable = Yii::app()->db->createCommand()->select('
                                                                    shdf.handler_feature_id,
                                                                    shdf.handler_id,
                                                                    shdf.feature_code,
                                                                    shdf.aws_panel_show,
                                                                    shdf.feature_constant_value,
                                                                    shdf.metric_id,
                                                                    shdf.filter_max,
                                                                    shdf.filter_min,
                                                                    shdf.filter_diff,
                                                                    shdf.created,
                                                                    shdf.updated
                                                            ')->from('sensor_handler_default_feature shdf')->queryAll();
        $tablesArray['sensor_handler_default_feature'] = $sensor_handler_default_featureTable;
        $schedule_reportTable = Yii::app()->db->createCommand()->select('
                                                                    sr.schedule_id,
                                                                    sr.report_type,
                                                                    sr.station_id,
                                                                    sr.send_like_attach,
                                                                    sr.send_email_together,
                                                                    sr.period,
                                                                    sr.report_format,
                                                                    sr.last_scheduled_run_fact,
                                                                    sr.last_scheduled_run_planned,
                                                                    sr.created,
                                                                    sr.updated
                                                            ')->from('schedule_report sr')->queryAll();
        $tablesArray['schedule_report'] = $schedule_reportTable;
        $schedule_report_to_stationTable = Yii::app()->db->createCommand()->select('
                                                                    srts.id,
                                                                    srts.schedule_id,
                                                                    srts.station_id
                                                            ')->from('schedule_report_to_station srts')->queryAll();
        $tablesArray['schedule_report_to_station'] = $schedule_report_to_stationTable;
        $schedule_report_destinationTable = Yii::app()->db->createCommand()->select('
                                                                    srd.schedule_destination_id,
                                                                    srd.schedule_id,
                                                                    srd.method,
                                                                    srd.destination_email,
                                                                    srd.destination_local_folder,
                                                                    srd.destination_ip,
                                                                    srd.destination_ip_port,
                                                                    srd.destination_ip_folder,
                                                                    srd.destination_ip_user,
                                                                    srd.destination_ip_password
                                                            ')->from('schedule_report_destination srd')->queryAll();
        $tablesArray['schedule_report_destination'] = $schedule_report_destinationTable;
        $ex_schedule_reportTable = Yii::app()->db->createCommand()->from('ex_schedule_report esr')->queryAll();
        $tablesArray['ex_schedule_report'] = $ex_schedule_reportTable;
        $ex_schedule_report_destinationTable = Yii::app()->db->createCommand()->from('ex_schedule_report_destination esrd')->queryAll();
        $tablesArray['ex_schedule_report_destination'] = $ex_schedule_report_destinationTable;
        //        $ex_schedule_report_processedTable = Yii::app()->db->createCommand()
        //                                                            ->from('ex_schedule_report_processed esrp')
        //                                                            ->queryAll();
        //        $tablesArray['ex_schedule_report_processed'] = $ex_schedule_report_processedTable;
        //        $ex_schedule_send_logTable = Yii::app()->db->createCommand()
        //
        //                                                            ->from('ex_schedule_send_log essl')
        //                                                            ->queryAll();
        //        $tablesArray['ex_schedule_send_log'] = $ex_schedule_send_logTable;
        $settingsArray['common_settings'] = true;
        $resultArray['config'] = $settingsArray;
        $resultArray['data'] = $tablesArray;
        $result = serialize($resultArray);
        $additional = "";
        if ($settingsArray['user_settings']) {
            $additional = "_users";
        }
        $fileName = 'settings_export' . $additional . '_' . date('Y_m_d_H_i_s') . '.conf';
        It::downloadFile($result, $fileName, 'text/conf');
    }
Пример #13
0
 public function save()
 {
     $sql = "SET FOREIGN_KEY_CHECKS = 0;\n";
     $sql .= "";
     foreach ($this->data_after_validor as $key => $value) {
         $sql .= sqlBuilder::createTruncateTableCommand($key);
         $sql .= sqlBuilder::createInsertFromArray($value, $key);
     }
     $sql .= "\n\nSET FOREIGN_KEY_CHECKS = 1;\n";
     $connection = Yii::app()->db;
     $transaction = $connection->beginTransaction();
     try {
         TimezoneWork::set('UTC');
         $command = $connection->createCommand($sql);
         $command->execute();
         $transaction->commit();
         $this->result_success = true;
         return true;
     } catch (Exeption $e) {
         $transaction->rollback();
         $this->result_success = false;
     }
     return false;
     //            try{
     //                $count = $command->execute();
     //                $this->_logger->log(__METHOD__, array('count' => $count));
     //            } catch (Exception $e) {
     //                $this->_logger->log(__METHOD__,array('err' => $e->getMessage()));
     //            }
 }
Пример #14
0
 public function actionScheduleRegenerateReport()
 {
     // All reports are generated basing on data in UTC time.
     TimezoneWork::set('UTC');
     $return = array('ok' => 0);
     $schedule_processed_id = isset($_REQUEST['schedule_processed_id']) ? intval($_REQUEST['schedule_processed_id']) : null;
     if ($schedule_processed_id) {
         $data = ScheduleReportProcessed::getInfoForRegenerate($schedule_processed_id);
         if (!is_null($data)) {
             $reportType = null;
             switch ($data->ScheduleReportToStation->schedule_report->report_type) {
                 case 'bufr':
                     $reportType = 'Bufr';
                     break;
                 case 'synop':
                     $reportType = 'Synop';
                     break;
                 case 'metar':
                     $reportType = 'Metar';
                     break;
                 case 'speci':
                     $reportType = 'Speci';
                     break;
                 default:
                     $reportType = 'Export';
                     break;
             }
             $weather_report = WeatherReport::create($reportType);
             $weather_report->load($schedule_processed_id);
             if (!$weather_report->errors) {
                 $weather_report->generate();
                 $weather_report->prepareReportComplete();
                 $weather_report->saveProcess();
                 $return['ok'] = 1;
                 $return['report_string_initial'] = $weather_report->getReportComplete();
             } else {
                 $return['errors'] = $weather_report->errors;
             }
         }
     }
     print json_encode($return);
     CApplication::end();
 }
Пример #15
0
 /**
  * 
  * Backup process:
  * - initiates connection with backup datatbase
  * - if backup database is empty - creates whole backup
  * - else updates backup database and moves old data
  * 
  * @return type 
  */
 public function makeBackup()
 {
     It::debug("start", 'backup_database');
     try {
         $res = $this->initDbConnection();
     } catch (Exception $e) {
         $this->addBackupLog("cannot init DB Connection, " . $e->getMessage());
         It::debug($e->getMessage(), 'backup_database');
         return;
     }
     // for backup database: set the same timezone as we have at actual database
     $this->db_conn->createCommand("SET time_zone='" . TimezoneWork::getOffsetFromUTC('UTC', 1) . "'")->query();
     $limit_timestamp = $this->current_backup->data_timestamp_limit;
     // check if database doesn't exist
     $version = $this->backupDBVersion();
     //        $this->addBackupLog("Backup database version: ".$version."; Actual database version: ".getConfigValue('version_name'));
     $this->addBackupLog("Backup database version: ; Actual database version: ");
     if ($version === false) {
         $this->addBackupLog("There are no tables yet. Going to copy current whole DB");
         It::debug("backup database structure is not ready. Going to copy current whole DB", 'backup_database');
         // create whole backup
         $cmd = Yii::app()->params['applications']['mysqldump_exe_path'] . ' --host="' . Yii::app()->params['db_params']['host'] . '" --quick ' . ' --port="' . Yii::app()->params['db_params']['port'] . '"' . ' --user="******"' . ' --password="******"  ' . Yii::app()->params['db_params']['dbname'] . " | " . Yii::app()->params['applications']['mysqldump_exe_path'] . ' --host="' . $this->settings->db_exp_sql_host . '"' . ' --port="' . $this->settings->db_exp_sql_port . '"' . ' --user="******"' . ' --password="******" ' . $this->settings->db_exp_sql_dbname;
         try {
             $this->addBackupLog("Command to execute: " . $cmd);
             exec($cmd, $output, $return);
             $this->addBackupLog("Command has been executed. Whole db was copied to backup_db");
         } catch (Exception $e) {
             $this->addBackupLog("Command has not been executed. Cannot make whole backup");
             It::debug($e->getMessage(), 'backup_database');
             return;
         }
         // check if database doesn't exist
         $version = $this->backupDBVersion();
         //            $this->addBackupLog("Again check Backup database version: ".$version."; Actual database version: ".getConfigValue('version_name'));
         $this->addBackupLog("Again check Backup database version: ; Actual database version: ");
         if ($version !== false) {
             // remove old data from actual database
             $res = $this->removeDataBeforeDate($limit_timestamp);
             // mark current backup process as completed
             $this->current_backup->completed = '1';
             $this->current_backup->save();
         } else {
             $this->addBackupLog("Is false again!");
         }
     } else {
         // apply all previous updates to that database
         $res = $this->applyVersionChanges($version);
         if ($res === FALSE) {
             $this->addBackupLog("Data was not moved. Process stopped!");
             return;
         }
         // copy data from actual DB to backup DB before some timestamp
         $this->copyDataBetweenDatabases($limit_timestamp);
     }
     $this->addBackupLog("Done");
     It::debug("\n\n== COMPLETED ==", 'backup_database');
 }
Пример #16
0
</td>
            <td><?php 
        echo Yii::app()->params['station_type'][$station->station_type];
        ?>
</td>
            
			<td nowrap><?php 
        echo CHtml::link($station->display_name, array('admin/StationSave', 'station_id' => $station->station_id), array('title' => 'Change Station Details'));
        ?>
</td>
			
			<td nowrap><?php 
        echo $station->timezone_id;
        ?>
 (GMT <?php 
        echo TimezoneWork::getOffsetFromUTC($station->timezone_id, 1);
        ?>
)</td>
            <td nowrap>
                <?php 
        echo Yii::app()->params['com_type'][$station->communication_type] . ' ';
        if ($station->communication_type === 'direct' || $station->communication_type === 'sms') {
            echo '(' . SMSCOMPort::getLinuxComName($station->communication_port) . ')';
        } else {
            if ($station->communication_type === 'tcpip') {
                echo '(' . $station->communication_esp_ip . ':' . $station->communication_esp_port . ')';
            } else {
                if ($station->communication_type === 'gprs') {
                    echo '(' . $station->communication_esp_ip . ':' . $station->communication_esp_port . ')';
                } else {
                    if ($station->communication_type === 'server') {
Пример #17
0
 public function actionStationTypeDataHistory()
 {
     $ex_schedule_id = isset($_REQUEST['ex_schedule_id']) ? intval($_REQUEST['ex_schedule_id']) : null;
     if (!(int) $ex_schedule_id) {
         $this->redirect($this->createUrl('site/StationTypeDataExport'));
     }
     TimezoneWork::set('UTC');
     $history = ScheduleTypeReportProcessed::getHistory($ex_schedule_id);
     $scheduleTypeReport = new ScheduleTypeReport();
     $report = $scheduleTypeReport->findByPk($ex_schedule_id);
     $this->render('schedule_type_report_history', array('report' => $report, 'history' => $history));
 }
Пример #18
0
<div class="middlenarrow">
    <h1>Other Settings</h1>

    <?php 
$timezones = TimezoneWork::prepareList();
?>
    <?php 
echo CHtml::beginForm($this->createUrl('admin/setupother'), 'post');
?>

        <table class="formtable">
        <tr>
            <td><?php 
echo CHtml::activeCheckbox($settings, 'overwrite_data_on_import');
?>
</td>
            <td><?php 
echo CHtml::activeLabel($settings, 'overwrite_data_on_import');
?>
</td>
        </tr>
        <tr>
            <td><?php 
echo CHtml::activeCheckbox($settings, 'overwrite_data_on_listening');
?>
</td>
            <td><?php 
echo CHtml::activeLabel($settings, 'overwrite_data_on_listening');
?>
</td>
 public function generate()
 {
     $this->_logger->log(__METHOD__);
     $current_user_timezone = date_default_timezone_get();
     $timezone_id = 'UTC';
     if ($timezone_id != $current_user_timezone) {
         TimezoneWork::set($timezone_id);
     }
     $this->sensors = $this->prepareSensorsInfo($this->listener_log_info->log_id);
     $this->calculations = $this->_prepareCalculationsInfo($this->listener_log_info->log_id);
     if ($timezone_id != $current_user_timezone) {
         TimezoneWork::set($current_user_timezone);
     }
     if ($this->errors) {
         $this->_logger->log(__METHOD__, array('errors' => $this->errors));
         return false;
     }
     $this->report_parts = array();
     $this->explanations = array();
     $this->prepareSection0();
     $this->prepareSection1();
     $this->prepareSection3();
     $this->prepareSection4();
     $this->prepareSection5();
 }
Пример #20
0
 public function m_0_4_1()
 {
     @apache_setenv('no-gzip', 1);
     @ini_set('zlib.output_compression', 0);
     @ini_set('implicit_flush', 1);
     ini_set('memory_limit', '-1');
     //ob_start();
     $this->flushNotification('...Please wait... Updating is going on... DO NOT LEAVE THIS PAGE!');
     $this->flushNotification('<br/>...Going to add "is_last" fields to `listener_log` table...');
     $res = Yii::app()->db->createCommand("SHOW COLUMNS FROM `" . ListenerLog::model()->tableName() . "` LIKE 'is_last'")->queryAll();
     if (!$res) {
         Yii::app()->db->createCommand("ALTER TABLE `" . ListenerLog::model()->tableName() . "` ADD `is_last` tinyint(1) NOT NULL DEFAULT '0' AFTER `is_processed`")->query();
         Yii::app()->db->createCommand("COMMIT")->query();
         $stations = Yii::app()->db->createCommand("SELECT * FROM `" . Station::model()->tableName() . "`")->queryAll();
         if ($stations) {
             foreach ($stations as $key => $value) {
                 ListenerLog::updateIsLastForStation($value['station_id']);
             }
         }
         $this->flushNotification(' ... done');
     } else {
         $this->flushNotification(' ... not need');
     }
     $this->flushNotification('<br/>...Going to add "is_processing" column to `listener_log` table...');
     $res = Yii::app()->db->createCommand("SHOW COLUMNS FROM `" . ListenerLog::model()->tableName() . "` LIKE 'is_processing'")->queryAll();
     if (!$res) {
         Yii::app()->db->createCommand("ALTER TABLE `" . ListenerLog::model()->tableName() . "` ADD `is_processing` TINYINT(1) NOT NULL DEFAULT '0' AFTER `is_processed`")->query();
         Yii::app()->db->createCommand("COMMIT")->query();
         $this->flushNotification(' ... done');
     } else {
         $this->flushNotification(' ... not need');
     }
     // station
     $this->flushNotification('<br/><br/>Station table:');
     $this->flushNotification('<br/>...Going to update  "national_aws_number" field at `station` table...');
     $res = Yii::app()->db->createCommand("SHOW COLUMNS FROM `" . Station::model()->tableName() . "` LIKE 'national_aws_number'")->queryAll();
     if ($res[0]['Null'] == 'NO') {
         Yii::app()->db->createCommand("ALTER TABLE `station` CHANGE `national_aws_number` `national_aws_number`  int(11) DEFAULT '0'")->query();
         Yii::app()->db->createCommand("COMMIT")->query();
         $this->flushNotification(' ... done');
     } else {
         $this->flushNotification(' ... not need');
     }
     $this->flushNotification('<br/>...Going to add new column "country_id" to `station` table...');
     $res = Yii::app()->db->createCommand("SHOW COLUMNS FROM `" . Station::model()->tableName() . "` LIKE 'country_id'")->queryAll();
     if (!$res) {
         Yii::app()->db->createCommand("ALTER TABLE `station` ADD `country_id` int(11) NOT NULL DEFAULT '0' AFTER `magnetic_north_offset`")->query();
         Yii::app()->db->createCommand("COMMIT")->query();
         $this->flushNotification(' ... done');
     } else {
         $this->flushNotification(' ... already exists');
     }
     $this->flushNotification('<br/>...Going to add new column "city_id" to `station` table...');
     $res = Yii::app()->db->createCommand("SHOW COLUMNS FROM `" . Station::model()->tableName() . "` LIKE 'city_id'")->queryAll();
     if (!$res) {
         Yii::app()->db->createCommand("ALTER TABLE `station` ADD `city_id` int(11) NOT NULL DEFAULT '0' AFTER `country_id`")->query();
         Yii::app()->db->createCommand("COMMIT")->query();
         $this->flushNotification(' ... done');
     } else {
         $this->flushNotification(' ... already exists');
     }
     $this->flushNotification('<br/>...Going to add new column "timezone_offset" to `station` table...');
     $res = Yii::app()->db->createCommand("SHOW COLUMNS FROM `" . Station::model()->tableName() . "` LIKE 'timezone_offset'")->queryAll();
     if (!$res) {
         Yii::app()->db->createCommand("ALTER TABLE `station` ADD `timezone_offset` varchar(20) NOT NULL AFTER `timezone_id`")->query();
         Yii::app()->db->createCommand("COMMIT")->query();
         $this->flushNotification(' ... done');
     } else {
         $this->flushNotification(' ... already exists');
     }
     $this->flushNotification('<br/>...Going to update "timezone_offset" data in `station` table...');
     $sql = "SELECT `station_id`, `timezone_id` FROM `" . Station::model()->tableName() . "` WHERE `timezone_offset` = ''";
     $res = Yii::app()->db->createCommand($sql)->queryAll();
     if ($res) {
         foreach ($res as $key => $value) {
             $sql = "UPDATE `" . Station::model()->tableName() . "` SET `timezone_offset` = '" . TimezoneWork::getOffsetFromUTC($value['timezone_id'], 1) . "' WHERE `station_id` = '" . $value['station_id'] . "'";
             Yii::app()->db->createCommand($sql)->query();
         }
         Yii::app()->db->createCommand("COMMIT")->query();
         $this->flushNotification(' ... done');
     } else {
         $this->flushNotification(' ... not need');
     }
     $this->flushNotification('<br/>...Going to add new column "awos_msg_source_folder" to `station` table...');
     $res = Yii::app()->db->createCommand("SHOW COLUMNS FROM `" . Station::model()->tableName() . "` LIKE 'awos_msg_source_folder'")->queryAll();
     if (!$res) {
         Yii::app()->db->createCommand("ALTER TABLE `station` ADD `awos_msg_source_folder` TEXT CHARACTER SET ucs2 COLLATE ucs2_general_ci NOT NULL AFTER `city_id`")->query();
         Yii::app()->db->createCommand("COMMIT")->query();
         $this->flushNotification(' ... done');
     } else {
         $this->flushNotification(' ... already exists');
     }
     // Sensor Data
     $this->flushNotification('<br/>...Going to update `sensor_data` table\'s data...');
     Yii::app()->db->createCommand("UPDATE `sensor_data` SET `period` = 1440 WHERE `period` = 86400")->query();
     Yii::app()->db->createCommand("COMMIT")->query();
     $this->flushNotification(' ... done');
     //Schedule report
     $this->flushNotification('<br/>...Going to create `schedule_report` table...');
     $tables = array();
     $res = Yii::app()->db->createCommand("SHOW TABLES")->queryAll();
     if ($res) {
         foreach ($res as $key => $value) {
             foreach ($value as $k1 => $v1) {
                 $tables[] = $v1;
             }
         }
     }
     if (!in_array('schedule_report', $tables)) {
         $sql = "CREATE TABLE `schedule_report` (\n                      `schedule_id` int(11) NOT NULL AUTO_INCREMENT,\n                      `report_type` varchar(50) NOT NULL DEFAULT 'synop' COMMENT 'synop, bufr',\n                      `station_id` int(11) NOT NULL,\n                      `period` int(11) NOT NULL DEFAULT '60' COMMENT 'in minutes',\n                      `method` varchar(20) NOT NULL DEFAULT 'email' COMMENT 'email, ftp',\n                      `destination_email` varchar(255) NOT NULL,\n                      `destination_ip` varchar(15) NOT NULL,\n                      `destination_ip_port` int(5) NOT NULL DEFAULT '21',\n                      `destination_ip_folder` varchar(255) NOT NULL DEFAULT '/',\n                      `destination_ip_user` varchar(255) NOT NULL,\n                      `destination_ip_password` varchar(255) NOT NULL,\n                      `report_format` varchar(20) NOT NULL DEFAULT 'csv' COMMENT 'txt, csv',\n                      `last_scheduled_run_fact` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',\n                      `last_scheduled_run_planned` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',\n                      `created` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',\n                      `updated` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',\n                      PRIMARY KEY (`schedule_id`)\n                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
         Yii::app()->db->createCommand($sql)->query();
         Yii::app()->db->createCommand("COMMIT")->query();
         $this->flushNotification(' ... done');
     } else {
         $this->flushNotification(' ... already exists');
     }
     $this->flushNotification('<br/>...Going to create `schedule_report_processed` table...');
     if (!in_array('schedule_report_processed', $tables)) {
         $sql = "CREATE TABLE `schedule_report_processed` (\n                      `schedule_processed_id` int(11) NOT NULL AUTO_INCREMENT,\n                      `schedule_id` int(11) NOT NULL,\n                      `listener_log_id` int(11) NOT NULL,\n                      `is_processed` tinyint(1) NOT NULL DEFAULT '0',\n                      `report_string_initial` text NOT NULL,\n                      `report_string_changed` text NOT NULL,\n                      `serialized_report_problems` text NOT NULL,\n                      `serialized_report_errors` text NOT NULL,\n                      `serialized_report_explanations` text NOT NULL,\n                      `is_last` tinyint(1) NOT NULL DEFAULT '0',\n                      `created` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',\n                      `updated` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',\n                      PRIMARY KEY (`schedule_processed_id`),\n                      KEY `schedule_id` (`schedule_id`),\n                      KEY `listener_log_id` (`listener_log_id`),\n                      CONSTRAINT `schedule_report_processed_fk` FOREIGN KEY (`schedule_id`) REFERENCES `schedule_report` (`schedule_id`) ON DELETE CASCADE ON UPDATE NO ACTION,\n                      CONSTRAINT `schedule_report_processed_ibfk_1` FOREIGN KEY (`listener_log_id`) REFERENCES `listener_log` (`log_id`) ON DELETE CASCADE ON UPDATE NO ACTION\n                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
         Yii::app()->db->createCommand($sql)->query();
         Yii::app()->db->createCommand("COMMIT")->query();
         $this->flushNotification(' ... done');
     } else {
         $this->flushNotification(' ... already exists');
     }
     // metrics
     $this->flushNotification('<br/><br/>New Metrics:');
     $this->flushNotification('<br/>...Going to add new metric "kJ/sq.m" ...');
     Yii::app()->db->createCommand("INSERT INTO `refbook_metric` (`metric_id`, `html_code`, `short_name`, `full_name`, `code`) VALUES ('21', 'kJ/sq.m', 'kJ/sq.m', 'Kilo Joule per square meter', 'kjoule_per_sq_meter')")->query();
     Yii::app()->db->createCommand("COMMIT")->query();
     $this->flushNotification(' ... done');
     $this->flushNotification('<br/>...Going to add new metric "feet"...');
     Yii::app()->db->createCommand("INSERT INTO `refbook_metric` (`metric_id`, `html_code`, `short_name`, `full_name`, `code`) VALUES ('22', 'ft', 'ft', 'Feet', 'feet')")->query();
     Yii::app()->db->createCommand("COMMIT")->query();
     $this->flushNotification(' ... done');
     $this->flushNotification('<br/>...Going to add new metric "km"...');
     Yii::app()->db->createCommand("INSERT INTO `refbook_metric` (`metric_id`,`html_code`,`short_name`,`full_name`,`code`) VALUES (23 , 'km', 'km', 'Kilometer', 'kilometer')")->query();
     Yii::app()->db->createCommand("COMMIT")->query();
     $this->flushNotification(' ... done');
     $this->flushNotification('<br/>...Going to add new relation between "solar radiation" and "kj/sq.m"...');
     RefbookMeasurementTypeMetric::model()->deleteByPk(23);
     Yii::app()->db->createCommand("INSERT INTO `refbook_measurement_type_metric` (`measurement_type_metric_id`, `measurement_type_id`, `metric_id`, `is_main`) VALUES ('23', '9', '21', '0')")->query();
     Yii::app()->db->createCommand("COMMIT")->query();
     $this->flushNotification(' ... done');
     $this->flushNotification('<br/>...Going to add new measuring type "Cloud Vertical Visibility"...');
     Yii::app()->db->createCommand("INSERT INTO `refbook_measurement_type` (`measurement_type_id`, `display_name`, `code`, `ord`) VALUES (16 ,'Cloud Vertical Visibility', 'cloud_vertical_visibility', '14')")->query();
     Yii::app()->db->createCommand("COMMIT")->query();
     $this->flushNotification(' ... done');
     $this->flushNotification('<br/>...Going to add new measuring type "Cloud Height" ...');
     Yii::app()->db->createCommand("INSERT INTO `refbook_measurement_type` (`measurement_type_id`, `display_name`, `code`, `ord`) VALUES (17, 'Cloud Height', 'cloud_height', 15)")->query();
     Yii::app()->db->createCommand("COMMIT")->query();
     $this->flushNotification(' ... done');
     $this->flushNotification('<br/>...Going to add new measuring type "Sea Level" ...');
     Yii::app()->db->createCommand("INSERT INTO `refbook_measurement_type` (`measurement_type_id`, `display_name`, `code`, `ord`) VALUES (18 , 'Sea Level (Mean, Sigma, Wave Hight)', 'sea_level', '16')")->query();
     Yii::app()->db->createCommand("COMMIT")->query();
     $this->flushNotification(' ... done');
     $this->flushNotification('<br/>...Going to add relation between "Cloud Vertical Visibility" and "ft" ...');
     Yii::app()->db->createCommand("INSERT INTO `refbook_measurement_type_metric` (`measurement_type_metric_id`, `measurement_type_id`, `metric_id`, `is_main`) VALUES (24,16,22,1)")->query();
     Yii::app()->db->createCommand("COMMIT")->query();
     $this->flushNotification(' ... done');
     $this->flushNotification('<br/>...Going to add new relation between "Cloud Vertical Visibility" and "meter"...');
     Yii::app()->db->createCommand("INSERT INTO `refbook_measurement_type_metric` (`measurement_type_metric_id`, `measurement_type_id`, `metric_id`, `is_main`) VALUES (25,16,11,0)")->query();
     Yii::app()->db->createCommand("COMMIT")->query();
     $this->flushNotification(' ... done');
     $this->flushNotification('<br/>...Going to add new relation between "Cloud Height" and "ft"...');
     Yii::app()->db->createCommand("INSERT INTO `refbook_measurement_type_metric` (`measurement_type_metric_id`, `measurement_type_id`, `metric_id`, `is_main`) VALUES (26,17,22,1)")->query();
     Yii::app()->db->createCommand("COMMIT")->query();
     $this->flushNotification(' ... done');
     $this->flushNotification('<br/>...Going to add new relation between "Cloud Height" and "meter"...');
     Yii::app()->db->createCommand("INSERT INTO `refbook_measurement_type_metric` (`measurement_type_metric_id`, `measurement_type_id`, `metric_id`, `is_main`) VALUES (27,17,11,0)")->query();
     Yii::app()->db->createCommand("COMMIT")->query();
     $this->flushNotification(' ... done');
     $this->flushNotification('<br/>...Going to add new relation between "Visibility" and "meter"...');
     Yii::app()->db->createCommand("INSERT INTO `refbook_measurement_type_metric` (`measurement_type_metric_id`, `measurement_type_id`, `metric_id`, `is_main`) VALUES (28, 11, 11, 1)")->query();
     Yii::app()->db->createCommand("COMMIT")->query();
     $this->flushNotification(' ... done');
     $this->flushNotification('<br/>...Going to add new relation between "Sea Level" and "meter"...');
     Yii::app()->db->createCommand("INSERT INTO `refbook_measurement_type_metric` (`measurement_type_metric_id`, `measurement_type_id`, `metric_id`, `is_main`) VALUES (29, 18, 11, 1)")->query();
     Yii::app()->db->createCommand("COMMIT")->query();
     $this->flushNotification(' ... done');
     // sensor handler
     $this->flushNotification('<br/>...Going to add new column "awos_station_uses" to `sensor_handler` table...');
     $res = Yii::app()->db->createCommand("SHOW COLUMNS FROM `sensor_handler` LIKE 'awos_station_uses'")->queryAll();
     if (!$res) {
         $res = Yii::app()->db->createCommand("ALTER TABLE `sensor_handler` ADD `awos_station_uses` TINYINT( 1 ) NOT NULL DEFAULT '0'")->query();
         Yii::app()->db->createCommand("COMMIT")->query();
         $this->flushNotification(' ... done');
     } else {
         $this->flushNotification(' ... already exists');
     }
     $this->flushNotification('<br/>...Going to update `sensor_handler` table...');
     $sql = "UPDATE `sensor_handler` SET \n                `handler_id_code` = 'SeaLevelAWS',\n                `display_name` = 'Sea Level and Tide Data',\n                `description` = 'Handler \"Sea Level and Tide Data\" : Processes string like \"SL1XXXXYYYYZZZZ\", where <br/>SL1 - device Id; <br/>XXXX - Mean value;<br/>YYYY - Sigma value; <br/>ZZZZ - Wave Height <br/>Example: SL1179017900140 = SL1 sensor sent data: Mean value = 1.79, Sigma value = 1.79, Wave height = 140m.',\n                `default_prefix` = 'SL',\n                `aws_station_uses` = 1,\n                `rain_station_uses` = 0,\n                `awos_station_uses` = 0,\n                `aws_single_group` = 'sea_level'\n                WHERE `handler_id` = 13";
     Yii::app()->db->createCommand($sql)->query();
     Yii::app()->db->createCommand("COMMIT")->query();
     $sql = "UPDATE `sensor_handler` SET \n                `handler_id_code` = 'VisibilityAWS',\n                `display_name` = 'Visibility',\n                `description` = 'Handler \"Visibility\"',\n                `default_prefix` = 'VI',\n                `aws_station_uses` = 1,\n                `rain_station_uses` = 0,\n                `awos_station_uses` = 0,\n                `aws_single_group` = 'visibility'\n                WHERE `handler_id` = 14";
     Yii::app()->db->createCommand($sql)->query();
     Yii::app()->db->createCommand("COMMIT")->query();
     $sql = "UPDATE `sensor_handler` SET `handler_id_code` = 'CloudHeightAWS',\n                `display_name` = 'Cloud Height',\n                `description` = 'Handler \"Cloud Height\"',\n                `default_prefix` = 'CH',\n                `aws_station_uses` = 1,\n                `rain_station_uses` = 0,\n                `awos_station_uses` = 0,\n                `aws_single_group` = 'clouds'\n                WHERE `handler_id` = 15";
     Yii::app()->db->createCommand($sql)->query();
     Yii::app()->db->createCommand("COMMIT")->query();
     $this->flushNotification(' ... done');
     $this->flushNotification('<br/>...Going to update calculation_handler table...');
     $res = Yii::app()->db->createCommand("UPDATE `calculation_handler` SET `display_name` = 'Pressure Adjusted to MSL' WHERE `handler_id` = 2");
     Yii::app()->db->createCommand("COMMIT")->query();
     $this->flushNotification(' ... done');
     $bat_path = dirname(Yii::app()->request->scriptFile) . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR . 'at' . DIRECTORY_SEPARATOR . 'schedule.bat';
     $schedule_bat_content = getConfigValue('php_exe_path') . " -f  " . dirname(Yii::app()->request->scriptFile) . DIRECTORY_SEPARATOR . "console.php schedule";
     file_put_contents($bat_path, $schedule_bat_content);
     exec('schtasks /create /sc minute /mo 1 /F /ru "SYSTEM" /tn delaircoScheduleScript /tr ' . $bat_path, $output);
     $values = getConfigValue('schedule');
     $values['each_minute_process_id'] = 'delaircoScheduleScript';
     InstallConfig::setConfigSection('schedule', $values);
     $values = getConfigValue('path');
     $values['site_url_for_console'] = It::baseUrl();
     InstallConfig::setConfigSection('path', $values);
     It::memStatus('update__success');
     $this->flushNotification('<script type="text/javascript"> setTimeout(function(){document.location.href="' . Yii::app()->controller->createUrl('update/index') . '"}, 10000)</script>');
 }
 /**
  *
  * @return boolean 
  */
 public function generate()
 {
     $this->_logger->log(__METHOD__);
     if ($this->errors) {
         $this->_logger->log(__METHOD__, array('errors' => $this->errors));
         return false;
     }
     $current_user_timezone = date_default_timezone_get();
     $timezone_id = 'UTC';
     if ($timezone_id != $current_user_timezone) {
         TimezoneWork::set($timezone_id);
     }
     $this->sensors = $this->prepareSensorsInfo($this->listener_log_info->log_id);
     $this->calculations = $this->_prepareCalculationsInfo($this->listener_log_info->log_id);
     if ($timezone_id != $current_user_timezone) {
         TimezoneWork::set($current_user_timezone);
     }
     if ($this->errors) {
         $this->_logger->log(__METHOD__, array('errors' => $this->errors));
         return false;
     }
     $this->report_parts = array();
     $this->explanations = array();
     $this->_measuring_timestamp = strtotime($this->listener_log_info->measuring_timestamp);
     $this->_measuring_day = gmdate('d', $this->_measuring_timestamp);
     $this->_measuring_hour = gmdate('H', $this->_measuring_timestamp);
     $this->_measuring_minute = gmdate('i', $this->_measuring_timestamp);
     $this->_logger->log(__METHOD__ . ' Prepare sections.');
     foreach ($this->getSections() as $sectionNumber => $section) {
         $this->_section = $sectionNumber;
         $this->_logger->log(__METHOD__, array('section' => $section));
         foreach ($section as $subsectionNumber => $subsection) {
             $this->_subsection = $subsectionNumber;
             $this->_logger->log(__METHOD__, array('subsection' => $subsection));
             $this->{'write' . $subsection}();
         }
     }
     return true;
 }
Пример #22
0
 public function beforeSave()
 {
     $this->local_timezone_offset = TimezoneWork::getOffsetFromUTC($this->local_timezone_id, 1);
     return parent::beforeSave();
 }
Пример #23
0
 public function checkPeriod($measuring_timestamp, $sensor_feature_id, $station_id, $key)
 {
     // todo
     $station = new Station();
     $stationData = $station->findbypk($station_id);
     if ($stationData['timezone_id']) {
         TimezoneWork::set($stationData['timezone_id']);
     }
     $last = $this->prepared_pairs[$this->checkPeriodArray[$key]];
     $criteria = new CDbCriteria();
     $criteria->select = 'measuring_timestamp, sensor_feature_value, sensor_feature_normalized_value, period, measuring_timestamp, sensor_feature_id, station_id';
     $criteria->addCondition('measuring_timestamp < "' . $measuring_timestamp . '"');
     $criteria->addCondition('sensor_feature_id = "' . $sensor_feature_id . '"');
     $criteria->addCondition('station_id = "' . $station_id . '"');
     $criteria->order = 'measuring_timestamp DESC';
     $criteria->limit = 1;
     $data = SensorData::model()->find($criteria);
     if (!is_null($data) and $data != false) {
         $value_norm = $last['normilized_value'] - $data['sensor_feature_normalized_value'];
         $getDate = getdate(strtotime($measuring_timestamp));
         $getDatePrev = getdate(strtotime($data['measuring_timestamp']));
         if ($getDate['yday'] != $getDatePrev['yday'] && ($getDate['hours'] != 0 || $getDate['minutes'] != 0 || $getDate['seconds'] != 0) || $getDate['yday'] == $getDatePrev['yday'] && $getDatePrev['hours'] == 0 && $getDatePrev['minutes'] == 0 && $getDatePrev['seconds'] == 0) {
             $this->prepared_pairs[$key]['period'] = $getDate['hours'] * 60 + $getDate['minutes'];
             $this->prepared_pairs[$key]['value'] = $last['value'];
             $this->prepared_pairs[$key]['normilized_value'] = $last['normilized_value'];
         } else {
             $this->prepared_pairs[$key]['period'] = round((strtotime($measuring_timestamp) - strtotime($data['measuring_timestamp'])) / 60);
             $this->prepared_pairs[$key]['value'] = $last['value'] - $data['sensor_feature_value'];
             $this->prepared_pairs[$key]['normilized_value'] = $value_norm;
             if ($this->prepared_pairs[$key]['value'] < 0) {
                 $this->prepared_pairs[$key]['period'] = $getDate['hours'] * 60 + $getDate['minutes'];
                 $this->prepared_pairs[$key]['value'] = $last['value'];
                 $this->prepared_pairs[$key]['normilized_value'] = $last['normilized_value'];
             }
             if ($last['value'] == 0 && $this->prepared_pairs[$key]['value'] < 0) {
                 $this->prepared_pairs[$key]['value'] = 0;
                 $this->prepared_pairs[$key]['normilized_value'] = 0.0;
             }
         }
         $this->_logger->log(__METHOD__ . ' getDate: ' . $measuring_timestamp);
         $this->_logger->log(__METHOD__ . ' sensor_feature_id: ' . $sensor_feature_id);
         $this->_logger->log(__METHOD__ . ' station_id: ' . $station_id);
         $this->_logger->log(__METHOD__ . ' getDatePrev: ' . $data['measuring_timestamp']);
     }
     return $this->prepared_pairs[$key];
 }
Пример #24
0
 public function __destruct()
 {
     if (get_class(Yii::app()) != 'CConsoleApplication') {
         $tz = Yii::app()->user->getTZ();
         if ($tz != date_default_timezone_get()) {
             TimezoneWork::set($tz);
         }
     }
 }
Пример #25
0
 public function __destruct()
 {
     if (get_class(Yii::app()) != 'CConsoleApplication') {
         $tz = Yii::app()->user->getTZ();
         $this->_logger->log(__METHOD__ . ' $tz: ' . $tz);
         $this->_logger->log(__METHOD__ . ' $tz: ' . $tz);
         $this->_logger->log(__METHOD__ . ' $tz: ' . $tz);
         $this->_logger->log(__METHOD__ . ' $tz: ' . $tz);
         if ($tz != date_default_timezone_get()) {
             TimezoneWork::set($tz);
         }
     }
 }
Пример #26
0
				<?php 
echo CHtml::error($form, 'event_message_period');
?>
			</td>
		</tr>
		<?php 
/*}*/
?>
		<tr style="max-height: 200px">
			<th><?php 
echo CHtml::activeLabel($form, 'timezone_id');
?>
 <sup>*</sup></th>
			<td colspan="3">
				<?php 
echo CHtml::activeDropDownList($form, 'timezone_id', TimezoneWork::prepareList(), array('style' => 'width: 270px; height: 250px'));
?>
				<?php 
echo CHtml::error($form, 'timezone_id');
?>
			</td>
		</tr>

		<tr>
			<th><?php 
echo CHtml::activeLabel($form, 'aws_format');
?>
 <sup>*</sup></th>
			<td colspan="3">
				<?php 
echo CHtml::activeDropDownList($form, 'aws_format', AWSFormat::listFormats(), array('style' => 'width: 270px;'));
Пример #27
0
 public static function setTimeByLocalTz($tz, $time)
 {
     $tz = TimezoneWork::getReverseOffsetFromUTC($tz, 1);
     $mark = substr($tz, 0, 1);
     $hour = substr($tz, 1, 2);
     $minutes = substr($tz, 4, 2);
     $second_diff = 0;
     $second_diff = (int) $hour * 60 * 60 + (int) $minutes * 60;
     if ($mark == '-') {
         $time -= $second_diff;
     } elseif ($mark == '+') {
         $time += $second_diff;
     }
     return $time;
 }