MQTT Client

GreenLightning fully supports the MQTT protocol. On this page, learn how to build a simple MQTT client. We recommend using a broker such as mosquitto to do your testing with.

Please refer to the GreenLightning-API repo for more examples like this one.

Example

We want to build a very simple app that can do the following:

  • Subscribe to a topic that informs us about the status of an LED somewhere

  • Publish LED status every 5 seconds

  • Listen to the toggle message

Let's get started with our client. First, we need to update GreenApp to look like this:

LEDClient.java
package com.ociweb;

import com.ociweb.gl.api.*;

public class LEDClient implements GreenApp {
    private MQTTBridge mqttConfig;

    // Define the topics.
    private final String toggleLightTopic = "light/toggle";
    private final String lightStatusTopic = "light/status";

    @Override
    public void declareConfiguration(Builder config) {
        // Configure MQTT.
        mqttConfig = config.useMQTT("127.0.0.1", 1883, "LedController", 200)
                .cleanSession(true)
                .transmissionQoS(MQTTQoS.atLeastOnce)
                .keepAliveSeconds(10);

        // This is not needed, but if you visit the URL given to you in the console when you run this app,
        // you can see a detailed overview of your entire application in your browser.
        config.enableTelemetry(8099);
        
        // Set the pulse for the timer in seconds.
        config.setTimerPulseRate(5000);
    }

    @Override
    public void declareBehavior(GreenRuntime runtime) {
        // We subscribe to the topic that is sent when someone wants to toggle the light.
        runtime.bridgeSubscription(toggleLightTopic, toggleLightTopic, mqttConfig).setQoS(MQTTQoS.atLeastOnce);

        // We want to publish the status of the LED every 5 secs.
        runtime.bridgeTransmission(lightStatusTopic, lightStatusTopic, mqttConfig).setQoS(MQTTQoS.atLeastOnce);

        // Create the light behavior.
        LightBehavior light = new LightBehavior(runtime, lightStatusTopic);
        runtime.registerListener("LightBehavior", light)
                .addSubscription(toggleLightTopic, light::toggleLight)
                .addSubscription(lightStatusTopic, light::lightStatusUpdate);
    }
  
} 

Finally, create another file named LightBehavior.java to look like this:

LightBehavior.java
package com.ociweb;

import com.ociweb.gl.api.*;
import com.ociweb.pronghorn.pipe.ChannelReader;

public class LightBehavior implements PubSubMethodListener, TimeListener {
    // This will be bridged to MQTT inside LEDClient.java
    private PubSubFixedTopicService cmd;

    private boolean status = false; // current state of LED, false = off, true = on

    public LightBehavior(GreenRuntime runtime, String statusTopic) {
        // Need PubSub command channel
        cmd = runtime.newCommandChannel().newPubSubService(statusTopic);
    }

    public boolean lightStatusUpdate(CharSequence topic, ChannelReader payload) {
        // We received an update about the status of the light
        status = payload.readBoolean();
        System.out.println("Status update! Light on: " + status);

        return true;
    }

    @Override
    public void timeEvent(long time, int iteration) {
        // Every 5 seconds, publish the status of the LED.
        cmd.publishTopic(writer -> writer.writeBoolean(status));
    }

    public boolean toggleLight(CharSequence topic, ChannelReader payload) {
        // Read if light should be on or off from the payload
        status = payload.readBoolean();

        // TODO: do something here with an LED
        System.out.println("Toggle request! Status: " + status);

        return true;
    }
}

Last updated