1. Go to this page and download the library: Download aldas/modbus-tcp-client library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
$address = 'tcp://127.0.0.1:5022';
$unitID = 0; // also known as 'slave ID'
$fc3 = ReadRegistersBuilder::newReadHoldingRegisters($address, $unitID)
->unaddressableRanges([[100,110], [1512]])
->bit(256, 15, 'pump2_feedbackalarm_do')
// will be split into 2 requests as 1 request can return only range of 124 registers max
->int16(657, 'battery3_voltage_wo')
// will be another request as uri is different for subsequent int16 register
->useUri('tcp://127.0.0.1:5023')
->string(
669,
10,
'username_plc2',
function ($value, $address, $response) {
return 'prefix_' . $value; // optional: transform value after extraction
},
function (\Exception $exception, Address $address, $response) {
// optional: callback called then extraction failed with an error
return $address->getType() === Address::TYPE_STRING ? '' : null; // does not make sense but gives you an idea
}
)
->build(); // returns array of 3 ReadHoldingRegistersRequest requests
// this will use PHP non-blocking stream io to recieve responses
$responseContainer = (new NonBlockingClient(['readTimeoutSec' => 0.2]))->sendRequests($fc3);
print_r($responseContainer->getData()); // array of assoc. arrays (keyed by address name)
print_r($responseContainer->getErrors());
$connection = BinaryStreamConnection::getBuilder()
->setHost('192.168.0.1')
->build();
$packet = new ReadHoldingRegistersRequest(256, 8); //create FC3 request packet
try {
$binaryData = $connection->connect()->sendAndReceive($packet);
//parse binary data to response object
$response = ResponseFactory::parseResponseOrThrow($binaryData);
//same as 'foreach ($response->getWords() as $word) {'
foreach ($response as $word) {
print_r($word->getInt16());
}
// print registers as double words in big endian low word first order (as WAGO-750 does)
foreach ($response->getDoubleWords() as $dword) {
print_r($dword->getInt32(Endian::BIG_ENDIAN_LOW_WORD_FIRST));
}
// set internal index to match start address to simplify array access
$responseWithStartAddress = $response->withStartAddress(256);
print_r($responseWithStartAddress[256]->getBytes()); // use array access to get word
print_r($responseWithStartAddress->getDoubleWordAt(257)->getFloat());
} catch (Exception $exception) {
echo $exception->getMessage() . PHP_EOL;
} finally {
$connection->close();
}