MqttHandler.jadd 10.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.io.IOException;
import java.util.concurrent.TimeUnit;aspect MqttHandler {
public class MqttServerHandler {
  private final java.util.Map<String, MqttHandler> handlers = new java.util.HashMap<>();
  private long time;
  private java.util.concurrent.TimeUnit unit;
  private String name;

  public MqttServerHandler() {
    this("RagConnect");
  }

  public MqttServerHandler(String name) {
    this.name = name;
    setupWaitUntilReady(1, TimeUnit.SECONDS);
  }

  public void setupWaitUntilReady(long time, java.util.concurrent.TimeUnit unit) {
    this.time = time;
    this.unit = unit;
  }

  public MqttHandler resolveHandler(java.net.URI uri) throws IOException {
    MqttHandler handler = handlers.get(uri.getHost());
    if (handler == null) {
      // first connect to that server
      handler = new MqttHandler();
      if (uri.getPort() == -1) {
        handler.setHost(uri.getHost());
      } else {
        handler.setHost(uri.getHost(), uri.getPort());
      }
      handlers.put(uri.getHost(), handler);
    }
    handler.waitUntilReady(this.time, this.unit);
    return handler;
  }

  public boolean newConnection(java.net.URI uri, java.util.function.Consumer<byte[]> callback) throws IOException {
    return resolveHandler(uri).newConnection(extractTopic(uri), callback);
  }

  public void publish(java.net.URI uri, byte[] bytes) throws IOException {
    resolveHandler(uri).publish(extractTopic(uri), bytes);
  }

  public void publish(java.net.URI uri, byte[] bytes, boolean retain) throws IOException {
    resolveHandler(uri).publish(extractTopic(uri), bytes, retain);
  }

  public void publish(java.net.URI uri, byte[] bytes,
                      org.fusesource.mqtt.client.QoS qos, boolean retain) throws IOException {
    resolveHandler(uri).publish(extractTopic(uri), bytes, qos, retain);
  }

René Schöne's avatar
René Schöne committed
56
  public static String extractTopic(java.net.URI uri) {
57
58
59
60
61
62
63
64
65
66
67
68
69
70
    String path = uri.getPath();
    if (path.charAt(0) == '/') {
      path = path.substring(1);
    }
    return path;
  }

  public void close() {
    for (MqttHandler handler : handlers.values()) {
      handler.close();
    }
  }

}
71
72
73
74
75
/**
 * Helper class to receive updates via MQTT and use callbacks to handle those messages.
 *
 * @author rschoene - Initial contribution
 */
76
public class MqttHandler {
René Schöne's avatar
René Schöne committed
77
  private static final int DEFAULT_PORT = 1883;
78

René Schöne's avatar
René Schöne committed
79
  private final org.apache.logging.log4j.Logger logger;
80
81
82
  private final String name;

  /** The host running the MQTT broker. */
René Schöne's avatar
René Schöne committed
83
  private java.net.URI host;
84
  /** The connection to the MQTT broker. */
René Schöne's avatar
René Schöne committed
85
  private org.fusesource.mqtt.client.CallbackConnection connection;
86
87
  /** Whether we are connected yet */
  private final java.util.concurrent.CountDownLatch readyLatch;
René Schöne's avatar
René Schöne committed
88
  private boolean sendWelcomeMessage = true;
René Schöne's avatar
René Schöne committed
89
  private org.fusesource.mqtt.client.QoS qos;
90
  /** Dispatch knowledge */
91
  private final java.util.Map<String, java.util.List<java.util.function.Consumer<byte[]>>> callbacks;
92

93
  public MqttHandler() {
94
    this("RagConnect");
95
96
  }

97
  public MqttHandler(String name) {
René Schöne's avatar
René Schöne committed
98
    this.name = java.util.Objects.requireNonNull(name, "Name must be set");
99
    this.logger = org.apache.logging.log4j.LogManager.getLogger(MqttHandler.class);
René Schöne's avatar
René Schöne committed
100
    this.callbacks = new java.util.HashMap<>();
101
    this.readyLatch = new java.util.concurrent.CountDownLatch(1);
René Schöne's avatar
René Schöne committed
102
    this.qos = org.fusesource.mqtt.client.QoS.AT_LEAST_ONCE;
103
104
  }

105
  public MqttHandler dontSendWelcomeMessage() {
René Schöne's avatar
René Schöne committed
106
107
108
109
110
111
112
113
114
    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
   */
115
  public MqttHandler setHost(String host) throws java.io.IOException {
René Schöne's avatar
René Schöne committed
116
117
118
    return setHost(host, DEFAULT_PORT);
  }

119
120
121
122
123
  /**
   * 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
   */
124
  public MqttHandler setHost(String host, int port) throws java.io.IOException {
René Schöne's avatar
René Schöne committed
125
126
    java.util.Objects.requireNonNull(host, "Host need to be set!");

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

René Schöne's avatar
René Schöne committed
130
    org.fusesource.mqtt.client.MQTT mqtt = new org.fusesource.mqtt.client.MQTT();
131
132
    mqtt.setHost(this.host);
    connection = mqtt.callbackConnection();
René Schöne's avatar
René Schöne committed
133
    java.util.concurrent.atomic.AtomicReference<Throwable> error = new java.util.concurrent.atomic.AtomicReference<>();
134
135

    // add the listener to dispatch messages later
René Schöne's avatar
René Schöne committed
136
    connection.listener(new org.fusesource.mqtt.client.ExtendedListener() {
137
138
139
140
141
142
143
144
145
146
      public void onConnected() {
        logger.debug("Connected");
      }

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

      @Override
René Schöne's avatar
René Schöne committed
147
      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) {
148
        String topicString = topic.toString();
149
150
        java.util.List<java.util.function.Consumer<byte[]>> callbackList = callbacks.get(topicString);
        if (callbackList == null || callbackList.isEmpty()) {
René Schöne's avatar
René Schöne committed
151
          logger.debug("Got a message, but no callback to call. Forgot to subscribe?");
152
153
154
        } else {
          byte[] message = body.toByteArray();
//          System.out.println("message = " + Arrays.toString(message));
155
156
157
          for (java.util.function.Consumer<byte[]> callback : callbackList) {
            callback.accept(message);
          }
158
159
160
161
162
        }
        ack.onSuccess(null);  // always acknowledge message
      }

      @Override
René Schöne's avatar
René Schöne committed
163
      public void onPublish(org.fusesource.hawtbuf.UTF8Buffer topicBuffer, org.fusesource.hawtbuf.Buffer body, Runnable ack) {
164
165
166
167
168
169
170
171
172
173
174
175
        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
176
    connection.connect(new org.fusesource.mqtt.client.Callback<Void>() {
177
178
      @Override
      public void onSuccess(Void value) {
179
        if (MqttHandler.this.sendWelcomeMessage) {
René Schöne's avatar
René Schöne committed
180
181
182
183
184
          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();
185
186
            }

René Schöne's avatar
René Schöne committed
187
188
189
190
191
192
193
194
            @Override
            public void onFailure(Throwable value) {
              logger.debug("failure sending welcome message", value);
            }
          });
        } else {
          setReady();
        }
195
196
197
198
199
200
201
202
203
204
205
206
      }

      @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
207
  public java.net.URI getHost() {
208
209
210
    return host;
  }

René Schöne's avatar
René Schöne committed
211
  private void setReady() {
212
    readyLatch.countDown();
René Schöne's avatar
René Schöne committed
213
214
  }

René Schöne's avatar
René Schöne committed
215
  private void throwIf(java.util.concurrent.atomic.AtomicReference<Throwable> error) throws java.io.IOException {
216
    if (error.get() != null) {
René Schöne's avatar
René Schöne committed
217
      throw new java.io.IOException(error.get());
218
219
220
    }
  }

René Schöne's avatar
René Schöne committed
221
  public void setQoSForSubscription(org.fusesource.mqtt.client.QoS qos) {
222
223
224
    this.qos = qos;
  }

225
226
227
228
229
230
  public boolean newConnection(String topic, java.util.function.Consumer<byte[]> callback) {
    if (readyLatch.getCount() > 0) {
      System.err.println("Handler not ready");
      return false;
//      // should maybe be something more kind than throwing an exception here
//      throw new IllegalStateException("Updater not ready");
231
232
    }
    // register callback
233
    logger.debug("new connection for {}", topic);
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
    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);
          }
        });
251
      });
