54 lines
1.2 KiB
PHP
54 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace app\mqtt;
|
|
|
|
use Workerman\Connection\TcpConnection;
|
|
|
|
|
|
/**
|
|
* 发送
|
|
*/
|
|
class Publish
|
|
{
|
|
|
|
public function onConnect(TcpConnection $connection)
|
|
{
|
|
$mqtt = new \Workerman\Mqtt\Client('mqtt://ceshi-mqtt.lihaink.cn:1883', array(
|
|
"username" => "demo2",
|
|
"password" => "123456",
|
|
"client_id" => "admin_123",
|
|
));
|
|
$mqtt->connect();
|
|
$connection->mqtt = $mqtt;
|
|
}
|
|
|
|
/**
|
|
* {"topic":"demo","content":"asdasd"}
|
|
*/
|
|
public function onMessage(TcpConnection $connection, $data)
|
|
{
|
|
|
|
$data = json_decode($data, true);
|
|
if ($data == null) {
|
|
$connection->send("参数不能为空");
|
|
return false;
|
|
}
|
|
if ($data['topic'] == '') {
|
|
$connection->send("topic为空");
|
|
return false;
|
|
}
|
|
if ($data['content'] == '') {
|
|
$connection->send("content为空");
|
|
return false;
|
|
}
|
|
$topic = $data['topic'];
|
|
$content = $data['content'];
|
|
$res = $connection->mqtt->publish($topic, $content);
|
|
if ($res == null) {
|
|
$connection->send("发布成功");
|
|
} else {
|
|
$connection->send("发布失败");
|
|
}
|
|
}
|
|
}
|