PHP Serial Port Access - php

I am trying to implement this code below, I have a wavecom gsm modem connected to COM6 http://imgur.com/QwkwfMc it works on 3rd party sms gateway software but it is very expensive.
I am getting these errors
Fatal error: Uncaught exception 'Exception' with message 'Unable to setup COM port, check it is correct' in C:\wamp\www\sms\index.php on line 53
( ! ) Exception: Unable to setup COM port, check it is correct in C:\wamp\www\sms\index.php on line 53
What do i need to do to make this work?
<?php
//SMS via GSM Modem - A PHP class to send SMS messages via a GSM modem attached to the computers serial port.
//Windows only (tested on XP with PHP 5.2.6)
//Tested with the EZ863 (Telit GE863) GSM modem
//Requires that PHP has permission to access "COM" system device, and system "mode" command
error_reporting(E_ALL);
//Example
$gsm_send_sms = new gsm_send_sms();
$gsm_send_sms->debug = false;
$gsm_send_sms->port = 'COM6';
$gsm_send_sms->baud = 9600;
$gsm_send_sms->init();
$status = $gsm_send_sms->send('+642102844012', 'testing 123');
if ($status) {
echo "Message sent\n";
} else {
echo "Message not sent\n";
}
$gsm_send_sms->close();
//Send SMS via serial SMS modem
class gsm_send_sms {
public $port = 'COM6';
public $baud = 9600;
public $debug = false;
private $fp;
private $buffer;
//Setup COM port
public function init() {
$this->debugmsg("Setting up port: \"{$this->port} # \"{$this->baud}\" baud");
exec("MODE {$this->port}: BAUD={$this->baud} PARITY=N DATA=8 STOP=1", $output, $retval);
if ($retval != 0) {
throw new Exception('Unable to setup COM port, check it is correct');
}
$this->debugmsg(implode("\n", $output));
$this->debugmsg("Opening port");
//Open COM port
$this->fp = fopen($this->port . ':', 'r+');
//Check port opened
if (!$this->fp) {
throw new Exception("Unable to open port \"{$this->port}\"");
}
$this->debugmsg("Port opened");
$this->debugmsg("Checking for responce from modem");
//Check modem connected
fputs($this->fp, "AT\r");
//Wait for ok
$status = $this->wait_reply("OK\r\n", 5);
if (!$status) {
throw new Exception('Did not receive responce from modem');
}
$this->debugmsg('Modem connected');
//Set modem to SMS text mode
$this->debugmsg('Setting text mode');
fputs($this->fp, "AT+CMGF=1\r");
$status = $this->wait_reply("OK\r\n", 5);
if (!$status) {
throw new Exception('Unable to set text mode');
}
$this->debugmsg('Text mode set');
}
//Wait for reply from modem
private function wait_reply($expected_result, $timeout) {
$this->debugmsg("Waiting {$timeout} seconds for expected result");
//Clear buffer
$this->buffer = '';
//Set timeout
$timeoutat = time() + $timeout;
//Loop until timeout reached (or expected result found)
do {
$this->debugmsg('Now: ' . time() . ", Timeout at: {$timeoutat}");
$buffer = fread($this->fp, 1024);
$this->buffer .= $buffer;
usleep(200000);//0.2 sec
$this->debugmsg("Received: {$buffer}");
//Check if received expected responce
if (preg_match('/'.preg_quote($expected_result, '/').'$/', $this->buffer)) {
$this->debugmsg('Found match');
return true;
//break;
} else if (preg_match('/\+CMS ERROR\:\ \d{1,3}\r\n$/', $this->buffer)) {
return false;
}
} while ($timeoutat > time());
$this->debugmsg('Timed out');
return false;
}
//Print debug messages
private function debugmsg($message) {
if ($this->debug == true) {
$message = preg_replace("%[^\040-\176\n\t]%", '', $message);
echo $message . "\n";
}
}
//Close port
public function close() {
$this->debugmsg('Closing port');
fclose($this->fp);
}
//Send message
public function send($tel, $message) {
//Filter tel
$tel = preg_replace("%[^0-9\+]%", '', $tel);
//Filter message text
$message = preg_replace("%[^\040-\176\r\n\t]%", '', $message);
$this->debugmsg("Sending message \"{$message}\" to \"{$tel}\"");
//Start sending of message
fputs($this->fp, "AT+CMGS=\"{$tel}\"\r");
//Wait for confirmation
$status = $this->wait_reply("\r\n> ", 5);
if (!$status) {
//throw new Exception('Did not receive confirmation from modem');
$this->debugmsg('Did not receive confirmation from modem');
return false;
}
//Send message text
fputs($this->fp, $message);
//Send message finished indicator
fputs($this->fp, chr(26));
//Wait for confirmation
$status = $this->wait_reply("OK\r\n", 180);
if (!$status) {
//throw new Exception('Did not receive confirmation of messgage sent');
$this->debugmsg('Did not receive confirmation of messgage sent');
return false;
}
$this->debugmsg("Message sent");
return true;
}
}
?>