252
253
    }
    callbacks.get(topic).add(callback);
254
    return true;
255
256
257
258
259
260
261
262
263
264
265
  }

  /**
   * 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
266
  public boolean waitUntilReady(long time, java.util.concurrent.TimeUnit unit) {
267
    try {
268
      return readyLatch.await(time, unit);
269
270
271
272
273
274
275
276
277
278
279
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    return false;
  }

  public void close() {
    if (connection == null) {
      logger.warn("Stopping without connection. Was setHost() called?");
      return;
    }
280
281
282
283
284
285
    connection.getDispatchQueue().execute(() -> {
      connection.disconnect(new org.fusesource.mqtt.client.Callback<Void>() {
        @Override
        public void onSuccess(Void value) {
          logger.info("Disconnected {} from {}", name, host);
        }
286

287
288
289
290
291
        @Override
        public void onFailure(Throwable ignored) {
          // Disconnects never fail. And we do not care either.
        }
      });
292
293
294
295
    });
  }

  public void publish(String topic, byte[] bytes) {
296
297
298
299
300
301
302
303
    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) {
304
    connection.getDispatchQueue().execute(() -> {
305
      connection.publish(topic, bytes, qos, retain, new org.fusesource.mqtt.client.Callback<Void>() {
306
307
308
309
        @Override
        public void onSuccess(Void value) {
          logger.debug("Published some bytes to {}", topic);
        }
310

311
312
        @Override
        public void onFailure(Throwable value) {
313
          logger.warn("Could not publish on topic '{}'", topic, value);
314
315
        }
      });
316
317
318
    });
  }
}
René Schöne's avatar
René Schöne committed
319
}