项目环境
vite
react
ahooks
mqtt
调试工具有很多, 我这里推荐 mqttx
安装mqtt
pnpm i -S mqtt@4.0.1
项目开发时,mqtt的最新版本有兼容性问题, 最后选择4.0.1版本
引用mqtt
import * as mqtt from 'mqtt/dist/mqtt.min'
连接mqtt
参考文档: react连接mqtt
const host = '0.0.0.0:8886'
const mqttOption = {
username: user,
password: pass,
rejectUnauthorized: false,
// keepalive: 30,
}
// host 机器端
// mqttOption mqtt配置参数
const mqttConnect = (host, mqttOption) => {
setState({
client: mqtt.connect(host, mqttOption),
clientSign: 1, // 触发useEffect更新
})
}
初始化
useUpdateEffect(() => {
if (state.clientSign) {
state.client.on('connect', () => {
console.log('1-connect') // 订阅
mqttSub()
})
state.client.on('error', (err) => {
console.log('2-error', err) // 报错
state.client.end()
})
state.client.on('reconnect', () => {
console.log('3-reconnect') // 重连
})
state.client.on('message', (topic, message) => {
const str = Utf8ArrayToString(message) // 接收值转utf8
let c = null
try {
c = JSON.parse(str)
} catch (error) {
console.log(error)
return
}
console.log('4-message', c) // 接收
mqttMessage(c)
})
}
}, [state.clientSign])
订阅
// 订阅
const mqttSub = () => {
if (state.client) {
const { rmapc } = state.robotMqtt.pipe
state.client.subscribe(rmapc, {}, (error) => {
if (error) {
console.log('订阅失败', error)
return
}
console.log('订阅成功')
})
}
}
取消订阅
const mqttUnSub = () => {
if (state.client) {
const { rmapc } = state.robotMqtt.pipe
state.client.unsubscribe(rmapc, (error) => {
if (error) {
console.log('取消订阅失败', error)
return
}
console.log('取消订阅成功')
})
}
}
断开连接
// 断开链接
const mqttDisconnect = () => {
if (state.client) {
state.client.end((e) => {
console.log('断开链接')
})
}
}
发送
const data={
type:'car'
}
// rmaps 发送通道
// req 发送内容
const mqttPublish = (data) => {
state.client.publish(rmaps, JSON.stringify(data), (error) => {
if (error) {
console.log('发布失败: ', error)
}
console.log('^发布成功')
})
}
接收
const mqttMessage = (res) => {}