Try this below code hope it helps,
Note : uses php_serial.class.php
Code :
<?php
require("php_serial.class.php");
$serial = new phpSerial;
// First we must specify the device. This works on both linux and windows (if
// your linux serial device is /dev/ttyS0 for COM1, etc)
$serial->deviceSet("/dev/ttyS0");
// We can change the baud rate, parity, length, stop bits, flow control
$serial->confBaudRate(9600);
$serial->confParity("none");
$serial->confCharacterLength(8);
$serial->confStopBits(1);
$serial->confFlowControl("none");
// Then we need to open it
$serial->deviceOpen();
// To write into
$serial->sendMessage("AT+CMGF=1\n\r");
$serial->sendMessage("AT+cmgs=\"+912709345x23\"\n\r");
$serial->sendMessage("Hi, This is the sms that I sent to you using PHP script with serial Port communication with my phone as serial device!! GN - VKSALIAN \n\r");
$serial->sendMessage(chr(26));
//wait for modem to send message
sleep(7);
// Or to read from
$read = $serial->readPort();
echo $read;
// If you want to change the configuration, the device must be closed
$serial->deviceClose();
?>

Related

Uncaught Exception: "Did not receive response from modem sending SMS using GSM Modem"

I am using GPRS MODEM to send SMS using php with this device.
I tried my device using AT Tester to determine if my device works well and it successfully sent.
Then I tried this link which uses PHP to send SMS via GPRS Modem: https://www.sitepoint.com/community/t/send-sms-using-gsm-modem/28584 .
Here is the code that was provided :
<?php
//Example
error_reporting(E_ALL);
//Example
$gsm_send_sms = new gsm_send_sms();
$gsm_send_sms->debug = true;
$gsm_send_sms->port = 'COM4';
$gsm_send_sms->baud = 9600;
$gsm_send_sms->init();
$status = $gsm_send_sms->send('+639153380630', 'testing 123');
if ($status) {
echo "Message sent\
";
} else {
echo "Message not sent\
";
}
$gsm_send_sms->close();
//Send SMS via serial SMS modem
class gsm_send_sms {
public $port = 'COM4';
public $baud = 9600;
public $debug = true;
private $fp;
private $buffer;
//Setup COM port
public function init() {
$this->debugmsg("Setting up port: \"{$this->port} # \"{$this->baud}\" baud");
exec("MODE {$this->port}: BAUD={$this->baud} PARITY=N DATA=8 STOP=1", $output, $retval);
if ($retval != 0) {
throw new Exception('Unable to setup COM port, check it is correct');
}
$this->debugmsg(implode("\n", $output));
$this->debugmsg("Opening port");
//Open COM port
$this->fp = fopen($this->port . ':', 'r+');
//Check port opened
if (!$this->fp) {
throw new Exception("Unable to open port \"{$this->port}\"");
}
$this->debugmsg("Port opened");
$this->debugmsg("Checking for responce from modem");
//Check modem connected
fputs($this->fp, "AT\r");
//Wait for ok
$status = $this->wait_reply("OK\r\n", 5);
if (!$status) {
throw new Exception('Did not receive responce from modem');
}
$this->debugmsg('Modem connected');
//Set modem to SMS text mode
$this->debugmsg('Setting text mode');
fputs($this->fp, "AT+CMGF=1\r");
$status = $this->wait_reply("OK\r\n", 5);
if (!$status) {
throw new Exception('Unable to set text mode');
}
$this->debugmsg('Text mode set');
}
//Wait for reply from modem
private function wait_reply($expected_result, $timeout) {
$this->debugmsg("Waiting {$timeout} seconds for expected result");
//Clear buffer
$this->buffer = '';
//Set timeout
$timeoutat = time() + $timeout;
//Loop until timeout reached (or expected result found)
do {
$this->debugmsg('Now: ' . time() . ", Timeout at: {$timeoutat}");
$buffer = fread($this->fp, 1024);
$this->buffer .= $buffer;
usleep(200000);//0.2 sec
$this->debugmsg("Received: {$buffer}");
//Check if received expected responce
if (preg_match('/'.preg_quote($expected_result, '/').'$/', $this->buffer)) {
$this->debugmsg('Found match');
return true;
//break;
} else if (preg_match('/\+CMS ERROR\:\ \d{1,3}\r\n$/', $this->buffer)) {
return false;
}
} while ($timeoutat > time());
$this->debugmsg('Timed out');
return false;
}
//Print debug messages
private function debugmsg($message) {
if ($this->debug == true) {
$message = preg_replace("%[^\040-\176\n\t]%", '', $message);
echo $message . "\n";
}
}
//Close port
public function close() {
$this->debugmsg('Closing port');
fclose($this->fp);
}
//Send message
public function send($tel, $message) {
//Filter tel
$tel = preg_replace("%[^0-9\+]%", '', $tel);
//Filter message text
$message = preg_replace("%[^\040-\176\r\n\t]%", '', $message);
$this->debugmsg("Sending message \"{$message}\" to \"{$tel}\"");
//Start sending of message
fputs($this->fp, "AT+CMGS=\"{$tel}\"\r");
//Wait for confirmation
$status = $this->wait_reply("\r\n> ", 5);
if (!$status) {
//throw new Exception('Did not receive confirmation from modem');
$this->debugmsg('Did not receive confirmation from modem');
return false;
}
//Send message text
fputs($this->fp, $message);
//Send message finished indicator
fputs($this->fp, chr(26));
//Wait for confirmation
$status = $this->wait_reply("OK\r\n", 180);
if (!$status) {
//throw new Exception('Did not receive confirmation of messgage sent');
$this->debugmsg('Did not receive confirmation of messgage sent');
return false;
}
$this->debugmsg("Message sent");
return true;
}
}
?>
After executing the code, PHP returns with this error :
Setting up port: "COM4 # "9600" baud
Status for device COM4: -----------------------
Baud: 9600 Parity: None Data Bits: 8 Stop Bits: 1
Timeout: OFF XON/XOFF: OFF
CTS handshaking: OFF
DSR handshaking: OFF
DSR sensitivity: OFF
DTR circuit: ON
RTS circuit: ON
Opening port
Port opened
Checking for responce from modem
Waiting 5 seconds for expected result
Now: 1580560507, Timeout at: 1580560512
Received:
Now: 1580560508, Timeout at: 1580560512
Received:
Now: 1580560508, Timeout at: 1580560512
Received:
Now: 1580560508, Timeout at: 1580560512
Received:
Now: 1580560508, Timeout at: 1580560512
Received:
Now: 1580560508, Timeout at: 1580560512
Received:
Now: 1580560509, Timeout at: 1580560512
Received:
Now: 1580560509, Timeout at: 1580560512
Received:
Now: 1580560509, Timeout at: 1580560512
Received:
Now: 1580560509, Timeout at: 1580560512
Received:
Now: 1580560509, Timeout at: 1580560512
Received:
Now: 1580560510, Timeout at: 1580560512
Received:
Now: 1580560510, Timeout at: 1580560512
Received:
Now: 1580560510, Timeout at: 1580560512
Received:
Now: 1580560510, Timeout at: 1580560512
Received:
Now: 1580560510, Timeout at: 1580560512
Received:
Now: 1580560511, Timeout at: 1580560512
Received:
Now: 1580560511, Timeout at: 1580560512
Received:
Now: 1580560511, Timeout at: 1580560512
Received:
Now: 1580560511, Timeout at: 1580560512
Received:
Now: 1580560511, Timeout at: 1580560512
Received:
**Timed out**
**Fatal error: Uncaught Exception: Did not receive responce from modem in C:\xampp\htdocs\sms_test\text1.php:77 **
Stack trace:
#0 C:\xampp\htdocs\sms_test\text1.php(13): gsm_send_sms->init()
#1 {main} thrown in C:\xampp\htdocs\sms_test\text1.php on line 77
The root cause of your exception, that is a custom generated one, is not in the AT commands sequence you use in the attempt to send an SMS. I can confirm that it is correct, and it is also confirmed by your tests with AT tester:
/* Set SMS text mode */
AT+CMGF=1\r
OK
/* Send SMS */
AT+CMGS="---destination Number---"\r
> SMS Contents
CTRL+Z
+CGMS: <N>
OK
Just one preliminary step is missing: the one in which you set Service Center address through AT+CSCA command, but since you are able to send message with your AT tester I assume it is already set.
Let's analyze your log. The exception occurs because no response has been received after the very first command you send: AT. You wait up to 5 seconds for its response, that usually comes immediately (< 100ms). Since you don't receive it, it clearly means that there are some communication problems.
Let's review your communication parameters, directly from the attached debug log:
Setting up port: "COM4 # "9600" baud
Status for device COM4: -----------------------
Baud: 9600 Parity: None Data Bits: 8 Stop Bits: 1
Timeout: OFF
XON/XOFF: OFF
CTS handshaking: OFF
DSR handshaking: OFF
DSR sensitivity: OFF
DTR circuit: ON
RTS circuit: ON
I can suggest the following check list:
Is your device correctly powered on?
Make sure you are using the correct COM port
Make sure to disconnect the AT tester and any other COM terminal before launching your PHP script
Check your baudrate. Usually default baudrate for cellular modems is 115200 (if autobauding is not enabled), so I would start trying this change.
'8n1' (data bits-parity-stop bits) is usually the default setting, so it is probably correct. We can say the same for all other settings. Before changing them, as a last resort, check the modem's current settings through your AT tester by issuing AT+IPR? (to query current baudrate), AT+ICF? (to query character framing format, e.g. 8n1) and AT&V (to query current profile status, including flow control settings).

Send sms through d-link GSM modem in PHP

I am trying to send sms via D-Link GSM modem. I am new on this. My code shows Unable to setup COM port I did not add any additional file, library or any modification in php.ini file in xampp. just installed software provided by modem. My operating system is windows 10. I am mentioning my code, though I got it from internet.
$mobile_number=$_POST['mobile_number'];
$messages=$_POST['messages'];
$gsm_send_sms = new gsm_send_sms();
$gsm_send_sms->debug = false;
$gsm_send_sms->port = 'COM3';
$gsm_send_sms->baud = 115200;
$gsm_send_sms->init();
$status = $gsm_send_sms->send($mobile_number,$messages);
if ($status) {
echo "<body bgcolor='lightgreen'>";
echo "<br><br><br>";
echo "<h3 align='center'>Message Successfully Send... </h3>\n";
echo "</body>";
} else {
echo "<body bgcolor='lightgreen'>";
echo "<br><br><br>";
echo "<h3 align='center'>Message not sent Successfully... </h3>\n";
echo "</body>";
}
$gsm_send_sms->close();
//Send SMS via serial SMS modem
class gsm_send_sms {
public $port = 'COM3';
public $baud = 115200;
public $debug = false;
private $fp;
private $buffer;
//Setup COM port
public function init() {
$this->debugmsg("Setting up port: \"{$this->port} # \"{$this->baud}\" baud");
exec("MODE {$this->port}: BAUD={$this->baud} PARITY=N DATA=8 STOP=1", $output, $retval);
if ($retval != 0) {
throw new Exception('Unable to setup COM port, check it is correct');
}
$this->debugmsg(implode("\n", $output));
$this->debugmsg("Opening port");
//Open COM port
$this->fp = fopen($this->port . ':', 'r+');
//Check port opened
if (!$this->fp) {
throw new Exception("Unable to open port \"{$this->port}\"");
}
$this->debugmsg("Port opened");
$this->debugmsg("Checking for response from modem");
//Check modem connected
fputs($this->fp, "AT\r");
//Wait for ok
$status = $this->wait_reply("OK\r\n", 5);
if (!$status) {
throw new Exception('Did not receive responce from modem');
}
$this->debugmsg('Modem connected');
//Set modem to SMS text mode
$this->debugmsg('Setting text mode');
fputs($this->fp, "AT+CMGF=1\r");
$status = $this->wait_reply("OK\r\n", 5);
if (!$status) {
throw new Exception('Unable to set text mode');
}
$this->debugmsg('Text mode set');
}
//Wait for reply from modem
private function wait_reply($expected_result, $timeout) {
$this->debugmsg("Waiting {$timeout} seconds for expected result");
//Clear buffer
$this->buffer = '';
//Set timeout
$timeoutat = time() + $timeout;
//Loop until timeout reached (or expected result found)
do {
$this->debugmsg('Now: ' . time() . ", Timeout at: {$timeoutat}");
$buffer = fread($this->fp, 1024);
$this->buffer .= $buffer;
usleep(200000);//0.2 sec
$this->debugmsg("Received: {$buffer}");
//Check if received expected responce
if (preg_match('/'.preg_quote($expected_result, '/').'$/', $this->buffer)) {
$this->debugmsg('Found match');
return true;
//break;
} else if (preg_match('/\+CMS ERROR\:\ \d{1,3}\r\n$/', $this->buffer)) {
return false;
}
} while ($timeoutat > time());
$this->debugmsg('Timed out');
return false;
}
//Print debug messages
private function debugmsg($message) {
if ($this->debug == true) {
$message = preg_replace("%[^\040-\176\n\t]%", '', $message);
echo $message . "\n";
}
}
//Close port
public function close() {
$this->debugmsg('Closing port');
fclose($this->fp);
}
//Send message
public function send($tel, $message) {
//Filter tel
$tel = preg_replace("%[^0-9\+]%", '', $tel);
//Filter message text
$message = preg_replace("%[^\040-\176\r\n\t]%", '', $message);
$this->debugmsg("Sending message \"{$message}\" to \"{$tel}\"");
//Start sending of message
fputs($this->fp, "AT+CMGS=\"{$tel}\"\r");
//Wait for confirmation
$status = $this->wait_reply("\r\n> ", 5);
if (!$status) {
//throw new Exception('Did not receive confirmation from modem');
$this->debugmsg('Did not receive confirmation from modem');
return false;
}
//Send message text
fputs($this->fp, $message);
//Send message finished indicator
fputs($this->fp, chr(26));
//Wait for confirmation
$status = $this->wait_reply("OK\r\n", 180);
if (!$status) {
//throw new Exception('Did not receive confirmation of message sent');
$this->debugmsg('Did not receive confirmation of message sent');
return false;
}
$this->debugmsg("Message Send Successfully...");
return true;
}
}
It's Look like You are using a D-Link USB GSM Modem.
in this case Modem COM port doesn't show in Device Manager Automatically.
First you must start D-Link Connection Manager SoftWare and then you can find your modem under MODEM category in Device Manager.
R-Click on it and Open Properties window.
You can find COM port on it!

