新建vue3项目
# 新建 vite + vue3的项目
npm init vue@latest
yarn 安装依赖包
yarn add mqtt
初探 - 连接阿里云物联网平台
代码:
<template>
<div>
<h1>LED - IOT</h1>
<button @click="connectToBroker">Connect</button>
<button @click="subscribe">Subscribe</button>
<button @click="publish">Publish</button>
</div>
</template>
<script>
import { ref, onMounted } from 'vue'
import mqtt from 'mqtt'
import hexHmacSha1 from '../utils/hex_hmac_sha1'
export default {
name: 'LED',
setup() {
const deviceConfig = {
productKey: 'xx',
deviceName: 'led_1',
deviceSecret: 'xxxx',
regionId: 'cn-shanghai', // 根据自己的区域替换
}
const client = ref(null)
const connectToBroker = () => {
const options = initializeMqttOptions(deviceConfig)
console.log(options)
client.value = mqtt.connect(
'wss://productKey.iot-as-mqtt.cn-shanghai.aliyuncs.com',
options
)
client.value.on('connect', () => {
console.log('Successfully connected to the server')
})
client.value.on('message', (topic, message) => {
let msg = message.toString()
console.log('Received message: ' + msg)
// Close the connection: client.value.end()
})
}
const publish = ()=>{
if (client.value) {
client.value.publish(`/sys/${deviceConfig.productKey}/${deviceConfig.deviceName}/thing/event/property/post`, {
"NightLightSwitch": "0"
})
}
}
const subscribe = ()=>{
client.value.subscribe('/productKey/deviceName/user/get', (err) => {
if (!err) {
console.log('Successfully subscribed!')
}
})
}
const initializeMqttOptions = (deviceConfig) => {
const params = {
productKey: deviceConfig.productKey,
deviceName: deviceConfig.deviceName,
timestamp: Date.now(),
clientId: Math.random().toString(36).substr(2),
}
const options = {
keepalive: 60,
clean: true,
protocolVersion: 4,
}
options.password = generateHmacSha1Signature(params, deviceConfig.deviceSecret)
options.clientId = `${params.clientId}|securemode=2,signmethod=hmacsha1,timestamp=${params.timestamp}|`
options.username = `${params.deviceName}&${params.productKey}`
return options
}
const generateHmacSha1Signature = (params, deviceSecret) => {
let keys = Object.keys(params).sort()
const list = []
keys.forEach((key) => {
list.push(`${key}${params[key]}`)
})
const contentStr = list.join('')
return hexHmacSha1(deviceSecret, contentStr)
}
onMounted(() => {
connectToBroker()
})
return {
connectToBroker,
initializeMqttOptions,
generateHmacSha1Signature,
publish
}
},
}
</script>
<style></style>
放弃探索阿里云物联网平台,好像有不少的坑...
转向自己搭建emqx
参考文章
【精选】微信小程序使用MQTT.js连接阿里云IoT物联网平台_阿里 mqtt js版本-CSDN博客
踩的坑
Node.js和浏览器的不同
注意是MQTT基于的协议不同
Node.js中mqtt是基于tcp
而浏览器的mqtt是基于websocket
因此配置的端口号和路径会有所不一样。
进阶 - 转向 本地emqx
下载emqx:
启动emqx:
bin/emqx start
打开管理后台:
账号密码:
admin
public
示例代码:
// Node.js
const mqtt = require('mqtt');
// MQTT连接地址
const broker = 'mqtt://a1sIKncPskh.iot-as-mqtt.cn-shanghai.aliyuncs.com:1883';
// MQTT连接选项
const options = {
clientId: 'a1sIKncPskh.led_1|securemode=2,signmethod=hmacsha256,timestamp=1699678758528|',
username: 'led_1&a1sIKncPskh',
password: '74ee471ac5e5ac4b99bbb82652905127c2ecca77c38d198b114fd5c4bfee9158',
keepalive: 60,
clean: true,
};
// 创建MQTT客户端
const client = mqtt.connect(broker, options);
// 连接成功回调
client.on('connect', function () {
console.log('Connected to Aliyun IoT Platform');
});
// 订阅主题
client.subscribe('your_topic');
// 接收消息回调
client.on('message', function (topic, message) {
console.log('Received message:', message.toString());
});
// 发布消息
client.publish('your_topic', 'Hello, IoT Platform');
标签:Vue,const,mqtt,MQTT,client,params,options,搭建
From: https://www.cnblogs.com/yecss/p/17832727.html