Giter VIP home page Giter VIP logo

processing-mqtt's Introduction

processing-mqtt

MQTT library for Processing based on the Eclipse Paho project

This library bundles the Java Client library of the Eclipse Paho project and adds a thin wrapper to get a Processing like API.

Download the latest version of the library.

Or even better use the Library Manager in the Processing IDE.

Example

This example sketch connects to the public shiftr.io instance and sends a message on every keystroke. After starting the sketch you can find the client here: https://www.shiftr.io/try.

import mqtt.*;

MQTTClient client;

void setup() {
  client = new MQTTClient(this);
  client.connect("mqtt://public:[email protected]", "processing");
}

void draw() {}

void keyPressed() {
  client.publish("/hello", "world");
}

void clientConnected() {
  println("client connected");

  client.subscribe("/hello");
}

void messageReceived(String topic, byte[] payload) {
  println("new message: " + topic + " - " + new String(payload));
}

void connectionLost() {
  println("connection lost");
}

API

Instantiate a new client by supplying the parent applet:

MQTTClient client = new MQTTClient(PApplet parent);
  • The constructor expects the following method to be declared on the parent applet: void messageReceived(String topic, byte[] payload). That callback will then be invoked in the future with incoming messages.
  • Additionally, the following callbacks will be detected: void clientConnected() and void connectionLost() and executed appropriately.

Alternatively you can provide your own Listener class instead of relying on global methods:

MQTTClient client = new MQTTClient(PApplet parent, Listener listener);

Set the will message that gets transmitted to the server in all subsequent connect commands:

void client.setWill(String topic, String payload);
void client.setWill(String topic, String payload, int qos, boolean retained);
  • The QoS level and retained flag default to 0 and false respectively.

Connect to the supplied broker by parsing the URL and setting the optionally supplied client id and clean session flag:

void client.connect(String brokerURI);
void client.connect(String brokerURI, String clientId);
void client.connect(String brokerURI, String clientId, boolean cleanSession);
  • A client id will be generated if needed and the clean session flag defaults to true.

Publish a message to the broker using the supplied topic and the optional payload in form of a String or byte-array. If available it will set the QoS level as well as the retained flag appropriately.

void client.publish(String topic);
void client.publish(String topic, String payload);
void client.publish(String topic, String payload, int qos, boolean retained);
void client.publish(String topic, byte[] payload);
void client.publish(String topic, byte[] payload, int qos, boolean retained);
  • The QoS level and the retained flag default to 0 and false respectively.

Subscribe to the supplied topic using the optionally provided QoS level that defaults to 0:

void client.subscribe(String topic);
void client.subscribe(String topic, int qos);

Unsubscribe from the supplied topic:

void client.unsubscribe(String topic);

Disconnect from the broker:

void client.disconnect();

Notes

  • If you're running the sketch via the Android Mode you need to set the INTERNET permission in Android > Sketch Permissions.

processing-mqtt's People

Contributors

256dpi avatar benmens avatar eadf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

processing-mqtt's Issues

Websocket (wss://) is unsupported

The Java Client library of the Eclipse Paho project support websockets. But the processing library replaces all scheme identifiers with "tcp://" and this doesn't work for websockets. Please let the library handle the schemes like in my pull request: #15

Crash of my processing program caused by the library timeout

Hello, on a recurring basis, my processing software is being stopped due to Timeout problems, why success it? why a timeout problem take down my program? is possible increase the timeout?

Error 1:

Sending: Topic message: Game/inbox/2N6PXV - Publish message: 20210301124307;0;0
java.lang.RuntimeException: [MQTT] Failed to publish: Tiempo de espera excedido al esperar una respuesta del servidor
	at mqtt.MQTTClient.publish(Unknown Source)
	at mqtt.MQTTClient.publish(Unknown Source)
	at MY_Game.publisher_mqtt(MY_Game.java:6688)
	at MY_Game.dev_actuador(MY_Game.java:1591)
	at MY_Game.resetSala(MY_Game.java:2506)
	at MY_Game.Config_game(MY_Game.java:300)
	at MY_Game.mouseReleased(MY_Game.java:187)
	at processing.core.PApplet.mouseReleased(PApplet.java:2849)
	at processing.core.PApplet.handleMouseEvent(PApplet.java:2758)
	at processing.core.PApplet.dequeueEvents(PApplet.java:2652)
	at processing.core.PApplet.handleDraw(PApplet.java:2493)
	at processing.awt.PSurfaceAWT$12.callDraw(PSurfaceAWT.java:1547)
	at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:313)
Caused by: Tiempo de espera excedido al esperar una respuesta del servidor (32000)
	at org.eclipse.paho.client.mqttv3.internal.Token.waitForCompletion(Token.java:112)
	at org.eclipse.paho.client.mqttv3.MqttToken.waitForCompletion(MqttToken.java:67)
	... 13 more

