I have a react app that I need to connect to control an ESP32. The first thing I thought was to use MQTT (HiveMQ) to communicate with the ESP. The problem is that an error is being returned in loop in my browser console
WebSocket connection to 'ws://79642a966da549118f1128bb058d42ce.s2.eu.hivemq.cloud:8883/' failed:
If anyone knows what is happening or has any better solution to communicate with the ESP32 using JS it would be incredible too. Follow my index.tsx file
export default function Home() {
const options = {
username: 'gio.nacimento',
password: 'Gio133ebu',
};
const mqtt = require('mqtt');
// connect to your cluster, insert your host name and port
const client = mqtt.connect('tls://79642a966da549118f1128bb058d42ce.s2.eu.hivemq.cloud:8883', options);
// prints a received message
client.on('message', function(topic: any, message: any) {
console.log(String.fromCharCode.apply(null, message)); // need to convert the byte array to string
});
// reassurance that the connection worked
client.on('connect', () => {
console.log('Connected!');
});
// prints an error message
client.on('error', (error: any) => {
console.log('Error:', error);
});
// subscribe and publish to the same topic
client.subscribe('messages');
client.publish('messages', 'Hello, this message was received from the app!');
const test = (): void =>{
client.subscribe('messages');
client.publish('messages', 'Hello, this message was received from the app by clicking!');
}
return (
<div className='flex justify-center items-center flex-col'>
<h1>Controle de LED</h1>
<button onClick={test}>Test server</button>
</div>
)
}
Don't know if this can be a problem but I'm using React + Next in my app. I already follow all the instructions at HiveMq site but the error persists.
As mentioned by some other members, the WebSocket port in the HiveMQ Cloud broker is 8884, which is different from the usual MQTT (TLS) port of 8883 (1). Depending on your library, you may need to use the prefix wss:// or omit the prefix completely when connecting to HiveMQ Cloud's WebSocket port.
If you have any further questions or concerns, I would recommend visiting the HiveMQ Community Forum (2). Our community members and HiveMQ experts are always happy to help with any questions related to HiveMQ.
References:
HiveMQ Cloud Documentation. "WebSocket and MQTT ports." HiveMQ Cloud. Retrieved from https://www.hivemq.com/docs/cloud/enterprise/introduction/limits/#websocket-and-mqtt-ports
HiveMQ Community Forum. Retrieved from https://community.hivemq.com/