代码之家  ›  专栏  ›  技术社区  ›  Andrey Tsarev

从串行端口上的命令读取响应

  •  1
  • Andrey Tsarev  · 技术社区  · 7 年前

    我正在编写一个PHP应用程序,它使用串行设备来处理GSM调制解调器。因此,您可以通过 screen 当您编写命令时,您会得到一个响应。

    我使用PHP与串行端口通信,并使用 sleep 要在命令之间等待,请使用 fopen 具有 w+ 标志和 fwrite 发送命令。我试着用 fread 函数来检查响应是否存在,但它不存在。如何在PHP中做到这一点?

    1 回复  |  直到 7 年前
        1
  •  0
  •   ralf htp    7 年前

    概念上 f_read 如果端口配置正确,则应正常工作。有一个图书馆 php-serial 在…上 https://github.com/Xowap/PHP-Serial

    这是 readPort() 功能:

    public function readPort($count = 0)
        {
            if ($this->_dState !== SERIAL_DEVICE_OPENED) {
                trigger_error("Device must be opened to read it", E_USER_WARNING);
                return false;
            }
            if ($this->_os === "linux" || $this->_os === "osx") {
                // Behavior in OSX isn't to wait for new data to recover, but just
                // grabs what's there!
                // Doesn't always work perfectly for me in OSX
                $content = ""; $i = 0;
                if ($count !== 0) {
                    do {
                        if ($i > $count) {
                            $content .= fread($this->_dHandle, ($count - $i));
                        } else {
                            $content .= fread($this->_dHandle, 128);
                        }
                    } while (($i += 128) === strlen($content));
                } else {
                    do {
                        $content .= fread($this->_dHandle, 128);
                    } while (($i += 128) === strlen($content));
                }
                return $content;
            } elseif ($this->_os === "windows") {
                // Windows port reading procedures still buggy
                $content = ""; $i = 0;
                if ($count !== 0) {
                    do {
                        if ($i > $count) {
                            $content .= fread($this->_dHandle, ($count - $i));
                        } else {
                            $content .= fread($this->_dHandle, 128);
                        }
                    } while (($i += 128) === strlen($content));
                } else {
                    do {
                        $content .= fread($this->_dHandle, 128);
                    } while (($i 
    
    += 128) === strlen($content));
            }
            return $content;
        }
        return false;
    }
    

    ( How to Read RS232 Serial Port in PHP like this QBasic Program )