Exemplo n.º 1
2
 public function init()
 {
     if (preg_match('/COM[0-9]+/', $this->source)) {
         $this->_logger->log(__METHOD__ . ' Check Serial port');
         // else it is COM port connection: it can be DataLogger or GSM modem
         ListenerProcess::addComment($this->listener->listener_id, 'hardware_recognizing', SMSCOMPort::getLinuxComName($this->source) . ' is Serial port.');
         try {
             // try to send AT command
             // if script recieves "OK" - this is GSM modem. Else - it can be only DataLogger
             $serial = new PhpSerial($this->_logger);
             $this->_logger->log(__METHOD__ . $this->source);
             $serial->deviceSet($this->source);
             $serial->confFlowControl(Yii::app()->params['com_connect_params']['hardwareflowcontrol']);
             $serial->confBaudRate(Yii::app()->params['com_connect_params']['baudrate']);
             $serial->confParity(Yii::app()->params['com_connect_params']['parity']);
             $serial->confStopBits(Yii::app()->params['com_connect_params']['stopbits']);
             $serial->confCharacterLength(Yii::app()->params['com_connect_params']['databits']);
             $this->_connector = new GsmModemSerialConnector($this->_logger, $serial);
             $this->_connector->setParams(array('port' => $this->source));
             ListenerProcess::addComment($this->listener->listener_id, 'hardware_recognizing', 'Script started to recognize hardware connected to PC via Serial port');
             if ($this->listener->additional_param == 'SMS') {
                 while (1) {
                     if ($this->_connector->check()) {
                         $this->_logger->log(__METHOD__, array('hardware' => 'modem'));
                         $this->hardware = 'modem';
                         ListenerProcess::addComment($this->listener->listener_id, 'hardware_recognizing', 'Hardware connected to PC via Serial port - is GSM Modem');
                         $this->_logger->log(__METHOD__, array('hardware' => $this->hardware));
                         return true;
                     }
                     sleep(60);
                 }
             }
             $this->_connector = new DataLoggerSerialConnector($this->_logger, $serial);
             $this->_connector->setParams(array('port' => $this->source));
             if ($this->listener->additional_param == 'DIRECT') {
                 if ($this->_connector->check()) {
                     $this->_logger->log(__METHOD__, array('hardware' => 'datalogger'));
                     $this->hardware = 'dl';
                     ListenerProcess::addComment($this->listener->listener_id, 'hardware_recognizing', 'Hardware connected to PC via Serial port - is Datalogger');
                     $this->_logger->log(__METHOD__, array('hardware' => $this->hardware));
                     return true;
                 }
             }
         } catch (Exception $e) {
             $this->_logger->log(__METHOD__, array('ExceptionMessage' => $e->getMessage()));
         }
         $this->_logger->log(__METHOD__, array('hardware' => 'unknown'));
         $this->hardware = 'unknown';
         ListenerProcess::addComment($this->listener->listener_id, 'hardware_recognizing', 'No device found.');
         $this->_logger->log(__METHOD__, array('hardware' => $this->hardware));
         return false;
     }
 }
