我正在订阅所有主题,并且我想进行相同的操作(例如从主题名称获取ID)并重新发布相同的有效内容,但主题不同。这是我的代码,我可以通过创建另一个连接来成功实现它。我想使用相同的连接来发布我的味精。
<?php
$client = new Mosquitto\Client();
$client->onConnect('connect');
$client->onDisconnect('disconnect');
$client->onSubscribe('subscribe');
$client->onMessage('message');
$client->connect(localhost, 8080, 60);
$client->subscribe('#', 1); // Subscribe to all messages
while(true){
$client->loopForever();
sleep(5);
}
function connect($r) {
echo "Received response code {$r}\n";
}
function subscribe() {
echo "Subscribed to a topic\n";
}
function message($message) {
printf("Got a message on topic %s with payload:\n%s\n", $message-
>topic, $message->payload);
$dbusername="root";
$dbpassword="";
$server="localhost";
$dbconnect=mysql_connect($server,$dbusername,$dbpassword);
$topic=explode("/",$message->topic);
$savetopicname=$topic[0]; // home
$savesensor=$topic[1]; //temperature
$sqlfetch="SELECT id FROM datas.rooms WHERE room='".$savetopicname."'";
$sql_run=mysql_query($sqlfetch,$dbconnect);
$out=mysql_fetch_array($sql_run);
$sendid=$out[0]; //id =5
$newpayload=$message->payload;
$newtopic=$message->topic."/".$sendid." ";
$client_new=new Mosquitto\Client();
$client_new=onConnect('connect');
$client_new=connect("localhost",8080,60);
$client_new->publish($newtopic,$newpayload,1,false);
}
function disconnect() {
echo "Disconnected cleanly\n";
}