From fd2ae72b7975331ed4a5b0d09b984f923954add5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20Hru=C5=A1ka?= Date: Sat, 2 Sep 2017 14:35:28 +0200 Subject: [PATCH] use timeout in socket_recv fail loop --- src/ModbusMaster.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/ModbusMaster.php b/src/ModbusMaster.php index 9c27f53..7f0a9b4 100644 --- a/src/ModbusMaster.php +++ b/src/ModbusMaster.php @@ -64,7 +64,7 @@ class ModbusMaster public $status; /** @var float Total response timeout (seconds, decimals allowed) */ - public $timeout_sec = 5; + public $timeout_sec = 3; /** @var float Socket read timeout (seconds, decimals allowed) */ public $socket_read_timeout_sec = 0.3; // 300 ms @@ -205,16 +205,18 @@ class ModbusMaster $rec = ""; $totalReadTimeout = $this->timeout_sec; $lastAccess = microtime(true); + $readStart = microtime(true); $readTout = $this->secsToSecUsecArray($this->socket_read_timeout_sec); - while (false !== socket_select($readsocks, $writesocks, $exceptsocks, $readTout['sec'], $readTout['usec'])) { - $this->status .= "Wait data ... \n"; if (in_array($this->sock, $readsocks)) { - if (@socket_recv($this->sock, $rec, 2000, 0)) { // read max 2000 bytes + if ($recn = @socket_recv($this->sock, $rec, 2000, 0)) { // read max 2000 bytes $this->status .= "Data received \n"; return $rec; } $lastAccess = microtime(true); + if (microtime(true) - $readStart > $totalReadTimeout) { + throw new Exception("Read timed out, last error: " . socket_strerror(socket_last_error($this->sock))); + } } else { $timeSpentWaiting = microtime(true) - $lastAccess; if ($timeSpentWaiting >= $totalReadTimeout) {