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
Enabled the WebSocket support on my MQTT protocol, and declare host as
ws://sample-mqtt.com.ph:port/mqtt
.I have declared my client like so: