使用PHP读取串行端口? 有时我们可能会遇到这样的需求,从网络浏览器读取串行设备。 有点复杂吧?是的,用现有技术实现这一目标的方法很少 。
我们都知道浏览器是沙盒模式,它严格限制访问系统硬盘或任何串行设备。 那么我们如何使用PHP(使用客户端浏览器执行服务器端脚本)读取串行端口。 是的,有点疯狂。我们可以找找一些其他可用的选项。Java Applet 。
Active X组件。
以上两种方法都有自己的优点和局限,Active X只支持Windows平台,Java是跨平台,所以它可以被使用,它还有一些要求,如JDK应安装在客户端PC上,应该对applet进行签名和验证, 等等.
所以,如果我们可以做到(在客户端电脑上安装JDK),那么我们也就可以在客户端PC上去安装带有PHP的apache服务器, 所以我们可以用PHP自己去开发它。 不需要与applet签名进程进行斗争。
所以PC需要先连接串口设备。 我在linux机器上工作,所以,我可以用PHP本身进行串口读取,在Windows中使用PHP读取串口有一些问题,它不能快速实现,工作量很大,在我的情况下也很好实现,bcoz客户端PC是Linux,所以,我很高兴使用PHP。
让我们检查PHP中的代码,以及我的执行代码的计划,如下所示。
我将把代码放在一个/var/htm里面名为serialport的文件夹,所以,我可以像localhost/serialport/index.php那样去访问,它会返回数据,在我的网页中我可以使用Ajax调用上面的url,并且在我的web app文本框里面返回结果 。
在linux中你要记住的东西很少,端口名称通常像ttyUSB0或 ttyS0
首先,您可以将设备与系统连接,然后使用终端输入命令测试设备是否正常工作。cat/dev/ttyUSB0
如果端口名正确,它将读取,并且显示终端中的值。 只要用 Ctl Z 就可以停止它。
现在在Linux机器上使用apache服务器时很少,默认的apache用户名为 www-data应该在dialout组中,然后才能访问该端口 。 因此,请确保用户已经在dialout组中。 否则,你可以使用以下命令添加。sudo usermod -a -G dialout www-data
你可以使用以下脚本列出用户的当前组。groups www-data
现在代码比这个设置更简单了。
串口数据将连续读取,并且输出每个值之间的空格,所以,我所做的是找到最大重复次数值,即必须是设备中显示的值。 并输出。ini_set("display_errors","1");
error_reporting(E_ALL);
header('Access-Control-Allow-Origin: *');
include"php_serial.class.php";
//Let's start the class
$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/ttyUSB0");
//Set for 9600-8-N-1 (no flow control)
$serial->confBaudRate(9600);//Baud rate: 9600
$serial->confParity("none");//Parity (this is the"N" in"8-N-1")
$serial->confCharacterLength(8);//Character length (this is the"8" in"8-N-1")
$serial->confStopBits(1);//Stop bits (this is the"1" in"8-N-1")
$serial->confFlowControl("none");
//Then we need to open it
$serial->deviceOpen();
//Read data
$read = $serial->readPort();
//Print out the data
$data = preg_split('/s+/', $read);
//print_r($data);//red and split the data by spaces to array
$array = array_count_values($data);//count the array values
$values = array_keys($array, max($array));//count the maximum repeating value
echo $values[0];
//If you want to change the configuration, the device must be closed.
$serial->deviceClose();
您也可以将整个代码下载为zip文件,在上面的代码中我使用了一个php串口类,也可以用zip文件。 这只适用于不使用Windows的Linux 。 在Windows中无法读取串行端口的数据,Windows只支持直接从PHP写入串行端口。
只需下载下面的php脚本读取串行端口即可。 并将它提取到你的/var/www/html/文件夹。 它有一个index.html文件,使用jQuery使ajax调用读取串口数据,并且返回网页的PHP文件 。
如果你尝试使用远程机器的代码,请确保你在部分的顶部添加了此脚本。header('Access-Control-Allow-Origin: *');
阅读快乐