MQTT and P5 Example Code

Hi, all is it possible to receive MQTT data with P5.js?

I found this code but it does not seem to connect with my broker.

var mqtt;
var reconnectTimeout = 2000;
var host  = "127.0.0.1";
var port  = 1883;

function setup()
{

MQTTconnect(); //connect to MQTT Server
createCanvas(100,100);
background(200,0,0);



}

function draw()
{

}

function onConnect()
{
//once a connection has been made make a subscription and send a message.
  console.log("Connected");
  //mqtt.subscribe("sensor1");
  message = new Paho.MQTT.Message("Hello World"); //Message
  message.destinationName = "sensor1"; //publish topic
  mqtt.send(message); //publish Message
}

function MQTTconnect()
{
  console.log("connecting to " + host + " " + port);
  mqtt = new Paho.MQTT.Client(host,port,"ClientJs"); //create client object
  //document.write("connecting to " + host);
  var options = {
    timeout: 3,
    onSuccess: onConnect,
  };
  mqtt.connect(options); //connect
}

1 Like

I guess you are using a library like this?

https://editor.p5js.org/JonnyJo/sketches/3mVr0vnZg

it would be helpful if you write what library you are using :slight_smile: and what MQTT broker are you using, and how did you set it up?

1 Like

Fixed it. The Paho Matt library uses web socket port for Mqtt, not the standard port. This fixed my problem.

It would be great if you can share the complete code (and mark as solution) so it’s helpful for others :slight_smile:

1 Like

The code posted works. It was my router that was blocking the connection.

I have not replied on here as no one ever answers my posts at this one has been up for a bit. Ow.

1 Like

@Jhdgkss

hello. I enjoyed reading your article.
By any chance, can I get the MQTT library material?
I wonder.