Unable to setup COM port, check it is correct

I am sending sms using Nokia usb Device and PHP script but getting error
many answer are there on stack but no answer has solution of this problem
Fatal error: Uncaught Exception: Unable to setup COM port, check it is correct in C:\xampp\htdocs\sms-prac\send-sms.php:103
Stack trace:
#0 C:\xampp\htdocs\sms-prac\send-sms.php(36): gsm_send_sms->init()
#1 {main}
thrown in C:\xampp\htdocs\sms-prac\send-sms.php on line 103
My gsm_send_sms Class Code
//Send SMS via serial SMS modem
class gsm_send_sms {
public $port = 'COM1';
public $baud = 115200;
public $debug = false;
private $fp;
private $buffer;
//Setup COM port
public function init() {
$this->debugmsg("Setting up port: \"{$this->port} # \"{$this->baud}\" baud");
exec("MODE {$this->port}: BAUD={$this->baud} PARITY=N DATA=8 STOP=1", $output, $retval);
if ($retval != 0) {
throw new Exception('Unable to setup COM port, check it is correct');
}
$this->debugmsg(implode("\n", $output));
$this->debugmsg("Opening port");
//Open COM port
$this->fp = fopen($this->port . ':', 'r+');
//Check port opened
if (!$this->fp) {
throw new Exception("Unable to open port \"{$this->port}\"");
}
$this->debugmsg("Port opened");
$this->debugmsg("Checking for responce from modem");
//Check modem connected
fputs($this->fp, "AT\r");
//Wait for ok
$status = $this->wait_reply("OK\r\n", 5);
if (!$status) {
throw new Exception('Did not receive responce from modem');
}
$this->debugmsg('Modem connected');
//Set modem to SMS text mode
$this->debugmsg('Setting text mode');
fputs($this->fp, "AT+CMGF=1\r");
$status = $this->wait_reply("OK\r\n", 5);
if (!$status) {
throw new Exception('Unable to set text mode');
}
$this->debugmsg('Text mode set');
}
//Wait for reply from modem
private function wait_reply($expected_result, $timeout) {
$this->debugmsg("Waiting {$timeout} seconds for expected result");
//Clear buffer
$this->buffer = '';
//Set timeout
$timeoutat = time() + $timeout;
//Loop until timeout reached (or expected result found)
do {
$this->debugmsg('Now: ' . time() . ", Timeout at: {$timeoutat}");
$buffer = fread($this->fp, 1024);
$this->buffer .= $buffer;
usleep(200000);//0.2 sec
$this->debugmsg("Received: {$buffer}");
//Check if received expected responce
if (preg_match('/'.preg_quote($expected_result, '/').'$/', $this->buffer)) {
$this->debugmsg('Found match');
return true;
//break;
} else if (preg_match('/\+CMS ERROR\:\ \d{1,3}\r\n$/', $this->buffer)) {
return false;
}
} while ($timeoutat > time());
$this->debugmsg('Timed out');
return false;
}
//Print debug messages
private function debugmsg($message) {
if ($this->debug == true) {
$message = preg_replace("%[^\040-\176\n\t]%", '', $message);
echo $message . "\n";
}
}
//Close port
public function close() {
$this->debugmsg('Closing port');
fclose($this->fp);
}
//Send message
public function send($tel, $message) {
//Filter tel
$tel = preg_replace("%[^0-9\+]%", '', $tel);
//Filter message text
$message = preg_replace("%[^\040-\176\r\n\t]%", '', $message);
$this->debugmsg("Sending message \"{$message}\" to \"{$tel}\"");
//Start sending of message
fputs($this->fp, "AT+CMGS=\"{$tel}\"\r");
//Wait for confirmation
$status = $this->wait_reply("\r\n> ", 5);
if (!$status) {
//throw new Exception('Did not receive confirmation from modem');
$this->debugmsg('Did not receive confirmation from modem');
return false;
}
//Send message text
fputs($this->fp, $message);
//Send message finished indicator
fputs($this->fp, chr(26));
//Wait for confirmation
$status = $this->wait_reply("OK\r\n", 180);
if (!$status) {
//throw new Exception('Did not receive confirmation of messgage sent');
$this->debugmsg('Did not receive confirmation of messgage sent');
return false;
}
$this->debugmsg("Message sent");
return true;
}
}
My PHP Code which i am using to send SMS
<?php
//SMS via GSM Modem - A PHP class to send SMS messages via a GSM modem attached to the computers serial port.
//Windows only (tested on XP with PHP 5.2.6)
//Tested with the EZ863 (Telit GE863) GSM modem
//Requires that PHP has permission to access "COM" system device, and system "mode" command
ini_set('max_execution_time', 300);
error_reporting(E_ALL);
//Example
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "MembersManagmentSystem";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Member.memberId, Member.memberContactMobileNumber, SMSRecipient.smsRecipientReceiverId, SMSRecipient.smsInfoId, SMSInfo.smsInfoText, SMSInfo.`smsInfoSaveDateTime` FROM Member, SMSRecipient,SMSInfo WHERE SMSRecipient.`smsRecipientReceiverId` = Member.`memberId` AND SMSRecipient.`smsInfoId`= SMSInfo.`smsInfoId` AND SMSRecipient.smsRecipientSentDateTime IS NULL AND Member.`memberContactMobileNumber` IS NOT NULL AND SMSInfo.`smsInfoSaveDateTime` > DATE_SUB(NOW(), INTERVAL 1 DAY)";
$result = $conn->query($sql);
echo "<pre>";
$gsm_send_sms = new gsm_send_sms();
$gsm_send_sms->debug = false;
$gsm_send_sms->port = 'COM3';
$gsm_send_sms->baud = 115200;
$gsm_send_sms->init();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
print_r($row);
$status = $gsm_send_sms->send($row['memberContactMobileNumber'], $row['smsInfoText']);
if ($status) {
$sql = "UPDATE SMSRecipient SET smsRecipientSentDateTime = now() WHERE smsInfoId = ".$row['smsInfoId']." and smsRecipientReceiverId = ".$row['memberId'];
if ($conn->query($sql) === TRUE) {
echo "Message sent\n";
}
} else {
echo "Message not sent\n";
}
}
//exit();
} else {
echo "0 results";
}
$gsm_send_sms->close();
$conn->close();
?>
on change $gsm_send_sms->debug = false; to true, get
Array
(
[0] =>
[1] => Status for device COM3:
[2] => -----------------------
[3] => Baud: 115200
[4] => Parity: None
[5] => Data Bits: 8
[6] => Stop Bits: 1
[7] => Timeout: OFF
[8] => XON/XOFF: OFF
[9] => CTS handshaking: OFF
[10] => DSR handshaking: OFF
[11] => DSR sensitivity: OFF
[12] => DTR circuit: ON
[13] => RTS circuit: ON
[14] =>
)
After Debug above Code I found that when i first time connect my device and run it php executing this line as like as infinity loop and before this line all debugmsg and other code running fine please help me
$buffer = fread($this->fp, 8192);

