Replies: 2 comments 29 replies
-
<?php
use ModbusTcpClient\Network\BinaryStreamConnection;
use ModbusTcpClient\Packet\ModbusFunction\ReadHoldingRegistersRequest;
use ModbusTcpClient\Packet\RtuConverter;
use ModbusTcpClient\Packet\ModbusFunction\ReadHoldingRegistersResponse;
require __DIR__ . '/vendor/autoload.php';
//require __DIR__ . '/logger.php';
$connection = BinaryStreamConnection::getBuilder()
->setPort(1001)
->setHost('10.20.0.74')
->setReadTimeoutSec(3) // increase read timeout to 3 seconds
->setIsCompleteCallback(function ($binaryData, $streamIndex) {
// Do not check for complete TCP packet structure. Default implementation works only for Modbus TCP.
// Modbus TCP has 7 byte header and this function checks for it and whole packet to be complete. RTU does
// not have that.
// Read about differences here: https://www.simplymodbus.ca/TCP.htm
return true;
})
// ->setLogger(new EchoLogger())
->build();
$startAddress = 4;
$quantity = 2;
$slaveId = 1; // RTU packet slave id equivalent is Modbus TCP unitId
$tcpPacket = new ReadHoldingRegistersRequest($startAddress, $quantity, $slaveId);
$rtuPacket = RtuConverter::toRtu($tcpPacket);
try {
$binaryData = $connection->connect()->sendAndReceive($rtuPacket);
echo 'RTU Binary received (in hex): ' . unpack('H*', $binaryData)[1] . PHP_EOL;
$response = RtuConverter::fromRtu($binaryData);
echo 'Parsed packet (in hex): ' . $response->toHex() . PHP_EOL;
echo 'Data parsed from packet (bytes):' . PHP_EOL;
print_r($response->getData());
} catch (Exception $exception) {
echo 'An exception occurred' . PHP_EOL;
echo $exception->getMessage() . PHP_EOL;
echo $exception->getTraceAsString() . PHP_EOL;
} finally {
$connection->close();
} |
Beta Was this translation helpful? Give feedback.
16 replies
-
aldas thanks a lot i read it but do you have any idea about this problem multiple connections at the same time |
Beta Was this translation helpful? Give feedback.
13 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
hello aldas, first of all, thank you, but I have a problem, I connected as modbus rtu, but I get the following package error, I make 10-15 queries, it gives as an array, then it is the same again, package parsing error, can you help?
Beta Was this translation helpful? Give feedback.
All reactions