marhg
marhg

Reputation: 687

Publish event via MQTT

I'm new using MQTT and I ran the Publisher/Subscriber example. I wonder if I can send events as well. For example, I have a SoundEvent class

class SoundEvent { 

    private int value;

    public SoundEvent(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

Then a SoundSensor class (a simulation sensor), which generates random values, so every time a value is generated, I want to send the value to the Subscriber as a (SoundEvent value)

Then the Subscriber can do something with the value, eg.

public class Subscriber {

    public void highTraffic(SoundEvent e) {
        if (e.value == 10) {
            System.out.println("High"));
        }
    }
}   

But what I have only seen in MQTT, is sending MQTT Messages, is it possible to send an Event? Or am I confused with the event-based idea?

If someone has some examples, that will be very useful

Thank you in advance

Upvotes: 0

Views: 603

Answers (1)

hardillb
hardillb

Reputation: 59826

MQTT can be used to publish anything you can encode as an array of bytes.

In the case of the SoundEvent you have described this is just a wrapper round a Integer value, you could just publish the integer and create a new SoundEvent at the Subscriber with this value.

The other option would be to make SoundEvent implement Serializable, serialize the object to a byte array and send this in the MQTT message where it can be deserialized at the subscriber.

Given how simple SoundEvent is I would just go with sending the Interger value it wraps and save the Serialization of objects for more complext objects.

You can of course miss out the Java Serialization all together and create language neutral representations of the data in the object e.g. JSON or XML and publish these which would make the messages more easily commensurable by subscribers not implemented in Java

Upvotes: 1

Related Questions