Can't monitor STDOUT of a C program in parallel with web sockets, by using stream select in PHP

I m writing a websocket based client server in PHP.Server is listeninig for clients which get connected from a browser, when client write something its echoed
back to the client. Client input and new connection from the client are monitored by using stream select.
In my previous work I used stream select to get output of the C program and display it on the browser now I want that when a client
send some message I execute a C program using proc open. C program outputs "hello" message in a loop after certain time, I want that when ever there
is output on the C program I send it to the client browser.
Client browser successful gets connected, when client sends data the server echo it back, the C program gets executed on server but I cant monitor its STDOUT by using same stream select that is monitoring my sockets.
I am not able to monitor my child process STDOUT using stream select. By using select How can I monitor the new process STDOUT that I started using proc open
,It looks that some how I lost the STDOUT descriptor that is usually accessible after starting the C program by using proc open.
hello.c
#include<stdio.h>
#include<stdint.h>
void main(void)
{
uint8_t i = 0;
uint8_t count = 10;
for(i = 0; i < count; i++)
{
printf("hello world\n");
sleep(1);
}
}
server.php
execute_prog('unbuffer /var/www/html/test/./hello3');//unbuffer stdout
function execute_prog($exe)
{
echo "[+execute_prog]";
$host = 'localhost'; //host
$port = '9000'; //port
$null = NULL; //null var
$read_socks;
$new_client;
$server = stream_socket_server("tcp://0.0.0.0:9000", $errno, $errorMessage);
if ($server === false)
{
throw new UnexpectedValueException("Could not bind to socket: $errorMessage");
}
set_time_limit(1800);
$exe_command = escapeshellcmd($exe);
$descriptorspec = array(
0 => array("pipe", "r"), // stdin -> for execution
1 => array("pipe", "w"), // stdout -> for execution
2 => array("pipe", "w") // stderr
);
{
$client_socks = array();
$read_socks = array($server);
$changed = array();
$stdout = NULL;
while(1)
{
//prepare readable sockets
$write = NULL;
$err = NULL;
$except = NULL;
$changed = $read_socks;//by refrence
if (false === ($num_changed_streams = stream_select($changed, $write, $except, 0)))
{
/* Error handling */
echo "Errors\n";
}
else if ($num_changed_streams > 0)
{
/* At least on one of the streams something interesting happened */
echo "Data on ".$num_changed_streams." descriptor\n";
if(in_array($stdout[0], $changed))
{
echo "Data on child process STDOUT\n";
$s = fgets($stdout[0]);
if( $s === false )
{
// Hello program has finished.
echo 'Finished', PHP_EOL;
$s = NULL;
ob_flush();
flush();
// Close all descriptors and return...
// break;
}
else
{
echo $s."</br>";
//fwrite($new_client,$s,strlen($s));//commented temporarily
$s = NULL;
ob_flush();
flush();
}
}
else if(in_array($server, $changed))
{
//new client
echo "New Connection\n";
$new_client = stream_socket_accept($server);
if ($new_client)
{
//print remote client information, ip and port number
echo 'Connection accepted from ' . stream_socket_get_name($new_client, true) . "n";
$read_socks[] = $new_client;
echo "Now there are total ". count($read_socks) . " clients.n";
}
$header = fread($new_client, 1024);//read data sent by the socket
perform_handshaking($header, $new_client, $host, $port); //perform websocket handshake
$ip = stream_socket_get_name($new_client, true);
$response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' connected'))); //prepare json data
fwrite($new_client,$response,strlen($response));
//delete the server socket from the read sockets
unset($changed[ array_search($server, $changed) ]);
}
else if($write)
{
echo "Data on child process STDIN\n";
}
else if($err)
{
echo "Data on child process STDERR\n";
}
else
{
echo "Message from the client \n";
//message from existing client
foreach($changed as $sock)
{
$data = fread($sock, 128);
//echo "Data read:".$data." From sock:".$sock."\n";
if(!$data)
{
unset($client_socks[ array_search($sock, $client_socks) ]);
#fclose($sock);
echo "A client disconnected. Now there are total ". count($client_socks) . " clients.n";
continue;
}
else
{
$received_text = unmask($data); //unmask data
$tst_msg = json_decode($received_text); //json decode
$user_name = $tst_msg->name; //sender name
$user_message = $tst_msg->message; //message text
$user_color = $tst_msg->color; //color
// echo "name:".$user_name." user mesg:".$user_message."\n";
//prepare data to be sent to client
$response_text = mask(json_encode(array('type'=>'usermsg', 'name'=>$user_name, 'message'=>$user_message, 'color'=>$user_color)));
fwrite($sock, $response_text, strlen($response_text));
//..................................................................................................................
echo "Executing a process\n";
$process = proc_open($exe_command, $descriptorspec, $pipes);//creating child process
if (is_resource($process))
{
echo "Process Created";
}
$read_sock[] = $pipes[1];//add a descriptor
$stdout = array($pipes[1]);//save stdout in a variable defined above
print_r ($stdout);
}
}
}
$num_changed_streams = 0;
}
}
// close the listening socket
fclose($server);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
echo "exitcode: ".proc_close($process)."\n";
}
echo "[-execute_prog]";
// return $ret;
}
Output Of server.php
[+execute_prog]Data on 1 descriptor
New Connection
Connection accepted from 127.0.0.1:49875nNow there are total 2 clients.nData on 1 descriptor
Message from the client
Executing a process
Process Created Array
(
[0] => Resource id #12
)
As can be seen from output that it never show message "Data on child process STDOUT" even the C program was created
Other utility functions unmask, mask etc can be provided if required.
Thankyou
i was saving the stdout in read_sock instead of read_socks array, now its resolved

