react-mqtt package

front end_little chestnut 2023-01-25 21:27:31 阅读数:189

react-mqttreactmqttpackage
import {
 useState, useEffect } from 'react';
import * as mqtt from "mqtt/dist/mqtt.min";
function useMqtt() {

const [client, setClient] = useState(null);
const [payload, setPayload] = useState({
});
const [connectStatus, setConnectStatus] = useState('Connect');
const [isSubed, setIsSub] = useState(false);
useEffect(() => {

if (client) {

client.on('connect', () => {

setConnectStatus('Connected');
});
client.on('error', (err) => {

console.error('Connection error: ', err);
client.end();
});
client.on('reconnect', () => {

setConnectStatus('Reconnecting');
});
client.on('message', (topic, message) => {

const payload = {
 topic, message: JSON.parse(message.toString()) };
setPayload(payload);
});
}
}, [client]);
// 连接mqtt
const mqttConnect = (host, mqttOption) => {

setConnectStatus('Connecting');
setClient(mqtt.connect(host, mqttOption));
};
// 断开连接
const mqttDisconnect = () => {

if (client) {

client.end(() => {

console.log('断开连接成功!!');
});
}
}
// 订阅消息
const mqttSub = (subscription) => {

if (client) {

const {
 topic, qos } = subscription;
client.subscribe(topic, {
 qos }, (error) => {

if (error) {

console.log('Subscribe to topics error', error)
return
}
console.log('订阅消息===>', topic, qos);
});
}
};
// 取消订阅
const mqttUnSub = (subscription) => {

if (client) {

const {
 topic } = subscription;
client.unsubscribe(topic, error => {

if (error) {

console.log('Unsubscribe error', error)
return
}
console.log('取消订阅成功!!');
});
}
};
return {

mqttConnect,
payload,
connectStatus,
mqttSub,
mqttUnSub,
mqttDisconnect,
client,
setPayload
}
}
export default useMqtt;
版权声明:本文为[front end_little chestnut]所创,转载请带上原文链接,感谢。 https://qdmana.com/2023/025/202301252114385843.html