Error 2:

Sending: Topic message: Game/ACK/ - Publish message: 20210301172352;ACK
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
	at mqtt.MQTTClient.draw(Unknown Source)
	at jdk.internal.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	at processing.core.PApplet$RegisteredMethods.handle(PApplet.java:1436)
	at processing.core.PApplet$RegisteredMethods.handle(PApplet.java:1429)
	at processing.core.PApplet.handleMethods(PApplet.java:1628)
	at processing.core.PApplet.handleDraw(PApplet.java:2495)
	at processing.awt.PSurfaceAWT$12.callDraw(PSurfaceAWT.java:1547)
	at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:313)
Caused by: java.lang.reflect.InvocationTargetException
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	... 10 more
Caused by: java.lang.RuntimeException: [MQTT] Failed to publish: Tiempo de espera excedido al esperar una respuesta del servidor
	at mqtt.MQTTClient.publish(Unknown Source)
	at mqtt.MQTTClient.publish(Unknown Source)
	at MY_Game.publisher_mqtt(MY_Game.java:6694)
	at MY_Game.messageReceived(MY_Game.java:6644)
	... 14 more
Caused by: Tiempo de espera excedido al esperar una respuesta del servidor (32000)
	at org.eclipse.paho.client.mqttv3.internal.Token.waitForCompletion(Token.java:112)
	at org.eclipse.paho.client.mqttv3.MqttToken.waitForCompletion(MqttToken.java:67)
	... 18 more

Can you help me to make it stable?

How to instantiate multiple clients connecting to different brokers from one .pde

It's not really an error but more of a request to show an example for a not so special use case:

Scenario:
I have a sketch and it should connect to 2 different MQTT brokers.

To instantiate one instance:

MQTTClient localClient;
localClient = new MQTTClient(this);

And then the global events from the interface are, as described in your MQTTListener.java are:

void clientConnected();
void connectionLost();
void messageReceived(String topic, byte[] payload);

Now to instantiate a new client in the same sketch, first I can instantiate another something like this:

MQTTClient remoteClient;

Now the question is, what should be here?
remoteClient = new MQTTClient(this, <Listener??>);
And where to define that with my custom event functions and how ?
An example would be awesome, as I don't know much of Java.

How to connect to a broker that requires a username and password?

I use CloudMQTT as my broker. It requires me to connect to it using a username and password.
client.connect only has the following options:

  • public void connect(String brokerURI)
  • public void connect(String brokerURI, String clientID)
  • public void connect(String brokerURI, String clientId, boolean cleanSession)

I don't know how to connect to my broker as it doesn't give me a URI. It gives me the following details:

  • Host (a url)
  • Username
  • Password
  • Port

I can't figure out if I can use MqttConnectOptions or MqttConnectOptions.userame to set my client.connect options.

Please help.

Status

Hi, I found very useful this library as it works perfectly. But I find an issue with it.
I did not find any way of getting the status of the connection. Also when connecting (with not internet), the library passes the error as a message which seems imposible to catch with any function. The thing is if there is any function that returns the status of the connection?

Thanks

When checking topic in messageRecieved function boolean always returns false

I have written this piece of test code

I need to check the content of the message and the topic for various actions to occur
"/telemetry" is a topic subscribed to, and it is receiving those messages, but when I try and check the content of either the topic or the message, I always get a false
Is this an issue with Java that I am missing?

void messageReceived(String topic, byte[] payload) {
   String rMsg =  new String(payload); 

   println("new message: " + topic + " - " + rMsg);
    if(topic == "/telemetry"){
      println("telemetry received");
    }
    println (topic == "/telemetry");
  }

Update

  • Add note that the topics must start with a /.

Any implementation to use wss over TLS?

How can I use a broker that uses wss://.. and has a cert file associated with it with this library?
For using ws://.. and mqtt://.., no problem.. :)
But to use tcp/tls or wss, I didn't see any implementation requiring ca.cert file in the MQTTClient.java .
Am I correct that this has not been implemented yet and if so, is there any future plan to accomodate secure connections?

Missing Callback in Python Mode

add_library('mqtt')
number = 0
def messageReceivedMethod(topic, payload):
    global number 
    number += 1
    print(topic, payload)
    
def clientConnected():    
    global client
    print('client connected')
    # client.subscribe("/led/show")
    
def connectionLost():
    pass
    print('lost')
    
def setup():
    global client
    
    dir(MQTTClient)
    client = MQTTClient(this)
    dir(client)
    # client.clientConnectedMethod = connectionLost
    client.connect("mqtt://eeyi.org","processing")
    # client.setCallback(messageReceived)
    size(600, 600)
    noLoop()
    noStroke()
    # colorMode(HSB)
    stroke(0)
    rectMode(CENTER)
    noFill()
