public function generateMessage()
 {
     $station = Station::model()->findByPk($this->station_id);
     $command = 'C';
     $command .= $station->station_id_code;
     $command .= $this->sms_command_code;
     $command .= implode($this->sms_command_params ? $this->sms_command_params : []);
     $command .= It::prepareCRC($command);
     $command = '@' . $command . '$';
     return $command;
 }
Ejemplo n.º 2
0
 function checkIntegrity()
 {
     $this->_logger->log(__METHOD__);
     // sometimes arrived message can contain casual symbols before @ or after $
     // we should strip them to work with clear message
     $occurances_at = strpos($this->message_obj->message, '@');
     $occurances_dl = strpos($this->message_obj->message, '$');
     if ($occurances_at !== false && $occurances_dl !== false) {
         $this->message_obj->message = substr($this->message_obj->message, $occurances_at);
         $len = strlen($this->message_obj->message);
         $occurances_dl = ($len - strpos($this->message_obj->message, '$') - 1) * -1;
         if ($occurances_dl) {
             $this->message_obj->message = substr($this->message_obj->message, 0, $occurances_dl);
         }
     }
     // check if arrived message - is line from Rain Datalogger's log OR is regular message
     $rg_log_pattern = '/^\\d{2}\\/\\d{2}\\/\\d{2},\\d{2}:\\d{2},\\d{3},\\d{0,5}$/';
     if (preg_match($rg_log_pattern, $this->message_obj->message)) {
         $this->_message_type = 'rg_log';
         $this->_type = 'rain';
     } else {
         $this->_message_type = 'message';
     }
     $this->_logger->log(__METHOD__ . ' Message type detected', array('type' => $this->_message_type));
     // if arrived message - is regular message
     if ($this->_message_type == 'message') {
         // message must start with @
         if (substr($this->message_obj->message, 0, 1) != '@') {
             $this->pushError('start_missed', 'Record does not start with @');
         }
         // message must end with $
         if (substr($this->message_obj->message, -1, 1) != '$') {
             $this->pushError('end_missed', 'Record does not end with $');
         }
         if (!$this->errors) {
             // Rain DataLogger's message has R at 22nd position
             if (substr($this->message_obj->message, 21, 1) == 'R') {
                 $this->_type = 'rain';
                 $this->_header = substr($this->message_obj->message, 0, 21);
             } else {
                 $this->_type = 'aws';
                 $this->_header = substr($this->message_obj->message, 0, 19);
             }
             // footer - is last 8 symbols of message without first and last symbols
             $this->_footer = substr($this->message_obj->message, -9, -1);
             // crc source - is CRC code of other part of the message
             $compare_with_crc = substr($this->message_obj->message, 1, -9);
             $check_str = It::prepareCRC($compare_with_crc);
             if ($check_str !== $this->_footer) {
                 $this->pushError('crc_wrong', 'CRC code is incorrect');
             }
         }
     }
     if (!$this->errors) {
         // RG log line, AWS and Rain messages have different position of date and time
         // RG message also has battery voltage value without specific sensor
         // station ID is located just after date and time substrings, so we can get it by the way
         if ($this->_message_type == 'rg_log') {
             $this->_tx_date = str_replace('/', '', substr($this->message_obj->message, 0, 8));
             $this->_tx_time = str_replace(':', '', substr($this->message_obj->message, 9, 5));
             $this->rg_battery_voltage = substr($this->message_obj->message, 15, 3);
             $this->_body = substr($this->message_obj->message, 19);
             $this->getStation('', $this->message_obj->station_id);
         } else {
             if ($this->_type == 'aws') {
                 // starts from 20s symbol and discards 9 symbols from end (CRC)
                 $this->_body = substr($this->message_obj->message, 19, -9);
                 $this->_tx_date = substr($this->message_obj->message, 7, 6);
                 $this->_tx_time = substr($this->message_obj->message, 13, 4);
                 $station_id = substr($this->message_obj->message, 2, 5);
             } else {
                 // starts from 22d symbol and discards 9 symbols from end (CRC)
                 $this->_body = substr($this->message_obj->message, 21, -9);
                 $this->_tx_date = substr($this->message_obj->message, 6, 6);
                 $this->_tx_time = substr($this->message_obj->message, 12, 4);
                 $this->rg_battery_voltage = substr($this->message_obj->message, 16, 3);
                 $station_id = substr($this->message_obj->message, 2, 4);
             }
             $this->getStation($station_id);
         }
         // Check length string of DATE & TIME
         // Good if strlen(date + time) == 6 + 4 and date + time is numeric
         if (empty($this->_tx_date) || empty($this->_tx_time) || strlen($this->_tx_date . $this->_tx_time) != 10 || !is_numeric($this->_tx_date . $this->_tx_time)) {
             $this->pushError('date_format', 'Time or date is incorrect:' . $this->_tx_date . $this->_tx_time);
         }
     }
 }
 /**
  * @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]);
     }
 }
 /**
  * @param $data
  * @param $prev
  * @return string
  */
 private function getMsg($data, $prev)
 {
     if (is_null($prev)) {
         $prev = $data;
     }
     $params = [];
     $a = date_create_from_format('m/d/Y H:i', $prev['DATE'] . ' ' . $prev['TIME']);
     $b = date_create_from_format('m/d/Y H:i', $data['DATE'] . ' ' . $data['TIME']);
     $i = (int) $b->diff($a, true)->format('i');
     $h = (int) $b->diff($a, true)->format('h');
     if ($i == 0 && $h != 0) {
         $i = $h * 60;
     } elseif ($h != 0 && $i != 0) {
         $i = $i + $h * 60;
     }
     $params['interval'] = $i;
     $msg = $this->prefix;
     $msg .= $this->getStation();
     $msg .= $b->format('ymd');
     $msg .= $b->format('Hi');
     $msg .= '00';
     $msg .= $this->prepareData($data, $params);
     return '@' . $msg . It::prepareCRC($msg) . '$';
 }