Exemplo n.º 2
1
 /**
  * 
  */
 public function send()
 {
     $this->_logger->log(__METHOD__, array('phone' => $this->_phoneNumber, 'message' => $this->_messageText));
     $this->_errors = array();
     set_error_handler(array($this, 'errorHandler'));
     try {
         if ($this->_serial->deviceSet($this->_serialPort) === true) {
             $this->_serial->confBaudRate($this->_serialPortParams['baudrate']);
             $this->_serial->confStopBits($this->_serialPortParams['stopbits']);
             $this->_serial->confParity($this->_serialPortParams['parity']);
             $this->_serial->confCharacterLength($this->_serialPortParams['databits']);
             $this->_serial->confFlowControl($this->_serialPortParams['hardwareflowcontrol']);
             if ($this->_serial->deviceOpen('r+b') === true) {
                 if ($this->sendSmsMessage()) {
                     $this->_logger->log(__METHOD__ . ' SMS message was sent', array('phone_number' => $this->_phoneNumber, 'serial_port' => $this->_serialPort, 'message' => $this->_messageText));
                     ListenerProcess::addComment($this->_listener->listener_id, 'sms_command', 'SMS message was sent to: "' . $this->_phoneNumber . '" using: ' . $this->_serialPort);
                 } else {
                     $this->_logger->log(__METHOD__ . ' Failed to send SMS message', array('phone_number' => $this->_phoneNumber, 'serial_port' => $this->_serialPort, 'message' => $this->_messageText));
                     ListenerProcess::addComment($this->_listener->listener_id, 'sms_command', 'Failed to send SMS message to: "' . $this->_phoneNumber . '" using: ' . $this->_serialPort);
                     $this->_errors[] = 'SMS message was not sent.';
                 }
                 $this->_serial->deviceClose();
             } else {
                 $this->_errors[] = 'Can\'t open port "' . $this->_serialPort . '".';
             }
         } else {
             $this->_errors[] = 'Can\'t set port "' . $this->_serialPort . '".';
         }
     } catch (Exception $ex) {
         if ($this->_serial->_dState === PhpSerial::SERIAL_DEVICE_OPENED) {
             $this->_serial->deviceClose();
         }
         $this->_errors[] = $ex->getMessage();
     }
     restore_error_handler();
     return count($this->_errors) === 0;
 }
Exemplo n.º 3
0
 public static function addComment($listener_id, $status, $comment = '')
 {
     $obj = new ListenerProcess();
     $obj->listener_id = $listener_id;
     $obj->status = $status;
     $obj->comment = $comment;
     $obj->save();
 }
 public function run($args)
 {
     $logger = LoggerFactory::getFileLogger('check_processes');
     $logger->log(__METHOD__ . ' Start checkprocesses command.');
     $criteria = new CDbCriteria();
     $criteria->compare('stopped', 0);
     $connections = Listener::model()->findAll($criteria);
     $logger->log(__METHOD__ . ' Found ' . count($connections) . ' connections.');
     foreach ($connections as $connection) {
         $logger->log(__METHOD__ . ' Listener info:', array('process_pid' => $connection->process_pid, 'listener_id' => $connection->listener_id, 'source' => $connection->source));
         if (ProcessPid::isActiveProcess($connection->process_pid) === false) {
             ListenerProcess::addComment($connection->listener_id, 'comment', 'System found out that process is not active any more. Process will be re-run right now.');
             Listener::stopConnection($connection->listener_id, time());
             Listener::runConnection($connection->source, $connection->additional_param, 'auto');
         }
     }
     //        ProcessPid::killProcess(12376);
     $synchronization = new Synchronization();
     if ($synchronization->isProcessed() && ProcessPid::isActiveProcess($synchronization->getTcpServerPid()) === false) {
         $synchronization->startTcpServer();
     }
     if ($synchronization->isProcessed() && ProcessPid::isActiveProcess($synchronization->getTcpClientPid()) === false) {
         $synchronization->startTcpClient();
     }
 }
Exemplo n.º 5
0
 protected function stopListenFromMasterForwardingMessages()
 {
     $source = 'TCP:' . $this->forwarding_messages_ip . ":" . $this->forwarding_messages_port;
     $last_connection = Listener::getLastConnectionInfoForSynch($source);
     if ($last_connection && !$last_connection['stopped']) {
         ProcessPid::killProcess($last_connection['process_pid']);
         ListenerProcess::addComment($last_connection['listener_id'], 'comment', 'Server has set master');
         Listener::stopConnection($last_connection['listener_id']);
         $this->_configForm->updateParam('LISTENER_ID_FROM_MASTER', false);
         $this->_configForm->saveToFile();
     }
 }
