使用php在Windows上通信串行端口

Rad*_*idi 6 windows modem gsm serial-port

我正在使用通过php中的COM端口连接到华为3G调制解调器的应用程序。这是我的代码:

<?php
include("sms.php");
$sms = new sms();
$device = "COM11";
exec("mode $device BAUD=9600 PARITY=n DATA=8 STOP=1 xon=off octs=off rts=on");
$comport = fopen($device, "r+b");
if ($comport === false){
    die("Failed opening com port<br/>");
}else{
    echo "Com Port Open<br/>";
}

//Set non-blocking mode for writing
//stream_set_blocking($comport, 0);
$sms->_blocking($comport,0);
$atcmd = "AT\r";
fputs($comport, $atcmd);

sleep(5); // Sleep for response from the modem

 // Set blocking mode for reading
$sms->_blocking($comport,1);
$res = fgets($comport, 4017);
if(trim($res) == "OK"){
    echo "Modem supports AT Commands<br/>";
}else{
    echo "Error response: ".$res;
}

fclose($comport);
?>
Run Code Online (Sandbox Code Playgroud)

sms.php:

<?php
    class sms{
        function _blocking($device,$mode){
            stream_set_blocking($device, $mode);
            return true;
        }
    }
?>
Run Code Online (Sandbox Code Playgroud)

这对我来说很好。现在的挑战是,每次我连接到新的USB端口时,COM都会为我的调制解调器进行更改。还有其他方法可以在Windows中使用php自动检测设备吗?

mik*_*ikg 3

您需要通过 PHP 的 shell_exec() 等外部命令来确定 USB 设备的 COM 端口号。

对于 Windows,您可以尝试这个小工具:

http://todbot.com/blog/2012/03/02/listcomports-windows-command-line-tool-for-usb-to-serial/

https://github.com/todbot/usbSearch/

通过 shell_exec() 调用此工具后,您需要解析其输出 (RegExp) 并根据公司/设备名称查找确切的 COM 端口号。