如何使用 php exec 将 mosquitto_sub 输出分配给变量?

how to assign the mosquitto_sub output to a variable using php exec?

在我的发布者中,我尝试了类似

的东西
$msg = '{"test":"a","test2":"b"}';
$publishCommand = "mosquitto_pub -h IP_ADDRESS_HERE -t TOPIC_HERE -m $msg";
exec($publishCommand);

上面的代码片段有效。

因为当我在服务器中手动尝试以下代码片段时,我可以看到 json 字符串输出

mosquitto_sub -h 127.0.0.1 -t TOPIC_HERE -i 'ID_HERE'

然而,当我尝试在 PHP 中使用上面的代码片段时,为了将输出分配给变量并能够 json_decode 数据,它根本不起作用,我无法通过下面的代码片段获得输出

exec("mosquitto_sub -h 127.0.0.1 -t TOPIC_HERE -i 'ID_HERE'", $output);
print_r($output);

NOR 与这个

exec("mosquitto_sub -h 127.0.0.1 -t TOPIC_HERE -i 'ID_HERE' 2>&1", $output);
print_r($output);

NOR 与这个

exec("/usr/bin/mosquitto_sub -h 127.0.0.1 -t TOPIC_HERE -i 'ID_HERE'", $output);
print_r($output);

我也试过使用 passthru OR 系统,但是这两个都立即显示输出,我无法将输出分配给变量 即使在使用 ob_* 系列函数后,例如 ob_start、ob_get_contents 等...

您的问题很可能是因为 mosquitto_sub 永远不会退出。

默认情况下 mosquitto_sub 永远运行打印出它发布到匹配主题的每条消息。为了获得输出,您需要 mosquitto_sub 到 return 并关闭它在 stdout 上的句柄。

mosquitto_sub 可以通过 -C 选项得知在退出之前要等待多少条消息。来自男人page:

-C

Disconnect and exit the program immediately after the given count of messages have been received. This may be useful in shell scripts where on a single status value is required, for example.

如果您想从 PHP 订阅 MQTT 主题,我建议您查看本机 PHP 客户端。有一个列表 here