Ejemplo n.º 5
0
 /**
  * Find current sms command and set in here response
  *
  * @param $response string
  * @example $response OK   : '@ B AWS01 DT OK   234567890 BV1 126 7558E9F6 $' (without space)
  * @example $response FAIL : '@ B AWS01 DT FAIL                   E3290CA6 $' (without space)
  *
  * @return null|SMSCommand
  */
 public static function setResponse($response)
 {
     /**
      * 1. Min response length
      * 2. Lead X code
      * 3. Start @
      *    Ended $
      * 4. CRC
      */
     if (strlen($response) >= 18 && (substr($response, 1, 1) === 'B' || substr($response, 1, 1) === 'C') && substr($response, 0, 1) === '@' && substr($response, -1) === '$' && substr($response, -9, 8) === It::prepareCRC(substr($response, 1, -9))) {
         $sms_command_code = substr($response, 7, 2);
         $station_id_code = substr($response, 2, 5);
         $qb = new CDbCriteria();
         $qb->compare('sms_command_status', SMSCommand::STATUS_SENT);
         $qb->compare('sms_command_code', $sms_command_code);
         $qb->compare('station.station_id_code', $station_id_code);
         $qb->with = ['station' => ['select' => false]];
         $qb->order = 't.updated ASC';
         /** @var SMSCommand $sms_command */
         $sms_command = SMSCommand::model()->find($qb);
         if (!isset($sms_command)) {
             $sms_command = new SMSCommand();
             $station = Station::Model()->findByAttributes(array('station_id_code' => $station_id_code));
             if (is_null($station)) {
                 return null;
             }
             $sms_command->station_id = $station->station_id;
             $sms_command->sms_command_code = "-";
             $sms_command->sms_command_message = "-";
         }
         $sms_command->sms_command_response = $response;
         $sms_command->sms_command_status = SMSCommand::STATUS_PROCESSED;
         if (!$sms_command->save()) {
             It::sendLetter(yii::app()->params['developer_email'], 'Error', json_encode($sms_command->getErrors()));
         }
         return $sms_command;
     }
     return null;
 }
