Reputation:
I tried playing around with accessing a serial port with PHP, but haven't had much luck.
I've tried using fsockopen
, fopen
, proc_open
, etc. I can't read or write to the socket.
Example:
$fp = fopen("/dev/ttyUSB0", "w+");
fwrite("enable");
echo fread($fp, 1024);
Upvotes: 5
Views: 10464
Reputation: 14237
I've run into this many times in the past. Once was creating a management interface for a Cisco 2811. This may work for yours, although I am not sure of your IOS version (assuming Cisco because of your fwrite();
through console).
See if your user has access to the device first. Easily, this can be done with screen /dev/ttyUSB0
. Run your commands, to detach, press ctrl+a
then d
.
I most commonly use the stream_*
family for something like this.
Here is an example:
$stream = stream_socket_client("udg:///dev/ttyUSB0", $errno, $errstr, 30);
fwrite($stream, "enable");
while(true){
$line = stream_get_contents( $stream );
if($line == 'exit'){
break;
}
}
By default, stream_socket_client
starts in blocking mode, so you do not need to manually toggle it.
Another thing you can do if you dont mind installing an extension is the DirectIO
extension. It possesses functions to allow you to set baud rate and all the goodies, example here.
You can even take a look at this project: http://code.google.com/p/php-serial/source/browse/trunk/
Upvotes: 4