| 10 | } |
| 11 | |
| 12 | function useMqtt({ |
| 13 | uri, |
| 14 | options = {}, |
| 15 | topicHandlers = [{ topic: "", handler: ({ topic, payload, packet }) => {} }], |
| 16 | onConnectedHandler = (client) => {}, |
| 17 | }: useMqttProps) { |
| 18 | const clientRef = useRef<MqttClient | null>(null); |
| 19 | |
| 20 | useEffect(() => { |
| 21 | if (clientRef.current) return; |
| 22 | if (!topicHandlers || topicHandlers.length === 0) return () => {}; |
| 23 | |
| 24 | try { |
| 25 | clientRef.current = options |
| 26 | ? MQTT.connect(uri, options) |
| 27 | : MQTT.connect(uri); |
| 28 | } catch (error) { |
| 29 | console.error("error", error); |
| 30 | } |
| 31 | |
| 32 | const client = clientRef.current; |
| 33 | topicHandlers.forEach((th) => { |
| 34 | client?.subscribe(th.topic); |
| 35 | }); |
| 36 | client?.on("message", (topic: string, rawPayload: any, packet: any) => { |
| 37 | const th = topicHandlers.find((t) => t.topic === topic); |
| 38 | let payload; |
| 39 | try { |
| 40 | payload = JSON.parse(rawPayload); |
| 41 | } catch { |
| 42 | payload = rawPayload; |
| 43 | } |
| 44 | if (th) th.handler({ topic, payload, packet }); |
| 45 | }); |
| 46 | |
| 47 | client?.on("connect", () => { |
| 48 | if (onConnectedHandler) onConnectedHandler(client); |
| 49 | }); |
| 50 | |
| 51 | return () => { |
| 52 | if (client) { |
| 53 | topicHandlers.forEach((th) => { |
| 54 | client.unsubscribe(th.topic); |
| 55 | }); |
| 56 | client.end(); |
| 57 | } |
| 58 | }; |
| 59 | // eslint-disable-next-line react-hooks/exhaustive-deps |
| 60 | }, []); |
| 61 | } |
| 62 | |
| 63 | export default useMqtt; |