# MQTT Client

GreenLightning fully supports the [MQTT protocol](http://mqtt.org/). On this page, learn how to build a simple MQTT client. We recommend using a broker such as [mosquitto](https://mosquitto.org/) to do your testing with.

Please refer to the [GreenLightning-API](https://github.com/oci-pronghorn/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:

{% code title="LEDClient.java" %}

```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);
    }
  
} 
```

{% endcode %}

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

{% code title="LightBehavior.java" %}

```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;
    }
}
```

{% endcode %}

�


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://oci-pronghorn.gitbook.io/greenlightning/chapter-6-clients/mqtt-client.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
