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
packagecom.ociweb;importcom.ociweb.gl.api.*;publicclassLEDClientimplementsGreenApp{privateMQTTBridge mqttConfig; // Define the topics.privatefinalString toggleLightTopic ="light/toggle";privatefinalString lightStatusTopic ="light/status";@OverridepublicvoiddeclareConfiguration(Builderconfig){ // 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);}@OverridepublicvoiddeclareBehavior(GreenRuntimeruntime){ // 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 =newLightBehavior(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: