我有一个应用程序,我在其中订阅MQTT代理上的主题。当收到消息时,我需要处理消息中的数据并将其发回给同一个代理,关于不同的主题。我正在使用PHPMQTT的Lightning分支,因为它维护得很好(github repo)。
我的脚本如下。
<?php
require("./vendor/autoload.php");
/**
* An example callback function that is not inline.
* @param \Lightning\Response $response
*/
function callbackFunction($response) {
$topic = $response->getRoute();
$wildcard = $response->getWildcard();
$message = $response->getMessage();
echo "Message recieved:\n =============\n Topic: $topic\n Wildcard: $wildcard\n Message:\n $message\n\n";
}
$host = "m21.cloudmqtt.com";
$port = 18256;
$clientID = md5(uniqid()); // use a unique client id for each connection
$username = ''; // username is optional
$password = ''; // password is optional
$mqtt = new \Lightning\App($host, $port, $clientID, $username, $password);
// Optional debugging
$mqtt->debug(true);
if (!$mqtt->connect()) {
echo "Failed to connect\n";
exit;
}
// Add a new subscription for each topic that is needed
$mqtt->subscribe('net/raw/#', 0, function ($response) {
$topic = $response->getRoute();
$message = $response->getMessage();
$attributes = $response->getAttributes(); // Returns all the attributes received
$id = $response->attr('id'); // Gets a specific attribute by key. Returns null if not present.
echo "Message recieved:\n =============\n Topic: $topic\n Attribute - id: $id\n Message:\n $message\n\n";
$topic_id = 524;
$message = "0A";
$mqtt->publish("test/request/yes".$topic_id, $message, 1);
});
// Callback functions can be inline or by name as a string
$mqtt->subscribe('test/request/#', 0, 'callbackFunction');
// Call listen to begin polling for messages
$mqtt->listen();
?>
我可以订阅&net; raw / raw&#39;正好。加工也很好。将其发布回代理时会出现问题。第18行中启动的连接对该函数不可用,并发生以下错误:
注意:未定义的变量:第35行的C:\ wamp64 \ www \ sub.php中的mqtt
致命错误:未捕获错误:在C:\ wamp64 \ www \ sub.php中调用null上的成员函数publish():35 堆栈跟踪: 0 [内部函数]:{closure}(对象(Lightning \ Response)) 1 C:\ wamp64 \ www \ vendor \ brandonhudson \ lightning \ Lightning \ App.php(353):call_user_func(Object(Closure),Object(Lightning \ Response)) 2 C:\ wamp64 \ www \ vendor \ brandonhudson \ lightning \ Lightning \ App.php(424):Lightning \ App-&gt;消息(&#39; 0A&#39;) 3 C:\ wamp64 \ www \ sub.php(40):Lightning \ App-&gt; listen() 4 {line}在第35行的C:\ wamp64 \ www \ sub.php中抛出
我可以在函数内部创建一个新连接,但是当一个连接足够时,我不想继续打开和关闭新连接。我该怎么做才能在函数内部建立连接?
答案 0 :(得分:1)
您正在使用closure (anonymous function)作为方法response
的回调函数。要将变量继承到闭包中,可以使用use
而不是闭包上的其他参数。
因此,您可以将response
的来电更改为以下内容:
// Add a new subscription for each topic that is needed
$mqtt->subscribe('net/raw/#', 0, function ($response) use ($mqtt) {
$topic = $response->getRoute();
$message = $response->getMessage();
$attributes = $response->getAttributes(); // Returns all the attributes received
$id = $response->attr('id'); // Gets a specific attribute by key. Returns null if not present.
echo "Message recieved:\n =============\n Topic: $topic\n Attribute - id: $id\n Message:\n $message\n\n";
$topic_id = 524;
$message = "0A";
$mqtt->publish("test/request/yes".$topic_id, $message, 1);
});