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:
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: