I have tried to read serial port data sending with arduino by php or nodejs and I couldn't. I think my codes are correct. I think the problem is permission access reading serial port limited by windows or browser but i'm not sure. although the software of arduino can read data.
when I run my codes, arduio sends data over and over but nothing to show data.
can you help me?!
Here my php codes:
<?php
//-- settings --//
//brainboxes serial ports
$portName = "COM5";
$baudRate = 9600;
$bits = 8;
$spotBit = 1;
header( 'Content-type: text/plain; charset=utf-8' );
?>
Serial Port Test
================
<?php
function echoFlush($string)
{
echo $string . "\n";
flush();
ob_flush();
}
if(!extension_loaded('dio'))
{
echoFlush( "PHP Direct IO does not appear to be installed for more info see: http://www.php.net/manual/en/book.dio.php" );
exit;
}
try
{
//the serial port resource
$bbSerialPort;
echoFlush( "Connecting to serial port: {$portName}" );
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
{
$bbSerialPort = dio_open($portName, O_RDWR );
//we're on windows configure com port from command line
exec("mode {$portName} baud={$baudRate} data={$bits} stop={$spotBit} parity=n xon=on");
}
else //'nix
{
$bbSerialPort = dio_open($portName, O_RDWR | O_NOCTTY | O_NONBLOCK );
dio_fcntl($bbSerialPort, F_SETFL, O_SYNC);
//we're on 'nix configure com from php direct io function
dio_tcsetattr($bbSerialPort, array(
'baud' => $baudRate,
'bits' => $bits,
'stop' => $spotBit,
'parity' => 0
));
}
if(!$bbSerialPort)
{
echoFlush( "Could not open Serial port {$portName} ");
exit;
}
// send data
$dataToSend = "HELLO WORLD!";
echoFlush( "Writing to serial port data: \"{$dataToSend}\"" );
$bytesSent = dio_write($bbSerialPort, $dataToSend );
echoFlush( "Sent: {$bytesSent} bytes" );
//date_default_timezone_set ("Europe/London");
$runForSeconds = new DateInterval("PT10S"); //10 seconds
$endTime = (new DateTime())->add($runForSeconds);
echoFlush( "Waiting for {$runForSeconds->format('%S')} seconds to recieve data on serial port" );
while (new DateTime() < $endTime) {
$data = dio_read($bbSerialPort, 256); //this is a blocking call
if ($data) {
echoFlush( "Data Recieved: ". $data );
}
}
echoFlush( "Closing Port" );
dio_close($bbSerialPort);
}
catch (Exception $e)
{
echoFlush( $e->getMessage() );
exit(1);
}
?>
Error in php:
"Warning: dio_open(): cannot open file COM5 with flags 2 and permissions 0: Permission denied in C:\xampp\htdocs\serialreading\SerialPortTest.php on line 42
Could not open Serial port COM5"
Here my nodejs codes:
var express = require('express'),
app = express(),
server = require('http').Server(app),
io = require('socket.io')(server),
port = 8888;
//Server start
server.listen(port, () => console.log('on port' + port))
//user server
app.use(express.static(__dirname + '/public'));
io.on('connection', onConnection);
var connectedSocket = null;
function onConnection(socket){
connectedSocket = socket;
}
//Arduino to CMD
const SerialPort = require('serialport');
const Readline = SerialPort.parsers.Readline;
const usbport = new SerialPort('COM5');
const parser = usbport.pipe(new Readline());
parser.on('data', function (data) {
io.emit('data', { data: data });
});
Error in nodejs:
"Could Not get"
Related
Q :
Please let i know why socket_sendto function occurred Unknown host error
env
centos 7.9
php-fpm 7.4 AND php-fpm 8.1
in docker container
/etc/hosts
<docker net ip> <docker container id>
127.0.0.1 nd.domain.com
execution
php -q SERVER.php
source
#!/usr/local/bin/php -q
<?php
// error_reporting(E_ALL);
// set_time_limit(0);
// ob_implicit_flush();
$address = '0.0.0.0';
$port = 80;
echo "server now start\r\n";
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP) or dir("create failed this socket");
if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}
socket_bind($socket, $address, $port) or dir("Failed to bind to (".$address.":".$port.")");
echo "server binded\r\n";
$messageBuffer = "";
$clients = [];
while (true){
if (#socket_recvfrom($socket, $messageBuffer, 2048, MSG_WAITALL, $ip, $port)) {
$address = "$ip:$port";
echo "Receive data : " . $messageBuffer . " FROM " . $address. "\r\n";
if (!isset($clients[$address]))
$clients[$address] = array();
$data = "hello-world";
$client_ip = gethostbyname($address);
echo "callback - send to " . $client_ip . "\r\n";
if (#socket_sendto($socket, $data, strlen($data), 0, $client_ip, $port)) {
echo "sendto ok";
} else {
echo socket_strerror(socket_last_error($socket))."\r\n";
};
} else {
echo socket_strerror(socket_last_error($socket))."\r\n";
};
// $clients[$address]->handlePacket($buffer);
}
socket_close($socket);
//socket_close
// namespace cgiServer;
// include_once './server_fn.php';
// include_once './socketManager.php';
// include_once './socketManagerSessionCtl.php';
// // 무한정 실행하기 위해 시간한계를 0으로 설정한다.
// set_time_limit(0);
// // 대기할 IP 주소와 포트번호를 설정한다
// $unit = new \cgiServer\server\manageUnit('192.168.35.29', 9000);
// //서버 실행
// $unit->serverOpen();
// exit;
?>
server log
with php-fpm 8.1 (display error on)
server now start
server binded
Receive data : hello world FROM 123.123.123.12:12345
callback - send to 123.123.123.12:12345
Warning: socket_sendto(): Host lookup failed [-10000]: Unknown error -10000 in [err-path] on line 47
Unknown error -10000
with php-fpm 7.4 (display error off)
Receive data : 0101010101! FROM 123.123.123.12:12345
callback - send to 123.123.123.12:12345
Unknown host
$client_ip and $address returns 123.123.123.123:12345
$ip returns 123.123.123.123
so i replace like that
#socket_sendto($socket, $data, strlen($data), 0, $client_ip, $port)
to
#socket_sendto($socket, $data, strlen($data), 0, $ip, $port)
I'm new to working with the serial port module to read data from devices and I'm trying to read data from an electronic balance through Nport W2150a device using php with the php_dio module, the code is outputing but the result is printing with unknow charset. What should I do to change that?
Output:
Code:
<?php
$portName = 'com1:1';
$baudRate = 9600;
$bits = 8;
$spotBit = 1;
header( 'Content-type: text/plain; charset=utf-8' );
?>
<?php
function echoFlush($string)
{
echo $string . "\n";
flush();
ob_flush();
}
if(!extension_loaded('dio'))
{
echoFlush( "PHP Direct IO does not appear to be installed for more info see: http://www.php.net/manual/en/book.dio.php" );
exit;
}
try
{
$bbSerialPort;
echoFlush( "Connecting to serial port: {$portName}" );
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
{
$bbSerialPort = dio_open($portName, O_RDWR );
//we're on windows configure com port from command line
exec("mode {$portName} baud={$baudRate} data={$bits} stop={$spotBit} parity=n xon=on");
}
else //'nix
{
$bbSerialPort = dio_open($portName, O_RDWR | O_NOCTTY | O_NONBLOCK );
dio_fcntl($bbSerialPort, F_SETFL, O_SYNC);
//we're on 'nix configure com from php direct io function
dio_tcsetattr($bbSerialPort, array(
'baud' => $baudRate,
'bits' => $bits,
'stop' => $spotBit,
'parity' => 0
));
}
if(!$bbSerialPort)
{
echoFlush( "Could not open Serial port {$portName} ");
exit;
}
// send data
$dataToSend = "HELLO WORLD!";
echoFlush( "Writing to serial port data: \"{$dataToSend}\"" );
$bytesSent = dio_write($bbSerialPort, $dataToSend );
echoFlush( "Sent: {$bytesSent} bytes" );
$runForSeconds = new DateInterval("PT10S");
$endTime = (new DateTime())->add($runForSeconds);
echoFlush( "Waiting for {$runForSeconds->format('%S')} seconds to recieve data on serial port" );
while (new DateTime() < $endTime) {
$data = dio_read($bbSerialPort, 256);
if ($data) {
echoFlush( "Data Recieved: ". $data );
}
}
echoFlush( "Closing Port" );
dio_close($bbSerialPort);
}
catch (Exception $e)
{
echoFlush( $e->getMessage() );
exit(1);
}
?>
I am trying to send data to my serial port using the php_dio.dll extention below code manage to send "HELLO WORLD" to serial com port 11 (com11) and returned the bytes, now i cannot close the serial port after it received my data.
On my com11 i have an arduino mega attached.
PHP code
$portName = '\\\\.\COM11';
$baudRate = 9600;
$bits = 8;
$spotBit = 1;
header( 'Content-type: text/plain; charset=utf-8' );
?>
Serial Port Test
================
<?php
function echoFlush($string)
{
echo $string . "\n";
flush();
ob_flush();
}
if(!extension_loaded('dio'))
{
echoFlush( "PHP Direct IO does not appear to be installed for more info see: http://www.php.net/manual/en/book.dio.php" );
exit;
}
try
{
//the serial port resource
$bbSerialPort;
echoFlush( "Connecting to serial port: {$portName}" );
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
{
$bbSerialPort = dio_open($portName, O_RDWR );
//we're on windows configure com port from command line
exec("mode {$portName} baud={$baudRate} data={$bits} stop={$spotBit} parity=n xon=on");
}
else //'nix
{
$bbSerialPort = dio_open($portName, O_RDWR | O_NOCTTY | O_NONBLOCK );
dio_fcntl($bbSerialPort, F_SETFL, O_SYNC);
//we're on 'nix configure com from php direct io function
dio_tcsetattr($bbSerialPort, array(
'baud' => $baudRate,
'bits' => $bits,
'stop' => $spotBit,
'parity' => 0
));
}
if(!$bbSerialPort)
{
echoFlush( "Could not open Serial port {$portName} ");
exit;
}
// send data
$dataToSend = "HELLO WORLD!";
echoFlush( "Writing to serial port data: \"{$dataToSend}\"" );
$bytesSent = dio_write($bbSerialPort, $dataToSend );
echoFlush( "Sent: {$bytesSent} bytes" );
//date_default_timezone_set ("Europe/London");
$runForSeconds = new DateInterval("PT10S"); //10 seconds
$endTime = (new DateTime())->add($runForSeconds);
echoFlush( "Waiting for {$runForSeconds->format('%S')} seconds to recieve data on serial port" );
while (new DateTime() < $endTime) {
$data = dio_read($bbSerialPort, 256); //this is a blocking call
if ($data) {
echoFlush( "Data Recieved: ". $data );
}
}
echoFlush( "Closing Port" );
dio_close($bbSerialPort);
}
catch (Exception $e)
{
echoFlush( $e->getMessage() );
exit(1);
}
Arduino Code
char incomingByte;
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
// say what you got:
Serial.print("I received: ");
Serial.println(incomingByte);
}
}
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();
?>
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');
}