function smpp_check($smpp_hosts, $smpp_port, $smpp_login, $smpp_password, $smpp_from, $smpp_id) { require_once '../httpsdocs/includes/smpp/smppclient.class.php'; require_once '../httpsdocs/includes/smpp/sockettransport.class.php'; $transport = new SocketTransport($smpp_hosts, $smpp_port); $transport->setRecvTimeout(10000); $smpp = new SmppClient($transport); $smpp->debug = false; $transport->debug = false; $transport->open(); $smpp->bindTransmitter($smpp_login, $smpp_password); $source = new SmppAddress($smpp_from, SMPP::TON_ALPHANUMERIC); if ($smpp_res = $smpp->queryStatus($smpp_id, $source)) { $smpp->close(); return $smpp_res; } else { $smpp->close(); return false; } }
/** * {@inheritDoc} */ public function send(SmsInterface $sms, GatewayInterface $gateway) { // Get the gateway configurations $configs = $gateway->getConfigs(); // Create a new socket transport $transport = new \SocketTransport(array($gateway->getHost()), $gateway->getPort(), $configs['persistent']); $transport->setSendTimeout($configs['send_timeout']); $transport->setRecvTimeout($configs['receive_timeout']); $transport->debug = $configs['debug']; // Create a new SMPP client $smpp = new \SmppClient($transport); $smpp->debug = $configs['debug']; // Open the connection $transport->open(); $smpp->bindTransmitter($gateway->getUsername(), $gateway->getPassword()); // Configure a sender, recipient and message $sender = new \SmppAddress($sms->getSender(), $configs['sender']['ton'], $configs['sender']['npi']); $recipient = new \SmppAddress($sms->getRecipient(), $configs['recipient']['ton'], $configs['recipient']['npi']); $message = \GsmEncoder::utf8_to_gsm0338($sms->getMessage()); // Send an SMS and close the connection $messageId = $smpp->sendSMS($sender, $recipient, $message); $smpp->close(); return $messageId; }
<?php require_once 'smppclient.class.php'; require_once 'gsmencoder.class.php'; require_once 'sockettransport.class.php'; // Construct transport and client $transport = new SocketTransport(array('127.0.0.1'), 2775); $transport->setRecvTimeout(100000); $smpp = new SmppClient($transport); // Activate binary hex-output of server interaction $smpp->debug = true; $transport->debug = true; // Open the connection $transport->open(); $smpp->bindTransmitter("demouser", "demopass"); // Optional connection specific overrides //SmppClient::$sms_null_terminate_octetstrings = false; //SmppClient::$csms_method = SmppClient::CSMS_PAYLOAD; //SmppClient::$sms_registered_delivery_flag = SMPP::REG_DELIVERY_SMSC_BOTH; // Prepare message $tags = array(); $from = new SmppAddress('SMSIND', SMPP::TON_ALPHANUMERIC); $to = new SmppAddress(919942012345, SMPP::TON_INTERNATIONAL, SMPP::NPI_E164); for ($i = 0; $i < 1; $i++) { $message = 'Hello sms from Mr.ABC' . $i . '.'; //$encodedMessage = $message; $encodedMessage = utf8_encode($message); // $encodedMessage = GsmEncoder::utf8_to_gsm0338($message); // Send $msgid = $smpp->sendSMS($from, $to, $encodedMessage, $tags); print 'message ref id: ' . $msgid;
<?php // эта строчка обязательна к подключению всеми скриптами require_once $_SERVER['DOCUMENT_ROOT'] . "/prerequisites.php"; // проверяем, онлайн ли выбранный контроллер $online = 0; if ($authorized) { $posted = intval(@$_GET['posted']); if ($posted == 1) { $controller_id = intval(@$_GET['controller_id']); if ($controller_id > 0) { // обновляем базу $res = $dbengine->query("SELECT * FROM controllers WHERE controller_id={$controller_id};"); if ($array = $res->fetchArray()) { $online = $array['is_online']; $tp = new SocketTransport(); if ($tp->open($array['controller_address'])) { $online = 1; $tp->close(); } else { $online = 0; } if ($online != $array['is_online']) { $dbengine->beginTransaction(); $dbengine->exec("UPDATE controllers SET is_online={$online} WHERE controller_id={$controller_id};"); $dbengine->commitTransaction(); } } } } // if
/** * Sets the receive timeout. * Returns true on success, or false. * @param int $timeout Timeout in milliseconds. * @return boolean */ public function setRecvTimeout($timeout) { if (!$this->isOpen()) { self::$defaultRecvTimeout = $timeout; } else { $r = socket_set_option($this->socket, SOL_SOCKET, SO_RCVTIMEO, $this->millisecToSolArray($timeout)); return $r; } }
function requestControllerData($controller_id, $address) { global $dbengine; global $states; global $sensor_types; global $modules; global $SIMULATION; global $SAVE_CONTROLLER_STATE; $NO_TEMPERATURE_DATA = "-128.00"; // нет показаний с датчика температуры $NO_LUMINOSITY_DATA = "-1.00"; // нет показаний с датчика освещенности $NO_PH_DATA = "-128.00"; // нет показаний с датчика pH // пытаемся законнектиться $tp = new SocketTransport(); if ($tp->open($address)) { // законнектились if (!$SIMULATION) { $dbengine->beginTransaction(); $dbengine->exec("UPDATE controllers SET is_online=1 WHERE controller_id={$controller_id};"); $dbengine->commitTransaction(); } // теперь собираем данные $line = trim($tp->ctget('0|STAT')); // проверяем, ок ли ответ? $pos = strpos($line, 'OK='); if (!($pos === false)) { // ответ OK, продолжаем парсить $line = substr($line, 3); if ($SIMULATION) { echo $line . "\n"; } // теперь разбираем, чего там пришло $firstByte = hexdec(substr($line, 0, 2)); $secondByte = hexdec(substr($line, 2, 2)); if ($SIMULATION) { echo $firstByte . "\n"; echo $secondByte . "\n"; } $line = substr($line, 4); if ($SIMULATION) { echo $line . "\n"; } // проверяем состояния $windows_open = BitIsSet($firstByte, 0) ? 1 : 0; $windows_auto_mode = BitIsSet($firstByte, 1) ? 1 : 0; $water_on = BitIsSet($firstByte, 2) ? 1 : 0; $water_auto_mode = BitIsSet($firstByte, 3) ? 1 : 0; $light_on = BitIsSet($firstByte, 4) ? 1 : 0; $light_auto_mode = BitIsSet($firstByte, 5) ? 1 : 0; if ($SIMULATION) { echo "windows open: {$windows_open}\nwindows auto mode: {$windows_auto_mode}\nwater on: {$water_on}\nwater auto mode: {$water_auto_mode}\nlight on: {$light_on}\nlight auto mode: {$light_auto_mode}\n"; } // теперь генерируем набор SQL для вставки if (!$SIMULATION) { $dbengine->beginTransaction(); } if ($SAVE_CONTROLLER_STATE) { $sql = "INSERT INTO controller_state(controller_id,state_id,state) VALUES({$controller_id}, {$states['WINDOWS']}, {$windows_open});"; if ($SIMULATION) { echo $sql . "\n"; } else { $dbengine->exec($sql); } $sql = "INSERT INTO controller_state(controller_id,state_id,state) VALUES({$controller_id}, {$states['WINDOWS_MODE']}, {$windows_auto_mode});"; if ($SIMULATION) { echo $sql . "\n"; } else { $dbengine->exec($sql); } $sql = "INSERT INTO controller_state(controller_id,state_id,state) VALUES({$controller_id}, {$states['WATER']}, {$water_on});"; if ($SIMULATION) { echo $sql . "\n"; } else { $dbengine->exec($sql); } $sql = "INSERT INTO controller_state(controller_id,state_id,state) VALUES({$controller_id}, {$states['WATER_MODE']}, {$water_auto_mode});"; if ($SIMULATION) { echo $sql . "\n"; } else { $dbengine->exec($sql); } $sql = "INSERT INTO controller_state(controller_id,state_id,state) VALUES({$controller_id}, {$states['LIGHT']}, {$light_on});"; if ($SIMULATION) { echo $sql . "\n"; } else { $dbengine->exec($sql); } $sql = "INSERT INTO controller_state(controller_id,state_id,state) VALUES({$controller_id}, {$states['LIGHT_MODE']}, {$light_auto_mode});"; if ($SIMULATION) { echo $sql . "\n"; } else { $dbengine->exec($sql); } } // if($SAVE_CONTROLLER_STATE) // тут уже обновили состояние контроллера, пора переходить к данным while (strlen($line) > 0) { $f = substr($line, 0, 2); $line = substr($line, 2); $flags = hexdec($f); $tempPresent = ($flags & 1) == 1; $luminosityPresent = ($flags & 4) == 4; $humidityPresent = ($flags & 8) == 8; $waterFlowInstantPresent = ($flags & 16) == 16; $waterFlowIncrementalPresent = ($flags & 32) == 32; $soilMoisturePresent = ($flags & 64) == 64; $phPresent = ($flags & 128) == 128; // читаем байт имени модуля $namelen = hexdec(substr($line, 0, 2)); $moduleName = substr($line, 2, $namelen); // получаем ID модуля $module_id = intval(@$modules[$moduleName]); if ($SIMULATION) { echo "Module name: {$moduleName}; module id: {$module_id}\n"; } $line = substr($line, 2 + $namelen); $cnt = 0; // прочитали имя модуля, можем работать с датчиками // сперва идут температурные, первый байт - их количество if ($tempPresent) { $cnt = hexdec(substr($line, 0, 2)); $line = substr($line, 2); $sensor_type_id = intval(@$sensor_types['TEMP']); // теперь читаем данные с датчиков for ($i = 0; $i < $cnt; $i++) { // первым байтом идёт индекс датчика $sensorIdx = hexdec(substr($line, 0, 2)); // затем два байта - его показания $val = substr($line, 2, 2); $fract = substr($line, 4, 2); $line = substr($line, 6); // теперь смотрим, есть ли показания с датчика $haveSensorData = !($val == "FF" && $fract == "FF"); $temp = $NO_TEMPERATURE_DATA; if ($haveSensorData) { // имеем показания, надо сконвертировать $temp = '' . hexdec($val) . "."; $fractVal = hexdec($fract); if ($fractVal < 10) { $temp .= "0"; } $temp .= '' . $fractVal; } // получили показания с датчика, надо их сохранить в БД $sql = "INSERT INTO controller_data(controller_id,sensor_type_id,module_id,sensor_index,sensor_data) VALUES({$controller_id},{$sensor_type_id},{$module_id},{$sensorIdx},{$temp});"; if ($SIMULATION) { echo "{$sql}\n"; } else { $dbengine->exec($sql); } } // for } // if($tempPresent) // опрос температурных датчиков окончен, переходим на датчики влажности if ($humidityPresent) { // переходим на чтение данных с датчиков влажности $cnt = hexdec(substr($line, 0, 2)); $line = substr($line, 2); $sensor_type_id = intval(@$sensor_types['HUMIDITY']); // обрабатываем их for ($i = 0; $i < $cnt; $i++) { // первым байтом идёт индекс датчика $sensorIdx = hexdec(substr($line, 0, 2)); // затем два байта - его показания $val = substr($line, 2, 2); $fract = substr($line, 4, 2); $line = substr($line, 6); // теперь смотрим, есть ли показания с датчика $haveSensorData = !($val == "FF" && $fract == "FF"); $humidity = $NO_TEMPERATURE_DATA; if ($haveSensorData) { // имеем показания, надо сконвертировать $humidity = '' . hexdec($val) . "."; $fractVal = hexdec($fract); if ($fractVal < 10) { $humidity .= "0"; } $humidity .= '' . $fractVal; } // получили показания с датчика, надо их сохранить в БД $sql = "INSERT INTO controller_data(controller_id,sensor_type_id,module_id,sensor_index,sensor_data) VALUES({$controller_id},{$sensor_type_id},{$module_id},{$sensorIdx},{$humidity});"; if ($SIMULATION) { echo "{$sql}\n"; } else { $dbengine->exec($sql); } } // for } // if($humidityPresent) if ($luminosityPresent) { // далее идут показания датчиков освещенности $cnt = hexdec(substr($line, 0, 2)); $line = substr($line, 2); $sensor_type_id = intval(@$sensor_types['LIGHT']); // обрабатываем их for ($i = 0; $i < $cnt; $i++) { // первым байтом идёт индекс датчика $sensorIdx = hexdec(substr($line, 0, 2)); // затем два байта - его показания $val = substr($line, 2, 2); $fract = substr($line, 4, 2); $line = substr($line, 6); // теперь смотрим, есть ли показания с датчика $haveSensorData = !($val == "FF" && $fract == "FF"); $luminosity = $NO_LUMINOSITY_DATA; if ($haveSensorData) { // имеем показания, надо сконвертировать $luminosity = hexdec($val . $fract); } // получили показания с датчика, надо их сохранить в БД $sql = "INSERT INTO controller_data(controller_id,sensor_type_id,module_id,sensor_index,sensor_data) VALUES({$controller_id},{$sensor_type_id},{$module_id},{$sensorIdx},{$luminosity});"; if ($SIMULATION) { echo "{$sql}\n"; } else { $dbengine->exec($sql); } } // for } // $luminosityPresent if ($waterFlowInstantPresent) { // далее идут показания датчиков мгновенного расхода воды $cnt = hexdec(substr($line, 0, 2)); $line = substr($line, 2); $sensor_type_id = intval(@$sensor_types['FLOW_INSTANT']); // обрабатываем их for ($i = 0; $i < $cnt; $i++) { // первым байтом идёт индекс датчика $sensorIdx = hexdec(substr($line, 0, 2)); // затем 4 байта - его показания $dt = substr($line, 2, 8); $line = substr($line, 10); $flow = hexdec($dt); // получили показания с датчика, надо их сохранить в БД $sql = "INSERT INTO controller_data(controller_id,sensor_type_id,module_id,sensor_index,sensor_data) VALUES({$controller_id},{$sensor_type_id},{$module_id},{$sensorIdx},{$flow});"; if ($SIMULATION) { echo "{$sql}\n"; } else { $dbengine->exec($sql); } } // for } // $waterFlowInstantPresent if ($waterFlowIncrementalPresent) { // далее идут показания датчиков накопительного расхода воды $cnt = hexdec(substr($line, 0, 2)); $line = substr($line, 2); $sensor_type_id = intval(@$sensor_types['FLOW_INCREMENTAL']); // обрабатываем их for ($i = 0; $i < $cnt; $i++) { // первым байтом идёт индекс датчика $sensorIdx = hexdec(substr($line, 0, 2)); // затем 4 байта - его показания $dt = substr($line, 2, 8); $line = substr($line, 10); $flow = hexdec($dt); // получили показания с датчика, надо их сохранить в БД $sql = "INSERT INTO controller_data(controller_id,sensor_type_id,module_id,sensor_index,sensor_data) VALUES({$controller_id},{$sensor_type_id},{$module_id},{$sensorIdx},{$flow});"; if ($SIMULATION) { echo "{$sql}\n"; } else { $dbengine->exec($sql); } } // for } // $waterFlowIncrementalPresent // разбираем показания с датчиков влажности почвы if ($soilMoisturePresent) { $cnt = hexdec(substr($line, 0, 2)); $line = substr($line, 2); $sensor_type_id = intval(@$sensor_types['SOIL']); // обрабатываем их for ($i = 0; $i < $cnt; $i++) { // первым байтом идёт индекс датчика $sensorIdx = hexdec(substr($line, 0, 2)); // затем два байта - его показания $val = substr($line, 2, 2); $fract = substr($line, 4, 2); $line = substr($line, 6); // теперь смотрим, есть ли показания с датчика $haveSensorData = !($val == "FF" && $fract == "FF"); $temp = $NO_TEMPERATURE_DATA; if ($haveSensorData) { // имеем показания, надо сконвертировать $temp = '' . hexdec($val) . "."; $fractVal = hexdec($fract); if ($fractVal < 10) { $temp .= "0"; } $temp .= '' . $fractVal; } // получили показания с датчика, надо их сохранить в БД $sql = "INSERT INTO controller_data(controller_id,sensor_type_id,module_id,sensor_index,sensor_data) VALUES({$controller_id},{$sensor_type_id},{$module_id},{$sensorIdx},{$temp});"; if ($SIMULATION) { echo "{$sql}\n"; } else { $dbengine->exec($sql); } } // for } // if($soilMoisturePresent) if ($phPresent) { // переходим на чтение данных с датчиков PH $cnt = hexdec(substr($line, 0, 2)); $line = substr($line, 2); $sensor_type_id = intval(@$sensor_types['PH']); // обрабатываем их for ($i = 0; $i < $cnt; $i++) { // первым байтом идёт индекс датчика $sensorIdx = hexdec(substr($line, 0, 2)); // затем два байта - его показания $val = substr($line, 2, 2); $fract = substr($line, 4, 2); $line = substr($line, 6); // теперь смотрим, есть ли показания с датчика // теперь смотрим, есть ли показания с датчика $haveSensorData = !($val == "FF" && $fract == "FF"); $phValue = $NO_PH_DATA; if ($haveSensorData) { // имеем показания, надо сконвертировать $phValue = '' . hexdec($val) . "."; $fractVal = hexdec($fract); if ($fractVal < 10) { $phValue .= "0"; } $phValue .= '' . $fractVal; } // получили показания с датчика, надо их сохранить в БД $sql = "INSERT INTO controller_data(controller_id,sensor_type_id,module_id,sensor_index,sensor_data) VALUES({$controller_id},{$sensor_type_id},{$module_id},{$sensorIdx},{$phValue});"; if ($SIMULATION) { echo "{$sql}\n"; } else { $dbengine->exec($sql); } } // for } // if($phPresent) // все датчики обработали, переходим к следующему модулю } // while if (!$SIMULATION) { $dbengine->commitTransaction(); } } // if ok answer $tp->close(); // закрываем соединение } else { // контроллер оффлайн if (!$SIMULATION) { $dbengine->beginTransaction(); $dbengine->exec("UPDATE controllers SET is_online=0 WHERE controller_id={$controller_id};"); $dbengine->commitTransaction(); } } }
<?php // эта строчка обязательна к подключению всеми скриптами require_once $_SERVER['DOCUMENT_ROOT'] . "/prerequisites.php"; // обрабатываем запрос CTSET и получаем данные с контроллера $query_result = "ER=OFFLINE"; if ($authorized) { $posted = intval(@$_GET['posted']); if ($posted == 1) { $controller_id = intval(@$_GET['controller_id']); $query = @$_GET['query']; if ($controller_id > 0) { $res = $dbengine->query("SELECT * FROM controllers WHERE controller_id={$controller_id};"); if ($array = $res->fetchArray()) { $online = $array['is_online']; if ($online) { $tp = new SocketTransport(); if ($tp->open($array['controller_address'])) { $query_result = $tp->ctset($query); $tp->close(); } } } } } // if } // создаём массив данных $json_data = array('authorized' => $authorized, 'query_result' => $query_result); // отсылаем его юзеру echo json_encode($json_data);
function smpp_send($smpp_hosts, $smpp_port, $smpp_login, $smpp_password, $smpp_from, $smpp_to, $smpp_msg) { $transport = new SocketTransport($smpp_hosts, $smpp_port); $transport->setRecvTimeout(60000); $smpp = new SmppClient($transport); $tags = "CSMS_16BIT_TAGS"; $data_coding = SMPP::DATA_CODING_ISO8859_5; // Cyrillic $smpp->debug = false; $transport->debug = false; $transport->open(); $smpp->bindTransmitter($smpp_login, $smpp_password); $message = $smpp_msg; $encodedMessage = $message; $from = new SmppAddress($smpp_from, SMPP::TON_ALPHANUMERIC); $to = new SmppAddress($smpp_to, SMPP::TON_INTERNATIONAL, SMPP::NPI_E164); if ($smpp_id = $smpp->sendSMS($from, $to, $encodedMessage, $tags, $data_coding)) { $smpp->close(); return trim($smpp_id); } else { $smpp->close(); return false; } }
public function smpp_check($smpp_id) { global $smpp_hosts, $smpp_port, $smpp_login, $smpp_password, $smpp_from; $transport = new SocketTransport($smpp_hosts, $smpp_port); $transport->setRecvTimeout(10000); $smpp = new SmppClient($transport); $smpp->debug = false; $transport->debug = false; $transport->open(); $smpp->bindTransmitter($smpp_login, $smpp_password); $source = new SmppAddress($smpp_from, SMPP::TON_ALPHANUMERIC); if (!($smpp_res = $smpp->queryStatus($smpp_id, $source))) { $smpp->close(); throw new Exception('SMPP check error'); } return $smpp_res; }