php 做一个mqtt按钮,发布触发信号

在之前博客php 做一个文件下载服务器,得避免跨路径工具,安全很重要 中加了一个按钮,触发物联网设备返回数据。基于mqtt开发,如果想知道mqtt如何搭建,可以看我的博客【MQTT(1)】服务端的搭建

效果

需要写两个文件

1、一个php发送mqtt信号

复制代码
<?php  
require 'vendor/autoload.php'; // 引入 Composer 的自动加载文件  
require('vendor/bluerhinos/phpmqtt/phpMQTT.php');

$server   = "gz.xxx.xxx.com"; // MQTT 服务器地址  
$port     = 1883;                // MQTT 服务器端口  
$username = "user1";     // MQTT 用户名(如果需要)  
$password = "123456";     // MQTT 密码(如果需要)  
$client_id = "phpMQTT-publisher"; // 客户端ID  


$mqtt = new Bluerhinos\phpMQTT($server, $port, $client_id);

if (!$mqtt->connect(true, NULL, $username, $password)) {  
    exit(1);  
}  
  
$topic = "example/temperature"; // MQTT 主题  
$content = "Hello MQTT!"; // 要发送的消息内容  
  
$mqtt->publish($topic, $content, 0); // 发送消息  
$mqtt->close(); // 关闭连接  
  
echo "Data Return success\n";  
?>

2、 AJAX 请求来实现这一点。以下是一个基本的实现方案: 前端 HTML 和 JavaScript

首先,你需要一个 HTML 页面,其中包含一个按钮,用于发送 AJAX 请求到 PHP 脚本。

html 复制代码
<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>MQTT Publish Button</title>  
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>  
    <script>  
        $(document).ready(function() {  
            $('#publishBtn').click(function() {  
                $.ajax({  
                    url: 'publish_mqtt.php', // 你的 PHP 脚本路径  
                    type: 'POST',  
                    success: function(response) {  
                        alert('Message published: ' + response);  
                    },  
                    error: function(xhr, status, error) {  
                        alert('Error: ' + error);  
                    }  
                });  
            });  
        });  
    </script>  
</head>  
<body>  
    <button id="publishBtn">Publish MQTT Message</button>  
</body>  
</html>

(正文结束)

相关推荐
BingoGo1 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php
JaguarJack1 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php·服务端
BingoGo2 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php
JaguarJack2 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php·服务端
JaguarJack3 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
后端·php·服务端
BingoGo3 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
php
JaguarJack4 天前
告别 Laravel 缓慢的 Blade!Livewire Blaze 来了,为你的 Laravel 性能提速
后端·php·laravel
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端