54 lines
1.1 KiB
TypeScript
54 lines
1.1 KiB
TypeScript
|
|
import { useEffect, useRef } from 'react';
|
||
|
|
import mqtt, { MqttClient } from 'mqtt';
|
||
|
|
|
||
|
|
interface Options {
|
||
|
|
url: string;
|
||
|
|
topic: string | string[];
|
||
|
|
onMessage: (topic: string, message: string) => void;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function useMqtt({ url, topic, onMessage }: Options) {
|
||
|
|
const clientRef = useRef<MqttClient | null>(null);
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
const client = mqtt.connect(url, {
|
||
|
|
reconnectPeriod: 3000,
|
||
|
|
username: 'maibu',
|
||
|
|
password: 'maibu',
|
||
|
|
clean: true,
|
||
|
|
});
|
||
|
|
|
||
|
|
clientRef.current = client;
|
||
|
|
|
||
|
|
client.on('connect', () => {
|
||
|
|
console.log('MQTT connected');
|
||
|
|
client.subscribe(topic);
|
||
|
|
});
|
||
|
|
|
||
|
|
client.on('message', (t, payload) => {
|
||
|
|
onMessage(t, payload.toString());
|
||
|
|
});
|
||
|
|
|
||
|
|
client.on('error', err => {
|
||
|
|
console.error('MQTT error', err);
|
||
|
|
});
|
||
|
|
|
||
|
|
return () => {
|
||
|
|
client.end(true);
|
||
|
|
};
|
||
|
|
}, [url, JSON.stringify(topic)]);
|
||
|
|
|
||
|
|
return clientRef;
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
/* 使用 */
|
||
|
|
// useMqtt({
|
||
|
|
// url: 'wss://broker.emqx.io:8084/mqtt',
|
||
|
|
// topic: 'robot/status',
|
||
|
|
// onMessage: (_, message) => {
|
||
|
|
// setMsg(message);
|
||
|
|
// },
|
||
|
|
// });
|