由于我无法通过引用Linux服务器和Windows服务器来访问COM端口值。因此,我可以通过对Linux和Linux的引用来解释所有需要进行的设置。 Windows Server。由于以下代码在localhost中正常工作
<?php
//You need to set the com with a dos command like like:
//for windows
//$output = "mode COM1: BAUD=9600 PARITY=N data=8 stop=1 XON=off TO=on";
for linux
$output = "mode /dev/ttyS1: BAUD=9600 PARITY=N data=8 stop=1 XON=off TO=on";
//The next command executes the dos command through php:
system($output);
//Create the resource id:
//for Windows
$fp = fopen('COM1', 'r+');
//for Linux
$fp = fopen('/dev/ttyS1', 'r+');
if(!$fp)
{
echo"Port not accessible";
}
else
{
echo"Port COM1 opened successfully";
}
//Read from port:
$buffer = fgets($fp);
echo"Read from buffer: $buffer";
$file = "output/a.txt";
file_put_contents($file,$buffer);
?>
*
答案 0 :(得分:0)
您永远不会费心检查您所使用的操作系统,并盲目尝试使用SAME文件句柄打开两个COM端口:
如果你在Windows上,那么:
$fp = fopen('COM1', 'r+');
成功,然后立即执行此操作:
$fp = fopen('/dev/ttyS1', 'r+');
并杀死您刚刚创建的句柄,因为Windows没有/dev/ttyS1
。
您需要条件代码:
$path = ($os == 'Linux') ? '/dev/ttyS1', 'COM1';
$fp = fopen($path, 'r+');
答案 1 :(得分:0)
清理代码并添加错误检查。
<?php
// Change Parms on Comport: Linux: Windows
$command = (PHP_OS == 'Linux') ? 'mode /dev/ttyS1: BAUD=9600 PARITY=N data=8 stop=1 XON=off TO=on' : 'mode COM1: BAUD=9600 PARITY=N data=8 stop=1 XON=off TO=on';
system($command, $retVar);
if($retVar == '127'){
echo("Command not found:$command<br>");
// May want to exit here.
}
//Create the resource id: Linux: Windows
$path = (PHP_OS == 'Linux') ? '/dev/ttyS1' : 'COM1';
$fp = fopen($path, 'r+');
if(!$fp){
echo"Port not accessible";
exit();
} else {
echo"Port COM1 opened successfully";
}
//Read from port:
$buffer = fgets($fp);
echo "<br>Data read from buffer: $buffer";
// Put full path to log in
//$file = "output/a.txt";
//file_put_contents($file,$buffer);