Exemplo n.º 6
0
 protected function _recognizeHardware()
 {
     $this->_logger->log(__CLASS__ . ' ' . __METHOD__, array('source' => $this->source));
     $matches = array();
     // Check IP_ADDRESS:PORT pattern
     if (preg_match('/^([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})\\:([0-9]{1,5})$/', $this->source, $matches)) {
         $this->_logger->log(__CLASS__ . ' ' . __METHOD__, array('hardware' => 'client'));
         $this->hardware = 'client';
         ListenerProcess::addComment($this->listener->listener_id, 'hardware_recognizing', $this->source . ' is IP address. Script supposes it is ESP.');
     } else {
         if (preg_match('/^POLLER\\:([a-zA-Z0-9]{1,5})$/i', $this->source, $matches)) {
             $this->_logger->log(__CLASS__ . ' ' . __METHOD__, array('hardware' => 'poller'));
             $this->hardware = 'poller';
         } else {
             if (preg_match('/^([a-zA-Z]{3,})\\:([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}|[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z]+|localhost)\\:([0-9]{1,5})$/i', $this->source, $matches)) {
                 $this->_logger->log(__CLASS__ . ' ' . __METHOD__, array('hardware' => 'server'));
                 $this->hardware = 'server';
                 ListenerProcess::addComment($this->listener->listener_id, 'hardware_recognizing', $this->source . ' is IP address with protocol. Script supposes it is Server.');
             } else {
                 if (preg_match('/COM[0-9]+/', $this->source)) {
                     $this->_logger->log(__CLASS__ . ' ' . __METHOD__ . ' Check COM port');
                     // else it is COM port connection: it can be DataLogger or GSM modem
                     ListenerProcess::addComment($this->listener->listener_id, 'hardware_recognizing', $this->source . ' is COM port.');
                     $this->hardware = 'com';
                 } else {
                     $this->_logger->log(__CLASS__ . ' ' . __METHOD__ . ' Source has no matches');
                 }
             }
         }
     }
 }
Exemplo n.º 7
0
 public static function stopConnection($listener_id, $time = 0)
 {
     $time = $time ? $time : time();
     Listener::model()->updateByPk($listener_id, array('stopped' => $time));
     ListenerProcess::addComment($listener_id, 'comment', 'Stop time was saved');
     return true;
 }
Exemplo n.º 8
0
 protected function listenDLTorrent($cycle = 1)
 {
     $this->_logger->log(__METHOD__, array('cycle' => $cycle));
     $this->_connector->setParams(array('timeout' => 60));
     ListenerProcess::addComment($this->listener->listener_id, 'comment', 'Opening COM connection');
     $messages = null;
     $process = $this;
     $logger = $process->_logger;
     $this->_connector->onReceiveMessage = function ($message) use(&$process, &$logger) {
         $logger->log(__METHOD__ . ' New message', array('message' => $message, 'listener_id' => $process->listener->listener_id, 'overwrite' => $process->settings->overwrite_data_on_listening));
         $messageId = ListenerLog::addNew($message, $process->listener->listener_id, $process->settings->overwrite_data_on_listening, 'datalogger');
         ListenerProcess::addComment($process->listener->listener_id, 'comment', 'got msg #' . $messageId);
     };
     $result = $this->_connector->readData($messages);
     $this->_logger->log(__METHOD__ . ' Complete listen datalogger.', array('cycle' => $cycle, 'result' => $result));
 }
 protected function listenPollingTemp($cycle = 1)
 {
     $this->_logger->log(__CLASS__ . ' ' . __METHOD__, array('cycle' => $cycle));
     $this->_connector->setParams(array('timeout' => 60));
     // 1min
     ListenerProcess::addComment($this->listener->listener_id, 'comment', 'Start polling');
     $messages = null;
     $process = $this;
     $logger = $process->_logger;
     $this->_connector->onReceiveMessage = function ($message, $stationId) use(&$process, &$logger) {
         $logger->log(__CLASS__ . ' ' . __METHOD__ . ' New message', array('message' => $message, 'listener_id' => $process->listener->listener_id, 'overwrite' => $process->settings->overwrite_data_on_listening));
         $messageId = ListenerLogTemp::addNew($message, $process->listener->listener_id, $process->settings->overwrite_data_on_listening, 'poller', $stationId);
         ListenerProcess::addComment($process->listener->listener_id, 'comment', 'got msg #' . $messageId);
     };
     $result = $this->_connector->readData($messages);
     $this->_logger->log(__CLASS__ . ' ' . __METHOD__ . ' Complete listen datalogger.', array('cycle' => $cycle, 'result' => $result));
     return $result;
 }
