From 66154d6c48102460a0661169fc17e733fa4c3a5e Mon Sep 17 00:00:00 2001 From: Fernando Herrero Date: Tue, 12 Oct 2021 23:23:53 +0200 Subject: [PATCH] sendRequest fix error detection --- composer.json | 2 +- src/ModbusRTU.php | 11 ++++------- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/composer.json b/composer.json index 1e6b580..c9256d4 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "fawno/modbus", - "version": "0.1.0", + "version": "0.1.1", "description": "Modbus RTU serial protocol in PHP", "keywords": ["Modbus RTU", "DDS238"], "license": "MIT", diff --git a/src/ModbusRTU.php b/src/ModbusRTU.php index c8dbdf6..b6af7c4 100644 --- a/src/ModbusRTU.php +++ b/src/ModbusRTU.php @@ -12,9 +12,6 @@ class ModbusRTU extends SerialDio { public const MODBUS_ADU = 'C1station/C1function/C*data/'; public const MODBUS_ERROR = 'C1station/C1error/C1exception/'; - private const MODBUS_REQUEST = 'C2n2'; - //public const MODBUS_RESPONSE = 'C1station/C1function/C1count/n*records/'; - protected $_options = [ 'data_rate' => 9600, 'data_bits' => 8, @@ -434,10 +431,6 @@ public function sendRequest (string $request) { throw new Exception(sprintf('Response lenght too short: "%s"', bin2hex($response)), -1); } - if (substr($response, -2) != $this->crc16(substr($response, 0, -2))) { - throw new Exception('Error check fails', -2); - } - $adu_request = unpack(self::MODBUS_ADU, $request); $adu_response = unpack(self::MODBUS_ERROR, $response); if ($adu_request['function'] != $adu_response['error']) { @@ -449,6 +442,10 @@ public function sendRequest (string $request) { } } + if (substr($response, -2) != $this->crc16(substr($response, 0, -2))) { + throw new Exception(sprintf('Error check fails: "%s"', bin2hex($response)), -2); + } + return $response; } }