Modbus TCP and UDP library for PHP., originally from code.google.com/p/phpmodbus
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
php-modbus/examples/example_datatype.php

64 lines
1.8 KiB

12 years ago
<?php
use PHPModbus\ModbusMaster;
use PHPModbus\PhpType;
12 years ago
$ip = filter_var($_GET['ip'], FILTER_VALIDATE_IP) ? $_GET['ip'] : '192.192.15.51';
$unitId = ((int)$_GET['unitid']) ?: 0;
$reference = ((int)$_GET['reference']) ?: 12288;
$quantity = ((int)$_GET['quantity']) ?: 10;
$modbus = new ModbusMaster($ip, 'UDP');
12 years ago
12 years ago
try {
// FC 3
// read 10 words (20 bytes) from device ID=0, address=12288
$recData = $modbus->readMultipleRegisters($unitId, $reference, $quantity);
} catch (Exception $e) {
// Print error information if any
echo $modbus;
echo $e;
exit;
12 years ago
}
// Received data
12 years ago
echo "<h1>Received Data</h1>\n";
12 years ago
print_r($recData);
// Conversion
12 years ago
echo "<h2>32 bits types</h2>\n";
12 years ago
// Chunk the data array to set of 4 bytes
$values = array_chunk($recData, 4);
// Get float from REAL interpretation
12 years ago
echo "<h3>REAL to Float</h3>\n";
foreach ($values as $bytes)
echo PhpType::bytes2float($bytes) . "</br>";
12 years ago
// Get integer from DINT interpretation
12 years ago
echo "<h3>DINT to integer </h3>\n";
foreach ($values as $bytes)
echo PhpType::bytes2signedInt($bytes) . "</br>";
12 years ago
// Get integer of float from DINT interpretation
12 years ago
echo "<h3>DWORD to integer (or float) </h3>\n";
foreach ($values as $bytes)
echo PhpType::bytes2unsignedInt($bytes) . "</br>";
12 years ago
12 years ago
echo "<h2>16 bit types</h2>\n";
12 years ago
// Chunk the data array to set of 4 bytes
$values = array_chunk($recData, 2);
// Get signed integer from INT interpretation
12 years ago
echo "<h3>INT to integer </h3>\n";
foreach ($values as $bytes)
echo PhpType::bytes2signedInt($bytes) . "</br>";
12 years ago
// Get unsigned integer from WORD interpretation
12 years ago
echo "<h3>WORD to integer </h3>\n";
foreach ($values as $bytes)
echo PhpType::bytes2unsignedInt($bytes) . "</br>";
12 years ago
// Get string from STRING interpretation
echo "<h3>STRING to string </h3>\n";
echo PhpType::bytes2string($recData) . "</br>";