【转】PHP的mqtt发布和订阅demo:原生、thinkphp、PhalApi

一、原生php的mqtt订阅和发布demo  
1、发布 pub.php
<?php

$client = new Mosquitto\Client();
$client->connect(MQTT_IP, MQTT_PORT, 5);//MQTT_IP是mqtt服务器ip MQTT_PORT一般是1883
$client->loop();
$client->publish($topic, $message, 1, 0);
$client->disconnect();//断开链接
unset($client);


?>
2、订阅 sub.php
<?php

$client = new Mosquitto\Client();
$client->onMessage('message'); //回调函数
$client->connect(IP, 1883, 5);
$client->subscribe('订阅主题', 1);
$payload='';

$client->loop();
$client->publish('发布主题', "发布信息", 1, 0);
$nowtime=time();

while(true){
$client->loop();
global $payload;
if(!empty($payload)){

echo $payload; //订阅到的消息
break;
}
if($nowtime==(time()-2)){
break;
}
}

$client->unsubscribe('订阅主题');//取消订阅
$client->disconnect();//断开链接
unset($client);


function message($message) {
//printf("Got a message ID %d on topic %s with payload:\n%s\n\n", $message->mid, $message->topic, $message->payload);
global $payload;
$payload=$message->payload;
}
二、Thinkphp3.2 的Demo

Home/Common/function.php
<?php

function mqtt_message($message) {
// printf("Got a message ID %d on topic %s with payload:\n%s\n\n", $message->mid, $message->topic, $message->payload);
session("payload",$message->payload);
}

function mqtt_mosquitto($phy_addr_gid,$msg,$timeout=2){
$client = new \Mosquitto\Client();
$client->onMessage('mqtt_message');
$client->connect(MQTT_IP, MQTT_PORT, 5);
$client->subscribe(MQTT_SUB, 1);

$client->loop();
$client->publish($phy_addr_gid, $msg, 1, 0);

$nowtime=time();
while(true){
$client->loop();
if(session("payload")){
$payload=session("payload");
session("payload",null);
return $payload;
break;
}
if ($nowtime==(time()-$timeout)) {
return "timeout";
break;
}
}
$client->unsubscribe(MQTT_SUB);
$client->disconnect();
unset($client);
}
三、PhalApi框架的订阅demo

对这个框架不太熟,订阅里的回调函数不能直接套用本小白真的很头疼,开发文档里只提了一句需要将自定义的回调函数名加入白名单,看了半天还是不会,有人懂的话希望评论里能指点一二,谢谢

mqtt.php
 
class Api_mqtt extends PhalApi_Api
{

public function getRules()
{
return array(
);
}


function mqtt_sub(){

$client = new \Mosquitto\Client();
$client->onMessage(function($m){
$_SESSION['test']=$m->payload;
});
$client->connect('服务器IP', 1883, 5);
$client->subscribe('123', 1);//123 订阅主题

$client->loop();
$client->publish('123', '456', 1, 0);//123 发布主题 456发布的消息 订阅自己发布的消息没毛病2333

$nowtime=time();

while(true){
$client->loop();
if ($_SESSION['test']!==null){
$b=$_SESSION['test'];
$_SESSION['test']=null;
return $b;
break;
}
if ($nowtime==(time()-2)) {
return "timeout";
break;
}

}

$client->unsubscribe('123'); //取消订阅
$client->disconnect();
unset($client);

}

}

原文链接:https://blog.csdn.net/iiiLen/a ... 85422

0 个评论

要回复文章请先登录注册