Send SMS using GSM modem in PHP

I would like to send SMS from my GSM modem. I tried to implement this using this link as reference. But my modem will not produce any response.Any help..Thanks in advance....
Here is my code snippet..
$gsm_send_sms = new gsm_send_sms();
$gsm_send_sms->init();
$status = $gsm_send_sms->my_send_message_function("+09524566775", "raja");
$gsm_send_sms->close();
//Send SMS via serial SMS modem
class gsm_send_sms {
public $port = 'COM7';
public $baud = "9600";
public $debug = true;
private $fp;
private $buffer;
//Setup COM port
public function init() {
$this->debugmsg("Setting up port: \"{$this->port} # \"{$this->baud}\" baud");
exec("MODE {$this->port}: BAUD={$this->baud} PARITY=N DATA=8 STOP=1", $output, $retval);
if ($retval != 0) {
throw new Exception('Unable to setup COM port, check it is correct');
}
$this->debugmsg(implode("\n", $output));
$this->debugmsg("Opening port");
//Open COM port
$this->fp = fopen($this->port . ':', 'r+');
//Check port opened
if (!$this->fp) {
throw new Exception("Unable to open port \"{$this->port}\"");
}
$this->debugmsg("Port opened");
$this->debugmsg("Checking for responce from modem");
//Check modem connected
fputs($this->fp, "AT\r");
//Wait for ok
$status = $this->wait_reply("OK\r\n", 5);
if (!$status) {
throw new Exception('Did not receive responce from modem');
}

Categories