skip to Main Content

I’m trying to connect to MQTT broker. I uses mqtt and here is my code:

// the MQTT_URL is just a sample structure
const MQTT_URL = 'mqtt://sample-mqtt.com.ph';
const MQTT_OPTIONS = {
    clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
    clean: true
}

export const onMqttConnect = () => {
    const client = mqttConnect(MQTT_URL, MQTT_OPTIONS);

    client.on('connect', () => {
        console.log('Connected to MQTT broker');

        client.subscribe('test/topic', (err) => {
            if (!err) {
                console.log('Subscribed to topic');
                client.publish('test/topic', 'Hello MQTT');
            }
        });
    })

    client.on('message', (topic, message) => {
        console.log(`Received message from ${topic}: ${message.toString()}`);
    });

    client.on('error', (error) => {
        console.log(`MQTT error: ${error}`);
    });

    client.on('close', () => {
        console.log('Connection to MQTT broker closed');
    });

    return () => {
        client.end();
    }
}

I call it inside useEffect and it return Connection to MQTT broker closed. However if I run it as single file of code like node mqtt.js it return Connected to MQTT broker.

I also try to use react-native-mqtt and it return an error stating [TypeError: Cannot convert null value to object], and paho-mqtt similar with above it return Connection to MQTT broker closed.

Thank you for the help!

2

Answers


  1. Chosen as BEST ANSWER

    Enabled the WebSocket support on my MQTT protocol, and declare host as ws://sample-mqtt.com.ph:port/mqtt.


  2. I have declared my client like so:

      import MQTT from "sp-react-native-mqtt";
    
      ...
    
      const mqttClient = await MQTT.createClient({
            clientId: "id_" + parseInt(id.toString()),
            uri: "mqtt://something.something:1883",
            host: "something.something",
            port: 1883,
            protocol: "mqtts",
            tls: false,
            keepalive: 60,
            protocolLevel: 0,
            clean: true,
            auth: true,
            user: "user",
            pass: "pass",
            automaticReconnect: true,
          });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search