Ejemplo n.º 6
0
 public function actionMsgGeneration()
 {
     ini_set('memory_limit', '-1');
     $form = new GenerateMessageForm();
     $messages = array();
     $sensors = array();
     if (Yii::app()->request->isPostRequest && (isset($_POST['generate']) || isset($_POST['import']))) {
         $form->attributes = $_POST['GenerateMessageForm'];
         if ($form->validate()) {
             $sensors = array();
             if ($form->sensor_id) {
                 $sql = "SELECT `t1`.`station_sensor_id`, `t1`.`sensor_id_code`, `t2`.`handler_id_code`, `t3`.`feature_code`, `t4`.`code` AS `metric_code` \n                            FROM `" . StationSensor::model()->tableName() . "` `t1`\n                            LEFT JOIN `" . SensorDBHandler::model()->tableName() . "`      `t2` ON `t2`.`handler_id` = `t1`.`handler_id`\n                            LEFT JOIN `" . StationSensorFeature::model()->tableName() . "` `t3` ON `t3`.`sensor_id`  = `t1`.`station_sensor_id`\n                            LEFT JOIN `" . RefbookMetric::model()->tableName() . "`        `t4` ON `t4`.`metric_id`  = `t3`.`metric_id`\n                            WHERE `t1`.`station_id` = '" . $form->station_id . "' AND `t1`.`station_sensor_id` IN (" . implode(',', $form->sensor_id) . ")";
                 $res = Yii::app()->db->createCommand($sql)->queryAll();
                 if ($res) {
                     foreach ($res as $key => $value) {
                         if (!isset($sensors[$value['station_sensor_id']])) {
                             $sensors[$value['station_sensor_id']] = array('station_sensor_id' => $value['station_sensor_id'], 'sensor_id_code' => $value['sensor_id_code'], 'handler_id_code' => $value['handler_id_code']);
                         }
                         $sensors[$value['station_sensor_id']]['features'][$value['feature_code']] = $value['metric_code'];
                     }
                 }
             }
             $i = $form->start_timestamp;
             while ($i <= $form->end_timestamp) {
                 $messages[$i]['timestamp'] = $i;
                 $i = $i + $form->interval * 60;
             }
             foreach ($messages as $key => $value) {
                 if ($form->choosed_station['station_type'] === 'rain') {
                     $messages[$key]['parts'][] = 'D';
                     $messages[$key]['parts'][] = $form->choosed_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'][] = $form->choosed_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']);
     }
     $station_sensors = StationSensor::getList($form->station_id);
     if ($station_sensors) {
         foreach ($station_sensors as $key => $value) {
             $station_sensors[$key]['checked'] = 1;
         }
     }
     if (isset($_POST['GenerateMessageForm']['sensor_id'])) {
         if ($station_sensors) {
             foreach ($station_sensors as $key => $value) {
                 $station_sensors[$key]['checked'] = in_array($value['station_sensor_id'], $_POST['GenerateMessageForm']['sensor_id']) ? 1 : 0;
             }
         }
     }
     $this->render('msg_generation', array('form' => $form, 'messages_display' => $messages_display, 'messages_copy' => $messages_copy, 'station_sensors' => $station_sensors));
 }
Ejemplo n.º 7
0
 /**
  * Generates poll command for a given station.
  * 
  * @param Station $station
  * @return string
  */
 protected function generatePollCommand($station)
 {
     $command = 'C';
     $command .= $station->station_id_code;
     $command .= 'DR';
     $command .= It::prepareCRC($command);
     $command = '@' . $command . '$';
     return $command;
 }
Ejemplo n.º 8
0
 public function process($path)
 {
     if (!file_exists($path)) {
         throw new Exception('Can\'t find file ' . $path);
     }
     $pathinfo = pathinfo($path);
     $base_filename = $pathinfo['basename'];
     $xml_content = file_get_contents($path);
     if (!strlen($xml_content)) {
         throw new Exception($base_filename . " is empty");
     }
     libxml_use_internal_errors(true);
     $sxe = simplexml_load_string($xml_content);
     $error_str = "";
     if ($sxe === false) {
         foreach (libxml_get_errors() as $error) {
             $error_str .= "\n" . $error->message;
         }
         throw new Exception($error_str);
     }
     // XML must contain 1 RUNWAY tag
     if (count($sxe->RUNWAY) > 1) {
         throw new Exception('XML ' . $base_filename . ' contains ' . count($sxe->RUNWAY) . ' RUNWAY tags');
     }
     if (count($sxe->RUNWAY) == 0) {
         throw new Exception('XML ' . $base_filename . ' doesn\'t contain RUNWAY tags');
     }
     // RUNWAY's "NAME" attribute must be "08/26"
     if ($sxe->RUNWAY['NAME'] != '08/26') {
         throw new Exception('XML ' . $base_filename . ' RUNWAY name = "' . $sxe->RUNWAY['NAME'] . '", "08/26" was expected');
     }
     // RUNWAY must contain at least 1 ZONE tag
     if (count($sxe->RUNWAY->ZONE) == 0) {
         throw new Exception('XML ' . $base_filename . ' doesn\'t contain ZONE tags');
     }
     // XML must contain "UNITS" tag
     if (!isset($sxe->UNITS)) {
         throw new Exception('XML ' . $base_filename . ' doesn\'t contain UNITS section');
     }
     $str = '';
     $possible_units = array('WIND' => 'kt', 'VISBILITY' => 'meters', 'RVR' => 'meters', 'ALTIMETER' => 'hpa');
     foreach ($possible_units as $key => $value) {
         if (!isset($sxe->UNITS->{$key})) {
             $str .= ($str ? '; ' : '') . ' UNITS[' . $key . '] is missed';
         } else {
             if ($sxe->UNITS->{$key} != $value) {
                 $str .= ($str ? '; ' : '') . ' unknown metric "' . $sxe->UNITS->{$key} . '" in UNITS[' . $key . ']';
             }
         }
     }
     if ($str) {
         throw new Exception($str);
     }
     $result = array();
     $messages = array();
     for ($key = 0; $key < count($sxe->RUNWAY->ZONE); $key++) {
         // Get's Station ID
         if ($sxe->RUNWAY->ZONE[$key]['NAME'] == '08') {
             $messages[$key]['station_id_code'] = 'AWS08';
         } else {
             if ($sxe->RUNWAY->ZONE[$key]['NAME'] == '26') {
                 $messages[$key]['station_id_code'] = 'AWS26';
             } else {
                 continue;
             }
         }
         //Gets sensor's data from tags:
         // WIND SPEED
         if (isset($sxe->RUNWAY->ZONE[$key]->WSPD_5SEC)) {
             $messages[$key]['sensors']['WindSpeed'][0]['wind_speed_1'] = (string) $sxe->RUNWAY->ZONE[$key]->WSPD_5SEC;
         }
         if (isset($sxe->RUNWAY->ZONE[$key]->WSPD_2MIN)) {
             $messages[$key]['sensors']['WindSpeed'][0]['wind_speed_2'] = (string) $sxe->RUNWAY->ZONE[$key]->WSPD_2MIN;
         }
         // WIND DIRECTION
         if (isset($sxe->RUNWAY->ZONE[$key]->WDIR_5SEC)) {
             $messages[$key]['sensors']['WindDirection'][0]['wind_direction_1'] = (string) $sxe->RUNWAY->ZONE[$key]->WDIR_5SEC;
         }
         if (isset($sxe->RUNWAY->ZONE[$key]->WDIR_2MIN)) {
             $messages[$key]['sensors']['WindDirection'][0]['wind_direction_2'] = (string) $sxe->RUNWAY->ZONE[$key]->WDIR_2MIN;
         }
         // TEMPERATURE
         if (isset($sxe->RUNWAY->ZONE[$key]->TEMP_5MIN)) {
             $messages[$key]['sensors']['Temperature'][0]['temperature'] = (string) $sxe->RUNWAY->ZONE[$key]->TEMP_5MIN;
         }
         // HUMIDITY
         if (isset($sxe->RUNWAY->ZONE[$key]->HUM_5MIN)) {
             $messages[$key]['sensors']['Humidity'][0]['humidity'] = (string) $sxe->RUNWAY->ZONE[$key]->HUM_5MIN;
         }
         // PRESSURE
         if (isset($sxe->RUNWAY->ZONE[$key]->PRESSURE1)) {
             $messages[$key]['sensors']['Pressure'][0]['pressure'] = (string) $sxe->RUNWAY->ZONE[$key]->PRESSURE1;
         }
         if (isset($sxe->RUNWAY->ZONE[$key]->PRESSURE2)) {
             $messages[$key]['sensors']['Pressure'][1]['pressure'] = (string) $sxe->RUNWAY->ZONE[$key]->PRESSURE2;
         }
         if (isset($sxe->RUNWAY->ZONE[$key]->PRESSURE3)) {
             $messages[$key]['sensors']['Pressure'][2]['pressure'] = (string) $sxe->RUNWAY->ZONE[$key]->PRESSURE3;
         }
         // CLOUD
         if (isset($sxe->RUNWAY->ZONE[$key]->CLOUDRANGE)) {
             $messages[$key]['sensors']['CloudHeightAWS'][0]['cloud_measuring_range'] = (string) $sxe->RUNWAY->ZONE[$key]->CLOUDRANGE;
         }
         if (isset($sxe->RUNWAY->ZONE[$key]->CLOUDVV)) {
             $messages[$key]['sensors']['CloudHeightAWS'][0]['cloud_vertical_visibility'] = (string) $sxe->RUNWAY->ZONE[$key]->CLOUDVV;
         }
         if (isset($sxe->RUNWAY->ZONE[$key]->CLOUDH1)) {
             $messages[$key]['sensors']['CloudHeightAWS'][0]['cloud_height_height_1'] = (string) $sxe->RUNWAY->ZONE[$key]->CLOUDH1;
         }
         if (isset($sxe->RUNWAY->ZONE[$key]->CLOUDH2)) {
             $messages[$key]['sensors']['CloudHeightAWS'][0]['cloud_height_height_2'] = (string) $sxe->RUNWAY->ZONE[$key]->CLOUDH2;
         }
         if (isset($sxe->RUNWAY->ZONE[$key]->CLOUDH3)) {
             $messages[$key]['sensors']['CloudHeightAWS'][0]['cloud_height_height_3'] = (string) $sxe->RUNWAY->ZONE[$key]->CLOUDH3;
         }
         if (isset($sxe->RUNWAY->ZONE[$key]->CLOUDD1)) {
             $messages[$key]['sensors']['CloudHeightAWS'][0]['cloud_height_depth_1'] = (string) $sxe->RUNWAY->ZONE[$key]->CLOUDD1;
         }
         if (isset($sxe->RUNWAY->ZONE[$key]->CLOUDD2)) {
             $messages[$key]['sensors']['CloudHeightAWS'][0]['cloud_height_depth_2'] = (string) $sxe->RUNWAY->ZONE[$key]->CLOUDD2;
         }
         if (isset($sxe->RUNWAY->ZONE[$key]->CLOUDD3)) {
             $messages[$key]['sensors']['CloudHeightAWS'][0]['cloud_height_depth_3'] = (string) $sxe->RUNWAY->ZONE[$key]->CLOUDD3;
         }
         // VISIBILITY
         $vis = (string) $sxe->RUNWAY->ZONE[$key]->EXC;
         if (isset($sxe->RUNWAY->ZONE[$key]->EXC) && is_numeric($vis) && $vis != 0) {
             //P = (1/σ) x ln (1/0.05)
             //where ln is the log to base e or the natural logarithm. σ  is the extinction cooefficient.
             //This number will be in km, so we will need to multiply by 1000.
             $messages[$key]['sensors']['VisibilityAWS'][0]['visibility_1'] = 1 / $vis * log(20) * 1000;
         }
         // SOLAR
         if (isset($sxe->RUNWAY->ZONE[$key]->SOLAR_1MIN)) {
             $messages[$key]['sensors']['SolarRadiation'][0]['solar_radiation_in_period'] = (string) $sxe->RUNWAY->ZONE[$key]->SOLAR_1MIN;
         }
         // Rain fall
         if (isset($sxe->RUNWAY->ZONE[$key]->PRECIP_ACCUM)) {
             $messages[$key]['sensors']['RainAws'][0]['period'] = 5;
             $messages[$key]['sensors']['RainAws'][0]['rain_in_period'] = (string) $sxe->RUNWAY->ZONE[$key]->PRECIP_ACCUM;
         }
         // Sunshine duration
         if (isset($sxe->RUNWAY->ZONE[$key]->SUN_ACCUM)) {
             $messages[$key]['sensors']['SunshineDuration'][0]['period'] = 5;
             $messages[$key]['sensors']['SunshineDuration'][0]['sun_duration_in_period'] = (string) $sxe->RUNWAY->ZONE[$key]->SUN_ACCUM;
         }
     }
     if (!$messages) {
         $result[] = $base_filename . " : No datasets found";
         return implode("\n", $result);
     }
     $result[] = $base_filename . " : " . count($messages) . ' datasets were found';
     $sql = "SELECT * \n                FROM `" . Station::model()->tableName() . "` `t1`\n                WHERE `t1`.`station_id_code` IN ('AWS08', 'AWS26')";
     $res = Yii::app()->db->createCommand($sql)->queryAll();
     if (!$res) {
         $result[] = "AWS08 and AWS26 are not exist in database, no sense to convert XML into messages";
         return implode("\n", $result);
     }
     // for each stationID looks for sensors and features of this station
     $stations = array();
     foreach ($res as $key => $value) {
         $stations[$value['station_id_code']] = $value;
         $sql = "SELECT `t1`.`sensor_id_code`,\n                           `t1`.`station_id`,\n                           `t2`.`feature_code`,\n                           `t3`.`code` AS `metric_code`,\n                           `t4`.`handler_id_code`\n                    FROM `" . StationSensor::model()->tableName() . "` `t1`\n                    LEFT JOIN `" . StationSensorFeature::model()->tableName() . "` `t2` ON `t1`.`station_sensor_id` = `t2`.`sensor_id`\n                    LEFT JOIN `" . RefbookMetric::model()->tableName() . "`        `t3` ON `t3`.`metric_id` = `t2`.`metric_id`\n                    LEFT JOIN `" . SensorDBHandler::model()->tableName() . "`      `t4` ON `t4`.`handler_id` = `t1`.`handler_id`\n                    WHERE `t1`.`station_id` = '" . $value['station_id'] . "'\n                    ORDER BY `t4`.`handler_id_code` ASC, `t1`.`sensor_id_code` ASC";
         $res2 = Yii::app()->db->createCommand($sql)->queryAll();
         if ($res2) {
             $tmp = array();
             foreach ($res2 as $value2) {
                 $tmp[$value2['handler_id_code']][$value2['sensor_id_code']][$value2['feature_code']] = $value2['metric_code'];
             }
             foreach ($tmp as $key_handler => $value_sensors) {
                 foreach ($value_sensors as $key_sensor => $value_features) {
                     $stations[$value['station_id_code']]['sensors'][$key_handler][] = array('sensor_id_code' => $key_sensor, 'features' => $value_features);
                 }
             }
         }
     }
     $date_parsed = date_parse_from_format("D, j M Y H:i:s", $sxe->DATE);
     $date_prepared = mktime($date_parsed['hour'], $date_parsed['minute'], $date_parsed['second'], $date_parsed['month'], $date_parsed['day'], $date_parsed['year']);
     // convert parsed XML data into regular message
     // for this kind of messages we have an agreement to put X instead of D at the beginning of message.
     foreach ($messages as $key => $value) {
         if (!$stations[$value['station_id_code']]) {
             $result[] = $value['station_id_code'] . " station is not exists in database, no sense to convert RNWY part into message";
             continue;
         }
         $result_message_body = 'X' . $value['station_id_code'];
         $result_message_body .= date('ymdHi', $date_prepared);
         $result_message_body .= '00';
         // we need last_log for this satation to calculate period of measurement (some sensors' strings should contain this period
         $last_logs = ListenerLog::getLast2Messages($stations[$value['station_id_code']]['station_id']);
         if (isset($value['sensors'])) {
             foreach ($value['sensors'] as $key_handler => $value_sensors) {
                 if ($value_sensors) {
                     foreach ($value_sensors as $key_sensor => $value2) {
                         if (isset($stations[$value['station_id_code']]['sensors'][$key_handler][$key_sensor])) {
                             // create handler for each sensor (we parsed new data for)
                             $handler = SensorHandler::create($key_handler);
                             if ($key_handler == 'SolarRadiation' && $last_logs[0]['log_id']) {
                                 if ($last_logs[0]['log_id']) {
                                     $total_minutes = round(abs($date_prepared - strtotime($last_logs[0]['measuring_timestamp'])) / 60);
                                     $value2['period'] = $total_minutes;
                                 } else {
                                     $value2['period'] = 1;
                                 }
                                 if ($value2['solar_radiation_in_period'][0] != 'M') {
                                     $value2['solar_radiation_in_period'] = $value2['solar_radiation_in_period'] * $value2['period'] * 60;
                                 }
                             }
                             // each handler has it's own implementation of preparing sensors string for message basing on XML data
                             $res = $handler->prepareXMLValue($value2, $stations[$value['station_id_code']]['sensors'][$key_handler][$key_sensor]['features']);
                             $result_message_body .= $stations[$value['station_id_code']]['sensors'][$key_handler][$key_sensor]['sensor_id_code'] . $res;
                         }
                     }
                 }
             }
             $result_message_body .= It::prepareCRC($result_message_body);
             $result_message_body = '@' . $result_message_body . '$';
             // add new message into database. It will be processed later as all newcame messages
             $log_id = ListenerLog::addNew($result_message_body, 0, 1);
             $result[] = $base_filename . " : New message #" . $log_id . " was added";
         }
     }
     // return some comments created during convertation
     return implode("\n", $result);
 }