MqttHandler.jadd 8.36 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 */
René Schöne's avatar
René Schöne committed
24
  private final java.util.Map<String, java.util.function.Consumer<byte[]>> callbacks;
25

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

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();
René Schöne's avatar
René Schöne committed
84
        java.util.function.Consumer<byte[]> callback = callbacks.get(topicString);
85
86
87
88
89
90
91
92
93
94
95
        if (callback == null) {
          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));
          callback.accept(message);
        }
        ack.onSuccess(null);  // always acknowledge message
      }

      @Override
René Schöne's avatar
René Schöne committed
96
      public void onPublish(org.fusesource.hawtbuf.UTF8Buffer topicBuffer, org.fusesource.hawtbuf.Buffer body, Runnable ack) {
97
98
99
100
101
102
103
104
105
106
107
108
        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
109
    connection.connect(new org.fusesource.mqtt.client.Callback<Void>() {
110
111
      @Override
      public void onSuccess(Void value) {
112
        if (MqttHandler.this.sendWelcomeMessage) {
René Schöne's avatar
René Schöne committed
113
114
115
116
117
          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();
118
119
            }

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

      @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
140
  public java.net.URI getHost() {
141
142
143
    return host;
  }

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

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

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

René Schöne's avatar
René Schöne committed
164
  public void newConnection(String topic, java.util.function.Consumer<byte[]> callback) {
165
166
167
168
169
170
171
172
    if (!ready) {
      // TODO should maybe be something more kind than throwing an exception here
      throw new IllegalStateException("Updater not ready");
    }
    // register callback
    callbacks.put(topic, callback);

    // subscribe at broker
173
    org.fusesource.mqtt.client.Topic[] topicArray = { new org.fusesource.mqtt.client.Topic(topic, this.qos) };
174
175
176
177
178
179
    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);
        }
180

181
182
183
184
185
        @Override
        public void onFailure(Throwable cause) {
          logger.error("Could not subscribe to {}", topic, cause);
        }
      });
186
187
188
189
190
191
192
193
194
195
196
197
    });
  }

  /**
   * 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
198
  public boolean waitUntilReady(long time, java.util.concurrent.TimeUnit unit) {
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
    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;
    }
218
219
220
221
222
223
    connection.getDispatchQueue().execute(() -> {
      connection.disconnect(new org.fusesource.mqtt.client.Callback<Void>() {
        @Override
        public void onSuccess(Void value) {
          logger.info("Disconnected {} from {}", name, host);
        }
224

225
226
227
228
229
        @Override
        public void onFailure(Throwable ignored) {
          // Disconnects never fail. And we do not care either.
        }
      });
230
231
232
233
    });
  }

  public void publish(String topic, byte[] bytes) {
234
235
236
237
238
239
240
241
    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) {
242
    connection.getDispatchQueue().execute(() -> {
243
      connection.publish(topic, bytes, qos, retain, new org.fusesource.mqtt.client.Callback<Void>() {
244
245
246
247
        @Override
        public void onSuccess(Void value) {
          logger.debug("Published some bytes to {}", topic);
        }
248

249
250
251
252
253
        @Override
        public void onFailure(Throwable value) {
          logger.warn("Could not publish on topic '{}'", topic);
        }
      });
254
255
256
    });
  }
}
René Schöne's avatar
René Schöne committed
257
}