MqttHandler.jadd 8.65 KB
Newer Older
1
aspect MqttHandler {
2
3
4
5
6
/**
 * Helper class to receive updates via MQTT and use callbacks to handle those messages.
 *
 * @author rschoene - Initial contribution
 */
7
public class MqttHandler {
René Schöne's avatar
René Schöne committed
8
  private static final int DEFAULT_PORT = 1883;
9

René Schöne's avatar
René Schöne committed
10
  private final org.apache.logging.log4j.Logger logger;
11
12
13
  private final String name;

  /** The host running the MQTT broker. */
René Schöne's avatar
René Schöne committed
14
  private java.net.URI host;
15
  /** The connection to the MQTT broker. */
René Schöne's avatar
René Schöne committed
16
  private org.fusesource.mqtt.client.CallbackConnection connection;
17
  /** Whether we are subscribed to the topics yet */
René Schöne's avatar
René Schöne committed
18
19
  private final java.util.concurrent.locks.Condition readyCondition;
  private final java.util.concurrent.locks.Lock readyLock;
20
  private boolean ready;
René Schöne's avatar
René Schöne committed
21
  private boolean sendWelcomeMessage = true;
René Schöne's avatar
René Schöne committed
22
  private org.fusesource.mqtt.client.QoS qos;
23
  /** Dispatch knowledge */
24
  private final java.util.Map<String, java.util.List<java.util.function.Consumer<byte[]>>> callbacks;
25

26
  public MqttHandler() {
27
    this("RagConnect");
28
29
  }

30
  public MqttHandler(String name) {
René Schöne's avatar
René Schöne committed
31
    this.name = java.util.Objects.requireNonNull(name, "Name must be set");
32
    this.logger = org.apache.logging.log4j.LogManager.getLogger(MqttHandler.class);
René Schöne's avatar
René Schöne committed
33
34
    this.callbacks = new java.util.HashMap<>();
    this.readyLock = new java.util.concurrent.locks.ReentrantLock();
35
36
    this.readyCondition = readyLock.newCondition();
    this.ready = false;
René Schöne's avatar
René Schöne committed
37
    this.qos = org.fusesource.mqtt.client.QoS.AT_LEAST_ONCE;
38
39
  }

40
  public MqttHandler dontSendWelcomeMessage() {
René Schöne's avatar
René Schöne committed
41
42
43
44
45
46
47
48
49
    this.sendWelcomeMessage = false;
    return this;
  }

  /**
   * Sets the host (with default port) to receive messages from, and connects to it.
   * @throws IOException if could not connect, or could not subscribe to a topic
   * @return self
   */
50
  public MqttHandler setHost(String host) throws java.io.IOException {
René Schöne's avatar
René Schöne committed
51
52
53
    return setHost(host, DEFAULT_PORT);
  }

54
55
56
57
58
  /**
   * Sets the host to receive messages from, and connects to it.
   * @throws IOException if could not connect, or could not subscribe to a topic
   * @return self
   */
59
  public MqttHandler setHost(String host, int port) throws java.io.IOException {
René Schöne's avatar
René Schöne committed
60
61
    java.util.Objects.requireNonNull(host, "Host need to be set!");

René Schöne's avatar
René Schöne committed
62
    this.host = java.net.URI.create("tcp://" + host + ":" + port);
63
64
    logger.debug("Host for {} is {}", this.name, this.host);

René Schöne's avatar
René Schöne committed
65
    org.fusesource.mqtt.client.MQTT mqtt = new org.fusesource.mqtt.client.MQTT();
66
67
    mqtt.setHost(this.host);
    connection = mqtt.callbackConnection();
René Schöne's avatar
René Schöne committed
68
    java.util.concurrent.atomic.AtomicReference<Throwable> error = new java.util.concurrent.atomic.AtomicReference<>();
69
70

    // add the listener to dispatch messages later
René Schöne's avatar
René Schöne committed
71
    connection.listener(new org.fusesource.mqtt.client.ExtendedListener() {
72
73
74
75
76
77
78
79
80
81
      public void onConnected() {
        logger.debug("Connected");
      }

      @Override
      public void onDisconnected() {
        logger.debug("Disconnected");
      }

      @Override
René Schöne's avatar
René Schöne committed
82
      public void onPublish(org.fusesource.hawtbuf.UTF8Buffer topic, org.fusesource.hawtbuf.Buffer body, org.fusesource.mqtt.client.Callback<org.fusesource.mqtt.client.Callback<Void>> ack) {
83
        String topicString = topic.toString();
84
85
        java.util.List<java.util.function.Consumer<byte[]>> callbackList = callbacks.get(topicString);
        if (callbackList == null || callbackList.isEmpty()) {
86
87
88
89
          logger.debug("Got a message, but no callback to call. Forgot to unsubscribe?");
        } else {
          byte[] message = body.toByteArray();
//          System.out.println("message = " + Arrays.toString(message));
90
91
92
          for (java.util.function.Consumer<byte[]> callback : callbackList) {
            callback.accept(message);
          }
93
94
95
96
97
        }
        ack.onSuccess(null);  // always acknowledge message
      }

      @Override
René Schöne's avatar
René Schöne committed
98
      public void onPublish(org.fusesource.hawtbuf.UTF8Buffer topicBuffer, org.fusesource.hawtbuf.Buffer body, Runnable ack) {
99
100
101
102
103
104
105
106
107
108
109
110
        logger.warn("onPublish should not be called");
      }

      @Override
      public void onFailure(Throwable cause) {
//        logger.catching(cause);
        error.set(cause);
      }
    });
    throwIf(error);

    // actually establish the connection
René Schöne's avatar
René Schöne committed
111
    connection.connect(new org.fusesource.mqtt.client.Callback<Void>() {
112
113
      @Override
      public void onSuccess(Void value) {
114
        if (MqttHandler.this.sendWelcomeMessage) {
René Schöne's avatar
René Schöne committed
115
116
117
118
119
          connection.publish("components", (name + " is connected").getBytes(), org.fusesource.mqtt.client.QoS.AT_LEAST_ONCE, false, new org.fusesource.mqtt.client.Callback<Void>() {
            @Override
            public void onSuccess(Void value) {
              logger.debug("success sending welcome message");
              setReady();
120
121
            }

René Schöne's avatar
René Schöne committed
122
123
124
125
126
127
128
129
            @Override
            public void onFailure(Throwable value) {
              logger.debug("failure sending welcome message", value);
            }
          });
        } else {
          setReady();
        }
130
131
132
133
134
135
136
137
138
139
140
141
      }

      @Override
      public void onFailure(Throwable cause) {
//        logger.error("Could not connect", cause);
        error.set(cause);
      }
    });
    throwIf(error);
    return this;
  }

René Schöne's avatar
René Schöne committed
142
  public java.net.URI getHost() {
143
144
145
    return host;
  }

René Schöne's avatar
René Schöne committed
146
147
148
149
150
151
152
153
154
155
  private void setReady() {
    try {
      readyLock.lock();
      ready = true;
      readyCondition.signalAll();
    } finally {
      readyLock.unlock();
    }
  }

René Schöne's avatar
René Schöne committed
156
  private void throwIf(java.util.concurrent.atomic.AtomicReference<Throwable> error) throws java.io.IOException {
157
    if (error.get() != null) {
René Schöne's avatar
René Schöne committed
158
      throw new java.io.IOException(error.get());
159
160
161
    }
  }

René Schöne's avatar
René Schöne committed
162
  public void setQoSForSubscription(org.fusesource.mqtt.client.QoS qos) {
163
164
165
    this.qos = qos;
  }

René Schöne's avatar
René Schöne committed
166
  public void newConnection(String topic, java.util.function.Consumer<byte[]> callback) {
167
    if (!ready) {
168
      // should maybe be something more kind than throwing an exception here
169
170
171
      throw new IllegalStateException("Updater not ready");
    }
    // register callback
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
    if (callbacks.get(topic) == null) {
      callbacks.put(topic, new java.util.ArrayList<>());

      // subscribe at broker
      org.fusesource.mqtt.client.Topic[] topicArray = { new org.fusesource.mqtt.client.Topic(topic, this.qos) };
      connection.getDispatchQueue().execute(() -> {
        connection.subscribe(topicArray, new org.fusesource.mqtt.client.Callback<byte[]>() {
          @Override
          public void onSuccess(byte[] qoses) {
            logger.debug("Subscribed to {}, qoses: {}", topic, qoses);
          }

          @Override
          public void onFailure(Throwable cause) {
            logger.error("Could not subscribe to {}", topic, cause);
          }
        });
189
      });
190
191
    }
    callbacks.get(topic).add(callback);
192
193
194
195
196
197
198
199
200
201
202
  }

  /**
   * Waits until this updater is ready to receive MQTT messages.
   * If it already is ready, return immediately with the value <code>true</code>.
   * Otherwise waits for the given amount of time, and either return <code>true</code> within the timespan,
   * if it got ready, or <code>false</code> upon a timeout.
   * @param time the maximum time to wait
   * @param unit the time unit of the time argument
   * @return whether this updater is ready
   */
René Schöne's avatar
René Schöne committed
203
  public boolean waitUntilReady(long time, java.util.concurrent.TimeUnit unit) {
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
    try {
      readyLock.lock();
      if (ready) {
        return true;
      }
      return readyCondition.await(time, unit);
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      readyLock.unlock();
    }
    return false;
  }

  public void close() {
    if (connection == null) {
      logger.warn("Stopping without connection. Was setHost() called?");
      return;
    }
223
224
225
226
227
228
    connection.getDispatchQueue().execute(() -> {
      connection.disconnect(new org.fusesource.mqtt.client.Callback<Void>() {
        @Override
        public void onSuccess(Void value) {
          logger.info("Disconnected {} from {}", name, host);
        }
229

230
231
232
233
234
        @Override
        public void onFailure(Throwable ignored) {
          // Disconnects never fail. And we do not care either.
        }
      });
235
236
237
238
    });
  }

  public void publish(String topic, byte[] bytes) {
239
240
241
242
243
244
245
246
    publish(topic, bytes, false);
  }

  public void publish(String topic, byte[] bytes, boolean retain) {
    publish(topic, bytes, this.qos, retain);
  }

  public void publish(String topic, byte[] bytes, org.fusesource.mqtt.client.QoS qos, boolean retain) {
247
    connection.getDispatchQueue().execute(() -> {
248
      connection.publish(topic, bytes, qos, retain, new org.fusesource.mqtt.client.Callback<Void>() {
249
250
251
252
        @Override
        public void onSuccess(Void value) {
          logger.debug("Published some bytes to {}", topic);
        }
253

254
255
256
257
258
        @Override
        public void onFailure(Throwable value) {
          logger.warn("Could not publish on topic '{}'", topic);
        }
      });
259
260
261
    });
  }
}
René Schöne's avatar
René Schöne committed
262
}