You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP通过RS485 Modbus获取设备响应的问题求助

PHP与RS485 Modbus设备通信问题:响应截断/无响应解决求助

Windows环境初始尝试(无响应)

我尝试用PHP向RS485设备发送命令并获取响应,最初在Windows下使用以下脚本:

<?php
class rapidserial{
  function _blocking($device,$mode){
      stream_set_blocking($device, $mode);
      return true;
     }
  }
$rapidserial = new rapidserial();
$device = "COM3";
shell_exec("mode $device BAUD=9600 PARITY=n DATA=8 STOP=2 xon=off octs=off rts=off"); 
$comport = fopen($device, "r+b");
if ($comport === false)
    {
    die("Failed opening com port<br/>");
    }
    else
    {
    echo "Com Port Open<br/>"; 
    }
//Set non-blocking mode for writing
$rapidserial->_blocking($comport,0);
$atcmd = "\x0A\x04\x00\x00\x00\x49\x30\x87"; //
fputs($comport, $atcmd);
usleep(2000);
// Set blocking mode for reading
$rapidserial->_blocking($comport,1);
echo 'Response:';
$res = fgets($comport, 4017);
var_dump ($res);
fclose($comport);
?>

该脚本基于SuperUser上的帖子修改,原脚本可正常发送命令,但当前无法获取响应,返回结果为空。尝试过PhpSerialModbus库,提示“Unable to open the device”。已确认设备通信正常,第三方Modbus软件可正常收发完整响应。

Linux环境进展(响应截断)

切换到Linux环境后,使用PhpSerialModbus库取得部分进展,但收到的响应数据出现截断,请求非起始位置寄存器也无法获取完整预期数据。当前代码及返回结果如下:

当前代码

<?php
include("/var/www/html/PhpSerialModbus.php");
$modbus = new PhpSerialModbus();
$modbus->deviceInit('/dev/ttyUSB0',9600,'none',8,2,'none');
$modbus->deviceOpen();
$modbus->debug = false;
$rawquery="\x0A\x04\x00\x00\x00\x49\x30\x87";
$modbus->sendRawQuery($rawquery.$modbus->crc16($rawquery),false);
$result=$modbus->getResponse(true);
function hex2float($strHex) {
    $hex = sscanf($strHex, "%02x%02x%02x%02x%02x%02x%02x%02x");
    $bin = implode('', array_map('chr', $hex));
    $array = unpack("Gnum", $bin);
    return $array['num'];
}
$bin_result = bin2hex($result);
$bin_result = chunk_split($bin_result, 2, ',');
$bin_result = substr($bin_result, 9);
$myresults = print_r($bin_result, true);
$final_array = explode(",", $myresults);
print_r ($final_array);
?>

返回结果

[0] => 42
[1] => 48
[2] => 33
[3] => 33
[4] => 43
[5] => d3
[6] => 92
[7] => 00
[8] => 43
[9] => 75
[10] => 54
[11] => 86
[12] => 40
[13] => 66
[14] => 66
[15] => 72
[16] => be
[17] => dc
[18] => 7a
[19] => de
[20] => 44
[21] => 5c
[22] => f0
[23] => 0a
[24] => 44
[25] => 34
[26] => 50
[27] => 09
[28] => 42
[29] => f2
[30] => cc
[31] => cd
[32] => be
[33] => f9
[34] => db
[35] => 24
[36] => 40
[37] => 25
[38] => c2
[39] => 8f
[40] => 42
[41] => 06
[42] => cc
[43] => cd
[44] => 42
[45] => 90
[46] => 00
[47] => 07
[48] => 42
[49] => ef
[50] => 99
[51] => 9a
[52] => 43
[53] => d3
[54] => 51
[55] => 65
[56] => 43
[57] => 73
[58] => c2
[59] => 9b
[60] => 40
[61] => 80
[62] =>

现寻求解决方法,以获取完整的RS485 Modbus设备响应。


内容的提问来源于stack exchange,提问作者omega1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 11:44:57