modbus tcp通訊

adong發表於2022-05-24

composer require aldas/modbus-tcp-client

modbus協議包含 TCP RTU ASCII

modbus-tcp 不用CRC校驗了,因為走的是IP4。

modbus-tcp報文解析
00 00 00 00 00 06 00 05 00 00 ff 00
序號 00 00
協議 00 00 modbus協議
後面位元組數 00 06
裝置碼 00
功能碼 05
地址 00 00
資料閉合 01 00

use ModbusTcpClient\Network\BinaryStreamConnection;
use ModbusTcpClient\Packet\ModbusFunction\WriteSingleCoilRequest;
use ModbusTcpClient\Packet\ModbusFunction\WriteSingleCoilResponse;
use ModbusTcpClient\Packet\ResponseFactory;

//部分程式碼
$connection = BinaryStreamConnection::getBuilder()
        ->setPort(8234) //埠
        ->setHost('192.168.1.90')
        ->build();

    $startAddress = 0;
    $coil = true;
    $packet = new WriteSingleCoilRequest($startAddress, $coil);

        try {
        $binaryData = $connection->connect()
            ->sendAndReceive($packet);
        echo 'Binary received (in hex):   ' . unpack('H*', $binaryData)[1] . PHP_EOL;

        // @var $response WriteSingleCoilResponse 
        $response = ResponseFactory::parseResponseOrThrow($binaryData);
        echo 'Parsed packet (in hex):     ' . $response->toHex() . PHP_EOL;
        echo 'Coil value parsed from packet:' . PHP_EOL;
        print_r($response->isCoil());

    } catch (Exception $exception) {
        echo "<br/>";
        echo 'An exception occurred' . PHP_EOL;
        echo "<br/>";
        echo $exception->getMessage() . PHP_EOL;
        echo "<br/>";
        echo $exception->getTraceAsString() . PHP_EOL;
    } finally {
        $connection->close();
    }*/

裝置還沒到,不對的請指正

本作品採用《CC 協議》,轉載必須註明作者和本文連結
寫程式碼是一件趣事。

相關文章