Skip to content

Instantly share code, notes, and snippets.

@sebbo2002
Created June 6, 2017 09:24
Show Gist options
  • Save sebbo2002/d7f4273d1591b074f88b41b30d1a9532 to your computer and use it in GitHub Desktop.
Save sebbo2002/d7f4273d1591b074f88b41b30d1a9532 to your computer and use it in GitHub Desktop.
IoT MQTT Übung Beispiel-Lösung Farbkreis
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class Main {
private static MqttClient client;
private static int interval = 5;
private static String topic = "GGBB";
private static void connect(String broker, String myId, MemoryPersistence persistence) throws MqttException {
client = new MqttClient(broker, myId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
System.out.print("- Connecting to broker ");
client.connect(connOpts);
System.out.println(" [Ok]");
}
private static void hue() throws MqttException {
System.out.println("- Start hue…");
for(int i = 1; i <= 10; i += 1) {
System.out.println(" - Round " + i);
set("red", 100);
set("blue", 0);
for(int d = 0; d <= 100; d += interval) {
set("green", d);
sleep();
}
for(int d = 100; d >= 0; d -= interval) {
set("red", d);
sleep();
}
for(int d = 0; d <= 100; d += interval) {
set("blue", d);
sleep();
}
for(int d = 100; d >= 0; d -= interval) {
set("green", d);
sleep();
}
for(int d = 0; d <= 100; d += interval) {
set("red", d);
sleep();
}
for(int d = 100; d >= 0; d -= interval) {
set("blue", d);
sleep();
}
}
}
private static void set(String color, int value) throws MqttException {
String content = color + ":" + value;
MqttMessage message = new MqttMessage(content.getBytes());
message.setQos(0);
client.publish(topic, message);
}
private static void sleep() {
try {
Thread.sleep(50);
}
catch(InterruptedException e) {
// ignore it for now :P
}
}
public static void main(String[] args) {
String broker = "tcp://iot.sebbo.net:1883";
String myId = "sebastian.pekarek";
MemoryPersistence persistence = new MemoryPersistence();
try {
connect(broker, myId, persistence);
hue();
set("red", 0);
set("green", 0);
set("blue", 0);
client.disconnect();
System.out.println("- Done 🙌");
System.exit(0);
}
catch(MqttException e) {
System.out.println("## Ups, there was an MQTT error:");
System.out.println("Reason: " + e.getReasonCode());
System.out.println("Message: " + e.getMessage());
System.out.println("Localized Message: " + e.getLocalizedMessage());
System.out.println("Cause: " + e.getCause());
System.out.println("Excpetion: " + e);
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment