使用 jquery 的 mqtt Nodejs Web 应用程序

Nodejs web application for mqtt using jquery

我想设计一个 web 应用程序,能够在切换状态更改或填写并提交表单等时在 mqtt 代理上发布消息。我能够使用节点上的 mqtt 库发布消息。当使用 javascript 和 jquery 在 html 页面上更改时,我还能够检测到正常的开关状态。现在我想在这里从节点应用程序调用 mqtt 发布功能。我该怎么做?

这是正常的 html 文件 switch.html

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="switch.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="switch.js"></script> 
</head>
<body>

<h2>Toggle Switch</h2>


<label class="switch" id = "switchLabel1">
  <input type="checkbox" id = "switch1">
  <div class="slider round"></div>
</label>

</body>
</html> 

检测开关状态javascriptswitch.js

$( document ).ready(function() {
    $('#switch1').attr('checked', true);
    $('#switch1').click(function(){

        if($(this).prop("checked") == true){
            console.log("switch1 is checked.");
        }

        else if($(this).prop("checked") == false){
            console.log("switch1 is unchecked.");
        }

    });
});

Nodejs 应用程序将消息发布到 mqtt index.js。使用 npm 安装 MQTT 库。

var mqtt = require('mqtt')
var client  = mqtt.connect('mqtt://192.168.15.3')

client.on('connect', function () {
  client.subscribe('mqtt_node_subscribe')
  client.publish('mqtt_node_publish', 'Hello mqtt')
})

client.on('message', function (topic, message) {
  // message is Buffer 
  console.log(message.toString())
})

我想做的是调用 client.publish("topic", "message") 而不是 switch.js

中的 console.log

当我这样做时,它说客户端未定义,所以我尝试合并 js 和 运行 节点,它说 $ 未定义。我尝试在节点应用程序中包含 jquery,它说缺少 window。所以我需要一种方法来使用节点为这个 Web 应用程序提供服务,并按原样使用 jquery 等。

基于 websocket 的 MQTT 是一种困难的方法。使用 socket.io 可以完成相同的工作。它是一个基于 js 的库,提供主题发布和订阅消息的功能。试一试。