()
| 5 | import useMqtt from "@/lib/useMqtt"; |
| 6 | |
| 7 | export default function Home() { |
| 8 | const [incomingMessages, setIncomingMessages] = useState<any[]>([]); |
| 9 | const addMessage = (message: any) => { |
| 10 | setIncomingMessages((incomingMessages) => [...incomingMessages, message]); |
| 11 | }; |
| 12 | const clearMessages = () => { |
| 13 | setIncomingMessages(() => []); |
| 14 | }; |
| 15 | |
| 16 | const incomingMessageHandlers = useRef([ |
| 17 | { |
| 18 | topic: "topic1", |
| 19 | handler: (msg: string) => { |
| 20 | addMessage(msg); |
| 21 | }, |
| 22 | }, |
| 23 | ]); |
| 24 | |
| 25 | const mqttClientRef = useRef<MqttClient | null>(null); |
| 26 | const setMqttClient = (client: MqttClient) => { |
| 27 | mqttClientRef.current = client; |
| 28 | }; |
| 29 | useMqtt({ |
| 30 | uri: process.env.NEXT_PUBLIC_MQTT_URI, |
| 31 | options: { |
| 32 | username: process.env.NEXT_PUBLIC_MQTT_USERNAME, |
| 33 | password: process.env.NEXT_PUBLIC_MQTT_PASSWORD, |
| 34 | clientId: process.env.NEXT_PUBLIC_MQTT_CLIENTID, |
| 35 | }, |
| 36 | topicHandlers: incomingMessageHandlers.current, |
| 37 | onConnectedHandler: (client) => setMqttClient(client), |
| 38 | }); |
| 39 | |
| 40 | const publishMessages = (client: any) => { |
| 41 | if (!client) { |
| 42 | console.log("(publishMessages) Cannot publish, mqttClient: ", client); |
| 43 | return; |
| 44 | } |
| 45 | |
| 46 | client.publish("topic1", "1st message from component"); |
| 47 | }; |
| 48 | |
| 49 | return ( |
| 50 | <div> |
| 51 | <h2>Subscribed Topics</h2> |
| 52 | {incomingMessageHandlers.current.map((i) => ( |
| 53 | <p key={Math.random()}>{i.topic}</p> |
| 54 | ))} |
| 55 | <h2>Incoming Messages:</h2> |
| 56 | {incomingMessages.map((m) => ( |
| 57 | <p key={Math.random()}>{m.payload.toString()}</p> |
| 58 | ))} |
| 59 | <button onClick={() => publishMessages(mqttClientRef.current)}> |
| 60 | Publish Test Messages |
| 61 | </button> |
| 62 | <button onClick={() => clearMessages()}>Clear Test Messages</button> |
| 63 | </div> |
| 64 | ); |
nothing calls this directly
no test coverage detected