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
}

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?

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:

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.