use of org.eclipse.paho.client.mqttv3.IMqttAsyncClient in project mist by snuspl.
the class MQTTSharedResource method getMqttSinkClient.
/**
* Get the mqtt client for the sink with the target broker.
* @param brokerURI the mqtt broker uri
* @return mqtt client
* @throws MqttException
* @throws IOException
*/
public IMqttAsyncClient getMqttSinkClient(final String brokerURI, final String topic) throws MqttException, IOException {
this.publisherLock.lock();
final List<IMqttAsyncClient> mqttAsyncClientList = brokerPublisherMap.get(brokerURI);
if (mqttAsyncClientList == null) {
// Initialize the broker list
brokerPublisherMap.put(brokerURI, new ArrayList<>());
for (int i = 0; i < mqttSinkClientNumPerBroker; i++) {
createSinkClient(brokerURI, brokerPublisherMap.get(brokerURI));
}
// Initialize the topic-client list
final HashMap<String, IMqttAsyncClient> myTopicPublisherMap = new HashMap<>();
topicPublisherMap.put(brokerURI, myTopicPublisherMap);
// Get the first client...
final IMqttAsyncClient client = brokerPublisherMap.get(brokerURI).get(0);
publisherSinkNumMap.replace(client, publisherSinkNumMap.get(client) + 1);
myTopicPublisherMap.put(topic, client);
this.publisherLock.unlock();
return client;
} else {
final Map<String, IMqttAsyncClient> myTopicPublisherMap = topicPublisherMap.get(brokerURI);
if (myTopicPublisherMap.containsKey(topic)) {
final IMqttAsyncClient client = myTopicPublisherMap.get(topic);
publisherSinkNumMap.replace(client, publisherSinkNumMap.get(client) + 1);
this.publisherLock.unlock();
return client;
} else {
int minSinkNum = Integer.MAX_VALUE;
IMqttAsyncClient client = null;
for (final IMqttAsyncClient mqttAsyncClient : brokerPublisherMap.get(brokerURI)) {
if (minSinkNum > publisherSinkNumMap.get(mqttAsyncClient)) {
minSinkNum = publisherSinkNumMap.get(mqttAsyncClient);
client = mqttAsyncClient;
}
}
publisherSinkNumMap.replace(client, publisherSinkNumMap.get(client) + 1);
myTopicPublisherMap.put(topic, client);
this.publisherLock.unlock();
return client;
}
}
}
Aggregations