def draw():
    global number 
    
    background(255)
    fill(255, 0, 0)
    text(number, 10, 10)
    with pushMatrix():
        translate(width/2, height/2)
        
        for i in range(12):
            with pushMatrix():
                rotate(radians(30*i))
                # line(0,0,width,0)
                ellipse(0, 150, 30, 30)
def mouseClicked():
    client.publish("/led/show")
    

                    
                    

Receive all incoming messages

Hello there! Thanks for this nice library

Is there a way to receive all incoming messages, like OSC behavior, or we need to know exactly the name of channels to subscribe?

Thanks in advance,

Marlus

request

Hii dear, your Library works out of box with processing...
which QoS level you have implemented currently?
if it is more than 0 than how to change it in code...?
as once net is disconnected and even sending mqtt publish... I am getting it on other PC when the net connects again so i think its not QoS0...

topic use of *

play from processing 3.5.3. / raspberry pi /

i wanted to try

String mqtt_out    = "pcu/sensor/out";
String mqtt_in      = "pcu/in";
String mqtt_sub    = "/";    // also try  /*   or  *  or pcu/*   // test subscribe some topic

client.subscribe(mqtt_sub);

but not catch any of it unless i use the exact topic like in mqtt_out or mqtt_in
did i miss something?

Example not working with version 1.6.3

The example is not working with the latest version available on library manager (1.6.3).
I would recommend to either update the version on library manager or to put a reference to the issue.

issues with binary messages

Hello, and thank you for the very nice MQTT framework you have developed.
Consider I'm new to MQTT so what I'm writing might miss some basic information :-)

I'm doing some tests both with Processing and Arduino (using ESP8266)
My intention is to transmit a 3 byte binary payload.
I have upload my code in this repo: https://github.com/marcobrianza/wemakecolors/blob/master/Processing/testMQTT/testMQTT.pde

I made some tests both with shiftr and mosquitto server and I see a different behaviour:
The issue happens if I send a binary value above 127.
With shiftr server the subscriber receives a message of 5 byes instead of 3.
With mosquitto the message is of 3 bytes, but the byte is wrong.

This makes me think that there is something wrong both on the shiftr server and the lib.

With Arduino the problem is similar, but I could not find a way to connect to test.mosquitto.org so cannot see if the lib is correct in this case.

thank you
Marco

Server related questions

Server related questions

hello. I don't know, but I want to ask a question.

Server: https://www.shiftr.io/try.
is this run by you?
Or where do you operate from?

Can I use it for free for life? I'm asking because I don't know.

[MQTT] Failed to connect:: Timed out waiting for a response from the server

Hi,

regardless of my own server or using the example server configuration I get the error below.

RuntimeException: [MQTT] Failed to connect:: Timed out waiting for a response from the server
RuntimeException: [MQTT] Failed to connect:: Timed out waiting for a response from the server
RuntimeException: [MQTT] Failed to connect:: Timed out waiting for a response from the server

Receive Messages in Python Mode

I always get the message "messageReceived callback not found!". How do I need to call "client = MQTTClient(this)" to register the callback function correctly?

Thank you for your help!

OutOfMemoryError after multiple connection fails

I'm facing an issue that crashes Processing if the connection to the MQTT server fails. (For example it can be tested if the network is down).

I have attached the screenshot of Processing and the code I use. Maybe there is a workaround with a different code that retries to reconnect.

error2

String mqttServer = "broker.shiftr.io";
String T_TEST="testing/123";

import mqtt.*;

int isConnected=0; // -1=trying to connect, 0=not connected, 1=connected

MQTTClient client;


// ---- MQTT callbacks
void clientConnected() {
  println("mqtt connected");
  isConnected=1;
  client.subscribe(T_TEST);
}
void messageReceived(String topic, byte[] payload) {
  String pl=new String(payload);
  println("mqtt new message: " + topic + " - " + pl);
}

void connectionLost() {
  println("mqtt connection lost");
  isConnected=0;
}
//----------

void setup() {
  client = new MQTTClient(this);

  size(255, 255);
  background(0, 200, 200);
  frameRate(1);
}

int counter=0;
void draw() {
  sendMQTTmessage(T_TEST, str(counter));
  counter++;
}


void sendMQTTmessage(String Topic, String Payload) {
  if (isConnected==1) {
    try {
      client.publish(Topic, Payload);
      println("mqtt sending message:", Topic, Payload);
    }
    catch(RuntimeException e) {
      e.printStackTrace();
    }
  } else {
    println(millis(), "mqtt not connected");
    connectMqtt();
  }
}


void connectMqtt() {

  if (isConnected==0) {
    try {
      isConnected=-1;
      String clientID="pippo01";
      println("mqtt trying to connect: ", clientID);
      client.connect("mqtt://try:try@"+mqttServer, clientID);
    }
    catch(RuntimeException e) {
      isConnected=0;
      e.printStackTrace();
    }
  }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.