Jump to content

Timeout with fgets()?


KenHorse

Recommended Posts

I have a USB to serial convertor (/etc/ttyUSB0) that I read from, using fgets.

I'm looking for a way, that if nothing is received with a few seconds, the script terminates. As in  a "serial timeout"

Of course, fgets seems to hang forever if it never sees a EOL and I need a way around that

Link to comment
Share on other sites

'fgets' reads until it finds an EOF, newline or reaches a specified number of bytes. You didn't show any code so if none of those conditions occurs in your case it will hang forever. I am guessing what you are trying to accomplish but I suspect you are using the wrong read for a ttyUSB device. You might try minicom instead.

Link to comment
Share on other sites

Here's the code I'm using, which works just fine as long as serial data is returned:

 

//***NEW SERIAL FUNCTION***
function serial($cmd) {		
	$port = "/dev/ttyUSB0";	
	$c = exec('stty -F '. $port .' cs8 -parenb -cstopb -echo raw speed 57600');

	if(!file_exists($port)) {
		echo "I am not blocked!";
	} else {
		$f = fopen($port, "w+");
		fwrite($f, $cmd."\r");		

		while(1) {			
			$read = fgets($f);			
			if(strlen($read) >5) {
			//	echo $read;
				$x = $read;
				fclose($f);		
				break;
			} else {
				fwrite($f, $cmd."\r");
			//	echo "[Error Resend]\n";
			}		
	}	
		}
	
	$substring = substr($read,0,1);
	if($substring =="-"){			
		print"<CENTER><H2>We encountered an error when sending $read". "Please close window and try again</H2></CENTER>";	
		//$noDataToSend ="False";	
		exit();		
	}
return $x;
}

BUT, if the communicated-with device doesn't respond, obviously fgets hangs. Normally I'd refer to that circumstance as a serial timeout. That's what I'm trying to get around.

 

And I do know minicom but that's not a help in this case

Edited by KenHorse
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.