user27972404
user27972404

Reputation: 1

How to wait for modbus rtu response over tcp in PHP?

I have a socket server and I'm using reactphp to receive connections from multiple clients. I'll need to make several record requests and wait for each one to return before moving on to the next record.

What's happening in my execution is that I'm doing a loop and the result isn't as expected. For example, if I need records 30001, 30004 and 30006, even in the loop, with the request ($conn->write($rtuPacket)) for all the records, the final return is just "30001" repeatedly.

How can I wait for each question/answer transaction to complete before moving on to the next request?

Below is part of my code:

for ($i = 0; $i < sizeof($get_index_read_input_registers); $i++) {
      $startAddress = $get_index_read_input_registers[$i]["ADDRESS"];
      $quantity = $get_index_read_input_registers[$i]["QUANTITY"];
      $slaveId = $arr_addr_rs485[$j]; 
      $packet = new ReadInputRegistersRequest($startAddress, $quantity, $slaveId);
      $rtuPacket = RtuConverter::toRtu($packet);
      $conn->write($rtuPacket);

      $receivedData = b'';
      $conn->on('data', function ($data) use ($conn, $logger, &$receivedData) {
           $logger->debug($conn->getRemoteAddress() . ": RTU received: (in HEX):" . unpack('H*', $data)[1]) . PHP_EOL;
      });

       //React\Async\await(3.0);
}

Upvotes: 0

Views: 34

Answers (0)

Related Questions