控制初始化

This commit is contained in:
mmc
2026-05-12 10:34:50 +08:00
parent b62c1725ed
commit 74107e7020
6 changed files with 2683 additions and 113 deletions

53
src/components/useMqtt.ts Normal file
View File

@@ -0,0 +1,53 @@
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);
// },
// });