Exemplo n.º 10
0
 /**
  * Send sms commands
  *
  * @param $cycle int
  */
 protected function sendSMSByModem($cycle)
 {
     $this->_logger->log(__CLASS__ . ' ' . __METHOD__, array('cycle' => $cycle));
     // Find unsent sms
     /** @var array|SMSCommand[] $sms_commands */
     $sms_commands = SMSCommand::model()->with('station')->findAllByAttributes(['sms_command_status' => SMSCommand::STATUS_NEW], ['limit' => 5]);
     // Sent sms
     if (isset($sms_commands) && ($count = count($sms_commands))) {
         foreach ($sms_commands as $sms_command) {
             $this->_logger->log(__CLASS__ . ' ' . __METHOD__ . ' sms_command_id: ' . $sms_command->sms_command_id);
             $sms = new SmsMessageSender($this->_logger, $this->listener, new PhpSerial($this->_logger), Yii::app()->params['com_connect_params'], $this->source, $sms_command->station->phone_number, $sms_command->sms_command_message);
             if ($sms->send()) {
                 $sms_command->sms_command_status = SMSCommand::STATUS_SENT;
                 if (!$sms_command->save()) {
                     $this->_logger->log(__CLASS__ . ' ' . __METHOD__ . ' sms_command: ' . 'not save! ' . json_encode($sms_command->getErrors()));
                 }
             } elseif ($sms->hasError()) {
                 foreach ($sms->errors() as $error) {
                     $this->_logger->log(__CLASS__ . ' ' . __METHOD__ . ' error: ' . $error);
                 }
             }
             $this->_logger->log(__CLASS__ . ' ' . __METHOD__ . ' sms_command_status: ' . $sms_command->sms_command_status);
         }
         $sms_commands_sent = array_filter($sms_commands, function ($sms_command) {
             return $sms_command->sms_command_status == SMSCommand::STATUS_SENT;
         });
         if ($count = count($sms_commands_sent)) {
             ListenerProcess::addComment($this->listener->listener_id, 'sms_command', 'Sending complete. Submitted ' . $count . ' SMS command.
                 SMSCommand ids:' . implode(', ', array_keys(CHtml::listData($sms_commands_sent, 'sms_command_id', 'sms_command_message'))));
         } else {
             ListenerProcess::addComment($this->listener->listener_id, 'sms_command', 'Sending complete. Submitted ' . $count . ' SMS command.');
         }
     }
 }
Exemplo n.º 11
0
 protected function listen()
 {
     $this->_logger->log(__CLASS__ . ' ' . __METHOD__ . ' Start listen.', array('source' => $this->source));
     $messages = null;
     $process = $this;
     $logger = $process->_logger;
     $this->_connector->onReceiveMessage = function ($message, $station_id, $source_info) use(&$process, &$logger) {
         $logger->log(__CLASS__ . ' ' . __METHOD__ . ' New message', array('message' => $message, 'listener_id' => $process->listener->listener_id, 'overwrite' => $process->settings->overwrite_data_on_listening));
         $messageId = ListenerLog::addNew($message, $process->listener->listener_id, $process->settings->overwrite_data_on_listening, 'server', 0, $source_info);
         ListenerProcess::addComment($process->listener->listener_id, 'comment', 'got msg #' . $messageId);
     };
     $this->_connector->readData($messages);
     $this->_logger->log(__CLASS__ . ' ' . __METHOD__ . ' Complete listen.', array('source' => $this->source));
 }
Exemplo n.º 12
0
 public function actionStopListening()
 {
     if (!$_REQUEST['source']) {
         echo json_encode(array('errors' => array('Unknown connection type')));
         Yii::app()->end();
     }
     $source = strtoupper($_REQUEST['source']);
     $last_connection = Listener::getLastConnectionInfo($source);
     if ($last_connection && !$last_connection['stopped']) {
         ProcessPid::killProcess($last_connection['process_pid']);
         ListenerProcess::addComment($last_connection['listener_id'], 'comment', 'Stop by user');
         Listener::stopConnection($last_connection['listener_id']);
     }
     echo json_encode(array('ok' => 1));
     Yii::app()->end();
 }
Exemplo n.º 13
0
 protected function listenESPTorrent($attempt = 0)
 {
     $this->_logger->log(__CLASS__ . ' ' . __METHOD__, array('attempt' => $attempt));
     $timeout = 10;
     if ($attempt == 0) {
         ListenerProcess::addComment($this->listener->listener_id, 'comment', 'trying to connect with ' . $this->source);
     } else {
         ListenerProcess::addComment($this->listener->listener_id, 'comment', 'Trying to reconnect with ' . $this->source . '; attempt #' . $attempt . '/3');
     }
     $source_parts = explode(':', $this->source);
     // creates socket connection with IP:port
     $fp = @fsockopen($source_parts[0], $source_parts[1], $errno, $errstr, $timeout);
     if ($fp !== false) {
         $attempt = 0;
         ListenerProcess::addComment($this->listener->listener_id, 'connected', 'successfully');
         $message = '';
         while (!feof($fp)) {
             $res = fwrite($fp, ' ', 2);
             //print "\n try write: ".$res;
             $line = fread($fp, 8192);
             $line = trim($line);
             $occurances_dl = strpos($line, '$');
             if ($line != '') {
                 $message .= $line;
                 if ($occurances_dl !== false) {
                     if ($this->synchronization->isMaster()) {
                         $res = ListenerLog::addNew($message, $this->listener->listener_id, $this->settings->overwrite_data_on_listening, 'datalogger');
                     } else {
                         // slave
                         //$res = ListenerLog::addNew($message, $this->listener->listener_id, $this->settings->overwrite_data_on_listening, 'datalogger');
                     }
                     ListenerProcess::addComment($this->listener->listener_id, 'comment', 'got msg #' . $res);
                     $message = '';
                 }
             }
         }
         ListenerProcess::addComment($this->listener->listener_id, 'stopped', 'can not receive data anymore - ESP is unreachable');
         fclose($fp);
     } else {
         ListenerProcess::addComment($this->listener->listener_id, 'cannot_connect', '[' . $errno . '] ' . $errstr);
     }
     if ($attempt < 3) {
         $attempt++;
         sleep(3);
     } else {
         ListenerProcess::addComment($this->listener->listener_id, 'comment', 'Three attempts to reconnect failed. Waiting for 2 minutes before trying to reconnect.');
         sleep(120);
         $attempt = 0;
     }
     return $this->listenESPTorrent($attempt);
 }
Exemplo n.º 14
0
 private function prepareListenerDependantInserts($listener_ids)
 {
     $tables = array(ListenerProcess::model()->tableName() => 'listener_id');
     $result_sql = array();
     foreach ($tables as $table => $log_id_field) {
         $sql = "SELECT * \n                    FROM `" . $table . "`\n                    WHERE `" . $log_id_field . "` IN (" . implode(',', $listener_ids) . ")";
         $res = Yii::app()->db->createCommand($sql)->queryAll();
         $total = count($res);
         if ($res) {
             $fields = array();
             foreach ($res[0] as $key2 => $value2) {
                 $fields[] = $key2;
             }
             $sql_header = "INSERT IGNORE INTO `" . $table . "` (`" . implode('`,`', $fields) . "`) VALUES ";
             $res_sql = $sql_header;
             $cnt = 0;
             foreach ($res as $key => $value) {
                 $res_sql .= "('" . implode("','", $value) . "')";
                 if ($key + 1 < $total) {
                     $res_sql .= ", ";
                 }
                 $cnt++;
             }
             $result_sql[] = $res_sql;
             $this->addBackupLog("Prepared " . $cnt . " inserts for " . $table);
         }
     }
     return $result_sql;
 }