简体   繁体   中英

Read response from command on serial port

I am programming a PHP application that uses a serial device to do stuff with GSM modem. So you can communicate with the serial port via screen and you would get a response when you write a command.

I use PHP to communicate with my serial port and use sleep to wait between the commands, I se fopen with w+ flags and fwrite to send the commands. I tried using the fread function to check if the response is there, but it wasn't. How could that be done in PHP?

conceptually f_read should work if the port is configured correctly. there is a library php-serial on https://github.com/Xowap/PHP-Serial

this is the readPort() function :

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM