Processing 3.3.3 |
Setup mqtt for Processing
In order to get mqtt working with processing do the
following.
(1) Downloaded Processing 3.3.3 Link
(2) Download the “MQTT library for Processing based on
the Eclipse Paho project” Link
The following example allows for a Mosquitto Broker Username and Password and is merely based on the Joël Gähwiler example from the above link.
Where:
The URL of my Mosquitto Broker is: 192.168.5.102
Mosquitto Username: fred
Mosquitto Password: 1234
Mosquitto Password: 1234
Code
import mqtt.*;
MQTTClient client;
PFont myFont;
void setup() {
client = new
MQTTClient(this);
client.connect("mqtt://fred:1234@192.168.5.102",
"processingClient");
client.subscribe("#"); //subscribe to all mqtt topics
size(640, 360);
background(0);
myFont =
createFont("Georgia", 32);
textFont(myFont);
}
void draw() {
}
void keyPressed() {
client.publish("/Example", "One");
}
void messageReceived(String topic, byte[] payload) {
println("new
message: " + topic + " - " + new String(payload));
background(0);
String s = topic
+ " - " + new String(payload);
text(s, 0, 0,
640, 360); // Text wraps within text box
}
To add some “ControlP5” buttons:
ControlP5 buttons
can be added to allow you to send out various different mqtt messages etc.
import mqtt.*;
import controlP5.*;
// import controlP5 library
ControlP5 controlP5;
// controlP5 object
MQTTClient client;
PFont myFont;
void setup() {
client = new
MQTTClient(this);
client.connect("mqtt://fred:1234@192.168.5.102",
"processingClient2");
client.subscribe("#"); //subscribe to all mqtt topics
size(640, 360);
background(0);
myFont =
createFont("Georgia", 32);
textFont(myFont);
smooth();
controlP5 = new
ControlP5(this);
controlP5.addButton("Open")
.setValue(0)
.setPosition(200,200)
.setSize(200,19);
controlP5.addButton("Stop")
.setValue(0)
.setPosition(200,220)
.setSize(200,19);
controlP5.addButton("Close")
.setValue(0)
.setPosition(200,240)
.setSize(200,19);
}
void draw() {
}
public void controlEvent(ControlEvent theEvent) {
println(theEvent.getController().getName());
}
// function Open will receive changes from
// controller with name Open
public void Open(int theValue) {
println("a
button event from Open: "+theValue);
client.publish("START", "SomePayloadForTheStartTopic");
}
public void Stop(int theValue) {
println("a
button event from Open: "+theValue);
client.publish("STOP", " SomePayloadForTheStopTopic ");
}
public void Close(int theValue) {
println("a
button event from Open: "+theValue);
client.publish("CLOSE", " SomePayloadForTheCloseTopic ");
}
void keyPressed() {
client.publish("/Example", "Two");
}
void messageReceived(String topic, byte[] payload) {
println("new
message: " + topic + " - " + new String(payload));
background(0);
String s = topic
+ " - " + new String(payload);
text(s, 0, 0,
640, 360); // Text wraps within text box
}